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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f72f33e4ec182e1926312b120ecc0bd0087046c0 | 708 | ex | Elixir | lib/credo/check/readability/trailing_blank_line.ex | rodrigues/credo | b4e08477a2141d5537d8fc9c5cc08ebf93a5ee23 | [
"MIT"
] | null | null | null | lib/credo/check/readability/trailing_blank_line.ex | rodrigues/credo | b4e08477a2141d5537d8fc9c5cc08ebf93a5ee23 | [
"MIT"
] | null | null | null | lib/credo/check/readability/trailing_blank_line.ex | rodrigues/credo | b4e08477a2141d5537d8fc9c5cc08ebf93a5ee23 | [
"MIT"
] | null | null | null | defmodule Credo.Check.Readability.TrailingBlankLine do
@moduledoc """
Files should end in a trailing blank line. Many editors ensure this
"final newline" automatically.
"""
@explanation [check: @moduledoc]
use Credo.Check, base_priority: :low
def run(%SourceFile{lines: lines} = source_file, params \\ []) do
issue_meta = IssueMeta.for(source_file, params)
{line_no, last_line} = List.last(lines)
if String.strip(last_line) == "" do
[]
else
[issue_for(issue_meta, line_no)]
end
end
def issue_for(issue_meta, line_no) do
format_issue issue_meta,
message: "There should be a final \\n at the end of each file.",
line_no: line_no
end
end
| 25.285714 | 70 | 0.682203 |
f72f396f9ffc4c15232125d742882e4a4bd47bfd | 70 | exs | Elixir | imdb_data/test/test_helper.exs | defndaines/eiga | 89adc25dd6c7a5be86d6dc6be9dffc62ad05bdd8 | [
"Apache-2.0"
] | null | null | null | imdb_data/test/test_helper.exs | defndaines/eiga | 89adc25dd6c7a5be86d6dc6be9dffc62ad05bdd8 | [
"Apache-2.0"
] | 2 | 2016-03-10T03:04:11.000Z | 2017-02-11T17:43:44.000Z | imdb_data/test/test_helper.exs | defndaines/eiga | 89adc25dd6c7a5be86d6dc6be9dffc62ad05bdd8 | [
"Apache-2.0"
] | null | null | null | ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(IMDbData.Repo, :manual)
| 23.333333 | 54 | 0.785714 |
f72f451404859991ae34f3b2bdc5834adb477887 | 385 | ex | Elixir | lib/ash/error/query/invalid_sort_order.ex | smt116/ash | 880a17f197873eb1c8dc8d81a8b4d6d9cb570b3f | [
"MIT"
] | 528 | 2019-12-08T01:51:54.000Z | 2022-03-30T10:09:45.000Z | lib/ash/error/query/invalid_sort_order.ex | smt116/ash | 880a17f197873eb1c8dc8d81a8b4d6d9cb570b3f | [
"MIT"
] | 278 | 2019-12-04T15:25:06.000Z | 2022-03-31T03:40:51.000Z | lib/ash/error/query/invalid_sort_order.ex | smt116/ash | 880a17f197873eb1c8dc8d81a8b4d6d9cb570b3f | [
"MIT"
] | 53 | 2020-08-17T22:08:09.000Z | 2022-03-24T01:58:59.000Z | defmodule Ash.Error.Query.InvalidSortOrder do
@moduledoc "Used when an invalid sort order is provided"
use Ash.Error.Exception
def_ash_error([:order], class: :invalid)
defimpl Ash.ErrorKind do
def id(_), do: Ash.UUID.generate()
def code(_), do: "invalid_sort_order"
def message(%{order: order}) do
"No such sort order #{inspect(order)}"
end
end
end
| 22.647059 | 58 | 0.688312 |
f72f49eddc1131134845a20ea7732a61556e5788 | 489 | ex | Elixir | lib/solvent_web/router.ex | pbremer/solvent | 76e4ec6e1230f25f55069c5702dbe628f35f0798 | [
"MIT"
] | null | null | null | lib/solvent_web/router.ex | pbremer/solvent | 76e4ec6e1230f25f55069c5702dbe628f35f0798 | [
"MIT"
] | 1 | 2021-03-10T11:08:45.000Z | 2021-03-10T11:08:45.000Z | lib/solvent_web/router.ex | pbremer/solvent | 76e4ec6e1230f25f55069c5702dbe628f35f0798 | [
"MIT"
] | null | null | null | defmodule SolventWeb.Router do
use SolventWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", SolventWeb do
pipe_through :browser
get "/", PageController, :index
end
# Other scopes may use custom stacks.
# scope "/api", SolventWeb do
# pipe_through :api
# end
end
| 18.111111 | 39 | 0.672802 |
f72f7d45eeab92972ef791045393d458d8e4d895 | 2,075 | ex | Elixir | clients/game_services/lib/google_api/game_services/v1/model/log_config.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/game_services/lib/google_api/game_services/v1/model/log_config.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/game_services/lib/google_api/game_services/v1/model/log_config.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.GameServices.V1.Model.LogConfig do
@moduledoc """
Specifies what kind of log the caller must write
## Attributes
* `cloudAudit` (*type:* `GoogleApi.GameServices.V1.Model.CloudAuditOptions.t`, *default:* `nil`) - Cloud audit options.
* `counter` (*type:* `GoogleApi.GameServices.V1.Model.CounterOptions.t`, *default:* `nil`) - Counter options.
* `dataAccess` (*type:* `GoogleApi.GameServices.V1.Model.DataAccessOptions.t`, *default:* `nil`) - Data access options.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:cloudAudit => GoogleApi.GameServices.V1.Model.CloudAuditOptions.t(),
:counter => GoogleApi.GameServices.V1.Model.CounterOptions.t(),
:dataAccess => GoogleApi.GameServices.V1.Model.DataAccessOptions.t()
}
field(:cloudAudit, as: GoogleApi.GameServices.V1.Model.CloudAuditOptions)
field(:counter, as: GoogleApi.GameServices.V1.Model.CounterOptions)
field(:dataAccess, as: GoogleApi.GameServices.V1.Model.DataAccessOptions)
end
defimpl Poison.Decoder, for: GoogleApi.GameServices.V1.Model.LogConfig do
def decode(value, options) do
GoogleApi.GameServices.V1.Model.LogConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.GameServices.V1.Model.LogConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 39.150943 | 123 | 0.742169 |
f72fae835e4937abea95eacd9c73a435820aae8d | 251 | ex | Elixir | bullion/lib/bullion.ex | ttymck/bullion | d15babe80d30f9775e45f2a143b88a66b539d318 | [
"MIT"
] | null | null | null | bullion/lib/bullion.ex | ttymck/bullion | d15babe80d30f9775e45f2a143b88a66b539d318 | [
"MIT"
] | 8 | 2021-03-10T20:53:42.000Z | 2021-07-30T06:52:16.000Z | bullion/lib/bullion.ex | ttymck/bullion | d15babe80d30f9775e45f2a143b88a66b539d318 | [
"MIT"
] | null | null | null | defmodule Bullion do
@moduledoc """
Bullion keeps the contexts that define your domain
and business logic.
Contexts are also responsible for managing your data, regardless
if it comes from the database, an external API or others.
"""
end
| 25.1 | 66 | 0.752988 |
f72fca50b77aba5427164268f26aef447cefa939 | 8,755 | exs | Elixir | apps/ewallet_config/test/ewallet_config/setting_validator_test.exs | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 322 | 2018-02-28T07:38:44.000Z | 2020-05-27T23:09:55.000Z | apps/ewallet_config/test/ewallet_config/setting_validator_test.exs | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 643 | 2018-02-28T12:05:20.000Z | 2020-05-22T08:34:38.000Z | apps/ewallet_config/test/ewallet_config/setting_validator_test.exs | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 63 | 2018-02-28T10:57:06.000Z | 2020-05-27T23:10:38.000Z | defmodule EWalletConfig.SettingValidatorTest do
use EWalletConfig.SchemaCase, async: true
import Ecto.Changeset
import EWalletConfig.SettingValidator
alias EWalletConfig.StoredSetting
describe "validate_with_options/1" do
test "returns a valid changeset for a new StoredSetting" do
attrs = %{
data: %{value: "two"},
options: %{
array: ["one", "two", "three"]
}
}
changeset =
%StoredSetting{}
|> cast(attrs, [:data, :options])
|> validate_setting_with_options()
assert changeset.valid?
end
test "returns a valid changeset for an existing StoredSetting" do
setting = %StoredSetting{
data: %{value: "one"},
options: %{array: ["one", "two", "three"]}
}
attrs = %{data: %{value: "two"}}
changeset =
setting
|> cast(attrs, [:data])
|> validate_setting_with_options()
assert changeset.valid?
end
test "returns a valid changeset when the options' array is nil" do
attrs = %{
data: %{value: "any_value"},
options: %{
array: nil
}
}
changeset =
%StoredSetting{}
|> cast(attrs, [:data, :options])
|> validate_setting_with_options()
assert changeset.valid?
end
test "returns a valid changeset when the options did not change" do
attrs = %{
key: "new_key",
data: %{value: "new_value"}
}
changeset =
%StoredSetting{}
|> cast(attrs, [:key, :data, :options])
|> validate_setting_with_options()
assert changeset.valid?
end
test "returns an invalid changeset when the value is not in the allowed options" do
attrs = %{
data: %{value: "twenty"},
options: %{
array: ["one", "two", "three"]
}
}
changeset =
%StoredSetting{}
|> cast(attrs, [:data, :options])
|> validate_setting_with_options()
refute changeset.valid?
assert changeset.errors == [
value: {"must be one of 'one', 'two', 'three'", [validation: :value_not_allowed]}
]
end
end
describe "validate_setting_type/1" do
test "returns a valid changeset for a new StoredSetting" do
setting = %StoredSetting{}
attrs = %{type: "string", data: %{value: "new_value"}}
changeset =
setting
|> cast(attrs, [:type, :data])
|> validate_setting_type()
assert changeset.valid?
end
test "returns a valid changeset for an existing StoredSetting" do
setting = %StoredSetting{type: "string", data: %{value: "old_value"}}
attrs = %{data: %{value: "new_value"}}
changeset =
setting
|> cast(attrs, [:type, :data])
|> validate_setting_with_options()
assert changeset.valid?
end
test "returns a valid changeset when given a nil value" do
attrs = %{type: "string", data: %{value: nil}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
assert changeset.valid?
end
end
describe "validate_setting_type/1 for type 'string'" do
test "returns a valid changeset when given a string" do
attrs = %{type: "string", data: %{value: "string_value"}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
assert changeset.valid?
end
test "returns an invalid changeset when given a non-string" do
attrs = %{type: "string", data: %{value: 1234}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
refute changeset.valid?
end
end
describe "validate_setting_type/1 for type 'integer'" do
test "returns a valid changeset when given a positive integer value" do
attrs = %{type: "integer", data: %{value: 1234}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
assert changeset.valid?
end
test "returns a valid changeset when given a zero" do
attrs = %{type: "integer", data: %{value: 0}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
assert changeset.valid?
end
test "returns a valid changeset when given a negative integer value" do
attrs = %{type: "integer", data: %{value: -1234}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
assert changeset.valid?
end
test "returns an invalid changeset when given a non-integer" do
attrs = %{type: "integer", data: %{value: "not_an_integer"}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
refute changeset.valid?
end
end
describe "validate_setting_type/1 for type 'unsigned_integer'" do
test "returns a valid changeset when given a positive integer value" do
attrs = %{type: "unsigned_integer", data: %{value: 999}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
assert changeset.valid?
end
test "returns a valid changeset when given a zero" do
attrs = %{type: "unsigned_integer", data: %{value: 0}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
assert changeset.valid?
end
test "returns an invalid changeset when given a negative value" do
attrs = %{type: "unsigned_integer", data: %{value: -1}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
refute changeset.valid?
end
test "returns an invalid changeset when given a non-integer" do
attrs = %{type: "unsigned_integer", data: %{value: "not_an_integer"}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
refute changeset.valid?
end
end
describe "validate_setting_type/1 for type 'map'" do
test "returns a valid changeset when given a map" do
attrs = %{type: "map", data: %{value: %{"some_key" => "some_value"}}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
assert changeset.valid?
end
test "returns a valid changeset when given a non-map" do
attrs = %{type: "map", data: %{value: "not_a_map"}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
refute changeset.valid?
end
end
describe "validate_setting_type/1 for type 'array'" do
test "returns a valid changeset when given an array of strings" do
attrs = %{type: "array", data: %{value: ["one", "two", "three"]}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
assert changeset.valid?
end
test "returns a valid changeset when given an array of integers" do
attrs = %{type: "array", data: %{value: [1, 2, 3]}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
assert changeset.valid?
end
test "returns a valid changeset when given an array of mixed types" do
attrs = %{type: "array", data: %{value: ["one", 2, "three", false]}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
assert changeset.valid?
end
test "returns an invalid changeset when given a non-array" do
attrs = %{type: "array", data: %{value: "not_an_array"}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
refute changeset.valid?
end
end
describe "validate_setting_type/1 for type 'boolean'" do
test "returns a valid changeset when given a boolean" do
attrs = %{type: "boolean", data: %{value: true}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
assert changeset.valid?
end
test "returns an invalid changeset when given a non-boolean" do
attrs = %{type: "boolean", data: %{value: "not_boolean"}}
changeset =
%StoredSetting{}
|> cast(attrs, [:type, :data])
|> validate_setting_type()
refute changeset.valid?
end
end
end
| 25.902367 | 96 | 0.584352 |
f73008175daa4bbc1cf0b1d0be7f6f6e1cf6646b | 739 | exs | Elixir | test/unit/xsd/datatypes/short_test.exs | pukkamustard/rdf-ex | c459d8e7fa548fdfad82643338b68decf380a296 | [
"MIT"
] | 53 | 2017-06-25T22:20:44.000Z | 2020-04-27T17:27:51.000Z | test/unit/xsd/datatypes/short_test.exs | pukkamustard/rdf-ex | c459d8e7fa548fdfad82643338b68decf380a296 | [
"MIT"
] | 7 | 2017-06-25T00:29:11.000Z | 2020-03-11T00:23:47.000Z | test/unit/xsd/datatypes/short_test.exs | pukkamustard/rdf-ex | c459d8e7fa548fdfad82643338b68decf380a296 | [
"MIT"
] | 3 | 2020-07-03T13:25:36.000Z | 2021-04-04T12:33:51.000Z | defmodule RDF.XSD.ShortTest do
use RDF.XSD.Datatype.Test.Case,
datatype: RDF.XSD.Short,
name: "short",
base: RDF.XSD.Int,
base_primitive: RDF.XSD.Integer,
comparable_datatypes: [RDF.XSD.Decimal, RDF.XSD.Double],
applicable_facets: [
RDF.XSD.Facets.MinInclusive,
RDF.XSD.Facets.MaxInclusive,
RDF.XSD.Facets.MinExclusive,
RDF.XSD.Facets.MaxExclusive,
RDF.XSD.Facets.TotalDigits,
RDF.XSD.Facets.Pattern
],
facets: %{
min_inclusive: -32768,
max_inclusive: 32767,
min_exclusive: nil,
max_exclusive: nil,
total_digits: nil,
pattern: nil
},
valid: RDF.XSD.TestData.valid_shorts(),
invalid: RDF.XSD.TestData.invalid_shorts()
end
| 27.37037 | 60 | 0.658999 |
f73015ba8da24e53be0555e0fdf6a406a68fac13 | 7,243 | ex | Elixir | lib/okta/groups.ex | EdBondArcher/okta-elixir | f7831125e40a1b4f8b488528b6a09b87d654db45 | [
"MIT"
] | 7 | 2021-07-19T10:41:43.000Z | 2022-02-23T20:56:51.000Z | lib/okta/groups.ex | EdBondArcher/okta-elixir | f7831125e40a1b4f8b488528b6a09b87d654db45 | [
"MIT"
] | 10 | 2019-08-18T11:31:43.000Z | 2019-09-24T18:12:24.000Z | lib/okta/groups.ex | EdBondArcher/okta-elixir | f7831125e40a1b4f8b488528b6a09b87d654db45 | [
"MIT"
] | 2 | 2019-08-08T08:22:10.000Z | 2019-09-06T06:54:43.000Z | defmodule Okta.Groups do
@moduledoc """
The `Okta.Groups` module provides access methods to the [Okta Groups API](https://developer.okta.com/docs/reference/api/groups/).
All methods require a Tesla Client struct created with `Okta.client(base_url, api_key)`.
## Examples
client = Okta.Client("https://dev-000000.okta.com", "thisismykeycreatedinokta")
{:ok, result, _env} = Okta.Groups.list_groups(client)
"""
@groups_url "/api/v1/groups"
@doc """
Adds a new group with OKTA_GROUP type to your organization.
The [OKTA group profile object](https://developer.okta.com/docs/reference/api/groups/#objectclass-okta-user-group)
has a name and description attributes.
## Examples
client = Okta.Client("https://dev-000000.okta.com", "thisismykeycreatedinokta")
{:ok, result} = Okta.Groups.create_group(client, %{
name: "Designers", description: "All the designers"
})
https://developer.okta.com/docs/reference/api/groups/#add-group
"""
@spec create_group(Okta.client(), map()) :: Okta.result()
def create_group(client, profile) do
Tesla.post(client, @groups_url, %{profile: profile}) |> Okta.result()
end
@doc """
Updates the profile for a group with OKTA_GROUP type from your organization.
The [OKTA group profile object](https://developer.okta.com/docs/reference/api/groups/#objectclass-okta-user-group)
has a name and description attributes.
https://developer.okta.com/docs/reference/api/groups/#update-group
"""
@spec update_group(Okta.client(), String.t(), map()) :: Okta.result()
def update_group(client, group_id, profile) do
Tesla.put(client, @groups_url <> "/#{group_id}", %{profile: profile}) |> Okta.result()
end
@doc """
Removes a group with OKTA_GROUP type from your organization.
https://developer.okta.com/docs/reference/api/groups/#remove-group
"""
@spec delete_group(Okta.client(), String.t()) :: Okta.result()
def delete_group(client, group_id) do
Tesla.delete(client, @groups_url <> "/#{group_id}") |> Okta.result()
end
@doc """
Fetches a specific group by id from your organization.
https://developer.okta.com/docs/reference/api/groups/#get-group
"""
@spec get_group(Okta.client(), String.t()) :: Okta.result()
def get_group(client, group_id) do
Tesla.get(client, @groups_url <> "/#{group_id}") |> Okta.result()
end
@doc """
Enumerates all users that are a member of a group. `limit` and `after`
parameters provide for paging.
https://developer.okta.com/docs/reference/api/groups/#list-group-members
"""
@spec list_group_members(Okta.client(), String.t()) :: Okta.result()
def list_group_members(client, group_id, opt \\ []) do
Tesla.get(client, @groups_url <> "/#{group_id}/users", query: opt) |> Okta.result()
end
@doc """
Enumerates all applications that are assigned to a group.
https://developer.okta.com/docs/reference/api/groups/#list-assigned-applications
"""
@spec list_group_apps(Okta.client(), String.t()) :: Okta.result()
def list_group_apps(client, group_id, opt \\ []) do
Tesla.get(client, @groups_url <> "/#{group_id}/apps", query: opt) |> Okta.result()
end
@doc """
Removes a user from a group with OKTA_GROUP type.
https://developer.okta.com/docs/reference/api/groups/#remove-user-from-group
"""
@spec remove_user_from_group(Okta.client(), String.t(), String.t()) :: Okta.result()
def remove_user_from_group(client, group_id, user_id) do
Tesla.delete(client, @groups_url <> "/#{group_id}/users/#{user_id}") |> Okta.result()
end
@doc """
Adds a user to a group with OKTA_GROUP type.
https://developer.okta.com/docs/reference/api/groups/#add-user-to-group
"""
@spec add_user_to_group(Okta.client(), String.t(), String.t()) :: Okta.result()
def add_user_to_group(client, group_id, user_id) do
Tesla.put(client, @groups_url <> "/#{group_id}/users/#{user_id}", "") |> Okta.result()
end
@doc """
Enumerates groups in your organization with pagination.
A subset of groups can be returned that match a supported filter expression or
query.
See https://developer.okta.com/docs/reference/api/groups/#list-groups for
optional parameters that can be passed in.
##Example
{:ok, result} = Okta.Users.list_groups(client, q: "Design", limit: 10, after: 200)
"""
@spec list_groups(Okta.client(), keyword()) :: Okta.result()
def list_groups(client, opts \\ []) do
Tesla.get(client, @groups_url, query: opts) |> Okta.result()
end
@doc """
Searches for groups by name in your organization.
https://developer.okta.com/docs/reference/api/groups/#search-groups
"""
@spec search_groups(Okta.client(), String.t(), keyword()) :: Okta.result()
def search_groups(client, name, opts \\ []) do
list_groups(client, Keyword.merge(opts, q: name))
end
@doc """
Filter groups by expression.
See https://developer.okta.com/docs/reference/api/groups/#list-groups and
https://developer.okta.com/docs/reference/api-overview/#filtering
"""
@spec filter_groups(Okta.client(), String.t(), keyword()) :: Okta.result()
def filter_groups(client, filter, opts \\ []) do
list_groups(client, Keyword.merge(opts, filter: filter))
end
@doc """
Enumerates all groups with a specific type.
https://developer.okta.com/docs/reference/api/groups/#list-groups-with-type
"""
@spec list_groups_of_type(Okta.client(), String.t(), keyword()) :: Okta.result()
def list_groups_of_type(client, type, opts \\ []) do
filter_groups(client, "type eq \"#{type}\"", opts)
end
@doc """
Enumerates all groups with a profile updated after the specified timestamp.
https://developer.okta.com/docs/reference/api/groups/#list-groups-with-profile-updated-after-timestamp
"""
@spec list_groups_profile_updated_after(Okta.client(), Calendar.datetime(), keyword()) ::
Okta.result()
def list_groups_profile_updated_after(client, updated_at, opts \\ []) do
filter_groups(
client,
"lastUpdated gt \"#{DateTime.to_iso8601(updated_at, :extended)}\"",
opts
)
end
@doc """
Enumerates all groups with user memberships updated after the specified
timestamp.
https://developer.okta.com/docs/reference/api/groups/#list-groups-with-membership-updated-after-timestamp
"""
@spec list_groups_membership_updated_after(Okta.client(), Calendar.datetime(), keyword()) ::
Okta.result()
def list_groups_membership_updated_after(client, updated_at, opts \\ []) do
filter_groups(
client,
"lastMembershipUpdated gt \"#{DateTime.to_iso8601(updated_at, :extended)}\"",
opts
)
end
@doc """
Enumerates all groups with profile or user memberships updated after the
specified timestamp.
https://developer.okta.com/docs/reference/api/groups/#list-groups-updated-after-timestamp
"""
@spec list_groups_updated_after(Okta.client(), Calendar.datetime(), keyword()) :: Okta.result()
def list_groups_updated_after(client, updated_at, opts \\ []) do
filter_groups(
client,
"lastUpdated gt \"#{DateTime.to_iso8601(updated_at, :extended)}\" or lastMembershipUpdated gt \"#{
DateTime.to_iso8601(updated_at, :extended)
}\"",
opts
)
end
end
| 34.822115 | 131 | 0.692393 |
f7301783bb2eb3b939b8848a79f1b91fc4255b5a | 3,638 | exs | Elixir | test/unit/logger_json/plug_test.exs | thulio/logger_json | 3c3c2731772d1d937a61ec8d3d09d9288f4fac8f | [
"MIT"
] | null | null | null | test/unit/logger_json/plug_test.exs | thulio/logger_json | 3c3c2731772d1d937a61ec8d3d09d9288f4fac8f | [
"MIT"
] | null | null | null | test/unit/logger_json/plug_test.exs | thulio/logger_json | 3c3c2731772d1d937a61ec8d3d09d9288f4fac8f | [
"MIT"
] | null | null | null | defmodule LoggerJSON.PlugTest do
use Logger.Case
use Plug.Test
import ExUnit.CaptureIO
require Logger
defmodule MyPlug do
use Plug.Builder
plug(LoggerJSON.Plug)
plug(:passthrough)
defp passthrough(conn, _) do
Plug.Conn.send_resp(conn, 200, "Passthrough")
end
end
setup do
on_exit(fn ->
:ok = Logger.configure_backend(LoggerJSON, device: :user, level: nil, metadata: [], json_encoder: Jason)
end)
Logger.configure_backend(LoggerJSON, device: :standard_error, metadata: :all)
end
test "logs proper message" do
log =
capture_io(:standard_error, fn ->
call(conn(:get, "/"))
Logger.flush()
end)
assert %{
"jsonPayload" => %{
"message" => "",
"metadata" => %{
"application" => "logger_json",
"client" => %{"ip" => "127.0.0.1", "user_agent" => nil, "version" => nil},
"connection" => %{
"method" => "GET",
"request_id" => nil,
"request_path" => "/",
"status" => 200,
"type" => "sent"
},
"latency" => _,
"runtime" => %{},
"system" => %{"hostname" => _, "pid" => _}
}
}
} = Jason.decode!(log)
conn = %{conn(:get, "/hello/world") | private: %{phoenix_controller: MyController, phoenix_action: :foo}}
log =
capture_io(:standard_error, fn ->
call(conn)
Logger.flush()
end)
assert %{
"jsonPayload" => %{
"message" => "",
"metadata" => %{
"application" => "logger_json",
"client" => %{"ip" => "127.0.0.1", "user_agent" => nil, "version" => nil},
"connection" => %{
"method" => "GET",
"request_id" => nil,
"request_path" => "/hello/world",
"status" => 200,
"type" => "sent"
},
"latency" => _,
"runtime" => %{"controller" => "Elixir.MyController", "action" => "foo"},
"system" => %{"hostname" => _, "pid" => _}
}
}
} = Jason.decode!(log)
end
test "logs message with values from headers" do
request_id = Ecto.UUID.generate()
conn =
:get
|> conn("/")
|> Plug.Conn.put_resp_header("x-request-id", request_id)
|> Plug.Conn.put_req_header("user-agent", "chrome")
|> Plug.Conn.put_req_header("x-forwarded-for", "127.0.0.10")
|> Plug.Conn.put_req_header("x-api-version", "2017-01-01")
log =
capture_io(:standard_error, fn ->
call(conn)
Logger.flush()
end)
assert %{
"jsonPayload" => %{
"message" => "",
"metadata" => %{
"application" => "logger_json",
"client" => %{"ip" => "127.0.0.10", "user_agent" => "chrome", "version" => "2017-01-01"},
"connection" => %{
"method" => "GET",
"request_id" => ^request_id,
"request_path" => "/",
"status" => 200,
"type" => "sent"
},
"latency" => _,
"runtime" => %{},
"system" => %{"hostname" => _, "pid" => _}
}
}
} = Jason.decode!(log)
end
defp call(conn) do
MyPlug.call(conn, [])
end
end
| 29.33871 | 110 | 0.43238 |
f73018c36bc17bf8417636327724928e4035b056 | 3,758 | ex | Elixir | lib/rethinkdb/pseudotypes.ex | goonode/rethinkdb-elixir | 449fa3a11a65fb7e6ff729f3a4e7614acf69522e | [
"MIT"
] | null | null | null | lib/rethinkdb/pseudotypes.ex | goonode/rethinkdb-elixir | 449fa3a11a65fb7e6ff729f3a4e7614acf69522e | [
"MIT"
] | null | null | null | lib/rethinkdb/pseudotypes.ex | goonode/rethinkdb-elixir | 449fa3a11a65fb7e6ff729f3a4e7614acf69522e | [
"MIT"
] | null | null | null | defmodule RethinkDB.Pseudotypes do
@moduledoc false
defmodule Binary do
@moduledoc false
defstruct data: nil
def parse(%{"$reql_type$" => "BINARY", "data" => data}, opts) do
case Keyword.get(opts, :binary_format) do
:raw ->
%__MODULE__{data: data}
_ ->
:base64.decode(data)
end
end
end
defmodule Geometry do
@moduledoc false
defmodule Point do
@moduledoc false
defstruct coordinates: []
end
defmodule Line do
@moduledoc false
defstruct coordinates: []
end
defmodule Polygon do
@moduledoc false
defstruct coordinates: []
end
def parse(%{"$reql_type$" => "GEOMETRY", "coordinates" => [x, y], "type" => "Point"}) do
%Point{coordinates: {x, y}}
end
def parse(%{"$reql_type$" => "GEOMETRY", "coordinates" => coords, "type" => "LineString"}) do
%Line{coordinates: Enum.map(coords, &List.to_tuple/1)}
end
def parse(%{"$reql_type$" => "GEOMETRY", "coordinates" => coords, "type" => "Polygon"}) do
%Polygon{coordinates: for(points <- coords, do: Enum.map(points, &List.to_tuple/1))}
end
end
defmodule Time do
@moduledoc false
defstruct epoch_time: nil, timezone: nil
def parse(
%{"$reql_type$" => "TIME", "epoch_time" => epoch_time, "timezone" => timezone},
opts
) do
case Keyword.get(opts, :time_format) do
:raw ->
%__MODULE__{epoch_time: epoch_time, timezone: timezone}
_ ->
with <<sign::binary-size(1)>> <> rest = timezone <> ":00",
{:ok, {h, m, _, _}} = Calendar.ISO.parse_time(rest) do
sec = (h * 60 + m) * 60
zone_abbr =
case sec do
0 -> "UTC"
_ -> timezone
end
time_zone =
case {div(sec, 3600), rem(sec, 3600)} do
{0, 0} ->
"Etc/UTC"
{hours, 0} ->
"Etc/GMT" <> sign <> Integer.to_string(hours)
{hours, seconds} ->
"Etc/GMT" <>
sign <>
Integer.to_string(hours) <>
":" <> String.pad_leading(Integer.to_string(seconds), 2, "0")
end
(epoch_time * 1000)
|> trunc
|> DateTime.from_unix!(:millisecond)
|> struct(utc_offset: sec, zone_abbr: zone_abbr, time_zone: time_zone)
end
end
end
end
def convert_reql_pseudotypes(nil, _opts), do: nil
def convert_reql_pseudotypes(%{"$reql_type$" => "BINARY"} = data, opts) do
Binary.parse(data, opts)
end
def convert_reql_pseudotypes(%{"$reql_type$" => "GEOMETRY"} = data, _opts) do
Geometry.parse(data)
end
def convert_reql_pseudotypes(%{"$reql_type$" => "GROUPED_DATA"} = data, _opts) do
parse_grouped_data(data)
end
def convert_reql_pseudotypes(%{"$reql_type$" => "TIME"} = data, opts) do
Time.parse(data, opts)
end
def convert_reql_pseudotypes(list, opts) when is_list(list) do
Enum.map(list, fn data -> convert_reql_pseudotypes(data, opts) end)
end
def convert_reql_pseudotypes(map, opts) when is_map(map) do
Enum.map(map, fn {k, v} ->
{k, convert_reql_pseudotypes(v, opts)}
end)
|> Enum.into(%{})
end
def convert_reql_pseudotypes(string, _opts), do: string
def parse_grouped_data(%{"$reql_type$" => "GROUPED_DATA", "data" => data}) do
Enum.map(data, fn [k, data] ->
{k, data}
end)
|> Enum.into(%{})
end
def create_grouped_data(data) when is_map(data) do
data = data |> Enum.map(fn {k, v} -> [k, v] end)
%{"$reql_type$" => "GROUPED_DATA", "data" => data}
end
end
| 27.231884 | 97 | 0.555082 |
f7304810774878d437664adfec2ee5a39d379aa8 | 1,616 | ex | Elixir | clients/tag_manager/lib/google_api/tag_manager/v2/model/sync_status.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/tag_manager/lib/google_api/tag_manager/v2/model/sync_status.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/tag_manager/lib/google_api/tag_manager/v2/model/sync_status.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.TagManager.V2.Model.SyncStatus do
@moduledoc """
The status of a workspace after synchronization.
## Attributes
* `mergeConflict` (*type:* `boolean()`, *default:* `nil`) - Synchornization operation detected a merge conflict.
* `syncError` (*type:* `boolean()`, *default:* `nil`) - An error occurred during the synchronization operation.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:mergeConflict => boolean() | nil,
:syncError => boolean() | nil
}
field(:mergeConflict)
field(:syncError)
end
defimpl Poison.Decoder, for: GoogleApi.TagManager.V2.Model.SyncStatus do
def decode(value, options) do
GoogleApi.TagManager.V2.Model.SyncStatus.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.TagManager.V2.Model.SyncStatus do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.32 | 116 | 0.727104 |
f7304b1d26466d14e95e6ce13331dd002deb8461 | 24,581 | ex | Elixir | clients/chat/lib/google_api/chat/v1/api/spaces.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/chat/lib/google_api/chat/v1/api/spaces.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/chat/lib/google_api/chat/v1/api/spaces.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"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.Chat.V1.Api.Spaces do
@moduledoc """
API calls for all endpoints tagged `Spaces`.
"""
alias GoogleApi.Chat.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Returns a space.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name of the space, in the form "spaces/*".
Example: spaces/AAAAMpdlehY
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Chat.V1.Model.Space{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_get(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.Space.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def chat_spaces_get(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Chat.V1.Model.Space{}])
end
@doc """
Lists spaces the caller is a member of.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:pageSize` (*type:* `integer()`) - Requested page size. The value is capped at 1000.
Server may return fewer results than requested.
If unspecified, server will default to 100.
* `:pageToken` (*type:* `String.t`) - A token identifying a page of results the server should return.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Chat.V1.Model.ListSpacesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_list(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.ListSpacesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def chat_spaces_list(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/spaces", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Chat.V1.Model.ListSpacesResponse{}])
end
@doc """
Returns a membership.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name of the membership to be retrieved, in the form
"spaces/*/members/*".
Example: spaces/AAAAMpdlehY/members/105115627578887013105
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Chat.V1.Model.Membership{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_members_get(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.Membership.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def chat_spaces_members_get(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Chat.V1.Model.Membership{}])
end
@doc """
Lists human memberships in a space.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. The resource name of the space for which membership list is to be
fetched, in the form "spaces/*".
Example: spaces/AAAAMpdlehY
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:pageSize` (*type:* `integer()`) - Requested page size. The value is capped at 1000.
Server may return fewer results than requested.
If unspecified, server will default to 100.
* `:pageToken` (*type:* `String.t`) - A token identifying a page of results the server should return.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Chat.V1.Model.ListMembershipsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_members_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.ListMembershipsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def chat_spaces_members_list(connection, parent, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/members", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Chat.V1.Model.ListMembershipsResponse{}])
end
@doc """
Creates a message.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Required. Space resource name, in the form "spaces/*".
Example: spaces/AAAAMpdlehY
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:threadKey` (*type:* `String.t`) - Opaque thread identifier string that can be specified to group messages
into a single thread. If this is the first message with a given thread
identifier, a new thread is created. Subsequent messages with the same
thread identifier will be posted into the same thread. This relieves bots
and webhooks from having to store the Hangouts Chat thread ID of a thread (created earlier by them) to post
further updates to it.
Has no effect if thread field,
corresponding to an existing thread, is set in message.
* `:body` (*type:* `GoogleApi.Chat.V1.Model.Message.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Chat.V1.Model.Message{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_messages_create(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def chat_spaces_messages_create(connection, parent, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:threadKey => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+parent}/messages", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Chat.V1.Model.Message{}])
end
@doc """
Deletes a message.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name of the message to be deleted, in the form
"spaces/*/messages/*"
Example: spaces/AAAAMpdlehY/messages/UMxbHmzDlr4.UMxbHmzDlr4
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Chat.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_messages_delete(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def chat_spaces_messages_delete(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Chat.V1.Model.Empty{}])
end
@doc """
Returns a message.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Required. Resource name of the message to be retrieved, in the form
"spaces/*/messages/*".
Example: spaces/AAAAMpdlehY/messages/UMxbHmzDlr4.UMxbHmzDlr4
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Chat.V1.Model.Message{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_messages_get(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def chat_spaces_messages_get(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Chat.V1.Model.Message{}])
end
@doc """
Updates a message.
## Parameters
* `connection` (*type:* `GoogleApi.Chat.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Resource name, in the form "spaces/*/messages/*".
Example: spaces/AAAAMpdlehY/messages/UMxbHmzDlr4.UMxbHmzDlr4
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:updateMask` (*type:* `String.t`) - Required. The field paths to be updated, comma separated if there are
multiple.
Currently supported field paths:
* text
* cards
* `:body` (*type:* `GoogleApi.Chat.V1.Model.Message.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Chat.V1.Model.Message{}}` on success
* `{:error, info}` on failure
"""
@spec chat_spaces_messages_update(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Chat.V1.Model.Message.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def chat_spaces_messages_update(connection, name, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/v1/{+name}", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Chat.V1.Model.Message{}])
end
end
| 45.945794 | 196 | 0.616737 |
f730557a85cb87860e0c0599d6ca73343cca786d | 3,838 | ex | Elixir | exercises/practice/zipper/.meta/example.ex | herminiotorres/exercism-elixir | 0464a968f3e37680b2bf34868b889d6f8de5581e | [
"MIT"
] | 2 | 2019-07-09T05:23:38.000Z | 2019-07-29T01:39:59.000Z | exercises/practice/zipper/.meta/example.ex | herminiotorres/exercism-elixir | 0464a968f3e37680b2bf34868b889d6f8de5581e | [
"MIT"
] | 6 | 2021-05-12T06:06:14.000Z | 2022-03-21T16:08:49.000Z | exercises/practice/zipper/.meta/example.ex | herminiotorres/exercism-elixir | 0464a968f3e37680b2bf34868b889d6f8de5581e | [
"MIT"
] | null | null | null | defmodule BinTree do
@moduledoc """
A node in a binary tree.
`value` is the value of a node.
`left` is the left subtree (nil if no subtree).
`right` is the right subtree (nil if no subtree).
"""
@type t :: %BinTree{value: any, left: t() | nil, right: t() | nil}
defstruct [:value, :left, :right]
end
defimpl Inspect, for: BinTree do
import Inspect.Algebra
# A custom inspect instance purely for the tests, this makes error messages
# much more readable.
#
# %BinTree{value: 3, left: %BinTree{value: 5, right: %BinTree{value: 6}}} becomes (3:(5::(6::)):)
def inspect(%BinTree{value: value, left: left, right: right}, opts) do
concat([
"(",
to_doc(value, opts),
":",
if(left, do: to_doc(left, opts), else: ""),
":",
if(right, do: to_doc(right, opts), else: ""),
")"
])
end
end
defmodule BinTree.Zipper do
@moduledoc """
A binary tree zipper.
`value` is the value of the focus.
`left` is the left subtree of the focus.
`right` is the right subtree of the focus.
`trail` is the trail of the focus.
The trail stores the path that a zipper has taken into the tree from the root
and the alternative branches.
"""
@type t :: %BinTree.Zipper{
value: any,
left: BinTree.Zipper.t() | nil,
right: BinTree.Zipper.t() | nil,
trail: [{:left, any, BinTree.t()} | {:right, any, BinTree.t()}]
}
defstruct value: nil, left: nil, right: nil, trail: []
end
defmodule Zipper do
alias BinTree, as: BT
alias BinTree.Zipper, as: Z
@doc """
Get a zipper focussed on the root node.
"""
@spec from_tree(BT.t()) :: Z.t()
def from_tree(%BT{value: v, left: l, right: r}) do
%Z{value: v, left: l, right: r, trail: []}
end
@doc """
Get the complete tree from a zipper.
"""
@spec to_tree(Z.t()) :: BT.t()
def to_tree(%Z{value: v, left: l, right: r, trail: t}) do
do_to_tree(%BT{value: v, left: l, right: r}, t)
end
defp do_to_tree(b, []) do
b
end
defp do_to_tree(b, [{:left, pv, pr} | pt]) do
do_to_tree(%BT{value: pv, left: b, right: pr}, pt)
end
defp do_to_tree(b, [{:right, pv, pl} | pt]) do
do_to_tree(%BT{value: pv, left: pl, right: b}, pt)
end
@doc """
Get the value of the focus node.
"""
@spec value(Z.t()) :: any
def value(%Z{value: v}), do: v
@doc """
Get the left child of the focus node, if any.
"""
@spec left(Z.t()) :: Z.t() | nil
def left(%Z{left: nil}), do: nil
def left(%Z{value: v, left: %BT{value: lv, left: ll, right: lr}, right: r, trail: zt}) do
%Z{value: lv, left: ll, right: lr, trail: [{:left, v, r} | zt]}
end
@doc """
Get the right child of the focus node, if any.
"""
@spec right(Z.t()) :: Z.t() | nil
def right(%Z{right: nil}), do: nil
def right(%Z{value: v, left: l, right: %BT{value: rv, left: rl, right: rr}, trail: zt}) do
%Z{value: rv, left: rl, right: rr, trail: [{:right, v, l} | zt]}
end
@doc """
Get the parent of the focus node, if any.
"""
@spec up(Z.t()) :: Z.t()
def up(%Z{value: v, left: l, right: r, trail: t}) do
case t do
[] ->
nil
[{:left, pv, pr} | zt] ->
%Z{value: pv, left: %BT{value: v, left: l, right: r}, right: pr, trail: zt}
[{:right, pv, pl} | zt] ->
%Z{value: pv, left: pl, right: %BT{value: v, left: l, right: r}, trail: zt}
end
end
@doc """
Set the value of the focus node.
"""
@spec set_value(Z.t(), any) :: Z.t()
def set_value(z, v), do: %{z | value: v}
@doc """
Replace the left child tree of the focus node.
"""
@spec set_left(Z.t(), BT.t()) :: Z.t()
def set_left(z, l), do: %{z | left: l}
@doc """
Replace the right child tree of the focus node.
"""
@spec set_right(Z.t(), BT.t()) :: Z.t()
def set_right(z, r), do: %{z | right: r}
end
| 25.758389 | 99 | 0.565659 |
f7306f93b0eab05e541f9c613ec4dc0226d3ba9c | 393 | exs | Elixir | priv/repo/seeds.exs | nolantait/prop | d68d87d623b1d5352ba1b0f1d44e17bd7a119a3e | [
"MIT"
] | 22 | 2021-06-29T09:25:52.000Z | 2022-03-16T09:17:24.000Z | priv/repo/seeds.exs | nolantait/prop | d68d87d623b1d5352ba1b0f1d44e17bd7a119a3e | [
"MIT"
] | 54 | 2021-06-28T19:54:17.000Z | 2022-03-27T06:49:30.000Z | priv/repo/seeds.exs | nolantait/prop | d68d87d623b1d5352ba1b0f1d44e17bd7a119a3e | [
"MIT"
] | 2 | 2022-01-08T10:16:30.000Z | 2022-02-20T09:45:50.000Z | # Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# Prop.Repo.insert!(%Prop.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
Code.require_file("seeds/tokens.exs", __DIR__)
| 28.071429 | 61 | 0.709924 |
f730b32d36b8d6a1df6625377531aace52f31f08 | 8,081 | ex | Elixir | clients/deployment_manager/lib/google_api/deployment_manager/v2/api/operations.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/deployment_manager/lib/google_api/deployment_manager/v2/api/operations.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/deployment_manager/lib/google_api/deployment_manager/v2/api/operations.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.DeploymentManager.V2.Api.Operations do
@moduledoc """
API calls for all endpoints tagged `Operations`.
"""
alias GoogleApi.DeploymentManager.V2.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Gets information about a specific operation.
## Parameters
* `connection` (*type:* `GoogleApi.DeploymentManager.V2.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - The project ID for this request.
* `operation` (*type:* `String.t`) - The name of the operation for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DeploymentManager.V2.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec deploymentmanager_operations_get(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.DeploymentManager.V2.Model.Operation.t()} | {:error, Tesla.Env.t()}
def deploymentmanager_operations_get(
connection,
project,
operation,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/global/operations/{operation}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"operation" => URI.encode(operation, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.DeploymentManager.V2.Model.Operation{}])
end
@doc """
Lists all operations for a project.
## Parameters
* `connection` (*type:* `GoogleApi.DeploymentManager.V2.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - The project ID for this request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <.
For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance.
You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true).
* `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
* `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
Currently, only sorting by name or creationTimestamp desc is supported.
* `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DeploymentManager.V2.Model.OperationsListResponse{}}` on success
* `{:error, info}` on failure
"""
@spec deploymentmanager_operations_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.DeploymentManager.V2.Model.OperationsListResponse.t()}
| {:error, Tesla.Env.t()}
def deploymentmanager_operations_list(connection, project, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/global/operations", %{
"project" => URI.encode(project, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.DeploymentManager.V2.Model.OperationsListResponse{}]
)
end
end
| 51.801282 | 414 | 0.675288 |
f730c7a6c24a004f2ac9440efa21ca9adbaa969d | 569 | ex | Elixir | lib/mix/tasks/pelemay/nerves/bench.ex | kentaro/pelemay | fcdd8c2783adb9e57aa82f3fc8c1184346de9f3c | [
"Apache-2.0"
] | 192 | 2019-08-30T06:53:28.000Z | 2022-02-15T06:08:25.000Z | lib/mix/tasks/pelemay/nerves/bench.ex | kentaro/pelemay | fcdd8c2783adb9e57aa82f3fc8c1184346de9f3c | [
"Apache-2.0"
] | 121 | 2019-09-02T08:13:25.000Z | 2021-12-03T19:04:16.000Z | lib/mix/tasks/pelemay/nerves/bench.ex | kentaro/pelemay | fcdd8c2783adb9e57aa82f3fc8c1184346de9f3c | [
"Apache-2.0"
] | 15 | 2019-08-31T12:00:03.000Z | 2021-07-03T04:13:10.000Z | defmodule Mix.Tasks.Pelemay.Nerves.Bench do
use Mix.Task
@shortdoc "Benchmark kernels of Pelemay with ssh nerves.local"
@recursive true
@moduledoc """
Benchmark kernels of Pelemay with ssh nerves.local.
```
mix pelemay.nerves.bench `module_name`
```
"""
@impl true
def run(args) do
Mix.Project.get!()
args
|> Enum.map(&"Elixir.#{&1}")
|> Enum.map(&String.to_atom(&1))
|> Enum.map(&Pelemay.Generator.nif_module(&1))
|> Enum.each(&Mix.Shell.cmd("ssh nerves.local \"#{&1}.bench()\"", fn x -> IO.puts(x) end))
end
end
| 21.884615 | 94 | 0.630931 |
f73104b267eb7f19f679104d5f9086d6984baac3 | 297 | ex | Elixir | lib/cloudfront_signer/application.ex | qstream/cloudfront-signer | 515dafb4408a85439aa56a5deccd6cf17def2e11 | [
"MIT"
] | null | null | null | lib/cloudfront_signer/application.ex | qstream/cloudfront-signer | 515dafb4408a85439aa56a5deccd6cf17def2e11 | [
"MIT"
] | 1 | 2022-01-31T15:05:07.000Z | 2022-01-31T15:05:07.000Z | lib/cloudfront_signer/application.ex | qstream/cloudfront-signer | 515dafb4408a85439aa56a5deccd6cf17def2e11 | [
"MIT"
] | null | null | null | defmodule CloudfrontSigner.Application do
use Application
def start(_type, _args) do
children = [
{CloudfrontSigner.DistributionRegistry, []}
]
opts = [strategy: :one_for_one, name: CloudfrontSigner.Application.Supervisor]
Supervisor.start_link(children, opts)
end
end | 27 | 82 | 0.734007 |
f731655d2a0534b545408ad4e9f28a1e7cebdeb2 | 266 | exs | Elixir | priv/repo/migrations/20210420232741_create_restaurants.exs | manoel-lopes/invenger | 19f76964c95cd4e038c78cf743fe28069b73b9b2 | [
"MIT"
] | null | null | null | priv/repo/migrations/20210420232741_create_restaurants.exs | manoel-lopes/invenger | 19f76964c95cd4e038c78cf743fe28069b73b9b2 | [
"MIT"
] | null | null | null | priv/repo/migrations/20210420232741_create_restaurants.exs | manoel-lopes/invenger | 19f76964c95cd4e038c78cf743fe28069b73b9b2 | [
"MIT"
] | null | null | null | defmodule Invenger.Repo.Migrations.CreateRestaurants do
use Ecto.Migration
def change do
create table(:restaurants) do
add :email, :string
add :name, :string
timestamps()
end
create unique_index(:restaurants, [:email])
end
end
| 17.733333 | 55 | 0.680451 |
f7317b1f5db4cd7e41fee0114c40f3a889afa8b6 | 521 | ex | Elixir | lib/mix/tasks/piton/pip.ex | nutheory/piton | 2f1072456a095ea1862c3e0f339356b2d3b72dad | [
"MIT"
] | 41 | 2017-06-08T08:00:13.000Z | 2022-02-04T13:38:36.000Z | lib/mix/tasks/piton/pip.ex | nutheory/piton | 2f1072456a095ea1862c3e0f339356b2d3b72dad | [
"MIT"
] | null | null | null | lib/mix/tasks/piton/pip.ex | nutheory/piton | 2f1072456a095ea1862c3e0f339356b2d3b72dad | [
"MIT"
] | 1 | 2018-08-04T09:49:59.000Z | 2018-08-04T09:49:59.000Z | defmodule Mix.Tasks.Piton.Pip do
use Mix.Task
@moduledoc """
`Mix.Task` which will upgrade your Python pip.
"""
@shortdoc "It will install python pip. The pip's full path has to be given as argument"
def run(args) do
case args do
[pip_path | _] -> upgrade(pip_path)
_ -> IO.puts("Argument error")
end
end
defp upgrade(pip_path) do
IO.puts("Upgrading pip: #{pip_path}...")
System.cmd(pip_path, ["install", "--upgrade", "pip"])
IO.puts("pip has been upgraded.")
end
end
| 23.681818 | 89 | 0.637236 |
f7318284bb4b4fcc6620f43917c5b2ec0713e02b | 2,180 | ex | Elixir | lib/phoenix/live_dashboard/listener.ex | dbii/phoenix_live_dashboard | 08255b63a4a7236d3f99fe9053b997fab1027297 | [
"MIT"
] | null | null | null | lib/phoenix/live_dashboard/listener.ex | dbii/phoenix_live_dashboard | 08255b63a4a7236d3f99fe9053b997fab1027297 | [
"MIT"
] | null | null | null | lib/phoenix/live_dashboard/listener.ex | dbii/phoenix_live_dashboard | 08255b63a4a7236d3f99fe9053b997fab1027297 | [
"MIT"
] | null | null | null | defmodule Phoenix.LiveDashboard.Listener do
# This module is the one responsible for listening
# and sending metrics to a given node.
@moduledoc false
use GenServer, restart: :temporary
def listen(node, metrics) do
DynamicSupervisor.start_child(
{Phoenix.LiveDashboard.ListenerSupervisor, node},
{Phoenix.LiveDashboard.Listener, {self(), metrics}}
)
end
def start_link({parent, metrics}) do
GenServer.start_link(__MODULE__, {parent, metrics})
end
def handle_metrics(_event_name, measurements, metadata, {parent, metrics}) do
time = System.system_time(:millisecond)
entries =
for {metric, index} <- metrics do
if measurement = extract_measurement(metric, measurements) do
label = metric |> extract_tags(metadata) |> tags_to_label()
{index, label, measurement, time}
end
end
send(parent, {:telemetry, entries})
end
defp extract_measurement(metric, measurements) do
case metric.measurement do
fun when is_function(fun, 1) -> fun.(measurements)
key -> measurements[key]
end
end
defp extract_tags(metric, metadata) do
tag_values = metric.tag_values.(metadata)
Map.take(tag_values, metric.tags)
end
defp tags_to_label(tags) when tags == %{}, do: nil
defp tags_to_label(tags) when is_map(tags) do
Enum.map_join(tags, " ", fn {_k, v} -> v end)
end
@impl true
def init({parent, metrics}) do
Process.flag(:trap_exit, true)
ref = Process.monitor(parent)
metrics = Enum.with_index(metrics, 0)
metrics_per_event = Enum.group_by(metrics, fn {metric, _} -> metric.event_name end)
for {event_name, metrics} <- metrics_per_event do
id = {__MODULE__, event_name, self()}
:telemetry.attach(id, event_name, &handle_metrics/4, {parent, metrics})
end
{:ok, %{ref: ref, events: Map.keys(metrics_per_event)}}
end
@impl true
def handle_info({:DOWN, ref, _, _, _}, %{ref: ref} = state) do
{:stop, :shutdown, state}
end
@impl true
def terminate(_reason, %{events: events}) do
for event <- events do
:telemetry.detach({__MODULE__, event, self()})
end
:ok
end
end
| 27.594937 | 87 | 0.670642 |
f731b9442a50669d8abe362b198f814c1db452df | 2,317 | ex | Elixir | clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/http.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/http.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/http.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.ServiceConsumerManagement.V1.Model.Http do
@moduledoc """
Defines the HTTP configuration for an API service. It contains a list of
HttpRule, each specifying the mapping of an RPC method
to one or more HTTP REST API methods.
## Attributes
* `fullyDecodeReservedExpansion` (*type:* `boolean()`, *default:* `nil`) - When set to true, URL path parameters will be fully URI-decoded except in
cases of single segment matches in reserved expansion, where "%2F" will be
left encoded.
The default behavior is to not decode RFC 6570 reserved characters in multi
segment matches.
* `rules` (*type:* `list(GoogleApi.ServiceConsumerManagement.V1.Model.HttpRule.t)`, *default:* `nil`) - A list of HTTP configuration rules that apply to individual API methods.
**NOTE:** All service configuration rules follow "last one wins" order.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:fullyDecodeReservedExpansion => boolean(),
:rules => list(GoogleApi.ServiceConsumerManagement.V1.Model.HttpRule.t())
}
field(:fullyDecodeReservedExpansion)
field(:rules, as: GoogleApi.ServiceConsumerManagement.V1.Model.HttpRule, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.Http do
def decode(value, options) do
GoogleApi.ServiceConsumerManagement.V1.Model.Http.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.Http do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 39.271186 | 180 | 0.744929 |
f7323679deaad295e9933e08aba80280b84ed3f6 | 13,839 | exs | Elixir | test/glimesh/chat_test.exs | Eein/glimesh.tv | e55e96b852363b0d9576ca47d19f1499889c68db | [
"MIT"
] | 1 | 2021-06-08T00:07:39.000Z | 2021-06-08T00:07:39.000Z | test/glimesh/chat_test.exs | defango/glimesh.tv | d429d66cbb61bedcbb62a4d348b5e16a6b5a6868 | [
"MIT"
] | null | null | null | test/glimesh/chat_test.exs | defango/glimesh.tv | d429d66cbb61bedcbb62a4d348b5e16a6b5a6868 | [
"MIT"
] | null | null | null | defmodule Glimesh.ChatTest do
use Glimesh.DataCase
import Glimesh.AccountsFixtures
alias Glimesh.Accounts
alias Glimesh.Chat
alias Glimesh.Streams
alias Glimesh.StreamModeration
alias Glimesh.Streams.ChannelModerationLog
describe "chat_messages" do
alias Glimesh.Chat.ChatMessage
@valid_attrs %{message: "some message"}
@link_containing_attrs %{message: "https://glimesh.tv is cool"}
@invalid_attrs %{message: nil}
setup do
streamer = streamer_fixture()
%{
channel: streamer.channel,
streamer: streamer
}
end
def chat_message_fixture(attrs \\ %{}) do
%{channel: channel} = streamer_fixture()
user = user_fixture()
{:ok, chat_message} =
Chat.create_chat_message(user, channel, attrs |> Enum.into(@valid_attrs))
chat_message
end
def multiple_chat_message_fixture(attrs \\ %{num_of_messages: 10}) do
%{channel: channel} = streamer_fixture()
user = user_fixture()
# Pretty janky way of creating multiple chat messages but it works
created_messages =
Enum.map(1..attrs.num_of_messages, fn _i ->
Chat.create_chat_message(user, channel, attrs |> Enum.into(@valid_attrs))
end)
{:ok, chat_message} = List.last(created_messages)
chat_message
end
test "empty_chat_message/0 returns an empty changeset" do
assert %Ecto.Changeset{} = Chat.empty_chat_message()
end
test "list_chat_messages/0 returns all chat_messages" do
chat_message = chat_message_fixture()
assert length(Chat.list_chat_messages(chat_message.channel)) == 1
end
test "list_chat_messages/2 returns all chat_messages within the specified limit" do
chat_message = multiple_chat_message_fixture()
assert length(Chat.list_chat_messages(chat_message.channel, 8)) == 8
end
test "get_chat_message!/1 returns the chat_message with given id" do
chat_message = chat_message_fixture()
assert Chat.get_chat_message!(chat_message.id).id == chat_message.id
assert Chat.get_chat_message!(chat_message.id).message == chat_message.message
end
test "create_chat_message/3 with valid data creates a chat_message", %{channel: channel} do
assert {:ok, %ChatMessage{} = chat_message} =
Chat.create_chat_message(user_fixture(), channel, @valid_attrs)
assert chat_message.message == "some message"
end
test "create_chat_message/3 with valid data when the channel has links blocked creates a chat_message",
%{channel: channel, streamer: streamer} do
{:ok, _} = Streams.update_channel(streamer, channel, %{block_links: true})
assert {:ok, %ChatMessage{} = chat_message} =
Chat.create_chat_message(user_fixture(), channel, @valid_attrs)
assert chat_message.message == "some message"
end
test "create_chat_message/3 with invalid data returns error changeset", %{channel: channel} do
assert {:error, %Ecto.Changeset{}} =
Chat.create_chat_message(user_fixture(), channel, @invalid_attrs)
end
test "create_chat_message/3 with a link when channel has links blocked returns error changeset",
%{channel: channel, streamer: streamer} do
{:ok, channel} = Streams.update_channel(streamer, channel, %{block_links: true})
assert {:error, "This channel has links disabled!"} =
Chat.create_chat_message(user_fixture(), channel, @link_containing_attrs)
end
test "create_chat_message/1 with a link when channel allows links returns a chat_message", %{
channel: channel
} do
assert {:ok, %ChatMessage{}} =
Chat.create_chat_message(user_fixture(), channel, %{
"message" => "https://glimesh.tv is cool"
})
assert {:ok, %ChatMessage{} = chat_message} =
Chat.create_chat_message(user_fixture(), channel, @link_containing_attrs)
assert chat_message.message == @link_containing_attrs.message
end
# test "delete_chat_message/1 deletes the chat_message" do
# chat_message = chat_message_fixture()
# assert {:ok, %ChatMessage{}} = Chat.delete_chat_message(chat_message)
# assert_raise Ecto.NoResultsError, fn -> Chat.get_chat_message!(chat_message.id) end
# end
test "change_chat_message/1 returns a chat_message changeset" do
chat_message = chat_message_fixture()
assert %Ecto.Changeset{} = Chat.change_chat_message(chat_message)
end
end
describe "get_moderator_permissions/2" do
setup do
streamer = streamer_fixture()
%{
channel: streamer.channel,
streamer: streamer,
moderator: user_fixture(),
user: user_fixture()
}
end
test "random user has no permissions", %{channel: channel, user: user} do
assert %{can_short_timeout: false, can_long_timeout: false, can_ban: false} =
Chat.get_moderator_permissions(channel, user)
end
test "streamer has all permissions", %{channel: channel, streamer: streamer} do
assert %{can_short_timeout: true, can_long_timeout: true, can_ban: true} =
Chat.get_moderator_permissions(channel, streamer)
end
test "moderator has permissions based on grants", %{
channel: channel,
streamer: streamer,
moderator: moderator
} do
{:ok, _} =
StreamModeration.create_channel_moderator(streamer, channel, moderator, %{
can_short_timeout: true,
can_long_timeout: true,
can_ban: false
})
assert %{can_short_timeout: true, can_long_timeout: true, can_ban: false} =
Chat.get_moderator_permissions(channel, moderator)
end
end
describe "is_moderator/2" do
setup do
streamer = streamer_fixture()
%{
channel: streamer.channel,
streamer: streamer,
moderator: user_fixture(),
user: user_fixture()
}
end
test "random user is not moderator", %{channel: channel, user: user} do
refute Chat.is_moderator?(channel, user)
end
test "streamer is not a moderator but can moderate", %{channel: channel, streamer: streamer} do
refute Chat.is_moderator?(channel, streamer)
assert Bodyguard.permit?(Glimesh.Chat, :short_timeout, streamer, channel)
end
test "moderator is a moderator", %{channel: channel, streamer: streamer, moderator: moderator} do
{:ok, _} =
StreamModeration.create_channel_moderator(streamer, channel, moderator, %{
can_short_timeout: true,
can_long_timeout: false,
can_ban: false
})
assert Chat.is_moderator?(channel, moderator)
end
end
describe "bans and timeouts" do
setup do
streamer = streamer_fixture()
moderator = user_fixture()
# Banned user fixtures
banned_streamer = streamer_fixture(%{is_banned: true})
{:ok, _} =
StreamModeration.create_channel_moderator(streamer, streamer.channel, moderator, %{
can_short_timeout: true,
can_long_timeout: true,
can_ban: true,
can_delete: true
})
%{
channel: streamer.channel,
streamer: streamer,
banned_streamer: banned_streamer,
banned_channel: banned_streamer.channel,
moderator: moderator,
user: user_fixture()
}
end
test "global account ban prohibits chat", %{channel: channel} do
user = user_fixture(%{is_banned: true})
assert {:error, "You are banned from Glimesh."} =
Chat.create_chat_message(user, channel, %{message: "not allowed?"})
end
test "global account ban prohibits streamer from chat", %{
banned_channel: banned_channel,
banned_streamer: banned_streamer
} do
assert {:error, "You are banned from Glimesh."} =
Chat.create_chat_message(banned_streamer, banned_channel, %{
message: "not allowed?"
})
end
test "times out a user and removes messages successfully", %{
channel: channel,
moderator: moderator,
user: user
} do
{:ok, _} = Chat.create_chat_message(user, channel, %{message: "bad message"})
{:ok, _} = Chat.create_chat_message(moderator, channel, %{message: "good message"})
assert length(Chat.list_chat_messages(channel)) == 2
{:ok, _} = Chat.short_timeout_user(moderator, channel, user)
assert length(Chat.list_chat_messages(channel)) == 1
end
test "delete_message/4 deletes message", %{channel: channel, moderator: moderator, user: user} do
{:ok, bad_message} = Chat.create_chat_message(user, channel, %{message: "bad message"})
{:ok, _} = Chat.create_chat_message(moderator, channel, %{message: "good message"})
assert length(Chat.list_chat_messages(channel)) == 2
{:ok, _} = Chat.delete_message(moderator, channel, user, bad_message)
assert length(Chat.list_chat_messages(channel)) == 1
end
test "short_timeout_user prevents a new message", %{
channel: channel,
moderator: moderator,
user: user
} do
{:ok, _} = Chat.short_timeout_user(moderator, channel, user)
assert {:error, "You are banned from this channel for 5 more minutes."} =
Chat.create_chat_message(user, channel, %{message: "not allowed?"})
end
test "long_timeout_user prevents a new message", %{
channel: channel,
moderator: moderator,
user: user
} do
{:ok, _} = Chat.long_timeout_user(moderator, channel, user)
assert {:error, "You are banned from this channel for 15 more minutes."} =
Chat.create_chat_message(user, channel, %{message: "not allowed?"})
end
test "ban_user prevents a new message", %{
channel: channel,
moderator: moderator,
user: user
} do
{:ok, _} = Chat.ban_user(moderator, channel, user)
assert {:error, "You are permanently banned from this channel."} =
Chat.create_chat_message(user, channel, %{message: "not allowed?"})
end
test "adds log of mod actions", %{channel: channel, moderator: moderator, user: user} do
assert {:ok, record} = Chat.short_timeout_user(moderator, channel, user)
assert record.channel.id == channel.id
assert record.moderator.id == moderator.id
assert record.user.id == user.id
assert record.action == "short_timeout"
assert {:ok, %ChannelModerationLog{action: "long_timeout"}} =
Chat.long_timeout_user(moderator, channel, user)
assert {:ok, %ChannelModerationLog{action: "ban"}} = Chat.ban_user(moderator, channel, user)
end
test "moderation privileges are required to timeout", %{
channel: channel,
user: user
} do
assert {:error, :unauthorized} == Chat.short_timeout_user(user, channel, user)
assert {:error, :unauthorized} == Chat.long_timeout_user(user, channel, user)
assert {:error, :unauthorized} == Chat.ban_user(user, channel, user)
assert {:error, :unauthorized} == Chat.unban_user(user, channel, user)
end
test "admin can perform all mod actions", %{
channel: channel,
user: user
} do
admin = admin_fixture()
assert {:ok, _} = Chat.short_timeout_user(admin, channel, user)
assert {:ok, _} = Chat.long_timeout_user(admin, channel, user)
assert {:ok, _} = Chat.ban_user(admin, channel, user)
assert {:ok, _} = Chat.unban_user(admin, channel, user)
end
test "streamer can perform all mod actions", %{
channel: channel,
streamer: streamer,
user: user
} do
assert {:ok, _} = Chat.short_timeout_user(streamer, channel, user)
assert {:ok, _} = Chat.long_timeout_user(streamer, channel, user)
assert {:ok, _} = Chat.ban_user(streamer, channel, user)
assert {:ok, _} = Chat.unban_user(streamer, channel, user)
end
end
describe "chat settings button" do
test "toggle timestamp button toggles timestamps" do
user = user_fixture()
user_preferences = Accounts.get_user_preference!(user)
assert user_preferences.show_timestamps == false
{:ok, user_preferences} =
Accounts.update_user_preference(user_preferences, %{show_timestamps: true})
assert user_preferences.show_timestamps == true
end
test "toggle mod icons button toggles mod icons" do
user = user_fixture()
user_preferences = Accounts.get_user_preference!(user)
assert user_preferences.show_mod_icons == true
{:ok, user_preferences} =
Accounts.update_user_preference(user_preferences, %{show_mod_icons: false})
assert user_preferences.show_mod_icons == false
end
end
describe "chat safety & security" do
alias Glimesh.Chat.ChatMessage
setup do
streamer = streamer_fixture()
%{
channel: streamer.channel,
streamer: streamer
}
end
test "create_chat_message/3 with an account under 3 hours old fails when configured",
%{channel: channel, streamer: streamer} do
{:ok, channel} = Streams.update_channel(streamer, channel, %{minimum_account_age: 3})
assert {:error, "You must wait 180 more minutes to chat."} =
Chat.create_chat_message(user_fixture(), channel, "Hello world")
end
test "create_chat_message/3 with an unverified account fails when configured ",
%{channel: channel, streamer: streamer} do
{:ok, channel} = Streams.update_channel(streamer, channel, %{require_confirmed_email: true})
assert {:error, "You must confirm your email address before chatting."} =
Chat.create_chat_message(user_fixture(), channel, "Hello world")
end
end
end
| 34.684211 | 107 | 0.660741 |
f73248b684efd5bcb69f8f98bc34238d4fe6e5d3 | 1,108 | exs | Elixir | test/parser/set_parameter_values_response_test.exs | smiyabe/cwmp_ex | 9db322497aa3208b5985ccf496ada5286cde3925 | [
"Artistic-2.0"
] | 3 | 2017-11-29T05:07:35.000Z | 2019-12-18T17:16:41.000Z | test/parser/set_parameter_values_response_test.exs | smiyabe/cwmp_ex | 9db322497aa3208b5985ccf496ada5286cde3925 | [
"Artistic-2.0"
] | 1 | 2021-12-02T19:35:28.000Z | 2022-03-29T09:40:52.000Z | test/parser/set_parameter_values_response_test.exs | smiyabe/cwmp_ex | 9db322497aa3208b5985ccf496ada5286cde3925 | [
"Artistic-2.0"
] | 2 | 2017-11-29T05:07:30.000Z | 2020-11-10T07:10:42.000Z | defmodule CWMP.Protocol.Parser.SetParameterValuesResponseTest do
use ExUnit.Case, async: true
@sample """
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:cwmp="urn:dslforum-org:cwmp-1-0">
<SOAP-ENV:Header>
<cwmp:ID SOAP-ENV:mustUnderstand="1">50</cwmp:ID>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<cwmp:SetParameterValuesResponse>
<Status>0</Status>
</cwmp:SetParameterValuesResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
"""
@sample_result {:ok,%{cwmp_version: "1-0", entries: [%CWMP.Protocol.Messages.SetParameterValuesResponse{
status: 0}],
header: %CWMP.Protocol.Messages.Header{hold_requests: false, id: "50",
session_timeout: 30, no_more_requests: false}}}
test "parses SetParameterValuesResponse request" do
assert(CWMP.Protocol.Parser.parse(@sample) == @sample_result)
end
end
| 41.037037 | 275 | 0.674188 |
f7324d25e27dbf2ec2c956454c5288021e9d0309 | 774 | ex | Elixir | lib/ex_matchers/match.ex | 10Pines/ex_matchers | ff36b55eeaf3bd506d92abea497b297ab78f02b1 | [
"MIT"
] | 7 | 2016-07-11T13:17:34.000Z | 2019-07-24T18:27:02.000Z | lib/ex_matchers/match.ex | 10Pines/ex_matchers | ff36b55eeaf3bd506d92abea497b297ab78f02b1 | [
"MIT"
] | 2 | 2017-09-15T21:37:01.000Z | 2021-07-23T19:13:12.000Z | lib/ex_matchers/match.ex | 10Pines/ex_matchers | ff36b55eeaf3bd506d92abea497b297ab78f02b1 | [
"MIT"
] | 1 | 2017-09-15T21:39:22.000Z | 2017-09-15T21:39:22.000Z | defmodule ExMatchers.Match do
@moduledoc false
import ExUnit.Assertions
import ExMatchers.Custom
defprotocol MatchMatcher do
@fallback_to_any true
def to_match(actual, regex)
def to_not_match(actual, regex)
end
defimpl MatchMatcher, for: BitString do
def to_match(actual, regex) do
assert Regex.match?(regex, actual)
end
def to_not_match(actual, regex) do
refute Regex.match?(regex, actual)
end
end
defimpl MatchMatcher, for: Any do
def to_match(actual, regex) do
flunk "Match not supported between #{actual} and #{regex}"
end
def to_not_match(actual, regex) do
flunk "Match not supported between #{actual} and #{regex}"
end
end
defmatcher match(regex), matcher: MatchMatcher
end
| 22.764706 | 64 | 0.70155 |
f73270d9457f23e0cb199c16df5688c5b5cfdbe1 | 98 | ex | Elixir | test/unit/fixtures/compiler/transformers/struct_type_transformer/module_2.ex | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 40 | 2022-01-19T20:27:36.000Z | 2022-03-31T18:17:41.000Z | test/unit/fixtures/compiler/transformers/struct_type_transformer/module_2.ex | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 42 | 2022-02-03T22:52:43.000Z | 2022-03-26T20:57:32.000Z | test/unit/fixtures/compiler/transformers/struct_type_transformer/module_2.ex | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 3 | 2022-02-10T04:00:37.000Z | 2022-03-08T22:07:45.000Z | defmodule Hologram.Test.Fixtures.Compiler.StructTypeTransformer.Module2 do
defstruct b: nil
end
| 24.5 | 74 | 0.846939 |
f73281311964f9253a5aedc95a145b66e0f60c09 | 7 | ex | Elixir | testData/org/elixir_lang/parser_definition/list_dot_operation_parsing_test_case/AtomKeyword.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/list_dot_operation_parsing_test_case/AtomKeyword.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/list_dot_operation_parsing_test_case/AtomKeyword.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 145 | 2015-01-15T11:37:16.000Z | 2021-12-22T05:51:02.000Z | [].true | 7 | 7 | 0.571429 |
f7329790f16e720e565f906b40c5a8485db6651e | 1,031 | exs | Elixir | test/lib/openflow/ofp_desc_stats_test.exs | shun159/tres | 1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f | [
"Beerware"
] | 5 | 2019-05-25T02:25:13.000Z | 2020-10-06T17:00:03.000Z | test/lib/openflow/ofp_desc_stats_test.exs | shun159/tres | 1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f | [
"Beerware"
] | 5 | 2018-03-29T14:42:10.000Z | 2019-11-19T07:03:09.000Z | test/lib/openflow/ofp_desc_stats_test.exs | shun159/tres | 1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f | [
"Beerware"
] | 1 | 2019-03-30T20:48:27.000Z | 2019-03-30T20:48:27.000Z | defmodule OfpDescTest do
use ExUnit.Case
describe "Openflow.Multipart.Desc.Request" do
test "with default values" do
desc = Openflow.Multipart.Desc.Request.new(0)
desc
|> Openflow.to_binary()
|> Openflow.read()
|> Kernel.elem(1)
|> Kernel.==(desc)
|> assert()
end
end
describe "Openflow.Multipart.Desc.Reply" do
test "with default values" do
desc =
%Openflow.Multipart.Desc.Reply{
dp_desc: "None",
hw_desc: "Open vSwitch",
mfr_desc: "Nicira, Inc.",
serial_num: "None",
sw_desc: "2.11.0"
}
|> Map.to_list()
|> Openflow.Multipart.Desc.Reply.new()
|> Openflow.to_binary()
|> Openflow.read()
|> Kernel.elem(1)
assert desc.xid == 0
assert desc.mfr_desc == "Nicira, Inc."
assert desc.dp_desc == "None"
assert desc.hw_desc == "Open vSwitch"
assert desc.sw_desc == "2.11.0"
assert desc.serial_num == "None"
end
end
end
| 24.547619 | 51 | 0.563531 |
f73299b81b214ce247996ec34e9f1541f82be0ec | 480 | exs | Elixir | test/models/order_test.exs | the5fire/ex_admin_demo | 655540499a68670c7349974b47c5e0bfee29aa99 | [
"MIT"
] | 22 | 2016-03-31T02:58:09.000Z | 2020-06-16T02:37:16.000Z | test/models/order_test.exs | the5fire/ex_admin_demo | 655540499a68670c7349974b47c5e0bfee29aa99 | [
"MIT"
] | 7 | 2016-03-27T14:22:59.000Z | 2021-04-27T14:33:51.000Z | test/models/order_test.exs | the5fire/ex_admin_demo | 655540499a68670c7349974b47c5e0bfee29aa99 | [
"MIT"
] | 13 | 2016-04-21T06:05:32.000Z | 2018-08-23T06:38:54.000Z | defmodule ExAdminDemo.OrderTest do
use ExAdminDemo.ModelCase
alias ExAdminDemo.Order
@valid_attrs %{user_id: 1, checked_out_at: "2010-04-17 14:00:00", total_price: "120.5"}
@invalid_attrs %{}
test "changeset with valid attributes" do
changeset = Order.changeset(%Order{}, @valid_attrs)
assert changeset.valid?
end
test "changeset with invalid attributes" do
changeset = Order.changeset(%Order{}, @invalid_attrs)
refute changeset.valid?
end
end
| 25.263158 | 89 | 0.727083 |
f73306e3b94ea8fa2382fe9db897980e98ca83a4 | 6,594 | ex | Elixir | lib/ash/data_layer/ets.ex | ChristianTovar/ash | 66435322786c5d0b90a34051da969b68dcc8a045 | [
"MIT"
] | null | null | null | lib/ash/data_layer/ets.ex | ChristianTovar/ash | 66435322786c5d0b90a34051da969b68dcc8a045 | [
"MIT"
] | null | null | null | lib/ash/data_layer/ets.ex | ChristianTovar/ash | 66435322786c5d0b90a34051da969b68dcc8a045 | [
"MIT"
] | null | null | null | defmodule Ash.DataLayer.Ets do
@moduledoc """
An ETS (Erlang Term Storage) backed Ash Datalayer, for testing.
This is used for testing. *Do not use this data layer in production*
"""
@behaviour Ash.DataLayer
@ets %Ash.Dsl.Section{
name: :ets,
describe: """
A section for configuring the ets data layer
""",
examples: [
"""
ets do
# Used in testing
private? true
end
"""
],
schema: [
private?: [
type: :boolean,
default: false
]
]
}
use Ash.Dsl.Extension, sections: [@ets]
alias Ash.Actions.Sort
alias Ash.Dsl.Extension
@spec private?(Ash.Resource.t()) :: boolean
def private?(resource) do
Extension.get_opt(resource, [:ets], :private?, false, true)
end
defmodule Query do
@moduledoc false
defstruct [:resource, :filter, :limit, :sort, :tenant, :api, relationships: %{}, offset: 0]
end
@impl true
def can?(resource, :async_engine) do
not private?(resource)
end
def can?(_, :composite_primary_key), do: true
def can?(_, :multitenancy), do: true
def can?(_, :upsert), do: true
def can?(_, :create), do: true
def can?(_, :read), do: true
def can?(_, :update), do: true
def can?(_, :destroy), do: true
def can?(_, :sort), do: true
def can?(_, :filter), do: true
def can?(_, :limit), do: true
def can?(_, :offset), do: true
def can?(_, :boolean_filter), do: true
def can?(_, :transact), do: false
def can?(_, {:filter_expr, _}), do: true
def can?(resource, {:join, other_resource}) do
# See the comment in can?/2 in mnesia data layer to explain this
not (private?(resource) and
Ash.DataLayer.data_layer(other_resource) == Ash.DataLayer.Mnesia)
end
def can?(_, :nested_expressions), do: true
def can?(_, {:query_aggregate, :count}), do: true
def can?(_, {:sort, _}), do: true
def can?(_, _), do: false
@impl true
def resource_to_query(resource, api) do
%Query{
resource: resource,
api: api
}
end
@impl true
def limit(query, offset, _), do: {:ok, %{query | limit: offset}}
@impl true
def offset(query, offset, _), do: {:ok, %{query | offset: offset}}
@impl true
def set_tenant(_resource, query, tenant) do
{:ok, %{query | tenant: tenant}}
end
@impl true
def filter(query, filter, _resource) do
{:ok, %{query | filter: filter}}
end
@impl true
def sort(query, sort, _resource) do
{:ok, %{query | sort: sort}}
end
@impl true
def run_aggregate_query(%{api: api} = query, aggregates, resource) do
case run_query(query, resource) do
{:ok, results} ->
Enum.reduce_while(aggregates, {:ok, %{}}, fn
%{kind: :count, name: name, query: query}, {:ok, acc} ->
results
|> filter_matches(Map.get(query || %{}, :filter), api)
|> case do
{:ok, matches} ->
{:cont, {:ok, Map.put(acc, name, Enum.count(matches))}}
{:error, error} ->
{:halt, {:error, error}}
end
_, _ ->
{:halt, {:error, "unsupported aggregate"}}
end)
end
end
@impl true
def run_query(
%Query{
resource: resource,
filter: filter,
offset: offset,
limit: limit,
sort: sort,
tenant: tenant,
api: api
},
_resource
) do
with {:ok, records} <- get_records(resource, tenant),
{:ok, filtered_records} <- filter_matches(records, filter, api) do
offset_records =
filtered_records
|> Sort.runtime_sort(sort)
|> Enum.drop(offset || 0)
limited_records =
if limit do
Enum.take(offset_records, limit)
else
offset_records
end
{:ok, limited_records}
else
{:error, error} -> {:error, error}
end
end
defp get_records(resource, tenant) do
with {:ok, table} <- wrap_or_create_table(resource, tenant),
{:ok, record_tuples} <- ETS.Set.to_list(table) do
{:ok, Enum.map(record_tuples, &elem(&1, 1))}
end
end
defp filter_matches(records, nil, _api), do: {:ok, records}
defp filter_matches(records, filter, api) do
Ash.Filter.Runtime.filter_matches(api, records, filter)
end
@impl true
def upsert(resource, changeset) do
update(resource, changeset)
end
@impl true
def create(resource, changeset) do
pkey =
resource
|> Ash.Resource.Info.primary_key()
|> Enum.into(%{}, fn attr ->
{attr, Ash.Changeset.get_attribute(changeset, attr)}
end)
with {:ok, table} <- wrap_or_create_table(resource, changeset.tenant),
{:ok, record} <- Ash.Changeset.apply_attributes(changeset),
record <- unload_relationships(resource, record),
{:ok, _} <- ETS.Set.put(table, {pkey, record}) do
{:ok, record}
else
{:error, error} -> {:error, error}
end
end
@impl true
def destroy(resource, %{data: record} = changeset) do
pkey = Map.take(record, Ash.Resource.Info.primary_key(resource))
with {:ok, table} <- wrap_or_create_table(resource, changeset.tenant),
{:ok, _} <- ETS.Set.delete(table, pkey) do
:ok
else
{:error, error} -> {:error, error}
end
end
@impl true
def update(resource, changeset) do
create(resource, changeset)
end
defp unload_relationships(resource, record) do
empty = resource.__struct__
resource
|> Ash.Resource.Info.relationships()
|> Enum.reduce(record, fn relationship, record ->
Map.put(record, relationship.name, Map.get(empty, relationship.name))
end)
end
# sobelow_skip ["DOS.StringToAtom"]
defp wrap_or_create_table(resource, tenant) do
table =
if tenant do
String.to_atom(to_string(tenant) <> to_string(resource))
else
resource
end
case ETS.Set.wrap_existing(table) do
{:error, :table_not_found} ->
protection =
if private?(resource) do
:private
else
:public
end
case ETS.Set.new(
name: table,
protection: protection,
ordered: true,
read_concurrency: true
) do
{:ok, tab} ->
{:ok, tab}
{:error, :table_already_exists} ->
ETS.Set.wrap_existing(table)
other ->
other
end
{:ok, table} ->
{:ok, table}
{:error, other} ->
{:error, other}
end
end
end
| 24.789474 | 95 | 0.57613 |
f73321ff4b595a3c473892b1b0839500abaf4420 | 270 | ex | Elixir | backend/lib/spades_util/slugify.ex | mreishus/spades | 3e06fa5c2415ff43258ec4c231f8d6c49c683fe0 | [
"MIT"
] | 9 | 2019-10-28T08:48:50.000Z | 2021-03-05T09:44:46.000Z | backend/lib/spades_util/slugify.ex | mreishus/spades | 3e06fa5c2415ff43258ec4c231f8d6c49c683fe0 | [
"MIT"
] | 227 | 2019-10-28T08:52:58.000Z | 2022-02-27T04:31:42.000Z | backend/lib/spades_util/slugify.ex | mreishus/spades | 3e06fa5c2415ff43258ec4c231f8d6c49c683fe0 | [
"MIT"
] | 4 | 2020-04-18T19:38:37.000Z | 2021-08-02T19:43:03.000Z | defmodule SpadesUtil.Slugify do
@moduledoc """
Slugify: Make a string suitable for a url by lowercasing it
and changing non-word characters to spaces.
"""
def slugify(str) do
str
|> String.downcase()
|> String.replace(~r/[^\w-]+/u, "-")
end
end
| 22.5 | 62 | 0.648148 |
f73332740aaec8ccb3e28c5b8c0cb15b55cce9c2 | 509 | exs | Elixir | apps/snitch_core/priv/repo/migrations/20181217085522_add_promotion_rule.exs | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 456 | 2018-09-20T02:40:59.000Z | 2022-03-07T08:53:48.000Z | apps/snitch_core/priv/repo/migrations/20181217085522_add_promotion_rule.exs | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 273 | 2018-09-19T06:43:43.000Z | 2021-08-07T12:58:26.000Z | apps/snitch_core/priv/repo/migrations/20181217085522_add_promotion_rule.exs | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 122 | 2018-09-26T16:32:46.000Z | 2022-03-13T11:44:19.000Z | defmodule Snitch.Repo.Migrations.AddPromotionRule do
use Ecto.Migration
def change do
execute("CREATE EXTENSION IF NOT EXISTS citext")
create table("snitch_promotion_rules") do
add(:name, :citext, null: false)
add(:module, PromotionRuleEnum.type(), null: false)
add(:preferences, :map)
add(:promotion_id, references("snitch_promotions"),
null: false)
timestamps()
end
create unique_index("snitch_promotion_rules", [:name, :promotion_id])
end
end
| 26.789474 | 73 | 0.691552 |
f7335631f330f1673941be69cee57bd5042fd1d7 | 1,008 | exs | Elixir | backend/config/config.exs | djquan/budget.sh.old | e0c3ac772ce061c4a8c990ef86ea341172146d18 | [
"MIT"
] | 2 | 2019-09-08T23:26:20.000Z | 2019-10-04T21:05:40.000Z | backend/config/config.exs | djquan/budget.sh | e0c3ac772ce061c4a8c990ef86ea341172146d18 | [
"MIT"
] | null | null | null | backend/config/config.exs | djquan/budget.sh | e0c3ac772ce061c4a8c990ef86ea341172146d18 | [
"MIT"
] | null | null | null | # 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.
# General application configuration
use Mix.Config
config :budgetsh,
ecto_repos: [BudgetSH.Repo]
# Configures the endpoint
config :budgetsh, BudgetSHWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "bZCu1qesDOmlOWq8C46JVcmfQ89kJG+nJm4EhBAS9CqpEP4bSlDvE0ZIQXnFKyfF",
render_errors: [view: BudgetSHWeb.ErrorView, accepts: ~w(json)],
pubsub: [name: BudgetSH.PubSub, adapter: Phoenix.PubSub.PG2]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env()}.exs"
| 32.516129 | 86 | 0.771825 |
f73368533a9f48bc11d05d144be6ae4b5447471c | 690 | exs | Elixir | test/data/sample_row_keys_test.exs | rockneurotiko/bigtable | a83d0c3e513a212265b2f6fc775407fa71ac049c | [
"MIT"
] | 17 | 2019-01-22T12:59:38.000Z | 2021-12-13T10:41:52.000Z | test/data/sample_row_keys_test.exs | rockneurotiko/bigtable | a83d0c3e513a212265b2f6fc775407fa71ac049c | [
"MIT"
] | 17 | 2019-01-27T18:11:33.000Z | 2020-02-24T10:16:08.000Z | test/data/sample_row_keys_test.exs | rockneurotiko/bigtable | a83d0c3e513a212265b2f6fc775407fa71ac049c | [
"MIT"
] | 3 | 2019-02-04T17:08:09.000Z | 2021-04-07T07:13:53.000Z | defmodule SampleRowKeysTest do
@moduledoc false
alias Bigtable.SampleRowKeys
use ExUnit.Case
doctest SampleRowKeys
describe "SampleRowKeys.build()" do
test "should build a SampleRowKeysRequest with configured table" do
assert SampleRowKeys.build() == expected_request()
end
test "should build a ReadRowsRequest with custom table" do
table_name = "custom-table"
assert SampleRowKeys.build(table_name) == expected_request(table_name)
end
end
defp expected_request(table_name \\ Bigtable.Utils.configured_table_name()) do
%Google.Bigtable.V2.SampleRowKeysRequest{
app_profile_id: "",
table_name: table_name
}
end
end
| 24.642857 | 80 | 0.733333 |
f7336a03298a5e9b009a8bc497e7a622a649f8a9 | 254 | ex | Elixir | lib/evolvr/parallel.ex | matthewmacleod/evolvr | 6392f0e03a8218ea70e86afdd187dcf728155072 | [
"MIT"
] | 3 | 2015-12-29T21:13:23.000Z | 2017-08-14T22:35:25.000Z | lib/evolvr/parallel.ex | matthewmacleod/evolvr | 6392f0e03a8218ea70e86afdd187dcf728155072 | [
"MIT"
] | null | null | null | lib/evolvr/parallel.ex | matthewmacleod/evolvr | 6392f0e03a8218ea70e86afdd187dcf728155072 | [
"MIT"
] | null | null | null | defmodule Parallel do
def pmap(collection, fun) do
me = self
collection
|> Enum.map(fn (elem) -> spawn_link fn -> (send me, {self, fun.(elem) }) end end)
|> Enum.map(fn (pid) -> receive do { ^pid, result } -> result end end)
end
end
| 25.4 | 85 | 0.602362 |
f733b23866095314ee7942ebc0b864aa67ead4e3 | 2,983 | exs | Elixir | test/integration/response_factory_test.exs | fcapovilla/fake_server | 68ee414ed421127f5aaca19c104b7ba01c12d716 | [
"Apache-2.0"
] | null | null | null | test/integration/response_factory_test.exs | fcapovilla/fake_server | 68ee414ed421127f5aaca19c104b7ba01c12d716 | [
"Apache-2.0"
] | null | null | null | test/integration/response_factory_test.exs | fcapovilla/fake_server | 68ee414ed421127f5aaca19c104b7ba01c12d716 | [
"Apache-2.0"
] | null | null | null | defmodule MyResponseFactory do
use FakeServer.ResponseFactory
def person_response do
ok(%{
name: Faker.Name.name,
email: Faker.Internet.free_email,
company: %{name: Faker.Company.name, county: Faker.Address.country}
}, %{"Content-Type" => "application/json"})
end
end
defmodule FakeServer.Integration.ResponseFactoryTest do
use ExUnit.Case
import FakeServer
test_with_server "basic factory usage" do
customized_response = %{body: body} = MyResponseFactory.build(:person)
person = Poison.decode!(body)
route "/person", customized_response
response = HTTPoison.get! FakeServer.address <> "/person"
body = Poison.decode!(response.body)
assert response.status_code == 200
assert person["name"] == body["name"]
assert person["email"] == body["email"]
assert person["company"]["name"] == body["company"]["name"]
assert person["company"]["country"] == body["company"]["country"]
end
test_with_server "setting custom attributes" do
route "/person", MyResponseFactory.build(:person, name: "John", email: "[email protected]")
response = HTTPoison.get! FakeServer.address <> "/person"
body = Poison.decode!(response.body)
assert response.status_code == 200
assert body["name"] == "John"
assert body["email"] == "[email protected]"
end
test_with_server "deleting an attribute" do
route "/person", MyResponseFactory.build(:person, name: nil)
response = HTTPoison.get! FakeServer.address <> "/person"
body = Poison.decode!(response.body)
assert response.status_code == 200
assert body["name"] == nil
end
test_with_server "overriding a header" do
route "/person", MyResponseFactory.build(:person, %{"Content-Type" => "application/x-www-form-urlencoded"})
response = HTTPoison.get! FakeServer.address <> "/person"
assert response.status_code == 200
assert Enum.any?(response.headers, fn(header) -> header == {"Content-Type", "application/x-www-form-urlencoded"} end)
end
test_with_server "deleting a header" do
route "/person", MyResponseFactory.build(:person, %{"Content-Type" => nil})
response = HTTPoison.get! FakeServer.address <> "/person"
assert response.status_code == 200
refute Enum.any?(response.headers, fn(header) -> elem(header, 0) == "Content-Type" end)
end
test_with_server "create a list of responses" do
person_list = MyResponseFactory.build_list(3, :person)
route "/person", person_list
Enum.each(person_list, fn(person) ->
response = HTTPoison.get! FakeServer.address <> "/person"
body = Poison.decode!(response.body)
person = Poison.decode!(person.body)
assert response.status_code == 200
assert person["name"] == body["name"]
assert person["email"] == body["email"]
assert person["company"]["name"] == body["company"]["name"]
assert person["company"]["country"] == body["company"]["country"]
end)
end
end
| 32.78022 | 121 | 0.680188 |
f733e24287a3b0ba30539652fb7f4a06eb09f88e | 1,711 | ex | Elixir | clients/service_management/lib/google_api/service_management/v1/model/backend.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/service_management/lib/google_api/service_management/v1/model/backend.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/service_management/lib/google_api/service_management/v1/model/backend.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.ServiceManagement.V1.Model.Backend do
@moduledoc """
`Backend` defines the backend configuration for a service.
## Attributes
* `rules` (*type:* `list(GoogleApi.ServiceManagement.V1.Model.BackendRule.t)`, *default:* `nil`) - A list of API backend rules that apply to individual API methods.
**NOTE:** All service configuration rules follow "last one wins" order.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:rules => list(GoogleApi.ServiceManagement.V1.Model.BackendRule.t())
}
field(:rules, as: GoogleApi.ServiceManagement.V1.Model.BackendRule, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.ServiceManagement.V1.Model.Backend do
def decode(value, options) do
GoogleApi.ServiceManagement.V1.Model.Backend.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceManagement.V1.Model.Backend do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.918367 | 168 | 0.745763 |
f733e32c292ee9edae5f978c4a771fbe258cc05d | 2,015 | ex | Elixir | web/controllers/page_controller.ex | evadne/supervised-scaler | 30fa3275a3f9c16c79457ec2205e7bc129658713 | [
"MIT"
] | 44 | 2016-09-22T21:37:48.000Z | 2021-10-09T03:43:32.000Z | web/controllers/page_controller.ex | evadne/supervised-scaler | 30fa3275a3f9c16c79457ec2205e7bc129658713 | [
"MIT"
] | 3 | 2016-09-23T08:41:22.000Z | 2017-05-24T10:58:54.000Z | web/controllers/page_controller.ex | evadne/supervised-scaler | 30fa3275a3f9c16c79457ec2205e7bc129658713 | [
"MIT"
] | 5 | 2016-09-25T18:52:00.000Z | 2021-07-28T21:12:33.000Z | defmodule Scaler.PageController do
use Scaler.Web, :controller
def index(conn, _params) do
render conn, "index.html"
end
def preview(conn, params) do
path = params["image"].path
#
# we can assume that ImageMagick will always work for now
# n.b. this may very well not be the case
#
{:ok, {mogrify_diff, mogrify_base64}} = process_mogrify(path, 512, 512)
case process_resampler(path, 512, 512) do
{:ok, {resampler_diff, resampler_base64}} ->
render conn, "preview.html",
resampler_base64: resampler_base64,
resampler_diff: formatted_diff(resampler_diff),
mogrify_base64: mogrify_base64,
mogrify_diff: formatted_diff(mogrify_diff)
{:error, reason} ->
render conn, "preview.html",
resampler_error: reason,
mogrify_base64: mogrify_base64,
mogrify_diff: formatted_diff(mogrify_diff)
end
end
defp process_mogrify(path, width, height) do
start = System.monotonic_time()
%Mogrify.Image{path: image_path} = Mogrify.open(path)
|> Mogrify.resize_to_limit("#{width}x#{height}")
|> Mogrify.save
stop = System.monotonic_time()
diff = System.convert_time_unit(stop - start, :native, :micro_seconds)
{:ok, image_content} = File.read(image_path)
{:ok, {diff, Base.encode64(image_content)}}
end
defp process_resampler(path, width, height) do
start = System.monotonic_time()
results = Resampler.request(path, 512, 512)
stop = System.monotonic_time()
diff = System.convert_time_unit(stop - start, :native, :micro_seconds)
case results do
{:error, reason} = x -> x
{:ok, image_path} ->
{:ok, image_content} = File.read(image_path)
{:ok, {diff, Base.encode64(image_content)}}
end
end
defp formatted_diff(diff) when diff > 1000, do: [diff |> div(1000) |> Integer.to_string, "ms"]
defp formatted_diff(diff), do: [diff |> Integer.to_string, "µs"]
end
| 31.984127 | 96 | 0.648139 |
f733e5c4c92d8ddcaba3ab4c0edf3261c7bc2be4 | 32,739 | exs | Elixir | lib/iex/test/iex/helpers_test.exs | namjae/elixir | 6d1561a5939d68fb61f422b83271fbc824847395 | [
"Apache-2.0"
] | null | null | null | lib/iex/test/iex/helpers_test.exs | namjae/elixir | 6d1561a5939d68fb61f422b83271fbc824847395 | [
"Apache-2.0"
] | null | null | null | lib/iex/test/iex/helpers_test.exs | namjae/elixir | 6d1561a5939d68fb61f422b83271fbc824847395 | [
"Apache-2.0"
] | null | null | null | Code.require_file("../test_helper.exs", __DIR__)
defmodule IEx.HelpersTest do
use IEx.Case
import IEx.Helpers
describe "whereami" do
test "is disabled by default" do
assert capture_iex("whereami()") =~ "Pry session is not currently enabled"
end
test "shows current location for custom envs" do
whereami = capture_iex("whereami()", [], env: %{__ENV__ | line: 3})
assert whereami =~ "test/iex/helpers_test.exs:3"
assert whereami =~ "3: defmodule IEx.HelpersTest do"
end
test "prints message when location is not available" do
whereami = capture_iex("whereami()", [], env: %{__ENV__ | line: 30000})
assert whereami =~ "test/iex/helpers_test.exs:30000"
assert whereami =~ "Could not extract source snippet. Location is not available."
whereami = capture_iex("whereami()", [], env: %{__ENV__ | file: "nofile", line: 1})
assert whereami =~ "nofile:1"
assert whereami =~ "Could not extract source snippet. Location is not available."
end
end
if :erlang.system_info(:otp_release) >= '20' do
describe "breakpoints" do
setup do
on_exit(fn -> IEx.Pry.remove_breaks() end)
end
test "sets up a breakpoint with capture syntax" do
assert break!(URI.decode_query() / 2) == 1
assert IEx.Pry.breaks() == [{1, URI, {:decode_query, 2}, 1}]
end
test "sets up a breakpoint with call syntax" do
assert break!(URI.decode_query(_, %{})) == 1
assert IEx.Pry.breaks() == [{1, URI, {:decode_query, 2}, 1}]
end
test "sets up a breakpoint with guards syntax" do
assert break!(URI.decode_query(_, map) when is_map(map)) == 1
assert IEx.Pry.breaks() == [{1, URI, {:decode_query, 2}, 1}]
end
test "sets up a breakpoint on the given module" do
assert break!(URI, :decode_query, 2) == 1
assert IEx.Pry.breaks() == [{1, URI, {:decode_query, 2}, 1}]
end
test "resets breaks on the given id" do
assert break!(URI, :decode_query, 2) == 1
assert reset_break(1) == :ok
assert IEx.Pry.breaks() == [{1, URI, {:decode_query, 2}, 0}]
end
test "resets breaks on the given module" do
assert break!(URI, :decode_query, 2) == 1
assert reset_break(URI, :decode_query, 2) == :ok
assert IEx.Pry.breaks() == [{1, URI, {:decode_query, 2}, 0}]
end
test "removes breaks in the given module" do
assert break!(URI.decode_query() / 2) == 1
assert remove_breaks(URI) == :ok
assert IEx.Pry.breaks() == []
end
test "removes breaks on all modules" do
assert break!(URI.decode_query() / 2) == 1
assert remove_breaks() == :ok
assert IEx.Pry.breaks() == []
end
test "errors when setting up a breakpoint with invalid guard" do
assert_raise CompileError, ~r"cannot invoke local is_whatever/1 inside guard", fn ->
break!(URI.decode_query(_, map) when is_whatever(map))
end
end
test "errors when setting up a break with no beam" do
assert_raise RuntimeError,
"could not set breakpoint, could not find .beam file for IEx.HelpersTest",
fn -> break!(__MODULE__, :setup, 1) end
end
test "errors when setting up a break for unknown function" do
assert_raise RuntimeError,
"could not set breakpoint, unknown function/macro URI.unknown/2",
fn -> break!(URI, :unknown, 2) end
end
test "errors for non-Elixir modules" do
assert_raise RuntimeError,
"could not set breakpoint, module :elixir was not written in Elixir",
fn -> break!(:elixir, :unknown, 2) end
end
test "prints table with breaks" do
break!(URI, :decode_query, 2)
assert capture_io(fn -> breaks() end) == """
ID Module.function/arity Pending stops
---- ----------------------- ---------------
1 URI.decode_query/2 1
"""
assert capture_io(fn -> URI.decode_query("foo=bar", %{}) end) != ""
assert capture_io(fn -> breaks() end) == """
ID Module.function/arity Pending stops
---- ----------------------- ---------------
1 URI.decode_query/2 0
"""
assert capture_io(fn -> URI.decode_query("foo=bar", %{}) end) == ""
assert capture_io(fn -> breaks() end) == """
ID Module.function/arity Pending stops
---- ----------------------- ---------------
1 URI.decode_query/2 0
"""
end
test "does not print table when there are no breaks" do
assert capture_io(fn -> breaks() end) == "No breakpoints set\n"
end
end
end
describe "open" do
@iex_helpers "iex/lib/iex/helpers.ex"
@elixir_erl "elixir/src/elixir.erl"
{:ok, vsn} = :application.get_key(:stdlib, :vsn)
@lists_erl "lib/stdlib-#{vsn}/src/lists.erl"
@httpc_erl "src/http_client/httpc.erl"
@editor System.get_env("ELIXIR_EDITOR")
test "opens __FILE__ and __LINE__" do
System.put_env("ELIXIR_EDITOR", "echo __LINE__:__FILE__")
assert capture_iex("open({#{inspect(__ENV__.file)}, 3})") |> maybe_trim_quotes() ==
"3:#{__ENV__.file}"
after
System.put_env("ELIXIR_EDITOR", @editor)
end
test "opens Elixir module" do
assert capture_iex("open(IEx.Helpers)") |> maybe_trim_quotes() =~ ~r/#{@iex_helpers}:1$/
end
test "opens function" do
assert capture_iex("open(h)") |> maybe_trim_quotes() =~ ~r/#{@iex_helpers}:\d+$/
end
test "opens function/arity" do
assert capture_iex("open(b/1)") |> maybe_trim_quotes() =~ ~r/#{@iex_helpers}:\d+$/
assert capture_iex("open(h/0)") |> maybe_trim_quotes() =~ ~r/#{@iex_helpers}:\d+$/
end
test "opens module.function" do
assert capture_iex("open(IEx.Helpers.b)") |> maybe_trim_quotes() =~ ~r/#{@iex_helpers}:\d+$/
assert capture_iex("open(IEx.Helpers.h)") |> maybe_trim_quotes() =~ ~r/#{@iex_helpers}:\d+$/
end
test "opens module.function/arity" do
assert capture_iex("open(IEx.Helpers.b/1)") |> maybe_trim_quotes() =~
~r/#{@iex_helpers}:\d+$/
assert capture_iex("open(IEx.Helpers.h/0)") |> maybe_trim_quotes() =~
~r/#{@iex_helpers}:\d+$/
end
test "opens Erlang module" do
assert capture_iex("open(:elixir)") |> maybe_trim_quotes() =~ ~r/#{@elixir_erl}:\d+$/
end
test "opens Erlang module.function" do
assert capture_iex("open(:elixir.start)") |> maybe_trim_quotes() =~ ~r/#{@elixir_erl}:\d+$/
end
test "opens Erlang module.function/arity" do
assert capture_iex("open(:elixir.start/2)") |> maybe_trim_quotes() =~
~r/#{@elixir_erl}:\d+$/
end
test "opens OTP lists module" do
assert capture_iex("open(:lists)") |> maybe_trim_quotes() =~ ~r/#{@lists_erl}:\d+$/
end
test "opens OTP lists module.function" do
assert capture_iex("open(:lists.reverse)") |> maybe_trim_quotes() =~ ~r/#{@lists_erl}:\d+$/
end
test "opens OTP lists module.function/arity" do
assert capture_iex("open(:lists.reverse/1)") |> maybe_trim_quotes() =~
~r/#{@lists_erl}:\d+$/
end
test "opens OTP httpc module" do
assert capture_iex("open(:httpc)") |> maybe_trim_quotes() =~ ~r/#{@httpc_erl}:\d+$/
end
test "opens OTP httpc module.function" do
assert capture_iex("open(:httpc.request)") |> maybe_trim_quotes() =~ ~r/#{@httpc_erl}:\d+$/
end
test "opens OTP httpc module.function/arity" do
assert capture_iex("open(:httpc.request/1)") |> maybe_trim_quotes() =~
~r/#{@httpc_erl}:\d+$/
end
test "errors OTP preloaded module" do
assert capture_iex("open(:init)") =~ ~r"(Could not open)|(Invalid arguments)"
end
test "errors if module is not available" do
assert capture_iex("open(:unknown)") == "Could not open: :unknown. Module is not available."
end
test "errors if module.function is not available" do
assert capture_iex("open(:unknown.unknown)") ==
"Could not open: :unknown.unknown. Module is not available."
assert capture_iex("open(:elixir.unknown)") ==
"Could not open: :elixir.unknown. Function/macro is not available."
assert capture_iex("open(:lists.unknown)") ==
"Could not open: :lists.unknown. Function/macro is not available."
assert capture_iex("open(:httpc.unknown)") ==
"Could not open: :httpc.unknown. Function/macro is not available."
end
test "errors if module.function/arity is not available" do
assert capture_iex("open(:unknown.start/10)") ==
"Could not open: :unknown.start/10. Module is not available."
assert capture_iex("open(:elixir.start/10)") ==
"Could not open: :elixir.start/10. Function/macro is not available."
assert capture_iex("open(:lists.reverse/10)") ==
"Could not open: :lists.reverse/10. Function/macro is not available."
assert capture_iex("open(:httpc.request/10)") ==
"Could not open: :httpc.request/10. Function/macro is not available."
end
test "errors if module is in-memory" do
assert capture_iex("defmodule Foo, do: nil ; open(Foo)") =~
~r"Invalid arguments for open helper:"
after
cleanup_modules([Foo])
end
test "opens the current pry location" do
assert capture_iex("open()", [], env: %{__ENV__ | line: 3}) |> maybe_trim_quotes() ==
"#{__ENV__.file}:3"
end
test "errors if prying is not available" do
assert capture_iex("open()") == "Pry session is not currently enabled"
end
test "opens given {file, line}" do
assert capture_iex("open({#{inspect(__ENV__.file)}, 3})") |> maybe_trim_quotes() ==
"#{__ENV__.file}:3"
end
test "errors when given {file, line} is not available" do
assert capture_iex("open({~s[foo], 3})") ==
"Could not open: \"foo\". File is not available."
end
defp maybe_trim_quotes(string) do
case :os.type() do
{:win32, _} -> String.replace(string, "\"", "")
_ -> string
end
end
end
describe "clear" do
test "clear the screen with ansi" do
Application.put_env(:elixir, :ansi_enabled, true)
assert capture_iex("clear()") == "\e[H\e[2J"
Application.put_env(:elixir, :ansi_enabled, false)
assert capture_iex("clear()") =~
"Cannot clear the screen because ANSI escape codes are not enabled on this shell"
after
Application.delete_env(:elixir, :ansi_enabled)
end
end
describe "runtime_info" do
test "shows vm information" do
assert "\n## System and architecture" <> _ = capture_io(fn -> runtime_info() end)
end
end
describe "h" do
test "shows help" do
assert "* IEx.Helpers\n\nWelcome to Interactive Elixir" <> _ = capture_iex("h()")
end
test "prints module documentation" do
assert "* IEx.Helpers\n\nWelcome to Interactive Elixir" <> _ =
capture_io(fn -> h(IEx.Helpers) end)
assert capture_io(fn -> h(:whatever) end) ==
"Could not load module :whatever, got: nofile\n"
assert capture_io(fn -> h(:lists) end) ==
"Documentation is not available for non-Elixir modules, got: :lists\n"
end
test "prints function documentation" do
pwd_h = "* def pwd()\n\nPrints the current working directory.\n\n"
c_h = "* def c(files, path \\\\ :in_memory)\n\nCompiles the given files."
eq_h =
"* def ==(left, right)\n\n @spec term() == term() :: boolean()\n\nReturns `true` if the two items are equal.\n\n"
assert capture_io(fn -> h(IEx.Helpers.pwd() / 0) end) =~ pwd_h
assert capture_io(fn -> h(IEx.Helpers.c() / 2) end) =~ c_h
assert capture_io(fn -> h(== / 2) end) =~ eq_h
assert capture_io(fn -> h(IEx.Helpers.c() / 1) end) =~ c_h
assert capture_io(fn -> h(pwd) end) =~ pwd_h
end
test "prints __info__ documentation" do
h_output_module = capture_io(fn -> h(Module.__info__()) end)
assert capture_io(fn -> h(Module.UnlikelyTo.Exist.__info__()) end) == h_output_module
assert capture_io(fn -> h(Module.UnlikelyTo.Exist.__info__() / 1) end) == h_output_module
assert capture_io(fn -> h(__info__) end) ==
"No documentation for Kernel.__info__ was found\n"
end
test "considers underscored functions without docs by default" do
content = """
defmodule Sample do
def __foo__(), do: 0
@doc "Bar doc"
def __bar__(), do: 1
end
"""
filename = "sample.ex"
with_file(filename, content, fn ->
assert c(filename, ".") == [Sample]
assert capture_io(fn -> h(Sample.__foo__()) end) ==
"No documentation for Sample.__foo__ was found\n"
assert capture_io(fn -> h(Sample.__bar__()) end) == "* def __bar__()\n\nBar doc\n"
assert capture_io(fn -> h(Sample.__foo__() / 0) end) ==
"No documentation for Sample.__foo__/0 was found\n"
assert capture_io(fn -> h(Sample.__bar__() / 0) end) == "* def __bar__()\n\nBar doc\n"
end)
after
cleanup_modules([Sample])
end
test "prints callback documentation when function docs are not available" do
behaviour = """
defmodule MyBehaviour do
@doc "Docs for MyBehaviour.first"
@callback first(integer) :: integer
@callback second(integer) :: integer
@callback second(integer, integer) :: integer
end
"""
impl = """
defmodule Impl do
@behaviour MyBehaviour
def first(0), do: 0
@doc "Docs for Impl.second/1"
def second(0), do: 0
@doc "Docs for Impl.second/2"
def second(0, 0), do: 0
end
"""
files = ["my_behaviour.ex", "impl.ex"]
with_file(files, [behaviour, impl], fn ->
assert c(files, ".") |> Enum.sort() == [Impl, MyBehaviour]
assert capture_io(fn -> h(Impl.first() / 1) end) ==
"@callback first(integer()) :: integer()\n\nDocs for MyBehaviour.first\n"
assert capture_io(fn -> h(Impl.second() / 1) end) ==
"* def second(int)\n\nDocs for Impl.second/1\n"
assert capture_io(fn -> h(Impl.second() / 2) end) ==
"* def second(int1, int2)\n\nDocs for Impl.second/2\n"
assert capture_io(fn -> h(Impl.first()) end) ==
"@callback first(integer()) :: integer()\n\nDocs for MyBehaviour.first\n"
assert capture_io(fn -> h(Impl.second()) end) ==
"* def second(int)\n\nDocs for Impl.second/1\n* def second(int1, int2)\n\nDocs for Impl.second/2\n"
assert capture_io(fn -> h(MyBehaviour.first()) end) == """
No documentation for function MyBehaviour.first was found, but there is a callback with the same name.
You can view callback documentations with the b/1 helper.\n
"""
assert capture_io(fn -> h(MyBehaviour.second() / 2) end) == """
No documentation for function MyBehaviour.second/2 was found, but there is a callback with the same name.
You can view callback documentations with the b/1 helper.\n
"""
assert capture_io(fn -> h(MyBehaviour.second() / 3) end) ==
"No documentation for MyBehaviour.second/3 was found\n"
end)
after
cleanup_modules([Impl, MyBehaviour])
end
test "prints documentation for delegates" do
filename = "delegate.ex"
content = """
defmodule Delegator do
defdelegate func1, to: Delegated
@doc "Delegator func2 doc"
defdelegate func2, to: Delegated
end
defmodule Delegated do
def func1, do: 1
def func2, do: 2
end
"""
with_file(filename, content, fn ->
assert c(filename, ".") |> Enum.sort() == [Delegated, Delegator]
assert capture_io(fn -> h(Delegator.func1()) end) ==
"* def func1()\n\nSee `Delegated.func1/0`.\n"
assert capture_io(fn -> h(Delegator.func2()) end) ==
"* def func2()\n\nDelegator func2 doc\n"
end)
after
cleanup_modules([Delegated, Delegator])
end
end
describe "b" do
test "lists all callbacks for a module" do
assert capture_io(fn -> b(Mix) end) == "No callbacks for Mix were found\n"
assert capture_io(fn -> b(NoMix) end) == "Could not load module NoMix, got: nofile\n"
assert capture_io(fn -> b(Mix.SCM) end) =~ """
@callback accepts_options(app :: atom(), opts()) :: opts() | nil
@callback checked_out?(opts()) :: boolean()
"""
end
test "lists callback with multiple clauses" do
filename = "multiple_clauses_callback.ex"
content = """
defmodule MultipleClauseCallback do
@doc "callback"
@callback test(:foo) :: integer
@callback test(:bar) :: [integer]
end
"""
with_file(filename, content, fn ->
assert c(filename, ".") == [MultipleClauseCallback]
assert capture_io(fn -> b(MultipleClauseCallback) end) =~ """
@callback test(:foo) :: integer()
@callback test(:bar) :: [integer()]
"""
end)
after
cleanup_modules([MultipleClauseCallback])
end
test "prints callback documentation" do
assert capture_io(fn -> b(Mix.Task.stop()) end) ==
"No documentation for Mix.Task.stop was found\n"
assert capture_io(fn -> b(Mix.Task.run()) end) =~
"@callback run(command_line_args :: [binary()]) :: any()\n\nA task needs to implement `run`"
assert capture_io(fn -> b(NoMix.run()) end) == "Could not load module NoMix, got: nofile\n"
assert capture_io(fn -> b(Exception.message() / 1) end) ==
"@callback message(t()) :: String.t()\n\n"
end
end
describe "t" do
test "prints when there is no type information" do
assert capture_io(fn -> t(IEx) end) == "No type information for IEx was found\n"
end
test "prints all types in module" do
# Test that it shows at least two types
assert Enum.count(capture_io(fn -> t(Enum) end) |> String.split("\n"), fn line ->
String.starts_with?(line, "@type")
end) >= 2
end
test "prints type information" do
assert "@type t() :: " <> _ = capture_io(fn -> t(Enum.t()) end)
assert capture_io(fn -> t(Enum.t()) end) == capture_io(fn -> t(Enum.t() / 0) end)
assert "@opaque t(value)\n\n@type t() :: t(term())\n\n" =
capture_io(fn -> t(MapSet.t()) end)
assert capture_io(fn -> t(URI.t()) end) == capture_io(fn -> t(URI.t() / 0) end)
end
test "prints type documentation" do
content = """
defmodule TypeSample do
@typedoc "An id with description."
@type id_with_desc :: {number, String.t}
end
"""
filename = "typesample.ex"
with_file(filename, content, fn ->
assert c(filename, ".") == [TypeSample]
assert capture_io(fn -> t(TypeSample.id_with_desc() / 0) end) == """
@type id_with_desc() :: {number(), String.t()}
An id with description.
"""
assert capture_io(fn -> t(TypeSample.id_with_desc()) end) == """
@type id_with_desc() :: {number(), String.t()}
An id with description.
"""
end)
after
cleanup_modules([TypeSample])
end
end
describe "v" do
test "returns history" do
assert "** (RuntimeError) v(0) is out of bounds" <> _ = capture_iex("v(0)")
assert "** (RuntimeError) v(1) is out of bounds" <> _ = capture_iex("v(1)")
assert "** (RuntimeError) v(-1) is out of bounds" <> _ = capture_iex("v(-1)")
assert capture_iex("1\n2\nv(2)") == "1\n2\n2"
assert capture_iex("1\n2\nv(2)") == capture_iex("1\n2\nv(-1)")
assert capture_iex("1\n2\nv(2)") == capture_iex("1\n2\nv()")
end
end
describe "flush" do
test "flushes messages" do
assert capture_io(fn ->
send(self(), :hello)
flush()
end) == ":hello\n"
end
end
describe "pwd" do
test "prints the working directory" do
File.cd!(iex_path(), fn ->
assert capture_io(fn -> pwd() end) =~ ~r"lib[\\/]iex\n$"
end)
end
end
describe "ls" do
test "lists the current directory" do
File.cd!(iex_path(), fn ->
paths =
capture_io(fn -> ls() end)
|> String.split()
|> Enum.map(&String.trim/1)
assert "ebin" in paths
assert "mix.exs" in paths
end)
end
test "lists the given directory" do
assert capture_io(fn -> ls("~") end) == capture_io(fn -> ls(System.user_home()) end)
end
end
describe "exports" do
test "prints module exports" do
exports = capture_io(fn -> exports(IEx.Autocomplete) end)
assert exports == "expand/1 expand/2 exports/1 \n"
end
end
describe "import_file" do
test "imports a file" do
with_file("dot-iex", "variable = :hello\nimport IO", fn ->
capture_io(:stderr, fn ->
assert "** (CompileError) iex:1: undefined function variable/0" <> _ =
capture_iex("variable")
end)
assert "** (CompileError) iex:1: undefined function puts/1" <> _ =
capture_iex("puts \"hi\"")
assert capture_iex("import_file \"dot-iex\"\nvariable\nputs \"hi\"") ==
"IO\n:hello\nhi\n:ok"
end)
end
test "imports a file that imports another file" do
dot = "parent = true\nimport_file \"dot-iex-1\""
dot_1 = "variable = :hello\nimport IO"
with_file(["dot-iex", "dot-iex-1"], [dot, dot_1], fn ->
capture_io(:stderr, fn ->
assert "** (CompileError) iex:1: undefined function parent/0" <> _ =
capture_iex("parent")
end)
assert "** (CompileError) iex:1: undefined function puts/1" <> _ =
capture_iex("puts \"hi\"")
assert capture_iex("import_file \"dot-iex\"\nvariable\nputs \"hi\"\nparent") ==
"IO\n:hello\nhi\n:ok\ntrue"
end)
end
test "raises if file is missing" do
failing = capture_iex("import_file \"nonexistent\"")
assert "** (File.Error) could not read file" <> _ = failing
assert failing =~ "no such file or directory"
end
test "does not raise if file is missing and using import_file_if_available" do
assert "nil" == capture_iex("import_file_if_available \"nonexistent\"")
end
end
describe "import_if_available" do
test "imports a module only if available" do
assert "nil" == capture_iex("import_if_available NoSuchModule")
assert "[1, 2, 3]" == capture_iex("import_if_available Integer; digits 123")
assert "[1, 2, 3]" ==
capture_iex("import_if_available Integer, only: [digits: 1]; digits 123")
end
end
describe "c" do
test "compiles a file" do
assert_raise UndefinedFunctionError, ~r"function Sample\.run/0 is undefined", fn ->
Sample.run()
end
filename = "sample.ex"
with_file(filename, test_module_code(), fn ->
assert c(Path.expand(filename)) == [Sample]
refute File.exists?("Elixir.Sample.beam")
assert Sample.run() == :run
end)
after
cleanup_modules([Sample])
end
test "handles errors" do
ExUnit.CaptureIO.capture_io(fn ->
with_file("sample.ex", "raise \"oops\"", fn ->
assert_raise CompileError, fn -> c("sample.ex") end
end)
end)
end
test "compiles a file with multiple modules " do
assert_raise UndefinedFunctionError, ~r"function Sample.run/0 is undefined", fn ->
Sample.run()
end
filename = "sample.ex"
with_file(filename, test_module_code() <> "\n" <> another_test_module(), fn ->
assert c(filename) |> Enum.sort() == [Sample, Sample2]
assert Sample.run() == :run
assert Sample2.hello() == :world
end)
after
cleanup_modules([Sample, Sample2])
end
test "compiles multiple modules" do
assert_raise UndefinedFunctionError, ~r"function Sample.run/0 is undefined", fn ->
Sample.run()
end
filenames = ["sample1.ex", "sample2.ex"]
with_file(filenames, [test_module_code(), another_test_module()], fn ->
assert c(filenames) |> Enum.sort() == [Sample, Sample2]
assert Sample.run() == :run
assert Sample2.hello() == :world
end)
after
cleanup_modules([Sample, Sample2])
end
test "compiles Erlang modules" do
assert_raise UndefinedFunctionError, ~r"function :sample.hello/0 is undefined", fn ->
:sample.hello()
end
filename = "sample.erl"
with_file(filename, erlang_module_code(), fn ->
assert c(filename) == [:sample]
assert :sample.hello() == :world
refute File.exists?("sample.beam")
end)
after
cleanup_modules([:sample])
end
test "skips unknown files" do
assert_raise UndefinedFunctionError, ~r"function :sample.hello/0 is undefined", fn ->
:sample.hello()
end
filenames = ["sample.erl", "not_found.ex", "sample2.ex"]
with_file(filenames, [erlang_module_code(), "", another_test_module()], fn ->
assert c(filenames) |> Enum.sort() == [Sample2, :sample]
assert :sample.hello() == :world
assert Sample2.hello() == :world
end)
after
cleanup_modules([:sample, Sample2])
end
test "compiles file in path" do
assert_raise UndefinedFunctionError, ~r"function Sample\.run/0 is undefined", fn ->
Sample.run()
end
filename = "sample.ex"
with_file(filename, test_module_code(), fn ->
assert c(filename, ".") == [Sample]
assert File.exists?("Elixir.Sample.beam")
assert Sample.run() == :run
end)
after
cleanup_modules([Sample])
end
end
describe "l" do
test "loads a given module" do
assert_raise UndefinedFunctionError, ~r"function Sample.run/0 is undefined", fn ->
Sample.run()
end
assert l(:nonexistent_module) == {:error, :nofile}
filename = "sample.ex"
with_file(filename, test_module_code(), fn ->
assert c(filename, ".") == [Sample]
assert Sample.run() == :run
File.write!(filename, "defmodule Sample do end")
elixirc(["sample.ex"])
assert l(Sample) == {:module, Sample}
message = "function Sample.run/0 is undefined or private"
assert_raise UndefinedFunctionError, message, fn ->
Sample.run()
end
end)
after
# Clean up the old version left over after l()
cleanup_modules([Sample])
end
end
describe "nl" do
test "loads a given module on the given nodes" do
assert nl(:nonexistent_module) == {:error, :nofile}
assert nl([node()], Enum) == {:ok, [{:nonode@nohost, :loaded, Enum}]}
assert nl([:nosuchnode@badhost], Enum) == {:ok, [{:nosuchnode@badhost, :badrpc, :nodedown}]}
capture_log(fn ->
assert nl([node()], :lists) == {:ok, [{:nonode@nohost, :error, :sticky_directory}]}
end)
end
end
describe "r" do
test "raises when reloading a nonexistent module" do
assert_raise ArgumentError, "could not load nor find module: :nonexistent_module", fn ->
r(:nonexistent_module)
end
end
test "reloads elixir modules" do
message = ~r"function Sample.run/0 is undefined \(module Sample is not available\)"
assert_raise UndefinedFunctionError, message, fn ->
Sample.run()
end
filename = "sample.ex"
with_file(filename, test_module_code(), fn ->
assert capture_io(:stderr, fn ->
assert c(filename, ".") == [Sample]
assert Sample.run() == :run
File.write!(filename, "defmodule Sample do end")
assert {:reloaded, Sample, [Sample]} = r(Sample)
message = "function Sample.run/0 is undefined or private"
assert_raise UndefinedFunctionError, message, fn ->
Sample.run()
end
end) =~ "redefining module Sample (current version loaded from Elixir.Sample.beam)"
end)
after
# Clean up old version produced by the r helper
cleanup_modules([Sample])
end
test "reloads Erlang modules" do
assert_raise UndefinedFunctionError, ~r"function :sample.hello/0 is undefined", fn ->
:sample.hello()
end
filename = "sample.erl"
with_file(filename, erlang_module_code(), fn ->
assert c(filename, ".") == [:sample]
assert :sample.hello() == :world
File.write!(filename, other_erlang_module_code())
assert {:reloaded, :sample, [:sample]} = r(:sample)
assert :sample.hello() == :bye
end)
after
cleanup_modules([:sample])
end
end
describe "pid" do
test "builds a pid from string" do
assert inspect(pid("0.32767.3276")) == "#PID<0.32767.3276>"
assert inspect(pid("0.5.6")) == "#PID<0.5.6>"
assert_raise ArgumentError, fn ->
pid("0.6.-6")
end
end
test "builds a pid from integers" do
assert inspect(pid(0, 32767, 3276)) == "#PID<0.32767.3276>"
assert inspect(pid(0, 5, 6)) == "#PID<0.5.6>"
assert_raise FunctionClauseError, fn ->
pid(0, 6, -6)
end
end
end
describe "i" do
test "prints information about the data type" do
assert capture_io(fn -> i(:ok) end) =~ """
Term
:ok
Data type
Atom
Reference modules
Atom\
"""
end
test "handles functions that don't display result" do
assert capture_io(fn -> i(IEx.dont_display_result()) end) =~ """
Term
:"do not show this result in output"
Data type
Atom
Description
This atom is returned by IEx when a function that should not print its
return value on screen is executed.\
"""
end
defmodule MyIExInfoModule do
defstruct []
defimpl IEx.Info do
def info(_), do: [{"A", "it's A"}, {:b, "it's :b"}, {'c', "it's 'c'"}]
end
end
test "uses the IEx.Info protocol" do
assert capture_io(fn -> i(%MyIExInfoModule{}) end) =~ """
Term
%IEx.HelpersTest.MyIExInfoModule{}
A
it's A
b
it's :b
c
it's 'c'
"""
after
cleanup_modules([MyIExInfoModule])
end
end
defp test_module_code do
"""
defmodule Sample do
def run do
:run
end
end
"""
end
defp another_test_module do
"""
defmodule Sample2 do
def hello do
:world
end
end
"""
end
defp erlang_module_code do
"""
-module(sample).
-export([hello/0]).
hello() -> world.
"""
end
defp other_erlang_module_code do
"""
-module(sample).
-export([hello/0]).
hello() -> bye.
"""
end
defp cleanup_modules(mods) do
Enum.each(mods, fn mod ->
File.rm("#{mod}.beam")
:code.purge(mod)
true = :code.delete(mod)
end)
end
defp with_file(names, codes, fun) when is_list(names) and is_list(codes) do
Enum.each(Enum.zip(names, codes), fn {name, code} ->
File.write!(name, code)
end)
try do
fun.()
after
Enum.each(names, &File.rm/1)
end
end
defp with_file(name, code, fun) do
with_file(List.wrap(name), List.wrap(code), fun)
end
defp elixirc(args) do
executable = Path.expand("../../../../bin/elixirc", __DIR__)
System.cmd("#{executable}#{executable_extension()}", args, stderr_to_stdout: true)
end
defp iex_path do
Path.expand("../..", __DIR__)
end
if match?({:win32, _}, :os.type()) do
defp executable_extension, do: ".bat"
else
defp executable_extension, do: ""
end
end
| 31.909357 | 124 | 0.577935 |
f733ec93657bbc573bdb3d2dbc62fe54b5c2622e | 4,379 | ex | Elixir | lib/ex_rets/base_xml_parser.ex | jdav-dev/ex_rets | 16eb6a1adc5d1d1eb259f86d6b09080c3c1068bf | [
"Apache-2.0"
] | 1 | 2019-12-20T14:23:19.000Z | 2019-12-20T14:23:19.000Z | lib/ex_rets/base_xml_parser.ex | jdav-dev/ex_rets | 16eb6a1adc5d1d1eb259f86d6b09080c3c1068bf | [
"Apache-2.0"
] | null | null | null | lib/ex_rets/base_xml_parser.ex | jdav-dev/ex_rets | 16eb6a1adc5d1d1eb259f86d6b09080c3c1068bf | [
"Apache-2.0"
] | null | null | null | defmodule ExRets.BaseXmlParser do
@moduledoc false
@moduledoc since: "0.1.0"
alias ExRets.HttpClient
@typedoc since: "0.1.0"
@type uri :: charlist()
@typedoc since: "0.1.0"
@type prefix :: charlist()
@typedoc since: "0.1.0"
@type attribute_name :: charlist()
@typedoc since: "0.1.0"
@type value :: charlist()
@typedoc since: "0.1.0"
@type attributes :: [{uri(), prefix(), attribute_name(), value()}]
@typedoc since: "0.1.0"
@type local_name :: charlist()
@typedoc since: "0.1.0"
@type qualified_name :: {prefix(), local_name()}
@typedoc since: "0.1.0"
@type target :: charlist()
@typedoc since: "0.1.0"
@type data :: charlist()
@typedoc since: "0.1.0"
@type public_id :: charlist()
@typedoc since: "0.1.0"
@type system_id :: charlist()
@typedoc since: "0.1.0"
@type name :: charlist()
@typedoc since: "0.1.0"
@type model :: charlist()
@typedoc since: "0.1.0"
@type element_name :: charlist()
@typedoc since: "0.1.0"
@type type :: charlist()
@typedoc since: "0.1.0"
@type mode :: charlist()
@typedoc since: "0.1.0"
@type n_data :: charlist()
@typedoc since: "0.1.0"
@type event ::
:startDocument
| :endDocument
| {:startPrefixMapping, prefix(), uri()}
| {:endPrefixMapping, prefix()}
| {:startElement, uri(), local_name(), qualified_name(), attributes()}
| {:endElement, uri(), local_name(), qualified_name()}
| {:characters, charlist()}
| {:ignorableWhitespace, charlist()}
| {:processingInstruction, target(), data()}
| {:comment, charlist()}
| :startCDATA
| :endCDATA
| {:startDTD, name(), public_id(), system_id()}
| :endDTD
| {:startEntity, system_id()}
| {:endEntity, system_id()}
| {:elementDecl, name(), model()}
| {:attributeDecl, element_name(), attribute_name(), type(), mode(), value()}
| {:internalEntityDecl, name(), value}
| {:externalEntityDecl, name(), public_id(), system_id()}
| {:unparsedEntityDecl, name(), public_id(), system_id(), n_data()}
| {:notationDecl, name(), public_id(), system_id()}
@typedoc since: "0.1.0"
@type current_location :: charlist()
@typedoc since: "0.1.0"
@type entity_name :: charlist()
@typedoc since: "0.1.0"
@type line_no :: integer
@typedoc since: "0.1.0"
@type location :: {current_location, entity_name, line_no}
@typedoc since: "0.1.0"
@type state :: any()
@typedoc since: "0.1.0"
@type event_fun :: (event(), location(), state() -> state())
@doc since: "0.1.0"
@spec parse(HttpClient.stream(), event_fun(), state(), HttpClient.implementation()) ::
{:ok, state()} | {:error, ExRets.reason()}
def parse(stream, event_fun, event_state, http_client_implementation) do
opts = [
continuation_fun: &continuation_fun/1,
event_fun: event_fun,
event_state: event_state
]
result =
with {:ok, xml, stream} <- http_client_implementation.stream_next(stream) do
opts = put_continuation_state(opts, stream, http_client_implementation)
xml
|> :xmerl_sax_parser.stream(opts)
|> format_xmerl_result()
end
http_client_implementation.close_stream(stream)
result
end
defp continuation_fun(%{stream: stream, http_client_implementation: implementation}) do
case implementation.stream_next(stream) do
{:ok, xml, stream} -> {xml, %{stream: stream, http_client_implementation: implementation}}
{:error, reason} -> throw({:error, reason})
end
end
defp put_continuation_state(opts, stream, http_client_implementation) do
continuation_state = %{stream: stream, http_client_implementation: http_client_implementation}
Keyword.put(opts, :continuation_state, continuation_state)
end
defp format_xmerl_result({:ok, event_state, _rest}) do
{:ok, event_state}
end
defp format_xmerl_result({:fatal_error, _location, reason, _end_tags, _event_state}) do
case reason do
{:error, reason} -> {:error, reason}
reason when is_list(reason) -> {:error, to_string(reason)}
reason when is_binary(reason) -> {:error, reason}
end
end
defp format_xmerl_result({:fatal_error, %RuntimeError{message: message}}) do
{:error, message}
end
end
| 28.809211 | 98 | 0.625714 |
f734163994f06d578daa8e710948ea0bb8d6e961 | 671 | ex | Elixir | lib/oli/activities/model/response.ex | malav2110/oli-torus | 8af64e762a7c8a2058bd27a7ab8e96539ffc055f | [
"MIT"
] | 45 | 2020-04-17T15:40:27.000Z | 2022-03-25T00:13:30.000Z | lib/oli/activities/model/response.ex | malav2110/oli-torus | 8af64e762a7c8a2058bd27a7ab8e96539ffc055f | [
"MIT"
] | 944 | 2020-02-13T02:37:01.000Z | 2022-03-31T17:50:07.000Z | lib/oli/activities/model/response.ex | malav2110/oli-torus | 8af64e762a7c8a2058bd27a7ab8e96539ffc055f | [
"MIT"
] | 23 | 2020-07-28T03:36:13.000Z | 2022-03-17T14:29:02.000Z | defmodule Oli.Activities.Model.Response do
defstruct [:id, :rule, :score, :feedback]
def parse(%{"id" => id, "rule" => rule, "score" => score, "feedback" => feedback}) do
case Oli.Activities.Model.Feedback.parse(feedback) do
{:ok, feedback} ->
{:ok,
%Oli.Activities.Model.Response{
id: id,
rule: rule,
score: score,
feedback: feedback
}}
error ->
error
end
end
def parse(responses) when is_list(responses) do
Enum.map(responses, &parse/1)
|> Oli.Activities.ParseUtils.items_or_errors()
end
def parse(_) do
{:error, "invalid response"}
end
end
| 23.137931 | 87 | 0.579732 |
f734320c6e92717092048d7010d221d4a024177a | 4,675 | ex | Elixir | debian.save/manpage.sgml.ex | m2osw/controlled_vars | fc1225525c38a56470e4c01193411ef7ef9f2ed5 | [
"MIT"
] | null | null | null | debian.save/manpage.sgml.ex | m2osw/controlled_vars | fc1225525c38a56470e4c01193411ef7ef9f2ed5 | [
"MIT"
] | null | null | null | debian.save/manpage.sgml.ex | m2osw/controlled_vars | fc1225525c38a56470e4c01193411ef7ef9f2ed5 | [
"MIT"
] | 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>November 25, 2013</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 "R. Douglas Barbieri">
<!ENTITY dhucpackage "<refentrytitle>CONTROLLEDVARS</refentrytitle>">
<!ENTITY dhpackage "controlledvars">
<!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.16129 | 75 | 0.659037 |
f73437468efb6952847ea46c36ba7f4d22fdc82d | 193 | ex | Elixir | lib/hexpm/block_address/entry.ex | Benjamin-Philip/hexpm | 6f38244f81bbabd234c660f46ea973849ba77a7f | [
"Apache-2.0"
] | 691 | 2017-03-08T09:15:45.000Z | 2022-03-23T22:04:47.000Z | lib/hexpm/block_address/entry.ex | Benjamin-Philip/hexpm | 6f38244f81bbabd234c660f46ea973849ba77a7f | [
"Apache-2.0"
] | 491 | 2017-03-07T12:58:42.000Z | 2022-03-29T23:32:54.000Z | lib/hexpm/block_address/entry.ex | Benjamin-Philip/hexpm | 6f38244f81bbabd234c660f46ea973849ba77a7f | [
"Apache-2.0"
] | 200 | 2017-03-12T23:03:39.000Z | 2022-03-05T17:55:52.000Z | defmodule Hexpm.BlockAddress.Entry do
use Hexpm.Schema
# TODO: rename to block_address_entries
schema "blocked_addresses" do
field :ip, :string
field :comment, :string
end
end
| 19.3 | 41 | 0.735751 |
f734378baecae72c8d0ebb0acb3f81885601a125 | 2,692 | ex | Elixir | lib/exgopigo/brain.ex | infiniteNIL/exgopigo | 01599e3ef367f378d9263d1fbab211f5f6502315 | [
"MIT"
] | 5 | 2015-05-30T23:51:26.000Z | 2016-05-05T21:10:48.000Z | lib/exgopigo/brain.ex | infiniteNIL/exgopigo | 01599e3ef367f378d9263d1fbab211f5f6502315 | [
"MIT"
] | null | null | null | lib/exgopigo/brain.ex | infiniteNIL/exgopigo | 01599e3ef367f378d9263d1fbab211f5f6502315 | [
"MIT"
] | null | null | null | defmodule ExGoPiGo.Brain do
use GenServer
alias ExGoPiGo.Board
alias ExGoPiGo.LEDs
alias ExGoPiGo.Servo
alias ExGoPiGo.UltraSonicSensor
alias ExGoPiGo.Compass
alias ExGoPiGo.Motors
alias ExGoPiGo.GPS
require Logger
@moduledoc """
The brain for our robot. Controls and responds to all the sensors, motors, etc.
"""
#####
# External API
@doc """
Initialize the Brain
"""
def start_link() do
GenServer.start_link(__MODULE__, [], name: __MODULE__)
end
############
# GenServer Implementation
@doc """
Initialize the robot's brain.
Return the process ID for the GoPiGoBoard
"""
def init(_) do
Logger.info "Exy is starting up."
{ :ok, _ } = Board.start_link()
{ :ok, _ } = Compass.start_link()
{ :ok, _ } = GPS.start_link()
status_report()
{ :ok, [] }
end
defp status_report() do
Logger.info "GoPiGo Firmware v#{Board.firmware_version()}"
Logger.info "Power: #{Board.voltage()} volts"
Logger.info "Encoder Status: #{Board.read_encoder_status()}"
Logger.info "Timeout Status: #{Board.read_timeout_status()}"
{lat, long} = GPS.location()
Logger.info "GPS Location: #{lat}, #{long}"
Logger.info "Heading: #{Compass.heading} degrees."
Logger.info "Distance: #{UltraSonicSensor.distance()} cm."
end
@doc """
Start the control loop for our robot. Continuously waits for sensor messages and responds to them.
Returns the pid of the background run loop task
"""
def run() do
run_loop()
shutdown()
end
defp run_loop() do
Motors.stop()
LEDs.blink(2)
shake_head(2)
dance()
end
defp shake_head(0) do
Servo.turn_to_degrees(90)
:timer.sleep(500)
end
defp shake_head(count) do
Servo.turn_to_degrees(60)
:timer.sleep(500)
Servo.turn_to_degrees(120)
:timer.sleep(500)
shake_head(count - 1)
end
defp dance() do
Motors.forward()
:timer.sleep(500)
Motors.backward()
:timer.sleep(500)
Motors.forward()
:timer.sleep(500)
Motors.backward()
:timer.sleep(500)
# heading = Compass.heading
# Logger.info "Starting heading: #{heading}"
#Motors.right_rotate()
#:timer.sleep(2000)
# rotate_until(pid, heading)
Motors.stop()
end
defp rotate_until(pid, heading) do
:timer.sleep(500)
current = Compass.heading
Logger.info "Current heading: #{current}"
if abs(current - heading) < 5.0 do
Logger.info "Reached heading #{heading} degrees"
Motors.stop(pid)
else
rotate_until(pid, heading)
end
end
defp test_servo(degrees) do
Servo.turn_to_degrees(degrees)
:timer.sleep(250)
if degrees + 30 <= 180 do
test_servo(degrees + 30)
end
end
defp shutdown() do
Logger.info "Exy is shutting down."
end
end
| 20.549618 | 99 | 0.676077 |
f734a4deab6a7476a445aaf8e5f25d367f5f184d | 382 | exs | Elixir | priv/repo/migrations/20210325232307_add_hotspot_address_to_devices_table.exs | maco2035/console | 2a9a65678b8c671c7d92cdb62dfcfc71b84957c5 | [
"Apache-2.0"
] | 83 | 2018-05-31T14:49:10.000Z | 2022-03-27T16:49:49.000Z | priv/repo/migrations/20210325232307_add_hotspot_address_to_devices_table.exs | maco2035/console | 2a9a65678b8c671c7d92cdb62dfcfc71b84957c5 | [
"Apache-2.0"
] | 267 | 2018-05-22T23:19:02.000Z | 2022-03-31T04:31:06.000Z | priv/repo/migrations/20210325232307_add_hotspot_address_to_devices_table.exs | maco2035/console | 2a9a65678b8c671c7d92cdb62dfcfc71b84957c5 | [
"Apache-2.0"
] | 18 | 2018-11-20T05:15:54.000Z | 2022-03-28T08:20:13.000Z | defmodule Console.Repo.Migrations.AddHotspotAddressToDevicesTable do
use Ecto.Migration
def up do
alter table("devices") do
add_if_not_exists :hotspot_address, :string
end
create index(:devices, [:hotspot_address])
end
def down do
drop index(:devices, [:hotspot_address])
alter table("devices") do
remove :hotspot_address
end
end
end
| 21.222222 | 68 | 0.709424 |
f73505374b12b6476c31185c7ec196460df8769c | 241 | ex | Elixir | lib/vutuv_web/views/api/password_view.ex | vutuv/vutuv | 174706cdaf28cef24e1cc06bec0884c25f2412be | [
"MIT"
] | 309 | 2016-05-03T17:16:23.000Z | 2022-03-01T09:30:22.000Z | lib/vutuv_web/views/api/password_view.ex | vutuv/vutuv | 174706cdaf28cef24e1cc06bec0884c25f2412be | [
"MIT"
] | 662 | 2016-04-27T07:45:18.000Z | 2022-01-05T07:29:19.000Z | lib/vutuv_web/views/api/password_view.ex | vutuv/vutuv | 174706cdaf28cef24e1cc06bec0884c25f2412be | [
"MIT"
] | 40 | 2016-04-27T07:46:22.000Z | 2021-12-31T05:54:34.000Z | defmodule VutuvWeb.Api.PasswordView do
use VutuvWeb, :view
def render("error.json", %{error: message}) do
%{errors: %{detail: message}}
end
def render("info.json", %{info: message}) do
%{info: %{detail: message}}
end
end
| 20.083333 | 48 | 0.647303 |
f7351bbff2e90ee3436bfcd59a3482dd3f4bd4d0 | 2,253 | ex | Elixir | lib/ex_aws/boto/util.ex | seanedwards/ex_aws_boto | 53603c77318befb7a146e8b24d79dcb0003dab72 | [
"MIT"
] | 2 | 2020-02-19T18:34:35.000Z | 2020-10-26T19:54:28.000Z | lib/ex_aws/boto/util.ex | seanedwards/ex_aws_boto | 53603c77318befb7a146e8b24d79dcb0003dab72 | [
"MIT"
] | null | null | null | lib/ex_aws/boto/util.ex | seanedwards/ex_aws_boto | 53603c77318befb7a146e8b24d79dcb0003dab72 | [
"MIT"
] | null | null | null | defmodule ExAws.Boto.Util do
@doc """
Converts a service ID and shape name into an Elixir module
## Examples
iex> ExAws.Boto.Util.module_name("SomeService", "TestObject")
ExAws.SomeService.TestObject
"""
def module_name(service_id, shape \\ nil)
def module_name(service_id, nil) do
["Elixir", "ExAws", Macro.camelize(service_id), "Api"]
|> Enum.join(".")
|> String.to_atom()
end
def module_name(service_id, %{"shape" => shape_name}) do
module_name(service_id, shape_name)
end
def module_name(service_id, shape_name) when is_binary(shape_name) do
["Elixir", "ExAws", Macro.camelize(service_id), Macro.camelize(shape_name)]
|> Enum.join(".")
|> String.to_atom()
end
def module_name(_, module) when is_atom(module) do
module
end
@doc """
Converts a string key from an AWS spec into an atom,
such as for a function call or struct property
## Examples
iex> ExAws.Boto.Util.key_to_atom("UserName")
:user_name
iex> ExAws.Boto.Util.key_to_atom("NotificationARNs")
:notification_arns
iex> ExAws.Boto.Util.key_to_atom("TestARNs")
:test_arns
iex> ExAws.Boto.Util.key_to_atom("VpcID")
:vpc_id
"""
def key_to_atom("NotificationARNs"), do: :notification_arns
def key_to_atom(key) when is_binary(key) do
key
|> to_charlist()
|> underscorify([])
|> :erlang.list_to_atom()
end
def key_to_atom(nil) do
nil
end
@doc """
Determines whether a single erlang character is a lowercase ASCII letter
"""
defguard is_lower(letter) when letter >= 97 and letter <= 122
@doc """
Determines whether a single erlang character is an uppercase ASCII letter
"""
defguard is_upper(letter) when letter >= 65 and letter <= 90
defp underscorify([lower, upper | rest], acc) when is_lower(lower) and is_upper(upper) do
# don't forget to append in reverse order
underscorify(rest, [upper + 32, 95, lower | acc])
end
defp underscorify([upper | rest], acc) when is_upper(upper) do
underscorify(rest, [upper + 32 | acc])
end
defp underscorify([lower | rest], acc) do
underscorify(rest, [lower | acc])
end
defp underscorify([], acc) do
acc
|> Enum.reverse()
end
end
| 25.033333 | 91 | 0.668886 |
f73544b98b16f9d3ba9dd89fb3577cfd978c94cb | 1,221 | ex | Elixir | lib/hl7/2.2/segments/in2.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | lib/hl7/2.2/segments/in2.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | lib/hl7/2.2/segments/in2.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | defmodule HL7.V2_2.Segments.IN2 do
@moduledoc false
require Logger
alias HL7.V2_2.{DataTypes}
use HL7.Segment,
fields: [
segment: nil,
insureds_employee_id: nil,
insureds_social_security_number: nil,
insureds_employer_name: nil,
employer_information_data: nil,
mail_claim_party: nil,
medicare_health_insurance_card_number: nil,
medicaid_case_name: DataTypes.Pn,
medicaid_case_number: nil,
champus_sponsor_name: DataTypes.Pn,
champus_id_number: nil,
dependent_of_champus_recipient: nil,
champus_organization: nil,
champus_station: nil,
champus_service: nil,
champus_rank_grade: nil,
champus_status: nil,
champus_retire_date: nil,
champus_non_availability_certification_on_file: nil,
baby_coverage: nil,
combine_baby_bill: nil,
blood_deductible: nil,
special_coverage_approval_name: DataTypes.Pn,
special_coverage_approval_title: nil,
non_covered_insurance_code: nil,
payor_id: nil,
payor_subscriber_id: nil,
eligibility_source: nil,
room_coverage_type_amount: nil,
policy_type_amount: nil,
daily_deductible: nil
]
end
| 29.071429 | 58 | 0.706798 |
f7359e30b6302c75198ebbe8538bc110bc97f64e | 730 | ex | Elixir | lib/colly_web/live/live_helpers.ex | nidhindamodaran/colly | aaf5076afa24ea69ec084f19c5617f6808b40ade | [
"MIT"
] | null | null | null | lib/colly_web/live/live_helpers.ex | nidhindamodaran/colly | aaf5076afa24ea69ec084f19c5617f6808b40ade | [
"MIT"
] | 4 | 2020-05-30T13:25:44.000Z | 2021-05-11T13:32:44.000Z | lib/colly_web/live/live_helpers.ex | nidhinnambiar/colly | aaf5076afa24ea69ec084f19c5617f6808b40ade | [
"MIT"
] | null | null | null | defmodule CollyWeb.LiveHelpers do
import Phoenix.LiveView.Helpers
@doc """
Renders a component inside the `CollyWeb.ModalComponent` component.
The rendered modal receives a `:return_to` option to properly update
the URL when the modal is closed.
## Examples
<%= live_modal @socket, CollyWeb.ItemLive.FormComponent,
id: @item.id || :new,
action: @live_action,
item: @item,
return_to: Routes.item_index_path(@socket, :index) %>
"""
def live_modal(socket, component, opts) do
path = Keyword.fetch!(opts, :return_to)
modal_opts = [id: :modal, return_to: path, component: component, opts: opts]
live_component(socket, CollyWeb.ModalComponent, modal_opts)
end
end
| 30.416667 | 80 | 0.694521 |
f735abd69badfda0d240cefc7fabb94b7e50934e | 5,792 | ex | Elixir | lib/gossip/socket.ex | adamkittelson/gossip-elixir | bf131fc0dd225d2e89a221571b27bad5d60db308 | [
"MIT"
] | null | null | null | lib/gossip/socket.ex | adamkittelson/gossip-elixir | bf131fc0dd225d2e89a221571b27bad5d60db308 | [
"MIT"
] | null | null | null | lib/gossip/socket.ex | adamkittelson/gossip-elixir | bf131fc0dd225d2e89a221571b27bad5d60db308 | [
"MIT"
] | null | null | null | defmodule Gossip.Socket do
@moduledoc """
The websocket connection to the Gossip network
"""
use WebSockex
alias Gossip.Message
require Logger
alias Gossip.Monitor
alias Gossip.Socket.Implementation
def url(), do: Application.get_env(:gossip, :url)
def start_link() do
state = %{
authenticated: false,
channels: [],
}
WebSockex.start_link(url(), __MODULE__, state, [name: Gossip.Socket])
end
def handle_connect(_conn, state) do
Monitor.monitor()
send(self(), {:authorize})
{:ok, state}
end
def handle_frame({:text, message}, state) do
case Implementation.receive(state, message) do
{:ok, state} ->
{:ok, state}
{:reply, message, state} ->
{:reply, {:text, message}, state}
:stop ->
Logger.info("Closing the Gossip websocket", type: :gossip)
{:close, state}
:error ->
{:ok, state}
end
end
def handle_frame(_frame, state) do
{:ok, state}
end
def handle_cast({:broadcast, channel, message}, state) do
case Implementation.broadcast(state, channel, message) do
{:reply, message, state} ->
{:reply, {:text, message}, state}
{:ok, state} ->
{:ok, state}
end
end
def handle_cast({:player_sign_in, player_name}, state) do
case Implementation.player_sign_in(state, player_name) do
{:reply, message, state} ->
{:reply, {:text, message}, state}
{:ok, state} ->
{:ok, state}
end
end
def handle_cast({:player_sign_out, player_name}, state) do
case Implementation.player_sign_out(state, player_name) do
{:reply, message, state} ->
{:reply, {:text, message}, state}
{:ok, state} ->
{:ok, state}
end
end
def handle_cast(_, state) do
{:ok, state}
end
def handle_info({:authorize}, state) do
{state, message} = Implementation.authorize(state)
{:reply, {:text, message}, state}
end
defmodule Implementation do
@moduledoc false
require Logger
def client_id(), do: Application.get_env(:gossip, :client_id)
def client_secret(), do: Application.get_env(:gossip, :client_secret)
def callback_module(), do: Application.get_env(:gossip, :callback_module)
def authorize(state) do
channels = callback_module().channels()
message = Poison.encode!(%{
"event" => "authenticate",
"payload" => %{
"client_id" => client_id(),
"client_secret" => client_secret(),
"user_agent" => callback_module().user_agent(),
"supports" => ["channels", "players"],
"channels" => channels,
},
})
state = Map.put(state, :channels, channels)
{state, message}
end
def receive(state, message) do
with {:ok, message} <- Poison.decode(message),
{:ok, state} <- process(state, message) do
{:ok, state}
else
:stop ->
:stop
{:reply, message, state} ->
{:reply, message, state}
_ ->
{:ok, state}
end
end
def broadcast(state, channel, message) do
case channel in state.channels do
true ->
message = Poison.encode!(%{
"event" => "messages/new",
"payload" => %{
"channel" => channel,
"name" => message.name,
"message" => message.message,
},
})
{:reply, message, state}
false ->
{:ok, state}
end
end
def player_sign_in(state, player_name) do
message = Poison.encode!(%{
"event" => "players/sign-in",
"payload" => %{
"name" => player_name,
},
})
{:reply, message, state}
end
def player_sign_out(state, player_name) do
message = Poison.encode!(%{
"event" => "players/sign-out",
"payload" => %{
"name" => player_name,
},
})
{:reply, message, state}
end
def process(state, message = %{"event" => "authenticate"}) do
case message do
%{"status" => "success"} ->
Logger.info("Authenticated against Gossip", type: :gossip)
{:ok, Map.put(state, :authenticated, true)}
%{"status" => "failure"} ->
Logger.info("Failed to authenticate against Gossip", type: :gossip)
:stop
_ ->
{:ok, state}
end
end
def process(state, %{"event" => "heartbeat"}) do
Logger.debug("Gossip heartbeat", type: :gossip)
message = Poison.encode!(%{
"event" => "heartbeat",
"payload" => %{
"players" => callback_module().players(),
},
})
{:reply, message, state}
end
def process(state, %{"event" => "messages/broadcast", "payload" => payload}) do
message = %Message{
channel: payload["channel"],
game: payload["game"],
name: payload["name"],
message: payload["message"],
}
callback_module().message_broadcast(message)
{:ok, state}
end
def process(state, %{"event" => "players/sign-in", "payload" => payload}) do
Logger.debug("New sign in event", type: :gossip)
game_name = Map.get(payload, "game")
player_name = Map.get(payload, "name")
callback_module().player_sign_in(game_name, player_name)
{:ok, state}
end
def process(state, %{"event" => "players/sign-out", "payload" => payload}) do
Logger.debug("New sign out event", type: :gossip)
game_name = Map.get(payload, "game")
player_name = Map.get(payload, "name")
callback_module().player_sign_out(game_name, player_name)
{:ok, state}
end
def process(state, _), do: {:ok, state}
end
end
| 23.544715 | 83 | 0.55922 |
f735c02e99f54aabc3402b244a3d948a30c3cd7c | 13,832 | ex | Elixir | lib/drab/config.ex | grych/drab | 27132d9be7b9755359af5b8c9022073441ea2009 | [
"MIT"
] | 933 | 2017-01-14T13:47:37.000Z | 2022-03-21T18:14:41.000Z | lib/drab/config.ex | grych/drab | 27132d9be7b9755359af5b8c9022073441ea2009 | [
"MIT"
] | 189 | 2017-01-15T18:35:06.000Z | 2022-01-24T17:41:22.000Z | lib/drab/config.ex | grych/drab | 27132d9be7b9755359af5b8c9022073441ea2009 | [
"MIT"
] | 54 | 2017-01-15T18:10:48.000Z | 2021-02-06T17:21:44.000Z | defmodule Drab.Config do
@moduledoc """
Drab configuration.
Drab works over the Phoenix Endpoints. You must provide configuration for each endpoint. The
minimum is to set up the endpoint module name, and the application name, so for the application
configured like:
config :my_app_web, MyAppWeb.Endpoint,
...
provide corresponding Drab configuration:
config :drab, MyAppWeb.Endpoint,
otp_app: :my_app_web,
...
There are also global Drab options, which can't be configured by the endpoint, like
`:enable_live_scripts`. See the whole list below.
## Configuration options:
### Endpoint related options
This options are set within the endpoint:
config :drab, MyAppWeb.Endpoint, option: value, option: value
#### :access_session *(default: `[]`)*
Keys of the session map, which will be included to the Drab Session globally, usually
`:user_id`, etc. See `Drab.Commander.access_session/1` for more.
#### :browser_response_timeout *(default: `5000`)*
Timeout, after which all functions querying/updating browser UI will give up; integer in
milliseconds, or `:infinity`.
#### :disable_controls_while_processing *(default: `true`)*
After sending request to the server, sender object will be disabled until it gets the answer.
Warning: this behaviour is not broadcasted, so only the control in the current browser is going
to be disabled.
#### :disable_controls_when_disconnected *(default: `true`)*
Shall controls be disabled when there is no connectivity between the browser and the server?
#### :drab_store_storage *(default: `:session_storage`)*
Where to keep the Drab Store - `:memory`, `:local_storage` or `:session_storage`. Data in
the memory is kept to the next page load, session storage persist until browser (or a tab)
is closed, local storage is kept forever.
#### :events_shorthands *(default: `["click", "change", "keyup", "keydown"]`)*
The list of the shorthand attributes to be used in drab-controlled DOM object, ie:
`<drab-click="handler">`. Please keep the list small, as it affects the client JS performance.
#### :events_to_disable_while_processing *(default: `["click"]`)*
Controls with those Drab events will be disabled when waiting for server response.
#### :js_socket_constructor, *(default: `"require(\"phoenix\").Socket"`)*
Javascript constructor for the Socket; more info in Drab.Client.
#### :live_conn_pass_through, *(default: `%{private: %{phoenix_endpoint: true,
phoenix_controller: true, phoenix_action: true}}`)*
A deep map marking fields which should be preserved in the fake `@conn` assign. See `Drab.Live`
for more detailed explanation on conn case.
#### :socket *(default: `"/socket"`)*
Path to the socket on which Drab operates.
#### :templates_path *(default: "priv/templates/drab")*
Path to the user-defined Drab templates (not to be confused with Phoenix application templates,
these are to be used internally, see `Drab.Modal` for the example usage). Must start with
"priv/".
#### :token_max_age *(default: `86_400`)*
Socket token max age in seconds.
### Global configuration options
Those options are set globally and works in every endpoint.
config :drab, option: value, option: value
#### :default_encoder *(default: `Drab.Coder.Cipher`)*
Sets the default encoder/decoder for the various functions, like `Drab.Browser.set_cookie/3`.
#### :default_modules *(default: `[Drab.Live, Drab.Element, Drab.Modal]`)*
Sets the default Drab Modules. May be overwritten individually in the commander with
`use Drab.Commander, modules: [...]`.
#### :enable_live_scripts *(default: `false`)*
Re-evaluation of JavaScripts containing living assigns is disabled by default.
#### :modal_css *(default: `:bootstrap3`)*
A CSS framework used to show `Drab.Modal`. Available: `:bootstrap3`, `:bootstrap4`.
#### :phoenix_channel_options *(default: `[]`)*
An options passed to `use Phoenix.Channel`, for example: `[log_handle_in: false]`.
#### :presence *(default: `false`)*
Runs the `Drab.Presence` server. Defaults to false to avoid unnecessary load. See
`Drab.Presence` for more information.
#### :secret_key_base *(default taken from endpoint)*
Random key for ciphering. May be generated by `mix phx.gen.secret`. In single-endpoint
configuration it is taken from the endpoint.
"""
@doc """
Returns the name of the client Phoenix Application for given endpoint.
iex> Drab.Config.app_name(DrabTestApp.Endpoint)
:drab
"""
@spec app_name(atom) :: atom | no_return
def app_name(endpoint) do
case :drab |> Application.get_env(endpoint, []) |> Keyword.fetch(:otp_app) do
{:ok, app} -> app
:error -> raise_app_not_found()
end
end
@doc false
@spec get_all_env(atom) :: Keyword.t() | no_return
defp get_all_env(endpoint) do
Application.get_env(:drab, endpoint) || raise_app_not_found()
end
@spec get_env(atom, atom, any) :: any
defp get_env(endpoint, key, default) do
Keyword.get(get_all_env(endpoint), key, default)
end
@doc """
Returns the name of all configured Drab applications.
iex> Drab.Config.app_names()
[:drab]
"""
@spec app_names() :: [atom]
def app_names() do
Enum.map(app_endpoints(), &app_name/1)
end
@doc """
Returns the name of all configured Drab endpoints.
iex> Drab.Config.app_endpoints()
[DrabTestApp.Endpoint]
"""
@spec app_endpoints() :: [atom]
def app_endpoints() do
:drab
|> Application.get_all_env()
|> Enum.filter(fn {x, _} -> is_module?(x) end)
|> Keyword.keys()
end
@spec is_module?(any) :: boolean
defp is_module?(atom) when is_atom(atom), do: is_module?(Atom.to_string(atom))
defp is_module?("Elixir." <> _), do: true
defp is_module?(_), do: false
@spec raise_app_not_found :: no_return
defp raise_app_not_found() do
raise """
Drab can't find the web application or endpoint name.
Please add your app name and the endpoint to the config.exs:
config :drab, main_phoenix_app: :my_app_web, endpoint: MyAppWeb.Endpoint
"""
end
@doc """
Returns the PubSub module of the given endpoint.
iex> Drab.Config.pubsub(DrabTestApp.Endpoint)
DrabTestApp.PubSub
"""
@spec pubsub(atom) :: atom | no_return
def pubsub(endpoint) do
with app <- app_name(endpoint),
config <- Application.get_env(app, endpoint),
{:ok, pubsub_conf} <- Keyword.fetch(config, :pubsub),
{:ok, name} <- Keyword.fetch(pubsub_conf, :name) do
name
else
_ -> raise_app_not_found()
end
end
@doc false
@spec default_pubsub() :: atom | no_return
def default_pubsub() do
case app_endpoints() do
[endpoint] ->
with app <- app_name(endpoint),
config <- Application.get_env(app, endpoint),
{:ok, pubsub_conf} <- Keyword.fetch(config, :pubsub),
{:ok, name} <- Keyword.fetch(pubsub_conf, :name) do
name
else
_ -> raise_app_not_found()
end
_ ->
raise """
Can't find the default PubSub module. Please ensure that it is set in config.exs.
In multiple endpoint environments, broadcasting with a topic requires endpoint to
be specified:
broadcast_js same_topic(MyAppWeb.Endpoint, "product_10"), "console.log(2+2);"
"""
end
end
@doc false
@spec default_endpoint() :: atom | no_return
def default_endpoint() do
case app_endpoints() do
[endpoint] ->
endpoint
_ ->
raise """
Can't find the default Endpoint module. Please ensure that it is set in config.exs.
In multiple endpoint environments, you must specify which enpoint to use with presence:
config :drab, :presence, endpoint: MyAppWeb.Endpoint
"""
end
end
@doc false
@spec secret_key_base() :: String.t() | no_return
def secret_key_base() do
get(:secret_key_base) ||
case app_endpoints() do
[endpoint] ->
with app <- app_name(endpoint),
config <- Application.get_env(app, endpoint),
{:ok, secret_key_base} <- Keyword.fetch(config, :secret_key_base) do
secret_key_base
else
_ -> raise_app_not_found()
end
_ ->
raise """
Can't find the default secret key base. Please ensure that it is set in config.exs.
In multiple endpoint environments, you must specify it globally for Drab:
config :drab, secret_key_base: "remember to put it in prod_secret.exs"
"""
end
end
@doc false
@spec secret_key_base(atom) :: String.t() | no_return
def secret_key_base(endpoint) do
with app <- app_name(endpoint),
config <- Application.get_env(app, endpoint),
{:ok, secret_key_base} <- Keyword.fetch(config, :secret_key_base) do
secret_key_base
else
_ -> raise_app_not_found()
end
end
@doc """
Returns configured Drab.Live.Engine Extension. String with dot at the begin.
Example, for config:
config :phoenix, :template_engines,
drab: Drab.Live.Engine
it will return ".drab"
iex> Drab.Config.drab_extension()
".drab"
"""
@spec drab_extension :: String.t()
def drab_extension() do
{drab_ext, Drab.Live.Engine} =
Phoenix.Template.engines()
|> Enum.find(fn {_, v} -> v == Drab.Live.Engine end)
"." <> to_string(drab_ext)
end
@doc false
@spec default_controller_for(atom | nil) :: atom | nil
def default_controller_for(commander) do
replace_last(commander, "Commander", "Controller")
end
@doc false
@spec default_view_for(atom | nil) :: atom | nil
def default_view_for(commander) do
replace_last(default_controller_for(commander), "Controller", "View")
end
@doc false
@spec default_commander_for(atom | nil) :: atom | nil
def default_commander_for(controller) do
replace_last(controller, "Controller", "Commander")
end
@spec replace_last(atom, String.t(), String.t()) :: atom
defp replace_last(atom, from, to) do
path = Module.split(atom)
new_last = path |> List.last() |> String.replace(from, to)
new_path = List.replace_at(path, -1, new_last)
Module.concat(new_path)
end
@doc false
@spec drab_internal_commanders() :: list
def drab_internal_commanders() do
[Drab.Logger]
end
@doc """
Returns Drab configuration for the given atom.
iex> Drab.Config.get(:default_encoder)
Drab.Coder.Cipher
"""
@spec get(atom) :: term
def get(key)
def get(:enable_live_scripts), do: Application.get_env(:drab, :enable_live_scripts, false)
def get(:phoenix_channel_options), do: Application.get_env(:drab, :phoenix_channel_options, [])
def get(:default_encoder), do: Application.get_env(:drab, :default_encoder, Drab.Coder.Cipher)
def get(:secret_key_base), do: Application.get_env(:drab, :secret_key_base, nil)
def get(:presence), do: Application.get_env(:drab, :presence, false)
def get(:default_modules),
do: Application.get_env(:drab, :default_modules, [Drab.Live, Drab.Element, Drab.Modal])
def get(:modal_css), do: Application.get_env(:drab, :modal_css, :bootstrap3)
@doc """
Returns Drab configuration for the given endpoint and atom.
iex> Drab.Config.get(DrabTestApp.Endpoint, :templates_path)
"priv/custom_templates"
"""
@spec get(atom, atom) :: term
def get(endpoint, key)
def get(:presence, :id) do
case get(:presence) do
options when is_list(options) -> Keyword.get(options, :id, session: :user_id)
_ -> nil
end
end
def get(:presence, :endpoint) do
case get(:presence) do
options when is_list(options) -> Keyword.get(options, :endpoint, nil)
_ -> nil
end
end
def get(:presence, :module) do
case get(:presence) do
options when is_list(options) -> Keyword.get(options, :module, Drab.Presence)
_ -> Drab.Presence
end
end
def get(endpoint, :disable_controls_while_processing),
do: get_env(endpoint, :disable_controls_while_processing, true)
def get(endpoint, :events_to_disable_while_processing),
do: get_env(endpoint, :events_to_disable_while_processing, ["click"])
def get(endpoint, :events_shorthands),
do: get_env(endpoint, :events_shorthands, ["click", "change", "keyup", "keydown"])
def get(endpoint, :disable_controls_when_disconnected),
do: get_env(endpoint, :disable_controls_when_disconnected, true)
def get(endpoint, :drab_store_storage),
do: get_env(endpoint, :drab_store_storage, :session_storage)
def get(endpoint, :templates_path),
do: get_env(endpoint, :templates_path, "priv/templates/drab")
def get(endpoint, :token_max_age), do: get_env(endpoint, :token_max_age, 86_400)
def get(endpoint, :socket), do: get_env(endpoint, :socket, "/socket")
def get(endpoint, :browser_response_timeout),
do: get_env(endpoint, :browser_response_timeout, 5000)
def get(endpoint, :js_socket_constructor),
do: get_env(endpoint, :js_socket_constructor, "require(\"phoenix\").Socket")
def get(endpoint, :access_session) do
if get(:presence) do
[presence_session_id() | get_env(endpoint, :access_session, [])]
else
Application.get_env(endpoint, :access_session, [])
end
end
def get(endpoint, :live_conn_pass_through) do
get_env(endpoint, :live_conn_pass_through, %{
private: %{
phoenix_endpoint: true,
phoenix_controller: true,
phoenix_action: true
}
})
end
defp presence_session_id() do
Keyword.get(get(:presence, :id), :session, nil)
end
end
| 32.242424 | 99 | 0.671992 |
f735d460226909d71497f8a8d38de7d76eaae7c1 | 1,807 | exs | Elixir | mix.exs | ericdude4/phoenix_oauth2_provider | 4985a18f4a486e397fda1203fa64a9b05b74d7ff | [
"MIT"
] | null | null | null | mix.exs | ericdude4/phoenix_oauth2_provider | 4985a18f4a486e397fda1203fa64a9b05b74d7ff | [
"MIT"
] | null | null | null | mix.exs | ericdude4/phoenix_oauth2_provider | 4985a18f4a486e397fda1203fa64a9b05b74d7ff | [
"MIT"
] | null | null | null | defmodule PhoenixOauth2Provider.Mixfile do
use Mix.Project
@version "0.5.1"
def project do
[
app: :phoenix_oauth2_provider,
version: @version,
elixir: "~> 1.8",
elixirc_paths: elixirc_paths(Mix.env),
start_permanent: Mix.env == :prod,
compilers: [:phoenix] ++ Mix.compilers,
deps: deps(),
# Hex
description: "The fastest way to set up OAuth 2.0 server in your Phoenix app",
package: package(),
# Docs
name: "PhoenixOauth2Provider",
docs: docs()
]
end
def application do
[extra_applications: extra_applications(Mix.env)]
end
defp extra_applications(:test), do: [:ecto, :logger]
defp extra_applications(_), do: [:logger]
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
defp deps do
[
{:ex_oauth2_provider, "~> 0.5.1"},
{:phoenix, "~> 1.4"},
{:phoenix_html, "~> 3.0"},
{:phoenix_ecto, "~> 4.4", only: [:test, :dev]},
{:credo, "~> 1.1.0", only: [:dev, :test]},
{:jason, "~> 1.0", only: [:dev, :test]},
{:ex_doc, ">= 0.0.0", only: :dev},
{:ecto_sql, "~> 3.6", only: :test},
{:plug_cowboy, "~> 2.0", only: :test},
{:postgrex, ">= 0.0.0", only: :test},
]
end
defp package do
[
maintainers: ["Dan Shultzer", "Benjamin Schultzer"],
licenses: ["MIT"],
links: %{github: "https://github.com/danschultzer/phoenix_oauth2_provider"},
files: ~w(lib LICENSE mix.exs README.md)
]
end
defp docs do
[
source_ref: "v#{@version}", main: "PhoenixOauth2Provider",
canonical: "http://hexdocs.pm/phoenix_oauth2_provider",
source_url: "https://github.com/danschultzer/phoenix_oauth2_provider",
extras: ["README.md"]
]
end
end
| 25.097222 | 84 | 0.579967 |
f735e17e83ce951888755c320b676d1b2de6760c | 183 | ex | Elixir | lib/warehouse_web/pow/routes.ex | riebeekn/phx-auth-with-pow | 2b555365d6961b9afbff99f25540ca41264eba82 | [
"MIT"
] | 14 | 2019-02-27T18:49:28.000Z | 2020-12-24T21:39:16.000Z | lib/warehouse_web/pow/routes.ex | ammy-bajwa/phx-auth-with-pow | 2b555365d6961b9afbff99f25540ca41264eba82 | [
"MIT"
] | null | null | null | lib/warehouse_web/pow/routes.ex | ammy-bajwa/phx-auth-with-pow | 2b555365d6961b9afbff99f25540ca41264eba82 | [
"MIT"
] | 5 | 2019-07-16T17:50:36.000Z | 2020-08-12T22:14:41.000Z | defmodule WarehouseWeb.Pow.Routes do
use Pow.Phoenix.Routes
alias WarehouseWeb.Router.Helpers, as: Routes
def after_sign_out_path(conn), do: Routes.page_path(conn, :index)
end
| 26.142857 | 67 | 0.786885 |
f735e96dc8ac3a0f5d805d39f13911a9798583c5 | 1,901 | ex | Elixir | clients/monitoring/lib/google_api/monitoring/v3/model/list_metric_descriptors_response.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/monitoring/lib/google_api/monitoring/v3/model/list_metric_descriptors_response.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/monitoring/lib/google_api/monitoring/v3/model/list_metric_descriptors_response.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Monitoring.V3.Model.ListMetricDescriptorsResponse do
@moduledoc """
The ListMetricDescriptors response.
## Attributes
- metricDescriptors (List[MetricDescriptor]): The metric descriptors that are available to the project and that match the value of filter, if present. Defaults to: `null`.
- nextPageToken (String): If there are more results than have been returned, then this field is set to a non-empty value. To see the additional results, use that value as pageToken in the next call to this method. Defaults to: `null`.
"""
defstruct [
:"metricDescriptors",
:"nextPageToken"
]
end
defimpl Poison.Decoder, for: GoogleApi.Monitoring.V3.Model.ListMetricDescriptorsResponse do
import GoogleApi.Monitoring.V3.Deserializer
def decode(value, options) do
value
|> deserialize(:"metricDescriptors", :list, GoogleApi.Monitoring.V3.Model.MetricDescriptor, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Monitoring.V3.Model.ListMetricDescriptorsResponse do
def encode(value, options) do
GoogleApi.Monitoring.V3.Deserializer.serialize_non_nil(value, options)
end
end
| 38.02 | 236 | 0.768543 |
f735f81922aa58b15bcc23407e4c65dea6fd7919 | 1,550 | exs | Elixir | test/miotwo/train_cache_test.exs | jakswa/miotwo | b8455c0e019c952891f108dc5cd5ad134c57cbfc | [
"MIT"
] | 2 | 2018-08-24T18:09:34.000Z | 2020-07-20T01:42:37.000Z | test/miotwo/train_cache_test.exs | jakswa/miotwo | b8455c0e019c952891f108dc5cd5ad134c57cbfc | [
"MIT"
] | null | null | null | test/miotwo/train_cache_test.exs | jakswa/miotwo | b8455c0e019c952891f108dc5cd5ad134c57cbfc | [
"MIT"
] | 1 | 2018-05-16T22:57:57.000Z | 2018-05-16T22:57:57.000Z | defmodule Miotwo.TrainCacheTest do
use ExUnit.Case, async: true
use ExVCR.Mock, adapter: ExVCR.Adapter.Hackney
setup_all do
HTTPoison.start
end
describe "handle_call" do
test "gives cache when not expired (no HTTP)" do
expires = Timex.shift(Timex.now, minutes: 10)
assert {:reply, :cached_value, result} =
Miotwo.TrainCache.handle_call(:train_json, nil, {expires, :cached_value})
assert expires == elem(result, 0)
end
test "hits API when expired" do
use_cassette "marta_api" do
expires = Timex.shift(Timex.now, minutes: -10)
assert {:reply, resp, result} =
Miotwo.TrainCache.handle_call(:train_json, nil, {expires, :cached_value})
assert expires != elem(result, 0)
assert resp != :cached_value
assert elem(resp, 0) == :ok
end
end
test "subsequent hits return same result" do
use_cassette "marta_api" do
expires = Timex.shift(Timex.now, minutes: -10)
resp = Miotwo.TrainCache.handle_call(:train_json, nil, {expires, :cached_value})
assert resp == Miotwo.TrainCache.handle_call(:train_json, nil, elem(resp, 2))
end
end
end
describe "train_json" do
test "hits API" do
use_cassette "marta_api" do
assert {:ok, _resp} = Miotwo.TrainCache.train_json
end
end
test "quickly repeated calls are equal" do
use_cassette "marta_api" do
assert Miotwo.TrainCache.train_json ==
Miotwo.TrainCache.train_json
end
end
end
end
| 28.181818 | 88 | 0.649677 |
f73631003eb165e30065619f8e5ec21758b26cda | 1,037 | exs | Elixir | mix.exs | herenowcoder/reprise | e969b1a1cf775316c0bcd90a5ccc356967e1a7c6 | [
"BSD-2-Clause"
] | 24 | 2015-02-17T05:02:52.000Z | 2016-07-27T09:24:55.000Z | mix.exs | herenowcoder/reprise | e969b1a1cf775316c0bcd90a5ccc356967e1a7c6 | [
"BSD-2-Clause"
] | 11 | 2015-01-11T10:41:29.000Z | 2016-02-17T08:07:14.000Z | mix.exs | herenowcoder/reprise | e969b1a1cf775316c0bcd90a5ccc356967e1a7c6 | [
"BSD-2-Clause"
] | 8 | 2015-01-27T03:03:40.000Z | 2016-11-09T00:52:15.000Z | defmodule Reprise.Mixfile do
use Mix.Project
def project do
[app: :reprise,
version: "0.5.2-dev",
elixir: "~> 1.1",
description: description(),
package: package(),
deps: deps()]
end
def application do
[mod: {Reprise, []},
registered: [Reprise],
applications: [:logger],
description: 'Simple module reloader',
]
end
defp deps do
[
{:dialyze, "~> 0.2", only: :dev},
{:ex_doc, "~> 0.19", only: :dev},
]
end
defp description do
"""
Reprise reloads your modules after they've been recompiled.
It is thought as a companion to inotify tools.
It scans for changes in beam files belonging to youyr project.
Doesn't recompile stuff by itself.
"""
end
defp package do
[ maintainers: ["Wojciech Kaczmarek",
"Yurii Rashkovskii", "Jay Doane", "Josh Austin"],
licenses: ["BSD"],
description: description(),
links: %{"GitHub" => "https://github.com/herenowcoder/reprise"}
]
end
end
| 22.06383 | 69 | 0.590164 |
f73640123948734633d58b4695477e2f022010c2 | 2,322 | ex | Elixir | apps/gallery/lib/gallery/gallery.ex | danmarcab/deep_painting | 860c7d02bd6b112fffa199f715e61d895cba6623 | [
"Apache-2.0"
] | null | null | null | apps/gallery/lib/gallery/gallery.ex | danmarcab/deep_painting | 860c7d02bd6b112fffa199f715e61d895cba6623 | [
"Apache-2.0"
] | 11 | 2020-01-28T22:19:10.000Z | 2022-03-11T23:18:18.000Z | apps/gallery/lib/gallery/gallery.ex | danmarcab/deep_painting | 860c7d02bd6b112fffa199f715e61d895cba6623 | [
"Apache-2.0"
] | null | null | null | defmodule Gallery do
@moduledoc """
Gallery provides funcions to create, set the settings and start the process to create a painting.
"""
alias Gallery.Web.Endpoint
@doc """
Finds an existing painting with a given name.
## Examples
iex> Gallery.create_painting("My painting")
:ok
iex> {:ok, %Painting{} = painting} = Gallery.find_painting("My painting")
iex> painting.name
"My painting"
iex> Gallery.find_painting("Not my painting")
:error
"""
def find_painting(name) do
storage().find(storage_name(), name)
end
@doc """
Returns a map with all exisiting paintings (name of the painting as key, Painting as value)
## Examples
iex> Gallery.create_painting("My painting")
:ok
iex> Gallery.create_painting("My painting 2")
:ok
iex> paintings_map = Gallery.all_paintings()
iex> Map.keys(paintings_map)
["My painting", "My painting 2"]
"""
def all_paintings do
storage().all(storage_name())
end
@doc """
Saves a painting with a given name.
## Examples
iex> p = %Painting{name: "My painting", content: "my_content"}
iex> :ok = Gallery.save_painting(p)
iex> {:ok, %Painting{} = painting} = Gallery.find_painting("My painting")
iex> {painting.name, painting.content}
{"My painting", "my_content"}
"""
def save_painting(painting) do
:ok = storage().save(storage_name(), painting)
painting_to_push = prepare_painting_for_ui(painting)
IO.puts "broadcasting..."
:ok = Endpoint.broadcast("painting:" <> painting_to_push.name, "update", painting_to_push)
:ok = Endpoint.broadcast("gallery", "update", painting_to_push)
:ok
end
def clear_storage do
storage().clear(storage_name())
end
# TODO: move somewhere
def prepare_painting_for_ui(painting) do
Painting.prepend_path(painting, external_url() <> "/paintings/" <> painting.name <> "/")
end
defp storage do
Application.get_env(:gallery, :painting_storage)[:type]
end
defp storage_name do
Application.get_env(:gallery, :painting_storage)[:name]
end
def external_url do
if System.get_env("GALLERY_DONT_EXPOSE_PORT") do
url = Endpoint.struct_url()
URI.to_string %{url | port: nil}
else
Endpoint.url()
end
end
end
| 25.516484 | 99 | 0.661068 |
f736432537a73e6720781281be55ea327d7908ec | 7,465 | ex | Elixir | test/support/fixtures.ex | ElixirTradingTools/trade-indicators | 05bc3c28c30eaa73c59858dbf1ee62525ccbbf48 | [
"MIT"
] | 12 | 2021-04-06T17:57:55.000Z | 2021-12-19T03:04:39.000Z | test/support/fixtures.ex | ElixirTradingTools/trade-indicators | 05bc3c28c30eaa73c59858dbf1ee62525ccbbf48 | [
"MIT"
] | null | null | null | test/support/fixtures.ex | ElixirTradingTools/trade-indicators | 05bc3c28c30eaa73c59858dbf1ee62525ccbbf48 | [
"MIT"
] | 2 | 2021-04-07T19:46:12.000Z | 2021-07-10T07:43:12.000Z | defmodule TradeIndicators.Tests.Fixtures do
alias TradeIndicators.Util, as: U
alias Enum, as: E
alias Map, as: M
@msft_m1_2020_07_27 [
%{t: 1_595_620_860, o: 201.63, c: 201.63, h: 201.63, l: 201.63},
%{t: 1_595_852_820, o: 202.98, c: 202.98, h: 202.98, l: 202.98},
%{t: 1_595_853_360, o: 202.90, c: 202.90, h: 202.90, l: 202.90},
%{t: 1_595_854_020, o: 202.76, c: 202.76, h: 202.76, l: 202.76},
%{t: 1_595_854_200, o: 202.55, c: 202.55, h: 202.55, l: 202.55},
%{t: 1_595_855_580, o: 202.40, c: 202.40, h: 202.40, l: 202.40},
%{t: 1_595_856_300, o: 202.31, c: 202.31, h: 202.31, l: 202.31},
%{t: 1_595_856_480, o: 202.01, c: 201.93, h: 202.01, l: 201.62},
%{t: 1_595_856_540, o: 201.53, c: 201.59, h: 201.60, l: 201.53},
%{t: 1_595_856_600, o: 201.41, c: 202.46, h: 202.66, l: 201.41},
%{t: 1_595_856_660, o: 202.52, c: 201.94, h: 202.56, l: 201.88},
%{t: 1_595_856_720, o: 201.93, c: 201.54, h: 201.96, l: 201.54},
%{t: 1_595_856_780, o: 201.55, c: 201.90, h: 201.98, l: 201.42},
%{t: 1_595_856_840, o: 201.96, c: 202.22, h: 202.46, l: 201.95},
%{t: 1_595_856_900, o: 202.27, c: 202.62, h: 202.70, l: 202.27},
%{t: 1_595_856_960, o: 202.55, c: 202.22, h: 202.55, l: 201.94},
%{t: 1_595_857_020, o: 202.30, c: 202.55, h: 202.65, l: 202.29},
%{t: 1_595_857_080, o: 202.59, c: 202.68, h: 202.75, l: 202.50},
%{t: 1_595_857_140, o: 202.66, c: 202.44, h: 202.74, l: 202.11},
%{t: 1_595_857_200, o: 202.42, c: 202.56, h: 202.61, l: 202.20},
%{t: 1_595_857_260, o: 202.60, c: 202.56, h: 202.65, l: 202.42},
%{t: 1_595_857_320, o: 202.59, c: 202.60, h: 202.65, l: 202.54},
%{t: 1_595_857_380, o: 202.61, c: 202.47, h: 202.71, l: 202.44},
%{t: 1_595_857_440, o: 202.42, c: 202.55, h: 202.55, l: 202.13},
%{t: 1_595_857_500, o: 202.56, c: 202.54, h: 202.63, l: 202.48},
%{t: 1_595_857_560, o: 202.55, c: 202.44, h: 202.60, l: 202.31},
%{t: 1_595_857_620, o: 202.48, c: 202.43, h: 202.58, l: 202.42},
%{t: 1_595_857_680, o: 202.48, c: 202.47, h: 202.58, l: 202.37},
%{t: 1_595_857_740, o: 202.41, c: 202.76, h: 202.76, l: 202.39},
%{t: 1_595_857_800, o: 202.74, c: 202.69, h: 202.92, l: 202.69},
%{t: 1_595_857_860, o: 202.62, c: 202.74, h: 202.79, l: 202.62},
%{t: 1_595_857_920, o: 202.76, c: 202.88, h: 202.89, l: 202.70},
%{t: 1_595_857_980, o: 202.90, c: 203.02, h: 203.04, l: 202.84},
%{t: 1_595_858_040, o: 203.05, c: 203.18, h: 203.23, l: 202.95},
%{t: 1_595_858_100, o: 203.13, c: 203.10, h: 203.16, l: 203.03},
%{t: 1_595_858_160, o: 203.17, c: 203.22, h: 203.30, l: 203.16},
%{t: 1_595_858_220, o: 203.19, c: 203.21, h: 203.24, l: 203.09},
%{t: 1_595_858_280, o: 203.21, c: 202.96, h: 203.21, l: 202.90},
%{t: 1_595_858_340, o: 202.94, c: 202.82, h: 203.00, l: 202.82},
%{t: 1_595_858_400, o: 202.81, c: 202.80, h: 203.01, l: 202.80}
]
|> E.map(&(&1 |> M.drop([:t]) |> U.decimals() |> M.put(:t, &1[:t])))
@msft_m1_2020_08_17 [
%{t: 1_597_426_564, o: 208.69, c: 208.69, h: 208.69, l: 208.69},
%{t: 1_597_653_724, o: 209.36, c: 209.36, h: 209.36, l: 209.36},
%{t: 1_597_654_924, o: 209.55, c: 209.55, h: 209.55, l: 209.55},
%{t: 1_597_655_044, o: 209.55, c: 209.50, h: 209.55, l: 209.50},
%{t: 1_597_655_224, o: 209.50, c: 209.50, h: 209.50, l: 209.50},
%{t: 1_597_656_184, o: 209.50, c: 209.50, h: 209.50, l: 209.50},
%{t: 1_597_656_364, o: 209.50, c: 209.50, h: 209.50, l: 209.50},
%{t: 1_597_656_604, o: 209.60, c: 209.52, h: 209.68, l: 209.50},
%{t: 1_597_656_664, o: 209.60, c: 209.84, h: 210.16, l: 209.60},
%{t: 1_597_656_724, o: 209.80, c: 210.09, h: 210.12, l: 209.79},
%{t: 1_597_656_784, o: 210.09, c: 209.69, h: 210.11, l: 209.62},
%{t: 1_597_656_844, o: 209.78, c: 209.62, h: 210.00, l: 209.62},
%{t: 1_597_656_904, o: 209.75, c: 209.85, h: 209.89, l: 209.69},
%{t: 1_597_656_964, o: 209.86, c: 209.71, h: 209.91, l: 209.48},
%{t: 1_597_657_024, o: 209.72, c: 209.35, h: 209.72, l: 209.25},
%{t: 1_597_657_084, o: 209.51, c: 209.55, h: 209.72, l: 209.47},
%{t: 1_597_657_144, o: 209.56, c: 208.96, h: 209.70, l: 208.96},
%{t: 1_597_657_204, o: 209.03, c: 208.94, h: 209.25, l: 208.94},
%{t: 1_597_657_264, o: 208.97, c: 209.29, h: 209.32, l: 208.97},
%{t: 1_597_657_324, o: 209.31, c: 209.51, h: 209.56, l: 209.31},
%{t: 1_597_657_384, o: 209.49, c: 209.58, h: 209.71, l: 209.44},
%{t: 1_597_657_444, o: 209.59, c: 209.34, h: 209.63, l: 209.34},
%{t: 1_597_657_504, o: 209.30, c: 209.37, h: 209.49, l: 209.30},
%{t: 1_597_657_564, o: 209.54, c: 209.22, h: 209.54, l: 209.19},
%{t: 1_597_657_624, o: 209.35, c: 209.33, h: 209.40, l: 209.26},
%{t: 1_597_657_684, o: 209.33, c: 209.17, h: 209.34, l: 209.15},
%{t: 1_597_657_744, o: 209.17, c: 209.23, h: 209.37, l: 209.16},
%{t: 1_597_657_804, o: 209.34, c: 209.38, h: 209.50, l: 209.34},
%{t: 1_597_657_864, o: 209.44, c: 209.58, h: 209.63, l: 209.44},
%{t: 1_597_657_924, o: 209.64, c: 209.77, h: 209.82, l: 209.64},
%{t: 1_597_657_984, o: 209.78, c: 209.76, h: 209.79, l: 209.73},
%{t: 1_597_658_044, o: 209.77, c: 209.75, h: 209.80, l: 209.70},
%{t: 1_597_658_104, o: 209.76, c: 209.74, h: 209.78, l: 209.73},
%{t: 1_597_658_164, o: 209.72, c: 209.98, h: 209.98, l: 209.72},
%{t: 1_597_658_224, o: 209.98, c: 210.29, h: 210.29, l: 209.98},
%{t: 1_597_658_284, o: 210.33, c: 210.29, h: 210.33, l: 210.16},
%{t: 1_597_658_344, o: 210.28, c: 210.25, h: 210.37, l: 210.20},
%{t: 1_597_658_404, o: 210.36, c: 210.41, h: 210.50, l: 210.34}
]
|> E.map(&(&1 |> M.drop([:t]) |> U.decimals() |> M.put(:t, &1[:t])))
def get(:msft_m1_2020_07_27),
do: @msft_m1_2020_07_27
def get(:msft_m1_2020_08_17),
do: @msft_m1_2020_08_17
end
| 76.173469 | 90 | 0.433222 |
f7365b68b38746e4cb3964bd7a1eb66b55a0f214 | 1,640 | ex | Elixir | lib/astarte_data_updater_plant/application.ex | rbino/astarte_data_updater_plant | b1769207636fad9f91fdcad4ed768757af09683f | [
"Apache-2.0"
] | 5 | 2018-01-30T15:08:23.000Z | 2019-12-20T15:06:56.000Z | lib/astarte_data_updater_plant/application.ex | rbino/astarte_data_updater_plant | b1769207636fad9f91fdcad4ed768757af09683f | [
"Apache-2.0"
] | 17 | 2018-01-31T15:50:22.000Z | 2019-12-05T17:26:06.000Z | lib/astarte_data_updater_plant/application.ex | rbino/astarte_data_updater_plant | b1769207636fad9f91fdcad4ed768757af09683f | [
"Apache-2.0"
] | 2 | 2018-01-31T15:43:04.000Z | 2019-11-15T12:00:05.000Z | #
# This file is part of Astarte.
#
# Copyright 2017 Ispirata Srl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
defmodule Astarte.DataUpdaterPlant.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
require Logger
alias Astarte.DataUpdaterPlant.ConsumersSupervisor
alias Astarte.DataUpdaterPlant.AMQPEventsProducer
alias Astarte.DataUpdaterPlant.RPC.Handler
alias Astarte.RPC.Protocol.DataUpdaterPlant, as: Protocol
def start(_type, _args) do
Logger.info("Starting application.", tag: "data_updater_plant_app_start")
# List all child processes to be supervised
children = [
{Registry, [keys: :unique, name: Registry.MessageTracker]},
{Registry, [keys: :unique, name: Registry.DataUpdater]},
ConsumersSupervisor,
AMQPEventsProducer,
{Astarte.RPC.AMQP.Server, [amqp_queue: Protocol.amqp_queue(), handler: Handler]},
Astarte.RPC.AMQP.Client
]
opts = [strategy: :rest_for_one, name: Astarte.DataUpdaterPlant.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 32.8 | 87 | 0.74878 |
f73681db00aba453e89ed4acb6c1ba2156c6278d | 1,358 | ex | Elixir | lib/erlef_web/controllers/page_controller.ex | pedrosnk/erlef-website | bb8da73d09930056c9d31bcc75a92b8fb3caf6da | [
"Apache-2.0"
] | null | null | null | lib/erlef_web/controllers/page_controller.ex | pedrosnk/erlef-website | bb8da73d09930056c9d31bcc75a92b8fb3caf6da | [
"Apache-2.0"
] | null | null | null | lib/erlef_web/controllers/page_controller.ex | pedrosnk/erlef-website | bb8da73d09930056c9d31bcc75a92b8fb3caf6da | [
"Apache-2.0"
] | null | null | null | defmodule ErlefWeb.PageController do
use ErlefWeb, :controller
alias Erlef.{
Blog,
Posts,
WorkingGroup,
Twitter,
Data.Query.Event
}
action_fallback ErlefWeb.FallbackController
def index(conn, _params) do
latest_news =
Blog
|> Posts.all()
|> Posts.sort_by_datetime()
|> Enum.take(3)
render(conn,
working_groups: Posts.all(WorkingGroup),
latest_news: latest_news,
tweets: Twitter.latest_tweets(),
events: Event.approved() |> Enum.take(3)
)
end
def board_members(conn, _params) do
members = Enum.shuffle(Erlef.Rosters.get("board"))
render(conn, members: members)
end
def bylaws(conn, _params), do: render(conn)
def sponsor_info(conn, _params), do: render(conn, "become_a_sponsor.html")
def contact(conn, _params), do: render(conn)
def faq(conn, _params), do: render(conn)
def sponsors(conn, _params) do
%{true: founding_sponsors, false: sponsors} =
Erlef.Rosters.get("sponsors") |> Enum.group_by(fn {_k, x} -> x.founding_sponsor == true end)
render(conn, founding_sponsors: founding_sponsors, sponsors: sponsors)
end
def wg_proposal_template(conn, _params), do: render(conn, "wg-proposal-template.html")
def academic_papers(conn, _params) do
render(conn, academic_papers: Erlef.AcademicPapers.all())
end
end
| 24.690909 | 98 | 0.682622 |
f736820a08b001ddbb05cca199635898f904ca74 | 111 | ex | Elixir | lib/survey_api/repo.ex | AkioCode/elixir-survey | 420f4e5f60b84d381707f162b473dd91eb0fe9f2 | [
"MIT"
] | null | null | null | lib/survey_api/repo.ex | AkioCode/elixir-survey | 420f4e5f60b84d381707f162b473dd91eb0fe9f2 | [
"MIT"
] | null | null | null | lib/survey_api/repo.ex | AkioCode/elixir-survey | 420f4e5f60b84d381707f162b473dd91eb0fe9f2 | [
"MIT"
] | null | null | null | defmodule SurveyApi.Repo do
use Ecto.Repo,
otp_app: :survey_api,
adapter: Ecto.Adapters.Postgres
end
| 18.5 | 35 | 0.738739 |
f736adea4ea740ababc2c536ef5d3bf1fbb5bb04 | 1,115 | exs | Elixir | config/config.exs | davemenninger/ohio_elixir | 9472b71fa906e30a2a5fdc013256a5e80caedc2f | [
"MIT"
] | 7 | 2021-01-22T00:20:04.000Z | 2022-03-30T22:07:32.000Z | config/config.exs | davemenninger/ohio_elixir | 9472b71fa906e30a2a5fdc013256a5e80caedc2f | [
"MIT"
] | 11 | 2021-10-05T03:59:28.000Z | 2022-03-20T21:54:44.000Z | config/config.exs | davemenninger/ohio_elixir | 9472b71fa906e30a2a5fdc013256a5e80caedc2f | [
"MIT"
] | 3 | 2021-06-10T02:48:54.000Z | 2021-10-09T03:43:06.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.
# General application configuration
use Mix.Config
config :ohio_elixir,
ecto_repos: [OhioElixir.Repo]
# Configures the endpoint
config :ohio_elixir, OhioElixirWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "FMJbycK0Cue3kJwPSLjg8HSVRhD+FVopcBoDhponmJvzGcn+LibtBEP0dxb8ZEls",
render_errors: [view: OhioElixirWeb.ErrorView, accepts: ~w(html json), layout: false],
pubsub_server: OhioElixir.PubSub,
live_view: [signing_salt: "DzZCI9uL"]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
config :elixir, :time_zone_database, Tzdata.TimeZoneDatabase
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env()}.exs"
| 32.794118 | 88 | 0.777578 |
f736b379fb126cb23551b082b8b5fa75407fe5d4 | 9,432 | ex | Elixir | farmbot_core/lib/farmbot_core/farmware_runtime.ex | SeppPenner/farmbot_os | 39ba5c5880f8aef71792e2c009514bed1177089c | [
"MIT"
] | 1 | 2019-08-06T11:51:48.000Z | 2019-08-06T11:51:48.000Z | farmbot_core/lib/farmbot_core/farmware_runtime.ex | SeppPenner/farmbot_os | 39ba5c5880f8aef71792e2c009514bed1177089c | [
"MIT"
] | null | null | null | farmbot_core/lib/farmbot_core/farmware_runtime.ex | SeppPenner/farmbot_os | 39ba5c5880f8aef71792e2c009514bed1177089c | [
"MIT"
] | null | null | null | defmodule FarmbotCore.FarmwareRuntime do
@moduledoc """
Handles execution of Farmware plugins.
"""
alias FarmbotCeleryScript.AST
alias FarmbotCore.FarmwareRuntime.PipeWorker
alias FarmbotCore.AssetWorker.FarmbotCore.Asset.FarmwareInstallation
alias FarmbotCore.Asset.FarmwareInstallation.Manifest
alias FarmbotCore.BotState.FileSystem
alias FarmbotCore.Project
import FarmwareInstallation, only: [install_dir: 1]
alias FarmbotCore.{Asset, JSON}
import FarmbotCore.Config, only: [get_config_value: 3]
require Logger
@error_timeout_ms 5000
@runtime_dir Application.get_env(:farmbot_core, __MODULE__)[:runtime_dir]
@runtime_dir ||
Mix.raise("""
config :farmbot_core, FarmwareRuntime,
runtime_dir: "/tmp/farmware_runtime"
""")
@muontrap_opts Application.get_env(:farmbot_core, __MODULE__)[:muontrap_opts]
@muontrap_opts @muontrap_opts || []
@packet_header_token 0xFBFB
@packet_header_byte_size 10
alias __MODULE__, as: State
defstruct [
:cmd,
:mon,
:context,
:rpc,
:request_pipe,
:request_pipe_handle,
:response_pipe,
:response_pipe_handle
]
@opaque pipe_handle :: pid()
@type t :: %State{
request_pipe: Path.t(),
request_pipe_handle: pipe_handle,
response_pipe: Path.t(),
response_pipe_handle: pipe_handle,
cmd: pid(),
mon: pid() | nil,
rpc: map(),
context: :get_header | :get_payload | :process_payload | :send_response
}
@doc """
Calls the Farmware Runtime asking for any RPCs that need to be
processed. If an RPC was ready, the Farmware will not process
any more RPCs until the current one is done.
"""
def process_rpc(pid) do
GenServer.call(pid, :process_rpc)
end
@doc """
Calls the Farmware Runtime telling it that an RPC has been processed.
"""
def rpc_processed(pid, response) do
GenServer.call(pid, {:rpc_processed, response})
end
@doc "Start a Farmware"
def start_link(%Manifest{} = manifest, env \\ %{}) do
package = manifest.package
GenServer.start_link(__MODULE__, [manifest, env], name: String.to_atom(package))
end
def init([manifest, env]) do
package = manifest.package
request_pipe =
Path.join([
@runtime_dir,
package <> "-" <> Ecto.UUID.generate() <> "-farmware-request-pipe"
])
response_pipe =
Path.join([
@runtime_dir,
package <> "-" <> Ecto.UUID.generate() <> "-farmware-response-pipe"
])
env = build_env(manifest, env, request_pipe, response_pipe)
# Create pipe dir if it doesn't exist
_ = File.mkdir_p(@runtime_dir)
# Open a pipe
{:ok, req} = PipeWorker.start_link(request_pipe)
{:ok, resp} = PipeWorker.start_link(response_pipe)
exec = System.find_executable(manifest.executable)
installation_path = install_dir(manifest)
opts =
Keyword.merge(@muontrap_opts,
env: env,
cd: installation_path,
into: IO.stream(:stdio, :line)
)
# Start the plugin.
{cmd, _} = spawn_monitor(MuonTrap, :cmd, ["sh", ["-c", "#{exec} #{manifest.args}"], opts])
state = %State{
cmd: cmd,
mon: nil,
context: :get_header,
rpc: nil,
request_pipe: request_pipe,
request_pipe_handle: req,
response_pipe: response_pipe,
response_pipe_handle: resp
}
send self(), :timeout
{:ok, state}
end
def terminate(_reason, state) do
if state.cmd && Process.alive?(state.cmd), do: Process.exit(state.cmd, :kill)
if state.request_pipe_handle do
PipeWorker.close(state.request_pipe_handle)
end
if state.response_pipe_handle do
PipeWorker.close(state.response_pipe_handle)
end
end
# If we are in the `process_request` state, send the RPC out to be buffered.
# This moves us to the `send_response` state. (which has _no_ timeout)
def handle_call(:process_rpc, {pid, _} = _from, %{context: :process_request, rpc: rpc} = state) do
# Link the calling process
# so the Farmware can exit if the rpc never gets processed.
_ = Process.link(pid)
{:reply, {:ok, rpc}, %{state | rpc: nil, context: :send_response}}
end
# If not in the `process_request` state, noop
def handle_call(:process_rpc, _from, state) do
{:reply, {:error, :no_rpc}, state}
end
def handle_call({:rpc_processed, result}, {pid, _} = _from, %{context: :send_response} = state) do
# Unlink the calling process
_ = Process.unlink(pid)
ipc = add_header(result)
reply = PipeWorker.write(state.response_pipe_handle, ipc)
# Make sure to `timeout` after this one to go back to the
# get_header context. This will cause another rpc to be processed.
send self(), :timeout
{:reply, reply, %{state | rpc: nil, context: :get_header}}
end
# get_request does two reads. One to get the header,
# and a second to get the entire binary payload.
def handle_info(:timeout, %{context: :get_header} = state) do
state = async_request_pipe_read(state, @packet_header_byte_size)
{:noreply, state}
end
# Timeout set by `handle_packet/2`. This will mean the CSVM
# didn't pick up the scheduled AST in a reasonable amount of time.
def handle_info(:timeout, %{context: :process_request} = state) do
Logger.error("Timeout waiting for #{inspect(state.rpc)} to be processed")
{:stop, {:error, :rpc_timeout}, state}
end
# farmware exit
def handle_info({:DOWN, _ref, :process, cmd, _reason}, %{cmd: cmd} = state) do
Logger.debug("Farmware exit")
{:stop, :normal, state}
end
# successful result of an io:read/2 in :get_header context
def handle_info(
{PipeWorker, _ref,
{:ok,
<<@packet_header_token::size(16), _reserved::size(32),
payload_size::integer-big-size(32)>>}},
%{context: :get_header} = state
) do
state = async_request_pipe_read(state, payload_size)
{:noreply, %{state | context: :get_payload}}
end
# error result of an io:read/2 in :get_header context
def handle_info({PipeWorker, _ref, {:ok, data}}, %{context: :get_header} = state) do
Logger.error("Bad header: #{inspect(data, base: :hex, limit: :infinity)}")
{:stop, {:unhandled_packet, data}, state}
end
# error result of an io:read/2 in :get_header context
def handle_info({PipeWorker, _ref, error}, %{context: :get_header} = state) do
Logger.error("Bad header: #{inspect(error)}")
{:stop, error, state}
end
# successful result of an io:read/2 in :get_payload context
def handle_info({PipeWorker, _ref, {:ok, packet}}, %{context: :get_payload} = state) do
handle_packet(packet, state)
end
# error result of an io:read/2 in :get_header context
def handle_info({PipeWorker, _ref, error}, %{context: :get_payload} = state) do
Logger.error("Bad payload: #{inspect(error)}")
{:stop, error, state}
end
# Pipe reads are done async because reading will block the entire
# process from receiving more messages as well as
# prevent the processes from terminating.
# this means if a Farmware never opens the pipe
# (a valid use case), When the Farmware completes
# the pipe will still be waiting for information
# and prevent the pipes from closing.
defp async_request_pipe_read(state, size) do
mon = PipeWorker.read(state.request_pipe_handle, size)
%{state | mon: mon}
end
# When a packet arives, buffer it until
# the controlling process (the CSVM) picks it up.
# there is a timeout for how long a packet will wait to be collected,
# but no time limit to how long it will take to
# process the packet.
def handle_packet(packet, state) do
with {:ok, data} <- JSON.decode(packet),
{:ok, rpc} <- decode_ast(data) do
{:noreply, %{state | rpc: rpc, context: :process_request}, @error_timeout_ms}
else
error -> {:stop, error, state}
end
end
defp decode_ast(data) do
try do
case AST.decode(data) do
%{kind: :rpc_request} = ast ->
{:ok, ast}
%{} = ast ->
Logger.error("Got bad ast: #{inspect(ast)}")
{:error, :bad_ast}
end
rescue
_ -> {:error, :bad_ast}
end
end
# RPC ENV is passed in to `start_link` and overwrites everything
# except the `base` data.
defp build_env(manifest, rpc_env, request_pipe, response_pipe) do
token = get_config_value(:string, "authorization", "token")
images_dir = "/tmp/images"
installation_path = install_dir(manifest)
state_root_dir = Application.get_env(:farmbot_core, FileSystem)[:root_dir]
base =
Map.new()
|> Map.put("FARMWARE_API_V2_REQUEST_PIPE", request_pipe)
|> Map.put("FARMWARE_API_V2_RESPONSE_PIPE", response_pipe)
|> Map.put("FARMBOT_API_TOKEN", token)
|> Map.put("FARMBOT_OS_IMAGES_DIR", images_dir)
|> Map.put("FARMBOT_OS_VERSION", Project.version())
|> Map.put("FARMBOT_OS_STATE_DIR", state_root_dir)
|> Map.put("PYTHONPATH", installation_path)
Asset.list_farmware_env()
|> Map.new(fn %{key: key, value: val} -> {key, val} end)
|> Map.merge(rpc_env)
|> Map.merge(base)
end
defp add_header(%AST{} = rpc) do
payload = rpc |> Map.from_struct() |> JSON.encode!()
header =
<<@packet_header_token::size(16)>> <>
:binary.copy(<<0x00>>, 4) <> <<byte_size(payload)::big-size(32)>>
header <> payload
end
end
| 31.651007 | 100 | 0.66232 |
f736bcdb08fc0e1548adb44a43a1fcbc4481084d | 1,977 | exs | Elixir | clients/billing_budgets/mix.exs | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/billing_budgets/mix.exs | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/billing_budgets/mix.exs | 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.BillingBudgets.Mixfile do
use Mix.Project
@version "0.12.1"
def project() do
[
app: :google_api_billing_budgets,
version: @version,
elixir: "~> 1.6",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps(),
source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/billing_budgets"
]
end
def application() do
[extra_applications: [:logger]]
end
defp deps() do
[
{:google_gax, "~> 0.4"},
{:ex_doc, "~> 0.16", only: :dev}
]
end
defp description() do
"""
Cloud Billing Budget API client library. The Cloud Billing Budget API stores Cloud Billing budgets, which define a budget plan and the rules to execute as spend is tracked against that plan.
"""
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "LICENSE"],
maintainers: ["Jeff Ching", "Daniel Azuma"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/billing_budgets",
"Homepage" => "https://cloud.google.com/billing/docs/how-to/budget-api-overview"
}
]
end
end
| 29.507463 | 194 | 0.668184 |
f736f2af5624bcf295e29211a08f2a4a71f148d9 | 9,056 | exs | Elixir | test/extensions/invitation/phoenix/controllers/invitation_controller_test.exs | thejones/pow | 217d3d915ce6832a5b138535a54fa2c39b2d9be5 | [
"MIT"
] | null | null | null | test/extensions/invitation/phoenix/controllers/invitation_controller_test.exs | thejones/pow | 217d3d915ce6832a5b138535a54fa2c39b2d9be5 | [
"MIT"
] | null | null | null | test/extensions/invitation/phoenix/controllers/invitation_controller_test.exs | thejones/pow | 217d3d915ce6832a5b138535a54fa2c39b2d9be5 | [
"MIT"
] | null | null | null | defmodule PowInvitation.Phoenix.InvitationControllerTest do
use PowInvitation.TestWeb.Phoenix.ConnCase
alias Plug.Conn
alias PowInvitation.Test.Users.{User, UsernameUser}
@user %User{id: 1, email: "[email protected]"}
@url_regex ~r/http:\/\/localhost\/invitations\/[a-z0-9\-]*\/edit/
describe "new/2" do
test "not signed in", %{conn: conn} do
conn = get(conn, Routes.pow_invitation_invitation_path(conn, :new))
assert_not_authenticated_redirect(conn)
end
test "shows", %{conn: conn} do
conn =
conn
|> Pow.Plug.assign_current_user(@user, [])
|> get(Routes.pow_invitation_invitation_path(conn, :new))
assert html = html_response(conn, 200)
assert html =~ "<label for=\"user_email\">Email</label>"
assert html =~ "<input id=\"user_email\" name=\"user[email]\" type=\"text\">"
end
test "shows with username user", %{conn: conn} do
conn =
conn
|> Conn.put_private(:pow_test_config, user: UsernameUser)
|> Pow.Plug.assign_current_user(@user, [])
|> get(Routes.pow_invitation_invitation_path(conn, :new))
assert html = html_response(conn, 200)
assert html =~ "<label for=\"user_username\">Username</label>"
assert html =~ "<input id=\"user_username\" name=\"user[username]\" type=\"text\">"
end
end
describe "create/2" do
@valid_params %{"user" => %{"email" => "[email protected]"}}
@invalid_params %{"user" => %{"email" => "invalid"}}
@valid_params_email_taken %{"user" => %{"email" => "[email protected]"}}
@valid_params_no_email %{"user" => %{"email" => :no_email}}
test "not signed in", %{conn: conn} do
conn = post(conn, Routes.pow_invitation_invitation_path(conn, :create, @valid_params))
assert_not_authenticated_redirect(conn)
end
test "with valid params", %{conn: conn} do
conn =
conn
|> Pow.Plug.assign_current_user(@user, [])
|> post(Routes.pow_invitation_invitation_path(conn, :create, @valid_params))
assert_received {:mail_mock, mail}
assert mail.subject == "You've been invited"
assert mail.text =~ "You've been invited by #{@user.email}."
assert mail.text =~ @url_regex
assert mail.html =~ "<p>You've been invited by #{@user.email}."
assert mail.html =~ @url_regex
assert redirected_to(conn) == Routes.pow_invitation_invitation_path(conn, :new)
assert get_flash(conn, :info) == "An e-mail with invitation link has been sent."
end
test "with invalid params", %{conn: conn} do
conn =
conn
|> Pow.Plug.assign_current_user(@user, [])
|> post(Routes.pow_invitation_invitation_path(conn, :create, @invalid_params))
assert html = html_response(conn, 200)
assert html =~ "<label for=\"user_email\">Email</label>"
assert html =~ "<input id=\"user_email\" name=\"user[email]\" type=\"text\" value=\"invalid\">"
assert html =~ "<span class=\"help-block\">has invalid format</span>"
end
test "with valid params and email taken", %{conn: conn} do
conn =
conn
|> Pow.Plug.assign_current_user(@user, [])
|> post(Routes.pow_invitation_invitation_path(conn, :create, @valid_params_email_taken))
refute_received {:mail_mock, _mail}
assert redirected_to(conn) == Routes.pow_invitation_invitation_path(conn, :new)
assert get_flash(conn, :info) == "An e-mail with invitation link has been sent."
end
test "with valid params and email taken with pow_prevent_user_enumeration: false", %{conn: conn} do
conn =
conn
|> Conn.put_private(:pow_prevent_user_enumeration, false)
|> Pow.Plug.assign_current_user(@user, [])
|> post(Routes.pow_invitation_invitation_path(conn, :create, @valid_params_email_taken))
assert html = html_response(conn, 200)
assert html =~ "<label for=\"user_email\">Email</label>"
assert html =~ "<input id=\"user_email\" name=\"user[email]\" type=\"text\" value=\"[email protected]\">"
assert html =~ "<span class=\"help-block\">has already been taken</span>"
end
test "user with no email", %{conn: conn} do
conn =
conn
|> Pow.Plug.assign_current_user(@user, [])
|> post(Routes.pow_invitation_invitation_path(conn, :create, @valid_params_no_email))
refute_received {:mail_mock, _mail}
assert redirected_to(conn) == Routes.pow_invitation_invitation_path(conn, :show, "valid")
end
end
describe "show/2" do
test "not signed in", %{conn: conn} do
conn = get(conn, Routes.pow_invitation_invitation_path(conn, :show, "valid"))
assert_not_authenticated_redirect(conn)
end
test "shows", %{conn: conn} do
conn =
conn
|> Pow.Plug.assign_current_user(@user, [])
|> get(Routes.pow_invitation_invitation_path(conn, :show, "valid"))
assert html = html_response(conn, 200)
assert html =~ @url_regex
end
end
describe "edit/2" do
test "already signed in", %{conn: conn} do
conn =
conn
|> Pow.Plug.assign_current_user(@user, [])
|> get(Routes.pow_invitation_invitation_path(conn, :edit, "valid"))
assert_authenticated_redirect(conn)
end
test "invalid invitation token", %{conn: conn} do
conn = get conn, Routes.pow_invitation_invitation_path(conn, :edit, "invalid")
assert redirected_to(conn) == Routes.pow_session_path(conn, :new)
assert get_flash(conn, :error) == "The invitation doesn't exist."
end
test "shows", %{conn: conn} do
conn = get conn, Routes.pow_invitation_invitation_path(conn, :edit, "valid")
assert Conn.get_resp_header(conn, "cache-control") == ["no-cache, no-store, must-revalidate"]
assert html = html_response(conn, 200)
assert html =~ "<label for=\"user_email\">Email</label>"
assert html =~ "<input id=\"user_email\" name=\"user[email]\" type=\"text\" value=\"[email protected]\">"
assert html =~ "<label for=\"user_password\">Password</label>"
assert html =~ "<input id=\"user_password\" name=\"user[password]\" type=\"password\">"
assert html =~ "<label for=\"user_password_confirmation\">Password confirmation</label>"
assert html =~ "<input id=\"user_password_confirmation\" name=\"user[password_confirmation]\" type=\"password\">"
assert html =~ "<button type=\"submit\">Submit</button>"
end
end
describe "update/2" do
@password "password1234"
@valid_params %{"user" => %{"email" => "[email protected]", "password" => @password, "password_confirmation" => @password}}
@valid_params_email_taken %{"user" => %{"email" => "[email protected]", "password" => @password, "password_confirmation" => @password}}
@invalid_params %{"user" => %{"email" => "invalid", "password" => @password, "password_confirmation" => "invalid"}}
test "already signed in", %{conn: conn} do
conn =
conn
|> Pow.Plug.assign_current_user(@user, [])
|> put(Routes.pow_invitation_invitation_path(conn, :update, "valid", @valid_params))
assert_authenticated_redirect(conn)
end
test "invalid invitation", %{conn: conn} do
conn = put conn, Routes.pow_invitation_invitation_path(conn, :update, "invalid", @valid_params)
assert redirected_to(conn) == Routes.pow_session_path(conn, :new)
assert get_flash(conn, :error) == "The invitation doesn't exist."
end
test "with valid params", %{conn: conn} do
conn = put conn, Routes.pow_invitation_invitation_path(conn, :update, "valid", @valid_params)
assert redirected_to(conn) == "/after_registration"
assert get_flash(conn, :info) == "user_created"
assert conn.private[:plug_session]["auth"]
end
test "with valid params and email taken", %{conn: conn} do
conn = put conn, Routes.pow_invitation_invitation_path(conn, :update, "valid", @valid_params_email_taken)
assert html = html_response(conn, 200)
assert html =~ "<label for=\"user_email\">Email</label>"
assert html =~ "<input id=\"user_email\" name=\"user[email]\" type=\"text\" value=\"[email protected]\">"
assert html =~ "<span class=\"help-block\">has already been taken</span>"
end
test "with invalid params", %{conn: conn} do
conn = put conn, Routes.pow_invitation_invitation_path(conn, :update, "valid", @invalid_params)
assert html = html_response(conn, 200)
assert html =~ "<label for=\"user_email\">Email</label>"
assert html =~ "<input id=\"user_email\" name=\"user[email]\" type=\"text\" value=\"invalid\">"
assert html =~ "<span class=\"help-block\">has invalid format</span>"
assert html =~ "<label for=\"user_password\">Password</label>"
assert html =~ "<input id=\"user_password\" name=\"user[password]\" type=\"password\">"
assert html =~ "<span class=\"help-block\">does not match confirmation</span>"
refute conn.private[:plug_session]["auth"]
end
end
end
| 40.428571 | 139 | 0.647085 |
f736f38aedb57c4c8fc5e098fe20741f0fecee16 | 3,722 | ex | Elixir | lib/serum/cli.ex | dragsubil/Serum | a465c48b388ef1e6d69ee6e8793f2869035b0520 | [
"MIT"
] | null | null | null | lib/serum/cli.ex | dragsubil/Serum | a465c48b388ef1e6d69ee6e8793f2869035b0520 | [
"MIT"
] | null | null | null | lib/serum/cli.ex | dragsubil/Serum | a465c48b388ef1e6d69ee6e8793f2869035b0520 | [
"MIT"
] | null | null | null | defmodule Serum.CLI.Task do
@moduledoc false
@callback tasks() :: [binary]
@callback run(task_name :: binary, args :: [binary]) :: {:cli_exit, integer}
@callback short_help(task_name :: binary) :: binary
@callback synopsis(task_name :: binary) :: binary
@callback help(task_name :: binary) :: binary | false
end
defmodule Serum.CLI do
@moduledoc """
This module contains the entry point for the command line program
(`Serum.CLI.main/1`).
"""
import Serum.Util
@behaviour Serum.CLI.Task
@main_task_providers [
Serum.CLI.Init,
Serum.CLI.Build,
Serum.CLI.Server,
__MODULE__
]
@doc "The entry point for Serum command-line program."
@spec main(args :: [binary]) :: any
def main(args)
def main([]) do
info()
usage()
end
def main(args) do
info()
[task|opts] = args
with task_module when not is_nil(task_module) <- task_map()[task],
{:cli_exit, status} <- task_module.run(task, opts)
do
System.halt status
else
nil ->
usage()
System.halt 2
x ->
warn "The task returned unexpected value: #{x}"
System.halt 1
end
end
@spec task_map() :: %{required(binary) => {atom, binary}}
defp task_map do
providers = @main_task_providers
Enum.reduce providers, %{}, fn module, acc ->
temp =
for task when is_binary(task) <- module.tasks(), into: %{} do
{task, module}
end
Map.merge acc, temp
end
end
@spec info() :: :ok
defp info() do
{:ok, v} = :application.get_key :serum, :vsn
IO.puts "\x1b[1mSerum -- Yet another simple static website generator\n"
<> "Version #{v}. Copyright (C) 2016 Dalgona. <[email protected]>\x1b[0m"
end
@spec usage() :: :ok
def usage() do
IO.puts """
Usage: serum <TASK>
Available Tasks:
(run "serum help TASK" to read detailed description for each TASK)
"""
display_tasks @main_task_providers
IO.puts """
Visit http://dalgona.hontou.moe/Serum for the getting started guide,
the official Serum documentation and more.
"""
end
@spec display_tasks([atom]) :: :ok
defp display_tasks(task_providers) do
{names, descriptions} =
task_providers
|> get_short_help
|> Enum.unzip
max_name_len = names |> Enum.map(&String.length/1) |> Enum.max
padded_names = Enum.map names, &String.pad_trailing(&1, max_name_len)
[padded_names, descriptions]
|> Enum.zip
|> Enum.each(fn {name, desc} ->
IO.puts " \x1b[96m#{name}\x1b[0m -- #{desc}"
end)
end
@spec get_short_help([atom]) :: [{binary, binary}]
defp get_short_help(task_providers) do
task_providers
|> Enum.map(&{&1, &1.tasks()})
|> Enum.map(fn {mod, l} -> Enum.map l, &{&1, mod.short_help(&1)} end)
|> List.flatten
end
#
# Serum.CLI.Task BEHAVIOUR IMPLEMENTATION
#
def tasks, do: ["help", "version"]
def run("help", []) do
usage()
{:cli_exit, 0}
end
def run("help", [arg|_]) do
case task_map()[arg] do
nil ->
usage()
{:cli_exit, 2}
mod ->
IO.ANSI.Docs.print_heading mod.synopsis arg
case mod.help arg do
text when is_binary(text) ->
IO.ANSI.Docs.print text
false ->
IO.puts "This task does not provide help text.\n"
end
{:cli_exit, 0}
end
end
def run("version", _), do: {:cli_exit, 0}
def short_help("help"), do: "Show help messages"
def short_help("version"), do: "Show version information"
def synopsis("help"), do: "serum help [TASK]"
def synopsis("version"), do: "serum version"
def help("help"), do: false
def help("version"), do: false
end
| 23.556962 | 80 | 0.604245 |
f73725398da8cf39657152a832a1ef98f7ba281d | 1,411 | ex | Elixir | apps/web/lib/web/endpoint.ex | elixirschool/extracurricular | eb8b725fa49ca91b1c6b7e610a8522bc81a80de1 | [
"MIT"
] | 48 | 2017-08-21T02:08:16.000Z | 2022-01-05T14:02:56.000Z | apps/web/lib/web/endpoint.ex | elixirschool/extracurricular | eb8b725fa49ca91b1c6b7e610a8522bc81a80de1 | [
"MIT"
] | 68 | 2017-08-21T02:17:32.000Z | 2017-11-09T15:56:27.000Z | apps/web/lib/web/endpoint.ex | elixirschool/extracurricular | eb8b725fa49ca91b1c6b7e610a8522bc81a80de1 | [
"MIT"
] | 26 | 2017-08-21T04:28:22.000Z | 2018-12-09T14:20:29.000Z | defmodule Web.Endpoint do
use Phoenix.Endpoint, otp_app: :web
use Appsignal.Phoenix
socket("/socket", Web.UserSocket)
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phoenix.digest
# when deploying your static files in production.
plug(
Plug.Static,
at: "/",
from: :web,
gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
)
plug(Plug.RequestId)
plug(Plug.Logger)
plug(
Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
)
plug(Plug.MethodOverride)
plug(Plug.Head)
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
plug(Plug.Session, store: :cookie, key: "_web_key", signing_salt: "lq27PnMr")
plug(Web.Router)
@doc """
Callback invoked for dynamically configuring the endpoint.
It receives the endpoint configuration and checks if
configuration should be loaded from the system environment.
"""
def init(_key, config) do
if config[:load_from_system_env] do
port = System.get_env("PORT") || raise "expected the PORT environment variable to be set"
{:ok, Keyword.put(config, :http, [:inet6, port: port])}
else
{:ok, config}
end
end
end
| 26.12963 | 95 | 0.680369 |
f7374196e12079cafe8c8eefe4af3b8d98132b12 | 840 | ex | Elixir | lib/exzeitable/text/default.ex | e-fu/exzeitable | 195da90e7fbab867c4964acab717e1ccb68ab226 | [
"MIT"
] | 138 | 2019-10-04T19:55:35.000Z | 2022-03-31T10:24:32.000Z | lib/exzeitable/text/default.ex | e-fu/exzeitable | 195da90e7fbab867c4964acab717e1ccb68ab226 | [
"MIT"
] | 127 | 2019-10-03T21:51:27.000Z | 2022-03-31T02:57:00.000Z | lib/exzeitable/text/default.ex | e-fu/exzeitable | 195da90e7fbab867c4964acab717e1ccb68ab226 | [
"MIT"
] | 14 | 2019-10-04T19:55:41.000Z | 2022-03-27T04:47:30.000Z | defmodule Exzeitable.Text.Default do
@moduledoc "Default text for the Exzeitable HTML interface"
@behaviour Exzeitable.Text
# Action buttons
def actions(_assigns), do: "Actions"
def new(_assigns), do: "New"
def show(_assigns), do: "Show"
def edit(_assigns), do: "Edit"
def delete(_assigns), do: "Delete"
def confirm_action(_assigns), do: "Are you sure?"
# Pagination
def previous(_assigns), do: "Previous"
def next(_assigns), do: "Next"
# Search
def search(_assigns), do: "Search"
def nothing_found(_assigns), do: "Nothing found"
# Show and hide fields
def show_field_buttons(_assigns), do: "Show Field Buttons"
def hide_field_buttons(_assigns), do: "Hide Field Buttons"
def show_field(_assigns, field), do: "Show #{field}"
def hide(_assigns), do: "hide"
def sort(_assigns), do: "sort"
end
| 26.25 | 61 | 0.70119 |
f73742b42d15cf0939f0e993dd81d86429d1942c | 3,360 | ex | Elixir | lib/clusterable/epmd.ex | princemaple/clusterable | 6f6a3061dc29e7dc7bbe60c269e11efa6376e5ad | [
"MIT"
] | 23 | 2017-02-17T09:28:24.000Z | 2021-01-19T05:45:54.000Z | lib/clusterable/epmd.ex | princemaple/clusterable | 6f6a3061dc29e7dc7bbe60c269e11efa6376e5ad | [
"MIT"
] | 3 | 2017-02-17T18:01:09.000Z | 2017-09-12T04:19:46.000Z | lib/clusterable/epmd.ex | princemaple/clusterable | 6f6a3061dc29e7dc7bbe60c269e11efa6376e5ad | [
"MIT"
] | 1 | 2017-07-28T07:57:34.000Z | 2017-07-28T07:57:34.000Z | # Shamelessly borrowed from Magnus Henoch's fantastic Erlang Solutions article:
# https://www.erlang-solutions.com/blog/erlang-and-elixir-distribution-without-epmd.html
# You want to read that! :)
defmodule Clusterable.EPMD.Service do
@moduledoc false
def port(name) when is_atom(name) do
port Atom.to_string name
end
def port(name) when is_list(name) do
port List.to_string name
end
def port(name) when is_binary(name) do
# Figure out the base port. If not specified using the
# inet_dist_base_port kernel environment variable, default to
# 4370, one above the epmd port.
base_port = :application.get_env :kernel, :inet_dist_base_port, 4370
# Now, figure out our "offset" on top of the base port. The
# offset is the integer just to the left of the @ sign in our node
# name. If there is no such number, the offset is 0.
#
# Also handle the case when no hostname was specified.
node_name = Regex.replace ~r/@.*$/, name, ""
offset =
case Regex.run ~r/[0-9]+$/, node_name do
nil ->
0
[offset_as_string] ->
String.to_integer offset_as_string
end
base_port + offset
end
end
defmodule Clusterable.EPMD.Service_dist do
@moduledoc false
def listen(name) do
port = Clusterable.EPMD.Service.port name
# Set both "min" and "max" variables, to force the port number to this one.
:ok = :application.set_env :kernel, :inet_dist_listen_min, port
:ok = :application.set_env :kernel, :inet_dist_listen_max, port
:inet_tcp_dist.listen name
end
def select(node) do
:inet_tcp_dist.select node
end
def accept(listen) do
:inet_tcp_dist.accept listen
end
def accept_connection(accept_pid, socket, my_node, allowed, setup_time) do
require Logger
Logger.debug("Accepting connection! #{inspect my_node}")
:inet_tcp_dist.accept_connection accept_pid, socket, my_node, allowed, setup_time
end
def setup(node, type, my_node, long_or_short_names, setup_time) do
:inet_tcp_dist.setup node, type, my_node, long_or_short_names, setup_time
end
def close(listen) do
:inet_tcp_dist.close listen
end
def childspecs do
#:inet_tcp_dist.childspecs
[]
end
end
defmodule Clusterable.EPMD.Client do
@moduledoc false
# erl_distribution wants us to start a worker process. We don't
# need one, though.
def start_link do
:ignore
end
# As of Erlang/OTP 19.1, register_node/3 is used instead of
# register_node/2, passing along the address family, 'inet_tcp' or
# 'inet6_tcp'. This makes no difference for our purposes.
def register_node(name, port, _family) do
register_node(name, port)
end
def register_node(_name, _port) do
# This is where we would connect to epmd and tell it which port
# we're listening on, but since we're epmd-less, we don't do that.
# Need to return a "creation" number between 1 and 3.
creation = :rand.uniform 3
{:ok, creation}
end
def port_please(name, _ip) do
port = Clusterable.EPMD.Service.port name
# The distribution protocol version number has been 5 ever since
# Erlang/OTP R6.
version = 5
{:port, port, version}
end
def names(_hostname) do
# Since we don't have epmd, we don't really know what other nodes
# there are.
{:error, :address}
end
end
| 28 | 89 | 0.699107 |
f73746b893e756b3c7fbca4f701755de902ff9ab | 2,567 | exs | Elixir | test/mix/tasks/dicon.switch_test.exs | manikdv/dicon | 9278f3000ed5a4fa2b57f80d14afe054c5514ecd | [
"0BSD"
] | null | null | null | test/mix/tasks/dicon.switch_test.exs | manikdv/dicon | 9278f3000ed5a4fa2b57f80d14afe054c5514ecd | [
"0BSD"
] | null | null | null | test/mix/tasks/dicon.switch_test.exs | manikdv/dicon | 9278f3000ed5a4fa2b57f80d14afe054c5514ecd | [
"0BSD"
] | null | null | null | defmodule Mix.Tasks.Dicon.SwitchTest do
use DiconTest.Case
import Mix.Tasks.Dicon.Switch, only: [run: 1]
test "relative path" do
config = %{
target_dir: "test",
hosts: [:one, :two],
one: [authority: "one"],
two: [authority: "two"],
}
Mix.Config.persist(dicon: config)
run(["0.1.0"])
assert_receive {:dicon, ref, :connect, ["one"]}
assert_receive {:dicon, ^ref, :exec, ["ln -snf $PWD/test/0.1.0 $PWD/test/current"]}
assert_receive {:dicon, ref, :connect, ["two"]}
assert_receive {:dicon, ^ref, :exec, ["ln -snf $PWD/test/0.1.0 $PWD/test/current"]}
refute_receive {:dicon, _, _, _}
end
test "absolute path" do
config = %{
target_dir: "/home/test",
hosts: [:one],
one: [authority: "one"],
}
Mix.Config.persist(dicon: config)
run(["0.2.0"])
assert_receive {:dicon, ref, :connect, ["one"]}
assert_receive {:dicon, ^ref, :exec, ["ln -snf /home/test/0.2.0 /home/test/current"]}
refute_receive {:dicon, _, _, _}
end
test "hosts filtering" do
config = %{
target_dir: "test",
hosts: [:one, :two],
one: [authority: "one"],
two: [authority: "two"],
}
Mix.Config.persist(dicon: config)
run(["0.2.0", "--only", "one"])
assert_receive {:dicon, ref, :connect, ["one"]}
:ok = flush_reply(ref)
refute_receive {:dicon, _, _, _}
run(["0.2.0", "--skip", "one"])
assert_receive {:dicon, ref, :connect, ["two"]}
:ok = flush_reply(ref)
refute_receive {:dicon, _, _, _}
run(["0.2.0", "--skip", "one", "--only", "one"])
refute_receive {:dicon, _, _, _}
run(["0.2.0", "--only", "one", "--only", "two"])
assert_receive {:dicon, ref, :connect, ["one"]}
:ok = flush_reply(ref)
assert_receive {:dicon, ref, :connect, ["two"]}
:ok = flush_reply(ref)
refute_receive {:dicon, _, _, _}
run(["0.2.0", "--skip", "one", "--skip", "two"])
refute_receive {:dicon, _, _, _}
assert_raise Mix.Error, "unknown host: \"foo\"", fn ->
run(["0.2.0", "--skip", "foo", "--skip", "two"])
end
end
test "the task only accepts one argument" do
message = "Expected a single argument (the version)"
assert_raise Mix.Error, message, fn -> run([]) end
assert_raise Mix.Error, message, fn -> run(~w(one two)) end
message = "Invalid option: --invalid"
assert_raise Mix.Error, message, fn -> run(~w(--invalid option)) end
message = "Invalid option: --no-value"
assert_raise Mix.Error, message, fn -> run(~w(--no-value)) end
end
end
| 28.208791 | 89 | 0.571874 |
f737477b07dec238a46b6022ab4f350839468b9e | 3,118 | ex | Elixir | lib/ash_policy_authorizer/sat_solver.ex | kernel-io/ash_policy_authorizer | cf9f44398e156dad3c38eb56d5f3fd25ebaa704a | [
"MIT"
] | 3 | 2020-10-06T06:36:53.000Z | 2021-09-22T13:31:53.000Z | lib/ash_policy_authorizer/sat_solver.ex | kernel-io/ash_policy_authorizer | cf9f44398e156dad3c38eb56d5f3fd25ebaa704a | [
"MIT"
] | 19 | 2020-06-09T05:16:13.000Z | 2021-04-20T18:27:43.000Z | lib/ash_policy_authorizer/sat_solver.ex | ash-project/ash_policy_access | a954bf12e3a65c9ea0b0eb888162064cae786cbd | [
"MIT"
] | 4 | 2020-08-27T19:12:02.000Z | 2021-12-19T22:50:35.000Z | defmodule AshPolicyAuthorizer.SatSolver do
@moduledoc false
def solve(expression) do
expression
|> add_negations_and_solve([])
|> get_all_scenarios(expression)
|> case do
[] ->
{:error, :unsatisfiable}
scenarios ->
static_checks = [
{AshPolicyAuthorizer.Check.Static, [result: true]},
{AshPolicyAuthorizer.Check.Static, [result: false]}
]
{:ok,
scenarios
|> Enum.uniq()
|> remove_irrelevant_clauses()
|> Enum.uniq()
|> Enum.map(&Map.drop(&1, static_checks))}
end
end
defp get_all_scenarios(scenario_result, expression, scenarios \\ [])
defp get_all_scenarios({:error, :unsatisfiable}, _, scenarios), do: scenarios
defp get_all_scenarios({:ok, scenario}, expression, scenarios) do
expression
|> add_negations_and_solve([Map.drop(scenario, [true, false]) | scenarios])
|> get_all_scenarios(expression, [Map.drop(scenario, [true, false]) | scenarios])
end
def remove_irrelevant_clauses([scenario]), do: [scenario]
def remove_irrelevant_clauses(scenarios) do
new_scenarios =
scenarios
|> Enum.uniq()
|> Enum.map(fn scenario ->
unnecessary_fact = find_unnecessary_fact(scenario, scenarios)
Map.delete(scenario, unnecessary_fact)
end)
|> Enum.uniq()
if new_scenarios == scenarios do
scenarios
else
remove_irrelevant_clauses(new_scenarios)
end
end
defp find_unnecessary_fact(scenario, scenarios) do
Enum.find_value(scenario, fn
{fact, value_in_this_scenario} ->
matching =
Enum.find(scenarios, fn potential_irrelevant_maker ->
potential_irrelevant_maker != scenario &&
Map.delete(scenario, fact) == Map.delete(potential_irrelevant_maker, fact)
end)
case matching do
%{^fact => value} when is_boolean(value) and value != value_in_this_scenario ->
fact
_ ->
false
end
end)
end
@spec add_negations_and_solve(term, term) :: term | no_return()
defp add_negations_and_solve(requirements_expression, negations) do
negations =
Enum.reduce(negations, nil, fn negation, expr ->
negation_statement =
negation
|> Map.drop([true, false])
|> facts_to_statement()
if expr do
{:and, expr, {:not, negation_statement}}
else
{:not, negation_statement}
end
end)
full_expression =
if negations do
{:and, requirements_expression, negations}
else
requirements_expression
end
solve_expression(full_expression)
end
def facts_to_statement(facts) do
Enum.reduce(facts, nil, fn {fact, true?}, expr ->
expr_component =
if true? do
fact
else
{:not, fact}
end
if expr do
{:and, expr, expr_component}
else
expr_component
end
end)
end
defp solve_expression(expression) do
Ash.SatSolver.solve_expression(expression)
end
end
| 25.768595 | 89 | 0.618987 |
f73756754ef7ca09e0810e4531a9c9773701a246 | 2,175 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/allocation_specific_sku_reservation.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/compute/lib/google_api/compute/v1/model/allocation_specific_sku_reservation.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/allocation_specific_sku_reservation.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.Compute.V1.Model.AllocationSpecificSKUReservation do
@moduledoc """
This reservation type allows to pre allocate specific instance configuration.
## Attributes
* `count` (*type:* `String.t`, *default:* `nil`) - Specifies number of resources that are allocated.
* `inUseCount` (*type:* `String.t`, *default:* `nil`) - [OutputOnly] Indicates how many resource are in use.
* `instanceProperties` (*type:* `GoogleApi.Compute.V1.Model.AllocationSpecificSKUAllocationReservedInstanceProperties.t`, *default:* `nil`) - The instance properties for this specific sku reservation.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:count => String.t(),
:inUseCount => String.t(),
:instanceProperties =>
GoogleApi.Compute.V1.Model.AllocationSpecificSKUAllocationReservedInstanceProperties.t()
}
field(:count)
field(:inUseCount)
field(
:instanceProperties,
as: GoogleApi.Compute.V1.Model.AllocationSpecificSKUAllocationReservedInstanceProperties
)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.AllocationSpecificSKUReservation do
def decode(value, options) do
GoogleApi.Compute.V1.Model.AllocationSpecificSKUReservation.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.AllocationSpecificSKUReservation do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 37.5 | 204 | 0.746667 |
f737589d14d111113b6c928f8fc8905f7141c07b | 680 | ex | Elixir | 2020/elixir/day_01.ex | Prajjwal/advent-of-code | c3de48eee1e9e5b0eaabab31f4037542f0f2b374 | [
"CC0-1.0"
] | null | null | null | 2020/elixir/day_01.ex | Prajjwal/advent-of-code | c3de48eee1e9e5b0eaabab31f4037542f0f2b374 | [
"CC0-1.0"
] | null | null | null | 2020/elixir/day_01.ex | Prajjwal/advent-of-code | c3de48eee1e9e5b0eaabab31f4037542f0f2b374 | [
"CC0-1.0"
] | null | null | null | input = File.stream!(hd System.argv)
|> Enum.map(&Integer.parse/1)
|> Enum.map(fn { i, "\n" } -> i end)
|> Enum.sort
pairs = Stream.flat_map input, fn i ->
Stream.flat_map input, fn j ->
[{ i, j }]
end
end
triplets = Stream.flat_map pairs, fn { i, j } ->
Stream.flat_map input, fn k ->
[{ i, j, k }]
end
end
[{ a, b }] = pairs
|> Stream.filter(fn { i, j } -> i < j end)
|> Stream.filter(fn { i, j } -> i + j == 2020 end)
|> Enum.take(1)
IO.inspect(a * b)
[{ a, b, c }] = triplets
|> Stream.filter(fn { i, j, k } -> i + j + k == 2020 end)
|> Enum.take(1)
IO.inspect(a * b * c)
| 22.666667 | 71 | 0.472059 |
f73768edc80048c6cc2c1047860cfef77c0b0ba6 | 1,083 | ex | Elixir | lib/hl7/2.3.1/segments/stf.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | lib/hl7/2.3.1/segments/stf.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | lib/hl7/2.3.1/segments/stf.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | defmodule HL7.V2_3_1.Segments.STF do
@moduledoc false
require Logger
alias HL7.V2_3_1.{DataTypes}
use HL7.Segment,
fields: [
segment: nil,
primary_key_value_stf: DataTypes.Ce,
staff_id_code: DataTypes.Cx,
staff_name: DataTypes.Xpn,
staff_type: nil,
sex: nil,
date_time_of_birth: DataTypes.Ts,
active_inactive_flag: nil,
department: DataTypes.Ce,
hospital_service: DataTypes.Ce,
phone: DataTypes.Xtn,
office_home_address: DataTypes.Xad,
institution_activation_date: DataTypes.Din,
institution_inactivation_date: DataTypes.Din,
backup_person_id: DataTypes.Ce,
e_mail_address: nil,
preferred_method_of_contact: DataTypes.Ce,
marital_status: DataTypes.Ce,
job_title: nil,
job_code_class: DataTypes.Jcc,
employment_status: nil,
additional_insured_on_auto: nil,
drivers_license_number_staff: DataTypes.Dln,
copy_auto_ins: nil,
auto_ins_expires: nil,
date_last_dmv_review: nil,
date_next_dmv_review: nil
]
end
| 28.5 | 51 | 0.695291 |
f737938c878c7bc5831b2a1bccacf884fd8f7955 | 1,807 | exs | Elixir | config/dev.exs | onixus74/conduit-cqrs | 879973ea66be9470d46111312a2995004d3d0b58 | [
"MIT"
] | null | null | null | config/dev.exs | onixus74/conduit-cqrs | 879973ea66be9470d46111312a2995004d3d0b58 | [
"MIT"
] | 2 | 2022-01-15T02:09:30.000Z | 2022-01-22T10:18:43.000Z | config/dev.exs | onixus74/conduit-cqrs | 879973ea66be9470d46111312a2995004d3d0b58 | [
"MIT"
] | null | null | null | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :conduit, ConduitWeb.Endpoint,
http: [port: 4900],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: []
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# command from your terminal:
#
# openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem
#
# The `http:` config above can be replaced with:
#
# https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# 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
# Configures the event store database
config :conduit, Conduit.EventStore,
serializer: Commanded.Serialization.JsonSerializer,
username: "postgres",
password: "postgres",
database: "conduit_eventstore_dev",
hostname: "10.152.183.228",
pool_size: 10
# Configures the read store database
config :conduit, Conduit.Repo,
migration_timestamps: [type: :utc_datetime_usec],
username: "postgres",
password: "postgres",
database: "conduit_readstore_dev",
hostname: "10.152.183.228",
pool_size: 10
| 32.267857 | 170 | 0.7399 |
f737aced1c1be5b3f8956ed4812a3173d0db3b8f | 10,482 | ex | Elixir | lib/oli/grading.ex | candert1/oli-torus | b7408f7d7c04cc3e9cf537873d98c3a586ec3a66 | [
"MIT"
] | null | null | null | lib/oli/grading.ex | candert1/oli-torus | b7408f7d7c04cc3e9cf537873d98c3a586ec3a66 | [
"MIT"
] | null | null | null | lib/oli/grading.ex | candert1/oli-torus | b7408f7d7c04cc3e9cf537873d98c3a586ec3a66 | [
"MIT"
] | null | null | null | defmodule Oli.Grading do
@moduledoc """
Grading is responsible for compiling attempts into usable gradebook representation
consumable by various tools such as Excel (CSV) or an LMS API.
"""
require Logger
import Ecto.Query, warn: false
import Oli.Utils, only: [log_error: 2]
alias Oli.Publishing.DeliveryResolver
alias Oli.Delivery.Sections
alias Oli.Delivery.Sections.Section
alias Oli.Delivery.Attempts.Core, as: Attempts
alias Oli.Delivery.Attempts.Core.ResourceAccess
alias Oli.Grading.GradebookRow
alias Oli.Grading.GradebookScore
alias Oli.Activities.Realizer.Selection
alias Lti_1p3.Tool.ContextRoles
alias Lti_1p3.Tool.Services.AGS
alias Lti_1p3.Tool.Services.AGS.Score
alias Oli.Resources.Revision
alias Oli.Publishing.PublishedResource
alias Oli.Resources.ResourceType
alias Oli.Repo
alias Oli.Delivery.Sections.SectionsProjectsPublications
@doc """
If grade passback services 2.0 is enabled, sends the current state of a ResourceAccess
score for the current user to the LMS.
If sent successfully, returns {:ok, :synced}
If grade passback not enabled, returns {:ok, :not_synced}
If error encountered, returns {:error, error}
"""
def send_score_to_lms(section, user, %ResourceAccess{} = resource_access, access_token_provider) do
# First check to see if grade passback is enabled
if section.grade_passback_enabled do
case access_token_provider.() do
{:ok, access_token} -> send_score(section, user, resource_access, access_token)
e -> e
end
else
{:ok, :not_synced}
end
end
def ags_scopes() do
[
"https://purl.imsglobal.org/spec/lti-ags/scope/lineitem",
"https://purl.imsglobal.org/spec/lti-ags/scope/result.readonly",
"https://purl.imsglobal.org/spec/lti-ags/scope/score",
"https://purl.imsglobal.org/spec/lti-nrps/scope/contextmembership.readonly"
]
end
defp send_score(section, user, %ResourceAccess{} = resource_access, token) do
revision = DeliveryResolver.from_resource_id(section.slug, resource_access.resource_id)
out_of_provider = fn -> determine_page_out_of(section.slug, revision) end
# Next, fetch (and possibly create) the line item associated with this resource
case AGS.fetch_or_create_line_item(
section.line_items_service_url,
resource_access.resource_id,
out_of_provider,
revision.title,
token
) do
# Finally, post the score for this line item
{:ok, line_item} ->
case to_score(user.sub, resource_access)
|> AGS.post_score(line_item, token) do
{:ok, _} -> {:ok, :synced}
e -> e
end
{:error, e} ->
{_id, msg} = log_error("Failed to fetch or create LMS line item", e)
{:error, msg}
end
end
# helper to create an LTI AGS 2.0 compliant score from our launch params and
# our resource access
def to_score(sub, %ResourceAccess{} = resource_access) do
{:ok, dt} = DateTime.now("Etc/UTC")
timestamp = DateTime.to_iso8601(dt)
%Score{
timestamp: timestamp,
scoreGiven: resource_access.score,
scoreMaximum: resource_access.out_of,
comment: "",
activityProgress: "Completed",
gradingProgress: "FullyGraded",
userId: sub
}
end
@doc """
Exports the gradebook for the provided section in CSV format
Returns a Stream which can be written to a file or other IO
"""
def export_csv(%Section{} = section) do
{gradebook, column_labels} = generate_gradebook_for_section(section)
table_data =
gradebook
|> Enum.map(fn %GradebookRow{user: user, scores: scores} ->
[
"#{user.name} (#{user.email})"
| Enum.map(scores, fn gradebook_score ->
case gradebook_score do
nil ->
nil
%GradebookScore{score: score} ->
score
end
end)
]
end)
# unfortunately we must go through every score to ensure out_of has been found for a column
# TODO: optimize this logic to bail out once an out_of has been discovered for every column
points_possible =
gradebook
|> Enum.reduce([], fn %GradebookRow{scores: scores}, acc ->
scores
|> Enum.with_index()
|> Enum.map(fn {gradebook_score, i} ->
case gradebook_score do
nil ->
# use existing value for column
Enum.at(acc, i)
%GradebookScore{out_of: nil} ->
# use existing value for column
Enum.at(acc, i)
%GradebookScore{out_of: out_of} ->
# replace value of existing column
out_of
end
end)
end)
points_possible = [[" Points Possible" | points_possible]]
column_labels = [["Student" | column_labels]]
(column_labels ++ points_possible ++ table_data)
|> CSV.encode()
end
@doc """
Returns a tuple containing a list of GradebookRow for every enrolled user
and an ordered list of column labels
`{[%GradebookRow{user: %User{}, scores: [%GradebookScore{}, ...]}, ...], ["Quiz 1", "Quiz 2"]}`
"""
def generate_gradebook_for_section(%Section{} = section) do
# get publication page resources, filtered by graded: true
graded_pages = fetch_graded_pages(section.slug)
# get students enrolled in the section, filter by role: student
students = fetch_students(section.slug)
# create a map of all resource accesses, keyed off resource id
resource_accesses = fetch_resource_accesses(section.slug)
# build gradebook map - for each user in the section, create a gradebook row. Using
# resource_accesses, create a list of gradebook scores leaving scores null if they do not exist
gradebook =
Enum.map(students, fn %{id: user_id} = student ->
scores =
Enum.reduce(Enum.reverse(graded_pages), [], fn revision, acc ->
score =
case resource_accesses[revision.resource_id] do
%{^user_id => student_resource_accesses} ->
case student_resource_accesses do
%ResourceAccess{score: score, out_of: out_of} ->
%GradebookScore{
resource_id: revision.resource_id,
label: revision.title,
score: score,
out_of: out_of
}
_ ->
nil
end
_ ->
nil
end
[score | acc]
end)
%GradebookRow{user: student, scores: scores}
end)
# return gradebook
column_labels = Enum.map(graded_pages, fn revision -> revision.title end)
{gradebook, column_labels}
end
@doc """
Determines the maximum point value that can be obtained for a page.
Two implementations exist, one for adaptive pages and one for regular pages. The
adaptive implementation reads the "totalScore" key that should be present under the
"custom" key.
The basic implementation counts the activities present (including those from
activity bank selections).
"""
def determine_page_out_of(_section_slug, %Revision{
content: %{"advancedDelivery" => true} = content
}) do
read_total_score(content)
|> ensure_valid_number()
|> max(1.0)
end
def determine_page_out_of(_section_slug, %Revision{content: %{"model" => model}}) do
Enum.reduce(model, 0, fn e, count ->
case e["type"] do
"activity-reference" ->
count + 1
"selection" ->
case Selection.parse(e) do
{:ok, %Selection{count: selection_count}} -> selection_count + count
_ -> count
end
_ ->
count
end
end)
|> max(1.0)
end
# reads the "custom / totalScore" nested key in a robust manner, with a default
# value of 1.0.
defp read_total_score(content) do
Map.get(content, "custom", %{"totalScore" => 1.0})
|> Map.get("totalScore", 1.0)
end
# ensure the read total score is a number, converting from a string and
# ignoring other constructs (imagine a JSON object here instead)
defp ensure_valid_number(value) when is_binary(value) do
case Float.parse(value) do
{f, _} -> f
_ -> 1.0
end
end
defp ensure_valid_number(value) when is_integer(value), do: value
defp ensure_valid_number(value) when is_float(value), do: value
defp ensure_valid_number(_), do: 1.0
def fetch_students(section_slug) do
Sections.list_enrollments(section_slug)
|> Enum.filter(fn e ->
ContextRoles.contains_role?(e.context_roles, ContextRoles.get_role(:context_learner))
end)
|> Enum.map(fn e -> e.user end)
end
def fetch_instructors(section_slug) do
Sections.list_enrollments(section_slug)
|> Enum.filter(fn e ->
ContextRoles.contains_role?(e.context_roles, ContextRoles.get_role(:context_instructor))
end)
|> Enum.map(fn e -> e.user end)
end
def fetch_resource_accesses(section_slug) do
Attempts.get_graded_resource_access_for_context(section_slug)
|> Enum.reduce(%{}, fn resource_access, acc ->
case acc[resource_access.resource_id] do
nil ->
Map.put_new(
acc,
resource_access.resource_id,
Map.put_new(%{}, resource_access.user_id, resource_access)
)
resource_accesses ->
Map.put(
acc,
resource_access.resource_id,
Map.put_new(resource_accesses, resource_access.user_id, resource_access)
)
end
end)
end
def fetch_graded_pages(section_slug) do
resource_type_id = ResourceType.get_id_by_type("page")
Repo.all(
from(s in Section,
join: spp in SectionsProjectsPublications,
on: s.id == spp.section_id,
join: pr in PublishedResource,
on: pr.publication_id == spp.publication_id,
join: rev in Revision,
on: rev.id == pr.revision_id,
where:
rev.deleted == false and
rev.graded == true and
rev.resource_type_id == ^resource_type_id and
s.slug == ^section_slug and
s.status != :deleted,
order_by: [rev.inserted_at, rev.id],
distinct: true,
select: rev
)
)
end
end
| 31.477477 | 101 | 0.632227 |
f737b3eb39a0e0aa6df1b04a486beeb4748e75bb | 1,056 | ex | Elixir | echo/lib/echo/application.ex | lamboap/liveview_sept_2021 | 495731c20484a0e63e5fb768956b98d57b44be8f | [
"MIT"
] | 1 | 2021-09-14T01:52:42.000Z | 2021-09-14T01:52:42.000Z | echo/lib/echo/application.ex | lamboap/liveview_sept_2021 | 495731c20484a0e63e5fb768956b98d57b44be8f | [
"MIT"
] | 1 | 2021-09-17T11:30:04.000Z | 2021-09-17T11:30:04.000Z | echo/lib/echo/application.ex | lamboap/liveview_sept_2021 | 495731c20484a0e63e5fb768956b98d57b44be8f | [
"MIT"
] | 4 | 2021-09-14T00:04:39.000Z | 2021-09-15T15:14:52.000Z | defmodule Echo.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
# the OTP stuff here, lifecycle concerns (start/stop/children, etc...)
@moduledoc false
use Application
def start(_type, _args) do
children = [
# Start the Ecto repository
Echo.Repo,
# Start the Telemetry supervisor
EchoWeb.Telemetry,
# Start the PubSub system
{Phoenix.PubSub, name: Echo.PubSub},
# Start the Endpoint (http/https)
EchoWeb.Endpoint
# Start a worker by calling: Echo.Worker.start_link(arg)
# {Echo.Worker, arg}
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Echo.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
EchoWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 29.333333 | 72 | 0.695076 |
f737c73d3cd8dc53f247de5b46fca8a24779dd86 | 2,532 | ex | Elixir | lib/helper/public_ip_plug.ex | coderplanets/coderplanets_server | 3663e56340d6d050e974c91f7e499d8424fc25e9 | [
"Apache-2.0"
] | 240 | 2018-11-06T09:36:54.000Z | 2022-02-20T07:12:36.000Z | lib/helper/public_ip_plug.ex | coderplanets/coderplanets_server | 3663e56340d6d050e974c91f7e499d8424fc25e9 | [
"Apache-2.0"
] | 363 | 2018-07-11T03:38:14.000Z | 2021-12-14T01:42:40.000Z | lib/helper/public_ip_plug.ex | mydearxym/mastani_server | f24034a4a5449200165cf4a547964a0961793eab | [
"Apache-2.0"
] | 22 | 2019-01-27T11:47:56.000Z | 2021-02-28T13:17:52.000Z | # https://www.cogini.com/blog/getting-the-client-public-ip-address-in-phoenix/
defmodule Helper.PublicIpPlug do
@moduledoc "Get public IP address of request from x-forwarded-for header"
@behaviour Plug
@app :groupher_server
def init(opts), do: opts
def call(%{assigns: %{ip: _}} = conn, _opts), do: conn
def call(conn, _opts) do
process(conn, Plug.Conn.get_req_header(conn, "X-Forwarded-For"))
end
def process(conn, []) do
Plug.Conn.assign(conn, :ip, to_string(:inet.ntoa(get_peer_ip(conn))))
end
def process(conn, vals) do
if Application.get_env(@app, :trust_x_forwarded_for, false) do
ip_address = get_ip_address(conn, vals)
# Rewrite standard remote_ip field with value from header
# See https://hexdocs.pm/plug/Plug.Conn.html
conn = %{conn | remote_ip: ip_address}
Plug.Conn.assign(conn, :ip, to_string(:inet.ntoa(ip_address)))
else
Plug.Conn.assign(conn, :ip, to_string(:inet.ntoa(get_peer_ip(conn))))
end
end
defp get_ip_address(conn, vals)
defp get_ip_address(conn, []), do: get_peer_ip(conn)
defp get_ip_address(conn, [val | _]) do
# Split into multiple values
comps =
val
|> String.split(~r{\s*,\s*}, trim: true)
# Get rid of "unknown" values
|> Enum.filter(&(&1 != "unknown"))
# Split IP from port, if any
|> Enum.map(&hd(String.split(&1, ":")))
# Filter out blanks
|> Enum.filter(&(&1 != ""))
# Parse address into :inet.ip_address tuple
|> Enum.map(&parse_address(&1))
# Elminate internal IP addreses, e.g. 192.168.1.1
|> Enum.filter(&is_public_ip(&1))
case comps do
[] -> get_peer_ip(conn)
[comp | _] -> comp
end
end
@spec get_peer_ip(Plug.Conn.t()) :: :inet.ip_address()
defp get_peer_ip(conn) do
{ip, _port} = conn.peer
ip
end
@spec parse_address(String.t()) :: :inet.ip_address()
defp parse_address(ip) do
case :inet.parse_ipv4strict_address(to_charlist(ip)) do
{:ok, ip_address} -> ip_address
{:error, :einval} -> :einval
end
end
# Whether the input is a valid, public IP address
# http://en.wikipedia.org/wiki/Private_network
@spec is_public_ip(:inet.ip_address() | atom) :: boolean
defp is_public_ip(ip_address) do
case ip_address do
{10, _, _, _} -> false
{192, 168, _, _} -> false
{172, second, _, _} when second >= 16 and second <= 31 -> false
{127, 0, 0, _} -> false
{_, _, _, _} -> true
:einval -> false
end
end
end
| 29.44186 | 78 | 0.627962 |
f737dd19ed162d5fb18317111c125c31a7eca96f | 1,292 | exs | Elixir | config/config.exs | bitpal/bitpal_demo | 989df08f60dadc5d4e340fef91890cf8bb3106ad | [
"BSD-3-Clause-Clear"
] | null | null | null | config/config.exs | bitpal/bitpal_demo | 989df08f60dadc5d4e340fef91890cf8bb3106ad | [
"BSD-3-Clause-Clear"
] | 1 | 2021-06-04T13:53:01.000Z | 2021-06-04T13:53:01.000Z | config/config.exs | bitpal/bitpal_demo | 989df08f60dadc5d4e340fef91890cf8bb3106ad | [
"BSD-3-Clause-Clear"
] | null | null | null | import Config
config :demo,
# xpub:
# "xpub6DWyFPVAuvsno6PmiQq5Rrbw3Hb5fvD8EVSVGimu1koSuQc4HEmanCGVjc6GMxWpj2JsafJ4Rdbq2EwtprRxr6B9PxozpaoEDg6z168NYT1",
# recipent_description: "BitPal Demo",
required_confirmations: 0
# Configures the endpoint
config :demo, Demo.Endpoint,
url: [host: "localhost"],
secret_key_base: "5TKeJY+t76NIIJCFwLBu7yfjSI8DlN14H65sbN+AonRHFOBhBeSCSI1g4tmDlc7v",
render_errors: [view: Demo.ErrorView, accepts: ~w(html json), layout: false],
pubsub_server: Demo.PubSub,
live_view: [signing_salt: "gI8eT+Yx"]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
config :money, :custom_currencies, %{
BCH: %{name: "Bitcoin Cash", exponent: 8, symbol: "BCH"},
BTC: %{name: "Bitcoin", exponent: 8, symbol: "BTC"},
DGC: %{name: "Dogecoin", exponent: 8, symbol: "DGC"},
XMR: %{name: "Monero", exponent: 12, symbol: "XMR"}
}
config :demo,
http_client: BitPalPhx.HTTPClient,
recipent_description: "BitPal demo"
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config("#{config_env()}.exs")
| 33.128205 | 122 | 0.735294 |
f737ddccbaf0ffdc054059358424e952ddfa0f64 | 90 | exs | Elixir | test/yahoo_wrapper_web/views/page_view_test.exs | TKW25/yahoo-wrapper | 48e9a55b0a96ea0c7131ae408c9a35c5f6bb2382 | [
"MIT"
] | null | null | null | test/yahoo_wrapper_web/views/page_view_test.exs | TKW25/yahoo-wrapper | 48e9a55b0a96ea0c7131ae408c9a35c5f6bb2382 | [
"MIT"
] | null | null | null | test/yahoo_wrapper_web/views/page_view_test.exs | TKW25/yahoo-wrapper | 48e9a55b0a96ea0c7131ae408c9a35c5f6bb2382 | [
"MIT"
] | null | null | null | defmodule YahooWrapperWeb.PageViewTest do
use YahooWrapperWeb.ConnCase, async: true
end
| 22.5 | 43 | 0.844444 |
f73804ebac3d2643b0aa4b323d03e71e9e99336a | 1,876 | exs | Elixir | test/function_decorating_test.exs | elpddev/elixir-function-decorating | fb633792ada653ad81d4e0fd3aec9c8e6337ce3a | [
"MIT"
] | 4 | 2016-03-22T10:58:52.000Z | 2020-12-10T18:24:58.000Z | test/function_decorating_test.exs | elpddev/elixir-function-decorating | fb633792ada653ad81d4e0fd3aec9c8e6337ce3a | [
"MIT"
] | 9 | 2016-04-04T10:13:24.000Z | 2016-04-10T16:40:13.000Z | test/function_decorating_test.exs | elpddev/elixir-function-decorating | fb633792ada653ad81d4e0fd3aec9c8e6337ce3a | [
"MIT"
] | 2 | 2017-07-12T21:55:04.000Z | 2018-09-08T13:03:17.000Z | defmodule FunctionDecoratingTest do
use ExUnit.Case
doctest FunctionDecorating
test "calc args - mix_envs - default" do
assert FunctionDecorating.calc_args(quote do nil end) == {[:dev], :test}
end
test "do_using - simple - mix env = dev" do
result_ast = FunctionDecorating.do_using(quote do [current_mix_env: :dev] end)
assert result_ast == FunctionDecorating.generate_using_ast
end
test "do_using - simple - mix env = prod" do
result_ast = FunctionDecorating.do_using(quote do [current_mix_env: :prod] end)
expected_ast = FunctionDecorating.generate_bare_using_ast
assert result_ast == expected_ast
end
test "do_using - with 'mix_envs: [:prod]', mix env = :prod" do
result_ast = FunctionDecorating.do_using(quote do [mix_envs: [:prod], current_mix_env: :prod] end)
assert result_ast == FunctionDecorating.generate_using_ast
end
test "decorate_function_def" do
fn_call_ast = quote do beep(word) end
fn_options_ast = [do: quote do word end]
defmodule TestModuleDecorator do
def decorate(
%FnDef{
fn_call_ast: in_fn_call_ast,
fn_options_ast: [do: in_do_block] = _in_fn_options_ast
} = _fn_def, decorate_options) do
{:ok, %FnDef{
fn_call_ast: in_fn_call_ast,
fn_options_ast: [do: quote do
decorate_1
unquote(in_do_block)
end]
}}
end
end
result = FunctionDecorating.decorate_function_def(%FnDef{
fn_call_ast: fn_call_ast, fn_options_ast: fn_options_ast},
[{TestModuleDecorator, []}])
decorating_exp = quote context: TestModuleDecorator do decorate_1 end
assert result == {:ok, %FnDef{
fn_call_ast: quote do beep(word) end,
fn_options_ast: [do: quote do
unquote(decorating_exp)
word
end]
}}
end
end
| 30.754098 | 102 | 0.670576 |
f7380b7c5a77e9719e95a263d5d3ba7f5777b2e7 | 3,800 | ex | Elixir | lib/livebook/runtime.ex | edmundobiglia/livebook | d3b4a8a9e6d2f34d2c309e6cc59774dcf12ba0af | [
"Apache-2.0"
] | null | null | null | lib/livebook/runtime.ex | edmundobiglia/livebook | d3b4a8a9e6d2f34d2c309e6cc59774dcf12ba0af | [
"Apache-2.0"
] | null | null | null | lib/livebook/runtime.ex | edmundobiglia/livebook | d3b4a8a9e6d2f34d2c309e6cc59774dcf12ba0af | [
"Apache-2.0"
] | null | null | null | defprotocol Livebook.Runtime do
@moduledoc false
# This protocol defines an interface for evaluation backends.
#
# Usually a runtime involves a set of processes responsible
# for evaluation, which could be running on a different node,
# however the protocol does not require that.
@typedoc """
A term used to identify evaluation or container.
"""
@type ref :: term()
@typedoc """
A single completion result.
"""
@type completion_item :: %{
label: String.t(),
kind: completion_item_kind(),
detail: String.t() | nil,
documentation: String.t() | nil,
insert_text: String.t()
}
@type completion_item_kind :: :function | :module | :type | :variable | :field
@doc """
Sets the caller as runtime owner.
The runtime most likely has some kind of leading process,
this method starts monitoring it and returns the monitor reference,
so the caller knows if the runtime is down by listening to a :DOWN message.
"""
@spec connect(t()) :: reference()
def connect(runtime)
@doc """
Disconnects the current owner from runtime.
This should cleanup the underlying node/processes.
"""
@spec disconnect(t()) :: :ok
def disconnect(runtime)
@doc """
Asynchronously parses and evaluates the given code.
Container isolates a group of evaluations. Every evaluation can use previous
evaluation's environment and bindings, as long as they belong to the same container.
Evaluation outputs are send to the connected runtime owner.
The messages should be of the form:
* `{:evaluation_output, ref, output}` - output captured during evaluation
* `{:evaluation_response, ref, output}` - final result of the evaluation
The evaluation may request user input by sending `{:evaluation_input, ref, reply_to, prompt}`
to the runtime owner, who is supposed to reply with `{:evaluation_input_reply, reply}`
with `reply` being either `{:ok, input}` or `:error` if no matching input can be found.
If the evaluation state within a container is lost (e.g. a process goes down),
the runtime can send `{:container_down, container_ref, message}` to notify the owner.
## Options
* `:file` - file to which the evaluated code belongs. Most importantly,
this has an impact on the value of `__DIR__`.
"""
@spec evaluate_code(t(), String.t(), ref(), ref(), ref() | nil, keyword()) :: :ok
def evaluate_code(runtime, code, container_ref, evaluation_ref, prev_evaluation_ref, opts \\ [])
@doc """
Disposes of evaluation identified by the given ref.
This should be used to cleanup resources related to old evaluation if no longer needed.
"""
@spec forget_evaluation(t(), ref(), ref()) :: :ok
def forget_evaluation(runtime, container_ref, evaluation_ref)
@doc """
Disposes of evaluation container identified by the given ref.
This should be used to cleanup resources keeping track
of the container and contained evaluations.
"""
@spec drop_container(t(), ref()) :: :ok
def drop_container(runtime, container_ref)
@doc """
Asynchronously finds completion items matching the given `hint` text.
The given `{container_ref, evaluation_ref}` pair idenfities an evaluation,
which bindings and environment are used to provide a more relevant completion results.
If there's no appropriate evaluation, `nil` refs can be provided.
Completion response is sent to the `send_to` process as `{:completion_response, ref, items}`,
where `items` is a list of `Livebook.Runtime.completion_item()`.
"""
@spec request_completion_items(t(), pid(), term(), String.t(), ref() | nil, ref() | nil) :: :ok
def request_completion_items(
runtime,
send_to,
ref,
hint,
container_ref,
evaluation_ref
)
end
| 34.545455 | 98 | 0.697632 |
f7381c8571859b3089f2ae6ecee93f9b7dc95e5c | 2,247 | ex | Elixir | lib/elixir/lib/macro/env.ex | ekosz/elixir | 62e375bc711b4072e1b68de776e96cc31f571d45 | [
"Apache-2.0"
] | 1 | 2017-10-29T16:37:08.000Z | 2017-10-29T16:37:08.000Z | lib/elixir/lib/macro/env.ex | ekosz/elixir | 62e375bc711b4072e1b68de776e96cc31f571d45 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/macro/env.ex | ekosz/elixir | 62e375bc711b4072e1b68de776e96cc31f571d45 | [
"Apache-2.0"
] | null | null | null | # We generate this record using a raw module due to
# bootstrap constraints. Notice the fields are not
# represented by a keywords list because we want
# to keep control over the order.
defmodule Macro.Env do
@doc """
A record that contains compile time environment information,
It can be accessed at any time by calling __ENV__.
"""
def __access__(caller, args) do
Record.access(caller, __MODULE__, __record__(:fields), args)
end
def __record__(kind, _), do: __record__(kind)
def __record__(:name), do: Macro.Env
# When adding removing new fields,
# src/elixir_tree_helpers.erl needs to be changed as well.
def __record__(:fields) do
[
{:module,nil},
{:file,nil},
{:line,nil},
{:function,nil},
{:aliases,nil},
{:context,nil},
{:requires,nil},
{:macros,nil}
]
end
@doc """
Returns the current module name.
"""
def module(record), do: elem(record, 2)
@doc """
Returns the current file name as a binary.
"""
def file(record), do: elem(record, 3)
@doc """
Returns the current line as an integer.
"""
def line(record), do: elem(record, 4)
@doc """
Returns a tuple as { Atom, Integer }, where the first element
is the function name and the seconds its arity. Returns `nil`
if not inside a function.
"""
def function(record), do: elem(record, 5)
@doc """
Returns a list of two item tuples, where the first
item is the aliased name and the second the actual name.
"""
def aliases(record), do: elem(record, 6)
@doc """
Returns wether the compilation environment is currently
inside a guard.
"""
def in_guard?(record), do: elem(record, 7) == :guard
@doc """
Returns wether the compilation environment is currently
inside a match clause.
"""
def in_match?(record), do: elem(record, 7) == :assign
@doc """
Returns the list of required modules.
"""
def requires(record), do: elem(record, 8)
@doc """
Returns a list of macros imported from each module.
"""
def macros(record), do: elem(record, 9)
@doc """
Returns a keywords list containing the file and line
information as keys.
"""
def location(record) do
[file: file(record), line: line(record)]
end
end | 24.966667 | 64 | 0.655541 |
f73851d85842b90656d853f067568a03161e83ba | 285 | ex | Elixir | lib/asls/assertion.ex | Shopify/asls | 2c0f3c68e380cfeaa75f710b367a2f67ae09957a | [
"MIT"
] | 23 | 2021-02-05T01:50:07.000Z | 2021-12-10T13:24:41.000Z | lib/asls/assertion.ex | saulecabrera/asls | 2c0f3c68e380cfeaa75f710b367a2f67ae09957a | [
"MIT"
] | 5 | 2020-07-20T00:33:07.000Z | 2020-09-30T16:09:47.000Z | lib/asls/assertion.ex | saulecabrera/asls | 2c0f3c68e380cfeaa75f710b367a2f67ae09957a | [
"MIT"
] | 1 | 2020-10-24T09:02:22.000Z | 2020-10-24T09:02:22.000Z | defmodule AssemblyScriptLS.Assertion do
@type t :: %__MODULE__{
contents: String.t
}
@keys [:contents]
@enforce_keys @keys
defstruct @keys
@spec new(String.t) :: __MODULE__.t
def new(contents) do
struct!(__MODULE__, [
contents: contents
])
end
end
| 15.833333 | 39 | 0.652632 |
f7387c958edfadb93489072857d4c6634f760fa6 | 4,841 | exs | Elixir | lib/ex_unit/test/ex_unit/filters_test.exs | davidsulc/elixir | dd4fd6ab742acd75862e34e26dbdb86e0cf6453f | [
"Apache-2.0"
] | null | null | null | lib/ex_unit/test/ex_unit/filters_test.exs | davidsulc/elixir | dd4fd6ab742acd75862e34e26dbdb86e0cf6453f | [
"Apache-2.0"
] | null | null | null | lib/ex_unit/test/ex_unit/filters_test.exs | davidsulc/elixir | dd4fd6ab742acd75862e34e26dbdb86e0cf6453f | [
"Apache-2.0"
] | null | null | null | Code.require_file "../test_helper.exs", __DIR__
defmodule ExUnit.FiltersTest do
use ExUnit.Case, async: true
doctest ExUnit.Filters
test "evaluating filters" do
assert ExUnit.Filters.eval([], [:os], %{}, []) == :ok
assert ExUnit.Filters.eval([], [os: :win], %{os: :unix}, []) == :ok
assert ExUnit.Filters.eval([], [:os], %{os: :unix}, []) == {:error, "due to os filter"}
assert ExUnit.Filters.eval([], [os: :unix], %{os: :unix}, []) == {:error, "due to os filter"}
assert ExUnit.Filters.eval([os: :win], [], %{}, []) == :ok
assert ExUnit.Filters.eval([os: :win], [], %{os: :unix}, []) == :ok
assert ExUnit.Filters.eval([os: :win], [:os], %{}, []) == :ok
assert ExUnit.Filters.eval([os: :win], [:os], %{os: :win}, []) == :ok
assert ExUnit.Filters.eval([os: :win, os: :unix], [:os], %{os: :win}, []) == :ok
end
test "evaluating filters with skip" do
assert ExUnit.Filters.eval([], [], %{}, []) == :ok
assert ExUnit.Filters.eval([], [], %{skip: true}, []) == {:error, "due to skip tag"}
assert ExUnit.Filters.eval([], [], %{skip: "skipped"}, []) == {:error, "skipped"}
assert ExUnit.Filters.eval([], [:os], %{skip: "skipped"}, []) == {:error, "skipped"}
assert ExUnit.Filters.eval([:skip], [], %{skip: true}, []) == :ok
assert ExUnit.Filters.eval([:skip], [], %{skip: "skipped"}, []) == :ok
end
test "evaluating filters matches integers" do
assert ExUnit.Filters.eval([int: "1"], [], %{int: 1}, []) == :ok
assert ExUnit.Filters.eval([int: "1"], [int: 5], %{int: 1}, []) == :ok
assert ExUnit.Filters.eval([int: "1"], [:int], %{int: 1}, []) == :ok
end
test "evaluating filter matches atoms" do
assert ExUnit.Filters.eval([os: "win"], [], %{os: :win}, []) == :ok
assert ExUnit.Filters.eval([os: "win"], [os: :unix], %{os: :win}, []) == :ok
assert ExUnit.Filters.eval([os: "win"], [:os], %{os: :win}, []) == :ok
assert ExUnit.Filters.eval([module: "Foo"], [:os], %{module: Foo}, []) == :ok
end
test "evaluating filter matches regexes" do
assert ExUnit.Filters.eval([os: ~r"win"], [], %{os: :win}, []) == :ok
assert ExUnit.Filters.eval([os: ~r"mac"], [os: :unix], %{os: :unix}, []) == {:error, "due to os filter"}
end
test "evaluating filter uses special rules for line" do
tests = [
%ExUnit.Test{tags: %{line: 3, describe_line: 2}},
%ExUnit.Test{tags: %{line: 5, describe_line: nil}},
%ExUnit.Test{tags: %{line: 8, describe_line: 7}},
%ExUnit.Test{tags: %{line: 10, describe_line: 7}},
%ExUnit.Test{tags: %{line: 13, describe_line: 12}},
]
assert ExUnit.Filters.eval([line: "3"], [:line], %{line: 3, describe_line: 2}, tests) == :ok
assert ExUnit.Filters.eval([line: "4"], [:line], %{line: 3, describe_line: 2}, tests) == :ok
assert ExUnit.Filters.eval([line: "5"], [:line], %{line: 5, describe_line: nil}, tests) == :ok
assert ExUnit.Filters.eval([line: "6"], [:line], %{line: 5, describe_line: nil}, tests) == :ok
assert ExUnit.Filters.eval([line: "2"], [:line], %{line: 3, describe_line: 2}, tests) == :ok
assert ExUnit.Filters.eval([line: "7"], [:line], %{line: 8, describe_line: 7}, tests) == :ok
assert ExUnit.Filters.eval([line: "7"], [:line], %{line: 10, describe_line: 7}, tests) == :ok
assert ExUnit.Filters.eval([line: "1"], [:line], %{line: 3, describe_line: 2}, tests) == {:error, "due to line filter"}
assert ExUnit.Filters.eval([line: "7"], [:line], %{line: 3, describe_line: 2}, tests) == {:error, "due to line filter"}
assert ExUnit.Filters.eval([line: "7"], [:line], %{line: 5, describe_line: nil}, tests) == {:error, "due to line filter"}
end
test "parsing filters" do
assert ExUnit.Filters.parse(["run"]) == [:run]
assert ExUnit.Filters.parse(["run:true"]) == [run: "true"]
assert ExUnit.Filters.parse(["run:test"]) == [run: "test"]
assert ExUnit.Filters.parse(["line:9"]) == [line: "9"]
end
test "file paths with line numbers" do
assert ExUnit.Filters.parse_path("test/some/path.exs:123") ==
{"test/some/path.exs", [exclude: [:test], include: [line: "123"]]}
assert ExUnit.Filters.parse_path("test/some/path.exs") ==
{"test/some/path.exs", []}
assert ExUnit.Filters.parse_path("test/some/path.exs:123notreallyalinenumber123") ==
{"test/some/path.exs:123notreallyalinenumber123", []}
assert ExUnit.Filters.parse_path("C:\\some\\path.exs:123") ==
{"C:\\some\\path.exs", [exclude: [:test], include: [line: "123"]]}
assert ExUnit.Filters.parse_path("C:\\some\\path.exs") ==
{"C:\\some\\path.exs", []}
assert ExUnit.Filters.parse_path("C:\\some\\path.exs:123notreallyalinenumber123") ==
{"C:\\some\\path.exs:123notreallyalinenumber123", []}
end
end
| 49.907216 | 125 | 0.576121 |
f7389fe2a0746e930d27b6aa1401483909514d04 | 1,683 | ex | Elixir | lib/web/views/api/game_view.ex | sb8244/grapevine | effaaa01294d30114090c20f9cc40b8665d834f2 | [
"MIT"
] | 107 | 2018-10-05T18:20:32.000Z | 2022-02-28T04:02:50.000Z | lib/web/views/api/game_view.ex | sb8244/grapevine | effaaa01294d30114090c20f9cc40b8665d834f2 | [
"MIT"
] | 33 | 2018-10-05T14:11:18.000Z | 2022-02-10T22:19:18.000Z | lib/web/views/api/game_view.ex | sb8244/grapevine | effaaa01294d30114090c20f9cc40b8665d834f2 | [
"MIT"
] | 18 | 2019-02-03T03:08:20.000Z | 2021-12-28T04:29:36.000Z | defmodule Web.Api.GameView do
use Web, :view
alias Web.ConnectionView
def render("index.json", %{games: games, pagination: pagination, filter: filter}) do
games
|> index(pagination, filter)
|> Representer.transform("json")
end
def render("show.json", %{game: game}) do
game
|> show()
|> Representer.transform("json")
end
def render("game.json", %{game: game}) do
Map.take(game, [
:name,
:short_name,
:tagline,
:description,
:homepage_url,
:discord_invite_url
])
end
def render("online.json", %{games: games}) do
%{
collection: render_many(games, __MODULE__, "presence.json")
}
end
def render("presence.json", %{game: game}) do
%{
game: Map.take(game.game, [:name, :homepage_url]),
players: game.players
}
end
defp item(game) do
connections = render_many(game.connections, ConnectionView, "show.json", as: :connection)
%Representer.Item{
data: render("game.json", %{game: game}),
embedded: %{connections: connections}
}
end
defp show(game) do
game
|> item()
|> Representer.maybe_link(game.enable_web_client, %Representer.Link{
rel: "https://grapevine.haus/client",
href: Routes.play_url(Web.Endpoint, :show, game.short_name)
})
end
defp index(games, pagination, filter) do
games = Enum.map(games, &show/1)
self_link = Routes.game_url(Web.Endpoint, :index, filter)
%Representer.Collection{
items: games,
pagination: Representer.Pagination.new(self_link, pagination),
links: [
%Representer.Link{rel: "self", href: self_link}
]
}
end
end
| 23.054795 | 93 | 0.623886 |
f738b5b626afdd4d222a4aebfd927c5ee9f3e864 | 353 | exs | Elixir | priv/repo/seeds.exs | TDogVoid/health_demo | 4e9fbf79c32145cf563cdbdb3ea4a0f594a87053 | [
"MIT"
] | null | null | null | priv/repo/seeds.exs | TDogVoid/health_demo | 4e9fbf79c32145cf563cdbdb3ea4a0f594a87053 | [
"MIT"
] | 2 | 2021-03-10T04:15:17.000Z | 2021-05-10T23:54:35.000Z | priv/repo/seeds.exs | TDogVoid/health_demo | 4e9fbf79c32145cf563cdbdb3ea4a0f594a87053 | [
"MIT"
] | null | null | null | # Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# Health.Repo.insert!(%Health.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
#
#
| 25.214286 | 61 | 0.696884 |
f7391967bac4876cb6b4a35cc7e7b10532a1cade | 1,839 | exs | Elixir | installer/templates/phx_single/mix.exs | raspo/phoenix | 438b74255e7a4d68b4eaf1a295d0fcd201c71421 | [
"MIT"
] | null | null | null | installer/templates/phx_single/mix.exs | raspo/phoenix | 438b74255e7a4d68b4eaf1a295d0fcd201c71421 | [
"MIT"
] | null | null | null | installer/templates/phx_single/mix.exs | raspo/phoenix | 438b74255e7a4d68b4eaf1a295d0fcd201c71421 | [
"MIT"
] | null | null | null | defmodule <%= app_module %>.Mixfile do
use Mix.Project
def project do
[app: :<%= app_name %>,
version: "0.0.1",<%= if in_umbrella do %>
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",<% end %>
elixir: "~> 1.4",
elixirc_paths: elixirc_paths(Mix.env),
compilers: [:phoenix, :gettext] ++ Mix.compilers,
start_permanent: Mix.env == :prod,<%= if ecto do %>
aliases: aliases(),<% end %>
deps: deps()]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[mod: {<%= app_module %>.Application, []},
extra_applications: [:logger, :runtime_tools]]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[<%= phoenix_dep %>,
{:phoenix_pubsub, "~> 1.0"},<%= if ecto do %>
{:phoenix_ecto, "~> 3.2"},
{<%= inspect adapter_app %>, ">= 0.0.0"},<% end %><%= if html do %>
{:phoenix_html, "~> 2.6"},
{:phoenix_live_reload, "~> 1.0", only: :dev},<% end %>
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"}]
end<%= if ecto do %>
# Aliases are shortcuts or tasks specific to the current project.
# For example, to create, migrate and run the seeds file at once:
#
# $ mix ecto.setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
["ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
"ecto.reset": ["ecto.drop", "ecto.setup"],
"test": ["ecto.create --quiet", "ecto.migrate", "test"]]
end<% end %>
end
| 32.263158 | 78 | 0.584557 |
f73920ed06e0455ed5957c5f0c39397f2ee9b143 | 1,675 | exs | Elixir | config/config.exs | mateuscosta86/blog | 3ee4596bfbd0f0681041cb0d50ab4baccc7b571e | [
"MIT"
] | null | null | null | config/config.exs | mateuscosta86/blog | 3ee4596bfbd0f0681041cb0d50ab4baccc7b571e | [
"MIT"
] | 3 | 2021-12-30T20:43:08.000Z | 2021-12-31T19:51:04.000Z | config/config.exs | mateuscosta86/blog | 3ee4596bfbd0f0681041cb0d50ab4baccc7b571e | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
# General application configuration
import Config
config :blog,
ecto_repos: [Blog.Repo]
# Configures the endpoint
config :blog, BlogWeb.Endpoint,
url: [host: "localhost"],
render_errors: [view: BlogWeb.ErrorView, accepts: ~w(html json), layout: false],
pubsub_server: Blog.PubSub,
live_view: [signing_salt: "3Rcv1BId"]
# Configures the mailer
#
# By default it uses the "Local" adapter which stores the emails
# locally. You can see the emails in your browser, at "/dev/mailbox".
#
# For production it's recommended to configure a different adapter
# at the `config/runtime.exs`.
config :blog, Blog.Mailer, adapter: Swoosh.Adapters.Local
# Swoosh API client is needed for adapters other than SMTP.
config :swoosh, :api_client, false
# Configure esbuild (the version is required)
config :esbuild,
version: "0.12.18",
default: [
args:
~w(js/app.js --bundle --target=es2016 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*),
cd: Path.expand("../assets", __DIR__),
env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{config_env()}.exs"
| 31.603774 | 117 | 0.728955 |
f7395cccbc8367941aa9fad8bad46990d091a298 | 81 | exs | Elixir | test/ex_bin/formatter_test.exs | zcking/ex_bin | b32d29345ee4888e5d13c2afd20dca23d53be616 | [
"MIT"
] | 1 | 2020-05-12T10:46:27.000Z | 2020-05-12T10:46:27.000Z | test/ex_bin/formatter_test.exs | zcking/ex_bin | b32d29345ee4888e5d13c2afd20dca23d53be616 | [
"MIT"
] | null | null | null | test/ex_bin/formatter_test.exs | zcking/ex_bin | b32d29345ee4888e5d13c2afd20dca23d53be616 | [
"MIT"
] | null | null | null | defmodule ExBin.FormatterTest do
use ExUnit.Case
doctest ExBin.Formatter
end
| 16.2 | 32 | 0.814815 |
f7396b33e5cdee2ee56be0f96b0a24f045ad9791 | 2,580 | ex | Elixir | lib/2020/day21.ex | hallski/adventofcode | 03efb385688e8072b0b44d35012297833498f799 | [
"MIT"
] | null | null | null | lib/2020/day21.ex | hallski/adventofcode | 03efb385688e8072b0b44d35012297833498f799 | [
"MIT"
] | null | null | null | lib/2020/day21.ex | hallski/adventofcode | 03efb385688e8072b0b44d35012297833498f799 | [
"MIT"
] | null | null | null | defmodule AdventOfCode.Y2020.Day21 do
def run() do
parsed =
AdventOfCode.Helpers.Data.read_from_file_no_split("2020/day21.txt")
|> parse()
{solve1(parsed), solve2(parsed)}
end
def solve1(parsed) do
safe_ingredients = allergen_free(parsed)
parsed
|> Stream.flat_map(fn {_, ingredients} -> ingredients end)
|> Stream.filter(&MapSet.member?(safe_ingredients, &1))
|> Enum.count()
end
def solve2(parsed) do
parsed
|> allergen_to_possible_ingredients()
|> allergens_to_certain_ingredient()
|> Enum.sort(fn a, b -> elem(a, 0) < elem(b, 0) end)
|> Enum.map(&elem(&1, 1))
|> Enum.join(",")
end
def allergen_free(parsed) do
all_ingredients =
parsed |> Enum.reduce(MapSet.new(), fn {_, i}, acc -> MapSet.union(i, acc) end)
parsed
|> allergen_to_possible_ingredients()
|> Enum.reduce(all_ingredients, fn {_, ingredients}, acc ->
MapSet.difference(acc, ingredients)
end)
end
def dish_to_allergen_map({allergens, ingredients}) do
allergens
|> Enum.map(fn allergen -> {allergen, ingredients} end)
|> Map.new()
end
def allergen_to_possible_ingredients(lines) do
lines
|> Enum.map(&dish_to_allergen_map/1)
|> Enum.reduce(fn map, acc ->
Map.merge(map, acc, fn _, v1, v2 -> MapSet.intersection(v1, v2) end)
end)
end
def allergens_to_certain_ingredient(unmapped) do
{[], Enum.to_list(unmapped)}
|> Stream.iterate(&extract_allergen_matches/1)
|> Stream.take_while(&more_allergens_to_process?/1)
|> Stream.drop(1)
|> Stream.flat_map(fn {matches, _} ->
matches |> Enum.map(fn {k, v} -> {k, Enum.take(v, 1) |> hd} end)
end)
|> Map.new()
end
def more_allergens_to_process?(progress) do
progress
|> Tuple.to_list()
|> Enum.all?(&Enum.empty?/1)
|> Kernel.not()
end
def extract_allergen_matches({last_matches, unprocessed}) do
matches =
last_matches |> Enum.reduce(MapSet.new(), fn {_, v}, acc -> MapSet.union(acc, v) end)
unprocessed
|> Enum.map(fn {key, ingredients} -> {key, MapSet.difference(ingredients, matches)} end)
|> Enum.split_with(fn {_, ingredients} -> MapSet.size(ingredients) == 1 end)
end
def parse(data) do
data
|> String.split("\n", trim: true)
|> Enum.map(&parse_line/1)
end
def parse_line(line) do
line
|> String.replace(~r/[\(\),]/, "")
|> String.split("contains", trim: true)
|> Enum.map(&String.split/1)
|> (fn [ingredients, allergens] -> {allergens, MapSet.new(ingredients)} end).()
end
end
| 27.446809 | 92 | 0.634496 |
f73985450426b45a6e9721361414bd395f09317c | 2,117 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/placement_strategies_list_response.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/placement_strategies_list_response.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/placement_strategies_list_response.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DFAReporting.V34.Model.PlacementStrategiesListResponse do
@moduledoc """
Placement Strategy List Response
## Attributes
* `kind` (*type:* `String.t`, *default:* `dfareporting#placementStrategiesListResponse`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#placementStrategiesListResponse".
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Pagination token to be used for the next list operation.
* `placementStrategies` (*type:* `list(GoogleApi.DFAReporting.V34.Model.PlacementStrategy.t)`, *default:* `nil`) - Placement strategy collection.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kind => String.t(),
:nextPageToken => String.t(),
:placementStrategies => list(GoogleApi.DFAReporting.V34.Model.PlacementStrategy.t())
}
field(:kind)
field(:nextPageToken)
field(:placementStrategies, as: GoogleApi.DFAReporting.V34.Model.PlacementStrategy, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V34.Model.PlacementStrategiesListResponse do
def decode(value, options) do
GoogleApi.DFAReporting.V34.Model.PlacementStrategiesListResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V34.Model.PlacementStrategiesListResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 39.943396 | 208 | 0.749646 |
f73999e7e615287e646d044a526e49d8be413065 | 1,040 | ex | Elixir | test/support/conn_case.ex | togmund/hexen | 5166ba445af592516beae48ccfcb76efc3fde166 | [
"Unlicense"
] | 2 | 2019-12-28T21:31:43.000Z | 2019-12-30T01:03:28.000Z | test/support/conn_case.ex | togmund/hexen | 5166ba445af592516beae48ccfcb76efc3fde166 | [
"Unlicense"
] | 4 | 2019-12-23T23:51:30.000Z | 2021-05-10T22:24:18.000Z | test/support/conn_case.ex | togmund/hexen | 5166ba445af592516beae48ccfcb76efc3fde166 | [
"Unlicense"
] | 1 | 2020-01-17T20:19:14.000Z | 2020-01-17T20:19:14.000Z | defmodule HexenWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
use Phoenix.ConnTest
alias HexenWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint HexenWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Hexen.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Hexen.Repo, {:shared, self()})
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 26.666667 | 67 | 0.715385 |
f739ab6778b646a37bd03444980aeca40dd62b29 | 3,440 | ex | Elixir | apps/neoscan_sync/lib/neoscan_sync/syncer.ex | vincentgeneste/neo-scan | 4a654575331eeb3eb12d4fd61696a7bd6dbca3ce | [
"MIT"
] | null | null | null | apps/neoscan_sync/lib/neoscan_sync/syncer.ex | vincentgeneste/neo-scan | 4a654575331eeb3eb12d4fd61696a7bd6dbca3ce | [
"MIT"
] | null | null | null | apps/neoscan_sync/lib/neoscan_sync/syncer.ex | vincentgeneste/neo-scan | 4a654575331eeb3eb12d4fd61696a7bd6dbca3ce | [
"MIT"
] | null | null | null | defmodule NeoscanSync.Syncer do
alias Ecto.ConstraintError
alias NeoscanSync.Converter
alias Neoscan.Repo
alias Neoscan.Blocks
alias NeoscanSync.TokenSyncer
use GenServer
require Logger
@parallelism 16
@update_interval 1_000
@block_chunk_size 500
def start_link do
GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
end
@impl true
def init(:ok) do
missing_block_indexes = Blocks.get_missing_block_indexes()
Logger.warn("found #{Enum.count(missing_block_indexes)} missing blocks")
Process.send_after(self(), :sync, 0)
{:ok, missing_block_indexes}
end
def get_available_block_index_range do
max_index_in_db = Blocks.get_max_index() + 1
max_index_available = NeoscanNode.get_last_block_index()
if max_index_in_db > max_index_available do
[]
else
Enum.to_list(max_index_in_db..max_index_available)
end
end
@impl true
def handle_info(:sync, missing_block_indexes) do
Process.send_after(self(), :sync, @update_interval)
available_block_index_range = get_available_block_index_range()
indexes = missing_block_indexes ++ Enum.take(available_block_index_range, @block_chunk_size)
sync_indexes(indexes)
{:noreply, []}
end
def download_block(index) do
try do
block_raw = NeoscanNode.get_block_with_transfers(index)
^index = block_raw.index
Converter.convert_block(block_raw)
catch
error ->
Logger.error("error while downloading block #{inspect({index, error})}")
download_block(index)
error, reason ->
Logger.error("error while downloading block #{inspect({index, error, reason})}")
download_block(index)
end
end
def insert_block(block) do
try do
Enum.map(block.transactions, fn %{transfers: transfers} ->
Enum.map(transfers, fn %{contract: contract} ->
TokenSyncer.retrieve_contract(block.index, contract)
end)
end)
Repo.transaction(
fn ->
Repo.insert!(block, timeout: :infinity, returning: false)
end,
timeout: :infinity
)
:ok
catch
error ->
Logger.error("error while loading block #{inspect({block.index, error})}")
insert_block(block)
:error, %ConstraintError{constraint: "blocks_pkey"} ->
Logger.error("block already #{block.index} in the database")
error, reason ->
Logger.error("error while loading block #{inspect({block.index, error, reason})}")
insert_block(block)
end
end
def sync_indexes(indexes) do
concurrency = System.schedulers_online() * @parallelism
indexes
|> Task.async_stream(
fn n ->
now = Time.utc_now()
block = download_block(n)
Monitor.incr(:download_blocks_time, Time.diff(Time.utc_now(), now, :microseconds))
Monitor.incr(:download_blocks_count, 1)
block
end,
max_concurrency: concurrency,
timeout: :infinity,
ordered: false
)
|> Task.async_stream(
fn {:ok, block} ->
now = Time.utc_now()
insert_block(block)
Monitor.incr(:insert_blocks_time, Time.diff(Time.utc_now(), now, :microseconds))
Monitor.incr(:insert_blocks_count, 1)
Monitor.incr(:insert_transactions_count, block.tx_count)
end,
max_concurrency: System.schedulers_online(),
timeout: :infinity
)
|> Stream.run()
end
end
| 27.301587 | 96 | 0.667151 |
f739c1ef24a3923593a5552d44eb89ae47a67deb | 4 | ex | Elixir | testData/org/elixir_lang/parser_definition/literal_regex_line_parsing_test_case/Minimal.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/literal_regex_line_parsing_test_case/Minimal.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/literal_regex_line_parsing_test_case/Minimal.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 145 | 2015-01-15T11:37:16.000Z | 2021-12-22T05:51:02.000Z | ~R{} | 4 | 4 | 0.25 |
f739e02792296f4b9fd4afa9e83be2c0af321568 | 991 | exs | Elixir | mix.exs | michalmuskala/debounce | 1b6f8afab533fda89f26063a7276dce7a90a2c31 | [
"Apache-2.0"
] | 20 | 2017-01-11T21:05:25.000Z | 2021-06-25T14:05:49.000Z | mix.exs | michalmuskala/debounce | 1b6f8afab533fda89f26063a7276dce7a90a2c31 | [
"Apache-2.0"
] | 1 | 2020-09-18T11:12:28.000Z | 2020-09-18T19:17:30.000Z | mix.exs | michalmuskala/debounce | 1b6f8afab533fda89f26063a7276dce7a90a2c31 | [
"Apache-2.0"
] | 1 | 2019-02-28T21:24:52.000Z | 2019-02-28T21:24:52.000Z | defmodule Debounce.Mixfile do
use Mix.Project
@version "1.0.0"
def project do
[
app: :debounce,
version: @version,
elixir: "~> 1.6",
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
deps: deps(),
description: "A process-based debouncer for Elixir",
package: package(),
docs: docs()
]
end
def application do
[extra_applications: [], mod: {Debounce.Application, []}]
end
defp deps do
[
{:ex_doc, "~> 0.14", only: :dev, runtime: false},
{:dialyxir, "~> 1.0", only: [:dev, :test], runtime: false}
]
end
defp package do
[
maintainers: ["Michał Muskała"],
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/michalmuskala/debounce"}
]
end
defp docs do
[
main: "Debounce",
name: "Debounce",
source_ref: "v#{@version}",
source_url: "https://github.com/michalmuskala/debounce"
]
end
end
| 20.645833 | 71 | 0.561049 |
f739e133bea683504c3e6733dbbee1412a2f07c1 | 7,345 | ex | Elixir | lib/menu.ex | mpotra/ex_sni | ff2187da7208348a315eda03fe086a3ce5ded27c | [
"MIT"
] | null | null | null | lib/menu.ex | mpotra/ex_sni | ff2187da7208348a315eda03fe086a3ce5ded27c | [
"MIT"
] | null | null | null | lib/menu.ex | mpotra/ex_sni | ff2187da7208348a315eda03fe086a3ce5ded27c | [
"MIT"
] | null | null | null | defmodule ExSni.Menu do
require Logger
alias ExSni.Menu.Item
alias ExSni.Ref
defstruct __ref__: %Ref{path: "/MenuBar", interface: "com.canonical.dbusmenu"},
version: 1,
text_direction: "ltr",
icon_theme_path: [""],
status: "normal",
root: nil,
last_id: 0,
callbacks: []
@type fn_callback() :: (... -> any())
@type callback() :: {atom(), fn_callback()}
@type t() :: %__MODULE__{
__ref__: Ref.t() | nil,
version: integer(),
text_direction: String.t(),
icon_theme_path: list(String.t()),
status: String.t(),
root: Item.t(),
last_id: non_neg_integer(),
callbacks: list(callback())
}
@dbus_menu_item_type {:struct, [:int32, {:dict, :string, :variant}, {:array, :variant}]}
@spec get_layout(t(), integer(), list(String.t())) ::
{:ok, list(), list()} | {:error, binary(), binary()}
def get_layout(%__MODULE__{} = menu, depth, properties) do
get_layout(menu, 0, depth, properties)
end
@spec get_layout(t(), non_neg_integer(), integer(), list(String.t())) ::
{:ok, list(), list()} | {:error, binary(), binary()}
def get_layout(%__MODULE__{root: %Item{} = root, version: version}, 0, depth, properties) do
{_, _, root_layout} = Item.get_layout(root, depth, properties)
{:ok, [:uint32, @dbus_menu_item_type], [version, root_layout]}
end
def get_layout(%__MODULE__{root: %Item{children: children}}, parentId, depth, properties) do
case find_child(children, parentId) do
%Item{} = child ->
{_, _, child_layout} = Item.get_layout(child, depth, properties)
{:ok, [:uint32, @dbus_menu_item_type], [parentId, child_layout]}
_ ->
{:error, "org.freedesktop.DBus.Error.Failed", "No such menu item"}
end
end
def get_layout(%__MODULE__{root: _, version: version}, parentId, _, _) do
{:ok, [:uint32, @dbus_menu_item_type], [version, [parentId, [], []]]}
end
def get_layout(_, _, _, _) do
{:error, "org.freedesktop.DBus.Error.Failed", "No such menu item"}
end
def get_group_properties(%__MODULE__{} = menu, :all, properties) do
ids =
menu
|> get_children()
|> Enum.map(&Map.get(&1, :id))
get_group_properties(menu, ids, properties)
end
def get_group_properties(%__MODULE__{} = menu, ids, properties) do
ids
|> Enum.map(&find_item(menu, &1))
|> Enum.reject(&(&1 == nil))
|> Enum.map(fn item ->
values = ExSni.DbusProtocol.get_properties(item, properties)
[item.id, values]
end)
end
def get_group_properties(_, _, _) do
[]
end
def get_group_properties_per_item(%__MODULE__{} = menu, mapping) do
Enum.reduce(mapping, [], fn {id, properties}, acc ->
case find_item(menu, id) do
nil ->
acc
item ->
values = ExSni.DbusProtocol.get_properties(item, properties)
[id, values]
end
end)
end
def get_last_id(%__MODULE__{last_id: last_id}) do
last_id
end
def get_last_id(_) do
0
end
defp get_children(%__MODULE__{root: %{} = root}) do
get_children(root)
end
defp get_children(%{children: []}) do
[]
end
defp get_children(%{children: children}) when is_list(children) do
Enum.reduce(children, [], fn child, acc ->
children = get_children(child)
[child | children] ++ acc
end)
end
defp get_children(_) do
[]
end
def find_item(%__MODULE__{root: %Item{} = root}, id) do
Item.find_item(root, id)
end
def find_item(_, _) do
nil
end
@spec onAboutToShow(t(), id :: non_neg_integer()) :: boolean()
def onAboutToShow(%__MODULE__{callbacks: callbacks}, 0) do
run_aboutToShow(callbacks)
end
def onAboutToShow(%__MODULE__{} = menu, id) do
case find_item(menu, id) do
%Item{callbacks: callbacks} ->
run_aboutToShow(callbacks)
_ ->
Logger.debug("Menu.onEvent:: Failed to find menu item by id [#{id}] (AboutToShow})")
false
end
end
def onAboutToShow(nil, _) do
false
end
@spec onEvent(
t(),
eventId :: String.t(),
menuId :: non_neg_integer(),
data :: any(),
timestamp :: any()
) :: any()
def onEvent(%__MODULE__{callbacks: callbacks}, eventId, 0, data, timestamp) do
run_events(callbacks, eventId, data, timestamp)
end
def onEvent(%__MODULE__{} = menu, eventId, id, data, timestamp) do
case find_item(menu, id) do
%Item{callbacks: callbacks} ->
run_events(callbacks, eventId, data, timestamp)
_ ->
Logger.debug(
"Menu.onEvent:: Failed to find menu item by id [#{id}] (eventId: #{eventId})"
)
nil
end
end
def onEvent(nil, _, _, _, _) do
nil
end
defp run_events(callbacks, eventId, data, timestamp) do
callbacks
|> get_callbacks(eventId)
|> Enum.reduce(nil, fn func, _ ->
try do
func.(data, timestamp)
rescue
_ -> nil
end
end)
end
defp run_aboutToShow(callbacks) do
callbacks
|> get_callbacks(:show)
|> Enum.reduce(false, fn func, acc ->
try do
func.()
rescue
_ -> acc
else
v -> v || acc
end
end)
end
defp get_callbacks([], _eventId) do
[]
end
defp get_callbacks(callbacks, eventId) do
callbacks
# |> Enum.filter(&is_tuple/1)
# |> Enum.filter(&(elem(&1, 0) == eventId))
|> Enum.filter(&has_event_id(&1, eventId))
|> Enum.map(&elem(&1, 1))
|> Enum.filter(&is_function(&1))
end
defp has_event_id(item, eventId) when is_tuple(item) do
elem(item, 0) == eventId
end
defp has_event_id(_, _) do
false
end
@spec find_child(list(Item.t()), non_neg_integer()) :: nil | Item.t()
defp find_child([], _) do
nil
end
defp find_child([%Item{id: id} = item | _], id) do
item
end
defp find_child([_ | items], id) do
find_child(items, id)
end
end
defimpl ExSni.DbusProtocol, for: ExSni.Menu do
def get_property(%{version: version}, "Version") do
{:ok, version}
end
def get_property(%{text_direction: text_direction}, "TextDirection") do
{:ok, text_direction}
end
def get_property(%{status: status}, "Status") do
{:ok, status}
end
def get_property(%{icon_theme_path: icon_theme_path}, "IconThemePath")
when is_binary(icon_theme_path) do
{:ok, [icon_theme_path]}
end
def get_property(%{icon_theme_path: icon_theme_path}, "IconThemePath")
when is_list(icon_theme_path) do
{:ok, icon_theme_path}
end
def get_property(_, _) do
{:error, "org.freedesktop.DBus.Error.UnknownProperty", "Invalid property"}
end
def get_property(item, property, _) do
get_property(item, property)
end
def get_properties(item, []) do
get_properties(item, [
"Version",
"TextDirection",
"Status",
"IconThemePath"
])
end
def get_properties(item, properties) do
get_properties(item, properties, [])
end
def get_properties(item, properties, options) do
properties
|> Enum.reduce([], fn property, acc ->
case get_property(item, property, options) do
{:ok, value} -> [{property, value} | acc]
_ -> acc
end
end)
end
end
| 24.647651 | 94 | 0.602451 |
f73a2f9c619b37411a9a2859a94a8912630f868e | 1,086 | exs | Elixir | hello_phoenix/mix.exs | kkirstein/phoenix-tutorial | a2a66a554cf6eb4f6f36919795eed51d4d44b509 | [
"MIT"
] | null | null | null | hello_phoenix/mix.exs | kkirstein/phoenix-tutorial | a2a66a554cf6eb4f6f36919795eed51d4d44b509 | [
"MIT"
] | null | null | null | hello_phoenix/mix.exs | kkirstein/phoenix-tutorial | a2a66a554cf6eb4f6f36919795eed51d4d44b509 | [
"MIT"
] | null | null | null | defmodule HelloPhoenix.Mixfile do
use Mix.Project
def project do
[app: :hello_phoenix,
version: "0.0.1",
elixir: "~> 1.0",
elixirc_paths: elixirc_paths(Mix.env),
compilers: [:phoenix] ++ Mix.compilers,
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps]
end
# Configuration for the OTP application
#
# Type `mix help compile.app` for more information
def application do
[mod: {HelloPhoenix, []},
applications: [:phoenix, :phoenix_html, :cowboy, :logger,
:phoenix_ecto, :postgrex]]
end
# Specifies which paths to compile per environment
defp elixirc_paths(:test), do: ["lib", "web", "test/support"]
defp elixirc_paths(_), do: ["lib", "web"]
# Specifies your project dependencies
#
# Type `mix help deps` for examples and options
defp deps do
[{:phoenix, "~> 1.0.0"},
{:phoenix_ecto, "~> 1.1"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.1"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:cowboy, "~> 1.0"}]
end
end
| 27.15 | 63 | 0.603131 |
f73a4f76a330fe86c03f5255333a9bb949d52395 | 6,135 | exs | Elixir | test/zuul_plug_test.exs | dottorblaster/zuul | 35fa6861e29bc4ad48467bcd10d0cee33c0f8cd6 | [
"MIT"
] | null | null | null | test/zuul_plug_test.exs | dottorblaster/zuul | 35fa6861e29bc4ad48467bcd10d0cee33c0f8cd6 | [
"MIT"
] | 2 | 2020-04-22T04:40:18.000Z | 2020-06-15T07:24:12.000Z | test/zuul_plug_test.exs | dottorblaster/zuul | 35fa6861e29bc4ad48467bcd10d0cee33c0f8cd6 | [
"MIT"
] | null | null | null | defmodule Zuul.PlugTest do
@moduledoc """
Tests for `Zuul.Plug`.
"""
use ExUnit.Case
doctest Zuul.Plug
test "connection is OK" do
conn_to_test = get_fixture_ok()
assert Zuul.Plug.call(conn_to_test, key_file: "./test/fixtures/api_keys.txt") === conn_to_test
end
test "connection is KO" do
conn_to_test = get_fixture_not_ok()
assert_raise Zuul.KeyError, fn ->
Zuul.Plug.call(conn_to_test, key_file: "./test/fixtures/api_keys.txt")
end
end
test "connection is without authorization header" do
conn_to_test = get_fixture_without_key()
assert_raise Zuul.MissingAuthorizedHeaderError, fn ->
Zuul.Plug.call(conn_to_test, key_file: "./test/fixtures/api_keys.txt")
end
end
test "protect only some methods upon proper option declaration" do
wrong_get_request = get_fixture_without_key()
passing_options_request = Map.replace!(get_fixture_without_key(), :method, "OPTIONS")
plug_opts = [key_file: "./test/fixtures/api_keys.txt", protect_methods: ["GET", "POST"]]
assert_raise Zuul.MissingAuthorizedHeaderError, fn ->
Zuul.Plug.call(wrong_get_request, plug_opts)
end
assert Zuul.Plug.call(passing_options_request, plug_opts) === passing_options_request
end
def get_fixture_ok() do
%Plug.Conn{
assigns: %{},
body_params: %{},
cookies: %{"notice_gdpr_prefs" => "0", "notice_preferences" => "2:"},
halted: false,
host: "localhost",
method: "GET",
params: %{},
path_info: [],
path_params: %{},
port: 4000,
query_params: %{},
query_string: "",
remote_ip: {127, 0, 0, 1},
req_cookies: %{"notice_gdpr_prefs" => "0", "notice_preferences" => "2:"},
req_headers: [
{"accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"},
{"accept-encoding", "gzip, deflate"},
{"accept-language", "en-US,en;q=0.5"},
{"authorization", "correct-horse-battery-staples"},
{"connection", "keep-alive"},
{"cookie", "notice_preferences=2:; notice_gdpr_prefs=0,1,2:"},
{"host", "localhost:4000"},
{"upgrade-insecure-requests", "1"},
{"user-agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:67.0) Gecko/20100101 Firefox/67.0"}
],
request_path: "/",
resp_body: nil,
resp_cookies: %{},
resp_headers: [
{"cache-control", "max-age=0, private, must-revalidate"},
{"x-request-id", "FaEAVcb80eDeCJkAAAjB"},
{"x-frame-options", "SAMEORIGIN"},
{"x-xss-protection", "1; mode=block"},
{"x-content-type-options", "nosniff"},
{"x-download-options", "noopen"},
{"x-permitted-cross-domain-policies", "none"},
{"cross-origin-window-policy", "deny"}
],
scheme: :http,
script_name: [],
state: :unset,
status: nil
}
end
def get_fixture_not_ok() do
%Plug.Conn{
assigns: %{},
body_params: %{},
cookies: %{"notice_gdpr_prefs" => "0", "notice_preferences" => "2:"},
halted: false,
host: "localhost",
method: "GET",
params: %{},
path_info: [],
path_params: %{},
port: 4000,
query_params: %{},
query_string: "",
remote_ip: {127, 0, 0, 1},
req_cookies: %{"notice_gdpr_prefs" => "0", "notice_preferences" => "2:"},
req_headers: [
{"accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"},
{"accept-encoding", "gzip, deflate"},
{"accept-language", "en-US,en;q=0.5"},
{"authorization", "this-key-is-nah"},
{"connection", "keep-alive"},
{"cookie", "notice_preferences=2:; notice_gdpr_prefs=0,1,2:"},
{"host", "localhost:4000"},
{"upgrade-insecure-requests", "1"},
{"user-agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:67.0) Gecko/20100101 Firefox/67.0"}
],
request_path: "/",
resp_body: nil,
resp_cookies: %{},
resp_headers: [
{"cache-control", "max-age=0, private, must-revalidate"},
{"x-request-id", "FaEAVcb80eDeCJkAAAjB"},
{"x-frame-options", "SAMEORIGIN"},
{"x-xss-protection", "1; mode=block"},
{"x-content-type-options", "nosniff"},
{"x-download-options", "noopen"},
{"x-permitted-cross-domain-policies", "none"},
{"cross-origin-window-policy", "deny"}
],
scheme: :http,
script_name: [],
state: :unset,
status: nil
}
end
def get_fixture_without_key() do
%Plug.Conn{
assigns: %{},
body_params: %{},
cookies: %{"notice_gdpr_prefs" => "0", "notice_preferences" => "2:"},
halted: false,
host: "localhost",
method: "GET",
params: %{},
path_info: [],
path_params: %{},
port: 4000,
query_params: %{},
query_string: "",
remote_ip: {127, 0, 0, 1},
req_cookies: %{"notice_gdpr_prefs" => "0", "notice_preferences" => "2:"},
req_headers: [
{"accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"},
{"accept-encoding", "gzip, deflate"},
{"accept-language", "en-US,en;q=0.5"},
{"connection", "keep-alive"},
{"cookie", "notice_preferences=2:; notice_gdpr_prefs=0,1,2:"},
{"host", "localhost:4000"},
{"upgrade-insecure-requests", "1"},
{"user-agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:67.0) Gecko/20100101 Firefox/67.0"}
],
request_path: "/",
resp_body: nil,
resp_cookies: %{},
resp_headers: [
{"cache-control", "max-age=0, private, must-revalidate"},
{"x-request-id", "FaEAVcb80eDeCJkAAAjB"},
{"x-frame-options", "SAMEORIGIN"},
{"x-xss-protection", "1; mode=block"},
{"x-content-type-options", "nosniff"},
{"x-download-options", "noopen"},
{"x-permitted-cross-domain-policies", "none"},
{"cross-origin-window-policy", "deny"}
],
scheme: :http,
script_name: [],
state: :unset,
status: nil
}
end
end
| 33.162162 | 98 | 0.575061 |
f73a544220428ec8d3cf5322d5c1365f3121e6a2 | 1,080 | ex | Elixir | lib/codebeat_test_web/channels/user_socket.ex | dydx/codebeat-test | 0d81a42f253afbcdd953c566c7987363b22d585d | [
"MIT"
] | null | null | null | lib/codebeat_test_web/channels/user_socket.ex | dydx/codebeat-test | 0d81a42f253afbcdd953c566c7987363b22d585d | [
"MIT"
] | null | null | null | lib/codebeat_test_web/channels/user_socket.ex | dydx/codebeat-test | 0d81a42f253afbcdd953c566c7987363b22d585d | [
"MIT"
] | null | null | null | defmodule CodebeatTestWeb.UserSocket do
use Phoenix.Socket
## Channels
# channel "room:*", CodebeatTestWeb.RoomChannel
# 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, _connect_info) do
{:ok, socket}
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "user_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# CodebeatTestWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
def id(_socket), do: nil
end
| 31.764706 | 87 | 0.700926 |