hexsha
stringlengths 40
40
| size
int64 2
991k
| ext
stringclasses 2
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
208
| max_stars_repo_name
stringlengths 6
106
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequence | max_stars_count
int64 1
33.5k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
208
| max_issues_repo_name
stringlengths 6
106
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequence | max_issues_count
int64 1
16.3k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
208
| max_forks_repo_name
stringlengths 6
106
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequence | max_forks_count
int64 1
6.91k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 2
991k
| avg_line_length
float64 1
36k
| max_line_length
int64 1
977k
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
799cc34a96ffa80fdf172d3fe52d4c2f9cf075fa | 12,387 | ex | Elixir | lib/stripe/core_resources/payment_intent.ex | Rutaba/stripity_stripe | 12c525301c781f9c8c7e578cc0d933f5d35183d5 | [
"BSD-3-Clause"
] | 555 | 2016-11-29T05:02:27.000Z | 2022-03-30T00:47:59.000Z | lib/stripe/core_resources/payment_intent.ex | Rutaba/stripity_stripe | 12c525301c781f9c8c7e578cc0d933f5d35183d5 | [
"BSD-3-Clause"
] | 532 | 2016-11-28T18:22:25.000Z | 2022-03-30T17:04:32.000Z | lib/stripe/core_resources/payment_intent.ex | Rutaba/stripity_stripe | 12c525301c781f9c8c7e578cc0d933f5d35183d5 | [
"BSD-3-Clause"
] | 296 | 2016-12-05T14:04:09.000Z | 2022-03-28T20:39:37.000Z | defmodule Stripe.PaymentIntent do
@moduledoc """
Work with [Stripe `payment_intent` objects](https://stripe.com/docs/api/payment_intents).
You can:
- [Create a payment_intent](https://stripe.com/docs/api/payment_intents/create)
- [Retrieve a payment_intent](https://stripe.com/docs/api/payment_intents/retrieve)
- [Update a payment_intent](https://stripe.com/docs/api/payment_intents/update)
- [Confirm a payment_intent](https://stripe.com/docs/api/payment_intents/confirm)
- [Capture a payment_intent](https://stripe.com/docs/api/payment_intents/capture)
- [Cancel a payment_intent](https://stripe.com/docs/api/payment_intents/cancel)
- [List all payment_intent](https://stripe.com/docs/api/payment_intents/list)
"""
use Stripe.Entity
import Stripe.Request
require Stripe.Util
@type last_payment_error :: %{
type: String.t(),
charge: String.t(),
code: String.t(),
decline_code: String.t(),
doc_url: String.t(),
message: String.t(),
param: String.t(),
payment_intent: Stripe.PaymentIntent.t() | map,
source: Stripe.Card.t() | map
}
@type next_action :: %{
redirect_to_url: redirect_to_url | nil,
type: String.t(),
use_stripe_sdk: map | nil
}
@type redirect_to_url :: %{
return_url: String.t(),
url: String.t()
}
@type transfer_data :: %{
:destination => String.t()
}
@type t :: %__MODULE__{
id: Stripe.id(),
object: String.t(),
amount: non_neg_integer,
amount_capturable: non_neg_integer,
amount_received: non_neg_integer,
application: Stripe.id() | nil,
application_fee_amount: non_neg_integer | nil,
canceled_at: Stripe.timestamp() | nil,
cancellation_reason: String.t() | nil,
capture_method: String.t(),
charges: Stripe.List.t(Stripe.Charge.t()),
client_secret: String.t(),
confirmation_method: String.t(),
created: Stripe.timestamp(),
currency: String.t(),
customer: Stripe.id() | Stripe.Customer.t() | nil,
description: String.t() | nil,
invoice: Stripe.id() | Stripe.Invoice.t() | nil,
last_payment_error: last_payment_error | nil,
livemode: boolean,
metadata: Stripe.Types.metadata(),
next_action: next_action | nil,
on_behalf_of: Stripe.id() | Stripe.Account.t() | nil,
payment_method: Stripe.id() | Stripe.PaymentMethod.t() | nil,
payment_method_options: map,
payment_method_types: list(String.t()),
receipt_email: String.t() | nil,
review: Stripe.id() | Stripe.Review.t() | nil,
shipping: Stripe.Types.shipping() | nil,
source: Stripe.Card.t() | map,
statement_descriptor: String.t() | nil,
statement_descriptor_suffix: String.t() | nil,
status: String.t(),
setup_future_usage: String.t() | nil,
transfer_data: transfer_data | nil,
transfer_group: String.t() | nil
}
defstruct [
:id,
:object,
:amount,
:amount_capturable,
:amount_received,
:application,
:application_fee_amount,
:canceled_at,
:cancellation_reason,
:capture_method,
:charges,
:client_secret,
:confirmation_method,
:created,
:currency,
:customer,
:description,
:invoice,
:last_payment_error,
:livemode,
:metadata,
:next_action,
:on_behalf_of,
:payment_method,
:payment_method_options,
:payment_method_types,
:receipt_email,
:review,
:shipping,
:source,
:statement_descriptor,
:statement_descriptor_suffix,
:setup_future_usage,
:status,
:transfer_data,
:transfer_group
]
@plural_endpoint "payment_intents"
@doc """
Create a payment intent.
See the [Stripe docs](https://stripe.com/docs/api/payment_intents/create).
"""
@spec create(params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
when params:
%{
:amount => pos_integer,
:currency => String.t(),
optional(:application_fee_amount) => non_neg_integer,
optional(:capture_method) => String.t(),
optional(:confirm) => boolean,
optional(:customer) => Stripe.id() | Stripe.Customer.t(),
optional(:description) => String.t(),
optional(:metadata) => map,
optional(:off_session) => boolean,
optional(:on_behalf_of) => Stripe.id() | Stripe.Account.t(),
optional(:payment_method) => String.t(),
optional(:payment_method_options) => map,
optional(:payment_method_types) => [Stripe.id()],
optional(:receipt_email) => String.t(),
optional(:return_url) => String.t(),
optional(:save_payment_method) => boolean,
optional(:setup_future_usage) => String.t(),
optional(:shipping) => Stripe.Types.shipping(),
optional(:source) => Stripe.id() | Stripe.Card.t(),
optional(:statement_descriptor) => String.t(),
optional(:statement_descriptor_suffix) => String.t(),
optional(:transfer_data) => transfer_data,
optional(:transfer_group) => String.t()
}
| %{}
def create(params, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint)
|> put_params(params)
|> put_method(:post)
|> cast_to_id([:on_behalf_of, :customer, :source])
|> make_request()
end
@doc """
Retrieves the details of a PaymentIntent that has previously been created.
Client-side retrieval using a publishable key is allowed when the client_secret is provided in the query string.
When retrieved with a publishable key, only a subset of properties will be returned. Please refer to the payment intent object reference for more details.
See the [Stripe docs](https://stripe.com/docs/api/payment_intents/retrieve).
"""
@spec retrieve(Stripe.id() | t, params, Stripe.options()) ::
{:ok, t} | {:error, Stripe.Error.t()}
when params:
%{
optional(:client_secret) => String.t()
}
| %{}
def retrieve(id, params, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}")
|> put_params(params)
|> put_method(:get)
|> make_request()
end
@doc """
Updates a PaymentIntent object.
See the [Stripe docs](https://stripe.com/docs/api/payment_intents/update).
"""
@spec update(Stripe.id() | t, params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
when params:
%{
optional(:amount) => non_neg_integer,
optional(:application_fee_amount) => non_neg_integer,
optional(:currency) => String.t(),
optional(:customer) => Stripe.id() | Stripe.Customer.t(),
optional(:description) => String.t(),
optional(:metadata) => map,
optional(:payment_method) => String.t(),
optional(:payment_method_types) => [Stripe.id()],
optional(:receipt_email) => String.t(),
optional(:save_payment_method) => boolean,
optional(:setup_future_usage) => String.t(),
optional(:shipping) => Stripe.Types.shipping(),
optional(:source) => Stripe.id() | Stripe.Card.t(),
optional(:statement_descriptor_suffix) => String.t(),
optional(:transfer_group) => String.t()
}
| %{}
def update(id, params, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}")
|> put_method(:post)
|> put_params(params)
|> make_request()
end
@doc """
Confirm that your customer intends to pay with current or provided source. Upon confirmation,
the PaymentIntent will attempt to initiate a payment.
If the selected source requires additional authentication steps, the PaymentIntent will transition to
the requires_action status and suggest additional actions via next_source_action.
If payment fails, the PaymentIntent will transition to the requires_payment_method status.
If payment succeeds, the PaymentIntent will transition to the succeeded status (or requires_capture,
if capture_method is set to manual). Read the expanded documentation to learn more about server-side confirmation.
See the [Stripe docs](https://stripe.com/docs/api/payment_intents/confirm).
"""
@spec confirm(Stripe.id() | t, params, Stripe.options()) ::
{:ok, t} | {:error, Stripe.Error.t()}
when params:
%{
optional(:client_secret) => String.t(),
optional(:receipt_email) => String.t(),
optional(:return_url) => String.t(),
optional(:save_payment_method) => boolean,
optional(:shipping) => Stripe.Types.shipping(),
optional(:source) => Stripe.id() | Stripe.Card.t(),
optional(:payment_method) => Stripe.id() | Stripe.PaymentMethod.t()
}
| %{}
def confirm(id, params, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}" <> "/confirm")
|> put_method(:post)
|> put_params(params)
|> cast_to_id([:source, :payment_method])
|> make_request()
end
@doc """
Capture the funds of an existing uncaptured PaymentIntent where required_action="requires_capture".
Uncaptured PaymentIntents will be canceled exactly seven days after they are created.
See the [Stripe docs](https://stripe.com/docs/api/payment_intents/capture).
"""
@spec capture(Stripe.id() | t, params, Stripe.options()) ::
{:ok, t} | {:error, Stripe.Error.t()}
when params:
%{
optional(:amount_to_capture) => non_neg_integer,
optional(:application_fee_amount) => non_neg_integer
}
| %{}
def capture(id, params, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}/capture")
|> put_params(params)
|> put_method(:post)
|> make_request()
end
@doc """
A PaymentIntent object can be canceled when it is in one of these statuses: requires_payment_method,
requires_capture, requires_confirmation, requires_action.
Once canceled, no additional charges will be made by the PaymentIntent and any operations on the PaymentIntent will fail with an error.
For PaymentIntents with status='requires_capture', the remaining amount_capturable will automatically be refunded.
See the [Stripe docs](https://stripe.com/docs/api/payment_intents/cancel).
"""
@spec cancel(Stripe.id() | t, params, Stripe.options()) :: {:ok, t} | {:error, Stripe.Error.t()}
when params:
%{
optional(:cancellation_reason) => String.t()
}
| %{}
def cancel(id, params, opts \\ []) do
new_request(opts)
|> put_endpoint(@plural_endpoint <> "/#{get_id!(id)}" <> "/cancel")
|> put_method(:post)
|> put_params(params)
|> make_request()
end
@doc """
Returns a list of PaymentIntents.
See the [Stripe docs](https://stripe.com/docs/api/payment_intents/list).
"""
@spec list(params, Stripe.options()) :: {:ok, Stripe.List.t(t)} | {:error, Stripe.Error.t()}
when params: %{
optional(:customer) => Stripe.id() | Stripe.Customer.t(),
optional(:created) => Stripe.date_query(),
optional(:ending_before) => t | Stripe.id(),
optional(:limit) => 1..100,
optional(:starting_after) => t | Stripe.id()
}
def list(params \\ %{}, opts \\ []) do
new_request(opts)
|> prefix_expansions()
|> put_endpoint(@plural_endpoint)
|> put_method(:get)
|> put_params(params)
|> cast_to_id([:ending_before, :starting_after, :customer])
|> make_request()
end
end
| 39.32381 | 157 | 0.595867 |
799d00a13a859381b191ca9b90e108757749b1ef | 742 | exs | Elixir | old/test/blue_jet_web/controllers/helpers_test.exs | freshcom/freshcom-api | 4f2083277943cf4e4e8fd4c4d443c7309f285ad7 | [
"BSD-3-Clause"
] | 44 | 2018-05-09T01:08:57.000Z | 2021-01-19T07:25:26.000Z | old/test/blue_jet_web/controllers/helpers_test.exs | freshcom/freshcom-api | 4f2083277943cf4e4e8fd4c4d443c7309f285ad7 | [
"BSD-3-Clause"
] | 36 | 2018-05-08T23:59:54.000Z | 2018-09-28T13:50:30.000Z | old/test/blue_jet_web/controllers/helpers_test.exs | freshcom/freshcom-api | 4f2083277943cf4e4e8fd4c4d443c7309f285ad7 | [
"BSD-3-Clause"
] | 9 | 2018-05-09T14:09:19.000Z | 2021-03-21T21:04:04.000Z | defmodule BlueJetWeb.HelpersTest do
use BlueJet.DataCase
alias BlueJetWeb.Controller.Helpers
describe "pointer_for/1" do
test "with :fields as field" do
assert Helpers.pointer_for(:fields) == "/data"
end
test "with :attributes as field" do
assert Helpers.pointer_for(:attributes) == "/data/attributes"
end
test "with :relationships as field" do
assert Helpers.pointer_for(:relationships) == "/data/relationships"
end
test "with :attr_name as field" do
assert Helpers.pointer_for(:attr_name) == "/data/attributes/attrName"
end
test "with :one_example_id as field" do
assert Helpers.pointer_for(:one_example_id) == "/data/relationships/oneExample"
end
end
end
| 26.5 | 85 | 0.698113 |
799d05bfb286c028117910ea586deddd9a9b2fd0 | 9,526 | exs | Elixir | apps/schedules/test/repo_test.exs | noisecapella/dotcom | d5ef869412102d2230fac3dcc216f01a29726227 | [
"MIT"
] | 42 | 2019-05-29T16:05:30.000Z | 2021-08-09T16:03:37.000Z | apps/schedules/test/repo_test.exs | noisecapella/dotcom | d5ef869412102d2230fac3dcc216f01a29726227 | [
"MIT"
] | 872 | 2019-05-29T17:55:50.000Z | 2022-03-30T09:28:43.000Z | apps/schedules/test/repo_test.exs | noisecapella/dotcom | d5ef869412102d2230fac3dcc216f01a29726227 | [
"MIT"
] | 12 | 2019-07-01T18:33:21.000Z | 2022-03-10T02:13:57.000Z | defmodule Schedules.RepoTest do
use ExUnit.Case
use Timex
import Schedules.Repo
import Mock
alias Schedules.Schedule
describe "by_route_ids/2" do
test "can take a route/direction/sequence/date" do
response =
by_route_ids(
["CR-Lowell"],
date: Util.service_date(),
direction_id: 1,
stop_sequences: "first"
)
assert response != []
assert %Schedule{} = List.first(response)
end
test "can take multiple route IDs" do
response =
by_route_ids(
["1", "9"],
direction_id: 1,
stop_sequences: :first
)
refute response == []
assert Enum.any?(response, &(&1.route.id == "1"))
assert Enum.any?(response, &(&1.route.id == "9"))
end
test "returns the parent station as the stop" do
response =
by_route_ids(
["Red"],
date: Util.service_date(),
direction_id: 0,
stop_sequences: ["first"]
)
assert response != []
assert %{id: "place-alfcl", name: "Alewife"} = List.first(response).stop
end
test "filters by min_time when provided" do
now = Util.now()
before_now_fn = fn sched ->
case DateTime.compare(sched.time, now) do
:gt -> false
:eq -> true
:lt -> true
end
end
unfiltered =
by_route_ids(
["Red"],
date: Util.service_date(),
direction_id: 0
)
before_now = unfiltered |> Enum.filter(before_now_fn) |> Enum.count()
assert before_now > 0
filtered =
by_route_ids(
["Red"],
date: Util.service_date(),
direction_id: 0,
min_time: now
)
before_now = filtered |> Enum.filter(before_now_fn) |> Enum.count()
assert before_now == 0
end
test "if we get an error from the API, returns an error tuple" do
response =
by_route_ids(
["CR-Lowell"],
date: "1970-01-01",
stop: "place-north"
)
assert {:error, _} = response
end
end
describe "schedule_for_trip/2" do
@trip_id "place-WML-0442"
|> schedule_for_stop(direction_id: 1)
|> List.first()
|> Map.get(:trip)
|> Map.get(:id)
test "returns stops in order of their stop_sequence for a given trip" do
# find a Worcester CR trip ID
response = schedule_for_trip(@trip_id)
assert response |> Enum.all?(fn schedule -> schedule.trip.id == @trip_id end)
refute response == []
assert List.first(response).stop.id == "place-WML-0442"
assert List.last(response).stop.id == "place-sstat"
end
test "returns different values for different dates" do
today = Util.service_date()
tomorrow = Timex.shift(today, days: 1)
assert schedule_for_trip(@trip_id) == schedule_for_trip(@trip_id, date: today)
refute schedule_for_trip(@trip_id, date: today) ==
schedule_for_trip(@trip_id, date: tomorrow)
end
end
describe "trip/1" do
test "returns a %Schedule.Trip{} for a given ID" do
date = Timex.shift(Util.service_date(), days: 1)
schedules = by_route_ids(["1"], date: date, stop_sequences: :first, direction_id: 0)
scheduled_trip = List.first(schedules).trip
trip = trip(scheduled_trip.id)
assert scheduled_trip == trip
refute trip.shape_id == nil
end
test "caches an invalid trip ID and returns nil" do
assert trip("") == nil
assert trip("invalid ID") == nil
mock_response = %JsonApi{
data: [
%JsonApi.Item{
id: "invalid ID",
attributes: %{
"name" => "name",
"headsign" => "headsign",
"direction_id" => 1
}
}
]
}
assert trip("invalid ID", fn _ -> mock_response end) == nil
end
test "returns nil if there's an error" do
mock_response = {:error, "could not connect to the API"}
assert trip("trip ID with an error", fn _, _ -> mock_response end) == nil
end
end
describe "origin_destination/3" do
test "returns pairs of Schedule items" do
today = Util.service_date() |> Util.convert_to_iso_format()
response =
origin_destination("place-NHRML-0127", "North Station", date: today, direction_id: 1)
[{origin, dest} | _] = response
assert origin.stop.id == "place-NHRML-0127"
assert dest.stop.id == "place-north"
assert origin.trip.id == dest.trip.id
assert origin.time < dest.time
end
test "does not require a direction id" do
today = Util.service_date() |> Util.convert_to_iso_format()
no_direction_id = origin_destination("place-NHRML-0127", "North Station", date: today)
direction_id =
origin_destination("place-NHRML-0127", "North Station", date: today, direction_id: 1)
assert no_direction_id == direction_id
end
test "does not return duplicate trips if a stop hits multiple stops with the same parent" do
next_tuesday =
"America/New_York"
|> Timex.now()
|> Timex.end_of_week(:wed)
|> Util.convert_to_iso_format()
# stops multiple times at ruggles
response = origin_destination("place-rugg", "1237", route: "43", date: next_tuesday)
trips = Enum.map(response, fn {origin, _} -> origin.trip.id end)
assert trips == Enum.uniq(trips)
end
test "returns an error tuple if we get an error from the API" do
# when the API is updated such that this is an error, we won't need to
# mock this anymore. -ps
with_mock V3Api.Schedules, all: fn _ -> {:error, :tuple} end do
response =
origin_destination(
"place-NHRML-0127",
"North Station"
)
assert {:error, _} = response
end
end
end
describe "end_of_rating/1" do
test "returns the date if it comes back from the API" do
error = %JsonApi.Error{
code: "no_service",
meta: %{
"start_date" => "2016-12-01",
"end_date" => "2017-01-01"
}
}
assert ~D[2017-01-01] = end_of_rating(fn _ -> {:error, [error]} end)
end
test "returns nil if there are problems" do
refute end_of_rating(fn _ -> %JsonApi{} end)
end
@tag :external
test "returns a date (actual endpoint)" do
assert %Date{} = end_of_rating()
end
end
describe "rating_dates/1" do
test "returns the start/end dates if it comes back from the API" do
error = %JsonApi.Error{
code: "no_service",
meta: %{
"start_date" => "2016-12-01",
"end_date" => "2017-01-01"
}
}
assert {~D[2016-12-01], ~D[2017-01-01]} = rating_dates(fn _ -> {:error, [error]} end)
end
test "returns :error if there are problems" do
assert rating_dates(fn _ -> %JsonApi{} end) == :error
end
@tag :external
test "returns a date (actual endpoint)" do
assert {%Date{}, %Date{}} = rating_dates()
end
end
describe "hours_of_operation/1" do
@tag :external
test "returns an %HoursOfOperation{} struct for a valid route" do
assert %Schedules.HoursOfOperation{} = hours_of_operation("47")
end
@tag :external
test "returns an %HoursOfOperation{} struct for an invalid route" do
assert %Schedules.HoursOfOperation{} = hours_of_operation("unknown route ID")
end
end
describe "insert_trips_into_cache/1" do
test "caches trips that were already fetched" do
trip_id = "trip_with_data"
data = [
%JsonApi.Item{
relationships: %{
"trip" => [
%JsonApi.Item{
id: trip_id,
attributes: %{
"headsign" => "North Station",
"name" => "300",
"direction_id" => 1
}
}
]
}
}
]
insert_trips_into_cache(data)
assert {:ok, %Schedules.Trip{id: ^trip_id}} = ConCache.get(Schedules.Repo, {:trip, trip_id})
end
test "caches trips that don't have the right data as nil" do
# this can happen with Green Line trips. By caching them, we avoid an
# extra trip to the server only to get a 404.
trip_id = "trip_without_right_data"
data = [
%JsonApi.Item{relationships: %{"trip" => [%JsonApi.Item{id: trip_id}]}}
]
insert_trips_into_cache(data)
assert ConCache.get(Schedules.Repo, {:trip, trip_id}) == {:ok, nil}
end
end
describe "valid?/1" do
test "trips with an id are valid" do
assert valid?(%JsonApi.Item{relationships: %{"trip" => [%JsonApi.Item{id: "1"}]}})
end
test "trips without an id are invalid" do
refute valid?(%JsonApi.Item{relationships: %{"trip" => []}})
end
end
describe "has_trip?/1" do
test "keeps parsed schedules with trips" do
assert has_trip?(
{"CR-Lowell", "CR-Weekday-Fall-18-348", "place-NHRML-0254",
"2018-11-05 23:05:00-05:00 -05 Etc/GMT+5", false, false, false, 1, 0}
)
end
test "filters out parsed schedules that returned without trips" do
refute has_trip?(
{"CR-Lowell", nil, "place-NHRML-0254", "2018-11-05 23:05:00-05:00 -05 Etc/GMT+5",
false, false, false, 1, 0}
)
end
end
end
| 28.779456 | 98 | 0.576632 |
799d0e3d41acfdaa1fdfc9a7b754bc2665a697db | 2,301 | ex | Elixir | lib/cforum_web/plug/security_headers.ex | multitain/cforum_ex | 95634a547893f5392345b173f3c264b149e2b124 | [
"MIT"
] | 16 | 2019-04-04T06:33:33.000Z | 2021-08-16T19:34:31.000Z | lib/cforum_web/plug/security_headers.ex | multitain/cforum_ex | 95634a547893f5392345b173f3c264b149e2b124 | [
"MIT"
] | 294 | 2019-02-10T11:10:27.000Z | 2022-03-30T04:52:53.000Z | lib/cforum_web/plug/security_headers.ex | multitain/cforum_ex | 95634a547893f5392345b173f3c264b149e2b124 | [
"MIT"
] | 10 | 2019-02-10T10:39:24.000Z | 2021-07-06T11:46:05.000Z | defmodule CforumWeb.Plug.SecurityHeaders do
def init(opts), do: opts
def call(%{request_path: "/admin/dashboard" <> _} = conn, _), do: conn
def call(conn, _) do
if Application.get_env(:cforum, :environment) == :prod do
js_nonce =
32
|> :crypto.strong_rand_bytes()
|> Base.url_encode64(padding: false)
style_nonce =
32
|> :crypto.strong_rand_bytes()
|> Base.url_encode64(padding: false)
script_csp = "script-src 'self' 'nonce-#{js_nonce}' *.selfhtml.org" <> maybe_unsafe_eval(conn.request_path)
# 'nonce-#{style_nonce}' not yet possible, due to mathjax
style_csp = "style-src 'self' 'unsafe-inline'"
connect_csp =
"connect-src 'self' #{scheme()}://#{CforumWeb.Endpoint.config(:url)[:host]}#{port()} https://appsignal-endpoint.net/collect" <>
maybe_osm_connect(conn.request_path)
frame_src = "frame-src wiki.selfhtml.org"
media_src = "media-src 'self' src.selfhtml.org"
conn
|> Plug.Conn.assign(:nonce_for_js, js_nonce)
|> Plug.Conn.assign(:nonce_for_style, style_nonce)
|> Plug.Conn.put_resp_header(
"Content-Security-Policy",
"default-src 'self'; #{frame_src}; #{script_csp}; #{style_csp}; #{media_src}; #{connect_csp}" <>
img_csp(conn.request_path)
)
else
conn
|> Plug.Conn.assign(:nonce_for_js, "")
|> Plug.Conn.assign(:nonce_for_style, "")
end
end
defp maybe_unsafe_eval("/events/" <> _id), do: " 'unsafe-eval'"
defp maybe_unsafe_eval(_), do: ""
defp img_csp("/events/" <> _id),
do: "; img-src 'self' *.tile.openstreetmap.de data: wiki.selfhtml.org blog.selfhtml.org forum.selfhtml.org"
defp img_csp(_), do: "; img-src 'self' data: wiki.selfhtml.org blog.selfhtml.org forum.selfhtml.org"
defp maybe_osm_connect("/events/" <> _id), do: " nominatim.openstreetmap.org"
defp maybe_osm_connect(_), do: ""
defp scheme do
port = CforumWeb.Endpoint.config(:url)[:port] || CforumWeb.Endpoint.config(:http)[:port]
if port == 443,
do: "wss",
else: "ws"
end
defp port do
port = CforumWeb.Endpoint.config(:url)[:port] || CforumWeb.Endpoint.config(:http)[:port]
if port != 443 && port != 80,
do: ":#{port}",
else: ""
end
end
| 32.408451 | 135 | 0.62538 |
799d5bde95fc8e3c790645fb74cf91116adab916 | 201 | ex | Elixir | lib/yaphone.ex | balena/yaphone | 3f92a6acc8504289f8d9d13d5e75c45cb7008db6 | [
"BSD-3-Clause"
] | null | null | null | lib/yaphone.ex | balena/yaphone | 3f92a6acc8504289f8d9d13d5e75c45cb7008db6 | [
"BSD-3-Clause"
] | null | null | null | lib/yaphone.ex | balena/yaphone | 3f92a6acc8504289f8d9d13d5e75c45cb7008db6 | [
"BSD-3-Clause"
] | null | null | null | defmodule Yaphone do
@moduledoc """
Documentation for `Yaphone`.
"""
@doc """
Hello world.
## Examples
iex> Yaphone.hello()
:world
"""
def hello do
:world
end
end
| 10.578947 | 30 | 0.557214 |
799dbb90bff6c7c802b7b508be1d860c2a23f4d3 | 44 | ex | Elixir | testData/org/elixir_lang/parser_definition/matched_three_operation_parsing_test_case/CharListHeredoc.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 1,668 | 2015-01-03T05:54:27.000Z | 2022-03-25T08:01:20.000Z | testData/org/elixir_lang/parser_definition/matched_three_operation_parsing_test_case/CharListHeredoc.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 2,018 | 2015-01-01T22:43:39.000Z | 2022-03-31T20:13:08.000Z | testData/org/elixir_lang/parser_definition/matched_three_operation_parsing_test_case/CharListHeredoc.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 145 | 2015-01-15T11:37:16.000Z | 2021-12-22T05:51:02.000Z | '''
One
''' ^^^ '''
Two
'''
| 7.333333 | 11 | 0.136364 |
799dbcbb4a4e7ab4437b66fbf986eb5e29041e12 | 1,226 | ex | Elixir | clients/vision/lib/google_api/vision/v1/connection.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/vision/lib/google_api/vision/v1/connection.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/vision/lib/google_api/vision/v1/connection.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Vision.V1.Connection do
@moduledoc """
Handle Tesla connections for GoogleApi.Vision.V1.
"""
@type t :: Tesla.Env.client()
use GoogleApi.Gax.Connection,
scopes: [
# See, edit, configure, and delete your Google Cloud Platform data
"https://www.googleapis.com/auth/cloud-platform",
# Apply machine learning models to understand and label images
"https://www.googleapis.com/auth/cloud-vision"
],
otp_app: :google_api_vision,
base_url: "https://vision.googleapis.com/"
end
| 34.055556 | 74 | 0.731648 |
799dc6715b14e0b8210e3fa1829d274a04327d5e | 139 | exs | Elixir | priv/repo/migrations/20211205210703_add_username_index.exs | liviaab/twivia | ce00db2ef8375ef5c6f1c1f996aa7c44fa994a8e | [
"MIT"
] | null | null | null | priv/repo/migrations/20211205210703_add_username_index.exs | liviaab/twivia | ce00db2ef8375ef5c6f1c1f996aa7c44fa994a8e | [
"MIT"
] | null | null | null | priv/repo/migrations/20211205210703_add_username_index.exs | liviaab/twivia | ce00db2ef8375ef5c6f1c1f996aa7c44fa994a8e | [
"MIT"
] | null | null | null | defmodule Twivia.Repo.Migrations.AddUsernameIndex do
use Ecto.Migration
def change do
create index(:users, [:username])
end
end
| 17.375 | 52 | 0.748201 |
799df8631597e6a9d7186285e5d98249b3316a1b | 1,554 | ex | Elixir | clients/sas_portal/lib/google_api/sas_portal/v1alpha1/model/sas_portal_test_permissions_response.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/sas_portal/lib/google_api/sas_portal/v1alpha1/model/sas_portal_test_permissions_response.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/sas_portal/lib/google_api/sas_portal/v1alpha1/model/sas_portal_test_permissions_response.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.SASPortal.V1alpha1.Model.SasPortalTestPermissionsResponse do
@moduledoc """
Response message for `TestPermissions` method.
## Attributes
* `permissions` (*type:* `list(String.t)`, *default:* `nil`) - A set of permissions that the caller is allowed.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:permissions => list(String.t())
}
field(:permissions, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.SASPortal.V1alpha1.Model.SasPortalTestPermissionsResponse do
def decode(value, options) do
GoogleApi.SASPortal.V1alpha1.Model.SasPortalTestPermissionsResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.SASPortal.V1alpha1.Model.SasPortalTestPermissionsResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.06383 | 115 | 0.752896 |
799e0f351181908b36548042d9e18e257622aea4 | 1,178 | ex | Elixir | web/channels/user_socket.ex | fs/sentinel_api | 6f6f8ab3e3bf10c44a1d8e025aceded121a420e0 | [
"MIT"
] | null | null | null | web/channels/user_socket.ex | fs/sentinel_api | 6f6f8ab3e3bf10c44a1d8e025aceded121a420e0 | [
"MIT"
] | null | null | null | web/channels/user_socket.ex | fs/sentinel_api | 6f6f8ab3e3bf10c44a1d8e025aceded121a420e0 | [
"MIT"
] | null | null | null | defmodule SentinelApi.UserSocket do
use Phoenix.Socket
## Channels
# channel "room:*", SentinelApi.RoomChannel
## Transports
transport :websocket, Phoenix.Transports.WebSocket
# transport :longpoll, Phoenix.Transports.LongPoll
# Socket params are passed from the client and can
# be used to verify and authenticate a user. After
# verification, you can put default assigns into
# the socket that will be set for all channels, ie
#
# {:ok, assign(socket, :user_id, verified_user_id)}
#
# To deny connection, return `:error`.
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
def connect(_params, socket) do
{:ok, socket}
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "users_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# SentinelApi.Endpoint.broadcast("users_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
def id(_socket), do: nil
end
| 31 | 84 | 0.704584 |
799e362fe356c27e7d5699eea0f2705f5f7ac6f8 | 602 | exs | Elixir | test/liveman/user/users_test.exs | nimblehq/liveman-demo-api | e184349983f949c8434b8651f9223db597ef1025 | [
"MIT"
] | null | null | null | test/liveman/user/users_test.exs | nimblehq/liveman-demo-api | e184349983f949c8434b8651f9223db597ef1025 | [
"MIT"
] | 19 | 2021-07-02T08:14:52.000Z | 2021-07-30T09:33:12.000Z | test/liveman/user/users_test.exs | nimblehq/liveman | e184349983f949c8434b8651f9223db597ef1025 | [
"MIT"
] | null | null | null | defmodule Liveman.User.UsersTest do
use Liveman.DataCase, async: true
alias Liveman.User.Users
describe "register_user/1" do
test "creates a user successfully when the given params are valid" do
user = Users.register_user(%{email: "[email protected]", password: "secret"})
assert {:ok, _} = user
end
test "returns an error when the given params are invalid" do
{:error, changeset} = Users.register_user(%{})
assert %{
password: ["can't be blank"],
email: ["can't be blank"]
} = errors_on(changeset)
end
end
end
| 26.173913 | 78 | 0.621262 |
799e4dbb0c05489e1c6a5d2442d5affd43d82825 | 6,524 | ex | Elixir | clients/vm_migration/lib/google_api/vm_migration/v1/model/migrating_vm.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/vm_migration/lib/google_api/vm_migration/v1/model/migrating_vm.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/vm_migration/lib/google_api/vm_migration/v1/model/migrating_vm.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.VMMigration.V1.Model.MigratingVm do
@moduledoc """
MigratingVm describes the VM that will be migrated from a Source environment and its replication state.
## Attributes
* `awsSourceVmDetails` (*type:* `GoogleApi.VMMigration.V1.Model.AwsSourceVmDetails.t`, *default:* `nil`) - Output only. Details of the VM from an AWS source.
* `computeEngineTargetDefaults` (*type:* `GoogleApi.VMMigration.V1.Model.ComputeEngineTargetDefaults.t`, *default:* `nil`) - Details of the target VM in Compute Engine.
* `createTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The time the migrating VM was created (this refers to this resource and not to the time it was installed in the source).
* `currentSyncInfo` (*type:* `GoogleApi.VMMigration.V1.Model.ReplicationCycle.t`, *default:* `nil`) - Output only. The percentage progress of the current running replication cycle.
* `description` (*type:* `String.t`, *default:* `nil`) - The description attached to the migrating VM by the user.
* `displayName` (*type:* `String.t`, *default:* `nil`) - The display name attached to the MigratingVm by the user.
* `error` (*type:* `GoogleApi.VMMigration.V1.Model.Status.t`, *default:* `nil`) - Output only. Provides details on the state of the Migrating VM in case of an error in replication.
* `group` (*type:* `String.t`, *default:* `nil`) - Output only. The group this migrating vm is included in, if any. The group is represented by the full path of the appropriate Group resource.
* `labels` (*type:* `map()`, *default:* `nil`) - The labels of the migrating VM.
* `lastSync` (*type:* `GoogleApi.VMMigration.V1.Model.ReplicationSync.t`, *default:* `nil`) - Output only. The most updated snapshot created time in the source that finished replication.
* `name` (*type:* `String.t`, *default:* `nil`) - Output only. The identifier of the MigratingVm.
* `policy` (*type:* `GoogleApi.VMMigration.V1.Model.SchedulePolicy.t`, *default:* `nil`) - The replication schedule policy.
* `recentCloneJobs` (*type:* `list(GoogleApi.VMMigration.V1.Model.CloneJob.t)`, *default:* `nil`) - Output only. The recent clone jobs performed on the migrating VM. This field holds the vm's last completed clone job and the vm's running clone job, if one exists. Note: To have this field populated you need to explicitly request it via the "view" parameter of the Get/List request.
* `recentCutoverJobs` (*type:* `list(GoogleApi.VMMigration.V1.Model.CutoverJob.t)`, *default:* `nil`) - Output only. The recent cutover jobs performed on the migrating VM. This field holds the vm's last completed cutover job and the vm's running cutover job, if one exists. Note: To have this field populated you need to explicitly request it via the "view" parameter of the Get/List request.
* `sourceVmId` (*type:* `String.t`, *default:* `nil`) - The unique ID of the VM in the source. The VM's name in vSphere can be changed, so this is not the VM's name but rather its moRef id. This id is of the form vm-.
* `state` (*type:* `String.t`, *default:* `nil`) - Output only. State of the MigratingVm.
* `stateTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The last time the migrating VM state was updated.
* `updateTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The last time the migrating VM resource was updated.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:awsSourceVmDetails => GoogleApi.VMMigration.V1.Model.AwsSourceVmDetails.t() | nil,
:computeEngineTargetDefaults =>
GoogleApi.VMMigration.V1.Model.ComputeEngineTargetDefaults.t() | nil,
:createTime => DateTime.t() | nil,
:currentSyncInfo => GoogleApi.VMMigration.V1.Model.ReplicationCycle.t() | nil,
:description => String.t() | nil,
:displayName => String.t() | nil,
:error => GoogleApi.VMMigration.V1.Model.Status.t() | nil,
:group => String.t() | nil,
:labels => map() | nil,
:lastSync => GoogleApi.VMMigration.V1.Model.ReplicationSync.t() | nil,
:name => String.t() | nil,
:policy => GoogleApi.VMMigration.V1.Model.SchedulePolicy.t() | nil,
:recentCloneJobs => list(GoogleApi.VMMigration.V1.Model.CloneJob.t()) | nil,
:recentCutoverJobs => list(GoogleApi.VMMigration.V1.Model.CutoverJob.t()) | nil,
:sourceVmId => String.t() | nil,
:state => String.t() | nil,
:stateTime => DateTime.t() | nil,
:updateTime => DateTime.t() | nil
}
field(:awsSourceVmDetails, as: GoogleApi.VMMigration.V1.Model.AwsSourceVmDetails)
field(:computeEngineTargetDefaults,
as: GoogleApi.VMMigration.V1.Model.ComputeEngineTargetDefaults
)
field(:createTime, as: DateTime)
field(:currentSyncInfo, as: GoogleApi.VMMigration.V1.Model.ReplicationCycle)
field(:description)
field(:displayName)
field(:error, as: GoogleApi.VMMigration.V1.Model.Status)
field(:group)
field(:labels, type: :map)
field(:lastSync, as: GoogleApi.VMMigration.V1.Model.ReplicationSync)
field(:name)
field(:policy, as: GoogleApi.VMMigration.V1.Model.SchedulePolicy)
field(:recentCloneJobs, as: GoogleApi.VMMigration.V1.Model.CloneJob, type: :list)
field(:recentCutoverJobs, as: GoogleApi.VMMigration.V1.Model.CutoverJob, type: :list)
field(:sourceVmId)
field(:state)
field(:stateTime, as: DateTime)
field(:updateTime, as: DateTime)
end
defimpl Poison.Decoder, for: GoogleApi.VMMigration.V1.Model.MigratingVm do
def decode(value, options) do
GoogleApi.VMMigration.V1.Model.MigratingVm.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.VMMigration.V1.Model.MigratingVm do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 63.339806 | 396 | 0.706468 |
799e9781197bdcdc62cd0de534e83c44a54de315 | 658 | exs | Elixir | day16/test/day16_test.exs | bjorng/advent-of-code-2020 | 9d2f4b6cb7f6a2c9a39596a90ce2709c7f1df22a | [
"Apache-2.0"
] | 2 | 2020-12-19T00:40:21.000Z | 2021-02-16T04:17:05.000Z | day16/test/day16_test.exs | bjorng/advent-of-code-2020 | 9d2f4b6cb7f6a2c9a39596a90ce2709c7f1df22a | [
"Apache-2.0"
] | null | null | null | day16/test/day16_test.exs | bjorng/advent-of-code-2020 | 9d2f4b6cb7f6a2c9a39596a90ce2709c7f1df22a | [
"Apache-2.0"
] | 1 | 2020-12-14T22:37:13.000Z | 2020-12-14T22:37:13.000Z | defmodule Day16Test do
use ExUnit.Case
doctest Day16
test "part 1 with example" do
assert Day16.part1(example()) == 71
end
test "part 1 with my input data" do
assert Day16.part1(input()) == 26009
end
test "part 2 with my input data" do
assert Day16.part2(input()) == 589685618167
end
defp example() do
"""
class: 1-3 or 5-7
row: 6-11 or 33-44
seat: 13-40 or 45-50
your ticket:
7,1,14
nearby tickets:
7,3,47
40,4,50
55,2,20
38,6,12
"""
|> String.split("\n", trim: true)
end
defp input() do
File.read!("input.txt")
|> String.split("\n", trim: true)
end
end
| 16.45 | 47 | 0.583587 |
799e9c7f8a8a7d6879b45303030b9336e47fe14c | 912 | ex | Elixir | Microsoft.Azure.Management.Database.CosmosDb/lib/microsoft/azure/management/database/cosmos_db/model/operation_list_result.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | 4 | 2018-09-29T03:43:15.000Z | 2021-04-01T18:30:46.000Z | Microsoft.Azure.Management.Database.CosmosDb/lib/microsoft/azure/management/database/cosmos_db/model/operation_list_result.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | null | null | null | Microsoft.Azure.Management.Database.CosmosDb/lib/microsoft/azure/management/database/cosmos_db/model/operation_list_result.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | null | null | null | # NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule Microsoft.Azure.Management.Database.CosmosDb.Model.OperationListResult do
@moduledoc """
Result of the request to list Resource Provider operations. It contains a list of operations and a URL link to get the next set of results.
"""
@derive [Poison.Encoder]
defstruct [
:"value",
:"nextLink"
]
@type t :: %__MODULE__{
:"value" => [Operation],
:"nextLink" => String.t
}
end
defimpl Poison.Decoder, for: Microsoft.Azure.Management.Database.CosmosDb.Model.OperationListResult do
import Microsoft.Azure.Management.Database.CosmosDb.Deserializer
def decode(value, options) do
value
|> deserialize(:"value", :list, Microsoft.Azure.Management.Database.CosmosDb.Model.Operation, options)
end
end
| 30.4 | 141 | 0.736842 |
799ebb35884362aac6e431a54a7d58d395e77eeb | 1,141 | exs | Elixir | test/astarte_core/realm_test.exs | Pavinati/astarte_core | dd37ddd2b1bdcef0b1474be9c81d9a0efa4cda81 | [
"Apache-2.0"
] | 16 | 2018-02-02T14:07:10.000Z | 2021-02-03T13:57:30.000Z | test/astarte_core/realm_test.exs | Pavinati/astarte_core | dd37ddd2b1bdcef0b1474be9c81d9a0efa4cda81 | [
"Apache-2.0"
] | 62 | 2019-03-14T15:52:12.000Z | 2022-03-22T10:34:56.000Z | test/astarte_core/realm_test.exs | Pavinati/astarte_core | dd37ddd2b1bdcef0b1474be9c81d9a0efa4cda81 | [
"Apache-2.0"
] | 9 | 2018-02-02T09:55:06.000Z | 2021-03-04T15:15:08.000Z | defmodule Astarte.Core.RealmTest do
use ExUnit.Case
alias Astarte.Core.Realm
test "empty realm name is rejected" do
assert Realm.valid_name?("") == false
end
test "realm name with symbols are rejected" do
assert Realm.valid_name?("my_realm") == false
assert Realm.valid_name?("my-realm") == false
assert Realm.valid_name?("my/realm") == false
assert Realm.valid_name?("my@realm") == false
assert Realm.valid_name?("🤔") == false
end
test "reserved realm name are rejected" do
assert Realm.valid_name?("astarte") == false
assert Realm.valid_name?("system") == false
assert Realm.valid_name?("system_schema") == false
assert Realm.valid_name?("system_other") == false
end
test "realm name that are longer than 48 valid characters are rejected" do
# 48 characters
assert Realm.valid_name?("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == true
# 49 characters
assert Realm.valid_name?("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == false
end
test "valid realm names are accepted" do
assert Realm.valid_name?("goodrealmname") == true
end
end
| 31.694444 | 90 | 0.712533 |
799ec30883be1223794dc897f16bcbe415d9cf54 | 155 | ex | Elixir | lib/protected_hello_web/controllers/page_controller.ex | KeenMate/phoenix-guardian-example | 163d83780f8a8f3b7be20b1e4be63945e8434fb9 | [
"MIT"
] | null | null | null | lib/protected_hello_web/controllers/page_controller.ex | KeenMate/phoenix-guardian-example | 163d83780f8a8f3b7be20b1e4be63945e8434fb9 | [
"MIT"
] | null | null | null | lib/protected_hello_web/controllers/page_controller.ex | KeenMate/phoenix-guardian-example | 163d83780f8a8f3b7be20b1e4be63945e8434fb9 | [
"MIT"
] | null | null | null | defmodule ProtectedHelloWeb.PageController do
use ProtectedHelloWeb, :controller
def index(conn, _params) do
render(conn, "index.html")
end
end
| 19.375 | 45 | 0.76129 |
799eeab6e768cdd3fa032bada33daad730a8f231 | 309 | ex | Elixir | macros/chapter_1/exercises/my_unless.ex | CrabOnTheBeach/metaprogramming_elixir | a828f38228a6a5f1bf9ae4742329ecb932791d56 | [
"MIT"
] | null | null | null | macros/chapter_1/exercises/my_unless.ex | CrabOnTheBeach/metaprogramming_elixir | a828f38228a6a5f1bf9ae4742329ecb932791d56 | [
"MIT"
] | null | null | null | macros/chapter_1/exercises/my_unless.ex | CrabOnTheBeach/metaprogramming_elixir | a828f38228a6a5f1bf9ae4742329ecb932791d56 | [
"MIT"
] | null | null | null | defmodule MyUnless do
@doc """
Exercise is: write your own unless macro without using `if`
"""
defmacro unless(expression, do: block) do
quote do
case unquote(expression) do
x when x in [false, nil] ->
unquote(block)
_ ->
nil
end
end
end
end
| 18.176471 | 61 | 0.569579 |
799eef1222ca895dd3755e30f0c97e91581f13a3 | 613 | exs | Elixir | apps/tools_2/test/sentences_api/web/views/error_view_test.exs | WhiteRookPL/elixir-fire-brigade-workshop | 1c6183339fc623842a09f4d10be75bcecf2c37e7 | [
"MIT"
] | 14 | 2017-08-09T14:21:47.000Z | 2022-03-11T04:10:49.000Z | apps/tools_2/test/sentences_api/web/views/error_view_test.exs | nicholasjhenry/elixir-fire-brigade-workshop | 1c6183339fc623842a09f4d10be75bcecf2c37e7 | [
"MIT"
] | null | null | null | apps/tools_2/test/sentences_api/web/views/error_view_test.exs | nicholasjhenry/elixir-fire-brigade-workshop | 1c6183339fc623842a09f4d10be75bcecf2c37e7 | [
"MIT"
] | 15 | 2017-09-05T15:43:53.000Z | 2020-04-13T16:20:18.000Z | defmodule SentencesAPI.Web.ErrorViewTest do
use SentencesAPI.Web.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.html" do
assert render_to_string(SentencesAPI.Web.ErrorView, "404.html", []) ==
"Page not found"
end
test "render 500.html" do
assert render_to_string(SentencesAPI.Web.ErrorView, "500.html", []) ==
"Internal server error"
end
test "render any other" do
assert render_to_string(SentencesAPI.Web.ErrorView, "505.html", []) ==
"Internal server error"
end
end
| 27.863636 | 74 | 0.69168 |
799ef228f07549df0f40630ce28e246c5d63941f | 1,824 | exs | Elixir | test/heroicons_test.exs | miguel-s/ex_heroicons | 0c70a5b9450cab986d1d10e0d38b38f82ab4642a | [
"MIT"
] | 13 | 2021-05-19T15:32:10.000Z | 2022-02-28T15:00:41.000Z | test/heroicons_test.exs | miguel-s/ex_heroicons | 0c70a5b9450cab986d1d10e0d38b38f82ab4642a | [
"MIT"
] | 6 | 2021-05-22T12:36:01.000Z | 2021-09-25T21:20:15.000Z | test/heroicons_test.exs | miguel-s/ex_heroicons | 0c70a5b9450cab986d1d10e0d38b38f82ab4642a | [
"MIT"
] | 1 | 2021-05-22T12:54:50.000Z | 2021-05-22T12:54:50.000Z | defmodule HeroiconsTest do
use ExUnit.Case, async: true
doctest Heroicons
test "renders icon" do
assert Heroicons.icon("academic-cap", type: "outline")
|> Phoenix.HTML.safe_to_string() =~ "<svg"
end
test "renders icon with attribute" do
assert Heroicons.icon("academic-cap", type: "outline", class: "h-4 w-4")
|> Phoenix.HTML.safe_to_string() =~ ~s(<svg class="h-4 w-4")
end
test "converts opts to attributes" do
assert Heroicons.icon("academic-cap", type: "outline", aria_hidden: true)
|> Phoenix.HTML.safe_to_string() =~ ~s(<svg aria-hidden="true")
end
test "raises if icon name does not exist" do
msg = ~s(icon "hello" with type "outline" does not exist.)
assert_raise ArgumentError, msg, fn ->
Heroicons.icon("hello", type: "outline")
end
end
test "raises if type is missing" do
msg = ~s(expected type in options, got: [])
assert_raise ArgumentError, msg, fn ->
Heroicons.icon("academic-cap")
end
end
test "raises if icon type does not exist" do
msg = ~s(expected type to be one of #{inspect(Heroicons.types())}, got: "world")
assert_raise ArgumentError, msg, fn ->
Heroicons.icon("academic-cap", type: "world")
end
end
end
defmodule HeroiconsConfigTest do
use ExUnit.Case
test "renders icon with default type" do
Application.put_env(:ex_heroicons, :type, "outline")
assert Heroicons.icon("academic-cap")
|> Phoenix.HTML.safe_to_string() =~ "<svg"
end
test "raises if default icon type does not exist" do
Application.put_env(:ex_heroicons, :type, "world")
msg = ~s(expected default type to be one of #{inspect(Heroicons.types())}, got: "world")
assert_raise ArgumentError, msg, fn ->
Heroicons.icon("academic-cap")
end
end
end
| 28.061538 | 92 | 0.657346 |
799f20817dd5debce391045b49a3ea41d0b21974 | 796 | exs | Elixir | test/docs/doc_example_test.exs | MeneDev/espec | ec4b3d579c5192999e930224a8a2650bb1fdf0bc | [
"Apache-2.0"
] | 807 | 2015-03-25T14:00:19.000Z | 2022-03-24T08:08:15.000Z | test/docs/doc_example_test.exs | MeneDev/espec | ec4b3d579c5192999e930224a8a2650bb1fdf0bc | [
"Apache-2.0"
] | 254 | 2015-03-27T10:12:25.000Z | 2021-07-12T01:40:15.000Z | test/docs/doc_example_test.exs | MeneDev/espec | ec4b3d579c5192999e930224a8a2650bb1fdf0bc | [
"Apache-2.0"
] | 85 | 2015-04-02T10:25:19.000Z | 2021-01-30T21:30:43.000Z | defmodule ESpec.Docs.DocExampleTest do
use ExUnit.Case, async: true
import ExUnit.TestHelpers
defmodule Mod1 do
@doc """
iex> 1 + 1
2
iex> 2 + 2
5
"""
def f, do: :f
end
|> write_beam
test "Mod1" do
examples = ESpec.DocExample.extract(Mod1)
assert length(examples) == 2
ex = hd(examples)
assert ex.lhs == "1 + 1"
assert ex.rhs == "2"
assert ex.fun_arity == {:f, 0}
end
defmodule Mod2 do
@doc """
iex> 1 + 1
2
"""
def f, do: :f
end
|> write_beam
test "Mod2" do
assert_raise ESpec.DocExample.Error,
"indentation level mismatch: \"2\", should have been 2 spaces",
fn ->
ESpec.DocExample.extract(Mod2)
end
end
end
| 17.688889 | 80 | 0.530151 |
799f3b12a6257474334058758ea5f7758784073a | 372 | exs | Elixir | machine_translation/MorpHIN/Learned/Resources/Set2/TrainingInstances/49.exs | AdityaPrasadMishra/NLP--Project-Group-16 | fb62cc6a1db4a494058171f11c14a2be3933a9a1 | [
"MIT"
] | null | null | null | machine_translation/MorpHIN/Learned/Resources/Set2/TrainingInstances/49.exs | AdityaPrasadMishra/NLP--Project-Group-16 | fb62cc6a1db4a494058171f11c14a2be3933a9a1 | [
"MIT"
] | null | null | null | machine_translation/MorpHIN/Learned/Resources/Set2/TrainingInstances/49.exs | AdityaPrasadMishra/NLP--Project-Group-16 | fb62cc6a1db4a494058171f11c14a2be3933a9a1 | [
"MIT"
] | null | null | null | **EXAMPLE FILE**
cm pn verb pnoun quantifier;
cm pn noun adjective quantifier;
cm particle pnoun noun quantifier;
noun cm particle quantifier quantifier;
quantifier particle adverb noun quantifier;
cardinal cm noun cm quantifier;
noun cm noun cm quantifier;
cm particle noun SYM quantifier;
pn intensifier noun verb quantifier;
cm pn noun adjective quantifier;
| 28.615385 | 44 | 0.793011 |
799f491c004ecbb44e27cecde621ca66f365828a | 909 | exs | Elixir | apps/server/mix.exs | davemarkov/wichat | df34a66094beafb121d0c9be54a886ef040d8ca6 | [
"MIT"
] | null | null | null | apps/server/mix.exs | davemarkov/wichat | df34a66094beafb121d0c9be54a886ef040d8ca6 | [
"MIT"
] | null | null | null | apps/server/mix.exs | davemarkov/wichat | df34a66094beafb121d0c9be54a886ef040d8ca6 | [
"MIT"
] | null | null | null | defmodule Server.MixProject do
use Mix.Project
def project do
[
app: :server,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.6",
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger, :ecto, :postgrex],
mod: {Server, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:postgrex, "~> 0.13"},
{:ecto, "~> 2.0"}
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"},
# {:sibling_app_in_umbrella, in_umbrella: true},
]
end
end
| 23.921053 | 88 | 0.546755 |
799f7f63727a0ff5006c201a155e4fd572923197 | 65 | ex | Elixir | web/views/page_view.ex | slitherrr/alchemizer | 390826a7b33085f04ac955c434cdca3238164e74 | [
"Apache-2.0"
] | null | null | null | web/views/page_view.ex | slitherrr/alchemizer | 390826a7b33085f04ac955c434cdca3238164e74 | [
"Apache-2.0"
] | null | null | null | web/views/page_view.ex | slitherrr/alchemizer | 390826a7b33085f04ac955c434cdca3238164e74 | [
"Apache-2.0"
] | null | null | null | defmodule Alchemizer.PageView do
use Alchemizer.Web, :view
end
| 16.25 | 32 | 0.8 |
799f83071c11d0ef780fe2c18efabd2a95143f52 | 2,895 | ex | Elixir | lib/rclex/subscriber.ex | tlk-emb/rclex | 0706a3a3f54d494b8ab81b1c6c1279616e3afc39 | [
"Apache-2.0"
] | 34 | 2019-12-04T04:08:26.000Z | 2021-04-14T02:14:57.000Z | lib/rclex/subscriber.ex | tlk-emb/rclex | 0706a3a3f54d494b8ab81b1c6c1279616e3afc39 | [
"Apache-2.0"
] | 13 | 2020-02-24T09:47:15.000Z | 2021-04-12T10:24:23.000Z | lib/rclex/subscriber.ex | tlk-emb/rclex | 0706a3a3f54d494b8ab81b1c6c1279616e3afc39 | [
"Apache-2.0"
] | 3 | 2020-03-13T01:01:46.000Z | 2020-07-04T10:42:00.000Z | defmodule Rclex.Subscriber do
alias Rclex.Nifs
require Rclex.Macros
require Logger
use GenServer
@moduledoc """
T.B.A
"""
@doc """
subscriberプロセスの生成
"""
def start_link({sub, process_name}) do
Logger.debug("#{process_name} subscriber process start")
GenServer.start_link(__MODULE__, sub, name: {:global, process_name})
end
@doc """
subscriberプロセスの初期化
subscriberを状態として持つ。start_subscribingをした際にcontextとcall_backを追加で状態として持つ。
"""
def init(sub) do
{:ok, %{subscriber: sub}}
end
def start_subscribing({node_identifier, topic_name, :sub}, context, call_back) do
sub_identifier = node_identifier ++ '/' ++ topic_name
GenServer.cast({:global, sub_identifier}, {:start_subscribing, {context, call_back}})
end
def start_subscribing(sub_list, context, call_back) do
Enum.map(sub_list, fn {node_identifier, topic_name, :sub} ->
sub_identifier = node_identifier ++ '/' ++ topic_name
GenServer.cast({:global, sub_identifier}, {:start_subscribing, {context, call_back}})
end)
end
def stop_subscribing({node_identifier, topic_name, :sub}) do
sub_identifier = node_identifier ++ '/' ++ topic_name
:ok = GenServer.call({:global, sub_identifier}, :stop_subscribing)
end
def stop_subscribing(sub_list) do
Enum.map(sub_list, fn {node_identifier, topic_name, :sub} ->
sub_identifier = node_identifier ++ '/' ++ topic_name
GenServer.call({:global, sub_identifier}, :stop_subscribing)
end)
end
def handle_cast({:start_subscribing, {context, call_back}}, state) do
{:ok, sub} = Map.fetch(state, :subscriber)
children = [
{Rclex.SubLoop, {self(), sub, context, call_back}}
]
opts = [strategy: :one_for_one]
{:ok, supervisor_id} = Supervisor.start_link(children, opts)
{:noreply,
%{subscriber: sub, context: context, call_back: call_back, supervisor_id: supervisor_id}}
end
@doc """
コールバックの実行
"""
def handle_cast({:execute, msg}, state) do
{:ok, call_back} = Map.fetch(state, :call_back)
call_back.(msg)
{:noreply, state}
end
def handle_cast(:stop, state) do
{:stop, :normal, state}
end
def handle_call(:stop_subscribing, _from, state) do
{:ok, supervisor_id} = Map.fetch(state, :supervisor_id)
Supervisor.stop(supervisor_id)
new_state = Map.delete(state, :supervisor_id)
{:reply, :ok, new_state}
end
def handle_call({:finish, node}, _from, state) do
{:ok, sub} = Map.fetch(state, :subscriber)
Nifs.rcl_subscription_fini(sub, node)
{:reply, {:ok, 'subscriber finished: '}, state}
end
def handle_call({:finish_subscriber, node}, _from, state) do
{:ok, sub} = Map.fetch(state, :subscriber)
Nifs.rcl_subscription_fini(sub, node)
{:reply, :ok, state}
end
def terminate(:normal, _) do
Logger.debug("sub terminate")
end
# defp do_nothing do
# end
end
| 27.836538 | 94 | 0.676684 |
799f900855b48c64033dc3fd2bc9425ba6ce3ab7 | 3,032 | ex | Elixir | lib/scenic/primitive/style/theme.ex | zacck/scenic | 5f2170b7fba63b0af597ddeb3107fb1ffb79c2fe | [
"Apache-2.0"
] | null | null | null | lib/scenic/primitive/style/theme.ex | zacck/scenic | 5f2170b7fba63b0af597ddeb3107fb1ffb79c2fe | [
"Apache-2.0"
] | null | null | null | lib/scenic/primitive/style/theme.ex | zacck/scenic | 5f2170b7fba63b0af597ddeb3107fb1ffb79c2fe | [
"Apache-2.0"
] | null | null | null | #
# Created by Boyd Multerer on August 18 2018.
# Copyright © 2018 Kry10 Industries. All rights reserved.
#
defmodule Scenic.Primitive.Style.Theme do
@moduledoc """
The theme style is a way to bundle up default colors that are intended to be used by dynamic components invoked by a scene.
There is a set of pre-defined themes.
You can also pass in a map of theme values.
Unlike other styles, these are a guide to the components.
Each component gets to pick, choose, or ignore any colors in a given style.
"""
use Scenic.Primitive.Style
alias Scenic.Primitive.Style.Paint.Color
@theme_light %{
text: :black,
background: :white,
border: :dark_grey,
active: {215, 215, 215},
thumb: :cornflower_blue,
focus: :blue
}
@theme_dark %{
text: :white,
background: :black,
border: :light_grey,
active: {40, 40, 40},
thumb: :cornflower_blue,
focus: :cornflower_blue
}
# specialty themes
@primary Map.merge(@theme_dark, %{background: {72, 122, 252}, active: {58, 94, 201}})
@secondary Map.merge(@theme_dark, %{background: {111, 117, 125}, active: {86, 90, 95}})
@success Map.merge(@theme_dark, %{background: {99, 163, 74}, active: {74, 123, 56}})
@danger Map.merge(@theme_dark, %{background: {191, 72, 71}, active: {164, 54, 51}})
@warning Map.merge(@theme_light, %{background: {239, 196, 42}, active: {197, 160, 31}})
@info Map.merge(@theme_dark, %{background: {94, 159, 183}, active: {70, 119, 138}})
@text Map.merge(@theme_dark, %{text: {72, 122, 252}, background: :clear, active: :clear})
@themes %{
light: @theme_light,
dark: @theme_dark,
primary: @primary,
secondary: @secondary,
success: @success,
danger: @danger,
warning: @warning,
info: @info,
text: @text
}
# ============================================================================
# data verification and serialization
# --------------------------------------------------------
def info(data),
do: """
#{IO.ANSI.red()}#{__MODULE__} data must either a preset theme or a map of named colors
#{IO.ANSI.yellow()}Received: #{inspect(data)}
The predefined themes are:
:dark, :light, :primary, :secondary, :success, :danger, :warning, :info, :text
If you pass in a map of colors, the common ones used in the controls are:
:text, :background, :border, :active, :thumb, :focus
#{IO.ANSI.default_color()}
"""
# --------------------------------------------------------
def verify(name) when is_atom(name), do: Map.has_key?(@themes, name)
def verify(custom) when is_map(custom) do
Enum.all?(custom, fn {_, color} -> Color.verify(color) end)
end
def verify(_), do: false
# --------------------------------------------------------
def normalize(theme) when is_atom(theme), do: Map.get(@themes, theme)
def normalize(theme) when is_map(theme), do: theme
# --------------------------------------------------------
def preset(theme), do: Map.get(@themes, theme)
end
| 32.602151 | 125 | 0.585422 |
799f90bd3eae83c7e70140d2d755ac064e41107e | 3,451 | exs | Elixir | test/service/s3_service_test.exs | kieraneglin/activestorage_ex | 3cc00c212f2e87f9e04651e16e6701af8893cc7b | [
"MIT"
] | null | null | null | test/service/s3_service_test.exs | kieraneglin/activestorage_ex | 3cc00c212f2e87f9e04651e16e6701af8893cc7b | [
"MIT"
] | null | null | null | test/service/s3_service_test.exs | kieraneglin/activestorage_ex | 3cc00c212f2e87f9e04651e16e6701af8893cc7b | [
"MIT"
] | 2 | 2019-05-30T18:29:37.000Z | 2020-06-27T18:40:03.000Z | defmodule ActivestorageExTest.S3ServiceTest do
use ExUnit.Case
doctest ActivestorageEx.S3Service
alias ActivestorageEx.S3Service
@test_key "testing_key"
describe "S3Service.download/1" do
test "Returns a file from a given key as binary" do
upload_test_image()
downloaded_file = S3Service.download(@test_key)
assert is_binary(downloaded_file)
delete_test_image()
end
test "Returns an error if the file cannot be found" do
missing_file = S3Service.download("fake_key")
assert {:error, :not_found} == missing_file
end
end
describe "S3Service.stream_download/2" do
test "An image is downloaded to the given filepath" do
upload_test_image()
filepath = "test/files/streamed.jpg"
S3Service.stream_download(@test_key, filepath)
assert File.exists?(filepath)
File.rm(filepath)
delete_test_image()
end
test "The filepath is returned upon success" do
upload_test_image()
filepath = "test/files/streamed.jpg"
download = S3Service.stream_download(@test_key, filepath)
assert {:ok, ^filepath} = download
File.rm(filepath)
delete_test_image()
end
end
describe "S3Service.upload/2" do
test "An image is sucessfully saved to s3" do
image = Mogrify.open("test/files/image.jpg")
S3Service.upload(image, @test_key)
assert S3Service.exist?(@test_key)
delete_test_image()
end
test "An image with a complex path is sucessfully saved to s3" do
image = Mogrify.open("test/files/image.jpg")
key = "variants/new_key"
S3Service.upload(image, key)
assert S3Service.exist?(key)
delete_test_image()
end
end
describe "S3Service.delete/1" do
test "An image is sucessfully deleted from s3" do
upload_test_image()
assert S3Service.exist?(@test_key)
S3Service.delete(@test_key)
refute S3Service.exist?(@test_key)
end
test "An image with a complex path is sucessfully deleted from s3" do
key = "variants/new_key"
upload_test_image(key)
assert S3Service.exist?(key)
S3Service.delete(key)
refute S3Service.exist?(key)
end
end
describe "S3Service.url/2" do
test "The full disposition is present in the final URL" do
url =
S3Service.url(@test_key, %{
filename: @test_key,
disposition: "inline"
})
assert String.contains?(
url,
"disposition=inline%3B+filename%3D%22testing_key%22"
)
end
test "The filename is present in the final URL" do
url_path =
S3Service.url(@test_key, %{
filename: @test_key,
disposition: "inline"
})
|> String.split("/")
|> Enum.at(6)
assert String.starts_with?(url_path, @test_key)
end
end
describe "S3Service.exist?/1" do
test "Returns true if a file with a given key exists" do
upload_test_image()
assert S3Service.exist?(@test_key)
delete_test_image()
end
test "Returns false if a file with a given key doesn't exist" do
refute S3Service.exist?("not-a-real-key")
end
end
defp upload_test_image(key \\ @test_key) do
image = Mogrify.open("test/files/image.jpg")
S3Service.upload(image, key)
key
end
defp delete_test_image() do
S3Service.delete(@test_key)
@test_key
end
end
| 22.555556 | 73 | 0.649087 |
799fba9e63c345f7fdd61fc8611df62ced2cb904 | 3,265 | ex | Elixir | apps/ewallet/lib/ewallet/web/v1/serializers/transaction_consumption_serializer.ex | amadeobrands/ewallet | 505b7822721940a7b892a9b35c225e80cc8ac0b4 | [
"Apache-2.0"
] | 1 | 2018-12-07T06:21:21.000Z | 2018-12-07T06:21:21.000Z | apps/ewallet/lib/ewallet/web/v1/serializers/transaction_consumption_serializer.ex | amadeobrands/ewallet | 505b7822721940a7b892a9b35c225e80cc8ac0b4 | [
"Apache-2.0"
] | null | null | null | apps/ewallet/lib/ewallet/web/v1/serializers/transaction_consumption_serializer.ex | amadeobrands/ewallet | 505b7822721940a7b892a9b35c225e80cc8ac0b4 | [
"Apache-2.0"
] | null | null | null | defmodule EWallet.Web.V1.TransactionConsumptionSerializer do
@moduledoc """
Serializes transaction request consumption data into V1 JSON response format.
"""
alias Ecto.Association.NotLoaded
alias EWallet.Web.{Date, Paginator}
alias EWallet.Web.V1.{
AccountSerializer,
PaginatorSerializer,
TokenSerializer,
TransactionRequestSerializer,
TransactionSerializer,
UserSerializer,
WalletSerializer
}
alias EWalletConfig.Helpers.Assoc
alias EWalletDB.TransactionConsumption
def serialize(%Paginator{} = paginator) do
PaginatorSerializer.serialize(paginator, &serialize/1)
end
def serialize(%TransactionConsumption{} = consumption) do
final_consumption_amount = TransactionConsumption.get_final_amount(consumption)
final_request_amount = get_final_request_amount(consumption, final_consumption_amount)
%{
object: "transaction_consumption",
id: consumption.id,
socket_topic: "transaction_consumption:#{consumption.id}",
amount: consumption.amount,
estimated_request_amount: consumption.estimated_request_amount,
estimated_consumption_amount: consumption.estimated_consumption_amount,
finalized_request_amount: final_request_amount,
finalized_consumption_amount: final_consumption_amount,
token_id: consumption.token.id,
token: TokenSerializer.serialize(consumption.token),
correlation_id: consumption.correlation_id,
idempotency_token: consumption.idempotency_token,
transaction_id: Assoc.get(consumption, [:transaction, :id]),
transaction: TransactionSerializer.serialize(consumption.transaction),
user_id: Assoc.get(consumption, [:user, :id]),
user: UserSerializer.serialize(consumption.user),
account_id: Assoc.get(consumption, [:account, :id]),
account: AccountSerializer.serialize(consumption.account),
exchange_account_id: Assoc.get(consumption, [:exchange_account, :id]),
exchange_account: AccountSerializer.serialize(consumption.exchange_account),
exchange_wallet_address: Assoc.get(consumption, [:exchange_wallet, :address]),
exchange_wallet: WalletSerializer.serialize_without_balances(consumption.exchange_wallet),
transaction_request_id: consumption.transaction_request.id,
transaction_request:
TransactionRequestSerializer.serialize(consumption.transaction_request),
address: consumption.wallet_address,
metadata: consumption.metadata || %{},
encrypted_metadata: consumption.encrypted_metadata || %{},
expiration_date: Date.to_iso8601(consumption.expiration_date),
status: consumption.status,
approved_at: Date.to_iso8601(consumption.approved_at),
rejected_at: Date.to_iso8601(consumption.rejected_at),
confirmed_at: Date.to_iso8601(consumption.confirmed_at),
failed_at: Date.to_iso8601(consumption.failed_at),
expired_at: Date.to_iso8601(consumption.expired_at),
created_at: Date.to_iso8601(consumption.inserted_at)
}
end
def serialize(%NotLoaded{}), do: nil
def serialize(nil), do: nil
defp get_final_request_amount(_consumption, nil), do: nil
defp get_final_request_amount(consumption, _amount) do
consumption.estimated_request_amount
end
end
| 41.858974 | 96 | 0.767228 |
799fc49e8e14306533cea7cf663ee292c4107fc7 | 776 | ex | Elixir | test/support/channel_case.ex | robotarmy/serve_elm | 931787a55acbe076eac0c0b199c5cfc63425197e | [
"MIT"
] | null | null | null | test/support/channel_case.ex | robotarmy/serve_elm | 931787a55acbe076eac0c0b199c5cfc63425197e | [
"MIT"
] | null | null | null | test/support/channel_case.ex | robotarmy/serve_elm | 931787a55acbe076eac0c0b199c5cfc63425197e | [
"MIT"
] | null | null | null | defmodule ServeElmWeb.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 ServeElmWeb.Endpoint
end
end
setup _tags do
:ok
end
end
| 22.823529 | 58 | 0.726804 |
799fcff269b1e9466904919c9b72b77f50f6b933 | 4,367 | ex | Elixir | lib/ecto/query/builder/order_by.ex | zachahn/ecto | 8119ad877f7caa837912647a014f4a63a951dba0 | [
"Apache-2.0"
] | null | null | null | lib/ecto/query/builder/order_by.ex | zachahn/ecto | 8119ad877f7caa837912647a014f4a63a951dba0 | [
"Apache-2.0"
] | null | null | null | lib/ecto/query/builder/order_by.ex | zachahn/ecto | 8119ad877f7caa837912647a014f4a63a951dba0 | [
"Apache-2.0"
] | null | null | null | import Kernel, except: [apply: 2]
defmodule Ecto.Query.Builder.OrderBy do
@moduledoc false
alias Ecto.Query.Builder
@doc """
Escapes an order by query.
The query is escaped to a list of `{direction, expression}`
pairs at runtime. Escaping also validates direction is one of
`:asc` or `:desc`.
## Examples
iex> escape(:order_by, quote do [x.x, desc: 13] end, [x: 0], __ENV__)
{[asc: {:{}, [], [{:{}, [], [:., [], [{:{}, [], [:&, [], [0]]}, :x]]}, [], []]},
desc: 13],
%{}}
"""
@spec escape(:order_by | :distinct, Macro.t, Keyword.t, Macro.Env.t) :: Macro.t
def escape(kind, {:^, _, [expr]}, _vars, _env) do
{quote(do: Ecto.Query.Builder.OrderBy.order_by!(unquote(kind), unquote(expr))), %{}}
end
def escape(kind, expr, vars, env) do
expr
|> List.wrap
|> Enum.map_reduce(%{}, &do_escape(&1, &2, kind, vars, env))
end
defp do_escape({dir, {:^, _, [expr]}}, params, kind, _vars, _env) do
{{quoted_dir!(kind, dir), quote(do: Ecto.Query.Builder.OrderBy.field!(unquote(kind), unquote(expr)))}, params}
end
defp do_escape({:^, _, [expr]}, params, kind, _vars, _env) do
{{:asc, quote(do: Ecto.Query.Builder.OrderBy.field!(unquote(kind), unquote(expr)))}, params}
end
defp do_escape({dir, field}, params, kind, _vars, _env) when is_atom(field) do
{{quoted_dir!(kind, dir), Macro.escape(to_field(field))}, params}
end
defp do_escape(field, params, _kind, _vars, _env) when is_atom(field) do
{{:asc, Macro.escape(to_field(field))}, params}
end
defp do_escape({dir, expr}, params, kind, vars, env) do
{ast, {params, :acc}} = Builder.escape(expr, :any, {params, :acc}, vars, env)
{{quoted_dir!(kind, dir), ast}, params}
end
defp do_escape(expr, params, _kind, vars, env) do
{ast, {params, :acc}} = Builder.escape(expr, :any, {params, :acc}, vars, env)
{{:asc, ast}, params}
end
@doc """
Checks the variable is a quoted direction at compilation time or
delegate the check to runtime for interpolation.
"""
def quoted_dir!(kind, {:^, _, [expr]}),
do: quote(do: Ecto.Query.Builder.OrderBy.dir!(unquote(kind), unquote(expr)))
def quoted_dir!(_kind, dir) when dir in [:asc, :desc],
do: dir
def quoted_dir!(kind, other),
do: Builder.error!("expected :asc, :desc or interpolated value in `#{kind}`, got: `#{inspect other}`")
@doc """
Called by at runtime to verify the direction.
"""
def dir!(_kind, dir) when dir in [:asc, :desc],
do: dir
def dir!(kind, other),
do: Builder.error!("expected :asc or :desc in `#{kind}`, got: `#{inspect other}`")
@doc """
Called at runtime to verify a field.
"""
def field!(_kind, field) when is_atom(field) do
to_field(field)
end
def field!(kind, other) do
raise ArgumentError,
"expected a field as an atom, a list or keyword list in `#{kind}`, got: `#{inspect other}`"
end
@doc """
Called at runtime to verify order_by.
"""
def order_by!(kind, exprs) do
Enum.map List.wrap(exprs), fn
{dir, field} when dir in [:asc, :desc] ->
{dir, field!(kind, field)}
field ->
{:asc, field!(kind, field)}
end
end
defp to_field(field), do: {{:., [], [{:&, [], [0]}, field]}, [], []}
@doc """
Builds a quoted expression.
The quoted expression should evaluate to a query at runtime.
If possible, it does all calculations at compile time to avoid
runtime work.
"""
@spec build(Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t
def build(query, binding, expr, env) do
{query, binding} = Builder.escape_binding(query, binding, env)
{expr, params} = escape(:order_by, expr, binding, env)
params = Builder.escape_params(params)
order_by = quote do: %Ecto.Query.QueryExpr{
expr: unquote(expr),
params: unquote(params),
file: unquote(env.file),
line: unquote(env.line)}
Builder.apply_query(query, __MODULE__, [order_by], env)
end
@doc """
The callback applied by `build/4` to build the query.
"""
@spec apply(Ecto.Queryable.t, term) :: Ecto.Query.t
def apply(%Ecto.Query{order_bys: order_bys} = query, expr) do
%{query | order_bys: order_bys ++ [expr]}
end
def apply(query, expr) do
apply(Ecto.Queryable.to_query(query), expr)
end
end
| 32.110294 | 114 | 0.609343 |
79a002d0b496683996d79266d3ea3208b8bf0a5d | 3,594 | ex | Elixir | lib/packer/defs.ex | aseigo/packer | f02dfe21a35d874303551cb49798297f89b54883 | [
"Apache-2.0"
] | 3 | 2018-06-23T17:47:16.000Z | 2018-09-12T21:05:46.000Z | lib/packer/defs.ex | aseigo/packer | f02dfe21a35d874303551cb49798297f89b54883 | [
"Apache-2.0"
] | 12 | 2018-06-22T07:02:23.000Z | 2018-06-25T17:56:49.000Z | lib/packer/defs.ex | aseigo/packer | f02dfe21a35d874303551cb49798297f89b54883 | [
"Apache-2.0"
] | null | null | null | defmodule Packer.Defs do
@moduledoc false
defmacro __using__(_) do
quote do
import Packer.Defs
@c_small_int 0x01 # 1 byte
@c_small_uint 0x02 # 1 byte
@c_short_int 0x03 # 2 bytes
@c_short_uint 0x04 # 2 bytes
@c_int 0x05 # 4 bytes
@c_uint 0x06 # 4 bytes
@c_big_int 0x07 # 8 bytes
#@c_huge_int 0x08
@c_float 0x09 # 8 bytes
@c_byte 0x0A # 1 byte
@c_binary_1 0x0B # N bytes, 1 byte length
@c_binary_2 0x0C # N bytes, 2 byte length
@c_binary_4 0x0D # N bytes, 4 byte length
@c_binary_8 0x0E # N bytes, 8 byte length
@c_atom 0x0F # N bytes, 1 byte length
# collections, variable size, marked by an end byte value
@c_list 0x21
@c_map 0x22
@c_struct 0x23
@c_collection_end 0x00
# tuples are size 0..N where N up to 62 is encoded in the type byte
# and above that the size of the tuple appears as a size as with the
# other collections. tuple type values therefore range from 0b01000000
# to 0b01111111, with that last type value being signifying that the next
# 2 bytes are the length of the tuple
@c_tuple 0b01000000
# repeat markers: how many times to repeat the previous schema part
# recorded in the next 1..4 bytes
@c_repeat_1 0b10100000 # 1 byte repeat count
@c_repeat_2 0b10100001 # 2 byte repeat counts
@c_repeat_4 0b10100010 # 4 bytes repeat count
#@c_repeat_up 0b10100100
@c_max_short_tuple 0b01111111 - 0b01000000
@c_var_size_tuple 0b01111111
@c_tuple_arity_mask 0b00111111
@c_version_header <<0x04>>
@c_full_header <<0x45, 0x50, 0x4B, 0x52, 0x04>> # 'EPKR' + version
@c_full_header_prefix <<0x45, 0x50, 0x4B, 0x52>> # 'EPKR'
end
end
defmacro debuffer_primitive(type, length_bytes, binary_desc, default_on_fail) do
quote do
defp debuffer_one(unquote(type), schema, buffer) do
if byte_size(buffer) < unquote(length_bytes) do
decoded(schema, <<>>, unquote(default_on_fail))
else
<<term :: unquote(binary_desc), rem_buffer :: binary>> = buffer
decoded(schema, rem_buffer, term)
end
end
end
end
# NOTE:
# there is some dusky magic in the follownig macro, but boy does it help make the decode module short
# each invocation creates two functions, one that is a helper to avoid yet another level of nesting.
# the complexity mostly comes from the fact that this can handle both the needs of atom and binary
# decoding ...
defmacro debuffer_binary(type, length_encoding_size, default_on_fail \\ :consume_rest, fun \\ nil) do
final_term =
if fun == nil do
quote do
term
end
else
quote do
unquote(fun).(term)
end
end
on_fail =
if default_on_fail == :consume_rest do
quote do
buffer
end
else
default_on_fail
end
quote do
defp debuffer_one(unquote(type), schema, <<size :: unquote(length_encoding_size)-unsigned-little-integer, buffer :: binary>>) do
if byte_size(buffer) < size do
decoded(schema, <<>>, unquote(on_fail))
else
{term, rem_buffer} = String.split_at(buffer, size)
decoded(schema, rem_buffer, unquote(final_term))
end
end
defp debuffer_one(unquote(type), _schema, _buffer) do
decoded(<<>>, <<>>, <<>>)
end
end
end
end
| 32.972477 | 134 | 0.622426 |
79a0274fd418355aa2ae4219a69630d26ad028f1 | 704 | exs | Elixir | test/inmana_web/views/restaurants_view_test.exs | MateusMaceedo/NLW-Elixir-5.0 | 1137fe8ff137bf316efe537504980f6a857b52a9 | [
"RSA-MD"
] | 14 | 2021-04-26T14:19:28.000Z | 2021-09-12T03:29:42.000Z | test/inmana_web/views/restaurants_view_test.exs | israel206/InmanaIsrael | bc93ddb3ca23f3188f89ef012e463fcacc4e9777 | [
"MIT"
] | null | null | null | test/inmana_web/views/restaurants_view_test.exs | israel206/InmanaIsrael | bc93ddb3ca23f3188f89ef012e463fcacc4e9777 | [
"MIT"
] | 6 | 2021-04-27T12:41:16.000Z | 2021-07-02T04:11:53.000Z | defmodule InmanaWeb.RestaurantsViewTest do
use InmanaWeb.ConnCase, async: true
import Phoenix.View
alias Inmana.Restaurant
alias InmanaWeb.RestaurantsView
describe "render/2" do
test "renders create.json" do
params = %{name: "Siri cascudo", email: "[email protected]"}
{:ok, restaurant} = Inmana.create_restaurant(params)
response = render(RestaurantsView, "create.json", restaurant: restaurant)
assert %{
message: "Restaurant created!",
restaurant: %Restaurant{
email: "[email protected]",
id: _id,
name: "Siri cascudo"
}
} = response
end
end
end
| 26.074074 | 79 | 0.598011 |
79a033c42c474e02d40d287a1b2f482a4d0840b5 | 1,275 | ex | Elixir | lib/ex_sdp/attribute/ssrc.ex | membraneframework/membrane-protocol-sdp | 4cb3028d62a722e364196b58b73732567306a931 | [
"Apache-2.0"
] | null | null | null | lib/ex_sdp/attribute/ssrc.ex | membraneframework/membrane-protocol-sdp | 4cb3028d62a722e364196b58b73732567306a931 | [
"Apache-2.0"
] | 1 | 2020-07-31T10:37:43.000Z | 2020-08-10T09:22:13.000Z | lib/ex_sdp/attribute/ssrc.ex | membraneframework/membrane-protocol-sdp | 4cb3028d62a722e364196b58b73732567306a931 | [
"Apache-2.0"
] | null | null | null | defmodule ExSDP.Attribute.SSRC do
@moduledoc """
This module represents ssrc (RFC 5576).
"""
alias ExSDP.Utils
@enforce_keys [:id, :attribute]
defstruct @enforce_keys ++ [:value]
@type t :: %__MODULE__{id: non_neg_integer(), attribute: binary(), value: binary() | nil}
@typedoc """
Key that can be used for searching this attribute using `ExSDP.Media.get_attribute/2`.
"""
@type attr_key :: :ssrc
@spec parse(binary()) :: {:ok, t()} | {:error, :invalid_ssrc}
def parse(ssrc) do
with [id, attribute] <- String.split(ssrc, " ", parts: 2),
{:ok, id} <- Utils.parse_numeric_string(id) do
case String.split(attribute, ":") do
[attribute, value] -> {:ok, %__MODULE__{id: id, attribute: attribute, value: value}}
[attribute] -> {:ok, %__MODULE__{id: id, attribute: attribute}}
_invalid_ssrc -> {:error, :invalid_ssrc}
end
else
_invalid_ssrc -> {:error, :invalid_ssrc}
end
end
end
defimpl String.Chars, for: ExSDP.Attribute.SSRC do
alias ExSDP.Attribute.SSRC
@impl true
def to_string(%SSRC{id: id, attribute: attribute, value: nil}), do: "ssrc:#{id} #{attribute}"
def to_string(%SSRC{id: id, attribute: attribute, value: value}),
do: "ssrc:#{id} #{attribute}:#{value}"
end
| 31.097561 | 95 | 0.64 |
79a068b477d4d4d74bd6cd5d9d8a9e3b89e40d1e | 19,314 | ex | Elixir | lib/aws/generated/doc_db.ex | salemove/aws-elixir | debdf6482158a71a57636ac664c911e682093395 | [
"Apache-2.0"
] | null | null | null | lib/aws/generated/doc_db.ex | salemove/aws-elixir | debdf6482158a71a57636ac664c911e682093395 | [
"Apache-2.0"
] | null | null | null | lib/aws/generated/doc_db.ex | salemove/aws-elixir | debdf6482158a71a57636ac664c911e682093395 | [
"Apache-2.0"
] | null | null | null | # WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
# See https://github.com/aws-beam/aws-codegen for more details.
defmodule AWS.DocDB do
@moduledoc """
Amazon DocumentDB API documentation
"""
alias AWS.Client
alias AWS.Request
def metadata do
%AWS.ServiceMetadata{
abbreviation: "Amazon DocDB",
api_version: "2014-10-31",
content_type: "application/x-www-form-urlencoded",
credential_scope: nil,
endpoint_prefix: "rds",
global?: false,
protocol: "query",
service_id: "DocDB",
signature_version: "v4",
signing_name: "rds",
target_prefix: nil
}
end
@doc """
Adds metadata tags to an Amazon DocumentDB resource.
You can use these tags with cost allocation reporting to track costs that are
associated with Amazon DocumentDB resources. or in a `Condition` statement in an
AWS Identity and Access Management (IAM) policy for Amazon DocumentDB.
"""
def add_tags_to_resource(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "AddTagsToResource", input, options)
end
@doc """
Applies a pending maintenance action to a resource (for example, to an Amazon
DocumentDB instance).
"""
def apply_pending_maintenance_action(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ApplyPendingMaintenanceAction", input, options)
end
@doc """
Copies the specified cluster parameter group.
"""
def copy_db_cluster_parameter_group(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CopyDBClusterParameterGroup", input, options)
end
@doc """
Copies a snapshot of a cluster.
To copy a cluster snapshot from a shared manual cluster snapshot,
`SourceDBClusterSnapshotIdentifier` must be the Amazon Resource Name (ARN) of
the shared cluster snapshot. You can only copy a shared DB cluster snapshot,
whether encrypted or not, in the same AWS Region.
To cancel the copy operation after it is in progress, delete the target cluster
snapshot identified by `TargetDBClusterSnapshotIdentifier` while that cluster
snapshot is in the *copying* status.
"""
def copy_db_cluster_snapshot(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CopyDBClusterSnapshot", input, options)
end
@doc """
Creates a new Amazon DocumentDB cluster.
"""
def create_db_cluster(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateDBCluster", input, options)
end
@doc """
Creates a new cluster parameter group.
Parameters in a cluster parameter group apply to all of the instances in a
cluster.
A cluster parameter group is initially created with the default parameters for
the database engine used by instances in the cluster. In Amazon DocumentDB, you
cannot make modifications directly to the `default.docdb3.6` cluster parameter
group. If your Amazon DocumentDB cluster is using the default cluster parameter
group and you want to modify a value in it, you must first [ create a new parameter
group](https://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_group-create.html)
or [ copy an existing parameter group](https://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_group-copy.html),
modify it, and then apply the modified parameter group to your cluster. For the
new cluster parameter group and associated settings to take effect, you must
then reboot the instances in the cluster without failover. For more information,
see [ Modifying Amazon DocumentDB Cluster Parameter Groups](https://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_group-modify.html).
"""
def create_db_cluster_parameter_group(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateDBClusterParameterGroup", input, options)
end
@doc """
Creates a snapshot of a cluster.
"""
def create_db_cluster_snapshot(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateDBClusterSnapshot", input, options)
end
@doc """
Creates a new instance.
"""
def create_db_instance(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateDBInstance", input, options)
end
@doc """
Creates a new subnet group.
subnet groups must contain at least one subnet in at least two Availability
Zones in the AWS Region.
"""
def create_db_subnet_group(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "CreateDBSubnetGroup", input, options)
end
@doc """
Deletes a previously provisioned cluster.
When you delete a cluster, all automated backups for that cluster are deleted
and can't be recovered. Manual DB cluster snapshots of the specified cluster are
not deleted.
"""
def delete_db_cluster(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteDBCluster", input, options)
end
@doc """
Deletes a specified cluster parameter group.
The cluster parameter group to be deleted can't be associated with any clusters.
"""
def delete_db_cluster_parameter_group(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteDBClusterParameterGroup", input, options)
end
@doc """
Deletes a cluster snapshot.
If the snapshot is being copied, the copy operation is terminated.
The cluster snapshot must be in the `available` state to be deleted.
"""
def delete_db_cluster_snapshot(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteDBClusterSnapshot", input, options)
end
@doc """
Deletes a previously provisioned instance.
"""
def delete_db_instance(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteDBInstance", input, options)
end
@doc """
Deletes a subnet group.
The specified database subnet group must not be associated with any DB
instances.
"""
def delete_db_subnet_group(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DeleteDBSubnetGroup", input, options)
end
@doc """
Returns a list of certificate authority (CA) certificates provided by Amazon
DocumentDB for this AWS account.
"""
def describe_certificates(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeCertificates", input, options)
end
@doc """
Returns a list of `DBClusterParameterGroup` descriptions.
If a `DBClusterParameterGroupName` parameter is specified, the list contains
only the description of the specified cluster parameter group.
"""
def describe_db_cluster_parameter_groups(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeDBClusterParameterGroups", input, options)
end
@doc """
Returns the detailed parameter list for a particular cluster parameter group.
"""
def describe_db_cluster_parameters(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeDBClusterParameters", input, options)
end
@doc """
Returns a list of cluster snapshot attribute names and values for a manual DB
cluster snapshot.
When you share snapshots with other AWS accounts,
`DescribeDBClusterSnapshotAttributes` returns the `restore` attribute and a list
of IDs for the AWS accounts that are authorized to copy or restore the manual
cluster snapshot. If `all` is included in the list of values for the `restore`
attribute, then the manual cluster snapshot is public and can be copied or
restored by all AWS accounts.
"""
def describe_db_cluster_snapshot_attributes(%Client{} = client, input, options \\ []) do
Request.request_post(
client,
metadata(),
"DescribeDBClusterSnapshotAttributes",
input,
options
)
end
@doc """
Returns information about cluster snapshots.
This API operation supports pagination.
"""
def describe_db_cluster_snapshots(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeDBClusterSnapshots", input, options)
end
@doc """
Returns information about provisioned Amazon DocumentDB clusters.
This API operation supports pagination. For certain management features such as
cluster and instance lifecycle management, Amazon DocumentDB leverages
operational technology that is shared with Amazon RDS and Amazon Neptune. Use
the `filterName=engine,Values=docdb` filter parameter to return only Amazon
DocumentDB clusters.
"""
def describe_db_clusters(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeDBClusters", input, options)
end
@doc """
Returns a list of the available engines.
"""
def describe_db_engine_versions(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeDBEngineVersions", input, options)
end
@doc """
Returns information about provisioned Amazon DocumentDB instances.
This API supports pagination.
"""
def describe_db_instances(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeDBInstances", input, options)
end
@doc """
Returns a list of `DBSubnetGroup` descriptions.
If a `DBSubnetGroupName` is specified, the list will contain only the
descriptions of the specified `DBSubnetGroup`.
"""
def describe_db_subnet_groups(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeDBSubnetGroups", input, options)
end
@doc """
Returns the default engine and system parameter information for the cluster
database engine.
"""
def describe_engine_default_cluster_parameters(%Client{} = client, input, options \\ []) do
Request.request_post(
client,
metadata(),
"DescribeEngineDefaultClusterParameters",
input,
options
)
end
@doc """
Displays a list of categories for all event source types, or, if specified, for
a specified source type.
"""
def describe_event_categories(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeEventCategories", input, options)
end
@doc """
Returns events related to instances, security groups, snapshots, and DB
parameter groups for the past 14 days.
You can obtain events specific to a particular DB instance, security group,
snapshot, or parameter group by providing the name as a parameter. By default,
the events of the past hour are returned.
"""
def describe_events(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeEvents", input, options)
end
@doc """
Returns a list of orderable instance options for the specified engine.
"""
def describe_orderable_db_instance_options(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribeOrderableDBInstanceOptions", input, options)
end
@doc """
Returns a list of resources (for example, instances) that have at least one
pending maintenance action.
"""
def describe_pending_maintenance_actions(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "DescribePendingMaintenanceActions", input, options)
end
@doc """
Forces a failover for a cluster.
A failover for a cluster promotes one of the Amazon DocumentDB replicas
(read-only instances) in the cluster to be the primary instance (the cluster
writer).
If the primary instance fails, Amazon DocumentDB automatically fails over to an
Amazon DocumentDB replica, if one exists. You can force a failover when you want
to simulate a failure of a primary instance for testing.
"""
def failover_db_cluster(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "FailoverDBCluster", input, options)
end
@doc """
Lists all tags on an Amazon DocumentDB resource.
"""
def list_tags_for_resource(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ListTagsForResource", input, options)
end
@doc """
Modifies a setting for an Amazon DocumentDB cluster.
You can change one or more database configuration parameters by specifying these
parameters and the new values in the request.
"""
def modify_db_cluster(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ModifyDBCluster", input, options)
end
@doc """
Modifies the parameters of a cluster parameter group.
To modify more than one parameter, submit a list of the following:
`ParameterName`, `ParameterValue`, and `ApplyMethod`. A maximum of 20 parameters
can be modified in a single request.
Changes to dynamic parameters are applied immediately. Changes to static
parameters require a reboot or maintenance window before the change can take
effect.
After you create a cluster parameter group, you should wait at least 5 minutes
before creating your first cluster that uses that cluster parameter group as the
default parameter group. This allows Amazon DocumentDB to fully complete the
create action before the parameter group is used as the default for a new
cluster. This step is especially important for parameters that are critical when
creating the default database for a cluster, such as the character set for the
default database defined by the `character_set_database` parameter.
"""
def modify_db_cluster_parameter_group(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ModifyDBClusterParameterGroup", input, options)
end
@doc """
Adds an attribute and values to, or removes an attribute and values from, a
manual DB cluster snapshot.
To share a manual cluster snapshot with other AWS accounts, specify `restore` as
the `AttributeName`, and use the `ValuesToAdd` parameter to add a list of IDs of
the AWS accounts that are authorized to restore the manual cluster snapshot. Use
the value `all` to make the manual cluster snapshot public, which means that it
can be copied or restored by all AWS accounts. Do not add the `all` value for
any manual DB cluster snapshots that contain private information that you don't
want available to all AWS accounts. If a manual cluster snapshot is encrypted,
it can be shared, but only by specifying a list of authorized AWS account IDs
for the `ValuesToAdd` parameter. You can't use `all` as a value for that
parameter in this case.
"""
def modify_db_cluster_snapshot_attribute(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ModifyDBClusterSnapshotAttribute", input, options)
end
@doc """
Modifies settings for an instance.
You can change one or more database configuration parameters by specifying these
parameters and the new values in the request.
"""
def modify_db_instance(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ModifyDBInstance", input, options)
end
@doc """
Modifies an existing subnet group.
subnet groups must contain at least one subnet in at least two Availability
Zones in the AWS Region.
"""
def modify_db_subnet_group(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ModifyDBSubnetGroup", input, options)
end
@doc """
You might need to reboot your instance, usually for maintenance reasons.
For example, if you make certain changes, or if you change the cluster parameter
group that is associated with the instance, you must reboot the instance for the
changes to take effect.
Rebooting an instance restarts the database engine service. Rebooting an
instance results in a momentary outage, during which the instance status is set
to *rebooting*.
"""
def reboot_db_instance(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "RebootDBInstance", input, options)
end
@doc """
Removes metadata tags from an Amazon DocumentDB resource.
"""
def remove_tags_from_resource(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "RemoveTagsFromResource", input, options)
end
@doc """
Modifies the parameters of a cluster parameter group to the default value.
To reset specific parameters, submit a list of the following: `ParameterName`
and `ApplyMethod`. To reset the entire cluster parameter group, specify the
`DBClusterParameterGroupName` and `ResetAllParameters` parameters.
When you reset the entire group, dynamic parameters are updated immediately and
static parameters are set to `pending-reboot` to take effect on the next DB
instance reboot.
"""
def reset_db_cluster_parameter_group(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "ResetDBClusterParameterGroup", input, options)
end
@doc """
Creates a new cluster from a snapshot or cluster snapshot.
If a snapshot is specified, the target cluster is created from the source DB
snapshot with a default configuration and default security group.
If a cluster snapshot is specified, the target cluster is created from the
source cluster restore point with the same configuration as the original source
DB cluster, except that the new cluster is created with the default security
group.
"""
def restore_db_cluster_from_snapshot(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "RestoreDBClusterFromSnapshot", input, options)
end
@doc """
Restores a cluster to an arbitrary point in time.
Users can restore to any point in time before `LatestRestorableTime` for up to
`BackupRetentionPeriod` days. The target cluster is created from the source
cluster with the same configuration as the original cluster, except that the new
cluster is created with the default security group.
"""
def restore_db_cluster_to_point_in_time(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "RestoreDBClusterToPointInTime", input, options)
end
@doc """
Restarts the stopped cluster that is specified by `DBClusterIdentifier`.
For more information, see [Stopping and Starting an Amazon DocumentDB Cluster](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-stop-start.html).
"""
def start_db_cluster(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "StartDBCluster", input, options)
end
@doc """
Stops the running cluster that is specified by `DBClusterIdentifier`.
The cluster must be in the *available* state. For more information, see
[Stopping and Starting an Amazon DocumentDB Cluster](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-stop-start.html).
"""
def stop_db_cluster(%Client{} = client, input, options \\ []) do
Request.request_post(client, metadata(), "StopDBCluster", input, options)
end
end
| 39.336049 | 170 | 0.737393 |
79a069f8e3c855826034bdbd3221a8c32cb1fe8c | 766 | ex | Elixir | lib/salty/aead_chacha20poly1305.ex | benknowles/libsalty | 38a10812865cb855bfa46cf266bb68d51a296f39 | [
"Apache-2.0"
] | 23 | 2017-07-04T19:29:43.000Z | 2021-02-16T19:44:38.000Z | lib/salty/aead_chacha20poly1305.ex | benknowles/libsalty | 38a10812865cb855bfa46cf266bb68d51a296f39 | [
"Apache-2.0"
] | 16 | 2017-08-13T15:31:25.000Z | 2019-06-19T14:44:13.000Z | lib/salty/aead_chacha20poly1305.ex | benknowles/libsalty | 38a10812865cb855bfa46cf266bb68d51a296f39 | [
"Apache-2.0"
] | 19 | 2017-08-10T19:01:49.000Z | 2021-06-20T01:34:59.000Z | defmodule Salty.Aead.Chacha20poly1305 do
use Salty.Aead
def keybytes do
C.aead_chacha20poly1305_KEYBYTES()
end
def nsecbytes do
C.aead_chacha20poly1305_NSECBYTES()
end
def npubbytes do
C.aead_chacha20poly1305_NPUBBYTES()
end
def abytes do
C.aead_chacha20poly1305_ABYTES()
end
def encrypt(plain, ad, nsec, npub, key) when nsec == nil do
C.aead_chacha20poly1305_encrypt(plain, ad, nsec, npub, key)
end
def encrypt_detached(plain, ad, nsec, npub, key) when nsec == nil do
C.aead_chacha20poly1305_encrypt_detached(plain, ad, nsec, npub, key)
end
def decrypt_detached(nsec, cipher, mac, ad, npub, key) when nsec == nil do
C.aead_chacha20poly1305_decrypt_detached(nsec, cipher, mac, ad, npub, key)
end
end
| 23.212121 | 78 | 0.729765 |
79a06b96d63089c3db98ac0a81bd7c3b04db11fb | 2,018 | exs | Elixir | products/config/prod.exs | DivvyPayHQ/federation_poc | 74839abf7d3eb8e3029468bbe4d335d7b240da97 | [
"MIT"
] | 2 | 2021-09-21T13:36:49.000Z | 2021-09-25T13:17:40.000Z | products/config/prod.exs | DivvyPayHQ/federation_poc | 74839abf7d3eb8e3029468bbe4d335d7b240da97 | [
"MIT"
] | null | null | null | products/config/prod.exs | DivvyPayHQ/federation_poc | 74839abf7d3eb8e3029468bbe4d335d7b240da97 | [
"MIT"
] | null | null | null | use Mix.Config
# For production, don't forget to configure the url host
# to something meaningful, Phoenix uses this information
# when generating URLs.
#
# Note we also include the path to a cache manifest
# containing the digested version of static files. This
# manifest is generated by the `mix phx.digest` task,
# which you should run after static files are built and
# before starting your production server.
config :products, ProductsWeb.Endpoint,
url: [host: "example.com", port: 80],
cache_static_manifest: "priv/static/cache_manifest.json"
# Do not print debug messages in production
config :logger, level: :info
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :products, ProductsWeb.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [
# port: 443,
# cipher_suite: :strong,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH"),
# transport_options: [socket_opts: [:inet6]]
# ]
#
# The `cipher_suite` is set to `:strong` to support only the
# latest and more secure SSL ciphers. This means old browsers
# and clients may not be supported. You can set it to
# `:compatible` for wider support.
#
# `:keyfile` and `:certfile` expect an absolute path to the key
# and cert in disk or a relative path inside priv, for example
# "priv/ssl/server.key". For all supported SSL configuration
# options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1
#
# We also recommend setting `force_ssl` in your endpoint, ensuring
# no data is ever sent via http, always redirecting to https:
#
# config :products, ProductsWeb.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# Finally import the config/prod.secret.exs which loads secrets
# and configuration from environment variables.
import_config "prod.secret.exs"
| 36.035714 | 66 | 0.71556 |
79a070bba74c8ac0143b6424acf00f0cc782d818 | 2,049 | exs | Elixir | config/dev.exs | aronkst/elixir_phoenix_liveview_n_queen | e23d0c4dad0d16fecdd41b709a4d9830edf8bdee | [
"MIT"
] | 1 | 2020-05-09T02:03:24.000Z | 2020-05-09T02:03:24.000Z | config/dev.exs | aronkst/elixir_phoenix_liveview_n_queen | e23d0c4dad0d16fecdd41b709a4d9830edf8bdee | [
"MIT"
] | null | null | null | config/dev.exs | aronkst/elixir_phoenix_liveview_n_queen | e23d0c4dad0d16fecdd41b709a4d9830edf8bdee | [
"MIT"
] | null | null | null | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with webpack to recompile .js and .css sources.
config :elixir_phoenix_liveview_n_queen, ElixirPhoenixLiveviewNQueenWeb.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 :elixir_phoenix_liveview_n_queen, ElixirPhoenixLiveviewNQueenWeb.Endpoint,
live_reload: [
patterns: [
~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$",
~r"priv/gettext/.*(po)$",
~r"lib/elixir_phoenix_liveview_n_queen_web/(live|views)/.*(ex)$",
~r"lib/elixir_phoenix_liveview_n_queen_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
| 30.132353 | 81 | 0.704734 |
79a08a60aafb38904a1e79f285b45c3eafcbbf4f | 257 | ex | Elixir | lib/conversions.ex | electricshaman/mesquitte | a144b59f25823bef033b71d065b1abcbf770ce78 | [
"MIT"
] | null | null | null | lib/conversions.ex | electricshaman/mesquitte | a144b59f25823bef033b71d065b1abcbf770ce78 | [
"MIT"
] | null | null | null | lib/conversions.ex | electricshaman/mesquitte | a144b59f25823bef033b71d065b1abcbf770ce78 | [
"MIT"
] | null | null | null | defmodule Mesquitte.Conversions do
def to_int(true), do: 1
def to_int(false), do: 0
def to_int(value) when is_integer(value), do: value
def to_bool(1), do: true
def to_bool(0), do: false
def to_bool(value) when is_boolean(value), do: value
end
| 25.7 | 54 | 0.712062 |
79a1265bedaddbd04f8daba9268b5d81d5876e77 | 1,998 | ex | Elixir | clients/iam/lib/google_api/iam/v1/model/set_iam_policy_request.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/iam/lib/google_api/iam/v1/model/set_iam_policy_request.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/iam/lib/google_api/iam/v1/model/set_iam_policy_request.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.IAM.V1.Model.SetIamPolicyRequest do
@moduledoc """
Request message for `SetIamPolicy` method.
## Attributes
* `policy` (*type:* `GoogleApi.IAM.V1.Model.Policy.t`, *default:* `nil`) - REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Google Cloud services (such as Projects) might reject them.
* `updateMask` (*type:* `String.t`, *default:* `nil`) - OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only the fields in the mask will be modified. If no mask is provided, the following default mask is used: `paths: "bindings, etag"`
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:policy => GoogleApi.IAM.V1.Model.Policy.t() | nil,
:updateMask => String.t() | nil
}
field(:policy, as: GoogleApi.IAM.V1.Model.Policy)
field(:updateMask)
end
defimpl Poison.Decoder, for: GoogleApi.IAM.V1.Model.SetIamPolicyRequest do
def decode(value, options) do
GoogleApi.IAM.V1.Model.SetIamPolicyRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.IAM.V1.Model.SetIamPolicyRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 39.96 | 301 | 0.731732 |
79a138bf25a56d80408abd8e89a89d154cdfd07b | 72 | ex | Elixir | lib/planga_web/controllers/app_controller.ex | ResiliaDev/Planga | b21d290dd7c2c7fa30571d0a5124d63bd09c0c9e | [
"MIT"
] | 37 | 2018-07-13T14:08:16.000Z | 2021-04-09T15:00:22.000Z | lib/planga_web/controllers/app_controller.ex | ResiliaDev/Planga | b21d290dd7c2c7fa30571d0a5124d63bd09c0c9e | [
"MIT"
] | 9 | 2018-07-16T15:24:39.000Z | 2021-09-01T14:21:20.000Z | lib/planga_web/controllers/app_controller.ex | ResiliaDev/Planga | b21d290dd7c2c7fa30571d0a5124d63bd09c0c9e | [
"MIT"
] | 3 | 2018-10-05T20:19:25.000Z | 2019-12-05T00:30:01.000Z | defmodule PlangaWeb.AppController do
# use PlangaWeb, :controller
end
| 18 | 36 | 0.805556 |
79a13dfe65c5676dbc7d2ddb854a2a98d0473654 | 3,322 | exs | Elixir | test/single_product_web/controllers/user_confirmation_controller_test.exs | manojsamanta/stripe-single-product | d0af1cede55ce6ac71100b9f4b5473919c16c884 | [
"MIT"
] | null | null | null | test/single_product_web/controllers/user_confirmation_controller_test.exs | manojsamanta/stripe-single-product | d0af1cede55ce6ac71100b9f4b5473919c16c884 | [
"MIT"
] | null | null | null | test/single_product_web/controllers/user_confirmation_controller_test.exs | manojsamanta/stripe-single-product | d0af1cede55ce6ac71100b9f4b5473919c16c884 | [
"MIT"
] | null | null | null | defmodule SingleProductWeb.UserConfirmationControllerTest do
use SingleProductWeb.ConnCase, async: true
alias SingleProduct.Accounts
alias SingleProduct.Repo
import SingleProduct.AccountsFixtures
setup do
%{user: user_fixture()}
end
describe "GET /users/confirm" do
test "renders the confirmation page", %{conn: conn} do
conn = get(conn, Routes.user_confirmation_path(conn, :new))
response = html_response(conn, 200)
assert response =~ "<h1>Resend confirmation instructions</h1>"
end
end
describe "POST /users/confirm" do
@tag :capture_log
test "sends a new confirmation token", %{conn: conn, user: user} do
conn =
post(conn, Routes.user_confirmation_path(conn, :create), %{
"user" => %{"email" => user.email}
})
assert redirected_to(conn) == "/"
assert get_flash(conn, :info) =~ "If your email is in our system"
assert Repo.get_by!(Accounts.UserToken, user_id: user.id).context == "confirm"
end
test "does not send confirmation token if User is confirmed", %{conn: conn, user: user} do
Repo.update!(Accounts.User.confirm_changeset(user))
conn =
post(conn, Routes.user_confirmation_path(conn, :create), %{
"user" => %{"email" => user.email}
})
assert redirected_to(conn) == "/"
assert get_flash(conn, :info) =~ "If your email is in our system"
refute Repo.get_by(Accounts.UserToken, user_id: user.id)
end
test "does not send confirmation token if email is invalid", %{conn: conn} do
conn =
post(conn, Routes.user_confirmation_path(conn, :create), %{
"user" => %{"email" => "[email protected]"}
})
assert redirected_to(conn) == "/"
assert get_flash(conn, :info) =~ "If your email is in our system"
assert Repo.all(Accounts.UserToken) == []
end
end
describe "GET /users/confirm/:token" do
test "confirms the given token once", %{conn: conn, user: user} do
token =
extract_user_token(fn url ->
Accounts.deliver_user_confirmation_instructions(user, url)
end)
conn = get(conn, Routes.user_confirmation_path(conn, :confirm, token))
assert redirected_to(conn) == "/"
assert get_flash(conn, :info) =~ "User confirmed successfully"
assert Accounts.get_user!(user.id).confirmed_at
refute get_session(conn, :user_token)
assert Repo.all(Accounts.UserToken) == []
# When not logged in
conn = get(conn, Routes.user_confirmation_path(conn, :confirm, token))
assert redirected_to(conn) == "/"
assert get_flash(conn, :error) =~ "User confirmation link is invalid or it has expired"
# When logged in
conn =
build_conn()
|> log_in_user(user)
|> get(Routes.user_confirmation_path(conn, :confirm, token))
assert redirected_to(conn) == "/"
refute get_flash(conn, :error)
end
test "does not confirm email with invalid token", %{conn: conn, user: user} do
conn = get(conn, Routes.user_confirmation_path(conn, :confirm, "oops"))
assert redirected_to(conn) == "/"
assert get_flash(conn, :error) =~ "User confirmation link is invalid or it has expired"
refute Accounts.get_user!(user.id).confirmed_at
end
end
end
| 34.968421 | 94 | 0.649308 |
79a15a78b0e816516220485364693048835dae7e | 554 | ex | Elixir | test/support/pid_helpers.ex | fhunleth/slipstream | cebd924384b93b7dd3c1aa6ae2ac8d237e942f18 | [
"Apache-2.0"
] | 63 | 2021-02-10T16:18:11.000Z | 2022-03-18T11:06:44.000Z | test/support/pid_helpers.ex | fhunleth/slipstream | cebd924384b93b7dd3c1aa6ae2ac8d237e942f18 | [
"Apache-2.0"
] | 21 | 2021-01-30T21:00:06.000Z | 2021-12-27T04:27:15.000Z | test/support/pid_helpers.ex | fhunleth/slipstream | cebd924384b93b7dd3c1aa6ae2ac8d237e942f18 | [
"Apache-2.0"
] | 6 | 2021-02-26T23:56:49.000Z | 2022-03-26T09:28:13.000Z | defmodule Slipstream.PidHelpers do
@moduledoc """
Helpers for dealing with pids
Most of the tests for slipstream involve processes sending eachother messages.
Some of these pids are sent over-the-wire as strings, so we need helper
functions to serialize and deserialize them.
"""
def pid_string do
[pid_string] = Regex.run(~r/[\d\.]+/, inspect(self()))
pid_string
end
# N.B. this is a re-implementation of Iex.Helpers.pid/1
# I thought this was a Kernel function :P
def pid(str), do: :erlang.list_to_pid('<#{str}>')
end
| 27.7 | 80 | 0.705776 |
79a15da6ff887a63c061ed356430945f06bae228 | 68,453 | ex | Elixir | lib/elixir/lib/enum.ex | alfert/elixir | 4dfd08c79dc8b67e8a6d53add9e3ee47ba9be647 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/enum.ex | alfert/elixir | 4dfd08c79dc8b67e8a6d53add9e3ee47ba9be647 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/enum.ex | alfert/elixir | 4dfd08c79dc8b67e8a6d53add9e3ee47ba9be647 | [
"Apache-2.0"
] | null | null | null | defprotocol Enumerable do
@moduledoc """
Enumerable protocol used by `Enum` and `Stream` modules.
When you invoke a function in the `Enum` module, the first argument
is usually a collection that must implement this protocol. For example,
the expression
Enum.map([1, 2, 3], &(&1 * 2))
invokes underneath `Enumerable.reduce/3` to perform the reducing
operation that builds a mapped list by calling the mapping function
`&(&1 * 2)` on every element in the collection and cons'ing the
element with an accumulated list.
Internally, `Enum.map/2` is implemented as follows:
def map(enum, fun) do
reducer = fn x, acc -> {:cont, [fun.(x)|acc]} end
Enumerable.reduce(enum, {:cont, []}, reducer) |> elem(1) |> :lists.reverse()
end
Notice the user given function is wrapped into a `reducer` function.
The `reducer` function must return a tagged tuple after each step,
as described in the `acc/0` type.
The reason the accumulator requires a tagged tuple is to allow the
reducer function to communicate to the underlying enumerable the end
of enumeration, allowing any open resource to be properly closed. It
also allows suspension of the enumeration, which is useful when
interleaving between many enumerables is required (as in zip).
Finally, `Enumerable.reduce/3` will return another tagged tuple,
as represented by the `result/0` type.
"""
@typedoc """
The accumulator value for each step.
It must be a tagged tuple with one of the following "tags":
* `:cont` - the enumeration should continue
* `:halt` - the enumeration should halt immediately
* `:suspend` - the enumeration should be suspended immediately
Depending on the accumulator value, the result returned by
`Enumerable.reduce/3` will change. Please check the `result`
type docs for more information.
In case a reducer function returns a `:suspend` accumulator,
it must be explicitly handled by the caller and never leak.
"""
@type acc :: {:cont, term} | {:halt, term} | {:suspend, term}
@typedoc """
The reducer function.
Should be called with the collection element and the
accumulator contents. Returns the accumulator for
the next enumeration step.
"""
@type reducer :: (term, term -> acc)
@typedoc """
The result of the reduce operation.
It may be *done* when the enumeration is finished by reaching
its end, or *halted*/*suspended* when the enumeration was halted
or suspended by the reducer function.
In case a reducer function returns the `:suspend` accumulator, the
`:suspended` tuple must be explicitly handled by the caller and
never leak. In practice, this means regular enumeration functions
just need to be concerned about `:done` and `:halted` results.
Furthermore, a `:suspend` call must always be followed by another call,
eventually halting or continuing until the end.
"""
@type result :: {:done, term} | {:halted, term} | {:suspended, term, continuation}
@typedoc """
A partially applied reduce function.
The continuation is the closure returned as a result when
the enumeration is suspended. When invoked, it expects
a new accumulator and it returns the result.
A continuation is easily implemented as long as the reduce
function is defined in a tail recursive fashion. If the function
is tail recursive, all the state is passed as arguments, so
the continuation would simply be the reducing function partially
applied.
"""
@type continuation :: (acc -> result)
@doc """
Reduces the collection into a value.
Most of the operations in `Enum` are implemented in terms of reduce.
This function should apply the given `reducer` function to each
item in the collection and proceed as expected by the returned accumulator.
As an example, here is the implementation of `reduce` for lists:
def reduce(_, {:halt, acc}, _fun), do: {:halted, acc}
def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}
def reduce([], {:cont, acc}, _fun), do: {:done, acc}
def reduce([h|t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun)
"""
@spec reduce(t, acc, reducer) :: result
def reduce(collection, acc, fun)
@doc """
Checks if a value exists within the collection.
It should return `{:ok, boolean}`.
If `{:error, __MODULE__}` is returned a default algorithm using `reduce` and
the match (`===`) operator is used. This algorithm runs in linear time.
Please force use of the default algorithm unless you can implement an
algorithm that is significantly faster.
"""
@spec member?(t, term) :: {:ok, boolean} | {:error, module}
def member?(collection, value)
@doc """
Retrieves the collection's size.
It should return `{:ok, size}`.
If `{:error, __MODULE__}` is returned a default algorithm using `reduce` and
the match (`===`) operator is used. This algorithm runs in linear time.
Please force use of the default algorithm unless you can implement an
algorithm that is significantly faster.
"""
@spec count(t) :: {:ok, non_neg_integer} | {:error, module}
def count(collection)
end
defmodule Enum do
import Kernel, except: [max: 2, min: 2]
@moduledoc """
Provides a set of algorithms that enumerate over collections according to the
`Enumerable` protocol:
iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)
[2, 4, 6]
Some particular types, like dictionaries, yield a specific format on
enumeration. For dicts, the argument is always a `{key, value}` tuple:
iex> dict = %{a: 1, b: 2}
iex> Enum.map(dict, fn {k, v} -> {k, v * 2} end)
[a: 2, b: 4]
Note that the functions in the `Enum` module are eager: they always start
the enumeration of the given collection. The `Stream` module allows
lazy enumeration of collections and provides infinite streams.
Since the majority of the functions in `Enum` enumerate the whole
collection and return a list as result, infinite streams need to
be carefully used with such functions, as they can potentially run
forever. For example:
Enum.each Stream.cycle([1, 2, 3]), &IO.puts(&1)
"""
@compile :inline_list_funcs
@type t :: Enumerable.t
@type element :: any
@type index :: non_neg_integer
@type default :: any
# Require Stream.Reducers and its callbacks
require Stream.Reducers, as: R
defmacrop skip(acc) do
acc
end
defmacrop next(_, entry, acc) do
quote do: [unquote(entry)|unquote(acc)]
end
defmacrop acc(h, n, _) do
quote do: {unquote(h), unquote(n)}
end
defmacrop next_with_acc(f, entry, h, n, _) do
quote do
{[unquote(entry)|unquote(h)], unquote(n)}
end
end
@doc """
Invokes the given `fun` for each item in the `collection` and returns `false`
if at least one invocation returns `false` or `nil`. Otherwise returns `true`.
## Examples
iex> Enum.all?([2, 4, 6], fn(x) -> rem(x, 2) == 0 end)
true
iex> Enum.all?([2, 3, 4], fn(x) -> rem(x, 2) == 0 end)
false
If no function is given, it defaults to checking if
all items in the collection are truthy values.
iex> Enum.all?([1, 2, 3])
true
iex> Enum.all?([1, nil, 3])
false
"""
@spec all?(t) :: boolean
@spec all?(t, (element -> as_boolean(term))) :: boolean
def all?(collection, fun \\ fn(x) -> x end)
def all?(collection, fun) when is_list(collection) do
do_all?(collection, fun)
end
def all?(collection, fun) do
Enumerable.reduce(collection, {:cont, true}, fn(entry, _) ->
if fun.(entry), do: {:cont, true}, else: {:halt, false}
end) |> elem(1)
end
@doc """
Invokes the given `fun` for each item in the `collection` and returns `true` if
at least one invocation returns a truthy value. Returns `false` otherwise.
## Examples
iex> Enum.any?([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)
false
iex> Enum.any?([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)
true
If no function is given, it defaults to checking if
at least one item in the collection is a truthy value.
iex> Enum.any?([false, false, false])
false
iex> Enum.any?([false, true, false])
true
"""
@spec any?(t) :: boolean
@spec any?(t, (element -> as_boolean(term))) :: boolean
def any?(collection, fun \\ fn(x) -> x end)
def any?(collection, fun) when is_list(collection) do
do_any?(collection, fun)
end
def any?(collection, fun) do
Enumerable.reduce(collection, {:cont, false}, fn(entry, _) ->
if fun.(entry), do: {:halt, true}, else: {:cont, false}
end) |> elem(1)
end
@doc """
Finds the element at the given index (zero-based).
Returns `default` if index is out of bounds.
Note this operation takes linear time. In order to access
the element at index `n`, it will need to traverse `n`
previous elements.
## Examples
iex> Enum.at([2, 4, 6], 0)
2
iex> Enum.at([2, 4, 6], 2)
6
iex> Enum.at([2, 4, 6], 4)
nil
iex> Enum.at([2, 4, 6], 4, :none)
:none
"""
@spec at(t, integer, default) :: element | default
def at(collection, n, default \\ nil) do
case fetch(collection, n) do
{:ok, h} -> h
:error -> default
end
end
@doc """
Shortcut to `chunk(collection, n, n)`.
"""
@spec chunk(t, non_neg_integer) :: [list]
def chunk(collection, n), do: chunk(collection, n, n, nil)
@doc """
Returns a collection of lists containing `n` items each, where
each new chunk starts `step` elements into the collection.
`step` is optional and, if not passed, defaults to `n`, i.e.
chunks do not overlap. If the final chunk does not have `n`
elements to fill the chunk, elements are taken as necessary
from `pad` if it was passed. If `pad` is passed and does not
have enough elements to fill the chunk, then the chunk is
returned anyway with less than `n` elements. If `pad` is not
passed at all or is `nil`, then the partial chunk is discarded
from the result.
## Examples
iex> Enum.chunk([1, 2, 3, 4, 5, 6], 2)
[[1, 2], [3, 4], [5, 6]]
iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 2)
[[1, 2, 3], [3, 4, 5]]
iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 2, [7])
[[1, 2, 3], [3, 4, 5], [5, 6, 7]]
iex> Enum.chunk([1, 2, 3, 4, 5, 6], 3, 3, [])
[[1, 2, 3], [4, 5, 6]]
"""
@spec chunk(t, non_neg_integer, non_neg_integer, t | nil) :: [list]
def chunk(collection, n, step, pad \\ nil) when n > 0 and step > 0 do
limit = :erlang.max(n, step)
{acc, {buffer, i}} =
reduce(collection, {[], {[], 0}}, R.chunk(n, step, limit))
if is_nil(pad) || i == 0 do
:lists.reverse(acc)
else
buffer = :lists.reverse(buffer, take(pad, n - i))
:lists.reverse([buffer|acc])
end
end
@doc """
Splits `collection` on every element for which `fun` returns a new value.
## Examples
iex> Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1))
[[1], [2, 2], [3], [4, 4, 6], [7, 7]]
"""
@spec chunk_by(t, (element -> any)) :: [list]
def chunk_by(collection, fun) do
{acc, res} = reduce(collection, {[], nil}, R.chunk_by(fun))
case res do
{buffer, _} ->
:lists.reverse([:lists.reverse(buffer) | acc])
nil ->
[]
end
end
@doc """
Given an enumerable of enumerables, concatenates the enumerables into a single list.
## Examples
iex> Enum.concat([1..3, 4..6, 7..9])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
iex> Enum.concat([[1, [2], 3], [4], [5, 6]])
[1, [2], 3, 4, 5, 6]
"""
@spec concat(t) :: t
def concat(enumerables) do
do_concat(enumerables)
end
@doc """
Concatenates the enumerable on the right with the enumerable on the left.
This function produces the same result as the `Kernel.++/2` operator for lists.
## Examples
iex> Enum.concat(1..3, 4..6)
[1, 2, 3, 4, 5, 6]
iex> Enum.concat([1, 2, 3], [4, 5, 6])
[1, 2, 3, 4, 5, 6]
"""
@spec concat(t, t) :: t
def concat(left, right) when is_list(left) and is_list(right) do
left ++ right
end
def concat(left, right) do
do_concat([left, right])
end
defp do_concat(enumerable) do
fun = &[&1|&2]
reduce(enumerable, [], &reduce(&1, &2, fun)) |> :lists.reverse
end
@doc """
Returns the collection's size.
## Examples
iex> Enum.count([1, 2, 3])
3
"""
@spec count(t) :: non_neg_integer
def count(collection) when is_list(collection) do
:erlang.length(collection)
end
def count(collection) do
case Enumerable.count(collection) do
{:ok, value} when is_integer(value) ->
value
{:error, module} ->
module.reduce(collection, {:cont, 0}, fn
_, acc -> {:cont, acc + 1}
end) |> elem(1)
end
end
@doc """
Returns the count of items in the collection for which
`fun` returns a truthy value.
## Examples
iex> Enum.count([1, 2, 3, 4, 5], fn(x) -> rem(x, 2) == 0 end)
2
"""
@spec count(t, (element -> as_boolean(term))) :: non_neg_integer
def count(collection, fun) do
Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) ->
{:cont, if(fun.(entry), do: acc + 1, else: acc)}
end) |> elem(1)
end
@doc """
Enumerates the collection, returning a list where all consecutive
duplicated elements are collapsed to a single element.
Elements are compared using `===`.
## Examples
iex> Enum.dedup([1, 2, 3, 3, 2, 1])
[1, 2, 3, 2, 1]
"""
@spec dedup(t) :: list
def dedup(collection) do
dedup_by(collection, fn x -> x end)
end
@doc """
Enumerates the collection, returning a list where all consecutive
duplicated elements are collapsed to a single element.
The function `fun` maps every element to a term which is used to
determine if two elements are duplicates.
## Examples
iex> Enum.dedup_by([{1, :x}, {2, :y}, {2, :z}, {1, :x}], fn {x, _} -> x end)
[{1, :x}, {2, :y}, {1, :x}]
iex> Enum.dedup_by([5, 1, 2, 3, 2, 1], fn x -> x > 2 end)
[5, 1, 3, 2]
"""
@spec dedup_by(t, (element -> term)) :: list
def dedup_by(collection, fun) when is_function(fun, 1) do
{list, _} = reduce(collection, {[], []}, R.dedup(fun))
:lists.reverse(list)
end
@doc """
Drops the first `count` items from `collection`.
If a negative value `count` is given, the last `count`
values will be dropped. The collection is enumerated
once to retrieve the proper index and the remaining
calculation is performed from the end.
## Examples
iex> Enum.drop([1, 2, 3], 2)
[3]
iex> Enum.drop([1, 2, 3], 10)
[]
iex> Enum.drop([1, 2, 3], 0)
[1, 2, 3]
iex> Enum.drop([1, 2, 3], -1)
[1, 2]
"""
@spec drop(t, integer) :: list
def drop(collection, count) when is_list(collection) and count >= 0 do
do_drop(collection, count)
end
def drop(collection, count) when count >= 0 do
res =
reduce(collection, count, fn
x, acc when is_list(acc) -> [x|acc]
x, 0 -> [x]
_, acc when acc > 0 -> acc - 1
end)
if is_list(res), do: :lists.reverse(res), else: []
end
def drop(collection, count) when count < 0 do
do_drop(reverse(collection), abs(count)) |> :lists.reverse
end
@doc """
Drops items at the beginning of `collection` while `fun` returns a truthy value.
## Examples
iex> Enum.drop_while([1, 2, 3, 4, 5], fn(x) -> x < 3 end)
[3, 4, 5]
"""
@spec drop_while(t, (element -> as_boolean(term))) :: list
def drop_while(collection, fun) when is_list(collection) do
do_drop_while(collection, fun)
end
def drop_while(collection, fun) do
{res, _} = reduce(collection, {[], true}, R.drop_while(fun))
:lists.reverse(res)
end
@doc """
Invokes the given `fun` for each item in the `collection`.
Returns `:ok`.
## Examples
Enum.each(["some", "example"], fn(x) -> IO.puts x end)
"some"
"example"
#=> :ok
"""
@spec each(t, (element -> any)) :: :ok
def each(collection, fun) when is_list(collection) do
:lists.foreach(fun, collection)
:ok
end
def each(collection, fun) do
reduce(collection, nil, fn(entry, _) ->
fun.(entry)
nil
end)
:ok
end
@doc """
Returns `true` if the collection is empty, otherwise `false`.
## Examples
iex> Enum.empty?([])
true
iex> Enum.empty?([1, 2, 3])
false
"""
@spec empty?(t) :: boolean
def empty?(collection) when is_list(collection) do
collection == []
end
def empty?(collection) do
Enumerable.reduce(collection, {:cont, true}, fn(_, _) -> {:halt, false} end) |> elem(1)
end
@doc """
Finds the element at the given index (zero-based).
Returns `{:ok, element}` if found, otherwise `:error`.
A negative index can be passed, which means the collection is
enumerated once and the index is counted from the end (i.e.
`-1` fetches the last element).
Note this operation takes linear time. In order to access
the element at index `n`, it will need to traverse `n`
previous elements.
## Examples
iex> Enum.fetch([2, 4, 6], 0)
{:ok, 2}
iex> Enum.fetch([2, 4, 6], 2)
{:ok, 6}
iex> Enum.fetch([2, 4, 6], 4)
:error
"""
@spec fetch(t, integer) :: {:ok, element} | :error
def fetch(collection, n) when is_list(collection) and is_integer(n) and n >= 0 do
do_fetch(collection, n)
end
def fetch(collection, n) when is_integer(n) and n >= 0 do
res =
Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) ->
if acc == n do
{:halt, entry}
else
{:cont, acc + 1}
end
end)
case res do
{:halted, entry} -> {:ok, entry}
{:done, _} -> :error
end
end
def fetch(collection, n) when is_integer(n) and n < 0 do
do_fetch(reverse(collection), abs(n + 1))
end
@doc """
Finds the element at the given index (zero-based).
Raises `OutOfBoundsError` if the given position
is outside the range of the collection.
Note this operation takes linear time. In order to access
the element at index `n`, it will need to traverse `n`
previous elements.
## Examples
iex> Enum.fetch!([2, 4, 6], 0)
2
iex> Enum.fetch!([2, 4, 6], 2)
6
iex> Enum.fetch!([2, 4, 6], 4)
** (Enum.OutOfBoundsError) out of bounds error
"""
@spec fetch!(t, integer) :: element | no_return
def fetch!(collection, n) do
case fetch(collection, n) do
{:ok, h} -> h
:error -> raise Enum.OutOfBoundsError
end
end
@doc """
Filters the collection, i.e. returns only those elements
for which `fun` returns a truthy value.
## Examples
iex> Enum.filter([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)
[2]
"""
@spec filter(t, (element -> as_boolean(term))) :: list
def filter(collection, fun) when is_list(collection) do
for item <- collection, fun.(item), do: item
end
def filter(collection, fun) do
reduce(collection, [], R.filter(fun)) |> :lists.reverse
end
@doc """
Filters the collection and maps its values in one pass.
## Examples
iex> Enum.filter_map([1, 2, 3], fn(x) -> rem(x, 2) == 0 end, &(&1 * 2))
[4]
"""
@spec filter_map(t, (element -> as_boolean(term)), (element -> element)) :: list
def filter_map(collection, filter, mapper) when is_list(collection) do
for item <- collection, filter.(item), do: mapper.(item)
end
def filter_map(collection, filter, mapper) do
reduce(collection, [], R.filter_map(filter, mapper)) |> :lists.reverse
end
@doc """
Returns the first item for which `fun` returns a truthy value. If no such
item is found, returns `ifnone`.
## Examples
iex> Enum.find([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)
nil
iex> Enum.find([2, 4, 6], 0, fn(x) -> rem(x, 2) == 1 end)
0
iex> Enum.find([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)
3
"""
@spec find(t, default, (element -> any)) :: element | default
def find(collection, ifnone \\ nil, fun)
def find(collection, ifnone, fun) when is_list(collection) do
do_find(collection, ifnone, fun)
end
def find(collection, ifnone, fun) do
Enumerable.reduce(collection, {:cont, ifnone}, fn(entry, ifnone) ->
if fun.(entry), do: {:halt, entry}, else: {:cont, ifnone}
end) |> elem(1)
end
@doc """
Similar to `find/3`, but returns the value of the function
invocation instead of the element itself.
## Examples
iex> Enum.find_value([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)
nil
iex> Enum.find_value([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)
true
iex> Enum.find_value([1, 2, 3], "no bools!", &is_boolean/1)
"no bools!"
"""
@spec find_value(t, any, (element -> any)) :: any | :nil
def find_value(collection, ifnone \\ nil, fun)
def find_value(collection, ifnone, fun) when is_list(collection) do
do_find_value(collection, ifnone, fun)
end
def find_value(collection, ifnone, fun) do
Enumerable.reduce(collection, {:cont, ifnone}, fn(entry, ifnone) ->
fun_entry = fun.(entry)
if fun_entry, do: {:halt, fun_entry}, else: {:cont, ifnone}
end) |> elem(1)
end
@doc """
Similar to `find/3`, but returns the index (zero-based)
of the element instead of the element itself.
## Examples
iex> Enum.find_index([2, 4, 6], fn(x) -> rem(x, 2) == 1 end)
nil
iex> Enum.find_index([2, 3, 4], fn(x) -> rem(x, 2) == 1 end)
1
"""
@spec find_index(t, (element -> any)) :: index | :nil
def find_index(collection, fun) when is_list(collection) do
do_find_index(collection, 0, fun)
end
def find_index(collection, fun) do
res =
Enumerable.reduce(collection, {:cont, 0}, fn(entry, acc) ->
if fun.(entry), do: {:halt, acc}, else: {:cont, acc + 1}
end)
case res do
{:halted, entry} -> entry
{:done, _} -> nil
end
end
@doc """
Returns a new collection appending the result of invoking `fun`
on each corresponding item of `collection`.
The given function should return an enumerable.
## Examples
iex> Enum.flat_map([:a, :b, :c], fn(x) -> [x, x] end)
[:a, :a, :b, :b, :c, :c]
iex> Enum.flat_map([{1, 3}, {4, 6}], fn({x, y}) -> x..y end)
[1, 2, 3, 4, 5, 6]
"""
@spec flat_map(t, (element -> t)) :: list
def flat_map(collection, fun) do
reduce(collection, [], fn(entry, acc) ->
reduce(fun.(entry), acc, &[&1|&2])
end) |> :lists.reverse
end
@doc """
Maps and reduces a collection, flattening the given results.
It expects an accumulator and a function that receives each stream item
and an accumulator, and must return a tuple containing a new stream
(often a list) with the new accumulator or a tuple with `:halt` as first
element and the accumulator as second.
## Examples
iex> enum = 1..100
iex> n = 3
iex> Enum.flat_map_reduce(enum, 0, fn i, acc ->
...> if acc < n, do: {[i], acc + 1}, else: {:halt, acc}
...> end)
{[1, 2, 3], 3}
"""
@spec flat_map_reduce(t, acc, fun) :: {[any], any} when
fun: (element, acc -> {t, acc} | {:halt, acc}),
acc: any
def flat_map_reduce(collection, acc, fun) do
{_, {list, acc}} =
Enumerable.reduce(collection, {:cont, {[], acc}}, fn(entry, {list, acc}) ->
case fun.(entry, acc) do
{:halt, acc} ->
{:halt, {list, acc}}
{[], acc} ->
{:cont, {list, acc}}
{[entry], acc} ->
{:cont, {[entry|list], acc}}
{entries, acc} ->
{:cont, {reduce(entries, list, &[&1|&2]), acc}}
end
end)
{:lists.reverse(list), acc}
end
@doc """
Intersperses `element` between each element of the enumeration.
Complexity: O(n)
## Examples
iex> Enum.intersperse([1, 2, 3], 0)
[1, 0, 2, 0, 3]
iex> Enum.intersperse([1], 0)
[1]
iex> Enum.intersperse([], 0)
[]
"""
@spec intersperse(t, element) :: list
def intersperse(collection, element) do
list =
reduce(collection, [], fn(x, acc) ->
[x, element | acc]
end) |> :lists.reverse()
case list do
[] -> []
[_|t] -> t # Head is a superfluous intersperser element
end
end
@doc """
Inserts the given enumerable into a collectable.
## Examples
iex> Enum.into([1, 2], [0])
[0, 1, 2]
iex> Enum.into([a: 1, b: 2], %{})
%{a: 1, b: 2}
"""
@spec into(Enumerable.t, Collectable.t) :: Collectable.t
def into(collection, list) when is_list(list) do
list ++ to_list(collection)
end
def into(%{__struct__: _} = collection, collectable) do
do_into(collection, collectable)
end
def into(collection, %{__struct__: _} = collectable) do
do_into(collection, collectable)
end
def into(%{} = collection, %{} = collectable) do
Map.merge(collectable, collection)
end
def into(collection, %{} = collectable) when is_list(collection) do
Map.merge(collectable, :maps.from_list(collection))
end
def into(collection, %{} = collectable) do
reduce(collection, collectable, fn {k, v}, acc ->
Map.put(acc, k, v)
end)
end
def into(collection, collectable) do
do_into(collection, collectable)
end
defp do_into(collection, collectable) do
{initial, fun} = Collectable.into(collectable)
into(collection, initial, fun, fn x, acc ->
fun.(acc, {:cont, x})
end)
end
@doc """
Inserts the given enumerable into a collectable
according to the transformation function.
## Examples
iex> Enum.into([2, 3], [3], fn x -> x * 3 end)
[3, 6, 9]
"""
@spec into(Enumerable.t, Collectable.t, (term -> term)) :: Collectable.t
def into(collection, list, transform) when is_list(list) and is_function(transform, 1) do
list ++ map(collection, transform)
end
def into(collection, collectable, transform) when is_function(transform, 1) do
{initial, fun} = Collectable.into(collectable)
into(collection, initial, fun, fn x, acc ->
fun.(acc, {:cont, transform.(x)})
end)
end
defp into(collection, initial, fun, callback) do
try do
reduce(collection, initial, callback)
catch
kind, reason ->
stacktrace = System.stacktrace
fun.(initial, :halt)
:erlang.raise(kind, reason, stacktrace)
else
acc -> fun.(acc, :done)
end
end
@doc """
Joins the given `collection` into a binary using `joiner` as a separator.
If `joiner` is not passed at all, it defaults to the empty binary.
All items in the collection must be convertible
to a binary, otherwise an error is raised.
## Examples
iex> Enum.join([1, 2, 3])
"123"
iex> Enum.join([1, 2, 3], " = ")
"1 = 2 = 3"
"""
@spec join(t, String.t) :: String.t
def join(collection, joiner \\ "")
def join(collection, joiner) when is_binary(joiner) do
reduced = reduce(collection, :first, fn
entry, :first -> enum_to_string(entry)
entry, acc -> [acc, joiner|enum_to_string(entry)]
end)
if reduced == :first do
""
else
IO.iodata_to_binary reduced
end
end
@doc """
Returns a new collection, where each item is the result
of invoking `fun` on each corresponding item of `collection`.
For dicts, the function expects a key-value tuple.
## Examples
iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)
[2, 4, 6]
iex> Enum.map([a: 1, b: 2], fn({k, v}) -> {k, -v} end)
[a: -1, b: -2]
"""
@spec map(t, (element -> any)) :: list
def map(collection, fun) when is_list(collection) do
for item <- collection, do: fun.(item)
end
def map(collection, fun) do
reduce(collection, [], R.map(fun)) |> :lists.reverse
end
@doc """
Maps and joins the given `collection` in one pass.
`joiner` can be either a binary or a list and the
result will be of the same type as `joiner`. If
`joiner` is not passed at all, it defaults to an
empty binary.
All items in the collection must be convertible
to a binary, otherwise an error is raised.
## Examples
iex> Enum.map_join([1, 2, 3], &(&1 * 2))
"246"
iex> Enum.map_join([1, 2, 3], " = ", &(&1 * 2))
"2 = 4 = 6"
"""
@spec map_join(t, String.t, (element -> any)) :: String.t
def map_join(collection, joiner \\ "", mapper)
def map_join(collection, joiner, mapper) when is_binary(joiner) do
reduced = reduce(collection, :first, fn
entry, :first -> enum_to_string(mapper.(entry))
entry, acc -> [acc, joiner|enum_to_string(mapper.(entry))]
end)
if reduced == :first do
""
else
IO.iodata_to_binary reduced
end
end
@doc """
Invokes the given `fun` for each item in the `collection`
while also keeping an accumulator. Returns a tuple where
the first element is the mapped collection and the second
one is the final accumulator.
For dicts, the first tuple element must be a `{key, value}`
tuple.
## Examples
iex> Enum.map_reduce([1, 2, 3], 0, fn(x, acc) -> {x * 2, x + acc} end)
{[2, 4, 6], 6}
"""
@spec map_reduce(t, any, (element, any -> {any, any})) :: {any, any}
def map_reduce(collection, acc, fun) when is_list(collection) do
:lists.mapfoldl(fun, acc, collection)
end
def map_reduce(collection, acc, fun) do
{list, acc} = reduce(collection, {[], acc}, fn(entry, {list, acc}) ->
{new_entry, acc} = fun.(entry, acc)
{[new_entry|list], acc}
end)
{:lists.reverse(list), acc}
end
@doc """
Returns the maximum value.
Raises `EmptyError` if the collection is empty.
## Examples
iex> Enum.max([1, 2, 3])
3
"""
@spec max(t) :: element | no_return
def max(collection) do
reduce(collection, &Kernel.max(&1, &2))
end
@doc """
Returns the maximum value as calculated by the given function.
Raises `EmptyError` if the collection is empty.
## Examples
iex> Enum.max_by(["a", "aa", "aaa"], fn(x) -> String.length(x) end)
"aaa"
"""
@spec max_by(t, (element -> any)) :: element | no_return
def max_by([h|t], fun) do
reduce(t, {h, fun.(h)}, fn(entry, {_, fun_max} = old) ->
fun_entry = fun.(entry)
if(fun_entry > fun_max, do: {entry, fun_entry}, else: old)
end) |> elem(0)
end
def max_by([], _fun) do
raise Enum.EmptyError
end
def max_by(collection, fun) do
result =
reduce(collection, :first, fn
entry, {_, fun_max} = old ->
fun_entry = fun.(entry)
if(fun_entry > fun_max, do: {entry, fun_entry}, else: old)
entry, :first ->
{entry, fun.(entry)}
end)
case result do
:first -> raise Enum.EmptyError
{entry, _} -> entry
end
end
@doc """
Checks if `value` exists within the `collection`.
Membership is tested with the match (`===`) operator, although
enumerables like ranges may include floats inside the given
range.
## Examples
iex> Enum.member?(1..10, 5)
true
iex> Enum.member?([:a, :b, :c], :d)
false
"""
@spec member?(t, element) :: boolean
def member?(collection, value) when is_list(collection) do
:lists.member(value, collection)
end
def member?(collection, value) do
case Enumerable.member?(collection, value) do
{:ok, value} when is_boolean(value) ->
value
{:error, module} ->
module.reduce(collection, {:cont, false}, fn
v, _ when v === value -> {:halt, true}
_, _ -> {:cont, false}
end) |> elem(1)
end
end
@doc """
Returns the minimum value.
Raises `EmptyError` if the collection is empty.
## Examples
iex> Enum.min([1, 2, 3])
1
"""
@spec min(t) :: element | no_return
def min(collection) do
reduce(collection, &Kernel.min(&1, &2))
end
@doc """
Returns the minimum value as calculated by the given function.
Raises `EmptyError` if the collection is empty.
## Examples
iex> Enum.min_by(["a", "aa", "aaa"], fn(x) -> String.length(x) end)
"a"
"""
@spec min_by(t, (element -> any)) :: element | no_return
def min_by([h|t], fun) do
reduce(t, {h, fun.(h)}, fn(entry, {_, fun_min} = old) ->
fun_entry = fun.(entry)
if(fun_entry < fun_min, do: {entry, fun_entry}, else: old)
end) |> elem(0)
end
def min_by([], _fun) do
raise Enum.EmptyError
end
def min_by(collection, fun) do
result =
reduce(collection, :first, fn
entry, {_, fun_min} = old ->
fun_entry = fun.(entry)
if(fun_entry < fun_min, do: {entry, fun_entry}, else: old)
entry, :first ->
{entry, fun.(entry)}
end)
case result do
:first -> raise Enum.EmptyError
{entry, _} -> entry
end
end
@doc """
Returns a tuple with the minimum and maximum values.
Raises `EmptyError` if the collection is empty.
## Examples
iex> Enum.min_max([2, 3, 1])
{1, 3}
"""
@spec min_max(t) :: element | no_return
def min_max(collection) do
result =
Enum.reduce(collection, :first, fn
entry, {min_value, max_value} ->
{Kernel.min(entry, min_value), Kernel.max(entry, max_value)}
entry, :first ->
{entry, entry}
end)
case result do
:first -> raise Enum.EmptyError
result -> result
end
end
@doc """
Returns a tuple with the minimum and maximum values as calculated by the given function.
Raises `EmptyError` if the collection is empty.
## Examples
iex> Enum.min_max_by(["aaa", "bb", "c"], fn(x) -> String.length(x) end)
{"c", "aaa"}
"""
@spec min_max_by(t, (element -> any)) :: element | no_return
def min_max_by(collection, fun) do
result =
Enum.reduce(collection, :first, fn
entry, {{_, fun_min} = acc_min, {_, fun_max} = acc_max} ->
fun_entry = fun.(entry)
if fun_entry < fun_min, do: acc_min = {entry, fun_entry}
if fun_entry > fun_max, do: acc_max = {entry, fun_entry}
{acc_min, acc_max}
entry, :first ->
fun_entry = fun.(entry)
{{entry, fun_entry}, {entry, fun_entry}}
end)
case result do
:first ->
raise Enum.EmptyError
{{min_entry, _}, {max_entry, _}} ->
{min_entry, max_entry}
end
end
@doc """
Returns the sum of all values.
Raises `ArithmeticError` if collection contains a non-numeric value.
## Examples
iex> Enum.sum([1, 2, 3])
6
"""
@spec sum(t) :: number
def sum(collection) do
reduce(collection, 0, &+/2)
end
@doc """
Partitions `collection` into two collections, where the first one contains elements
for which `fun` returns a truthy value, and the second one -- for which `fun`
returns `false` or `nil`.
## Examples
iex> Enum.partition([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)
{[2], [1, 3]}
"""
@spec partition(t, (element -> any)) :: {list, list}
def partition(collection, fun) do
{acc1, acc2} =
reduce(collection, {[], []}, fn(entry, {acc1, acc2}) ->
if fun.(entry) do
{[entry|acc1], acc2}
else
{acc1, [entry|acc2]}
end
end)
{:lists.reverse(acc1), :lists.reverse(acc2)}
end
@doc """
Splits `collection` into groups based on `fun`.
The result is a dict (by default a map) where each key is
a group and each value is a list of elements from `collection`
for which `fun` returned that group. Ordering is not necessarily
preserved.
## Examples
iex> Enum.group_by(~w{ant buffalo cat dingo}, &String.length/1)
%{3 => ["cat", "ant"], 7 => ["buffalo"], 5 => ["dingo"]}
"""
@spec group_by(t, dict, (element -> any)) :: dict when dict: Dict.t
def group_by(collection, dict \\ %{}, fun) do
reduce(collection, dict, fn(entry, categories) ->
Dict.update(categories, fun.(entry), [entry], &[entry|&1])
end)
end
@doc """
Invokes `fun` for each element in the collection passing that element and the
accumulator `acc` as arguments. `fun`'s return value is stored in `acc`.
Returns the accumulator.
## Examples
iex> Enum.reduce([1, 2, 3], 0, fn(x, acc) -> x + acc end)
6
"""
@spec reduce(t, any, (element, any -> any)) :: any
def reduce(collection, acc, fun) when is_list(collection) do
:lists.foldl(fun, acc, collection)
end
def reduce(%{__struct__: _} = collection, acc, fun) do
Enumerable.reduce(collection, {:cont, acc},
fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1)
end
def reduce(%{} = collection, acc, fun) do
:maps.fold(fn k, v, acc -> fun.({k, v}, acc) end, acc, collection)
end
def reduce(collection, acc, fun) do
Enumerable.reduce(collection, {:cont, acc},
fn x, acc -> {:cont, fun.(x, acc)} end) |> elem(1)
end
@doc """
Invokes `fun` for each element in the collection passing that element and the
accumulator `acc` as arguments. `fun`'s return value is stored in `acc`.
The first element of the collection is used as the initial value of `acc`.
If you wish to use another value for `acc`, use `Enumerable.reduce/3`.
This function won't call the specified function for enumerables that are 1-element long.
Returns the accumulator.
Note that since the first element of the enumerable is used as the initial
value of the accumulator, `fun` will only be executed `n - 1` times where `n`
is the length of the enumerable.
## Examples
iex> Enum.reduce([1, 2, 3, 4], fn(x, acc) -> x * acc end)
24
"""
@spec reduce(t, (element, any -> any)) :: any
def reduce([h|t], fun) do
reduce(t, h, fun)
end
def reduce([], _fun) do
raise Enum.EmptyError
end
def reduce(collection, fun) do
result =
Enumerable.reduce(collection, {:cont, :first}, fn
x, :first ->
{:cont, {:acc, x}}
x, {:acc, acc} ->
{:cont, {:acc, fun.(x, acc)}}
end) |> elem(1)
case result do
:first -> raise Enum.EmptyError
{:acc, acc} -> acc
end
end
@doc """
Reduces the collection until halt is emitted.
The return value for `fun` is expected to be
`{:cont, acc}`, return `{:halt, acc}` to end the reduction early.
Returns the accumulator.
## Examples
iex> Enum.reduce_while(1..100, 0, fn i, acc ->
...> if i < 3, do: {:cont, acc + i}, else: {:halt, acc}
...> end)
3
"""
def reduce_while(collection, acc, fun) do
Enumerable.reduce(collection, {:cont, acc}, fun) |> elem(1)
end
@doc """
Returns elements of collection for which `fun` returns `false` or `nil`.
## Examples
iex> Enum.reject([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)
[1, 3]
"""
@spec reject(t, (element -> as_boolean(term))) :: list
def reject(collection, fun) when is_list(collection) do
for item <- collection, !fun.(item), do: item
end
def reject(collection, fun) do
reduce(collection, [], R.reject(fun)) |> :lists.reverse
end
@doc """
Reverses the collection.
## Examples
iex> Enum.reverse([1, 2, 3])
[3, 2, 1]
"""
@spec reverse(t) :: list
def reverse(collection) when is_list(collection) do
:lists.reverse(collection)
end
def reverse(collection) do
reverse(collection, [])
end
@doc """
Reverses the collection and appends the tail.
This is an optimization for
`Enum.concat(Enum.reverse(collection), tail)`.
## Examples
iex> Enum.reverse([1, 2, 3], [4, 5, 6])
[3, 2, 1, 4, 5, 6]
"""
@spec reverse(t, t) :: list
def reverse(collection, tail) when is_list(collection) and is_list(tail) do
:lists.reverse(collection, tail)
end
def reverse(collection, tail) do
reduce(collection, to_list(tail), fn(entry, acc) ->
[entry|acc]
end)
end
@doc """
Reverses the collection in the range from initial position `first`
through `count` elements. If `count` is greater than the size of
the rest of the collection, then this function will reverse the rest
of the collection.
## Examples
iex> Enum.reverse_slice([1, 2, 3, 4, 5, 6], 2, 4)
[1, 2, 6, 5, 4, 3]
"""
@spec reverse_slice(t, non_neg_integer, non_neg_integer) :: list
def reverse_slice(collection, start, count) when start >= 0 and count >= 0 do
list = reverse(collection)
length = length(list)
count = Kernel.min(count, length - start)
if count > 0 do
reverse_slice(list, length, start + count, count, [])
else
:lists.reverse(list)
end
end
@doc """
Returns a random element of a collection.
Raises `EmptyError` if the collection is empty.
Notice that you need to explicitly call `:random.seed/1` and
set a seed value for the random algorithm. Otherwise, the
default seed will be set which will always return the same
result. For example, one could do the following to set a seed
dynamically:
:random.seed(:os.timestamp)
The implementation is based on the
[reservoir sampling](https://en.wikipedia.org/wiki/Reservoir_sampling#Relation_to_Fisher-Yates_shuffle)
algorithm.
It assumes that the sample being returned can fit into memory;
the input collection doesn't have to - it is traversed just once.
## Examples
iex> Enum.random([1, 2, 3])
1
iex> Enum.random([1, 2, 3])
2
"""
@spec random(t) :: element
def random(collection) do
case take_random(collection, 1) do
[] -> raise Enum.EmptyError
[e] -> e
end
end
@doc """
Applies the given function to each element in the collection,
storing the result in a list and passing it as the accumulator
for the next computation.
## Examples
iex> Enum.scan(1..5, &(&1 + &2))
[1, 3, 6, 10, 15]
"""
@spec scan(t, (element, any -> any)) :: list
def scan(enum, fun) do
{res, _} = reduce(enum, {[], :first}, R.scan_2(fun))
:lists.reverse(res)
end
@doc """
Applies the given function to each element in the collection,
storing the result in a list and passing it as the accumulator
for the next computation. Uses the given `acc` as the starting value.
## Examples
iex> Enum.scan(1..5, 0, &(&1 + &2))
[1, 3, 6, 10, 15]
"""
@spec scan(t, any, (element, any -> any)) :: list
def scan(enum, acc, fun) do
{res, _} = reduce(enum, {[], acc}, R.scan_3(fun))
:lists.reverse(res)
end
@doc """
Returns a list of collection elements shuffled.
Notice that you need to explicitly call `:random.seed/1` and
set a seed value for the random algorithm. Otherwise, the
default seed will be set which will always return the same
result. For example, one could do the following to set a seed
dynamically:
:random.seed(:os.timestamp)
## Examples
iex> Enum.shuffle([1, 2, 3])
[3, 2, 1]
iex> Enum.shuffle([1, 2, 3])
[3, 1, 2]
"""
@spec shuffle(t) :: list
def shuffle(collection) do
randomized = reduce(collection, [], fn x, acc ->
[{:random.uniform, x}|acc]
end)
unwrap(:lists.keysort(1, randomized), [])
end
@doc """
Returns a subset list of the given collection. Drops elements
until element position `start`, then takes `count` elements.
If the count is greater than collection length, it returns as
much as possible. If zero, then it returns `[]`.
## Examples
iex> Enum.slice(1..100, 5, 10)
[6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
iex> Enum.slice(1..10, 5, 100)
[6, 7, 8, 9, 10]
iex> Enum.slice(1..10, 5, 0)
[]
"""
@spec slice(t, integer, non_neg_integer) :: list
def slice(_collection, start, 0) when is_integer(start), do: []
def slice(collection, start, count) when is_integer(start) and start < 0 and is_integer(count) and count >= 0 do
{list, new_start} = enumerate_and_count(collection, start)
if new_start >= 0 do
slice(list, new_start, count)
else
[]
end
end
def slice(collection, start, count) when is_list(collection) and is_integer(start) and start >= 0 and is_integer(count) and count > 0 do
do_slice(collection, start, count)
end
def slice(collection, start, count) when is_integer(start) and start >= 0 and is_integer(count) and count > 0 do
{_, _, list} = Enumerable.reduce(collection, {:cont, {start, count, []}}, fn
_entry, {start, count, _list} when start > 0 ->
{:cont, {start-1, count, []}}
entry, {start, count, list} when count > 1 ->
{:cont, {start, count-1, [entry|list]}}
entry, {start, count, list} ->
{:halt, {start, count, [entry|list]}}
end) |> elem(1)
:lists.reverse(list)
end
@doc """
Returns a subset list of the given collection. Drops elements
until element position `range.first`, then takes elements until element
position `range.last` (inclusive).
Positions are calculated by adding the number of items in the collection to
negative positions (so position -3 in a collection with count 5 becomes
position 2).
The first position (after adding count to negative positions) must be smaller
or equal to the last position.
If the start of the range is not a valid offset for the given
collection or if the range is in reverse order, returns `[]`.
## Examples
iex> Enum.slice(1..100, 5..10)
[6, 7, 8, 9, 10, 11]
iex> Enum.slice(1..10, 5..20)
[6, 7, 8, 9, 10]
iex> Enum.slice(1..10, 11..20)
[]
iex> Enum.slice(1..10, 6..5)
[]
"""
@spec slice(t, Range.t) :: list
def slice(collection, range)
def slice(collection, first..last) when is_integer(first) and first >= 0 and is_integer(last) and last >= 0 do
# Simple case, which works on infinite collections
if last - first >= 0 do
slice(collection, first, last - first + 1)
else
[]
end
end
def slice(collection, first..last) when is_integer(first) and is_integer(last) do
{list, count} = enumerate_and_count(collection, 0)
corr_first = if first >= 0, do: first, else: first + count
corr_last = if last >= 0, do: last, else: last + count
length = corr_last - corr_first + 1
if corr_first >= 0 and length > 0 do
slice(list, corr_first, length)
else
[]
end
end
@doc """
Sorts the collection according to Elixir's term ordering.
Uses the merge sort algorithm.
## Examples
iex> Enum.sort([3, 2, 1])
[1, 2, 3]
"""
@spec sort(t) :: list
def sort(collection) when is_list(collection) do
:lists.sort(collection)
end
def sort(collection) do
sort(collection, &(&1 <= &2))
end
@doc """
Sorts the collection by the given function.
This function uses the merge sort algorithm. The given function
must return `false` if the first argument is less than right one.
## Examples
iex> Enum.sort([1, 2, 3], &(&1 > &2))
[3, 2, 1]
The sorting algorithm will be stable as long as the given function
returns `true` for values considered equal:
iex> Enum.sort ["some", "kind", "of", "monster"], &(byte_size(&1) <= byte_size(&2))
["of", "some", "kind", "monster"]
If the function does not return `true` for equal values, the sorting is not stable and
the order of equal terms may be shuffled:
iex> Enum.sort ["some", "kind", "of", "monster"], &(byte_size(&1) < byte_size(&2))
["of", "kind", "some", "monster"]
"""
@spec sort(t, (element, element -> boolean)) :: list
def sort(collection, fun) when is_list(collection) do
:lists.sort(fun, collection)
end
def sort(collection, fun) do
reduce(collection, [], &sort_reducer(&1, &2, fun)) |> sort_terminator(fun)
end
@doc """
Sorts the mapped results of the `collection` according to the `sorter` function.
This function maps each element of the collection using the `mapper`
function. The collection is then sorted by the mapped elements using the
`sorter` function, which defaults to `<=/2`
`sort_by/3` differs from `sort/2` in that it only calculates the comparison
value for each element in the collection once instead of once for each
element in each comparison. If the same function is being called on both
element, it's also more compact to use `sort_by/3`.
This technique is also known as a
[Schwartzian Transform](https://en.wikipedia.org/wiki/Schwartzian_transform),
or the Lisp decorate-sort-undecorate idiom as the `mapper` is decorating the
original `collection`, then `sorter` is sorting the decorations, and finally
the `collection` is being undecorated so only the original elements remain,
but now in sorted order.
## Examples
Using the default `sorter` of `<=/2`:
iex> Enum.sort_by ["some", "kind", "of", "monster"], &byte_size/1
["of", "some", "kind", "monster"]
Using a custom `sorter` to override the order:
iex> Enum.sort_by ["some", "kind", "of", "monster"], &byte_size/1, &>=/2
["monster", "some", "kind", "of"]
"""
@spec sort_by(t, (element -> mapped_element), (mapped_element, mapped_element -> boolean)) :: list when mapped_element: element
def sort_by(collection, mapper, sorter \\ &<=/2) do
collection
|> map(&{&1, mapper.(&1)})
|> sort(&sorter.(elem(&1, 1), elem(&2, 1)))
|> map(&elem(&1, 0))
end
@doc """
Splits the enumerable into two collections, leaving `count`
elements in the first one. If `count` is a negative number,
it starts counting from the back to the beginning of the
collection.
Be aware that a negative `count` implies the collection
will be enumerated twice: once to calculate the position, and
a second time to do the actual splitting.
## Examples
iex> Enum.split([1, 2, 3], 2)
{[1, 2], [3]}
iex> Enum.split([1, 2, 3], 10)
{[1, 2, 3], []}
iex> Enum.split([1, 2, 3], 0)
{[], [1, 2, 3]}
iex> Enum.split([1, 2, 3], -1)
{[1, 2], [3]}
iex> Enum.split([1, 2, 3], -5)
{[], [1, 2, 3]}
"""
@spec split(t, integer) :: {list, list}
def split(collection, count) when is_list(collection) and count >= 0 do
do_split(collection, count, [])
end
def split(collection, count) when count >= 0 do
{_, list1, list2} =
reduce(collection, {count, [], []}, fn(entry, {counter, acc1, acc2}) ->
if counter > 0 do
{counter - 1, [entry|acc1], acc2}
else
{counter, acc1, [entry|acc2]}
end
end)
{:lists.reverse(list1), :lists.reverse(list2)}
end
def split(collection, count) when count < 0 do
do_split_reverse(reverse(collection), abs(count), [])
end
@doc """
Splits `collection` in two at the position of the element for which `fun` returns `false` for the
first time.
## Examples
iex> Enum.split_while([1, 2, 3, 4], fn(x) -> x < 3 end)
{[1, 2], [3, 4]}
"""
@spec split_while(t, (element -> as_boolean(term))) :: {list, list}
def split_while(collection, fun) when is_list(collection) do
do_split_while(collection, fun, [])
end
def split_while(collection, fun) do
{list1, list2} =
reduce(collection, {[], []}, fn
entry, {acc1, []} ->
if(fun.(entry), do: {[entry|acc1], []}, else: {acc1, [entry]})
entry, {acc1, acc2} ->
{acc1, [entry|acc2]}
end)
{:lists.reverse(list1), :lists.reverse(list2)}
end
@doc """
Takes the first `count` items from the collection.
`count` must be an integer. If a negative `count` is given, the last `count` values will
be taken. For such, the collection is fully enumerated keeping up
to `2 * count` elements in memory. Once the end of the collection is
reached, the last `count` elements are returned.
## Examples
iex> Enum.take([1, 2, 3], 2)
[1, 2]
iex> Enum.take([1, 2, 3], 10)
[1, 2, 3]
iex> Enum.take([1, 2, 3], 0)
[]
iex> Enum.take([1, 2, 3], -1)
[3]
"""
@spec take(t, integer) :: list
def take(_collection, 0), do: []
def take([], _count), do: []
def take(collection, count) when is_list(collection) and is_integer(count) and count > 0 do
do_take(collection, count)
end
def take(collection, count) when is_integer(count) and count > 0 do
{_, {res, _}} =
Enumerable.reduce(collection, {:cont, {[], count}}, fn(entry, {list, n}) ->
case n do
0 -> {:halt, {list, n}}
1 -> {:halt, {[entry|list], n - 1}}
_ -> {:cont, {[entry|list], n - 1}}
end
end)
:lists.reverse(res)
end
def take(collection, count) when is_integer(count) and count < 0 do
count = abs(count)
{_count, buf1, buf2} =
reduce(collection, {0, [], []}, fn entry, {n, buf1, buf2} ->
buf1 = [entry|buf1]
n = n + 1
if n == count do
{0, [], buf1}
else
{n, buf1, buf2}
end
end)
do_take_last(buf1, buf2, count, [])
end
defp do_take_last(_buf1, _buf2, 0, acc),
do: acc
defp do_take_last([], [], _, acc),
do: acc
defp do_take_last([], [h|t], count, acc),
do: do_take_last([], t, count-1, [h|acc])
defp do_take_last([h|t], buf2, count, acc),
do: do_take_last(t, buf2, count-1, [h|acc])
@doc """
Returns a collection of every `nth` item in the collection,
starting with the first element.
The first item is always included, unless `nth` is 0.
The second argument specifying every `nth` item must be a non-negative integer,
otherwise `FunctionClauseError` will be thrown.
## Examples
iex> Enum.take_every(1..10, 2)
[1, 3, 5, 7, 9]
iex> Enum.take_every(1..10, 0)
[]
iex> Enum.take_every([1, 2, 3], 1)
[1, 2, 3]
"""
@spec take_every(t, non_neg_integer) :: list
def take_every(collection, 1), do: to_list(collection)
def take_every(_collection, 0), do: []
def take_every([], _nth), do: []
def take_every(collection, nth) when is_integer(nth) and nth > 0 do
{res, _} = reduce(collection, {[], :first}, R.take_every(nth))
:lists.reverse(res)
end
@doc """
Takes random items from a collection.
Notice this function will traverse the whole collection to
get the random sublist of collection. If you want the random
number between two integers, the best option is to use the
`:random` module.
See `random/1` for notes on implementation and random seed.
## Examples
iex> Enum.take_random(1..10, 2)
[1, 5]
iex> Enum.take_random(?a..?z, 5)
'tfesm'
"""
@spec take_random(t, integer) :: list
def take_random(_collection, 0), do: []
if :erlang.system_info(:otp_release) >= '18' do
def take_random(collection, count) when count > 128 do
reducer = fn(elem, {idx, sample}) ->
jdx = random_index(idx)
cond do
idx < count ->
value = Map.get(sample, jdx)
{idx + 1, Map.put(sample, idx, value) |> Map.put(jdx, elem)}
jdx < count ->
{idx + 1, Map.put(sample, jdx, elem)}
true ->
{idx + 1, sample}
end
end
{size, sample} = reduce(collection, {0, %{}}, reducer)
take_random(sample, Kernel.min(count, size), [])
end
end
def take_random(collection, count) when count > 0 do
sample = Tuple.duplicate(nil, count)
reducer = fn(elem, {idx, sample}) ->
jdx = random_index(idx)
cond do
idx < count ->
value = elem(sample, jdx)
{idx + 1, put_elem(sample, idx, value) |> put_elem(jdx, elem)}
jdx < count ->
{idx + 1, put_elem(sample, jdx, elem)}
true ->
{idx + 1, sample}
end
end
{size, sample} = reduce(collection, {0, sample}, reducer)
sample |> Tuple.to_list |> take(Kernel.min(count, size))
end
if :erlang.system_info(:otp_release) >= '18' do
defp take_random(_sample, 0, acc), do: acc
defp take_random(sample, position, acc) do
position = position - 1
acc = [Map.get(sample, position) | acc]
take_random(sample, position, acc)
end
end
@doc """
Takes the items from the beginning of `collection` while `fun` returns a truthy value.
## Examples
iex> Enum.take_while([1, 2, 3], fn(x) -> x < 3 end)
[1, 2]
"""
@spec take_while(t, (element -> as_boolean(term))) :: list
def take_while(collection, fun) when is_list(collection) do
do_take_while(collection, fun)
end
def take_while(collection, fun) do
{_, res} =
Enumerable.reduce(collection, {:cont, []}, fn(entry, acc) ->
if fun.(entry) do
{:cont, [entry|acc]}
else
{:halt, acc}
end
end)
:lists.reverse(res)
end
@doc """
Converts `collection` to a list.
## Examples
iex> Enum.to_list(1 .. 3)
[1, 2, 3]
"""
@spec to_list(t) :: [term]
def to_list(collection) when is_list(collection) do
collection
end
def to_list(collection) do
reverse(collection) |> :lists.reverse
end
@doc """
Enumerates the collection, removing all duplicated elements.
## Examples
iex> Enum.uniq([1, 2, 3, 3, 2, 1])
[1, 2, 3]
"""
@spec uniq(t) :: list
def uniq(collection) do
uniq_by(collection, fn x -> x end)
end
# TODO: Deprecate by 1.2
# TODO: Remove by 2.0
@doc false
def uniq(collection, fun) do
uniq_by(collection, fun)
end
@doc """
Enumerates the collection, removing all duplicated elements.
## Example
iex> Enum.uniq_by([{1, :x}, {2, :y}, {1, :z}], fn {x, _} -> x end)
[{1, :x}, {2, :y}]
"""
@spec uniq_by(t, (element -> term)) :: list
def uniq_by(collection, fun) when is_list(collection) do
do_uniq(collection, HashSet.new, fun)
end
def uniq_by(collection, fun) do
{list, _} = reduce(collection, {[], HashSet.new}, R.uniq(fun))
:lists.reverse(list)
end
@doc """
Opposite of `Enum.zip/2`; takes a list of two-element tuples and returns a
tuple with two lists, each of which is formed by the first and second element
of each tuple, respectively.
This function fails unless `collection` is or can be converted into a list of
tuples with *exactly* two elements in each tuple.
## Examples
iex> Enum.unzip([{:a, 1}, {:b, 2}, {:c, 3}])
{[:a, :b, :c], [1, 2, 3]}
iex> Enum.unzip(%{a: 1, b: 2})
{[:a, :b], [1, 2]}
"""
@spec unzip(t) :: {list(element), list(element)}
def unzip(collection) do
{list1, list2} = reduce(collection, {[], []}, fn({el1, el2}, {list1, list2}) ->
{[el1|list1], [el2|list2]}
end)
{:lists.reverse(list1), :lists.reverse(list2)}
end
@doc """
Zips corresponding elements from two collections into one list
of tuples.
The zipping finishes as soon as any enumerable completes.
## Examples
iex> Enum.zip([1, 2, 3], [:a, :b, :c])
[{1, :a}, {2, :b}, {3, :c}]
iex> Enum.zip([1, 2, 3, 4, 5], [:a, :b, :c])
[{1, :a}, {2, :b}, {3, :c}]
"""
@spec zip(t, t) :: [{any, any}]
def zip(collection1, collection2) when is_list(collection1) and is_list(collection2) do
do_zip(collection1, collection2)
end
def zip(collection1, collection2) do
Stream.zip(collection1, collection2).({:cont, []}, &{:cont, [&1|&2]}) |> elem(1) |> :lists.reverse
end
@doc """
Returns the collection with each element wrapped in a tuple
alongside its index.
## Examples
iex> Enum.with_index [1, 2, 3]
[{1, 0}, {2, 1}, {3, 2}]
"""
@spec with_index(t) :: list({element, non_neg_integer})
def with_index(collection) do
map_reduce(collection, 0, fn x, acc ->
{{x, acc}, acc + 1}
end) |> elem(0)
end
## Helpers
@compile {:inline, enum_to_string: 1}
defp enumerate_and_count(collection, count) when is_list(collection) do
{collection, length(collection) - abs(count)}
end
defp enumerate_and_count(collection, count) do
map_reduce(collection, -abs(count), fn(x, acc) -> {x, acc + 1} end)
end
defp enum_to_string(entry) when is_binary(entry), do: entry
defp enum_to_string(entry), do: String.Chars.to_string(entry)
defp random_index(n) do
:random.uniform(n + 1) - 1
end
## Implementations
## all?
defp do_all?([h|t], fun) do
if fun.(h) do
do_all?(t, fun)
else
false
end
end
defp do_all?([], _) do
true
end
## any?
defp do_any?([h|t], fun) do
if fun.(h) do
true
else
do_any?(t, fun)
end
end
defp do_any?([], _) do
false
end
## fetch
defp do_fetch([h|_], 0), do: {:ok, h}
defp do_fetch([_|t], n), do: do_fetch(t, n - 1)
defp do_fetch([], _), do: :error
## drop
defp do_drop([_|t], counter) when counter > 0 do
do_drop(t, counter - 1)
end
defp do_drop(list, 0) do
list
end
defp do_drop([], _) do
[]
end
## drop_while
defp do_drop_while([h|t], fun) do
if fun.(h) do
do_drop_while(t, fun)
else
[h|t]
end
end
defp do_drop_while([], _) do
[]
end
## find
defp do_find([h|t], ifnone, fun) do
if fun.(h) do
h
else
do_find(t, ifnone, fun)
end
end
defp do_find([], ifnone, _) do
ifnone
end
## find_index
defp do_find_index([h|t], counter, fun) do
if fun.(h) do
counter
else
do_find_index(t, counter + 1, fun)
end
end
defp do_find_index([], _, _) do
nil
end
## find_value
defp do_find_value([h|t], ifnone, fun) do
fun.(h) || do_find_value(t, ifnone, fun)
end
defp do_find_value([], ifnone, _) do
ifnone
end
## shuffle
defp unwrap([{_, h} | collection], t) do
unwrap(collection, [h|t])
end
defp unwrap([], t), do: t
## sort
defp sort_reducer(entry, {:split, y, x, r, rs, bool}, fun) do
cond do
fun.(y, entry) == bool ->
{:split, entry, y, [x|r], rs, bool}
fun.(x, entry) == bool ->
{:split, y, entry, [x|r], rs, bool}
r == [] ->
{:split, y, x, [entry], rs, bool}
true ->
{:pivot, y, x, r, rs, entry, bool}
end
end
defp sort_reducer(entry, {:pivot, y, x, r, rs, s, bool}, fun) do
cond do
fun.(y, entry) == bool ->
{:pivot, entry, y, [x | r], rs, s, bool}
fun.(x, entry) == bool ->
{:pivot, y, entry, [x | r], rs, s, bool}
fun.(s, entry) == bool ->
{:split, entry, s, [], [[y, x | r] | rs], bool}
true ->
{:split, s, entry, [], [[y, x | r] | rs], bool}
end
end
defp sort_reducer(entry, [x], fun) do
{:split, entry, x, [], [], fun.(x, entry)}
end
defp sort_reducer(entry, acc, _fun) do
[entry|acc]
end
defp sort_terminator({:split, y, x, r, rs, bool}, fun) do
sort_merge([[y, x | r] | rs], fun, bool)
end
defp sort_terminator({:pivot, y, x, r, rs, s, bool}, fun) do
sort_merge([[s], [y, x | r] | rs], fun, bool)
end
defp sort_terminator(acc, _fun) do
acc
end
defp sort_merge(list, fun, true), do:
reverse_sort_merge(list, [], fun, true)
defp sort_merge(list, fun, false), do:
sort_merge(list, [], fun, false)
defp sort_merge([t1, [h2 | t2] | l], acc, fun, true), do:
sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, false) | acc], fun, true)
defp sort_merge([[h2 | t2], t1 | l], acc, fun, false), do:
sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, false) | acc], fun, false)
defp sort_merge([l], [], _fun, _bool), do: l
defp sort_merge([l], acc, fun, bool), do:
reverse_sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)
defp sort_merge([], acc, fun, bool), do:
reverse_sort_merge(acc, [], fun, bool)
defp reverse_sort_merge([[h2 | t2], t1 | l], acc, fun, true), do:
reverse_sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, true) | acc], fun, true)
defp reverse_sort_merge([t1, [h2 | t2] | l], acc, fun, false), do:
reverse_sort_merge(l, [sort_merge_1(t1, h2, t2, [], fun, true) | acc], fun, false)
defp reverse_sort_merge([l], acc, fun, bool), do:
sort_merge([:lists.reverse(l, []) | acc], [], fun, bool)
defp reverse_sort_merge([], acc, fun, bool), do:
sort_merge(acc, [], fun, bool)
defp sort_merge_1([h1 | t1], h2, t2, m, fun, bool) do
if fun.(h1, h2) == bool do
sort_merge_2(h1, t1, t2, [h2 | m], fun, bool)
else
sort_merge_1(t1, h2, t2, [h1 | m], fun, bool)
end
end
defp sort_merge_1([], h2, t2, m, _fun, _bool), do:
:lists.reverse(t2, [h2 | m])
defp sort_merge_2(h1, t1, [h2 | t2], m, fun, bool) do
if fun.(h1, h2) == bool do
sort_merge_2(h1, t1, t2, [h2 | m], fun, bool)
else
sort_merge_1(t1, h2, t2, [h1 | m], fun, bool)
end
end
defp sort_merge_2(h1, t1, [], m, _fun, _bool), do:
:lists.reverse(t1, [h1 | m])
## reverse_slice
defp reverse_slice(rest, idx, idx, count, acc) do
{slice, rest} = head_slice(rest, count, [])
:lists.reverse(rest, :lists.reverse(slice, acc))
end
defp reverse_slice([elem | rest], idx, start, count, acc) do
reverse_slice(rest, idx - 1, start, count, [elem | acc])
end
defp head_slice(rest, 0, acc), do: {acc, rest}
defp head_slice([elem | rest], count, acc) do
head_slice(rest, count - 1, [elem | acc])
end
## split
defp do_split([h|t], counter, acc) when counter > 0 do
do_split(t, counter - 1, [h|acc])
end
defp do_split(list, 0, acc) do
{:lists.reverse(acc), list}
end
defp do_split([], _, acc) do
{:lists.reverse(acc), []}
end
defp do_split_reverse([h|t], counter, acc) when counter > 0 do
do_split_reverse(t, counter - 1, [h|acc])
end
defp do_split_reverse(list, 0, acc) do
{:lists.reverse(list), acc}
end
defp do_split_reverse([], _, acc) do
{[], acc}
end
## split_while
defp do_split_while([h|t], fun, acc) do
if fun.(h) do
do_split_while(t, fun, [h|acc])
else
{:lists.reverse(acc), [h|t]}
end
end
defp do_split_while([], _, acc) do
{:lists.reverse(acc), []}
end
## take
defp do_take([h|t], counter) when counter > 0 do
[h|do_take(t, counter - 1)]
end
defp do_take(_list, 0) do
[]
end
defp do_take([], _) do
[]
end
## take_while
defp do_take_while([h|t], fun) do
if fun.(h) do
[h|do_take_while(t, fun)]
else
[]
end
end
defp do_take_while([], _) do
[]
end
## uniq
defp do_uniq([h|t], acc, fun) do
fun_h = fun.(h)
if HashSet.member?(acc, fun_h) do
do_uniq(t, acc, fun)
else
[h|do_uniq(t, HashSet.put(acc, fun_h), fun)]
end
end
defp do_uniq([], _acc, _fun) do
[]
end
## zip
defp do_zip([h1|next1], [h2|next2]) do
[{h1, h2}|do_zip(next1, next2)]
end
defp do_zip(_, []), do: []
defp do_zip([], _), do: []
## slice
defp do_slice([], _start, _count) do
[]
end
defp do_slice(_list, _start, 0) do
[]
end
defp do_slice([h|t], 0, count) do
[h|do_slice(t, 0, count-1)]
end
defp do_slice([_|t], start, count) do
do_slice(t, start-1, count)
end
end
defimpl Enumerable, for: List do
def reduce(_, {:halt, acc}, _fun), do: {:halted, acc}
def reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &reduce(list, &1, fun)}
def reduce([], {:cont, acc}, _fun), do: {:done, acc}
def reduce([h|t], {:cont, acc}, fun), do: reduce(t, fun.(h, acc), fun)
def member?(_list, _value),
do: {:error, __MODULE__}
def count(_list),
do: {:error, __MODULE__}
end
defimpl Enumerable, for: Map do
def reduce(map, acc, fun) do
do_reduce(:maps.to_list(map), acc, fun)
end
defp do_reduce(_, {:halt, acc}, _fun), do: {:halted, acc}
defp do_reduce(list, {:suspend, acc}, fun), do: {:suspended, acc, &do_reduce(list, &1, fun)}
defp do_reduce([], {:cont, acc}, _fun), do: {:done, acc}
defp do_reduce([h|t], {:cont, acc}, fun), do: do_reduce(t, fun.(h, acc), fun)
def member?(map, {key, value}) do
{:ok, match?({:ok, ^value}, :maps.find(key, map))}
end
def member?(_map, _other) do
{:ok, false}
end
def count(map) do
{:ok, map_size(map)}
end
end
defimpl Enumerable, for: Function do
def reduce(function, acc, fun) when is_function(function, 2),
do: function.(acc, fun)
def member?(_function, _value),
do: {:error, __MODULE__}
def count(_function),
do: {:error, __MODULE__}
end
| 25.87037 | 138 | 0.601084 |
79a173be76e2b6202ea9743a088a3ce3bbd518d9 | 594 | ex | Elixir | test/support/test_migration.ex | agleb/ecto_paginator | ec10b2cd717174a195adaf852f29467d1c959757 | [
"MIT"
] | 4 | 2020-02-15T01:35:44.000Z | 2020-06-24T19:26:52.000Z | test/support/test_migration.ex | agleb/ecto_paginator | ec10b2cd717174a195adaf852f29467d1c959757 | [
"MIT"
] | null | null | null | test/support/test_migration.ex | agleb/ecto_paginator | ec10b2cd717174a195adaf852f29467d1c959757 | [
"MIT"
] | null | null | null | defmodule EctoPaginator.TestMigration do
use Ecto.Migration
def change do
create table(:customers) do
add(:name, :string)
add(:active, :boolean)
timestamps()
end
create table(:payments) do
add(:description, :text)
add(:charged_at, :utc_datetime)
add(:amount, :integer)
add(:status, :string)
add(:customer_id, references(:customers))
timestamps()
end
create table(:addresses, primary_key: false) do
add(:city, :string, primary_key: true)
add(:customer_id, references(:customers))
end
end
end
| 19.8 | 51 | 0.63468 |
79a1985b173481fdcf75a2d1740cb371ebb9dbb5 | 1,877 | ex | Elixir | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2beta1_knowledge_answers.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2beta1_knowledge_answers.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2beta1_knowledge_answers.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2021-03-04T13:43:47.000Z | 2021-03-04T13:43:47.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.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1KnowledgeAnswers do
@moduledoc """
Represents the result of querying a Knowledge base.
## Attributes
* `answers` (*type:* `list(GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1KnowledgeAnswersAnswer.t)`, *default:* `nil`) - A list of answers from Knowledge Connector.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:answers =>
list(
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1KnowledgeAnswersAnswer.t()
)
}
field(:answers,
as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1KnowledgeAnswersAnswer,
type: :list
)
end
defimpl Poison.Decoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1KnowledgeAnswers do
def decode(value, options) do
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1KnowledgeAnswers.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1KnowledgeAnswers do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.362069 | 180 | 0.748535 |
79a19cf2e30029617f4342b71499be721c59f280 | 1,286 | ex | Elixir | clients/iam/lib/google_api/iam/v1/model/expr.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/iam/lib/google_api/iam/v1/model/expr.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/iam/lib/google_api/iam/v1/model/expr.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.IAM.V1.Model.Expr do
@moduledoc """
Represents an expression text. Example: title: \"User account presence\" description: \"Determines whether the request has a user account\" expression: \"size(request.user) > 0\"
"""
@derive [Poison.Encoder]
defstruct [
:"description",
:"expression",
:"location",
:"title"
]
end
defimpl Poison.Decoder, for: GoogleApi.IAM.V1.Model.Expr do
def decode(value, _options) do
value
end
end
| 32.15 | 226 | 0.725505 |
79a1ec5cab570ccc8b544713182027fdf129e17f | 7,781 | ex | Elixir | lib/celery/compiler.ex | bahanni/custom_rpi4 | ddefa85d30bacaae40151a63a9a0ebbf4ad30ed5 | [
"MIT"
] | null | null | null | lib/celery/compiler.ex | bahanni/custom_rpi4 | ddefa85d30bacaae40151a63a9a0ebbf4ad30ed5 | [
"MIT"
] | null | null | null | lib/celery/compiler.ex | bahanni/custom_rpi4 | ddefa85d30bacaae40151a63a9a0ebbf4ad30ed5 | [
"MIT"
] | null | null | null | defmodule FarmbotOS.Celery.Compiler do
@moduledoc """
Responsible for compiling canonical CeleryScript AST into
Elixir AST.
"""
require Logger
alias FarmbotOS.Celery.{AST, Compiler}
@doc "Returns current debug mode value"
def debug_mode?() do
# Set this to `true` when debuging.
false
end
@typedoc """
Compiled CeleryScript node should compile to an anon function.
Entrypoint nodes such as
* `rpc_request`
* `sequence`
will compile to a function that takes a Keyword list of variables. This function
needs to be executed before scheduling/executing.
Non entrypoint nodes compile to a function that symbolizes one individual step.
## Examples
`rpc_request` will be compiled to something like:
```
fn ->
[
# Body of the `rpc_request` compiled in here.
]
end
```
as compared to a "simple" node like `wait` will compile to something like:
```
fn() -> wait(200) end
```
"""
@type compiled :: (Keyword.t() -> [(() -> any())]) | (() -> any())
@doc """
Recursive function that will emit Elixir AST from CeleryScript AST.
"""
def compile(%AST{kind: :abort}, _cs_scope) do
fn -> {:error, "aborted"} end
end
# Every @valid_entry_point has its own compiler, but there is some
# common logic involved in the compilation of both, therefore,
# we need a common entrypoint for both.
def compile(%AST{} = ast, cs_scope) do
if cs_scope.valid do
ast
|> celery_to_elixir(cs_scope)
|> print_compiled_code()
else
{:error, "Exiting command because of errors."}
end
end
defdelegate assertion(ast, cs_scope), to: Compiler.Assertion
defdelegate calibrate(ast, cs_scope), to: Compiler.AxisControl
defdelegate coordinate(ast, cs_scope), to: Compiler.DataControl
defdelegate execute_script(ast, cs_scope), to: Compiler.Farmware
defdelegate execute(ast, cs_scope), to: Compiler.Execute
defdelegate find_home(ast, cs_scope), to: Compiler.AxisControl
defdelegate home(ast, cs_scope), to: Compiler.AxisControl
defdelegate lua(ast, cs_scope), to: Compiler.Lua
defdelegate move_absolute(ast, cs_scope), to: Compiler.AxisControl
defdelegate move_relative(ast, cs_scope), to: Compiler.AxisControl
defdelegate move(ast, cs_scope), to: Compiler.Move
defdelegate named_pin(ast, cs_scope), to: Compiler.DataControl
defdelegate point(ast, cs_scope), to: Compiler.DataControl
defdelegate read_pin(ast, cs_scope), to: Compiler.PinControl
defdelegate rpc_request(ast, cs_scope), to: Compiler.RPCRequest
defdelegate sequence(ast, cs_scope), to: Compiler.Sequence
defdelegate set_pin_io_mode(ast, cs_scope), to: Compiler.PinControl
defdelegate set_servo_angle(ast, cs_scope), to: Compiler.PinControl
defdelegate set_user_env(ast, cs_scope), to: Compiler.Farmware
defdelegate take_photo(ast, cs_scope), to: Compiler.Farmware
defdelegate toggle_pin(ast, cs_scope), to: Compiler.PinControl
defdelegate tool(ast, cs_scope), to: Compiler.DataControl
defdelegate unquote(:_if)(ast, cs_scope), to: Compiler.If
defdelegate update_resource(ast, cs_scope), to: Compiler.UpdateResource
# defdelegate variable_declaration(ast, cs_scope), to: Compiler.VariableDeclaration
defdelegate write_pin(ast, cs_scope), to: Compiler.PinControl
defdelegate zero(ast, cs_scope), to: Compiler.AxisControl
def celery_to_elixir(ast_or_literal, _cs_scope)
def celery_to_elixir(%AST{kind: kind} = ast, cs_scope) do
if function_exported?(__MODULE__, kind, 2),
do: apply(__MODULE__, kind, [ast, cs_scope]),
else: raise("no compiler for #{kind}")
end
def celery_to_elixir(lit, _cs_scope) when is_number(lit), do: lit
def celery_to_elixir(lit, _cs_scope) when is_binary(lit), do: lit
def nothing(_ast, _cs_scope) do
quote location: :keep do
FarmbotOS.Celery.SysCallGlue.nothing()
end
end
def abort(_ast, _cs_scope) do
quote location: :keep do
Macro.escape({:error, "aborted"})
end
end
def wait(%{args: %{milliseconds: millis}}, cs_scope) do
quote location: :keep do
with millis when is_integer(millis) <-
unquote(celery_to_elixir(millis, cs_scope)) do
FarmbotOS.Celery.SysCallGlue.log("Waiting for #{millis} milliseconds")
FarmbotOS.Celery.SysCallGlue.wait(millis)
else
{:error, reason} ->
{:error, reason}
end
end
end
def send_message(args, cs_scope) do
%{args: %{message: msg, message_type: type}, body: channels} = args
# body gets turned into a list of atoms.
# Example:
# [{kind: "channel", args: {channel_name: "email"}}]
# is turned into:
# [:email]
channels =
Enum.map(channels, fn %{
kind: :channel,
args: %{channel_name: channel_name}
} ->
String.to_atom(channel_name)
end)
quote location: :keep do
FarmbotOS.Celery.SysCallGlue.send_message(
unquote(celery_to_elixir(type, cs_scope)),
unquote(celery_to_elixir(msg, cs_scope)),
unquote(channels)
)
end
end
def identifier(%{args: %{label: var_name}}, _cs_scope) do
quote location: :keep do
{:ok, var} =
FarmbotOS.Celery.Compiler.Scope.fetch!(cs_scope, unquote(var_name))
var
end
end
def emergency_lock(_, _cs_scope) do
quote location: :keep do
FarmbotOS.Celery.SysCallGlue.emergency_lock()
end
end
def emergency_unlock(_, _cs_scope) do
quote location: :keep do
FarmbotOS.Celery.SysCallGlue.emergency_unlock()
end
end
def read_status(_, _cs_scope) do
quote location: :keep do
FarmbotOS.Celery.SysCallGlue.read_status()
end
end
def sync(_, _cs_scope) do
quote location: :keep do
FarmbotOS.Celery.SysCallGlue.sync()
end
end
def check_updates(_, _cs_scope) do
quote location: :keep do
FarmbotOS.Celery.SysCallGlue.check_update()
end
end
def flash_firmware(%{args: %{package: package_name}}, cs_scope) do
quote location: :keep do
FarmbotOS.Celery.SysCallGlue.flash_firmware(
unquote(celery_to_elixir(package_name, cs_scope))
)
end
end
def power_off(_, _cs_scope) do
quote location: :keep do
FarmbotOS.Celery.SysCallGlue.power_off()
end
end
def reboot(%{args: %{package: "farmbot_os"}}, _cs_scope) do
quote location: :keep do
FarmbotOS.Celery.SysCallGlue.reboot()
end
end
def reboot(%{args: %{package: "arduino_firmware"}}, _cs_scope) do
quote location: :keep do
FarmbotOS.Celery.SysCallGlue.firmware_reboot()
end
end
def factory_reset(%{args: %{package: package}}, cs_scope) do
quote location: :keep do
FarmbotOS.Celery.SysCallGlue.factory_reset(
unquote(celery_to_elixir(package, cs_scope))
)
end
end
def change_ownership(%{body: body}, cs_scope) do
pairs =
Map.new(body, fn %{args: %{label: label, value: value}} ->
{label, value}
end)
email = Map.fetch!(pairs, "email")
secret =
Map.fetch!(pairs, "secret")
|> Base.decode64!(padding: false, ignore: :whitespace)
server = Map.get(pairs, "server")
quote location: :keep do
FarmbotOS.SysCalls.ChangeOwnership.change_ownership(
unquote(celery_to_elixir(email, cs_scope)),
unquote(celery_to_elixir(secret, cs_scope)),
unquote(celery_to_elixir(server, cs_scope))
)
end
end
# Uncomment these lines if you
# need to inspect CeleryScript issue
defp print_compiled_code(compiled) do
# IO.puts("# === START ===")
# compiled
# |> Macro.to_string()
# |> Code.format_string!()
# |> IO.puts()
# IO.puts("# === END ===\n\n")
compiled
end
end
| 29.812261 | 85 | 0.676777 |
79a1f2577a54dc5ea3c885a3375dcec4e09d0afc | 928 | ex | Elixir | apps/ewallet_api/lib/ewallet_api/v1/serializers/json/transaction_request_serializer.ex | turbo-play/ewallet | b7fee3eed62ac716f46246132c2ead1045f2e4f3 | [
"Apache-2.0"
] | 2 | 2019-07-13T05:49:03.000Z | 2021-08-19T23:58:23.000Z | apps/ewallet_api/lib/ewallet_api/v1/serializers/json/transaction_request_serializer.ex | turbo-play/ewallet | b7fee3eed62ac716f46246132c2ead1045f2e4f3 | [
"Apache-2.0"
] | null | null | null | apps/ewallet_api/lib/ewallet_api/v1/serializers/json/transaction_request_serializer.ex | turbo-play/ewallet | b7fee3eed62ac716f46246132c2ead1045f2e4f3 | [
"Apache-2.0"
] | 3 | 2018-05-08T17:15:42.000Z | 2021-11-10T04:08:33.000Z | defmodule EWalletAPI.V1.JSON.TransactionRequestSerializer do
@moduledoc """
Serializes transaction request data into V1 JSON response format.
"""
use EWalletAPI.V1
alias EWalletAPI.V1.JSON.MintedTokenSerializer
alias EWallet.Web.Date
def serialize(transaction_request) do
%{
object: "transaction_request",
id: transaction_request.id,
type: transaction_request.type,
minted_token: MintedTokenSerializer.serialize(transaction_request.minted_token),
amount: transaction_request.amount,
address: transaction_request.balance_address,
user_id: transaction_request.user_id,
account_id: transaction_request.account_id,
correlation_id: transaction_request.correlation_id,
status: transaction_request.status,
created_at: Date.to_iso8601(transaction_request.inserted_at),
updated_at: Date.to_iso8601(transaction_request.updated_at)
}
end
end
| 35.692308 | 86 | 0.767241 |
79a207ce9281ce215dcbdc391b195f5a76f0101c | 67 | exs | Elixir | test/find_type_test.exs | JoeBanks13/find_type | 131ce226ca9afb9d724f06d40e390613ba1c8157 | [
"MIT"
] | null | null | null | test/find_type_test.exs | JoeBanks13/find_type | 131ce226ca9afb9d724f06d40e390613ba1c8157 | [
"MIT"
] | null | null | null | test/find_type_test.exs | JoeBanks13/find_type | 131ce226ca9afb9d724f06d40e390613ba1c8157 | [
"MIT"
] | null | null | null | defmodule FindTypeTest do
use ExUnit.Case
doctest FindType
end
| 13.4 | 25 | 0.80597 |
79a2244ee5332a3ae9f5ba0783fd5639d3e5fbc0 | 5,508 | ex | Elixir | lib/brando/authorization/authorization.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 4 | 2020-10-30T08:40:38.000Z | 2022-01-07T22:21:37.000Z | lib/brando/authorization/authorization.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 1,162 | 2020-07-05T11:20:15.000Z | 2022-03-31T06:01:49.000Z | lib/brando/authorization/authorization.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | null | null | null | defmodule Brando.Authorization do
@moduledoc """
## Example
use Brando.Authorization
types [
{"User", Brando.Users.User},
{"Page", Brando.Pages.Page},
{"Fragment", Brando.Pages.Fragment}
]
rules :superuser do
can :manage, :all
end
rules :admin do
can :manage, :all
cannot :manage, "User", %{role: "superuser"}
end
"""
alias Brando.Authorization.Rule
defmacro __using__(_) do
quote do
Module.register_attribute(__MODULE__, :rules, accumulate: true)
Module.register_attribute(__MODULE__, :types, accumulate: false)
import unquote(__MODULE__)
@before_compile unquote(__MODULE__)
def get_rules_for(role) do
role
|> __rules__()
|> Enum.map(
&unquote(__MODULE__).denormalize_subject(
&1,
__MODULE__.__types__(:atom_to_binary)
)
)
end
defmodule Can do
defmacro __using__(_) do
quote do
import unquote(__MODULE__)
end
end
@moduledoc """
can?(user, :delete, post)
{:ok, :authorized}
"""
@type user :: Brando.Users.User.t()
@authorization_module __MODULE__ |> Module.split() |> Enum.drop(-1) |> Module.concat()
@spec can?(user, atom, any) :: {:ok, :authorized} | {:error, :unauthorized}
def can?(%Brando.Users.User{} = user, action, subject) do
rules = @authorization_module.__rules__(user.role)
case Enum.reduce(
rules,
false,
&Brando.Authorization.Rule.test_rule(
&1,
action,
subject.__struct__,
subject,
&2
)
) do
true -> {:ok, :authorized}
false -> {:error, :unauthorized}
end
end
end
end
end
@doc false
defmacro __before_compile__(env) do
rules = Module.get_attribute(env.module, :rules)
types =
env.module
|> Module.get_attribute(:types)
|> Enum.into(%{})
types_reversed = Enum.into(types, %{}, &{elem(&1, 1), elem(&1, 0)})
[compile_types(types, types_reversed), compile_rules(rules, types, types_reversed)]
end
@doc false
def compile_types(types, types_reversed) do
quote do
def __types__(:binary_to_atom) do
unquote(Macro.escape(types))
end
def __types__(:atom_to_binary) do
unquote(Macro.escape(types_reversed))
end
end
end
# When we are dealing with rules inside Elixir, we want the subject stored as a
# module atom, whenever possible.
#
# So if subject is a binary -> "User", we look it up in our types map and return
# Brando.Users.User
#
# If the subject is a struct -> %Brando.Users.User, we grab the struct key (which
# is a module atom) and return Brando.Users.User
#
# If the subject is not found in the types map, we store it as a binary. This is
# useful for when we want to store rules that will only apply on the frontend,
# for instance a "MenuItem".
defp normalize_subject(%Rule{subject: :all} = rule, _, _), do: Map.put(rule, :subject, "all")
defp normalize_subject(%Rule{subject: subject} = rule, types, _) when is_binary(subject),
do: Map.put(rule, :subject, Map.get(types, subject, subject))
defp normalize_subject(%Rule{subject: subject} = rule, _, _) when is_map(subject),
do: Map.put(rule, :subject, subject.__struct__)
def denormalize_subject(%Rule{subject: subject} = rule, _) when is_binary(subject), do: rule
def denormalize_subject(%Rule{subject: subject} = rule, types) when is_atom(subject),
do: Map.put(rule, :subject, Map.get(types, subject))
@doc false
def compile_rules(rules, types, types_reversed) do
role_buckets =
rules
|> Keyword.keys()
|> Enum.map(&{&1, []})
|> Enum.into(%{})
reduced_rules =
Enum.reduce(rules, role_buckets, fn {role, rule}, acc ->
Map.put(acc, role, [normalize_subject(rule, types, types_reversed) | Map.get(acc, role)])
end)
for {role, rules_for_role} <- reduced_rules do
quote do
def __rules__(unquote(role)) do
unquote(Macro.escape(rules_for_role))
end
end
end
end
defmacro types(types) do
quote do
@types unquote(types)
end
end
defmacro rules(role, do: block) do
quote do
var!(role) = unquote(role)
unquote(block)
end
end
defmacro can(action, subject, opts \\ []) do
subject = (is_map(subject) && subject.__struct__) || subject
quote do
role = unquote(Macro.var(:role, nil))
action(
role,
unquote(action),
unquote(subject),
unquote(Keyword.get(opts, :when)),
false
)
end
end
defmacro cannot(action, subject, opts \\ []) do
quote do
role = unquote(Macro.var(:role, nil))
action(
role,
unquote(action),
unquote(subject),
unquote(Keyword.get(opts, :when)),
true
)
end
end
defmacro action(role, action, subject, conditions, inverted) do
quote do
rule = %Brando.Authorization.Rule{
action: unquote(action),
subject: unquote(subject),
conditions: unquote(conditions),
inverted: unquote(inverted)
}
@rules {unquote(role), rule}
end
end
end
| 25.981132 | 97 | 0.588962 |
79a23c934a4c194b5f0448a593247ce773db80bd | 62 | ex | Elixir | .env.ex | emamulandalib/redis-sentinal-docker | e0a18bf8a562ea653df492eb35b000c438e22ca8 | [
"MIT"
] | null | null | null | .env.ex | emamulandalib/redis-sentinal-docker | e0a18bf8a562ea653df492eb35b000c438e22ca8 | [
"MIT"
] | null | null | null | .env.ex | emamulandalib/redis-sentinal-docker | e0a18bf8a562ea653df492eb35b000c438e22ca8 | [
"MIT"
] | null | null | null | HOST_IP=
MASTER_PORT=6379
PASSWORD=secret
SENTINEL_NAME=master | 15.5 | 20 | 0.887097 |
79a256a8c9a8ce9094b8da9fce1e4f247b0bd734 | 661 | ex | Elixir | lib/codes/codes_r70.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_r70.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_r70.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_R70 do
alias IcdCode.ICDCode
def _R700 do
%ICDCode{full_code: "R700",
category_code: "R70",
short_code: "0",
full_name: "Elevated erythrocyte sedimentation rate",
short_name: "Elevated erythrocyte sedimentation rate",
category_name: "Elevated erythrocyte sedimentation rate"
}
end
def _R701 do
%ICDCode{full_code: "R701",
category_code: "R70",
short_code: "1",
full_name: "Abnormal plasma viscosity",
short_name: "Abnormal plasma viscosity",
category_name: "Abnormal plasma viscosity"
}
end
end
| 26.44 | 66 | 0.630862 |
79a2aed40f747d0ba9fa8c5270f8486dc7164e24 | 3,122 | ex | Elixir | lib/sdk/batch_sends.ex | edragonconnect/wechat_sdk | d1f08ec34937df8de2c31d472458c1682bf4db32 | [
"MIT"
] | 4 | 2020-06-05T09:30:59.000Z | 2021-05-08T11:35:22.000Z | lib/sdk/batch_sends.ex | edragonconnect/wechat_sdk | d1f08ec34937df8de2c31d472458c1682bf4db32 | [
"MIT"
] | null | null | null | lib/sdk/batch_sends.ex | edragonconnect/wechat_sdk | d1f08ec34937df8de2c31d472458c1682bf4db32 | [
"MIT"
] | 1 | 2020-06-05T16:05:27.000Z | 2020-06-05T16:05:27.000Z | defmodule WeChat.SDK.BatchSends do
@moduledoc """
消息管理 - 群发接口和原创效验
[API Docs Link](https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Batch_Sends_and_Originality_Checks.html){:target="_blank"}
"""
import Jason.Helpers
alias WeChat.SDK
@doc_link "#{SDK.doc_link_prefix()}/offiaccount/Message_Management/Batch_Sends_and_Originality_Checks.html"
@typedoc "消息发送任务的ID"
@type msg_id :: String.t()
@doc """
根据标签进行群发【订阅号与服务号认证后均可用】
## API Docs
[link](#{@doc_link}#2){:target="_blank"}
"""
@spec batch_send_by_tag(SDK.client(), body :: map) :: SDK.response()
def batch_send_by_tag(client, body) do
client.request(:post, url: "/cgi-bin/message/mass/sendall", body: body)
end
@doc """
根据OpenID列表群发【订阅号不可用,服务号认证后可用】
## API Docs
[link](#{@doc_link}#3){:target="_blank"}
"""
@spec batch_send_by_list(SDK.client(), body :: map) :: SDK.response()
def batch_send_by_list(client, body) do
client.request(:post, url: "/cgi-bin/message/mass/send", body: body)
end
@doc """
删除群发【订阅号与服务号认证后均可用】
群发之后,随时可以通过该接口删除群发。
## 请注意
1. 只有已经发送成功的消息才能删除
2. 删除消息是将消息的图文详情页失效,已经收到的用户,还是能在其本地看到消息卡片。
3. 删除群发消息只能删除图文消息和视频消息,其他类型的消息一经发送,无法删除。
4. 如果多次群发发送的是一个图文消息,那么删除其中一次群发,就会删除掉这个图文消息也,导致所有群发都失效
## API Docs
[link](#{@doc_link}#4){:target="_blank"}
"""
@spec delete(SDK.client(), msg_id, article_idx :: integer) :: SDK.response()
def delete(client, msg_id, article_idx \\ 0) do
client.request(:post,
url: "/cgi-bin/message/mass/delete",
body: json_map(msg_id: msg_id, article_idx: article_idx)
)
end
@doc """
预览接口【订阅号与服务号认证后均可用】
开发者可通过该接口发送消息给指定用户,在手机端查看消息的样式和排版。为了满足第三方平台开发者的需求,在保留对openID预览能力的同时,增加了对指定微信号发送预览的能力,但该能力每日调用次数有限制(100次),请勿滥用。
## API Docs
[link](#{@doc_link}#5){:target="_blank"}
"""
@spec preview(SDK.client(), body :: map) :: SDK.response()
def preview(client, body) do
client.request(:post, url: "/cgi-bin/message/mass/preview", body: body)
end
@doc """
查询群发消息发送状态【订阅号与服务号认证后均可用】
开发者可通过该接口发送消息给指定用户,在手机端查看消息的样式和排版。为了满足第三方平台开发者的需求,在保留对openID预览能力的同时,增加了对指定微信号发送预览的能力,但该能力每日调用次数有限制(100次),请勿滥用。
## API Docs
[link](#{@doc_link}#5){:target="_blank"}
"""
@spec get(SDK.client(), msg_id) :: SDK.response()
def get(client, msg_id) do
client.request(:post, url: "/cgi-bin/message/mass/get", body: json_map(msg_id: msg_id))
end
@doc """
群发速度 - 获取
## API Docs
[link](#{@doc_link}#9){:target="_blank"}
"""
@spec get_speed(SDK.client()) :: SDK.response()
def get_speed(client) do
client.request(:get, url: "/cgi-bin/message/mass/speed/get")
end
@doc """
群发速度 - 设置
群发速度的级别,是一个0到4的整数,数字越大表示群发速度越慢。
speed 与 realspeed 的关系如下:
| speed | realspeed |
| ----- | --------- |
| 0 | 80w/分钟 |
| 1 | 60w/分钟 |
| 2 | 45w/分钟 |
| 3 | 30w/分钟 |
| 4 | 10w/分钟 |
## API Docs
[link](#{@doc_link}#9){:target="_blank"}
"""
@spec set_speed(SDK.client(), speed :: integer) :: SDK.response()
def set_speed(client, speed) do
client.request(:post, url: "/cgi-bin/message/mass/speed/set", body: json_map(speed: speed))
end
end
| 26.016667 | 144 | 0.662396 |
79a2bcd86975dc22cad99e9a525d5e2f25373281 | 792 | exs | Elixir | spec/response/connect_spec.exs | rdalin82/pixie | add50e2bd7fbd807c7b82cd10a2123828be4c58f | [
"MIT"
] | null | null | null | spec/response/connect_spec.exs | rdalin82/pixie | add50e2bd7fbd807c7b82cd10a2123828be4c58f | [
"MIT"
] | null | null | null | spec/response/connect_spec.exs | rdalin82/pixie | add50e2bd7fbd807c7b82cd10a2123828be4c58f | [
"MIT"
] | null | null | null | defmodule PixieResponseConnectSpec do
use ESpec
let :message do
Pixie.Message.Connect.init %{
channel: "/meta/connect",
client_id: "abcd1234",
id: "efgh5678"
}
end
let :response do
Pixie.Response.Connect.init message
end
it "returns a Pixie.Response.Connect struct" do
expect(response.__struct__).to eq(Pixie.Response.Connect)
end
it "has correct client_id" do
expect(response.client_id).to eq("abcd1234")
end
it "has correct id" do
expect(response.id).to eq("efgh5678")
end
it "returns an ISO8601 timestamp" do
{ok, parsed} = Timex.DateFormat.parse(response.timestamp, "{ISO}")
expect(ok).to eq(:ok)
expect(parsed.__struct__).to eq(Timex.DateTime)
expect(parsed.year).to be :>=, 2015
end
end
| 22.628571 | 70 | 0.669192 |
79a2bed50edad29f218a9d0e96a11e8de60c5e44 | 1,065 | exs | Elixir | example/config/config.exs | menuan/kiosk_system_rpi3 | 6b28909454ee0219c8ba77b35f2ac60f41e86c54 | [
"Apache-2.0"
] | 60 | 2017-08-29T13:57:50.000Z | 2020-06-12T13:53:27.000Z | example/config/config.exs | menuan/kiosk_system_rpi3 | 6b28909454ee0219c8ba77b35f2ac60f41e86c54 | [
"Apache-2.0"
] | 36 | 2017-07-18T12:09:31.000Z | 2020-06-19T21:55:26.000Z | example/config/config.exs | menuan/kiosk_system_rpi3 | 6b28909454ee0219c8ba77b35f2ac60f41e86c54 | [
"Apache-2.0"
] | 17 | 2017-07-19T13:22:46.000Z | 2020-06-09T00:41:44.000Z | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
use Mix.Config
config :example, target: Mix.target()
# Customize non-Elixir parts of the firmware. See
# https://hexdocs.pm/nerves/advanced-configuration.html for details.
config :nerves, :firmware, rootfs_overlay: "rootfs_overlay"
# Set the SOURCE_DATE_EPOCH date for reproducible builds.
# See https://reproducible-builds.org/docs/source-date-epoch/ for more information
config :nerves, source_date_epoch: "1586221640"
# Use Ringlogger as the logger backend and remove :console.
# See https://hexdocs.pm/ring_logger/readme.html for more information on
# configuring ring_logger.
config :logger, backends: [RingLogger]
config :webengine_kiosk,
fullscreen: false,
background_color: "black",
progress: true,
sounds: true,
homepage: System.get_env("NERVES_KIOSK_URL")
if Mix.target() != :host do
import_config "target.exs"
end
| 29.583333 | 82 | 0.773709 |
79a2d8c0dd44348d0a1498378331e823834f0254 | 571 | ex | Elixir | lib/edgedb/protocol/types/dimension.ex | nsidnev/edgedb-elixir | bade2b9daba2e83bfaa5915b2addb74f41610968 | [
"MIT"
] | 30 | 2021-05-19T08:54:44.000Z | 2022-03-11T22:52:25.000Z | lib/edgedb/protocol/types/dimension.ex | nsidnev/edgedb-elixir | bade2b9daba2e83bfaa5915b2addb74f41610968 | [
"MIT"
] | 3 | 2021-11-17T21:26:01.000Z | 2022-03-12T09:49:25.000Z | lib/edgedb/protocol/types/dimension.ex | nsidnev/edgedb-elixir | bade2b9daba2e83bfaa5915b2addb74f41610968 | [
"MIT"
] | 3 | 2021-08-29T14:55:41.000Z | 2022-03-12T01:30:35.000Z | defmodule EdgeDB.Protocol.Types.Dimension do
use EdgeDB.Protocol.Type
alias EdgeDB.Protocol.Datatypes
@lower 1
deftype(
name: :dimension,
fields: [
upper: Datatypes.Int32.t(),
lower: Datatypes.Int32.t()
]
)
@impl EdgeDB.Protocol.Type
def encode_type(dimension(upper: upper)) do
[
Datatypes.Int32.encode(upper),
Datatypes.Int32.encode(@lower)
]
end
@impl EdgeDB.Protocol.Type
def decode_type(<<upper::int32, @lower::int32, rest::binary>>) do
{dimension(upper: upper, lower: @lower), rest}
end
end
| 19.689655 | 67 | 0.660245 |
79a2ff68f17d30ce41c242474c381b0b84191ff0 | 132 | exs | Elixir | ether/test/ether_test.exs | entro-pi/cauldron | 13688f0bff08604cf5097d3f89ab9253b0230b5b | [
"MIT"
] | 5 | 2019-10-27T07:02:30.000Z | 2019-11-26T18:48:22.000Z | ether/test/ether_test.exs | entro-pi/idleHands | 13688f0bff08604cf5097d3f89ab9253b0230b5b | [
"MIT"
] | null | null | null | ether/test/ether_test.exs | entro-pi/idleHands | 13688f0bff08604cf5097d3f89ab9253b0230b5b | [
"MIT"
] | null | null | null | defmodule EtherTest do
use ExUnit.Case
doctest Ether
test "greets the world" do
assert Ether.hello() == :world
end
end
| 14.666667 | 34 | 0.69697 |
79a3019f52a5d2b44e9de5bd151ef28c3277678d | 1,375 | exs | Elixir | test/speakeasy/load_resource_by_id_test.exs | rbino/speakeasy | 5bf7b52c21ce97471c5029ef4a6ea563633279c6 | [
"MIT"
] | 66 | 2018-08-18T02:53:06.000Z | 2021-12-12T18:43:03.000Z | test/speakeasy/load_resource_by_id_test.exs | rbino/speakeasy | 5bf7b52c21ce97471c5029ef4a6ea563633279c6 | [
"MIT"
] | 9 | 2018-09-10T22:39:45.000Z | 2021-08-06T00:30:41.000Z | test/speakeasy/load_resource_by_id_test.exs | rbino/speakeasy | 5bf7b52c21ce97471c5029ef4a6ea563633279c6 | [
"MIT"
] | 9 | 2018-09-11T03:07:11.000Z | 2021-08-06T00:09:03.000Z | defmodule Speakeasy.LoadResourceByIDTest do
use ExUnit.Case, async: true
alias Speakeasy.LoadResourceByID
def mock_resolution() do
%Absinthe.Resolution{
state: :unresolved,
arguments: %{id: "3", name: "foo"},
context: %{
current_user: "chauncy",
speakeasy: %Speakeasy.Context{
user: "chauncy"
}
}
}
end
test "updates the resolution's context with the results of loader.(id)" do
resolution = mock_resolution()
loader = fn id -> {:ok, "Received ID: #{id}"} end
%{context: %{speakeasy: context}} = LoadResourceByID.call(resolution, loader)
assert context == %Speakeasy.Context{resource: "Received ID: 3", user: "chauncy"}
end
test "updates the resolution's context with the results of loader.(id) when the user is under a different key" do
resolution = mock_resolution()
loader = fn id -> {:ok, "Received ID: #{id}"} end
%{context: %{speakeasy: context}} =
LoadResourceByID.call(resolution, loader: loader, user_key: :user)
assert context == %Speakeasy.Context{resource: "Received ID: 3", user: "chauncy"}
end
test "Doesn't do anything if the resolution is already resolved" do
resolution = %{mock_resolution() | state: :resolved}
loader = fn id -> {:ok, id} end
assert resolution == LoadResourceByID.call(resolution, loader)
end
end
| 31.976744 | 115 | 0.659636 |
79a3040d7e19221536c0daf3850580d64ceb0a84 | 1,854 | exs | Elixir | test/xema/validation_error_test.exs | xadhoom/xema | 267fbdbdd30c3e9a99542141d3959dd6cd7f5708 | [
"MIT"
] | 49 | 2018-06-05T09:42:19.000Z | 2022-02-15T12:50:51.000Z | test/xema/validation_error_test.exs | xadhoom/xema | 267fbdbdd30c3e9a99542141d3959dd6cd7f5708 | [
"MIT"
] | 152 | 2017-06-11T13:43:06.000Z | 2022-01-09T17:13:45.000Z | test/xema/validation_error_test.exs | xadhoom/xema | 267fbdbdd30c3e9a99542141d3959dd6cd7f5708 | [
"MIT"
] | 6 | 2019-05-31T05:41:47.000Z | 2021-12-14T08:09:36.000Z | defmodule Xema.ValidationErrorTest do
use ExUnit.Case, async: true
doctest Xema.ValidationError
alias Xema.ValidationError
alias Xema.Validator
describe "Xema.validate!/2" do
setup do
%{schema: Xema.new(:integer)}
end
test "returns a ValidationError for invalid data", %{schema: schema} do
Xema.validate!(schema, "foo")
rescue
error ->
assert %ValidationError{} = error
assert error.message == nil
assert Exception.message(error) == ~s|Expected :integer, got "foo".|
assert error.reason == %{type: :integer, value: "foo"}
end
end
describe "format_error/1" do
test "returns a formatted error for an error tuple (:integer)" do
schema = Xema.new(:integer)
assert schema |> Validator.validate("foo") |> ValidationError.format_error() ==
~s|Expected :integer, got \"foo\".|
end
test "returns a formatted error for an error tuple (:list)" do
schema = Xema.new({:list, items: :integer})
data = [1, "foo", 2, :bar]
assert schema |> Validator.validate(data) |> ValidationError.format_error() ==
"""
Expected :integer, got "foo", at [1].
Expected :integer, got :bar, at [3].\
"""
end
end
describe "exception/1" do
test "returns unexpected error for unexpected reason" do
error = ValidationError.exception(reason: "foo")
assert error == %Xema.ValidationError{
message: nil,
reason: "foo"
}
assert Exception.message(error) == "Unexpected error."
end
test "returns unexpected error for internal exception" do
error = ValidationError.exception(reason: %{items: {}})
assert Exception.message(error) =~ "got Protocol.UndefinedError with message"
end
end
end
| 29.428571 | 85 | 0.614887 |
79a304a431f816bcd0cd35350abb79d7386e03b5 | 3,274 | exs | Elixir | test/liblink/socket/recvmsg/impl_test.exs | Xerpa/liblink | 7b983431c5b391bb8cf182edd9ca4937601eea35 | [
"Apache-2.0"
] | 3 | 2018-10-26T12:55:15.000Z | 2019-05-03T22:41:34.000Z | test/liblink/socket/recvmsg/impl_test.exs | Xerpa/liblink | 7b983431c5b391bb8cf182edd9ca4937601eea35 | [
"Apache-2.0"
] | 4 | 2018-08-26T14:43:57.000Z | 2020-09-23T21:14:56.000Z | test/liblink/socket/recvmsg/impl_test.exs | Xerpa/liblink | 7b983431c5b391bb8cf182edd9ca4937601eea35 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 (c) Xerpa
#
# 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 Liblink.Socket.Recvmsg.ImplTest do
use ExUnit.Case, async: true
alias Liblink.Socket.Device
alias Liblink.Socket.Recvmsg.Impl
@moduletag capture_log: true
setup env do
device = %Device{}
{:ok, state} = Impl.init()
{:noreply, state} =
unless env[:no_attach] do
Impl.attach(device, :async, state)
else
{:noreply, state}
end
{:ok, [state: state]}
end
describe "in recv state" do
test "empty queue", %{state: state} do
assert {:reply, {:error, :empty}, _state} = Impl.recvmsg(:sync, state)
end
test "after receiving one message", %{state: state} do
assert {:noreply, state} = Impl.on_liblink_message([:foobar], :async, state)
assert {:reply, {:ok, [:foobar]}, _state} = Impl.recvmsg(:sync, state)
end
test "poll an empty queue", %{state: state} do
assert {:reply, {:ok, _tag}, _} = Impl.poll(:infinity, self(), :sync, state)
refute_receive _
end
test "poll after receiving one message", %{state: state} do
assert {:noreply, state} = Impl.on_liblink_message([:foobar], :async, state)
assert {:reply, {:ok, tag}, _state} = Impl.poll(:infinity, self(), :sync, state)
assert_receive {^tag, :data}
end
test "schedule poll notification", %{state: state} do
assert {:reply, {:ok, tag}, _} = Impl.poll(0, self(), :sync, state)
assert_receive {:halt, :poll, ^tag}
end
test "notify poll about timeout", %{state: state} do
{:reply, {:ok, tag}, state} = Impl.poll(0, self(), :sync, state)
assert {:noreply, _} = Impl.halt_poll(tag, :async, state)
assert_receive {^tag, :timeout}
end
end
describe "in subs state" do
setup env do
{:noreply, state} = Impl.consume(self(), :async, env.state)
{:ok, [state: state]}
end
test "proxy one message to consumer", %{state: state} do
{:noreply, _} = Impl.on_liblink_message([:foobar], :async, state)
assert_receive {Liblink.Socket, :data, [:foobar]}
end
test "proxy all messages to consumer", %{state: state} do
{:noreply, state} = Impl.on_liblink_message([:foo], :async, state)
{:noreply, _} = Impl.on_liblink_message([:bar], :async, state)
assert_receive {Liblink.Socket, :data, [:foo]}
assert_receive {Liblink.Socket, :data, [:bar]}
end
test "halt consumer when after it dies", %{state: state} do
{_, data} = state.fsm
tag = data.consumer.tag
{:noreply, state} =
Impl.on_monitor_message({:DOWN, tag, :process, self(), :normal}, :async, state)
{:noreply, _} = Impl.on_liblink_message([:bar], :async, state)
refute_receive _
end
end
end
| 32.74 | 87 | 0.638974 |
79a31a53e903494c29ba57cc864ce4b1c17f57b8 | 1,348 | ex | Elixir | harbor/lib/pier/message/_types/chat_token.ex | miapolis/port7 | 7df1223f83d055eeb6ce8f61f4af8b4f2cf33e74 | [
"MIT"
] | null | null | null | harbor/lib/pier/message/_types/chat_token.ex | miapolis/port7 | 7df1223f83d055eeb6ce8f61f4af8b4f2cf33e74 | [
"MIT"
] | null | null | null | harbor/lib/pier/message/_types/chat_token.ex | miapolis/port7 | 7df1223f83d055eeb6ce8f61f4af8b4f2cf33e74 | [
"MIT"
] | null | null | null | defmodule Pier.Message.Types.ChatToken do
use Ecto.Schema
@message_character_limit 100
@primary_key false
embedded_schema do
field(:type, Pier.Message.Types.ChatTokenType)
field(:value, :string, default: "")
end
defimpl Jason.Encoder do
def encode(%{type: type, value: value}, opts) do
Jason.Encode.map(
%{
t: type,
v: value
},
opts
)
end
end
import Ecto.Changeset
def changeset(changeset, %{"t" => type, "v" => value}) do
changeset(changeset, %{"type" => type, "value" => value})
end
def changeset(changeset, data) do
changeset
|> cast(data, [:type, :value])
|> validate_required([:type])
|> validate_length(:value, min: 0, max: @message_character_limit)
|> validate_link
end
defp validate_link(changeset) do
if get_change(changeset, :type) == :link do
validate_link_uri(changeset)
else
changeset
end
end
@allowed_schemes ["http", "https"]
defp validate_link_uri(changeset) do
uri =
changeset
|> get_change(:value)
|> URI.parse()
if match?(
%{host: host, scheme: scheme}
when is_binary(host) and scheme in @allowed_schemes,
uri
) do
changeset
else
add_error(changeset, :value, "invalid url")
end
end
end
| 21.0625 | 69 | 0.606825 |
79a32240bef2d4280111e71ed884cc9f7e134346 | 1,752 | ex | Elixir | lib/job_board_web/controllers/plugs/check_user_permission.ex | TDogVoid/job_board | 23793917bd1cc4e68bccce737b971093030a31eb | [
"MIT"
] | null | null | null | lib/job_board_web/controllers/plugs/check_user_permission.ex | TDogVoid/job_board | 23793917bd1cc4e68bccce737b971093030a31eb | [
"MIT"
] | null | null | null | lib/job_board_web/controllers/plugs/check_user_permission.ex | TDogVoid/job_board | 23793917bd1cc4e68bccce737b971093030a31eb | [
"MIT"
] | null | null | null | defmodule JobBoardWeb.Plugs.CheckUserPermission do
import JobBoardWeb.Plugs.PermissionHelper
alias JobBoard.Repo
def init(_params) do
end
def call(conn, _params) do
user = conn.assigns.current_user
|> Repo.preload(:role)
role = user.role
if role do
case conn.private.phoenix_action do
:index ->
if role.can_edit_other_users || role.admin do
conn
else
unauthorized(conn)
end
:show ->
if check_user_owner(conn) || role.can_view_other_users || role.admin do
conn
else
unauthorized(conn)
end
:edit ->
if check_user_owner(conn) || (role.can_edit_other_users && !is_account_being_edited_admin(conn)) || role.admin do
conn
else
unauthorized(conn)
end
:update ->
if check_user_owner(conn) || (role.can_edit_other_users && !is_account_being_edited_admin(conn)) || role.admin do
conn
else
unauthorized(conn)
end
:delete ->
if check_user_owner(conn) || (role.can_delete_other_users && !is_account_being_edited_admin(conn)) || role.admin do
conn
else
unauthorized(conn)
end
_ ->
unauthorized(conn)
end
else
unauthorized(conn)
end
end
defp check_user_owner(%{params: %{"id" => user_id}} = conn) do
conn.assigns.current_user && String.to_integer(user_id) == conn.assigns.current_user.id
end
defp is_account_being_edited_admin(conn) do
%{"id" => id} = conn.params
user = JobBoard.Accounts.get_user(id)
|> Repo.preload(:role)
user.role.admin
end
end
| 26.149254 | 125 | 0.591895 |
79a32c0b696e873b9474f228e42b4c30d6068cd2 | 1,263 | exs | Elixir | mix.exs | aleDsz/ecto-xsd | da9eec98cd8e3350184f278272ff5d9a828ce92c | [
"MIT"
] | 6 | 2021-03-11T17:23:14.000Z | 2021-11-15T11:13:53.000Z | mix.exs | aleDsz/ecto-xsd | da9eec98cd8e3350184f278272ff5d9a828ce92c | [
"MIT"
] | 9 | 2021-04-13T08:36:29.000Z | 2021-07-23T08:42:25.000Z | mix.exs | aleDsz/ecto-xsd | da9eec98cd8e3350184f278272ff5d9a828ce92c | [
"MIT"
] | null | null | null | defmodule EctoXSD.MixProject do
use Mix.Project
@version "0.1.0"
@repo "https://github.com/aledsz/ecto-xsd"
def project do
[
app: :ecto_xsd,
name: "EctoXSD",
description: "Ecto-based schemas to handle XSD validations",
version: @version,
elixir: "~> 1.11",
start_permanent: Mix.env() == :prod,
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
],
package: package(),
docs: docs(),
deps: deps()
]
end
def application do
[
extra_applications: [:logger]
]
end
defp docs do
[
main: "Astro",
source_ref: "v#{@version}",
source_url: @repo,
extras: ["README.md"]
]
end
defp package do
[
links: %{github: @repo}
]
end
defp deps do
[
{:ecto, "~> 3.5", optional: true},
{:temporary_env, "~> 2.0", optional: true, only: :test},
{:credo, "~> 1.5.0", optional: true, only: :test, runtime: false},
{:excoveralls, "~> 0.10", optional: true, only: :test},
{:git_hooks, "~> 0.5.0", optional: true, only: :test, runtime: false}
]
end
end
| 21.40678 | 75 | 0.543151 |
79a373d634f199258595cd8d7adfbab7070344c1 | 12,549 | ex | Elixir | clients/games_management/lib/google_api/games_management/v1management/api/achievements.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/games_management/lib/google_api/games_management/v1management/api/achievements.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/games_management/lib/google_api/games_management/v1management/api/achievements.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.GamesManagement.V1management.Api.Achievements do
@moduledoc """
API calls for all endpoints tagged `Achievements`.
"""
alias GoogleApi.GamesManagement.V1management.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Resets the achievement with the given ID for the currently authenticated player. This method is only accessible to whitelisted tester accounts for your application.
## Parameters
* `connection` (*type:* `GoogleApi.GamesManagement.V1management.Connection.t`) - Connection to server
* `achievement_id` (*type:* `String.t`) - The ID of the achievement used by this method.
* `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.GamesManagement.V1management.Model.AchievementResetResponse{}}` on success
* `{:error, info}` on failure
"""
@spec games_management_achievements_reset(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.GamesManagement.V1management.Model.AchievementResetResponse.t()}
| {:error, Tesla.Env.t()}
def games_management_achievements_reset(
connection,
achievement_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(:post)
|> Request.url("/achievements/{achievementId}/reset", %{
"achievementId" => URI.encode(achievement_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.GamesManagement.V1management.Model.AchievementResetResponse{}]
)
end
@doc """
Resets all achievements for the currently authenticated player for your application. This method is only accessible to whitelisted tester accounts for your application.
## Parameters
* `connection` (*type:* `GoogleApi.GamesManagement.V1management.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.GamesManagement.V1management.Model.AchievementResetAllResponse{}}` on success
* `{:error, info}` on failure
"""
@spec games_management_achievements_reset_all(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.GamesManagement.V1management.Model.AchievementResetAllResponse.t()}
| {:error, Tesla.Env.t()}
def games_management_achievements_reset_all(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(:post)
|> Request.url("/achievements/reset", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++
[struct: %GoogleApi.GamesManagement.V1management.Model.AchievementResetAllResponse{}]
)
end
@doc """
Resets all draft achievements for all players. This method is only available to user accounts for your developer console.
## Parameters
* `connection` (*type:* `GoogleApi.GamesManagement.V1management.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, %{}}` on success
* `{:error, info}` on failure
"""
@spec games_management_achievements_reset_all_for_all_players(
Tesla.Env.client(),
keyword(),
keyword()
) :: {:ok, nil} | {:error, Tesla.Env.t()}
def games_management_achievements_reset_all_for_all_players(
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(:post)
|> Request.url("/achievements/resetAllForAllPlayers", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [decode: false])
end
@doc """
Resets the achievement with the given ID for all players. This method is only available to user accounts for your developer console. Only draft achievements can be reset.
## Parameters
* `connection` (*type:* `GoogleApi.GamesManagement.V1management.Connection.t`) - Connection to server
* `achievement_id` (*type:* `String.t`) - The ID of the achievement used by this method.
* `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, %{}}` on success
* `{:error, info}` on failure
"""
@spec games_management_achievements_reset_for_all_players(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) :: {:ok, nil} | {:error, Tesla.Env.t()}
def games_management_achievements_reset_for_all_players(
connection,
achievement_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(:post)
|> Request.url("/achievements/{achievementId}/resetForAllPlayers", %{
"achievementId" => URI.encode(achievement_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [decode: false])
end
@doc """
Resets achievements with the given IDs for all players. This method is only available to user accounts for your developer console. Only draft achievements may be reset.
## Parameters
* `connection` (*type:* `GoogleApi.GamesManagement.V1management.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.
* `:body` (*type:* `GoogleApi.GamesManagement.V1management.Model.AchievementResetMultipleForAllRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %{}}` on success
* `{:error, info}` on failure
"""
@spec games_management_achievements_reset_multiple_for_all_players(
Tesla.Env.client(),
keyword(),
keyword()
) :: {:ok, nil} | {:error, Tesla.Env.t()}
def games_management_achievements_reset_multiple_for_all_players(
connection,
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("/achievements/resetMultipleForAllPlayers", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [decode: false])
end
end
| 42.683673 | 187 | 0.64794 |
79a3aacf2e454b3f4c11c4a460fc912eacbb7714 | 6,348 | ex | Elixir | lib/beam_to_ex_ast.ex | olafura/beam_to_ex_ast | 5451d189105c3a4b52aedbf4fbc4f0beca3b9b80 | [
"Apache-2.0"
] | 16 | 2016-02-12T15:15:58.000Z | 2021-08-24T21:48:34.000Z | lib/beam_to_ex_ast.ex | olafura/beam_to_ex_ast | 5451d189105c3a4b52aedbf4fbc4f0beca3b9b80 | [
"Apache-2.0"
] | 1 | 2016-02-17T04:58:38.000Z | 2016-02-17T04:58:38.000Z | lib/beam_to_ex_ast.ex | olafura/beam_to_ex_ast | 5451d189105c3a4b52aedbf4fbc4f0beca3b9b80 | [
"Apache-2.0"
] | 2 | 2016-02-17T03:21:23.000Z | 2016-03-08T09:23:27.000Z | defmodule BeamToExAst do
alias BeamToExAst.Translate
def convert(list, opts \\ []) do
opts = Enum.into(opts, %{})
{mod_name, rest, _opts} = Enum.reduce(list, {"", [], opts}, &do_convert/2)
case length(rest) do
1 ->
{:defmodule, [line: 1], [{:__aliases__, [line: 1], [mod_name]}, [do: List.first(rest)]]}
_ ->
{:defmodule, [line: 1],
[
{:__aliases__, [line: 1], [mod_name]},
[do: {:__block__, [], Enum.sort(rest, &sort_fun/2)}]
]}
end
end
def sort_fun({:def, [line: lna], _}, {:def, [line: lnb], _}) do
lna < lnb
end
# _n is number of parameters
# ln is the line number
def do_convert({:attribute, _ln, :module, name}, {_, rest, opts}) do
{clean_module(name), rest, opts}
end
def do_convert({:attribute, _ln, :record, _ast}, {mod_name, rest, opts}) do
{mod_name, rest, opts}
end
def do_convert({:attribute, _, _, _}, acc) do
acc
end
def do_convert({:function, _, :__info__, _, _}, acc) do
acc
end
def do_convert({:function, _ln, name, _n, body}, {mod_name, rest, opts}) do
opts = Map.put(opts, :parents, [:function])
{mod_name,
Enum.concat(
Enum.map(body, fn
{:clause, ln2, params, guard, body_def} ->
case guard do
[] ->
{:def, [line: ln2],
[{name, [line: ln2], Translate.to_elixir(params, opts)}, def_body(body_def, opts)]}
[[g]] ->
{:def, [line: ln2],
[
{:when, [line: ln2],
[
{name, [line: ln2], Translate.to_elixir(params, opts)},
Translate.to_elixir(g, opts)
]},
def_body(body_def, opts)
]}
[g1, g2] ->
{:def, [line: ln2],
[
{:when, [line: ln2],
[
{name, [line: ln2], Translate.to_elixir(params, opts)},
{:and, [],
[
Translate.to_elixir(List.first(g1), opts),
Translate.to_elixir(List.first(g2), opts)
]}
]},
def_body(body_def, opts)
]}
end
_ ->
body
end),
rest
), opts}
end
def do_convert({:eof, _ln}, acc) do
acc
end
def def_body(items, opts) do
opts = Map.update!(opts, :parents, &[:body | &1])
filtered_items =
items
|> Enum.filter(fn
{:atom, _, nil} -> false
_ -> true
end)
case length(filtered_items) do
1 -> [do: Translate.to_elixir(List.first(filtered_items), opts)]
_ -> [do: {:__block__, [], Translate.to_elixir(filtered_items, opts)}]
end
end
def def_body_less(items, opts) do
opts = Map.update!(opts, :parents, &[:body_less | &1])
case length(items) do
1 -> Translate.to_elixir(List.first(items), opts)
_ -> {:__block__, [], Translate.to_elixir(items, opts)}
end
end
def def_body_less_filter(items, opts) do
opts = Map.update!(opts, :parents, &[:body_less_filter | &1])
items2 =
items
|> Translate.to_elixir(opts)
|> Enum.filter(&filter_empty/1)
case length(items2) do
1 -> List.first(items2)
_ -> {:__block__, [], items2}
end
end
def get_caller(c_mod_call, ln, caller, params, opts) do
case String.match?(c_mod_call, ~r"^[A-Z]") do
true ->
{{:., [line: ln],
[{:__aliases__, [line: ln], [String.to_atom(c_mod_call)]}, clean_atom(caller, opts)]},
[line: ln], Translate.to_elixir(params, opts)}
false ->
{{:., [line: ln], [String.to_atom(c_mod_call), clean_atom(caller, opts)]}, [line: ln],
Translate.to_elixir(params, opts)}
end
end
def remove_tuples(l1) when is_list(l1) do
Enum.map(l1, &remove_tuple/1)
end
def remove_tuples(rest) do
rest
end
def remove_tuple({:{}, [line: _ln], params}) do
params
end
def remove_tuple(params) do
params
end
def only_one(l1) do
case length(l1) do
1 -> List.first(l1)
_ -> l1
end
end
def insert_line_number({:&, [line: 0], number}, ln) do
{:&, [line: ln], number}
end
def insert_line_number(var, _ln) do
var
end
def check_params(params) do
Enum.reduce(params, false, fn
{:var, _ln, var}, acc ->
case Atom.to_string(var) do
<<"__@", _rest::binary>> -> true
<<"_@", _rest::binary>> -> true
_ -> acc
end
_, acc ->
acc
end)
end
def check_bins(s1, acc) when is_binary(s1) do
acc
end
def check_bins(_, _acc) do
true
end
def clean_op(op1) do
op1
|> Atom.to_string()
|> case do
"=:=" -> "==="
"=/=" -> "!=="
"/=" -> "!="
"=<" -> "<="
"andalso" -> "and"
s1 -> s1
end
|> String.to_atom()
end
def clean_module(a1) do
s1 =
a1
|> Atom.to_string()
|> String.replace("Elixir.", "")
s1
|> String.match?(~r"^[A-Z]")
|> case do
true -> s1
false -> Macro.camelize(s1)
end
|> String.to_atom()
end
def clean_atom(a1, _) do
a1
|> Atom.to_string()
|> String.replace("Elixir.", "")
|> String.to_atom()
end
def half_clean_atom(a1, _) do
a1
|> Atom.to_string()
|> String.replace("Elixir.", "")
end
def clean_var(v1, %{erlang: true}) do
v1
|> Atom.to_string()
|> Macro.underscore()
|> String.to_atom()
end
def clean_var(v1, %{elixir: true}) do
v1_string =
v1
|> Atom.to_string()
case System.version() do
<<"1.6", _rest::binary>> ->
v1_string
|> String.replace(~r/^V/, "")
_ ->
if Regex.match?(~r/@\d*/, v1_string) do
v1_string
|> String.replace(~r/^_/, "")
else
v1_string
end
end
|> String.replace(~r/@\d*/, "")
|> String.to_atom()
end
def clean_var(v1, _) do
v1
|> Atom.to_string()
|> String.replace(~r"@\d+", "")
|> String.to_atom()
end
def filter_empty(:filter_this_thing_out_of_the_list_please) do
false
end
def filter_empty(_) do
true
end
end
| 22.352113 | 99 | 0.505514 |
79a3f24720e3e8af543891a578ff2b0867b5948f | 666 | exs | Elixir | mix.exs | qgadrian/locux | 77404174c5c66bd27fed0d07404f916c11060393 | [
"MIT"
] | null | null | null | mix.exs | qgadrian/locux | 77404174c5c66bd27fed0d07404f916c11060393 | [
"MIT"
] | null | null | null | mix.exs | qgadrian/locux | 77404174c5c66bd27fed0d07404f916c11060393 | [
"MIT"
] | null | null | null | defmodule Locux.Mixfile do
use Mix.Project
def project do
[
app: :locux,
version: "0.0.1",
elixir: "~> 1.4.5",
escript: [main_module: Locux],
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps(),
aliases: aliases(),
]
end
def application do
[applications: [:logger, :httpoison]]
end
defp deps do
[
{:httpoison, "~> 0.12"},
{:progress_bar, "> 0.0.0"},
{:statistics, "~> 0.4.1"},
{:credo, "~> 0.8.4", only: [:dev, :test], runtime: false}
]
end
defp aliases do
[
"build": ["compile", "escript.build"]
]
end
end
| 18.5 | 63 | 0.518018 |
79a409171bc0b6ac4b796373fcc94134bcd8d248 | 134 | exs | Elixir | test/test_helper.exs | tlux/rubberband | bece85cf8049ba487bba1d5df0906f6fbfa146eb | [
"MIT"
] | null | null | null | test/test_helper.exs | tlux/rubberband | bece85cf8049ba487bba1d5df0906f6fbfa146eb | [
"MIT"
] | null | null | null | test/test_helper.exs | tlux/rubberband | bece85cf8049ba487bba1d5df0906f6fbfa146eb | [
"MIT"
] | null | null | null | ExUnit.start()
Mox.defmock(MockJSONCodec, for: JSONCodec)
Mox.defmock(RubberBand.Client.Drivers.Mock, for: RubberBand.Client.Driver)
| 26.8 | 74 | 0.80597 |
79a47ae5597fbb17ecbb3e3ac521dda79fec854f | 3,381 | ex | Elixir | apps/omg_jsonrpc/lib/expose_spec/rpc_translate.ex | SingularityMatrix/elixir-omg | 7db3fcc3adfa303e30ff7703148cc5110b587d20 | [
"Apache-2.0"
] | null | null | null | apps/omg_jsonrpc/lib/expose_spec/rpc_translate.ex | SingularityMatrix/elixir-omg | 7db3fcc3adfa303e30ff7703148cc5110b587d20 | [
"Apache-2.0"
] | null | null | null | apps/omg_jsonrpc/lib/expose_spec/rpc_translate.ex | SingularityMatrix/elixir-omg | 7db3fcc3adfa303e30ff7703148cc5110b587d20 | [
"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 OMG.JSONRPC.ExposeSpec.RPCTranslate do
@moduledoc """
Translates an incoming call to a form that can be executed with `:erlang.apply/3`
The incoming call can originate from the JSONRPC handler or the Websockets handler (or other).
Returns JSONRPC2-like error values if there is a problem.
"""
@type function_name :: binary
@type arg_name :: binary
@type spec :: OMG.JSONRPC.ExposeSpec.spec()
@type json_args :: %{required(arg_name) => any}
@type rpc_error :: {:method_not_found, map} | {:invalid_params, map}
@doc """
`to_fa/3` transforms JSONRPC2 method and params to Elixir's Function and Arguments,
since the naming. See also type mfa() in Elixir's typespecs.
"""
@spec to_fa(method :: function_name, params :: json_args, spec :: spec) :: {:ok, atom, list(any)} | rpc_error
def to_fa(method, params, spec, on_match \\ &on_match_default/3) do
with {:ok, fname} <- existing_atom(method),
:ok <- is_exposed(fname, spec),
{:ok, args} <- get_args(fname, params, spec, on_match),
do: {:ok, fname, args}
end
defp on_match_default(_name, _type, value), do: {:ok, value}
@spec existing_atom(method :: function_name) :: {:ok, atom} | {:method_not_found, map}
defp existing_atom(method) do
try do
{:ok, String.to_existing_atom(method)}
rescue
ArgumentError -> {:method_not_found, %{method: method}}
end
end
@spec is_exposed(fname :: atom, spec :: spec) :: :ok | {:method_not_found, map}
defp is_exposed(fname, spec) do
case fname in Map.keys(spec) do
true -> :ok
false -> {:method_not_found, %{method: fname}}
end
end
@spec get_args(fname :: atom, params :: json_args, spec :: spec, on_match :: fun()) ::
{:ok, list(any)} | {:invalid_params, map}
defp get_args(fname, params, spec, on_match) when is_map(params) do
validate_args = fn {name, type} = argspec, list ->
value = Map.get(params, Atom.to_string(name))
value = on_match.(name, type, value)
# value has been looked-up in params and possibly decoded by handler-specific code.
# If either failed an arg was missing or given badly
case value do
{:error, _} ->
{:halt, {:missing_arg, argspec}}
nil ->
{:halt, {:missing_arg, argspec}}
{:ok, value} ->
{:cont, list ++ [value]}
end
end
case Enum.reduce_while(spec[fname].args, [], validate_args) do
{:missing_arg, {name, type}} ->
msg = "Please provide parameter `#{name}` of type `#{inspect(type)}`"
{:invalid_params, %{msg: msg, name: name, type: type}}
args ->
{:ok, args}
end
end
defp get_args(_, _, _, _) do
{:invalid_params, %{msg: "params should be a JSON key-value pair array"}}
end
end
| 35.21875 | 111 | 0.654244 |
79a47ef385fab786fbe9de304ddf1d60eb9de754 | 549 | exs | Elixir | priv/test_repo/migrations/20210427205854_migrate_resources10.exs | frankdugan3/ash_postgres | ae173f0229ffe1dea821e8a73c2c6b8c858b39f6 | [
"MIT"
] | 13 | 2020-09-04T22:31:23.000Z | 2022-02-06T13:24:23.000Z | priv/test_repo/migrations/20210427205854_migrate_resources10.exs | frankdugan3/ash_postgres | ae173f0229ffe1dea821e8a73c2c6b8c858b39f6 | [
"MIT"
] | 57 | 2019-12-04T15:23:41.000Z | 2022-02-14T22:55:16.000Z | priv/test_repo/migrations/20210427205854_migrate_resources10.exs | frankdugan3/ash_postgres | ae173f0229ffe1dea821e8a73c2c6b8c858b39f6 | [
"MIT"
] | 15 | 2020-10-22T13:26:25.000Z | 2021-07-26T23:49:42.000Z | defmodule AshPostgres.TestRepo.Migrations.MigrateResources10 do
@moduledoc """
Updates resources based on their most recent snapshots.
This file was autogenerated with `mix ash_postgres.generate_migrations`
"""
use Ecto.Migration
def up do
execute(
"ALTER INDEX multitenant_orgs_unique_by_name_unique_index RENAME TO multitenant_orgs_unique_by_name_index"
)
end
def down do
execute(
"ALTER INDEX multitenant_orgs_unique_by_name_index RENAME TO multitenant_orgs_unique_by_name_unique_index"
)
end
end | 26.142857 | 112 | 0.781421 |
79a482ac4220bdc7629e576793eac3af0c086470 | 202 | exs | Elixir | test/gotochgo_web/controllers/page_controller_test.exs | geolessel/GOTOchgo2021 | 4061a04647456712ba08e8f3c3fce6fb6e30751a | [
"Apache-2.0"
] | null | null | null | test/gotochgo_web/controllers/page_controller_test.exs | geolessel/GOTOchgo2021 | 4061a04647456712ba08e8f3c3fce6fb6e30751a | [
"Apache-2.0"
] | null | null | null | test/gotochgo_web/controllers/page_controller_test.exs | geolessel/GOTOchgo2021 | 4061a04647456712ba08e8f3c3fce6fb6e30751a | [
"Apache-2.0"
] | 2 | 2021-11-11T17:19:17.000Z | 2021-12-27T16:06:23.000Z | defmodule GotochgoWeb.PageControllerTest do
use GotochgoWeb.ConnCase
test "GET /", %{conn: conn} do
conn = get(conn, "/")
assert html_response(conn, 200) =~ "Welcome to Phoenix!"
end
end
| 22.444444 | 60 | 0.683168 |
79a4b4db983f8be2b11f3ca9ced3de0dc85bd473 | 1,327 | ex | Elixir | clients/cloud_build/lib/google_api/cloud_build/v1/model/retry_build_request.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/cloud_build/lib/google_api/cloud_build/v1/model/retry_build_request.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/cloud_build/lib/google_api/cloud_build/v1/model/retry_build_request.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.CloudBuild.V1.Model.RetryBuildRequest do
@moduledoc """
Specifies a build to retry.
## Attributes
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{}
end
defimpl Poison.Decoder, for: GoogleApi.CloudBuild.V1.Model.RetryBuildRequest do
def decode(value, options) do
GoogleApi.CloudBuild.V1.Model.RetryBuildRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudBuild.V1.Model.RetryBuildRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 30.860465 | 79 | 0.761869 |
79a4d80fb2d621acbc8b1ac0e4a3ee7f309cce8e | 1,467 | ex | Elixir | lib/mastering_bitcoin/secp256k1.ex | paulfioravanti/mastering_bitcoin | 1cf2eb230d4c04cfca6829ea60c045fe4b0d1756 | [
"MIT"
] | 6 | 2018-01-15T06:54:18.000Z | 2018-07-12T17:50:29.000Z | lib/mastering_bitcoin/secp256k1.ex | paulfioravanti/mastering_bitcoin | 1cf2eb230d4c04cfca6829ea60c045fe4b0d1756 | [
"MIT"
] | null | null | null | lib/mastering_bitcoin/secp256k1.ex | paulfioravanti/mastering_bitcoin | 1cf2eb230d4c04cfca6829ea60c045fe4b0d1756 | [
"MIT"
] | null | null | null | defmodule MasteringBitcoin.Secp256k1 do
@moduledoc """
Utility module to deal with functionality around secp265k1
Elliptic Point Cryptography. Specifically,
- Generating a secp256k1 public key from a private key
- Extracting an Elliptic Curve point (EC Point) with coordinates {x, y}
from a secp256k1 public key
- Generating a Bitcoin public key from an EC Point
"""
use Bitwise
@hex 16
@greater_than_curve_midpoint 0x03
@less_than_curve_midpoint 0x02
defguardp is_even?(y) when (y &&& 1) == 1
def bitcoin_public_key(private_key) do
with {public_key, _private_key} <- public_key_from_private_key(private_key),
ec_point <- ec_point_from_public_key(public_key),
bitcoin_public_key <- bitcoin_public_key_from_ec_point(ec_point) do
bitcoin_public_key
end
end
def public_key_from_private_key(private_key) do
private_key
|> String.to_integer(@hex)
|> (fn hex_num -> :crypto.generate_key(:ecdh, :secp256k1, hex_num) end).()
end
# Elliptic Curve point
def ec_point_from_public_key(public_key) do
<<_prefix::size(8), x::size(256), y::size(256)>> = public_key
{x, y}
end
def bitcoin_public_key_from_ec_point({x, y}) do
<<public_key_prefix(y)::size(8), x::size(256)>>
|> Base.encode16(case: :lower)
end
defp public_key_prefix(y) when is_even?(y) do
@greater_than_curve_midpoint
end
defp public_key_prefix(_y) do
@less_than_curve_midpoint
end
end
| 27.679245 | 80 | 0.720518 |
79a50de7a836947f1aa0781eb95f4dba7bfadf78 | 1,071 | exs | Elixir | test/ex_rss/feed_updater_test.exs | cruessler/exrss | 6ac17b7533d78460a1c34cabaae86fec317f460a | [
"MIT"
] | 4 | 2020-02-16T07:18:35.000Z | 2021-12-09T14:43:10.000Z | test/ex_rss/feed_updater_test.exs | cruessler/exrss | 6ac17b7533d78460a1c34cabaae86fec317f460a | [
"MIT"
] | 27 | 2019-10-16T18:35:19.000Z | 2022-03-13T16:39:57.000Z | test/ex_rss/feed_updater_test.exs | cruessler/exrss | 6ac17b7533d78460a1c34cabaae86fec317f460a | [
"MIT"
] | null | null | null | defmodule ExRss.FeedUpdaterTest do
use ExRss.DataCase
alias Ecto.Multi
alias ExRss.Feed
alias ExRss.FeedUpdater
test "updates entries" do
feed = %Feed{id: 1, title: "This is a title", url: "http://example.com", user_id: 1}
raw_feed = %{
title: "This is a title",
entries: [
%{
title: "This is a title",
link: "http://example.com/posts/1.html",
updated: DateTime.utc_now() |> DateTime.to_string()
},
%{
title: "This is a title",
link: "/posts/2.html",
updated: DateTime.utc_now() |> DateTime.to_string()
}
]
}
multi = FeedUpdater.update(feed, raw_feed)
assert [
{:insert_entries, {:insert_all, ExRss.Entry, [first, second], _}},
{:feed, {:update, feed_changeset, []}}
] = Multi.to_list(multi)
assert first.feed_id == feed.id
assert first.url == "http://example.com/posts/1.html"
assert second.url == "http://example.com/posts/2.html"
assert feed_changeset.valid?
end
end
| 26.775 | 88 | 0.573296 |
79a5160e755823003c0ef1545212b7a41ca50e5d | 1,089 | exs | Elixir | 12-new-project/facade/test/schedule_server_handler_test.exs | kranfix/elixir-playground | 28f1314b137eb591946f501647e76d8017070ffa | [
"MIT"
] | null | null | null | 12-new-project/facade/test/schedule_server_handler_test.exs | kranfix/elixir-playground | 28f1314b137eb591946f501647e76d8017070ffa | [
"MIT"
] | null | null | null | 12-new-project/facade/test/schedule_server_handler_test.exs | kranfix/elixir-playground | 28f1314b137eb591946f501647e76d8017070ffa | [
"MIT"
] | 1 | 2020-11-17T07:06:17.000Z | 2020-11-17T07:06:17.000Z | defmodule ScheduleServerHandlerTest do
use ExUnit.Case
doctest ScheduleServerHandler
test "Throws error because stops before starts" do
{:ok, server} = ScheduleServer.start_link()
handler = %ScheduleServerHandler{server: server}
{:error, _} = ServerHandler.stop(handler)
end
test "starts with error because of a unkown file" do
{:ok, server} = ScheduleServer.start_link()
handler = %ScheduleServerHandler{server: server}
{:error, e} = ServerHandler.start(handler, "unknown.md")
assert e == :enoent
end
test "starts and stops server with success" do
{:ok, server} = ScheduleServer.start_link()
handler = %ScheduleServerHandler{server: server}
assert ServerHandler.start(handler) == :ok
assert ServerHandler.stop(handler) == :ok
end
test "starts and stops server with success with no default config file" do
{:ok, server} = ScheduleServer.start_link()
handler = %ScheduleServerHandler{server: server}
assert ServerHandler.start(handler, "README.md") == :ok
assert ServerHandler.stop(handler) == :ok
end
end
| 34.03125 | 76 | 0.716253 |
79a518735d0f535436a9ee15fa135658fb9bb468 | 1,635 | ex | Elixir | lib/crit/setup/animal_impl/write.ex | jesseshieh/crit19 | 0bba407fea09afed72cbb90ca579ba34c537edef | [
"MIT"
] | null | null | null | lib/crit/setup/animal_impl/write.ex | jesseshieh/crit19 | 0bba407fea09afed72cbb90ca579ba34c537edef | [
"MIT"
] | null | null | null | lib/crit/setup/animal_impl/write.ex | jesseshieh/crit19 | 0bba407fea09afed72cbb90ca579ba34c537edef | [
"MIT"
] | null | null | null | defmodule Crit.Setup.AnimalImpl.Write do
alias Ecto.ChangesetX
alias Ecto.Changeset
alias Crit.Setup.Schemas.{Animal, ServiceGap}
alias Crit.Setup.AnimalApi
alias Crit.Sql
def update(animal, attrs, institution) do
case try_update(animal, attrs, institution) do
{:error, %{errors: [{:optimistic_lock_error, _}]}} ->
{:error, changeset_for_lock_error(animal.id, institution)}
{:error, partial_changeset} ->
changeset =
partial_changeset
|> ChangesetX.flush_lock_version
|> changeset_for_other_error
{:error, changeset}
{:ok, result} ->
{:ok, result}
end
end
defp try_update(animal, attrs, institution) do
animal
|> Animal.update_changeset(attrs)
|> Sql.update([stale_error_field: :optimistic_lock_error], institution)
end
defp changeset_for_lock_error(id, institution) do
AnimalApi.updatable!(id, institution)
|> Animal.form_changeset
|> Changeset.add_error(
:optimistic_lock_error,
"Someone else was editing the animal while you were."
)
|> ChangesetX.ensure_forms_display_errors()
end
defp changeset_for_other_error(changeset) do
case Changeset.fetch_change(changeset, :service_gaps) do
{:ok, [ %{action: :insert} | _rest ]} = _has_bad_new_service_gap ->
changeset
{:ok, only_has_service_gap_updates} ->
Changeset.put_change(changeset, :service_gaps,
[Changeset.change(%ServiceGap{}) | only_has_service_gap_updates])
:error ->
%{changeset | data: Animal.prepend_empty_service_gap(changeset.data)}
end
end
end
| 30.277778 | 77 | 0.681346 |
79a52c2319114f6ccf1dde42d8f6eae2da74400b | 1,388 | ex | Elixir | clients/docs/lib/google_api/docs/v1/model/object_references.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/docs/lib/google_api/docs/v1/model/object_references.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/docs/lib/google_api/docs/v1/model/object_references.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.Docs.V1.Model.ObjectReferences do
@moduledoc """
A collection of object IDs.
## Attributes
* `objectIds` (*type:* `list(String.t)`, *default:* `nil`) - The object IDs.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:objectIds => list(String.t())
}
field(:objectIds, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Docs.V1.Model.ObjectReferences do
def decode(value, options) do
GoogleApi.Docs.V1.Model.ObjectReferences.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Docs.V1.Model.ObjectReferences do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 29.531915 | 80 | 0.729107 |
79a5426fc511dca6756dc6196d3941bef7f002a0 | 2,554 | exs | Elixir | test/json_schema_test_suite/draft4/minimum_test.exs | romul/xema | 8273e10645cf54e8765a197b1ff0c097994275d9 | [
"MIT"
] | null | null | null | test/json_schema_test_suite/draft4/minimum_test.exs | romul/xema | 8273e10645cf54e8765a197b1ff0c097994275d9 | [
"MIT"
] | null | null | null | test/json_schema_test_suite/draft4/minimum_test.exs | romul/xema | 8273e10645cf54e8765a197b1ff0c097994275d9 | [
"MIT"
] | null | null | null | defmodule JsonSchemaTestSuite.Draft4.MinimumTest do
use ExUnit.Case
import Xema, only: [valid?: 2]
describe "minimum validation" do
setup do
%{
schema:
Xema.from_json_schema(
%{"minimum" => 1.1},
draft: "draft4"
)
}
end
test "above the minimum is valid", %{schema: schema} do
assert valid?(schema, 2.6)
end
test "boundary point is valid", %{schema: schema} do
assert valid?(schema, 1.1)
end
test "below the minimum is invalid", %{schema: schema} do
refute valid?(schema, 0.6)
end
test "ignores non-numbers", %{schema: schema} do
assert valid?(schema, "x")
end
end
describe "minimum validation (explicit false exclusivity)" do
setup do
%{
schema:
Xema.from_json_schema(
%{"exclusiveMinimum" => false, "minimum" => 1.1},
draft: "draft4"
)
}
end
test "above the minimum is valid", %{schema: schema} do
assert valid?(schema, 2.6)
end
test "boundary point is valid", %{schema: schema} do
assert valid?(schema, 1.1)
end
test "below the minimum is invalid", %{schema: schema} do
refute valid?(schema, 0.6)
end
test "ignores non-numbers", %{schema: schema} do
assert valid?(schema, "x")
end
end
describe "exclusiveMinimum validation" do
setup do
%{
schema:
Xema.from_json_schema(
%{"exclusiveMinimum" => true, "minimum" => 1.1},
draft: "draft4"
)
}
end
test "above the minimum is still valid", %{schema: schema} do
assert valid?(schema, 1.2)
end
test "boundary point is invalid", %{schema: schema} do
refute valid?(schema, 1.1)
end
end
describe "minimum validation with signed integer" do
setup do
%{
schema:
Xema.from_json_schema(
%{"minimum" => -2},
draft: "draft4"
)
}
end
test "negative above the minimum is valid", %{schema: schema} do
assert valid?(schema, -1)
end
test "positive above the minimum is valid", %{schema: schema} do
assert valid?(schema, 0)
end
test "boundary point is valid", %{schema: schema} do
assert valid?(schema, -2)
end
test "below the minimum is invalid", %{schema: schema} do
refute valid?(schema, -3)
end
test "ignores non-numbers", %{schema: schema} do
assert valid?(schema, "x")
end
end
end
| 22.403509 | 68 | 0.566171 |
79a57453c8a223648fbcb8ef6e48ca1858170741 | 6,836 | exs | Elixir | test/fun_with_flags/gate_test.exs | planswell/fun_with_flags | 97656285e59c4852d8be45a1ee8ceb15d53e9ffe | [
"MIT"
] | null | null | null | test/fun_with_flags/gate_test.exs | planswell/fun_with_flags | 97656285e59c4852d8be45a1ee8ceb15d53e9ffe | [
"MIT"
] | null | null | null | test/fun_with_flags/gate_test.exs | planswell/fun_with_flags | 97656285e59c4852d8be45a1ee8ceb15d53e9ffe | [
"MIT"
] | null | null | null | defmodule FunWithFlags.GateTest do
use ExUnit.Case, async: true
alias FunWithFlags.Gate
alias FunWithFlags.TestUser
describe "new() for boolean gates" do
test "new(:boolean, true|false) returns a new Boolean Gate" do
assert %Gate{type: :boolean, for: nil, enabled: true} = Gate.new(:boolean, true)
assert %Gate{type: :boolean, for: nil, enabled: false} = Gate.new(:boolean, false)
end
test "new(:actor, actor, true|false) returns a new Actor Gate" do
user = %TestUser{id: 234, email: "[email protected]" }
assert %Gate{type: :actor, for: "user:234", enabled: true} = Gate.new(:actor, user, true)
assert %Gate{type: :actor, for: "user:234", enabled: false} = Gate.new(:actor, user, false)
map = %{actor_id: "hello", foo: "bar"}
assert %Gate{type: :actor, for: "map:hello", enabled: true} = Gate.new(:actor, map, true)
assert %Gate{type: :actor, for: "map:hello", enabled: false} = Gate.new(:actor, map, false)
end
test "new(:actor, ...) with a non-actor raises an exception" do
assert_raise Protocol.UndefinedError, fn() ->
Gate.new(:actor, :not_a_valid_actor, true)
end
end
test "new(:group, group_name, true|false) returns a new Group Gate" do
assert %Gate{type: :group, for: :plants, enabled: true} = Gate.new(:group, :plants, true)
assert %Gate{type: :group, for: :animals, enabled: false} = Gate.new(:group, :animals, false)
end
test "new(:group, ...) with a name that is not an atom raises an exception" do
assert_raise FunWithFlags.Gate.InvalidGroupNameError, fn() -> Gate.new(:group, "a_binary", true) end
assert_raise FunWithFlags.Gate.InvalidGroupNameError, fn() -> Gate.new(:group, %{a: "map"}, false) end
end
end
describe "enabled?(gate), for boolean gates" do
test "without extra arguments, it simply checks the value of the gate" do
gate = %Gate{type: :boolean, for: nil, enabled: true}
assert {:ok, true} = Gate.enabled?(gate)
gate = %Gate{type: :boolean, for: nil, enabled: false}
assert {:ok, false} = Gate.enabled?(gate)
end
test "an optional [for: something] argument is ignored" do
gandalf = %TestUser{id: 42, email: "[email protected]" }
gate = %Gate{type: :boolean, for: nil, enabled: true}
assert {:ok, true} = Gate.enabled?(gate, for: gandalf)
gate = %Gate{type: :boolean, for: nil, enabled: false}
assert {:ok, false} = Gate.enabled?(gate, for: gandalf)
end
end
describe "enabled?(gate, for: actor)" do
setup do
chip = %TestUser{id: 1, email: "[email protected]" }
dale = %TestUser{id: 2, email: "[email protected]" }
gate = Gate.new(:actor, chip, true)
{:ok, gate: gate, chip: chip, dale: dale}
end
test "without the [for: actor] option it raises an exception", %{gate: gate} do
assert_raise FunctionClauseError, fn() ->
Gate.enabled?(gate)
end
end
test "passing a nil actor option raises an exception (just because nil is not an Actor)", %{gate: gate} do
assert_raise Protocol.UndefinedError, fn() ->
Gate.enabled?(gate, for: nil)
end
end
test "for an enabled gate, it returns {:ok, true} for the associated
actor and :ignore for other actors", %{gate: gate, chip: chip, dale: dale} do
assert {:ok, true} = Gate.enabled?(gate, for: chip)
assert :ignore = Gate.enabled?(gate, for: dale)
end
test "for a disabled gate, it returns {:ok, false} for the associated
actor and :ignore for other actors", %{gate: gate, chip: chip, dale: dale} do
gate = %Gate{gate | enabled: false}
assert {:ok, false} = Gate.enabled?(gate, for: chip)
assert :ignore = Gate.enabled?(gate, for: dale)
end
end
describe "enabled?(gate, for: item), for Group gates" do
setup do
bruce = %TestUser{id: 1, email: "[email protected]"}
clark = %TestUser{id: 2, email: "[email protected]"}
gate = Gate.new(:group, :admin, true)
{:ok, gate: gate, bruce: bruce, clark: clark}
end
test "without the [for: item] option it raises an exception", %{gate: gate} do
assert_raise FunctionClauseError, fn() ->
Gate.enabled?(gate)
end
end
test "for an enabled gate, it returns {:ok, true} for items that belongs to the group
and :ignore for the others", %{gate: gate, bruce: bruce, clark: clark} do
assert {:ok, true} = Gate.enabled?(gate, for: bruce)
assert :ignore = Gate.enabled?(gate, for: clark)
end
test "for a disabled gate, it returns {:ok, false} for items that belongs to the group
and :ignore for the others", %{gate: gate, bruce: bruce, clark: clark} do
gate = %Gate{gate | enabled: false}
assert {:ok, false} = Gate.enabled?(gate, for: bruce)
assert :ignore = Gate.enabled?(gate, for: clark)
end
test "it always returns :ignore for items that do not implement the Group protocol
(because of the fallback to Any)", %{gate: gate} do
assert :ignore = Gate.enabled?(gate, for: nil)
assert :ignore = Gate.enabled?(gate, for: "pompelmo")
assert :ignore = Gate.enabled?(gate, for: [1,2,3])
assert :ignore = Gate.enabled?(gate, for: {:a, "tuple"})
end
end
describe "boolean?(gate)" do
test "with a boolean gate it returns true" do
gate = %Gate{type: :boolean, for: nil, enabled: false}
assert Gate.boolean?(gate)
end
test "with an actor gate it returns false" do
gate = %Gate{type: :actor, for: "salami", enabled: false}
refute Gate.boolean?(gate)
end
test "with a group gate it returns false" do
gate = %Gate{type: :group, for: "prosciutto", enabled: false}
refute Gate.boolean?(gate)
end
end
describe "actor?(gate)" do
test "with an actor gate it returns true" do
gate = %Gate{type: :actor, for: "salami", enabled: false}
assert Gate.actor?(gate)
end
test "with a boolean gate it returns false" do
gate = %Gate{type: :boolean, for: nil, enabled: false}
refute Gate.actor?(gate)
end
test "with a group gate it returns false" do
gate = %Gate{type: :group, for: "prosciutto", enabled: false}
refute Gate.actor?(gate)
end
end
describe "group?(gate)" do
test "with a group gate it returns true" do
gate = %Gate{type: :group, for: "prosciutto", enabled: false}
assert Gate.group?(gate)
end
test "with a boolean gate it returns false" do
gate = %Gate{type: :boolean, for: nil, enabled: false}
refute Gate.group?(gate)
end
test "with an actor gate it returns false" do
gate = %Gate{type: :actor, for: "salami", enabled: false}
refute Gate.group?(gate)
end
end
end
| 36.169312 | 110 | 0.629754 |
79a59e1778644921c372a1a90fc033bfaa0d626d | 690 | exs | Elixir | test/portmidi/devices_test.exs | thbar/ex-portmidi | ad4abde02af60686f9dee8b066b92b5ffb79019b | [
"MIT"
] | 8 | 2021-05-01T19:01:07.000Z | 2021-05-18T12:19:25.000Z | test/portmidi/devices_test.exs | thbar/ex-portmidi | ad4abde02af60686f9dee8b066b92b5ffb79019b | [
"MIT"
] | 1 | 2021-10-13T13:55:47.000Z | 2021-10-13T13:55:47.000Z | test/portmidi/devices_test.exs | thbar/ex-portmidi | ad4abde02af60686f9dee8b066b92b5ffb79019b | [
"MIT"
] | null | null | null | defmodule PortMidiDevicesTest do
alias PortMidi.Device
use ExUnit.Case, async: false
import Mock
@mock_nif_devices %{
input: [%{name: 'Launchpad Mini', interf: 'CoreMIDI', input: 1, output: 0, opened: 0}],
output: [%{name: 'Launchpad Mini', interf: 'CoreMIDI', input: 0, output: 1, opened: 0}]
}
test_with_mock "list returns a map of devices", PortMidi.Nifs.Devices, [do_list: fn -> @mock_nif_devices end] do
assert PortMidi.Devices.list() == %{
input: [%Device{name: "Launchpad Mini", interf: "CoreMIDI", input: 1, output: 0, opened: 0}],
output: [%Device{name: "Launchpad Mini", interf: "CoreMIDI", input: 0, output: 1, opened: 0}]
}
end
end
| 36.315789 | 114 | 0.657971 |
79a5e004819fcdf9bdc009551265a13f06bc9b33 | 2,133 | ex | Elixir | verify/lib/ua_inspector_verify/cleanup/generic.ex | elixytics/ua_inspector | 11fd98f69b7853b70529ee73355ef57851248572 | [
"Apache-2.0"
] | 57 | 2015-04-07T03:10:45.000Z | 2019-03-11T01:01:40.000Z | verify/lib/ua_inspector_verify/cleanup/generic.ex | elixytics/ua_inspector | 11fd98f69b7853b70529ee73355ef57851248572 | [
"Apache-2.0"
] | 16 | 2015-03-09T19:56:17.000Z | 2019-03-16T14:24:02.000Z | verify/lib/ua_inspector_verify/cleanup/generic.ex | elixytics/ua_inspector | 11fd98f69b7853b70529ee73355ef57851248572 | [
"Apache-2.0"
] | 15 | 2015-02-02T23:14:00.000Z | 2019-03-16T13:15:05.000Z | defmodule UAInspectorVerify.Cleanup.Generic do
@moduledoc """
Cleans up testcases.
"""
alias UAInspectorVerify.Cleanup.Base
@empty_to_unknown [
[:client],
[:client, :engine],
[:client, :engine_version],
[:client, :version],
[:device, :brand],
[:device, :model],
[:device, :type],
[:os, :platform],
[:os, :version]
]
@unknown_to_atom [
[:browser_family],
[:os_family]
]
@doc """
Cleans up a test case.
"""
@spec cleanup(testcase :: map) :: map
def cleanup(testcase) do
testcase
|> Base.empty_to_unknown(@empty_to_unknown)
|> convert_unknown(@unknown_to_atom)
|> cleanup_client_engine()
|> cleanup_client_engine_version()
|> cleanup_os_entry()
|> remove_unknown_device()
end
defp convert_unknown(testcase, []), do: testcase
defp convert_unknown(testcase, [path | paths]) do
testcase
|> get_in(path)
|> case do
"Unknown" -> put_in(testcase, path, :unknown)
_ -> testcase
end
|> convert_unknown(paths)
end
defp cleanup_client_engine(%{client: client} = testcase) when is_map(client) do
client =
if Map.has_key?(client, :engine) do
client
else
Map.put(client, :engine, :unknown)
end
%{testcase | client: client}
end
defp cleanup_client_engine(testcase), do: testcase
defp cleanup_client_engine_version(%{client: client} = testcase) when is_map(client) do
client =
if Map.has_key?(client, :engine_version) do
client
else
Map.put(client, :engine_version, :unknown)
end
%{testcase | client: client}
end
defp cleanup_client_engine_version(testcase), do: testcase
defp cleanup_os_entry(%{os: os} = testcase) do
os =
case Map.keys(os) do
[] -> :unknown
_ -> os
end
%{testcase | os: os}
end
defp cleanup_os_entry(testcase), do: testcase
defp remove_unknown_device(
%{device: %{type: :unknown, brand: :unknown, model: :unknown}} = result
) do
%{result | device: :unknown}
end
defp remove_unknown_device(result), do: result
end
| 21.989691 | 89 | 0.626817 |
79a5e886d6dcdd4e73d68a4a1b34a7c27dbca85b | 129 | exs | Elixir | ring/test/ring_test.exs | mrmarbury/TheLittleElixirAndOTPGuideBook | 5aa46cdaee896ab5ecd87d3cf86bd7f9140fcda8 | [
"Apache-2.0"
] | null | null | null | ring/test/ring_test.exs | mrmarbury/TheLittleElixirAndOTPGuideBook | 5aa46cdaee896ab5ecd87d3cf86bd7f9140fcda8 | [
"Apache-2.0"
] | null | null | null | ring/test/ring_test.exs | mrmarbury/TheLittleElixirAndOTPGuideBook | 5aa46cdaee896ab5ecd87d3cf86bd7f9140fcda8 | [
"Apache-2.0"
] | null | null | null | defmodule RingTest do
use ExUnit.Case
doctest Ring
test "greets the world" do
assert Ring.hello() == :world
end
end
| 14.333333 | 33 | 0.689922 |
79a5edcbfda2e8131810b984e8512c9f429c6bb1 | 888 | ex | Elixir | solomon/web/views/account_role_view.ex | FoxComm/highlander | 1aaf8f9e5353b94c34d574c2a92206a1c363b5be | [
"MIT"
] | 10 | 2018-04-12T22:29:52.000Z | 2021-10-18T17:07:45.000Z | solomon/web/views/account_role_view.ex | FoxComm/highlander | 1aaf8f9e5353b94c34d574c2a92206a1c363b5be | [
"MIT"
] | null | null | null | solomon/web/views/account_role_view.ex | FoxComm/highlander | 1aaf8f9e5353b94c34d574c2a92206a1c363b5be | [
"MIT"
] | 1 | 2018-07-06T18:42:05.000Z | 2018-07-06T18:42:05.000Z | defmodule Solomon.AccountRoleView do
use Solomon.Web, :view
alias Solomon.AccountRoleView
alias Solomon.PermissionView
#Throughout this controller, we present the id of the granted_role as the AccountRole ID
def render("index.json", %{account_roles: account_roles}) do
%{granted_roles: render_many(account_roles, AccountRoleView, "account_role.json")}
end
def render("show.json", %{account_role: account_role}) do
%{granted_role: render_one(account_role, AccountRoleView, "account_role.json")}
end
# We add 'grant_' in front of id to help the API consumer know that this is explicitly
# the id for the mapping, and not the role itself.
def render("account_role.json", %{account_role: account_role}) do
%{grant_id: account_role.id,
role_id: account_role.role_id
}
end
def render("deleted.json", _) do
%{deleted: "success"}
end
end
| 32.888889 | 90 | 0.734234 |
79a601ff769619c9366cd002792a8ef8ad3838d0 | 1,591 | ex | Elixir | clients/run/lib/google_api/run/v1/model/configuration_spec.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/run/lib/google_api/run/v1/model/configuration_spec.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/run/lib/google_api/run/v1/model/configuration_spec.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.Run.V1.Model.ConfigurationSpec do
@moduledoc """
ConfigurationSpec holds the desired state of the Configuration (from the client).
## Attributes
* `template` (*type:* `GoogleApi.Run.V1.Model.RevisionTemplate.t`, *default:* `nil`) - Template holds the latest specification for the Revision to be stamped out.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:template => GoogleApi.Run.V1.Model.RevisionTemplate.t() | nil
}
field(:template, as: GoogleApi.Run.V1.Model.RevisionTemplate)
end
defimpl Poison.Decoder, for: GoogleApi.Run.V1.Model.ConfigurationSpec do
def decode(value, options) do
GoogleApi.Run.V1.Model.ConfigurationSpec.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Run.V1.Model.ConfigurationSpec do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.851064 | 166 | 0.7467 |
79a6417261577a78b06016b09cf698c2c6245458 | 274 | exs | Elixir | lib/mix/test/fixtures/deps_status/custom/deps_repo/mix.exs | doughsay/elixir | 7356a47047d0b54517bd6886603f09b1121dde2b | [
"Apache-2.0"
] | 19,291 | 2015-01-01T02:42:49.000Z | 2022-03-31T21:01:40.000Z | lib/mix/test/fixtures/deps_status/custom/deps_repo/mix.exs | doughsay/elixir | 7356a47047d0b54517bd6886603f09b1121dde2b | [
"Apache-2.0"
] | 8,082 | 2015-01-01T04:16:23.000Z | 2022-03-31T22:08:02.000Z | lib/mix/test/fixtures/deps_status/custom/deps_repo/mix.exs | doughsay/elixir | 7356a47047d0b54517bd6886603f09b1121dde2b | [
"Apache-2.0"
] | 3,472 | 2015-01-03T04:11:56.000Z | 2022-03-29T02:07:30.000Z | defmodule DepsRepo do
use Mix.Project
def project do
opts = Process.get(:custom_deps_git_repo_opts) || []
[
app: :deps_repo,
version: "0.1.0",
deps: [{:git_repo, "0.1.0", [git: MixTest.Case.fixture_path("git_repo")] ++ opts}]
]
end
end
| 19.571429 | 88 | 0.59854 |
79a688dd7724424de50c980b27dfe89eeb54f5af | 3,497 | exs | Elixir | test/movement/builders/new_version_test.exs | isshindev/accent | ae4c13139b0a0dfd64ff536b94c940a4e2862150 | [
"BSD-3-Clause"
] | 806 | 2018-04-07T20:40:33.000Z | 2022-03-30T01:39:57.000Z | test/movement/builders/new_version_test.exs | isshindev/accent | ae4c13139b0a0dfd64ff536b94c940a4e2862150 | [
"BSD-3-Clause"
] | 194 | 2018-04-07T13:49:37.000Z | 2022-03-30T19:58:45.000Z | test/movement/builders/new_version_test.exs | doc-ai/accent | e337e16f3658cc0728364f952c0d9c13710ebb06 | [
"BSD-3-Clause"
] | 89 | 2018-04-09T13:55:49.000Z | 2022-03-24T07:09:31.000Z | defmodule AccentTest.Movement.Builders.NewVersion do
use Accent.RepoCase
alias Accent.{
Document,
Language,
ProjectCreator,
Repo,
Translation,
User,
Version
}
alias Movement.Builders.NewVersion, as: NewVersionBuilder
@user %User{email: "[email protected]"}
setup do
user = Repo.insert!(@user)
language = Repo.insert!(%Language{name: "English", slug: Ecto.UUID.generate()})
{:ok, project} = ProjectCreator.create(params: %{main_color: "#f00", name: "My project", language_id: language.id}, user: user)
revision = project |> Repo.preload(:revisions) |> Map.get(:revisions) |> hd()
document = Repo.insert!(%Document{project_id: project.id, path: "test", format: "json"})
{:ok, [revision: revision, document: document, project: project, user: user]}
end
test "builder fetch translations and process operations", %{revision: revision, project: project, document: document} do
translation =
%Translation{
key: "a",
proposed_text: "A",
corrected_text: "A",
file_index: 2,
file_comment: "comment",
plural: true,
locked: true,
revision_id: revision.id,
document_id: document.id
}
|> Repo.insert!()
context =
%Movement.Context{}
|> Movement.Context.assign(:project, project)
|> NewVersionBuilder.build()
translation_ids = context.assigns[:translations] |> Enum.map(&Map.get(&1, :id))
operations = context.operations |> Enum.map(&Map.take(&1, [:key, :action, :text, :document_id, :file_comment, :file_index, :plural, :locked]))
assert translation_ids === [translation.id]
assert operations == [
%{
key: translation.key,
action: "version_new",
text: "A",
document_id: document.id,
file_index: 2,
file_comment: "comment",
plural: true,
locked: true
}
]
end
test "builder with existing version", %{revision: revision, project: project, document: document, user: user} do
version = %Version{user_id: user.id, tag: "v3.2", name: "Release", project_id: project.id} |> Repo.insert!()
translation =
%Translation{
key: "a",
proposed_text: "A",
corrected_text: "A",
file_index: 2,
file_comment: "comment",
revision_id: revision.id,
document_id: document.id
}
|> Repo.insert!()
%Translation{
key: "a",
proposed_text: "A",
corrected_text: "A",
file_index: 2,
file_comment: "comment",
revision_id: revision.id,
version_id: version.id,
document_id: document.id,
source_translation_id: translation.id
}
|> Repo.insert!()
context =
%Movement.Context{}
|> Movement.Context.assign(:project, project)
|> NewVersionBuilder.build()
translation_ids = context.assigns[:translations] |> Enum.map(&Map.get(&1, :id))
operations = context.operations |> Enum.map(&Map.take(&1, [:key, :action, :text, :document_id, :file_comment, :file_index]))
assert translation_ids === [translation.id]
assert operations == [
%{
key: translation.key,
action: "version_new",
text: "A",
document_id: document.id,
file_index: 2,
file_comment: "comment"
}
]
end
end
| 29.888889 | 146 | 0.585645 |
79a6f9e9eff0acf02e8cfbe08a5f37e4441524b5 | 7,539 | ex | Elixir | lib/ecto/exceptions.ex | tcrossland/ecto | e028a90920fed27865075787d33c2ad61f45fd24 | [
"Apache-2.0"
] | 2 | 2021-02-25T15:51:16.000Z | 2021-02-25T18:42:35.000Z | lib/ecto/exceptions.ex | tcrossland/ecto | e028a90920fed27865075787d33c2ad61f45fd24 | [
"Apache-2.0"
] | 3 | 2021-06-20T14:51:14.000Z | 2021-06-25T00:56:11.000Z | lib/ecto/exceptions.ex | tcrossland/ecto | e028a90920fed27865075787d33c2ad61f45fd24 | [
"Apache-2.0"
] | 1 | 2021-02-25T15:28:45.000Z | 2021-02-25T15:28:45.000Z | defmodule Ecto.Query.CompileError do
@moduledoc """
Raised at compilation time when the query cannot be compiled.
"""
defexception [:message]
end
defmodule Ecto.Query.CastError do
@moduledoc """
Raised at runtime when a value cannot be cast.
"""
defexception [:type, :value, :message]
def exception(opts) do
value = Keyword.fetch!(opts, :value)
type = Keyword.fetch!(opts, :type)
msg = Keyword.fetch!(opts, :message)
%__MODULE__{value: value, type: type, message: msg}
end
end
defmodule Ecto.QueryError do
@moduledoc """
Raised at runtime when the query is invalid.
"""
defexception [:message]
def exception(opts) do
message = Keyword.fetch!(opts, :message)
query = Keyword.fetch!(opts, :query)
hint = Keyword.fetch(opts, :hint)
message = """
#{message} in query:
#{Inspect.Ecto.Query.to_string(query)}
"""
file = opts[:file]
line = opts[:line]
message =
if file && line do
relative = Path.relative_to_cwd(file)
Exception.format_file_line(relative, line) <> " " <> message
else
message
end
message =
case hint do
{:ok, text} -> message <> "\n" <> text <> "\n"
_ -> message
end
%__MODULE__{message: message}
end
end
defmodule Ecto.SubQueryError do
@moduledoc """
Raised at runtime when a subquery is invalid.
"""
defexception [:message, :exception]
def exception(opts) do
exception = Keyword.fetch!(opts, :exception)
query = Keyword.fetch!(opts, :query)
message = """
the following exception happened when compiling a subquery.
#{Exception.format(:error, exception, []) |> String.replace("\n", "\n ")}
The subquery originated from the following query:
#{Inspect.Ecto.Query.to_string(query)}
"""
%__MODULE__{message: message, exception: exception}
end
end
defmodule Ecto.InvalidChangesetError do
@moduledoc """
Raised when we cannot perform an action because the
changeset is invalid.
"""
defexception [:action, :changeset]
def message(%{action: action, changeset: changeset}) do
changes = extract_changes(changeset)
errors = Ecto.Changeset.traverse_errors(changeset, & &1)
"""
could not perform #{action} because changeset is invalid.
Errors
#{pretty errors}
Applied changes
#{pretty changes}
Params
#{pretty changeset.params}
Changeset
#{pretty changeset}
"""
end
defp pretty(term) do
inspect(term, pretty: true)
|> String.split("\n")
|> Enum.map_join("\n", &" " <> &1)
end
defp extract_changes(%Ecto.Changeset{changes: changes}) do
Enum.reduce(changes, %{}, fn({key, value}, acc) ->
case value do
%Ecto.Changeset{action: :delete} -> acc
_ -> Map.put(acc, key, extract_changes(value))
end
end)
end
defp extract_changes([%Ecto.Changeset{action: :delete} | tail]),
do: extract_changes(tail)
defp extract_changes([%Ecto.Changeset{} = changeset | tail]),
do: [extract_changes(changeset) | extract_changes(tail)]
defp extract_changes(other),
do: other
end
defmodule Ecto.CastError do
@moduledoc """
Raised when a changeset can't cast a value.
"""
defexception [:message, :type, :value]
def exception(opts) do
type = Keyword.fetch!(opts, :type)
value = Keyword.fetch!(opts, :value)
msg = opts[:message] || "cannot cast #{inspect value} to #{inspect type}"
%__MODULE__{message: msg, type: type, value: value}
end
end
defmodule Ecto.InvalidURLError do
defexception [:message, :url]
def exception(opts) do
url = Keyword.fetch!(opts, :url)
msg = Keyword.fetch!(opts, :message)
msg = "invalid url #{url}, #{msg}"
%__MODULE__{message: msg, url: url}
end
end
defmodule Ecto.NoPrimaryKeyFieldError do
@moduledoc """
Raised at runtime when an operation that requires a primary key is invoked
with a schema that does not define a primary key by using `@primary_key false`
"""
defexception [:message, :schema]
def exception(opts) do
schema = Keyword.fetch!(opts, :schema)
message = "schema `#{inspect schema}` has no primary key"
%__MODULE__{message: message, schema: schema}
end
end
defmodule Ecto.NoPrimaryKeyValueError do
@moduledoc """
Raised at runtime when an operation that requires a primary key is invoked
with a schema missing value for its primary key
"""
defexception [:message, :struct]
def exception(opts) do
struct = Keyword.fetch!(opts, :struct)
message = "struct `#{inspect struct}` is missing primary key value"
%__MODULE__{message: message, struct: struct}
end
end
defmodule Ecto.ChangeError do
defexception [:message]
end
defmodule Ecto.NoResultsError do
defexception [:message]
def exception(opts) do
query = Keyword.fetch!(opts, :queryable) |> Ecto.Queryable.to_query
msg = """
expected at least one result but got none in query:
#{Inspect.Ecto.Query.to_string(query)}
"""
%__MODULE__{message: msg}
end
end
defmodule Ecto.MultipleResultsError do
defexception [:message]
def exception(opts) do
query = Keyword.fetch!(opts, :queryable) |> Ecto.Queryable.to_query
count = Keyword.fetch!(opts, :count)
msg = """
expected at most one result but got #{count} in query:
#{Inspect.Ecto.Query.to_string(query)}
"""
%__MODULE__{message: msg}
end
end
defmodule Ecto.MultiplePrimaryKeyError do
defexception [:message]
def exception(opts) do
operation = Keyword.fetch!(opts, :operation)
source = Keyword.fetch!(opts, :source)
params = Keyword.fetch!(opts, :params)
count = Keyword.fetch!(opts, :count)
msg = """
expected #{operation} on #{source} to return at most one entry but got #{count} entries.
This typically means the field(s) set as primary_key in your schema/source
are not enough to uniquely identify entries in the repository.
Those are the parameters sent to the repository:
#{inspect params}
"""
%__MODULE__{message: msg}
end
end
defmodule Ecto.MigrationError do
defexception [:message]
end
defmodule Ecto.StaleEntryError do
defexception [:message]
def exception(opts) do
action = Keyword.fetch!(opts, :action)
struct = Keyword.fetch!(opts, :struct)
msg = """
attempted to #{action} a stale struct:
#{inspect struct}
"""
%__MODULE__{message: msg}
end
end
defmodule Ecto.ConstraintError do
defexception [:type, :constraint, :message]
def exception(opts) do
type = Keyword.fetch!(opts, :type)
constraint = Keyword.fetch!(opts, :constraint)
changeset = Keyword.fetch!(opts, :changeset)
action = Keyword.fetch!(opts, :action)
constraints =
case changeset.constraints do
[] ->
"The changeset has not defined any constraint."
constraints ->
"The changeset defined the following constraints:\n\n" <>
Enum.map_join(constraints, "\n", &" * #{&1.constraint} (#{&1.type}_constraint)")
end
msg = """
constraint error when attempting to #{action} struct:
* #{constraint} (#{type}_constraint)
If you would like to stop this constraint violation from raising an
exception and instead add it as an error to your changeset, please
call `#{type}_constraint/3` on your changeset with the constraint
`:name` as an option.
#{constraints}
"""
%__MODULE__{message: msg, type: type, constraint: constraint}
end
end
| 24.557003 | 95 | 0.661228 |
79a729cd734d7e86c9c416ff9c09148d3e597e02 | 1,102 | exs | Elixir | elixir/test/homework_web/schema/mutation/update_merchant_test.exs | ztoolson/web-homework | 09865a5df66fe8f380dfe0d848bbfae8398be1ef | [
"MIT"
] | null | null | null | elixir/test/homework_web/schema/mutation/update_merchant_test.exs | ztoolson/web-homework | 09865a5df66fe8f380dfe0d848bbfae8398be1ef | [
"MIT"
] | null | null | null | elixir/test/homework_web/schema/mutation/update_merchant_test.exs | ztoolson/web-homework | 09865a5df66fe8f380dfe0d848bbfae8398be1ef | [
"MIT"
] | null | null | null | defmodule HomeworkWeb.Schema.Query.UpdateMerchantTest do
use HomeworkWeb.ConnCase, async: true
alias Homework.Repo
alias Homework.Merchants.Merchant
@query """
mutation Update($id: ID!, $name: Name!, $description: Description!) {
updateMerchant(id: $id, name: $name, description: $description) {
id
name
description
}
}
"""
test "updateMerchant field updates a merchant successfully" do
merchant =
Repo.insert!(%Merchant{
description: "Exotic Animal Zoo",
name: "Greater Wynnewood Exotic Animal Park"
})
conn = build_conn()
conn =
post(conn, "/graphiql",
query: @query,
variables: %{
id: merchant.id,
name: "G.W. Zoo",
description: merchant.description
}
)
assert json_response(conn, 200) == %{
"data" => %{
"updateMerchant" => %{
"id" => merchant.id,
"name" => "G.W. Zoo",
"description" => "Exotic Animal Zoo"
}
}
}
end
end
| 23.956522 | 71 | 0.534483 |
79a72ce2441aaa359c6742e88baf4d41a1f50bee | 374 | exs | Elixir | test/backends_test.exs | am-kantox/envio | ebcd4647b10265054267839fad8e31e25b3ec0e4 | [
"MIT"
] | 12 | 2018-07-25T08:38:05.000Z | 2020-05-16T07:29:11.000Z | test/backends_test.exs | am-kantox/envio | ebcd4647b10265054267839fad8e31e25b3ec0e4 | [
"MIT"
] | 6 | 2018-07-26T17:09:44.000Z | 2021-10-19T06:39:44.000Z | test/backends_test.exs | am-kantox/envio | ebcd4647b10265054267839fad8e31e25b3ec0e4 | [
"MIT"
] | null | null | null | defmodule Envio.Backends.Test do
use ExUnit.Case, async: true
doctest Envio.Backends
test "#pub_sub with registry" do
Spitter.Registry.spit(:backends, %{bar: 42, pid: self()})
assert_receive :on_envio_called, 1_000
end
test "#pub_sub with pg2" do
Spitter.PG2.spit("main", %{bar: 42, pid: self()})
assert_receive :on_envio_called, 1_000
end
end
| 24.933333 | 61 | 0.697861 |
79a7312d9c21c576011e084f2a24d02990a0ff1d | 672 | exs | Elixir | test/fixtures/delegate_bench.exs | hrzndhrn/benchee_dsl | a6061e751fdd625147fdd320dd6ef3dedb903b30 | [
"MIT"
] | 3 | 2020-07-18T11:02:23.000Z | 2021-06-24T12:32:56.000Z | test/fixtures/delegate_bench.exs | hrzndhrn/benchee_dsl | a6061e751fdd625147fdd320dd6ef3dedb903b30 | [
"MIT"
] | 6 | 2020-05-02T15:32:26.000Z | 2020-10-22T11:33:08.000Z | test/fixtures/delegate_bench.exs | hrzndhrn/benchee_dsl | a6061e751fdd625147fdd320dd6ef3dedb903b30 | [
"MIT"
] | 1 | 2020-10-22T11:06:05.000Z | 2020-10-22T11:06:05.000Z | defmodule Foo do
def flat_map(a, b) do
a |> data(b) |> Enum.flat_map(&map_fun/1)
end
def map_flatten(a, b) do
a |> data(b) |> Enum.map(&map_fun/1) |> List.flatten()
end
def data(a, b), do: Enum.to_list(a..b)
def map_fun(i), do: [i, i * i]
end
defmodule Foo.Bar.Baz do
import Foo
def flat_map(a, b) do
a |> data(b) |> Enum.flat_map(&map_fun/1)
end
end
defmodule DelegateBench do
use BencheeDsl.Benchmark
import Foo
inputs %{
"small" => [1, 100],
"medium" => [1, 10_000],
"bigger" => [1, 100_000]
}
job &flat_map/2
job &map_flatten/2, as: :mf
# credo:disable-for-next-line
job &Foo.Bar.Baz.flat_map/2
end
| 16.390244 | 58 | 0.602679 |
79a7936fbefbcf0bfb37b1aac99b2e63f24275f4 | 1,558 | ex | Elixir | web/web.ex | bionikspoon/classroom-dashboard | c324eeab568335591daf83ae0bdd9a60d25f4595 | [
"MIT"
] | null | null | null | web/web.ex | bionikspoon/classroom-dashboard | c324eeab568335591daf83ae0bdd9a60d25f4595 | [
"MIT"
] | null | null | null | web/web.ex | bionikspoon/classroom-dashboard | c324eeab568335591daf83ae0bdd9a60d25f4595 | [
"MIT"
] | null | null | null | defmodule Dashboard.Web do
@moduledoc """
A module that keeps using definitions for controllers,
views and so on.
This can be used in your application as:
use Dashboard.Web, :controller
use Dashboard.Web, :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.
"""
def model do
quote do
use Ecto.Schema
import Ecto
import Ecto.Changeset
import Ecto.Query
end
end
def controller do
quote do
use Phoenix.Controller
alias Dashboard.Repo
import Ecto
import Ecto.Query
import Dashboard.Router.Helpers
import Dashboard.Gettext
end
end
def view do
quote do
use Phoenix.View, root: "web/templates"
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1]
import Dashboard.Router.Helpers
import Dashboard.ErrorHelpers
import Dashboard.Gettext
end
end
def router do
quote do
use Phoenix.Router
end
end
def channel do
quote do
use Phoenix.Channel
alias Dashboard.Repo
import Ecto
import Ecto.Query
import Dashboard.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
| 19.721519 | 88 | 0.672657 |
79a799d84bcca0d1de214aedffdcf8a1ab7df03d | 2,123 | exs | Elixir | test/liblink/socket/sendmsg/send_state_test.exs | Xerpa/liblink | 7b983431c5b391bb8cf182edd9ca4937601eea35 | [
"Apache-2.0"
] | 3 | 2018-10-26T12:55:15.000Z | 2019-05-03T22:41:34.000Z | test/liblink/socket/sendmsg/send_state_test.exs | Xerpa/liblink | 7b983431c5b391bb8cf182edd9ca4937601eea35 | [
"Apache-2.0"
] | 4 | 2018-08-26T14:43:57.000Z | 2020-09-23T21:14:56.000Z | test/liblink/socket/sendmsg/send_state_test.exs | Xerpa/liblink | 7b983431c5b391bb8cf182edd9ca4937601eea35 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 (c) Xerpa
#
# 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 Liblink.Socket.Sendmsg.SendStateTest do
use ExUnit.Case, async: true
alias Liblink.Nif
alias Liblink.Timeout
alias Liblink.Socket.Device
alias Liblink.Socket.Sendmsg.Fsm
alias Liblink.Socket.Sendmsg.InitState
alias Liblink.Socket.Sendmsg.SendState
alias Liblink.Socket.Sendmsg.TermState
import Liblink.Random
setup do
{:ok, router} =
Nif.new_socket(
:router,
"@" <> random_inproc_endpoint(),
random_inproc_endpoint(),
self()
)
device = %Device{socket: router}
{InitState, data} = Fsm.new()
{:cont, :ok, {SendState, data}} = InitState.attach(device, data)
on_exit(fn ->
Nif.term(router)
end)
{:ok, [data: data]}
end
test "can't attach", %{data: data} do
assert {:cont, {:error, :badstate}, {SendState, _}} = SendState.attach(%Device{}, data)
end
test "can halt", %{data: data} do
assert {:halt, :ok, {TermState, _}} = SendState.halt(data)
end
test "sendmsg without deadline", %{data: data} do
assert {:cont, :ok, {SendState, _}} = SendState.sendmsg(["foobar"], :infinity, data)
end
test "sendmsg with valid deadline", %{data: data} do
deadline = Timeout.deadline(1, :second)
assert {:cont, :ok, {SendState, _}} = SendState.sendmsg(["foobar"], deadline, data)
end
test "sendmsg with expired deadline", %{data: data} do
deadline = Timeout.deadline(-1, :second)
assert {:cont, {:error, :timeout}, {SendState, _}} =
SendState.sendmsg(["foobar"], deadline, data)
end
end
| 29.082192 | 91 | 0.672162 |
79a79d826c4ff6b03e90141b19b391bb1161a261 | 1,927 | ex | Elixir | lib/jsonrpc2/object.ex | arpnetwork/jsonrpc2_ex | b94a26ab207bede74502452bb53d4a25d82e039f | [
"Apache-2.0"
] | 3 | 2018-08-13T13:12:19.000Z | 2018-09-21T16:31:31.000Z | lib/jsonrpc2/object.ex | arpnetwork/jsonrpc2_ex | b94a26ab207bede74502452bb53d4a25d82e039f | [
"Apache-2.0"
] | null | null | null | lib/jsonrpc2/object.ex | arpnetwork/jsonrpc2_ex | b94a26ab207bede74502452bb53d4a25d82e039f | [
"Apache-2.0"
] | null | null | null | defmodule JSONRPC2.Object do
@moduledoc """
JSON RPC Object.
"""
alias JSONRPC2.Misc
@doc """
Returns `true` if `term` is an `id`; otherwise returns `false`.
## Examples
iex> alias JSONRPC2.Object
iex> Object.is_id("123")
true
iex> Object.is_id(123)
true
iex> Object.is_id(:undefined)
false
"""
defguard is_id(term) when is_binary(term) or is_integer(term)
@doc """
Returns `true` if `term` is a `params`; otherwise returns `false`.
## Examples
iex> alias JSONRPC2.Object
iex> Object.is_params(["123"])
true
iex> Object.is_params(%{name: "123"})
true
iex> Object.is_params("123")
false
"""
defguard is_params(term) when is_list(term) or is_map(term)
@doc """
Decodes a JSON encoded string into the JSON RPC object/objects.
"""
def decode(data, as) when is_binary(data) do
case Poison.decode(data) do
{:ok, value} ->
if Misc.all?(value, &is_map/1) do
{:ok, Misc.map(value, &transform(&1, as))}
else
{:error, :invalid}
end
_ ->
{:error, :parse_error}
end
end
@doc """
Encodes the JSON RPC object/objects into a JSON encoded string.
"""
def encode!(term) do
term
|> Misc.map(&strip/1)
|> Poison.encode!()
end
@doc """
Transforms a map as a JSON RPC object.
"""
def transform(value, as) when is_map(value) do
trans = fn {key, default}, acc ->
value =
Map.get_lazy(value, Atom.to_string(key), fn ->
Map.get(value, key, default)
end)
Map.put(acc, key, value)
end
fields =
as
|> struct()
|> Map.from_struct()
|> Enum.reduce(%{}, trans)
struct(as, fields)
end
defp strip(%{__struct__: _} = obj) do
obj
|> Map.from_struct()
|> Stream.reject(&(elem(&1, 1) == :undefined))
|> Enum.into(%{})
end
end
| 20.72043 | 68 | 0.568241 |
79a7b331d54d7a3fa4792c164c69e12fd2daa106 | 1,056 | exs | Elixir | clients/sts/test/test_helper.exs | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/sts/test/test_helper.exs | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/sts/test/test_helper.exs | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"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.
ExUnit.start()
defmodule GoogleApi.STS.TestHelper do
defmacro __using__(opts) do
quote do
use ExUnit.Case, unquote(opts)
import GoogleApi.STS.TestHelper
end
end
def for_scope(scopes) when is_list(scopes), do: for_scope(Enum.join(scopes, " "))
def for_scope(scope) do
{:ok, token} = Goth.Token.for_scope(scope)
token.token
end
end
| 29.333333 | 83 | 0.736742 |
79a7b972f93e873e7d16439f31e8a974837a6c2f | 1,806 | exs | Elixir | rel/config/config.exs | glv/revista | 00ecb0780c62a5525155a773b959b169e0e0500d | [
"MIT"
] | 17 | 2019-01-31T18:33:09.000Z | 2022-01-18T12:38:49.000Z | rel/config/config.exs | glv/revista | 00ecb0780c62a5525155a773b959b169e0e0500d | [
"MIT"
] | null | null | null | rel/config/config.exs | glv/revista | 00ecb0780c62a5525155a773b959b169e0e0500d | [
"MIT"
] | 4 | 2018-11-10T01:56:17.000Z | 2020-06-09T21:10:41.000Z | use Mix.Config
defmodule Revista.ConfigHelpers do
@moduledoc false
def integer_var(varname, default \\ 1) do
case System.get_env(varname) do
nil -> default
val -> String.to_integer(val)
end
end
end
alias Revista.ConfigHelpers
# Set Configuration
admin = %{
port: ConfigHelpers.integer_var("ADMIN_PORT", 4001),
secret_key_base: System.get_env("ADMIN_SECRET_KEY_BASE")
}
auth = %{
pool_size: ConfigHelpers.integer_var("AUTH_POOL_SIZE", 10),
database_url: System.get_env("AUTH_DATABASE_URL")
}
cms = %{
pool_size: ConfigHelpers.integer_var("CMS_POOL_SIZE", 10),
database_url: System.get_env("CMS_DATABASE_URL")
}
twitter = %{
bearer_token: System.get_env("TWITTER_BEARER_TOKEN"),
port: ConfigHelpers.integer_var("TWITTER_PORT", 4002),
screen_name: System.get_env("TWITTER_SCREEN_NAME"),
secret_key_base: System.get_env("TWITTER_SECRET_KEY_BASE")
}
web = %{
port: ConfigHelpers.integer_var("WEB_PORT", 4003),
secret_key_base: System.get_env("WEB_SECRET_KEY_BASE")
}
# Apply Configuration
config :admin, Admin.Endpoint,
http: [:inet6, port: admin[:port]],
url: [host: "localhost", port: admin[:port]],
secret_key_base: admin[:secret_key_base]
config :auth, Auth.Repo,
url: auth[:database_url],
pool_size: auth[:pool_size]
config :cms, CMS.Repo,
url: cms[:database_url],
pool_size: cms[:pool_size]
config :twitter, Twitter.Endpoint,
http: [:inet6, port: twitter[:port]],
url: [host: "localhost", port: twitter[:port]],
secret_key_base: twitter[:secret_key_base]
config :twitter, Twitter.HTTPClient,
bearer_token: twitter[:bearer_token],
screen_name: twitter[:screen_name]
config :web, Web.Endpoint,
http: [:inet6, port: web[:port]],
url: [host: "localhost", port: web[:port]],
secret_key_base: web[:secret_key_base]
| 24.739726 | 61 | 0.725914 |
79a7ca99c512b2a5f5714a72e99ec1afa052ad41 | 1,370 | exs | Elixir | mix.exs | michaelst/surface_bulma | d978480c3eae32dd64ac83172babf17dad19e071 | [
"MIT"
] | null | null | null | mix.exs | michaelst/surface_bulma | d978480c3eae32dd64ac83172babf17dad19e071 | [
"MIT"
] | null | null | null | mix.exs | michaelst/surface_bulma | d978480c3eae32dd64ac83172babf17dad19e071 | [
"MIT"
] | null | null | null | defmodule SurfaceBulma.MixProject do
use Mix.Project
@source_url "https://github.com/surface-ui/surface_bulma"
@version "0.1.0"
def project do
[
app: :surface_bulma,
description: "A set of simple Surface components based on Bulma.",
version: @version,
elixir: "~> 1.9",
elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod,
compilers: [:phoenix] ++ Mix.compilers(),
deps: deps(),
aliases: aliases(),
package: package()
]
end
def application do
[
extra_applications: [:logger]
]
end
def catalogues do
[
"priv/catalogue",
"deps/surface/priv/catalogue"
]
end
defp elixirc_paths(:dev), do: ["lib"] ++ catalogues()
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
defp deps do
[
{:ex_doc, ">= 0.0.0", only: :dev, runtime: false},
{:floki, "~> 0.25.0", only: :test},
{:jason, "~> 1.0"},
{:surface_catalogue, "~> 0.0.1", only: :dev},
{:surface_font_awesome, "~> 0.1.1"},
{:surface, "~> 0.2.1"}
]
end
defp aliases do
[
dev: "run --no-halt dev.exs"
]
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "priv"],
licenses: ["MIT"],
links: %{"GitHub" => @source_url}
]
end
end
| 21.40625 | 72 | 0.551095 |
79a7f207935ce7e2daea9424f0079a3fc9caf3c4 | 1,895 | ex | Elixir | clients/container_analysis/lib/google_api/container_analysis/v1beta1/model/list_note_occurrences_response.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/container_analysis/lib/google_api/container_analysis/v1beta1/model/list_note_occurrences_response.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/container_analysis/lib/google_api/container_analysis/v1beta1/model/list_note_occurrences_response.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.ContainerAnalysis.V1beta1.Model.ListNoteOccurrencesResponse do
@moduledoc """
Response for listing occurrences for a note.
## Attributes
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Token to provide to skip to a particular spot in the list.
* `occurrences` (*type:* `list(GoogleApi.ContainerAnalysis.V1beta1.Model.Occurrence.t)`, *default:* `nil`) - The occurrences attached to the specified note.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:nextPageToken => String.t(),
:occurrences => list(GoogleApi.ContainerAnalysis.V1beta1.Model.Occurrence.t())
}
field(:nextPageToken)
field(:occurrences, as: GoogleApi.ContainerAnalysis.V1beta1.Model.Occurrence, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.ContainerAnalysis.V1beta1.Model.ListNoteOccurrencesResponse do
def decode(value, options) do
GoogleApi.ContainerAnalysis.V1beta1.Model.ListNoteOccurrencesResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ContainerAnalysis.V1beta1.Model.ListNoteOccurrencesResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 37.9 | 160 | 0.75409 |
79a81481f089d0e85ef505f1f75dfa16102704cc | 1,339 | ex | Elixir | lib/surface/components/form/multiple_select.ex | lnr0626/surface | 11ae4a8cfa167fc11c8f960e9d5821a057c9b5bb | [
"MIT"
] | 1 | 2021-06-04T20:46:52.000Z | 2021-06-04T20:46:52.000Z | lib/surface/components/form/multiple_select.ex | lnr0626/surface | 11ae4a8cfa167fc11c8f960e9d5821a057c9b5bb | [
"MIT"
] | null | null | null | lib/surface/components/form/multiple_select.ex | lnr0626/surface | 11ae4a8cfa167fc11c8f960e9d5821a057c9b5bb | [
"MIT"
] | null | null | null | defmodule Surface.Components.Form.MultipleSelect do
@moduledoc """
Defines a select.
Provides a wrapper for Phoenix.HTML.Form's `multiple_select/4` function.
All options passed via `opts` will be sent to `multiple_select/4`, `class` can
be set directly and will override anything in `opts`.
"""
use Surface.Component
import Phoenix.HTML.Form, only: [multiple_select: 4]
import Surface.Components.Form.Utils
alias Surface.Components.Form.Input.InputContext
@doc "The form identifier"
prop form, :form
@doc "The field name"
prop field, :string
@doc "The id of the corresponding select field"
prop id, :string
@doc "The name of the corresponding select field"
prop name, :string
@doc "The CSS class for the underlying tag"
prop class, :css_class
@doc "The options in the select"
prop options, :any, default: []
@doc "The default selected option"
prop selected, :any
@doc "Options list"
prop opts, :keyword, default: []
def render(assigns) do
helper_opts = props_to_opts(assigns, [:selected])
attr_opts = props_to_attr_opts(assigns, class: get_config(:default_class))
~F"""
<InputContext assigns={assigns} :let={form: form, field: field}>
{multiple_select(form, field, @options, helper_opts ++ attr_opts ++ @opts)}
</InputContext>
"""
end
end
| 25.75 | 81 | 0.70351 |
79a8431f694604b9a1b449effbd6282c7165f12e | 4,654 | ex | Elixir | debian/manpage.sgml.ex | timmy00274672/demo_dh_make | 9a241f67131019911d07d41407c3240ff70c241a | [
"RSA-MD"
] | null | null | null | debian/manpage.sgml.ex | timmy00274672/demo_dh_make | 9a241f67131019911d07d41407c3240ff70c241a | [
"RSA-MD"
] | null | null | null | debian/manpage.sgml.ex | timmy00274672/demo_dh_make | 9a241f67131019911d07d41407c3240ff70c241a | [
"RSA-MD"
] | null | null | null | <!doctype refentry PUBLIC "-//OASIS//DTD DocBook V4.1//EN" [
<!-- Process this file with docbook-to-man to generate an nroff manual
page: `docbook-to-man manpage.sgml > manpage.1'. You may view
the manual page with: `docbook-to-man manpage.sgml | nroff -man |
less'. A typical entry in a Makefile or Makefile.am is:
manpage.1: manpage.sgml
docbook-to-man $< > $@
The docbook-to-man binary is found in the docbook-to-man package.
Please remember that if you create the nroff version in one of the
debian/rules file targets (such as build), you will need to include
docbook-to-man in your Build-Depends control field.
-->
<!-- Fill in your name for FIRSTNAME and SURNAME. -->
<!ENTITY dhfirstname "<firstname>FIRSTNAME</firstname>">
<!ENTITY dhsurname "<surname>SURNAME</surname>">
<!-- Please adjust the date whenever revising the manpage. -->
<!ENTITY dhdate "<date>February 14 2020</date>">
<!-- SECTION should be 1-8, maybe w/ subsection other parameters are
allowed: see man(7), man(1). -->
<!ENTITY dhsection "<manvolnum>SECTION</manvolnum>">
<!ENTITY dhemail "<email>[email protected]</email>">
<!ENTITY dhusername "bmc">
<!ENTITY dhucpackage "<refentrytitle>Helloworld</refentrytitle>">
<!ENTITY dhpackage "helloworld">
<!ENTITY debian "<productname>Debian</productname>">
<!ENTITY gnu "<acronym>GNU</acronym>">
<!ENTITY gpl "&gnu; <acronym>GPL</acronym>">
]>
<refentry>
<refentryinfo>
<address>
&dhemail;
</address>
<author>
&dhfirstname;
&dhsurname;
</author>
<copyright>
<year>2003</year>
<holder>&dhusername;</holder>
</copyright>
&dhdate;
</refentryinfo>
<refmeta>
&dhucpackage;
&dhsection;
</refmeta>
<refnamediv>
<refname>&dhpackage;</refname>
<refpurpose>program to do something</refpurpose>
</refnamediv>
<refsynopsisdiv>
<cmdsynopsis>
<command>&dhpackage;</command>
<arg><option>-e <replaceable>this</replaceable></option></arg>
<arg><option>--example <replaceable>that</replaceable></option></arg>
</cmdsynopsis>
</refsynopsisdiv>
<refsect1>
<title>DESCRIPTION</title>
<para>This manual page documents briefly the
<command>&dhpackage;</command> and <command>bar</command>
commands.</para>
<para>This manual page was written for the &debian; distribution
because the original program does not have a manual page.
Instead, it has documentation in the &gnu;
<application>Info</application> format; see below.</para>
<para><command>&dhpackage;</command> is a program that...</para>
</refsect1>
<refsect1>
<title>OPTIONS</title>
<para>These programs follow the usual &gnu; command line syntax,
with long options starting with two dashes (`-'). A summary of
options is included below. For a complete description, see the
<application>Info</application> files.</para>
<variablelist>
<varlistentry>
<term><option>-h</option>
<option>--help</option>
</term>
<listitem>
<para>Show summary of options.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-v</option>
<option>--version</option>
</term>
<listitem>
<para>Show version of program.</para>
</listitem>
</varlistentry>
</variablelist>
</refsect1>
<refsect1>
<title>SEE ALSO</title>
<para>bar (1), baz (1).</para>
<para>The programs are documented fully by <citetitle>The Rise and
Fall of a Fooish Bar</citetitle> available via the
<application>Info</application> system.</para>
</refsect1>
<refsect1>
<title>AUTHOR</title>
<para>This manual page was written by &dhusername; &dhemail; for
the &debian; system (and may be used by others). Permission is
granted to copy, distribute and/or modify this document under
the terms of the &gnu; General Public License, Version 2 any
later version published by the Free Software Foundation.
</para>
<para>
On Debian systems, the complete text of the GNU General Public
License can be found in /usr/share/common-licenses/GPL.
</para>
</refsect1>
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:2
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:nil
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
-->
| 30.025806 | 75 | 0.658358 |
79a84e7ad3432abc418629cfc3fc1dd0d4e195f2 | 5,736 | ex | Elixir | lib/pow/plug/base.ex | patrickbiermann/pow | ebc2ac7d6e15961dac4be38091ff75dae0d26554 | [
"MIT"
] | 4 | 2018-05-07T16:37:15.000Z | 2018-07-14T00:44:12.000Z | lib/pow/plug/base.ex | patrickbiermann/pow | ebc2ac7d6e15961dac4be38091ff75dae0d26554 | [
"MIT"
] | null | null | null | lib/pow/plug/base.ex | patrickbiermann/pow | ebc2ac7d6e15961dac4be38091ff75dae0d26554 | [
"MIT"
] | null | null | null | defmodule Pow.Plug.Base do
@moduledoc """
This plug macro will set `:pow_config` as private, and attempt to fetch and
assign a user in the connection if it has not already been assigned. The user
will be assigned automatically in any of the operations.
Any writes to backend store or client should occur in `:before_send` callback
as defined in `Plug.Conn`. To ensure that the callbacks are called in the
order they were set, a `register_before_send/2` method is used to set
callbacks instead of `Plug.Conn.register_before_send/2`.
## Configuration options
* `:credentials_cache_store` - the credentials cache store. This value defaults to
`{Pow.Store.CredentialsCache, backend: Pow.Store.Backend.EtsCache}`. The
`Pow.Store.Backend.EtsCache` backend store can be changed with the
`:cache_store_backend` option.
* `:cache_store_backend` - the backend cache store. This value defaults to
`Pow.Store.Backend.EtsCache`.
## Example
defmodule MyAppWeb.Pow.CustomPlug do
use Pow.Plug.Base
@impl true
def fetch(conn, _config) do
user = fetch_user_from_cookie(conn)
{conn, user}
end
@impl true
def create(conn, user, _config) do
conn = update_cookie(conn, user)
{conn, user}
end
@impl true
def delete(conn, _config) do
delete_cookie(conn)
end
end
"""
alias Plug.Conn
alias Pow.{Config, Plug, Store.Backend.EtsCache, Store.CredentialsCache}
@callback init(Config.t()) :: Config.t()
@callback call(Conn.t(), Config.t()) :: Conn.t()
@callback fetch(Conn.t(), Config.t()) :: {Conn.t(), map() | nil}
@callback create(Conn.t(), map(), Config.t()) :: {Conn.t(), map()}
@callback delete(Conn.t(), Config.t()) :: Conn.t()
@doc false
defmacro __using__(_opts) do
quote do
@behaviour unquote(__MODULE__)
@before_send_private_key String.to_atom(Macro.underscore(__MODULE__) <> "/before_send")
import unquote(__MODULE__)
@doc false
@impl true
def init(config), do: config
@doc """
Configures the connection for Pow, and fetches user.
If no options have been passed to the plug, the existing configuration
will be pulled with `Pow.Plug.fetch_config/1`
`:plug` is appended to the passed configuration, so the current plug will
be used in any subsequent calls to create, update and delete user
credentials from the connection. The configuration is then set for the
conn with `Pow.Plug.put_config/2`.
If a user can't be fetched with `Pow.Plug.current_user/2`, `do_fetch/2`
will be called.
"""
@impl true
def call(conn, []), do: call(conn, Plug.fetch_config(conn))
def call(conn, config) do
config = put_plug(config)
conn = Plug.put_config(conn, config)
conn
|> Plug.current_user(config)
|> maybe_fetch_user(conn, config)
|> Conn.register_before_send(fn conn ->
conn.private
|> Map.get(@before_send_private_key, [])
|> Enum.reduce(conn, & &1.(&2))
end)
end
defp register_before_send(conn, callback) do
callbacks = Map.get(conn.private, @before_send_private_key, []) ++ [callback]
Conn.put_private(conn, @before_send_private_key, callbacks)
end
defp put_plug(config) do
config
|> Config.put(:plug, __MODULE__)
|> Config.put(:mod, __MODULE__) # TODO: Remove by 1.1.0, this is only for backwards compability
end
@doc """
Calls `fetch/2` and assigns the current user to the conn.
The user is assigned to the conn with `Pow.Plug.assign_current_user/3`.
"""
def do_fetch(conn, config) do
conn
|> fetch(config)
|> assign_current_user(config)
end
@doc """
Calls `create/3` and assigns the current user.
The user is assigned to the conn with `Pow.Plug.assign_current_user/3`.
"""
def do_create(conn, user, config) do
conn
|> create(user, config)
|> assign_current_user(config)
end
@doc """
Calls `delete/2` and removes the current user assigned to the conn.
The user assigned is removed from the conn with
`Pow.Plug.assign_current_user/3`.
"""
def do_delete(conn, config) do
conn
|> delete(config)
|> remove_current_user(config)
end
defp maybe_fetch_user(nil, conn, config), do: do_fetch(conn, config)
defp maybe_fetch_user(_user, conn, _config), do: conn
defp assign_current_user({conn, user}, config), do: Plug.assign_current_user(conn, user, config)
defp remove_current_user(conn, config), do: Plug.assign_current_user(conn, nil, config)
defoverridable unquote(__MODULE__)
end
end
@spec store(Config.t()) :: {module(), Config.t()}
def store(config) do
config
|> Config.get(:credentials_cache_store)
|> Kernel.||(fallback_store(config))
|> case do
{store, store_config} -> {store, store_opts(config, store_config)}
nil -> {CredentialsCache, store_opts(config)}
end
end
# TODO: Remove by 1.1.0
defp fallback_store(config) do
case Config.get(config, :session_store) do
nil ->
nil
value ->
IO.warn("use of `:session_store` config value is deprecated, use `:credentials_cache_store` instead")
value
end
end
defp store_opts(config, store_config \\ []) do
store_config
|> Keyword.put_new(:backend, Config.get(config, :cache_store_backend, EtsCache))
|> Keyword.put_new(:pow_config, config)
end
end
| 31.005405 | 109 | 0.639644 |
79a85252695d343b381815a72505baaaf946d7d6 | 85,704 | ex | Elixir | lib/elixir/lib/string.ex | donaldww/elixir | 62fb3a62de182beb99de8c969cbee0d2c22d628a | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/string.ex | donaldww/elixir | 62fb3a62de182beb99de8c969cbee0d2c22d628a | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/string.ex | donaldww/elixir | 62fb3a62de182beb99de8c969cbee0d2c22d628a | [
"Apache-2.0"
] | null | null | null | import Kernel, except: [length: 1]
defmodule String do
@moduledoc ~S"""
Strings in Elixir are UTF-8 encoded binaries.
Strings in Elixir are a sequence of Unicode characters,
typically written between double quoted strings, such
as `"hello"` and `"héllò"`.
In case a string must have a double-quote in itself,
the double quotes must be escaped with a backslash,
for example: `"this is a string with \"double quotes\""`.
You can concatenate two strings with the `<>/2` operator:
iex> "hello" <> " " <> "world"
"hello world"
The functions in this module act according to
[The Unicode Standard, Version 14.0.0](http://www.unicode.org/versions/Unicode14.0.0/).
## Interpolation
Strings in Elixir also support interpolation. This allows
you to place some value in the middle of a string by using
the `#{}` syntax:
iex> name = "joe"
iex> "hello #{name}"
"hello joe"
Any Elixir expression is valid inside the interpolation.
If a string is given, the string is interpolated as is.
If any other value is given, Elixir will attempt to convert
it to a string using the `String.Chars` protocol. This
allows, for example, to output an integer from the interpolation:
iex> "2 + 2 = #{2 + 2}"
"2 + 2 = 4"
In case the value you want to interpolate cannot be
converted to a string, because it doesn't have an human
textual representation, a protocol error will be raised.
## Escape characters
Besides allowing double-quotes to be escaped with a backslash,
strings also support the following escape characters:
* `\a` - Bell
* `\b` - Backspace
* `\t` - Horizontal tab
* `\n` - Line feed (New lines)
* `\v` - Vertical tab
* `\f` - Form feed
* `\r` - Carriage return
* `\e` - Command Escape
* `\#` - Returns the `#` character itself, skipping interpolation
* `\xNN` - A byte represented by the hexadecimal `NN`
* `\uNNNN` - A Unicode code point represented by `NNNN`
Note it is generally not advised to use `\xNN` in Elixir
strings, as introducing an invalid byte sequence would
make the string invalid. If you have to introduce a
character by its hexadecimal representation, it is best
to work with Unicode code points, such as `\uNNNN`. In fact,
understanding Unicode code points can be essential when doing
low-level manipulations of string, so let's explore them in
detail next.
## Unicode and code points
In order to facilitate meaningful communication between computers
across multiple languages, a standard is required so that the ones
and zeros on one machine mean the same thing when they are transmitted
to another. The Unicode Standard acts as an official registry of
virtually all the characters we know: this includes characters from
classical and historical texts, emoji, and formatting and control
characters as well.
Unicode organizes all of the characters in its repertoire into code
charts, and each character is given a unique numerical index. This
numerical index is known as a Code Point.
In Elixir you can use a `?` in front of a character literal to reveal
its code point:
iex> ?a
97
iex> ?ł
322
Note that most Unicode code charts will refer to a code point by its
hexadecimal (hex) representation, e.g. `97` translates to `0061` in hex,
and we can represent any Unicode character in an Elixir string by
using the `\u` escape character followed by its code point number:
iex> "\u0061" === "a"
true
iex> 0x0061 = 97 = ?a
97
The hex representation will also help you look up information about a
code point, e.g. [https://codepoints.net/U+0061](https://codepoints.net/U+0061)
has a data sheet all about the lower case `a`, a.k.a. code point 97.
Remember you can get the hex presentation of a number by calling
`Integer.to_string/2`:
iex> Integer.to_string(?a, 16)
"61"
## UTF-8 encoded and encodings
Now that we understand what the Unicode standard is and what code points
are, we can finally talk about encodings. Whereas the code point is **what**
we store, an encoding deals with **how** we store it: encoding is an
implementation. In other words, we need a mechanism to convert the code
point numbers into bytes so they can be stored in memory, written to disk, etc.
Elixir uses UTF-8 to encode its strings, which means that code points are
encoded as a series of 8-bit bytes. UTF-8 is a **variable width** character
encoding that uses one to four bytes to store each code point. It is capable
of encoding all valid Unicode code points. Let's see an example:
iex> string = "héllo"
"héllo"
iex> String.length(string)
5
iex> byte_size(string)
6
Although the string above has 5 characters, it uses 6 bytes, as two bytes
are used to represent the character `é`.
## Grapheme clusters
This module also works with the concept of grapheme cluster
(from now on referenced as graphemes). Graphemes can consist
of multiple code points that may be perceived as a single character
by readers. For example, "é" can be represented either as a single
"e with acute" code point, as seen above in the string `"héllo"`,
or as the letter "e" followed by a "combining acute accent"
(two code points):
iex> string = "\u0065\u0301"
"é"
iex> byte_size(string)
3
iex> String.length(string)
1
iex> String.codepoints(string)
["e", "́"]
iex> String.graphemes(string)
["é"]
Although it looks visually the same as before, the example above
is made of two characters, it is perceived by users as one.
Graphemes can also be two characters that are interpreted as one
by some languages. For example, some languages may consider "ch"
as a single character. However, since this information depends on
the locale, it is not taken into account by this module.
In general, the functions in this module rely on the Unicode
Standard, but do not contain any of the locale specific behaviour.
More information about graphemes can be found in the [Unicode
Standard Annex #29](https://www.unicode.org/reports/tr29/).
For converting a binary to a different encoding and for Unicode
normalization mechanisms, see Erlang's `:unicode` module.
## String and binary operations
To act according to the Unicode Standard, many functions
in this module run in linear time, as they need to traverse
the whole string considering the proper Unicode code points.
For example, `String.length/1` will take longer as
the input grows. On the other hand, `Kernel.byte_size/1` always runs
in constant time (i.e. regardless of the input size).
This means often there are performance costs in using the
functions in this module, compared to the more low-level
operations that work directly with binaries:
* `Kernel.binary_part/3` - retrieves part of the binary
* `Kernel.bit_size/1` and `Kernel.byte_size/1` - size related functions
* `Kernel.is_bitstring/1` and `Kernel.is_binary/1` - type-check function
* Plus a number of functions for working with binaries (bytes)
in the [`:binary` module](`:binary`)
A `utf8` modifier is also available inside the binary syntax `<<>>`.
It can be used to match code points out of a binary/string:
iex> <<eacute::utf8>> = "é"
iex> eacute
233
You can also fully convert a string into a list of integer code points,
known as "charlists" in Elixir, by calling `String.to_charlist/1`:
iex> String.to_charlist("héllo")
[104, 233, 108, 108, 111]
If you would rather see the underlying bytes of a string, instead of
its codepoints, a common trick is to concatenate the null byte `<<0>>`
to it:
iex> "héllo" <> <<0>>
<<104, 195, 169, 108, 108, 111, 0>>
Alternatively, you can view a string's binary representation by
passing an option to `IO.inspect/2`:
iex> IO.inspect("héllo", binaries: :as_binaries)
<<104, 195, 169, 108, 108, 111>>
## Self-synchronization
The UTF-8 encoding is self-synchronizing. This means that
if malformed data (i.e., data that is not possible according
to the definition of the encoding) is encountered, only one
code point needs to be rejected.
This module relies on this behaviour to ignore such invalid
characters. For example, `length/1` will return
a correct result even if an invalid code point is fed into it.
In other words, this module expects invalid data to be detected
elsewhere, usually when retrieving data from the external source.
For example, a driver that reads strings from a database will be
responsible to check the validity of the encoding. `String.chunk/2`
can be used for breaking a string into valid and invalid parts.
## Compile binary patterns
Many functions in this module work with patterns. For example,
`String.split/3` can split a string into multiple strings given
a pattern. This pattern can be a string, a list of strings or
a compiled pattern:
iex> String.split("foo bar", " ")
["foo", "bar"]
iex> String.split("foo bar!", [" ", "!"])
["foo", "bar", ""]
iex> pattern = :binary.compile_pattern([" ", "!"])
iex> String.split("foo bar!", pattern)
["foo", "bar", ""]
The compiled pattern is useful when the same match will
be done over and over again. Note though that the compiled
pattern cannot be stored in a module attribute as the pattern
is generated at runtime and does not survive compile time.
"""
@typedoc """
A UTF-8 encoded binary.
The types `String.t()` and `binary()` are equivalent to analysis tools.
Although, for those reading the documentation, `String.t()` implies
it is a UTF-8 encoded binary.
"""
@type t :: binary
@typedoc "A single Unicode code point encoded in UTF-8. It may be one or more bytes."
@type codepoint :: t
@typedoc "Multiple code points that may be perceived as a single character by readers"
@type grapheme :: t
@typedoc """
Pattern used in functions like `replace/4` and `split/3`.
It must be one of:
* a string
* an empty list
* a list containing non-empty strings
* a compiled search pattern created by `:binary.compile_pattern/1`
"""
# TODO: Replace "nonempty_binary :: <<_::8, _::_*8>>" with "nonempty_binary()"
# when minimum requirement is >= OTP 24.
@type pattern ::
t()
| [nonempty_binary :: <<_::8, _::_*8>>]
| (compiled_search_pattern :: :binary.cp())
@conditional_mappings [:greek, :turkic]
@doc """
Checks if a string contains only printable characters up to `character_limit`.
Takes an optional `character_limit` as a second argument. If `character_limit` is `0`, this
function will return `true`.
## Examples
iex> String.printable?("abc")
true
iex> String.printable?("abc" <> <<0>>)
false
iex> String.printable?("abc" <> <<0>>, 2)
true
iex> String.printable?("abc" <> <<0>>, 0)
true
"""
@spec printable?(t, 0) :: true
@spec printable?(t, pos_integer | :infinity) :: boolean
def printable?(string, character_limit \\ :infinity)
when is_binary(string) and
(character_limit == :infinity or
(is_integer(character_limit) and character_limit >= 0)) do
recur_printable?(string, character_limit)
end
defp recur_printable?(_string, 0), do: true
defp recur_printable?(<<>>, _character_limit), do: true
for char <- 0x20..0x7E do
defp recur_printable?(<<unquote(char), rest::binary>>, character_limit) do
recur_printable?(rest, decrement(character_limit))
end
end
for char <- '\n\r\t\v\b\f\e\d\a' do
defp recur_printable?(<<unquote(char), rest::binary>>, character_limit) do
recur_printable?(rest, decrement(character_limit))
end
end
defp recur_printable?(<<char::utf8, rest::binary>>, character_limit)
when char in 0xA0..0xD7FF
when char in 0xE000..0xFFFD
when char in 0x10000..0x10FFFF do
recur_printable?(rest, decrement(character_limit))
end
defp recur_printable?(_string, _character_limit) do
false
end
defp decrement(:infinity), do: :infinity
defp decrement(character_limit), do: character_limit - 1
@doc ~S"""
Divides a string into substrings at each Unicode whitespace
occurrence with leading and trailing whitespace ignored. Groups
of whitespace are treated as a single occurrence. Divisions do
not occur on non-breaking whitespace.
## Examples
iex> String.split("foo bar")
["foo", "bar"]
iex> String.split("foo" <> <<194, 133>> <> "bar")
["foo", "bar"]
iex> String.split(" foo bar ")
["foo", "bar"]
iex> String.split("no\u00a0break")
["no\u00a0break"]
"""
@spec split(t) :: [t]
defdelegate split(binary), to: String.Break
@doc ~S"""
Divides a string into parts based on a pattern.
Returns a list of these parts.
The `pattern` may be a string, a list of strings, a regular expression, or a
compiled pattern.
The string is split into as many parts as possible by
default, but can be controlled via the `:parts` option.
Empty strings are only removed from the result if the
`:trim` option is set to `true`.
When the pattern used is a regular expression, the string is
split using `Regex.split/3`.
## Options
* `:parts` (positive integer or `:infinity`) - the string
is split into at most as many parts as this option specifies.
If `:infinity`, the string will be split into all possible
parts. Defaults to `:infinity`.
* `:trim` (boolean) - if `true`, empty strings are removed from
the resulting list.
This function also accepts all options accepted by `Regex.split/3`
if `pattern` is a regular expression.
## Examples
Splitting with a string pattern:
iex> String.split("a,b,c", ",")
["a", "b", "c"]
iex> String.split("a,b,c", ",", parts: 2)
["a", "b,c"]
iex> String.split(" a b c ", " ", trim: true)
["a", "b", "c"]
A list of patterns:
iex> String.split("1,2 3,4", [" ", ","])
["1", "2", "3", "4"]
A regular expression:
iex> String.split("a,b,c", ~r{,})
["a", "b", "c"]
iex> String.split("a,b,c", ~r{,}, parts: 2)
["a", "b,c"]
iex> String.split(" a b c ", ~r{\s}, trim: true)
["a", "b", "c"]
iex> String.split("abc", ~r{b}, include_captures: true)
["a", "b", "c"]
A compiled pattern:
iex> pattern = :binary.compile_pattern([" ", ","])
iex> String.split("1,2 3,4", pattern)
["1", "2", "3", "4"]
Splitting on empty string returns graphemes:
iex> String.split("abc", "")
["", "a", "b", "c", ""]
iex> String.split("abc", "", trim: true)
["a", "b", "c"]
iex> String.split("abc", "", parts: 1)
["abc"]
iex> String.split("abc", "", parts: 3)
["", "a", "bc"]
Be aware that this function can split within or across grapheme boundaries.
For example, take the grapheme "é" which is made of the characters
"e" and the acute accent. The following will split the string into two parts:
iex> String.split(String.normalize("é", :nfd), "e")
["", "́"]
However, if "é" is represented by the single character "e with acute"
accent, then it will split the string into just one part:
iex> String.split(String.normalize("é", :nfc), "e")
["é"]
"""
@spec split(t, pattern | Regex.t(), keyword) :: [t]
def split(string, pattern, options \\ [])
def split(string, %Regex{} = pattern, options) when is_binary(string) and is_list(options) do
Regex.split(pattern, string, options)
end
def split(string, "", options) when is_binary(string) and is_list(options) do
parts = Keyword.get(options, :parts, :infinity)
index = parts_to_index(parts)
trim = Keyword.get(options, :trim, false)
if trim == false and index != 1 do
["" | split_empty(string, trim, index - 1)]
else
split_empty(string, trim, index)
end
end
def split(string, [], options) when is_binary(string) and is_list(options) do
if string == "" and Keyword.get(options, :trim, false) do
[]
else
[string]
end
end
def split(string, pattern, options) when is_binary(string) and is_list(options) do
parts = Keyword.get(options, :parts, :infinity)
trim = Keyword.get(options, :trim, false)
case {parts, trim} do
{:infinity, false} ->
:binary.split(string, pattern, [:global])
{:infinity, true} ->
:binary.split(string, pattern, [:global, :trim_all])
{2, false} ->
:binary.split(string, pattern)
_ ->
pattern = maybe_compile_pattern(pattern)
split_each(string, pattern, trim, parts_to_index(parts))
end
end
defp parts_to_index(:infinity), do: 0
defp parts_to_index(n) when is_integer(n) and n > 0, do: n
defp split_empty("", true, 1), do: []
defp split_empty(string, _, 1), do: [string]
defp split_empty(string, trim, count) do
case :unicode_util.gc(string) do
[gc] -> [grapheme_to_binary(gc) | split_empty(<<>>, trim, count - 1)]
[gc | rest] -> [grapheme_to_binary(gc) | split_empty(rest, trim, count - 1)]
[] -> split_empty("", trim, 1)
{:error, <<byte, rest::bits>>} -> [<<byte>> | split_empty(rest, trim, count - 1)]
end
end
defp split_each("", _pattern, true, 1), do: []
defp split_each(string, _pattern, _trim, 1) when is_binary(string), do: [string]
defp split_each(string, pattern, trim, count) do
case do_splitter(string, pattern, trim) do
{h, t} -> [h | split_each(t, pattern, trim, count - 1)]
nil -> []
end
end
@doc """
Returns an enumerable that splits a string on demand.
This is in contrast to `split/3` which splits the
entire string upfront.
This function does not support regular expressions
by design. When using regular expressions, it is often
more efficient to have the regular expressions traverse
the string at once than in parts, like this function does.
## Options
* :trim - when `true`, does not emit empty patterns
## Examples
iex> String.splitter("1,2 3,4 5,6 7,8,...,99999", [" ", ","]) |> Enum.take(4)
["1", "2", "3", "4"]
iex> String.splitter("abcd", "") |> Enum.take(10)
["", "a", "b", "c", "d", ""]
iex> String.splitter("abcd", "", trim: true) |> Enum.take(10)
["a", "b", "c", "d"]
A compiled pattern can also be given:
iex> pattern = :binary.compile_pattern([" ", ","])
iex> String.splitter("1,2 3,4 5,6 7,8,...,99999", pattern) |> Enum.take(4)
["1", "2", "3", "4"]
"""
@spec splitter(t, pattern, keyword) :: Enumerable.t()
def splitter(string, pattern, options \\ [])
def splitter(string, "", options) when is_binary(string) and is_list(options) do
if Keyword.get(options, :trim, false) do
Stream.unfold(string, &next_grapheme/1)
else
Stream.unfold(:match, &do_empty_splitter(&1, string))
end
end
def splitter(string, [], options) when is_binary(string) and is_list(options) do
if string == "" and Keyword.get(options, :trim, false) do
Stream.duplicate(string, 0)
else
Stream.duplicate(string, 1)
end
end
def splitter(string, pattern, options) when is_binary(string) and is_list(options) do
pattern = maybe_compile_pattern(pattern)
trim = Keyword.get(options, :trim, false)
Stream.unfold(string, &do_splitter(&1, pattern, trim))
end
defp do_empty_splitter(:match, string), do: {"", string}
defp do_empty_splitter(:nomatch, _string), do: nil
defp do_empty_splitter("", _), do: {"", :nomatch}
defp do_empty_splitter(string, _), do: next_grapheme(string)
defp do_splitter(:nomatch, _pattern, _), do: nil
defp do_splitter("", _pattern, false), do: {"", :nomatch}
defp do_splitter("", _pattern, true), do: nil
defp do_splitter(bin, pattern, trim) do
case :binary.split(bin, pattern) do
["", second] when trim -> do_splitter(second, pattern, trim)
[first, second] -> {first, second}
[first] -> {first, :nomatch}
end
end
defp maybe_compile_pattern(pattern) when is_tuple(pattern), do: pattern
defp maybe_compile_pattern(pattern), do: :binary.compile_pattern(pattern)
@doc """
Splits a string into two at the specified offset. When the offset given is
negative, location is counted from the end of the string.
The offset is capped to the length of the string. Returns a tuple with
two elements.
Note: keep in mind this function splits on graphemes and for such it
has to linearly traverse the string. If you want to split a string or
a binary based on the number of bytes, use `Kernel.binary_part/3`
instead.
## Examples
iex> String.split_at("sweetelixir", 5)
{"sweet", "elixir"}
iex> String.split_at("sweetelixir", -6)
{"sweet", "elixir"}
iex> String.split_at("abc", 0)
{"", "abc"}
iex> String.split_at("abc", 1000)
{"abc", ""}
iex> String.split_at("abc", -1000)
{"", "abc"}
"""
@spec split_at(t, integer) :: {t, t}
def split_at(string, position)
def split_at(string, position)
when is_binary(string) and is_integer(position) and position >= 0 do
do_split_at(string, position)
end
def split_at(string, position)
when is_binary(string) and is_integer(position) and position < 0 do
position = length(string) + position
case position >= 0 do
true -> do_split_at(string, position)
false -> {"", string}
end
end
defp do_split_at(string, position) do
remaining = byte_size_remaining_at(string, position)
start = byte_size(string) - remaining
<<left::size(start)-binary, right::size(remaining)-binary>> = string
{left, right}
end
@doc ~S"""
Returns `true` if `string1` is canonically equivalent to `string2`.
It performs Normalization Form Canonical Decomposition (NFD) on the
strings before comparing them. This function is equivalent to:
String.normalize(string1, :nfd) == String.normalize(string2, :nfd)
If you plan to compare multiple strings, multiple times in a row, you
may normalize them upfront and compare them directly to avoid multiple
normalization passes.
## Examples
iex> String.equivalent?("abc", "abc")
true
iex> String.equivalent?("man\u0303ana", "mañana")
true
iex> String.equivalent?("abc", "ABC")
false
iex> String.equivalent?("nø", "nó")
false
"""
@spec equivalent?(t, t) :: boolean
def equivalent?(string1, string2) when is_binary(string1) and is_binary(string2) do
normalize(string1, :nfd) == normalize(string2, :nfd)
end
@doc """
Converts all characters in `string` to Unicode normalization
form identified by `form`.
Invalid Unicode codepoints are skipped and the remaining of
the string is converted. If you want the algorithm to stop
and return on invalid codepoint, use `:unicode.characters_to_nfd_binary/1`,
`:unicode.characters_to_nfc_binary/1`, `:unicode.characters_to_nfkd_binary/1`,
and `:unicode.characters_to_nfkc_binary/1` instead.
Normalization forms `:nfkc` and `:nfkd` should not be blindly applied
to arbitrary text. Because they erase many formatting distinctions,
they will prevent round-trip conversion to and from many legacy
character sets.
## Forms
The supported forms are:
* `:nfd` - Normalization Form Canonical Decomposition.
Characters are decomposed by canonical equivalence, and
multiple combining characters are arranged in a specific
order.
* `:nfc` - Normalization Form Canonical Composition.
Characters are decomposed and then recomposed by canonical equivalence.
* `:nfkd` - Normalization Form Compatibility Decomposition.
Characters are decomposed by compatibility equivalence, and
multiple combining characters are arranged in a specific
order.
* `:nfkc` - Normalization Form Compatibility Composition.
Characters are decomposed and then recomposed by compatibility equivalence.
## Examples
iex> String.normalize("yêṩ", :nfd)
"yêṩ"
iex> String.normalize("leña", :nfc)
"leña"
iex> String.normalize("fi", :nfkd)
"fi"
iex> String.normalize("fi", :nfkc)
"fi"
"""
def normalize(string, form)
def normalize(string, :nfd) when is_binary(string) do
case :unicode.characters_to_nfd_binary(string) do
string when is_binary(string) -> string
{:error, good, <<head, rest::binary>>} -> good <> <<head>> <> normalize(rest, :nfd)
end
end
def normalize(string, :nfc) when is_binary(string) do
case :unicode.characters_to_nfc_binary(string) do
string when is_binary(string) -> string
{:error, good, <<head, rest::binary>>} -> good <> <<head>> <> normalize(rest, :nfc)
end
end
def normalize(string, :nfkd) when is_binary(string) do
case :unicode.characters_to_nfkd_binary(string) do
string when is_binary(string) -> string
{:error, good, <<head, rest::binary>>} -> good <> <<head>> <> normalize(rest, :nfkd)
end
end
def normalize(string, :nfkc) when is_binary(string) do
case :unicode.characters_to_nfkc_binary(string) do
string when is_binary(string) -> string
{:error, good, <<head, rest::binary>>} -> good <> <<head>> <> normalize(rest, :nfkc)
end
end
@doc """
Converts all characters in the given string to uppercase according to `mode`.
`mode` may be `:default`, `:ascii`, `:greek` or `:turkic`. The `:default` mode considers
all non-conditional transformations outlined in the Unicode standard. `:ascii`
uppercases only the letters a to z. `:greek` includes the context sensitive
mappings found in Greek. `:turkic` properly handles the letter i with the dotless variant.
## Examples
iex> String.upcase("abcd")
"ABCD"
iex> String.upcase("ab 123 xpto")
"AB 123 XPTO"
iex> String.upcase("olá")
"OLÁ"
The `:ascii` mode ignores Unicode characters and provides a more
performant implementation when you know the string contains only
ASCII characters:
iex> String.upcase("olá", :ascii)
"OLá"
And `:turkic` properly handles the letter i with the dotless variant:
iex> String.upcase("ıi")
"II"
iex> String.upcase("ıi", :turkic)
"Iİ"
"""
@spec upcase(t, :default | :ascii | :greek | :turkic) :: t
def upcase(string, mode \\ :default)
def upcase("", _mode) do
""
end
def upcase(string, :default) when is_binary(string) do
String.Unicode.upcase(string, [], :default)
end
def upcase(string, :ascii) when is_binary(string) do
IO.iodata_to_binary(upcase_ascii(string))
end
def upcase(string, mode) when is_binary(string) and mode in @conditional_mappings do
String.Unicode.upcase(string, [], mode)
end
defp upcase_ascii(<<char, rest::bits>>) when char >= ?a and char <= ?z,
do: [char - 32 | upcase_ascii(rest)]
defp upcase_ascii(<<char, rest::bits>>), do: [char | upcase_ascii(rest)]
defp upcase_ascii(<<>>), do: []
@doc """
Converts all characters in the given string to lowercase according to `mode`.
`mode` may be `:default`, `:ascii`, `:greek` or `:turkic`. The `:default` mode considers
all non-conditional transformations outlined in the Unicode standard. `:ascii`
lowercases only the letters A to Z. `:greek` includes the context sensitive
mappings found in Greek. `:turkic` properly handles the letter i with the dotless variant.
## Examples
iex> String.downcase("ABCD")
"abcd"
iex> String.downcase("AB 123 XPTO")
"ab 123 xpto"
iex> String.downcase("OLÁ")
"olá"
The `:ascii` mode ignores Unicode characters and provides a more
performant implementation when you know the string contains only
ASCII characters:
iex> String.downcase("OLÁ", :ascii)
"olÁ"
The `:greek` mode properly handles the context sensitive sigma in Greek:
iex> String.downcase("ΣΣ")
"σσ"
iex> String.downcase("ΣΣ", :greek)
"σς"
And `:turkic` properly handles the letter i with the dotless variant:
iex> String.downcase("Iİ")
"ii̇"
iex> String.downcase("Iİ", :turkic)
"ıi"
"""
@spec downcase(t, :default | :ascii | :greek | :turkic) :: t
def downcase(string, mode \\ :default)
def downcase("", _mode) do
""
end
def downcase(string, :default) when is_binary(string) do
String.Unicode.downcase(string, [], :default)
end
def downcase(string, :ascii) when is_binary(string) do
IO.iodata_to_binary(downcase_ascii(string))
end
def downcase(string, mode) when is_binary(string) and mode in @conditional_mappings do
String.Unicode.downcase(string, [], mode)
end
defp downcase_ascii(<<char, rest::bits>>) when char >= ?A and char <= ?Z,
do: [char + 32 | downcase_ascii(rest)]
defp downcase_ascii(<<char, rest::bits>>), do: [char | downcase_ascii(rest)]
defp downcase_ascii(<<>>), do: []
@doc """
Converts the first character in the given string to
uppercase and the remainder to lowercase according to `mode`.
`mode` may be `:default`, `:ascii`, `:greek` or `:turkic`. The `:default` mode considers
all non-conditional transformations outlined in the Unicode standard. `:ascii`
capitalizes only the letters A to Z. `:greek` includes the context sensitive
mappings found in Greek. `:turkic` properly handles the letter i with the dotless variant.
## Examples
iex> String.capitalize("abcd")
"Abcd"
iex> String.capitalize("fin")
"Fin"
iex> String.capitalize("olá")
"Olá"
"""
@spec capitalize(t, :default | :ascii | :greek | :turkic) :: t
def capitalize(string, mode \\ :default)
def capitalize(<<char, rest::binary>>, :ascii) do
char = if char >= ?a and char <= ?z, do: char - 32, else: char
<<char>> <> downcase(rest, :ascii)
end
def capitalize(string, mode) when is_binary(string) do
{char, rest} = String.Unicode.titlecase_once(string, mode)
char <> downcase(rest, mode)
end
@doc false
@deprecated "Use String.trim_trailing/1 instead"
defdelegate rstrip(binary), to: String.Break, as: :trim_trailing
@doc false
@deprecated "Use String.trim_trailing/2 with a binary as second argument instead"
def rstrip(string, char) when is_integer(char) do
replace_trailing(string, <<char::utf8>>, "")
end
@doc """
Replaces all leading occurrences of `match` by `replacement` of `match` in `string`.
Returns the string untouched if there are no occurrences.
If `match` is `""`, this function raises an `ArgumentError` exception: this
happens because this function replaces **all** the occurrences of `match` at
the beginning of `string`, and it's impossible to replace "multiple"
occurrences of `""`.
## Examples
iex> String.replace_leading("hello world", "hello ", "")
"world"
iex> String.replace_leading("hello hello world", "hello ", "")
"world"
iex> String.replace_leading("hello world", "hello ", "ola ")
"ola world"
iex> String.replace_leading("hello hello world", "hello ", "ola ")
"ola ola world"
This function can replace across grapheme boundaries. See `replace/3`
for more information and examples.
"""
@spec replace_leading(t, t, t) :: t
def replace_leading(string, match, replacement)
when is_binary(string) and is_binary(match) and is_binary(replacement) do
if match == "" do
raise ArgumentError, "cannot use an empty string as the match to replace"
end
prefix_size = byte_size(match)
suffix_size = byte_size(string) - prefix_size
replace_leading(string, match, replacement, prefix_size, suffix_size, 0)
end
defp replace_leading(string, match, replacement, prefix_size, suffix_size, acc)
when suffix_size >= 0 do
case string do
<<prefix::size(prefix_size)-binary, suffix::binary>> when prefix == match ->
replace_leading(
suffix,
match,
replacement,
prefix_size,
suffix_size - prefix_size,
acc + 1
)
_ ->
prepend_unless_empty(duplicate(replacement, acc), string)
end
end
defp replace_leading(string, _match, replacement, _prefix_size, _suffix_size, acc) do
prepend_unless_empty(duplicate(replacement, acc), string)
end
@doc """
Replaces all trailing occurrences of `match` by `replacement` in `string`.
Returns the string untouched if there are no occurrences.
If `match` is `""`, this function raises an `ArgumentError` exception: this
happens because this function replaces **all** the occurrences of `match` at
the end of `string`, and it's impossible to replace "multiple" occurrences of
`""`.
## Examples
iex> String.replace_trailing("hello world", " world", "")
"hello"
iex> String.replace_trailing("hello world world", " world", "")
"hello"
iex> String.replace_trailing("hello world", " world", " mundo")
"hello mundo"
iex> String.replace_trailing("hello world world", " world", " mundo")
"hello mundo mundo"
This function can replace across grapheme boundaries. See `replace/3`
for more information and examples.
"""
@spec replace_trailing(t, t, t) :: t
def replace_trailing(string, match, replacement)
when is_binary(string) and is_binary(match) and is_binary(replacement) do
if match == "" do
raise ArgumentError, "cannot use an empty string as the match to replace"
end
suffix_size = byte_size(match)
prefix_size = byte_size(string) - suffix_size
replace_trailing(string, match, replacement, prefix_size, suffix_size, 0)
end
defp replace_trailing(string, match, replacement, prefix_size, suffix_size, acc)
when prefix_size >= 0 do
case string do
<<prefix::size(prefix_size)-binary, suffix::binary>> when suffix == match ->
replace_trailing(
prefix,
match,
replacement,
prefix_size - suffix_size,
suffix_size,
acc + 1
)
_ ->
append_unless_empty(string, duplicate(replacement, acc))
end
end
defp replace_trailing(string, _match, replacement, _prefix_size, _suffix_size, acc) do
append_unless_empty(string, duplicate(replacement, acc))
end
@doc """
Replaces prefix in `string` by `replacement` if it matches `match`.
Returns the string untouched if there is no match. If `match` is an empty
string (`""`), `replacement` is just prepended to `string`.
## Examples
iex> String.replace_prefix("world", "hello ", "")
"world"
iex> String.replace_prefix("hello world", "hello ", "")
"world"
iex> String.replace_prefix("hello hello world", "hello ", "")
"hello world"
iex> String.replace_prefix("world", "hello ", "ola ")
"world"
iex> String.replace_prefix("hello world", "hello ", "ola ")
"ola world"
iex> String.replace_prefix("hello hello world", "hello ", "ola ")
"ola hello world"
iex> String.replace_prefix("world", "", "hello ")
"hello world"
This function can replace across grapheme boundaries. See `replace/3`
for more information and examples.
"""
@spec replace_prefix(t, t, t) :: t
def replace_prefix(string, match, replacement)
when is_binary(string) and is_binary(match) and is_binary(replacement) do
prefix_size = byte_size(match)
case string do
<<prefix::size(prefix_size)-binary, suffix::binary>> when prefix == match ->
prepend_unless_empty(replacement, suffix)
_ ->
string
end
end
@doc """
Replaces suffix in `string` by `replacement` if it matches `match`.
Returns the string untouched if there is no match. If `match` is an empty
string (`""`), `replacement` is just appended to `string`.
## Examples
iex> String.replace_suffix("hello", " world", "")
"hello"
iex> String.replace_suffix("hello world", " world", "")
"hello"
iex> String.replace_suffix("hello world world", " world", "")
"hello world"
iex> String.replace_suffix("hello", " world", " mundo")
"hello"
iex> String.replace_suffix("hello world", " world", " mundo")
"hello mundo"
iex> String.replace_suffix("hello world world", " world", " mundo")
"hello world mundo"
iex> String.replace_suffix("hello", "", " world")
"hello world"
This function can replace across grapheme boundaries. See `replace/3`
for more information and examples.
"""
@spec replace_suffix(t, t, t) :: t
def replace_suffix(string, match, replacement)
when is_binary(string) and is_binary(match) and is_binary(replacement) do
suffix_size = byte_size(match)
prefix_size = byte_size(string) - suffix_size
case string do
<<prefix::size(prefix_size)-binary, suffix::binary>> when suffix == match ->
append_unless_empty(prefix, replacement)
_ ->
string
end
end
@compile {:inline, prepend_unless_empty: 2, append_unless_empty: 2}
defp prepend_unless_empty("", suffix), do: suffix
defp prepend_unless_empty(prefix, suffix), do: prefix <> suffix
defp append_unless_empty(prefix, ""), do: prefix
defp append_unless_empty(prefix, suffix), do: prefix <> suffix
@doc false
@deprecated "Use String.trim_leading/1 instead"
defdelegate lstrip(binary), to: String.Break, as: :trim_leading
@doc false
@deprecated "Use String.trim_leading/2 with a binary as second argument instead"
def lstrip(string, char) when is_integer(char) do
replace_leading(string, <<char::utf8>>, "")
end
@doc false
@deprecated "Use String.trim/1 instead"
def strip(string) do
trim(string)
end
@doc false
@deprecated "Use String.trim/2 with a binary second argument instead"
def strip(string, char) do
trim(string, <<char::utf8>>)
end
@doc ~S"""
Returns a string where all leading Unicode whitespaces
have been removed.
## Examples
iex> String.trim_leading("\n abc ")
"abc "
"""
@spec trim_leading(t) :: t
defdelegate trim_leading(string), to: String.Break
@doc """
Returns a string where all leading `to_trim` characters have been removed.
## Examples
iex> String.trim_leading("__ abc _", "_")
" abc _"
iex> String.trim_leading("1 abc", "11")
"1 abc"
"""
@spec trim_leading(t, t) :: t
def trim_leading(string, to_trim)
when is_binary(string) and is_binary(to_trim) do
replace_leading(string, to_trim, "")
end
@doc ~S"""
Returns a string where all trailing Unicode whitespaces
has been removed.
## Examples
iex> String.trim_trailing(" abc\n ")
" abc"
"""
@spec trim_trailing(t) :: t
defdelegate trim_trailing(string), to: String.Break
@doc """
Returns a string where all trailing `to_trim` characters have been removed.
## Examples
iex> String.trim_trailing("_ abc __", "_")
"_ abc "
iex> String.trim_trailing("abc 1", "11")
"abc 1"
"""
@spec trim_trailing(t, t) :: t
def trim_trailing(string, to_trim)
when is_binary(string) and is_binary(to_trim) do
replace_trailing(string, to_trim, "")
end
@doc ~S"""
Returns a string where all leading and trailing Unicode whitespaces
have been removed.
## Examples
iex> String.trim("\n abc\n ")
"abc"
"""
@spec trim(t) :: t
def trim(string) when is_binary(string) do
string
|> trim_leading()
|> trim_trailing()
end
@doc """
Returns a string where all leading and trailing `to_trim` characters have been
removed.
## Examples
iex> String.trim("a abc a", "a")
" abc "
"""
@spec trim(t, t) :: t
def trim(string, to_trim) when is_binary(string) and is_binary(to_trim) do
string
|> trim_leading(to_trim)
|> trim_trailing(to_trim)
end
@doc ~S"""
Returns a new string padded with a leading filler
which is made of elements from the `padding`.
Passing a list of strings as `padding` will take one element of the list
for every missing entry. If the list is shorter than the number of inserts,
the filling will start again from the beginning of the list.
Passing a string `padding` is equivalent to passing the list of graphemes in it.
If no `padding` is given, it defaults to whitespace.
When `count` is less than or equal to the length of `string`,
given `string` is returned.
Raises `ArgumentError` if the given `padding` contains a non-string element.
## Examples
iex> String.pad_leading("abc", 5)
" abc"
iex> String.pad_leading("abc", 4, "12")
"1abc"
iex> String.pad_leading("abc", 6, "12")
"121abc"
iex> String.pad_leading("abc", 5, ["1", "23"])
"123abc"
"""
@spec pad_leading(t, non_neg_integer, t | [t]) :: t
def pad_leading(string, count, padding \\ [" "])
def pad_leading(string, count, padding) when is_binary(padding) do
pad_leading(string, count, graphemes(padding))
end
def pad_leading(string, count, [_ | _] = padding)
when is_binary(string) and is_integer(count) and count >= 0 do
pad(:leading, string, count, padding)
end
@doc ~S"""
Returns a new string padded with a trailing filler
which is made of elements from the `padding`.
Passing a list of strings as `padding` will take one element of the list
for every missing entry. If the list is shorter than the number of inserts,
the filling will start again from the beginning of the list.
Passing a string `padding` is equivalent to passing the list of graphemes in it.
If no `padding` is given, it defaults to whitespace.
When `count` is less than or equal to the length of `string`,
given `string` is returned.
Raises `ArgumentError` if the given `padding` contains a non-string element.
## Examples
iex> String.pad_trailing("abc", 5)
"abc "
iex> String.pad_trailing("abc", 4, "12")
"abc1"
iex> String.pad_trailing("abc", 6, "12")
"abc121"
iex> String.pad_trailing("abc", 5, ["1", "23"])
"abc123"
"""
@spec pad_trailing(t, non_neg_integer, t | [t]) :: t
def pad_trailing(string, count, padding \\ [" "])
def pad_trailing(string, count, padding) when is_binary(padding) do
pad_trailing(string, count, graphemes(padding))
end
def pad_trailing(string, count, [_ | _] = padding)
when is_binary(string) and is_integer(count) and count >= 0 do
pad(:trailing, string, count, padding)
end
defp pad(kind, string, count, padding) do
string_length = length(string)
if string_length >= count do
string
else
filler = build_filler(count - string_length, padding, padding, 0, [])
case kind do
:leading -> [filler | string]
:trailing -> [string | filler]
end
|> IO.iodata_to_binary()
end
end
defp build_filler(0, _source, _padding, _size, filler), do: filler
defp build_filler(count, source, [], size, filler) do
rem_filler =
rem(count, size)
|> build_filler(source, source, 0, [])
filler =
filler
|> IO.iodata_to_binary()
|> duplicate(div(count, size) + 1)
[filler | rem_filler]
end
defp build_filler(count, source, [elem | rest], size, filler)
when is_binary(elem) do
build_filler(count - 1, source, rest, size + 1, [filler | elem])
end
defp build_filler(_count, _source, [elem | _rest], _size, _filler) do
raise ArgumentError, "expected a string padding element, got: #{inspect(elem)}"
end
@doc false
@deprecated "Use String.pad_leading/2 instead"
def rjust(subject, length) do
rjust(subject, length, ?\s)
end
@doc false
@deprecated "Use String.pad_leading/3 with a binary padding instead"
def rjust(subject, length, pad) when is_integer(pad) and is_integer(length) and length >= 0 do
pad(:leading, subject, length, [<<pad::utf8>>])
end
@doc false
@deprecated "Use String.pad_trailing/2 instead"
def ljust(subject, length) do
ljust(subject, length, ?\s)
end
@doc false
@deprecated "Use String.pad_trailing/3 with a binary padding instead"
def ljust(subject, length, pad) when is_integer(pad) and is_integer(length) and length >= 0 do
pad(:trailing, subject, length, [<<pad::utf8>>])
end
@doc ~S"""
Returns a new string created by replacing occurrences of `pattern` in
`subject` with `replacement`.
The `subject` is always a string.
The `pattern` may be a string, a list of strings, a regular expression, or a
compiled pattern.
The `replacement` may be a string or a function that receives the matched
pattern and must return the replacement as a string or iodata.
By default it replaces all occurrences but this behaviour can be controlled
through the `:global` option; see the "Options" section below.
## Options
* `:global` - (boolean) if `true`, all occurrences of `pattern` are replaced
with `replacement`, otherwise only the first occurrence is
replaced. Defaults to `true`
## Examples
iex> String.replace("a,b,c", ",", "-")
"a-b-c"
iex> String.replace("a,b,c", ",", "-", global: false)
"a-b,c"
The pattern may also be a list of strings and the replacement may also
be a function that receives the matches:
iex> String.replace("a,b,c", ["a", "c"], fn <<char>> -> <<char + 1>> end)
"b,b,d"
When the pattern is a regular expression, one can give `\N` or
`\g{N}` in the `replacement` string to access a specific capture in the
regular expression:
iex> String.replace("a,b,c", ~r/,(.)/, ",\\1\\g{1}")
"a,bb,cc"
Note that we had to escape the backslash escape character (i.e., we used `\\N`
instead of just `\N` to escape the backslash; same thing for `\\g{N}`). By
giving `\0`, one can inject the whole match in the replacement string.
A compiled pattern can also be given:
iex> pattern = :binary.compile_pattern(",")
iex> String.replace("a,b,c", pattern, "[]")
"a[]b[]c"
When an empty string is provided as a `pattern`, the function will treat it as
an implicit empty string between each grapheme and the string will be
interspersed. If an empty string is provided as `replacement` the `subject`
will be returned:
iex> String.replace("ELIXIR", "", ".")
".E.L.I.X.I.R."
iex> String.replace("ELIXIR", "", "")
"ELIXIR"
Be aware that this function can replace within or across grapheme boundaries.
For example, take the grapheme "é" which is made of the characters
"e" and the acute accent. The following will replace only the letter "e",
moving the accent to the letter "o":
iex> String.replace(String.normalize("é", :nfd), "e", "o")
"ó"
However, if "é" is represented by the single character "e with acute"
accent, then it won't be replaced at all:
iex> String.replace(String.normalize("é", :nfc), "e", "o")
"é"
"""
@spec replace(t, pattern | Regex.t(), t | (t -> t | iodata), keyword) :: t
def replace(subject, pattern, replacement, options \\ [])
when is_binary(subject) and
(is_binary(replacement) or is_function(replacement, 1)) and
is_list(options) do
replace_guarded(subject, pattern, replacement, options)
end
defp replace_guarded(subject, %{__struct__: Regex} = regex, replacement, options) do
Regex.replace(regex, subject, replacement, options)
end
defp replace_guarded(subject, "", "", _) do
subject
end
defp replace_guarded(subject, [], _, _) do
subject
end
defp replace_guarded(subject, "", replacement_binary, options)
when is_binary(replacement_binary) do
if Keyword.get(options, :global, true) do
intersperse_bin(subject, replacement_binary, [replacement_binary])
else
replacement_binary <> subject
end
end
defp replace_guarded(subject, "", replacement_fun, options) do
if Keyword.get(options, :global, true) do
intersperse_fun(subject, replacement_fun, [replacement_fun.("")])
else
IO.iodata_to_binary([replacement_fun.("") | subject])
end
end
defp replace_guarded(subject, pattern, replacement, options) do
if insert = Keyword.get(options, :insert_replaced) do
IO.warn(
"String.replace/4 with :insert_replaced option is deprecated. " <>
"Please use :binary.replace/4 instead or pass an anonymous function as replacement"
)
binary_options = if Keyword.get(options, :global) != false, do: [:global], else: []
:binary.replace(subject, pattern, replacement, [insert_replaced: insert] ++ binary_options)
else
matches =
if Keyword.get(options, :global, true) do
:binary.matches(subject, pattern)
else
case :binary.match(subject, pattern) do
:nomatch -> []
match -> [match]
end
end
IO.iodata_to_binary(do_replace(subject, matches, replacement, 0))
end
end
defp intersperse_bin(subject, replacement, acc) do
case :unicode_util.gc(subject) do
[current | rest] ->
intersperse_bin(rest, replacement, [replacement, current | acc])
[] ->
reverse_characters_to_binary(acc)
{:error, <<byte, rest::bits>>} ->
reverse_characters_to_binary(acc) <>
<<byte>> <> intersperse_bin(rest, replacement, [replacement])
end
end
defp intersperse_fun(subject, replacement, acc) do
case :unicode_util.gc(subject) do
[current | rest] ->
intersperse_fun(rest, replacement, [replacement.(""), current | acc])
[] ->
reverse_characters_to_binary(acc)
{:error, <<byte, rest::bits>>} ->
reverse_characters_to_binary(acc) <>
<<byte>> <> intersperse_fun(rest, replacement, [replacement.("")])
end
end
defp do_replace(subject, [], _, n) do
[binary_part(subject, n, byte_size(subject) - n)]
end
defp do_replace(subject, [{start, length} | matches], replacement, n) do
prefix = binary_part(subject, n, start - n)
middle =
if is_binary(replacement) do
replacement
else
replacement.(binary_part(subject, start, length))
end
[prefix, middle | do_replace(subject, matches, replacement, start + length)]
end
@doc ~S"""
Reverses the graphemes in given string.
## Examples
iex> String.reverse("abcd")
"dcba"
iex> String.reverse("hello world")
"dlrow olleh"
iex> String.reverse("hello ∂og")
"go∂ olleh"
Keep in mind reversing the same string twice does
not necessarily yield the original string:
iex> "̀e"
"̀e"
iex> String.reverse("̀e")
"è"
iex> String.reverse(String.reverse("̀e"))
"è"
In the first example the accent is before the vowel, so
it is considered two graphemes. However, when you reverse
it once, you have the vowel followed by the accent, which
becomes one grapheme. Reversing it again will keep it as
one single grapheme.
"""
@spec reverse(t) :: t
def reverse(string) when is_binary(string) do
do_reverse(:unicode_util.gc(string), [])
end
defp do_reverse([grapheme | rest], acc),
do: do_reverse(:unicode_util.gc(rest), [grapheme | acc])
defp do_reverse([], acc),
do: :unicode.characters_to_binary(acc)
defp do_reverse({:error, <<byte, rest::bits>>}, acc),
do: :unicode.characters_to_binary(acc) <> <<byte>> <> do_reverse(:unicode_util.gc(rest), [])
@doc """
Returns a string `subject` repeated `n` times.
Inlined by the compiler.
## Examples
iex> String.duplicate("abc", 0)
""
iex> String.duplicate("abc", 1)
"abc"
iex> String.duplicate("abc", 2)
"abcabc"
"""
@compile {:inline, duplicate: 2}
@spec duplicate(t, non_neg_integer) :: t
def duplicate(subject, n) when is_binary(subject) and is_integer(n) and n >= 0 do
:binary.copy(subject, n)
end
@doc ~S"""
Returns a list of code points encoded as strings.
To retrieve code points in their natural integer
representation, see `to_charlist/1`. For details about
code points and graphemes, see the `String` module
documentation.
## Examples
iex> String.codepoints("olá")
["o", "l", "á"]
iex> String.codepoints("оптими зации")
["о", "п", "т", "и", "м", "и", " ", "з", "а", "ц", "и", "и"]
iex> String.codepoints("ἅἪῼ")
["ἅ", "Ἢ", "ῼ"]
iex> String.codepoints("\u00e9")
["é"]
iex> String.codepoints("\u0065\u0301")
["e", "́"]
"""
@spec codepoints(t) :: [codepoint]
def codepoints(string) when is_binary(string) do
do_codepoints(string)
end
defp do_codepoints(<<codepoint::utf8, rest::bits>>) do
[<<codepoint::utf8>> | do_codepoints(rest)]
end
defp do_codepoints(<<byte, rest::bits>>) do
[<<byte>> | do_codepoints(rest)]
end
defp do_codepoints(<<>>), do: []
@doc ~S"""
Returns the next code point in a string.
The result is a tuple with the code point and the
remainder of the string or `nil` in case
the string reached its end.
As with other functions in the `String` module, `next_codepoint/1`
works with binaries that are invalid UTF-8. If the string starts
with a sequence of bytes that is not valid in UTF-8 encoding, the
first element of the returned tuple is a binary with the first byte.
## Examples
iex> String.next_codepoint("olá")
{"o", "lá"}
iex> invalid = "\x80\x80OK" # first two bytes are invalid in UTF-8
iex> {_, rest} = String.next_codepoint(invalid)
{<<128>>, <<128, 79, 75>>}
iex> String.next_codepoint(rest)
{<<128>>, "OK"}
## Comparison with binary pattern matching
Binary pattern matching provides a similar way to decompose
a string:
iex> <<codepoint::utf8, rest::binary>> = "Elixir"
"Elixir"
iex> codepoint
69
iex> rest
"lixir"
though not entirely equivalent because `codepoint` comes as
an integer, and the pattern won't match invalid UTF-8.
Binary pattern matching, however, is simpler and more efficient,
so pick the option that better suits your use case.
"""
@spec next_codepoint(t) :: {codepoint, t} | nil
def next_codepoint(<<cp::utf8, rest::binary>>), do: {<<cp::utf8>>, rest}
def next_codepoint(<<byte, rest::binary>>), do: {<<byte>>, rest}
def next_codepoint(<<>>), do: nil
@doc ~S"""
Checks whether `string` contains only valid characters.
## Examples
iex> String.valid?("a")
true
iex> String.valid?("ø")
true
iex> String.valid?(<<0xFFFF::16>>)
false
iex> String.valid?(<<0xEF, 0xB7, 0x90>>)
true
iex> String.valid?("asd" <> <<0xFFFF::16>>)
false
"""
@spec valid?(t) :: boolean
def valid?(string)
def valid?(<<string::binary>>), do: valid_utf8?(string)
def valid?(_), do: false
defp valid_utf8?(<<_::utf8, rest::bits>>), do: valid_utf8?(rest)
defp valid_utf8?(<<>>), do: true
defp valid_utf8?(_), do: false
@doc false
@deprecated "Use String.valid?/1 instead"
def valid_character?(string) do
case string do
<<_::utf8>> -> valid?(string)
_ -> false
end
end
@doc ~S"""
Splits the string into chunks of characters that share a common trait.
The trait can be one of two options:
* `:valid` - the string is split into chunks of valid and invalid
character sequences
* `:printable` - the string is split into chunks of printable and
non-printable character sequences
Returns a list of binaries each of which contains only one kind of
characters.
If the given string is empty, an empty list is returned.
## Examples
iex> String.chunk(<<?a, ?b, ?c, 0>>, :valid)
["abc\0"]
iex> String.chunk(<<?a, ?b, ?c, 0, 0xFFFF::utf16>>, :valid)
["abc\0", <<0xFFFF::utf16>>]
iex> String.chunk(<<?a, ?b, ?c, 0, 0x0FFFF::utf8>>, :printable)
["abc", <<0, 0x0FFFF::utf8>>]
"""
@spec chunk(t, :valid | :printable) :: [t]
def chunk(string, trait)
def chunk("", _), do: []
def chunk(string, trait) when is_binary(string) and trait in [:valid, :printable] do
{cp, _} = next_codepoint(string)
pred_fn = make_chunk_pred(trait)
do_chunk(string, pred_fn.(cp), pred_fn)
end
defp do_chunk(string, flag, pred_fn), do: do_chunk(string, [], <<>>, flag, pred_fn)
defp do_chunk(<<>>, acc, <<>>, _, _), do: Enum.reverse(acc)
defp do_chunk(<<>>, acc, chunk, _, _), do: Enum.reverse(acc, [chunk])
defp do_chunk(string, acc, chunk, flag, pred_fn) do
{cp, rest} = next_codepoint(string)
if pred_fn.(cp) != flag do
do_chunk(rest, [chunk | acc], cp, not flag, pred_fn)
else
do_chunk(rest, acc, chunk <> cp, flag, pred_fn)
end
end
defp make_chunk_pred(:valid), do: &valid?/1
defp make_chunk_pred(:printable), do: &printable?/1
@doc ~S"""
Returns Unicode graphemes in the string as per Extended Grapheme
Cluster algorithm.
The algorithm is outlined in the [Unicode Standard Annex #29,
Unicode Text Segmentation](https://www.unicode.org/reports/tr29/).
For details about code points and graphemes, see the `String` module documentation.
## Examples
iex> String.graphemes("Ńaïve")
["Ń", "a", "ï", "v", "e"]
iex> String.graphemes("\u00e9")
["é"]
iex> String.graphemes("\u0065\u0301")
["é"]
"""
@compile {:inline, graphemes: 1}
@spec graphemes(t) :: [grapheme]
def graphemes(string) when is_binary(string), do: do_graphemes(string)
defp do_graphemes(gcs) do
case :unicode_util.gc(gcs) do
[gc | rest] -> [grapheme_to_binary(gc) | do_graphemes(rest)]
[] -> []
{:error, <<byte, rest::bits>>} -> [<<byte>> | do_graphemes(rest)]
end
end
@doc """
Returns the next grapheme in a string.
The result is a tuple with the grapheme and the
remainder of the string or `nil` in case
the String reached its end.
## Examples
iex> String.next_grapheme("olá")
{"o", "lá"}
iex> String.next_grapheme("")
nil
"""
@compile {:inline, next_grapheme: 1}
@spec next_grapheme(t) :: {grapheme, t} | nil
def next_grapheme(string) when is_binary(string) do
case :unicode_util.gc(string) do
[gc] -> {grapheme_to_binary(gc), <<>>}
[gc | rest] -> {grapheme_to_binary(gc), rest}
[] -> nil
{:error, <<byte, rest::bits>>} -> {<<byte>>, rest}
end
end
@doc false
@deprecated "Use String.next_grapheme/1 instead"
@spec next_grapheme_size(t) :: {pos_integer, t} | nil
def next_grapheme_size(string) when is_binary(string) do
case :unicode_util.gc(string) do
[gc] -> {grapheme_byte_size(gc), <<>>}
[gc | rest] -> {grapheme_byte_size(gc), rest}
[] -> nil
{:error, <<_, rest::bits>>} -> {1, rest}
end
end
@doc """
Returns the first grapheme from a UTF-8 string,
`nil` if the string is empty.
## Examples
iex> String.first("elixir")
"e"
iex> String.first("եոգլի")
"ե"
iex> String.first("")
nil
"""
@spec first(t) :: grapheme | nil
def first(string) when is_binary(string) do
case :unicode_util.gc(string) do
[gc | _] -> grapheme_to_binary(gc)
[] -> nil
{:error, <<byte, _::bits>>} -> <<byte>>
end
end
@doc """
Returns the last grapheme from a UTF-8 string,
`nil` if the string is empty.
It traverses the whole string to find its last grapheme.
## Examples
iex> String.last("")
nil
iex> String.last("elixir")
"r"
iex> String.last("եոգլի")
"ի"
"""
@spec last(t) :: grapheme | nil
def last(""), do: nil
def last(string) when is_binary(string), do: do_last(:unicode_util.gc(string), nil)
defp do_last([gc | rest], _), do: do_last(:unicode_util.gc(rest), gc)
defp do_last([], acc) when is_binary(acc), do: acc
defp do_last([], acc), do: :unicode.characters_to_binary([acc])
defp do_last({:error, <<byte, rest::bits>>}, _), do: do_last(:unicode_util.gc(rest), <<byte>>)
@doc """
Returns the number of Unicode graphemes in a UTF-8 string.
## Examples
iex> String.length("elixir")
6
iex> String.length("եոգլի")
5
"""
@spec length(t) :: non_neg_integer
def length(string) when is_binary(string), do: length(string, 0)
defp length(gcs, acc) do
case :unicode_util.gc(gcs) do
[_ | rest] -> length(rest, acc + 1)
[] -> acc
{:error, <<_, rest::bits>>} -> length(rest, acc + 1)
end
end
@doc """
Returns the grapheme at the `position` of the given UTF-8 `string`.
If `position` is greater than `string` length, then it returns `nil`.
## Examples
iex> String.at("elixir", 0)
"e"
iex> String.at("elixir", 1)
"l"
iex> String.at("elixir", 10)
nil
iex> String.at("elixir", -1)
"r"
iex> String.at("elixir", -10)
nil
"""
@spec at(t, integer) :: grapheme | nil
def at(string, position) when is_binary(string) and is_integer(position) and position >= 0 do
do_at(string, position)
end
def at(string, position) when is_binary(string) and is_integer(position) and position < 0 do
position = length(string) + position
case position >= 0 do
true -> do_at(string, position)
false -> nil
end
end
defp do_at(string, position) do
left = byte_size_remaining_at(string, position)
string
|> binary_part(byte_size(string) - left, left)
|> first()
end
@doc """
Returns a substring starting at the offset `start`, and of the given `length`.
If the offset is greater than string length, then it returns `""`.
Remember this function works with Unicode graphemes and considers
the slices to represent grapheme offsets. If you want to split
on raw bytes, check `Kernel.binary_part/3` or `Kernel.binary_slice/3`
instead.
## Examples
iex> String.slice("elixir", 1, 3)
"lix"
iex> String.slice("elixir", 1, 10)
"lixir"
iex> String.slice("elixir", 10, 3)
""
iex> String.slice("elixir", -4, 4)
"ixir"
iex> String.slice("elixir", -10, 3)
""
iex> String.slice("a", 0, 1500)
"a"
iex> String.slice("a", 1, 1500)
""
iex> String.slice("a", 2, 1500)
""
"""
@spec slice(t, integer, non_neg_integer) :: grapheme
def slice(_, _, 0) do
""
end
def slice(string, start, length)
when is_binary(string) and is_integer(start) and is_integer(length) and start >= 0 and
length >= 0 do
do_slice(string, start, length)
end
def slice(string, start, length)
when is_binary(string) and is_integer(start) and is_integer(length) and start < 0 and
length >= 0 do
start = length(string) + start
case start >= 0 do
true -> do_slice(string, start, length)
false -> ""
end
end
defp do_slice(string, start, length) do
from_start = byte_size_remaining_at(string, start)
rest = binary_part(string, byte_size(string) - from_start, from_start)
from_end = byte_size_remaining_at(rest, length)
binary_part(rest, 0, from_start - from_end)
end
@doc """
Returns a substring from the offset given by the start of the
range to the offset given by the end of the range.
If the start of the range is not a valid offset for the given
string or if the range is in reverse order, returns `""`.
If the start or end of the range is negative, the whole string
is traversed first in order to convert the negative indices into
positive ones.
Remember this function works with Unicode graphemes and considers
the slices to represent grapheme offsets. If you want to split
on raw bytes, check `Kernel.binary_part/3` or
`Kernel.binary_slice/2` instead
## Examples
iex> String.slice("elixir", 1..3)
"lix"
iex> String.slice("elixir", 1..10)
"lixir"
iex> String.slice("elixir", -4..-1)
"ixir"
iex> String.slice("elixir", -4..6)
"ixir"
For ranges where `start > stop`, you need to explicitly
mark them as increasing:
iex> String.slice("elixir", 2..-1//1)
"ixir"
iex> String.slice("elixir", 1..-2//1)
"lixi"
You can use `../0` as a shortcut for `0..-1//1`, which returns
the whole string as is:
iex> String.slice("elixir", ..)
"elixir"
The step can be any positive number. For example, to
get every 2 characters of the string:
iex> String.slice("elixir", 0..-1//2)
"eii"
If values are out of bounds, it returns an empty string:
iex> String.slice("elixir", 10..3)
""
iex> String.slice("elixir", -10..-7)
""
iex> String.slice("a", 1..1500)
""
"""
@spec slice(t, Range.t()) :: t
def slice(string, first..last//step = range) when is_binary(string) do
# TODO: Deprecate negative steps on Elixir v1.16
cond do
step > 0 ->
slice_range(string, first, last, step)
step == -1 and first > last ->
slice_range(string, first, last, 1)
true ->
raise ArgumentError,
"String.slice/2 does not accept ranges with negative steps, got: #{inspect(range)}"
end
end
# TODO: Remove me on v2.0
def slice(string, %{__struct__: Range, first: first, last: last} = range)
when is_binary(string) do
step = if first <= last, do: 1, else: -1
slice(string, Map.put(range, :step, step))
end
defp slice_range("", _, _, _), do: ""
defp slice_range(_string, first, last, _step) when first >= 0 and last >= 0 and first > last do
""
end
defp slice_range(string, first, last, step) when first >= 0 do
from_start = byte_size_remaining_at(string, first)
rest = binary_part(string, byte_size(string) - from_start, from_start)
cond do
last == -1 ->
slice_every(rest, byte_size(rest), step)
last >= 0 and step == 1 ->
from_end = byte_size_remaining_at(rest, last - first + 1)
binary_part(rest, 0, from_start - from_end)
last >= 0 ->
slice_every(rest, last - first + 1, step)
true ->
rest
|> slice_range_negative(0, last)
|> slice_every(byte_size(string), step)
end
end
defp slice_range(string, first, last, step) do
string
|> slice_range_negative(first, last)
|> slice_every(byte_size(string), step)
end
defp slice_range_negative(string, first, last) do
{reversed_bytes, length} = acc_bytes(string, [], 0)
first = add_if_negative(first, length)
last = add_if_negative(last, length)
if first < 0 or first > last or first > length do
""
else
last = min(last + 1, length)
reversed_bytes = Enum.drop(reversed_bytes, length - last)
{length_bytes, start_bytes} = split_bytes(reversed_bytes, 0, last - first)
binary_part(string, start_bytes, length_bytes)
end
end
defp slice_every(string, _count, 1), do: string
defp slice_every(string, count, step), do: slice_every(string, count, step, [])
defp slice_every(string, count, to_drop, acc) when count > 0 do
case :unicode_util.gc(string) do
[current | rest] ->
rest
|> drop(to_drop)
|> slice_every(count - to_drop, to_drop, [current | acc])
[] ->
reverse_characters_to_binary(acc)
{:error, <<byte, rest::bits>>} ->
reverse_characters_to_binary(acc) <>
<<byte>> <> slice_every(drop(rest, to_drop), count - to_drop, to_drop, [])
end
end
defp slice_every(_string, _count, _to_drop, acc) do
reverse_characters_to_binary(acc)
end
defp drop(string, 1), do: string
defp drop(string, count) do
case :unicode_util.gc(string) do
[_ | rest] -> drop(rest, count - 1)
[] -> ""
{:error, <<_, rest::bits>>} -> drop(rest, count - 1)
end
end
defp acc_bytes(string, bytes, length) do
case :unicode_util.gc(string) do
[gc | rest] -> acc_bytes(rest, [grapheme_byte_size(gc) | bytes], length + 1)
[] -> {bytes, length}
{:error, <<_, rest::bits>>} -> acc_bytes(rest, [1 | bytes], length + 1)
end
end
defp add_if_negative(value, to_add) when value < 0, do: value + to_add
defp add_if_negative(value, _to_add), do: value
defp split_bytes(rest, acc, 0), do: {acc, Enum.sum(rest)}
defp split_bytes([], acc, _), do: {acc, 0}
defp split_bytes([head | tail], acc, count), do: split_bytes(tail, head + acc, count - 1)
@doc """
Returns `true` if `string` starts with any of the prefixes given.
`prefix` can be either a string, a list of strings, or a compiled
pattern.
## Examples
iex> String.starts_with?("elixir", "eli")
true
iex> String.starts_with?("elixir", ["erlang", "elixir"])
true
iex> String.starts_with?("elixir", ["erlang", "ruby"])
false
An empty string will always match:
iex> String.starts_with?("elixir", "")
true
iex> String.starts_with?("elixir", ["", "other"])
true
An empty list will never match:
iex> String.starts_with?("elixir", [])
false
iex> String.starts_with?("", [])
false
"""
@spec starts_with?(t, t | [t]) :: boolean
def starts_with?(string, prefix) when is_binary(string) and is_binary(prefix) do
starts_with_string?(string, byte_size(string), prefix)
end
def starts_with?(string, prefix) when is_binary(string) and is_list(prefix) do
string_size = byte_size(string)
Enum.any?(prefix, &starts_with_string?(string, string_size, &1))
end
def starts_with?(string, prefix) when is_binary(string) do
IO.warn("compiled patterns are deprecated in starts_with?")
Kernel.match?({0, _}, :binary.match(string, prefix))
end
@compile {:inline, starts_with_string?: 3}
defp starts_with_string?(string, string_size, prefix) when is_binary(prefix) do
prefix_size = byte_size(prefix)
if prefix_size <= string_size do
prefix == binary_part(string, 0, prefix_size)
else
false
end
end
@doc """
Returns `true` if `string` ends with any of the suffixes given.
`suffixes` can be either a single suffix or a list of suffixes.
## Examples
iex> String.ends_with?("language", "age")
true
iex> String.ends_with?("language", ["youth", "age"])
true
iex> String.ends_with?("language", ["youth", "elixir"])
false
An empty suffix will always match:
iex> String.ends_with?("language", "")
true
iex> String.ends_with?("language", ["", "other"])
true
"""
@spec ends_with?(t, t | [t]) :: boolean
def ends_with?(string, suffix) when is_binary(string) and is_binary(suffix) do
ends_with_string?(string, byte_size(string), suffix)
end
def ends_with?(string, suffix) when is_binary(string) and is_list(suffix) do
string_size = byte_size(string)
Enum.any?(suffix, &ends_with_string?(string, string_size, &1))
end
@compile {:inline, ends_with_string?: 3}
defp ends_with_string?(string, string_size, suffix) when is_binary(suffix) do
suffix_size = byte_size(suffix)
if suffix_size <= string_size do
suffix == binary_part(string, string_size - suffix_size, suffix_size)
else
false
end
end
@doc """
Checks if `string` matches the given regular expression.
## Examples
iex> String.match?("foo", ~r/foo/)
true
iex> String.match?("bar", ~r/foo/)
false
Elixir also provides `Kernel.=~/2` and `Regex.match?/2` as
alternatives to test strings against regular expressions.
"""
@spec match?(t, Regex.t()) :: boolean
def match?(string, regex) when is_binary(string) do
Regex.match?(regex, string)
end
@doc """
Searches if `string` contains any of the given `contents`.
`contents` can be either a string, a list of strings,
or a compiled pattern. If `contents` is a list, this
function will search if any of the strings in `contents`
are part of `string`.
> Note: if you want to check if `string` is listed in `contents`,
> where `contents` is a list, use `Enum.member?(contents, string)`
> instead.
## Examples
iex> String.contains?("elixir of life", "of")
true
iex> String.contains?("elixir of life", ["life", "death"])
true
iex> String.contains?("elixir of life", ["death", "mercury"])
false
The argument can also be a compiled pattern:
iex> pattern = :binary.compile_pattern(["life", "death"])
iex> String.contains?("elixir of life", pattern)
true
An empty string will always match:
iex> String.contains?("elixir of life", "")
true
iex> String.contains?("elixir of life", ["", "other"])
true
An empty list will never match:
iex> String.contains?("elixir of life", [])
false
iex> String.contains?("", [])
false
Be aware that this function can match within or across grapheme boundaries.
For example, take the grapheme "é" which is made of the characters
"e" and the acute accent. The following returns `true`:
iex> String.contains?(String.normalize("é", :nfd), "e")
true
However, if "é" is represented by the single character "e with acute"
accent, then it will return `false`:
iex> String.contains?(String.normalize("é", :nfc), "e")
false
"""
@spec contains?(t, [t] | pattern) :: boolean
def contains?(string, contents) when is_binary(string) and is_list(contents) do
list_contains?(string, byte_size(string), contents, [])
end
def contains?(string, contents) when is_binary(string) do
"" == contents or :binary.match(string, contents) != :nomatch
end
defp list_contains?(string, size, [head | tail], acc) do
case byte_size(head) do
0 -> true
head_size when head_size > size -> list_contains?(string, size, tail, acc)
_ -> list_contains?(string, size, tail, [head | acc])
end
end
defp list_contains?(_string, _size, [], []),
do: false
defp list_contains?(string, _size, [], contents),
do: :binary.match(string, contents) != :nomatch
@doc """
Converts a string into a charlist.
Specifically, this function takes a UTF-8 encoded binary and returns a list of its integer
code points. It is similar to `codepoints/1` except that the latter returns a list of code points as
strings.
In case you need to work with bytes, take a look at the
[`:binary` module](`:binary`).
## Examples
iex> String.to_charlist("æß")
'æß'
"""
@spec to_charlist(t) :: charlist
def to_charlist(string) when is_binary(string) do
case :unicode.characters_to_list(string) do
result when is_list(result) ->
result
{:error, encoded, rest} ->
raise UnicodeConversionError, encoded: encoded, rest: rest, kind: :invalid
{:incomplete, encoded, rest} ->
raise UnicodeConversionError, encoded: encoded, rest: rest, kind: :incomplete
end
end
@doc """
Converts a string to an atom.
Warning: this function creates atoms dynamically and atoms are
not garbage-collected. Therefore, `string` should not be an
untrusted value, such as input received from a socket or during
a web request. Consider using `to_existing_atom/1` instead.
By default, the maximum number of atoms is `1_048_576`. This limit
can be raised or lowered using the VM option `+t`.
The maximum atom size is of 255 Unicode code points.
Inlined by the compiler.
## Examples
iex> String.to_atom("my_atom")
:my_atom
"""
@spec to_atom(String.t()) :: atom
def to_atom(string) when is_binary(string) do
:erlang.binary_to_atom(string, :utf8)
end
@doc """
Converts a string to an existing atom.
The maximum atom size is of 255 Unicode code points.
Inlined by the compiler.
## Examples
iex> _ = :my_atom
iex> String.to_existing_atom("my_atom")
:my_atom
"""
@spec to_existing_atom(String.t()) :: atom
def to_existing_atom(string) when is_binary(string) do
:erlang.binary_to_existing_atom(string, :utf8)
end
@doc """
Returns an integer whose text representation is `string`.
`string` must be the string representation of an integer.
Otherwise, an `ArgumentError` will be raised. If you want
to parse a string that may contain an ill-formatted integer,
use `Integer.parse/1`.
Inlined by the compiler.
## Examples
iex> String.to_integer("123")
123
Passing a string that does not represent an integer leads to an error:
String.to_integer("invalid data")
** (ArgumentError) argument error
"""
@spec to_integer(String.t()) :: integer
def to_integer(string) when is_binary(string) do
:erlang.binary_to_integer(string)
end
@doc """
Returns an integer whose text representation is `string` in base `base`.
Inlined by the compiler.
## Examples
iex> String.to_integer("3FF", 16)
1023
"""
@spec to_integer(String.t(), 2..36) :: integer
def to_integer(string, base) when is_binary(string) and is_integer(base) do
:erlang.binary_to_integer(string, base)
end
@doc """
Returns a float whose text representation is `string`.
`string` must be the string representation of a float including a decimal point.
In order to parse a string without decimal point as a float then `Float.parse/1`
should be used. Otherwise, an `ArgumentError` will be raised.
Inlined by the compiler.
## Examples
iex> String.to_float("2.2017764e+0")
2.2017764
iex> String.to_float("3.0")
3.0
String.to_float("3")
** (ArgumentError) argument error
"""
@spec to_float(String.t()) :: float
def to_float(string) when is_binary(string) do
:erlang.binary_to_float(string)
end
@doc """
Computes the bag distance between two strings.
Returns a float value between 0 and 1 representing the bag
distance between `string1` and `string2`.
The bag distance is meant to be an efficient approximation
of the distance between two strings to quickly rule out strings
that are largely different.
The algorithm is outlined in the "String Matching with Metric
Trees Using an Approximate Distance" paper by Ilaria Bartolini,
Paolo Ciaccia, and Marco Patella.
## Examples
iex> String.bag_distance("abc", "")
0.0
iex> String.bag_distance("abcd", "a")
0.25
iex> String.bag_distance("abcd", "ab")
0.5
iex> String.bag_distance("abcd", "abc")
0.75
iex> String.bag_distance("abcd", "abcd")
1.0
"""
@spec bag_distance(t, t) :: float
@doc since: "1.8.0"
def bag_distance(_string, ""), do: 0.0
def bag_distance("", _string), do: 0.0
def bag_distance(string1, string2) when is_binary(string1) and is_binary(string2) do
{bag1, length1} = string_to_bag(string1, %{}, 0)
{bag2, length2} = string_to_bag(string2, %{}, 0)
diff1 = bag_difference(bag1, bag2)
diff2 = bag_difference(bag2, bag1)
1 - max(diff1, diff2) / max(length1, length2)
end
defp string_to_bag(string, bag, length) do
case :unicode_util.gc(string) do
[gc | rest] -> string_to_bag(rest, bag_store(bag, gc), length + 1)
[] -> {bag, length}
{:error, <<byte, rest::bits>>} -> string_to_bag(rest, bag_store(bag, <<byte>>), length + 1)
end
end
defp bag_store(bag, gc) do
case bag do
%{^gc => current} -> %{bag | gc => current + 1}
%{} -> Map.put(bag, gc, 1)
end
end
defp bag_difference(bag1, bag2) do
Enum.reduce(bag1, 0, fn {char, count1}, sum ->
case bag2 do
%{^char => count2} -> sum + max(count1 - count2, 0)
%{} -> sum + count1
end
end)
end
@doc """
Computes the Jaro distance (similarity) between two strings.
Returns a float value between `0.0` (equates to no similarity) and `1.0`
(is an exact match) representing [Jaro](https://en.wikipedia.org/wiki/Jaro-Winkler_distance)
distance between `string1` and `string2`.
The Jaro distance metric is designed and best suited for short
strings such as person names. Elixir itself uses this function
to provide the "did you mean?" functionality. For instance, when you
are calling a function in a module and you have a typo in the
function name, we attempt to suggest the most similar function
name available, if any, based on the `jaro_distance/2` score.
## Examples
iex> String.jaro_distance("Dwayne", "Duane")
0.8222222222222223
iex> String.jaro_distance("even", "odd")
0.0
iex> String.jaro_distance("same", "same")
1.0
"""
@spec jaro_distance(t, t) :: float
def jaro_distance(string1, string2)
def jaro_distance(string, string), do: 1.0
def jaro_distance(_string, ""), do: 0.0
def jaro_distance("", _string), do: 0.0
def jaro_distance(string1, string2) when is_binary(string1) and is_binary(string2) do
{chars1, len1} = graphemes_and_length(string1)
{chars2, len2} = graphemes_and_length(string2)
case match(chars1, len1, chars2, len2) do
{0, _trans} ->
0.0
{comm, trans} ->
(comm / len1 + comm / len2 + (comm - trans) / comm) / 3
end
end
defp match(chars1, len1, chars2, len2) do
if len1 < len2 do
match(chars1, chars2, div(len2, 2) - 1)
else
match(chars2, chars1, div(len1, 2) - 1)
end
end
defp match(chars1, chars2, lim) do
match(chars1, chars2, {0, lim}, {0, 0, -1}, 0)
end
defp match([char | rest], chars, range, state, idx) do
{chars, state} = submatch(char, chars, range, state, idx)
case range do
{lim, lim} -> match(rest, tl(chars), range, state, idx + 1)
{pre, lim} -> match(rest, chars, {pre + 1, lim}, state, idx + 1)
end
end
defp match([], _, _, {comm, trans, _}, _), do: {comm, trans}
defp submatch(char, chars, {pre, _} = range, state, idx) do
case detect(char, chars, range) do
nil ->
{chars, state}
{subidx, chars} ->
{chars, proceed(state, idx - pre + subidx)}
end
end
defp detect(char, chars, {pre, lim}) do
detect(char, chars, pre + 1 + lim, 0, [])
end
defp detect(_char, _chars, 0, _idx, _acc), do: nil
defp detect(_char, [], _lim, _idx, _acc), do: nil
defp detect(char, [char | rest], _lim, idx, acc), do: {idx, Enum.reverse(acc, [nil | rest])}
defp detect(char, [other | rest], lim, idx, acc),
do: detect(char, rest, lim - 1, idx + 1, [other | acc])
defp proceed({comm, trans, former}, current) do
if current < former do
{comm + 1, trans + 1, current}
else
{comm + 1, trans, current}
end
end
@doc """
Returns a keyword list that represents an edit script.
Check `List.myers_difference/2` for more information.
## Examples
iex> string1 = "fox hops over the dog"
iex> string2 = "fox jumps over the lazy cat"
iex> String.myers_difference(string1, string2)
[eq: "fox ", del: "ho", ins: "jum", eq: "ps over the ", del: "dog", ins: "lazy cat"]
"""
@doc since: "1.3.0"
@spec myers_difference(t, t) :: [{:eq | :ins | :del, t}]
def myers_difference(string1, string2) when is_binary(string1) and is_binary(string2) do
graphemes(string1)
|> List.myers_difference(graphemes(string2))
|> Enum.map(fn {kind, chars} -> {kind, IO.iodata_to_binary(chars)} end)
end
@doc false
@deprecated "Use String.to_charlist/1 instead"
@spec to_char_list(t) :: charlist
def to_char_list(string), do: String.to_charlist(string)
## Helpers
@compile {:inline,
codepoint_byte_size: 1,
grapheme_byte_size: 1,
grapheme_to_binary: 1,
graphemes_and_length: 1,
reverse_characters_to_binary: 1}
defp byte_size_unicode(binary) when is_binary(binary), do: byte_size(binary)
defp byte_size_unicode([head]), do: byte_size_unicode(head)
defp byte_size_unicode([head | tail]), do: byte_size_unicode(head) + byte_size_unicode(tail)
defp byte_size_remaining_at(unicode, 0) do
byte_size_unicode(unicode)
end
defp byte_size_remaining_at(unicode, n) do
case :unicode_util.gc(unicode) do
[_] -> 0
[_ | rest] -> byte_size_remaining_at(rest, n - 1)
[] -> 0
{:error, <<_, bin::bits>>} -> byte_size_remaining_at(bin, n - 1)
end
end
defp codepoint_byte_size(cp) when cp <= 0x007F, do: 1
defp codepoint_byte_size(cp) when cp <= 0x07FF, do: 2
defp codepoint_byte_size(cp) when cp <= 0xFFFF, do: 3
defp codepoint_byte_size(_), do: 4
defp grapheme_to_binary(cp) when is_integer(cp), do: <<cp::utf8>>
defp grapheme_to_binary(gc), do: :unicode.characters_to_binary(gc)
defp grapheme_byte_size(cp) when is_integer(cp), do: codepoint_byte_size(cp)
defp grapheme_byte_size(cps), do: grapheme_byte_size(cps, 0)
defp grapheme_byte_size([cp | cps], acc),
do: grapheme_byte_size(cps, acc + codepoint_byte_size(cp))
defp grapheme_byte_size([], acc),
do: acc
defp graphemes_and_length(string),
do: graphemes_and_length(string, [], 0)
defp graphemes_and_length(string, acc, length) do
case :unicode_util.gc(string) do
[gc | rest] ->
graphemes_and_length(rest, [gc | acc], length + 1)
[] ->
{:lists.reverse(acc), length}
{:error, <<byte, rest::bits>>} ->
graphemes_and_length(rest, [<<byte>> | acc], length + 1)
end
end
defp reverse_characters_to_binary(acc),
do: acc |> :lists.reverse() |> :unicode.characters_to_binary()
end
| 29.48194 | 102 | 0.650075 |
79a86e88939dc24a410c7c1bbd5726646c32631f | 5,279 | exs | Elixir | test/image_test.exs | lgandersen/jocker_dist | b5e676f8d9e60bbc8bc7a82ccd1e05389f2cd5b5 | [
"BSD-2-Clause"
] | null | null | null | test/image_test.exs | lgandersen/jocker_dist | b5e676f8d9e60bbc8bc7a82ccd1e05389f2cd5b5 | [
"BSD-2-Clause"
] | null | null | null | test/image_test.exs | lgandersen/jocker_dist | b5e676f8d9e60bbc8bc7a82ccd1e05389f2cd5b5 | [
"BSD-2-Clause"
] | null | null | null | defmodule ImageTest do
use ExUnit.Case
alias Jocker.Engine.{Config, Image, MetaData, Layer, Network}
@moduletag :capture_log
@tmp_dockerfile "tmp_dockerfile"
@tmp_context "./"
setup_all do
Application.stop(:jocker)
TestHelper.clear_zroot()
start_supervised(Config)
:ok
end
setup do
start_supervised(MetaData)
start_supervised(Layer)
start_supervised(Network)
start_supervised(
{DynamicSupervisor, name: Jocker.Engine.ContainerPool, strategy: :one_for_one}
)
on_exit(fn -> stop_and_delete_db() end)
:ok
end
test "create an image with a 'RUN' instruction" do
dockerfile = """
FROM scratch
RUN echo "lol1" > /root/test_1.txt
"""
TestHelper.create_tmp_dockerfile(dockerfile, @tmp_dockerfile)
%Image{layer_id: layer_id} =
TestHelper.build_and_return_image(@tmp_context, @tmp_dockerfile, "test:latest")
%Layer{mountpoint: mountpoint} = Jocker.Engine.MetaData.get_layer(layer_id)
assert File.read(Path.join(mountpoint, "/root/test_1.txt")) == {:ok, "lol1\n"}
assert MetaData.list_containers() == []
end
test "create an image with a 'COPY' instruction" do
dockerfile = """
FROM scratch
COPY test.txt /root/
"""
context = create_test_context("test_copy_instruction")
TestHelper.create_tmp_dockerfile(dockerfile, @tmp_dockerfile, context)
%Image{layer_id: layer_id} =
TestHelper.build_and_return_image(context, @tmp_dockerfile, "test:latest")
%Layer{mountpoint: mountpoint} = Jocker.Engine.MetaData.get_layer(layer_id)
assert File.read(Path.join(mountpoint, "root/test.txt")) == {:ok, "lol\n"}
assert [] == MetaData.list_containers()
end
test "create an image with a 'COPY' instruction using symlinks" do
dockerfile = """
FROM scratch
RUN mkdir /etc/testdir
RUN ln -s /etc/testdir /etc/symbolic_testdir
COPY test.txt /etc/symbolic_testdir/
"""
context = create_test_context("test_copy_instruction_symbolic")
TestHelper.create_tmp_dockerfile(dockerfile, @tmp_dockerfile, context)
%Image{layer_id: layer_id} =
TestHelper.build_and_return_image(context, @tmp_dockerfile, "test:latest")
%Layer{mountpoint: mountpoint} = Jocker.Engine.MetaData.get_layer(layer_id)
# we cannot check the symbolic link from the host:
assert File.read(Path.join(mountpoint, "etc/testdir/test.txt")) == {:ok, "lol\n"}
end
test "create an image with a 'CMD' instruction" do
dockerfile = """
FROM scratch
CMD /bin/sleep 10
"""
TestHelper.create_tmp_dockerfile(dockerfile, @tmp_dockerfile)
_image = TestHelper.build_and_return_image(@tmp_context, @tmp_dockerfile, "test:latest")
assert MetaData.list_containers() == []
end
test "create an image with 'ENV' instructions" do
dockerfile = """
FROM scratch
ENV TEST=lol
ENV TEST2="lool test"
CMD /bin/ls
"""
TestHelper.create_tmp_dockerfile(dockerfile, @tmp_dockerfile)
image = TestHelper.build_and_return_image(@tmp_context, @tmp_dockerfile, "test:latest")
assert image.env_vars == ["TEST2=lool test", "TEST=lol"]
end
test "create an image using three RUN/COPY instructions" do
dockerfile = """
FROM scratch
COPY test.txt /root/
RUN echo 'lol1' > /root/test_1.txt
RUN echo 'lol2' > /root/test_2.txt
"""
context = create_test_context("test_image_builder_three_layers")
TestHelper.create_tmp_dockerfile(dockerfile, @tmp_dockerfile, context)
%Image{layer_id: layer_id} =
TestHelper.build_and_return_image(context, @tmp_dockerfile, "test:latest")
%Layer{mountpoint: mountpoint} = Jocker.Engine.MetaData.get_layer(layer_id)
assert File.read(Path.join(mountpoint, "root/test.txt")) == {:ok, "lol\n"}
assert File.read(Path.join(mountpoint, "root/test_1.txt")) == {:ok, "lol1\n"}
assert File.read(Path.join(mountpoint, "root/test_2.txt")) == {:ok, "lol2\n"}
assert MetaData.list_containers() == []
end
test "receiving of status messages during build" do
dockerfile = """
FROM scratch
COPY test.txt /root/
RUN echo \
"this should be relayed back to the parent process"
USER ntpd
CMD /etc/rc
"""
context = create_test_context("test_image_builder_three_layers")
TestHelper.create_tmp_dockerfile(dockerfile, @tmp_dockerfile, context)
{:ok, pid} = Image.build(context, @tmp_dockerfile, "test:latest", false)
{_img, messages} = TestHelper.receive_imagebuilder_results(pid, [])
assert messages == [
"Step 1/5 : FROM scratch\n",
"Step 2/5 : COPY test.txt /root/\n",
"Step 3/5 : RUN echo \"this should be relayed back to the parent process\"\n",
"this should be relayed back to the parent process\n",
"Step 4/5 : USER ntpd\n",
"Step 5/5 : CMD /etc/rc\n"
]
end
defp create_test_context(name) do
dataset = Path.join(Config.get("zroot"), name)
mountpoint = Path.join("/", dataset)
Jocker.Engine.ZFS.create(dataset)
{"", 0} = System.cmd("sh", ["-c", "echo 'lol' > #{mountpoint}/test.txt"])
mountpoint
end
defp stop_and_delete_db() do
# Agent.stop(Jocker.Engine.MetaData)
File.rm(Config.get("metadata_db"))
end
end
| 31.993939 | 93 | 0.679295 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.