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
f77c14239f7a3f5d626224b9d22c765b42518e58
5,564
ex
Elixir
clients/civic_info/lib/google_api/civic_info/v2/api/elections.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/civic_info/lib/google_api/civic_info/v2/api/elections.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/civic_info/lib/google_api/civic_info/v2/api/elections.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.CivicInfo.V2.Api.Elections do @moduledoc """ API calls for all endpoints tagged `Elections`. """ alias GoogleApi.CivicInfo.V2.Connection alias GoogleApi.Gax.{Request, Response} @doc """ List of available elections to query. ## Parameters - connection (GoogleApi.CivicInfo.V2.Connection): Connection to server - opts (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (ElectionsQueryRequest): ## Returns {:ok, %GoogleApi.CivicInfo.V2.Model.ElectionsQueryResponse{}} on success {:error, info} on failure """ @spec civicinfo_elections_election_query(Tesla.Env.client(), keyword()) :: {:ok, GoogleApi.CivicInfo.V2.Model.ElectionsQueryResponse.t()} | {:error, Tesla.Env.t()} def civicinfo_elections_election_query(connection, opts \\ []) do optional_params = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:get) |> Request.url("/elections") |> Request.add_optional_params(optional_params, opts) connection |> Connection.execute(request) |> Response.decode(struct: %GoogleApi.CivicInfo.V2.Model.ElectionsQueryResponse{}) end @doc """ Looks up information relevant to a voter based on the voter's registered address. ## Parameters - connection (GoogleApi.CivicInfo.V2.Connection): Connection to server - address (String.t): The registered address of the voter to look up. - opts (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :electionId (String.t): The unique ID of the election to look up. A list of election IDs can be obtained at https://www.googleapis.com/civicinfo/{version}/electionsIf no election ID is specified in the query and there is more than one election with data for the given voter, the additional elections are provided in the otherElections response field. - :officialOnly (boolean()): If set to true, only data from official state sources will be returned. - :returnAllAvailableData (boolean()): If set to true, the query will return the success codeand include any partial information when it is unable to determine a matching address or unable to determine the election for electionId=0 queries. - :body (VoterInfoRequest): ## Returns {:ok, %GoogleApi.CivicInfo.V2.Model.VoterInfoResponse{}} on success {:error, info} on failure """ @spec civicinfo_elections_voter_info_query(Tesla.Env.client(), String.t(), keyword()) :: {:ok, GoogleApi.CivicInfo.V2.Model.VoterInfoResponse.t()} | {:error, Tesla.Env.t()} def civicinfo_elections_voter_info_query(connection, address, opts \\ []) do optional_params = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :electionId => :query, :officialOnly => :query, :returnAllAvailableData => :query, :body => :body } request = Request.new() |> Request.method(:get) |> Request.url("/voterinfo") |> Request.add_param(:query, :address, address) |> Request.add_optional_params(optional_params, opts) connection |> Connection.execute(request) |> Response.decode(struct: %GoogleApi.CivicInfo.V2.Model.VoterInfoResponse{}) end end
43.811024
356
0.701114
f77c3962e1c90fcf4d1ca775d0febd105af24481
662
exs
Elixir
priv/repo/migrations/20170603113410_create_results_result.exs
jrissler/ex_oneroster
cec492117bffc14aec91e2448643682ceeb449e9
[ "Apache-2.0" ]
3
2018-09-06T11:15:07.000Z
2021-12-27T15:36:51.000Z
priv/repo/migrations/20170603113410_create_results_result.exs
jrissler/ex_oneroster
cec492117bffc14aec91e2448643682ceeb449e9
[ "Apache-2.0" ]
null
null
null
priv/repo/migrations/20170603113410_create_results_result.exs
jrissler/ex_oneroster
cec492117bffc14aec91e2448643682ceeb449e9
[ "Apache-2.0" ]
null
null
null
defmodule ExOneroster.Repo.Migrations.CreateExOneroster.Results.Result do use Ecto.Migration def change do create table(:results) do add :sourcedId, :string add :user_id, references(:users, on_delete: :delete_all) add :lineitem_id, references(:lineitems, on_delete: :delete_all) add :status, :string add :dateLastModified, :utc_datetime add :metadata, :map add :scoreStatus, :string add :score, :decimal, precision: 5, scale: 1 add :scoreDate, :date add :comment, :string timestamps() end create index(:results, [:user_id]) create index(:results, [:lineitem_id]) end end
28.782609
73
0.669184
f77c4b3db7ea22794d91779f49001b47273f9493
379
exs
Elixir
test/cadet/accounts/form/login_test.exs
Hou-Rui/cadet
f9036d76005bf3b267b632dce176067ae1a19f71
[ "Apache-2.0" ]
null
null
null
test/cadet/accounts/form/login_test.exs
Hou-Rui/cadet
f9036d76005bf3b267b632dce176067ae1a19f71
[ "Apache-2.0" ]
2
2020-04-22T09:06:38.000Z
2020-04-22T09:15:33.000Z
test/cadet/accounts/form/login_test.exs
Hou-Rui/cadet
f9036d76005bf3b267b632dce176067ae1a19f71
[ "Apache-2.0" ]
1
2020-06-01T03:26:02.000Z
2020-06-01T03:26:02.000Z
defmodule Cadet.Accounts.LoginTest do alias Cadet.Accounts.Form.Login use Cadet.ChangesetCase, entity: Login describe "Changesets" do test "valid changeset" do assert_changeset(%{luminus_code: "C0dE"}, :valid) end test "invalid changeset" do assert_changeset(%{luminus_code: ""}, :invalid) assert_changeset(%{}, :invalid) end end end
22.294118
55
0.688654
f77cbd11d22093da54ae308ace1cd289312e1aaa
3,393
exs
Elixir
elixir/list-ops/list_ops_test.exs
bwheel/exercism
6648252bf61f0782ff0a0469ce0df6bf483b3d4d
[ "MIT" ]
null
null
null
elixir/list-ops/list_ops_test.exs
bwheel/exercism
6648252bf61f0782ff0a0469ce0df6bf483b3d4d
[ "MIT" ]
null
null
null
elixir/list-ops/list_ops_test.exs
bwheel/exercism
6648252bf61f0782ff0a0469ce0df6bf483b3d4d
[ "MIT" ]
null
null
null
if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("list_ops.exs", __DIR__) end ExUnit.start() ExUnit.configure(exclude: :pending, trace: true) defmodule ListOpsTest do alias ListOps, as: L use ExUnit.Case defp odd?(n), do: rem(n, 2) == 1 # @tag :pending test "count of empty list" do assert L.count([]) == 0 end # @tag :pending test "count of normal list" do assert L.count([1, 3, 5, 7]) == 4 end # @tag :pending test "count of huge list" do assert L.count(Enum.to_list(1..1_000_000)) == 1_000_000 end # @tag :pending test "reverse of empty list" do assert L.reverse([]) == [] end # @tag :pending test "reverse of normal list" do assert L.reverse([1, 3, 5, 7]) == [7, 5, 3, 1] end # @tag :pending test "reverse of huge list" do assert L.reverse(Enum.to_list(1..1_000_000)) == Enum.to_list(1_000_000..1) end # @tag :pending test "map of empty list" do assert L.map([], &(&1 + 1)) == [] end # @tag :pending test "map of normal list" do assert L.map([1, 3, 5, 7], &(&1 + 1)) == [2, 4, 6, 8] end # @tag :pending test "map of huge list" do assert L.map(Enum.to_list(1..1_000_000), &(&1 + 1)) == Enum.to_list(2..1_000_001) end # @tag :pending test "filter of empty list" do assert L.filter([], &odd?/1) == [] end # @tag :pending test "filter of normal list" do assert L.filter([1, 2, 3, 4], &odd?/1) == [1, 3] end # @tag :pending test "filter of huge list" do assert L.filter(Enum.to_list(1..1_000_000), &odd?/1) == Enum.map(1..500_000, &(&1 * 2 - 1)) end # @tag :pending test "reduce of empty list" do assert L.reduce([], 0, &(&1 + &2)) == 0 end # @tag :pending test "reduce of normal list" do assert L.reduce([1, 2, 3, 4], -3, &(&1 + &2)) == 7 end # @tag :pending test "reduce of huge list" do assert L.reduce(Enum.to_list(1..1_000_000), 0, &(&1 + &2)) == Enum.reduce(1..1_000_000, 0, &(&1 + &2)) end # @tag :pending test "reduce with non-commutative function" do assert L.reduce([1, 2, 3, 4], 10, fn x, acc -> acc - x end) == 0 end # @tag :pending test "append of empty lists" do assert L.append([], []) == [] end # @tag :pending test "append of empty and non-empty list" do assert L.append([], [1, 2, 3, 4]) == [1, 2, 3, 4] end #@tag :pending test "append of non-empty and empty list" do assert L.append([1, 2, 3, 4], []) == [1, 2, 3, 4] end # @tag :pending test "append of non-empty lists" do assert L.append([1, 2, 3], [4, 5]) == [1, 2, 3, 4, 5] end # @tag :pending test "append of huge lists" do assert L.append(Enum.to_list(1..1_000_000), Enum.to_list(1_000_001..2_000_000)) == Enum.to_list(1..2_000_000) end # @tag :pending test "concat of empty list of lists" do assert L.concat([]) == [] end # @tag :pending test "concat of normal list of lists" do assert L.concat([[1, 2], [3], [], [4, 5, 6]]) == [1, 2, 3, 4, 5, 6] end @tag :pending test "concat of huge list of small lists" do assert L.concat(Enum.map(1..1_000_000, &[&1])) == Enum.to_list(1..1_000_000) end @tag :pending test "concat of small list of huge lists" do assert L.concat(Enum.map(0..9, &Enum.to_list((&1 * 100_000 + 1)..((&1 + 1) * 100_000)))) == Enum.to_list(1..1_000_000) end end
23.727273
95
0.578249
f77cbf48925fc299d597103c17ab74cb8522a494
2,287
exs
Elixir
config/prod.exs
spkane31/cc-rankings
0acda9f3ca35abd4874ab06478ad22aa473811bf
[ "MIT" ]
1
2020-06-28T19:31:07.000Z
2020-06-28T19:31:07.000Z
config/prod.exs
spkane31/rankings
0acda9f3ca35abd4874ab06478ad22aa473811bf
[ "MIT" ]
5
2019-07-25T17:00:39.000Z
2019-07-25T17:12:07.000Z
config/prod.exs
spkane31/rankings
0acda9f3ca35abd4874ab06478ad22aa473811bf
[ "MIT" ]
null
null
null
use Mix.Config # For production, don't forget to configure the url host # to something meaningful, Phoenix uses this information # when generating URLs. # # Note we also include the path to a cache manifest # containing the digested version of static files. This # manifest is generated by the `mix phx.digest` task, # which you should run after static files are built and # before starting your production server. config :rankings, RankingsWeb.Endpoint, url: [host: "example.com", port: 80], cache_static_manifest: "priv/static/cache_manifest.json" # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :rankings, RankingsWeb.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [ # :inet6, # port: 443, # cipher_suite: :strong, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH") # ] # # The `cipher_suite` is set to `:strong` to support only the # latest and more secure SSL ciphers. This means old browsers # and clients may not be supported. You can set it to # `:compatible` for wider support. # # `:keyfile` and `:certfile` expect an absolute path to the key # and cert in disk or a relative path inside priv, for example # "priv/ssl/server.key". For all supported SSL configuration # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 # # We also recommend setting `force_ssl` in your endpoint, ensuring # no data is ever sent via http, always redirecting to https: # # config :rankings, RankingsWeb.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # ## Using releases (Elixir v1.9+) # # If you are doing OTP releases, you need to instruct Phoenix # to start each relevant endpoint: # # config :rankings, RankingsWeb.Endpoint, server: true # # Then you can assemble a release by calling `mix release`. # See `mix help release` for more information. # Finally import the config/prod.secret.exs which loads secrets # and configuration from environment variables. import_config "prod.secret.exs"
34.651515
66
0.715348
f77cf6acb9020bb9f788063c113bfb6f00e49aee
7,415
ex
Elixir
lib/x509/certificate/template.ex
ConnorRigby/x509
92ac8d56706459a198dac59763ebb2f67af208ba
[ "BSD-3-Clause" ]
75
2018-07-02T12:00:57.000Z
2022-02-07T14:47:56.000Z
lib/x509/certificate/template.ex
ConnorRigby/x509
92ac8d56706459a198dac59763ebb2f67af208ba
[ "BSD-3-Clause" ]
30
2018-07-04T12:33:01.000Z
2022-01-14T18:29:00.000Z
lib/x509/certificate/template.ex
ConnorRigby/x509
92ac8d56706459a198dac59763ebb2f67af208ba
[ "BSD-3-Clause" ]
12
2018-09-21T04:34:02.000Z
2022-02-28T20:11:13.000Z
defmodule X509.Certificate.Template do @moduledoc """ Certificate templates. """ import X509.Certificate.Extension defstruct serial: {:random, 8}, validity: 365, hash: :sha256, extensions: [] @type t :: %__MODULE__{ serial: pos_integer() | {:random, pos_integer()}, validity: pos_integer() | X509.Certificate.Validity.t(), hash: atom(), extensions: [{atom(), X509.Certificate.Extension.t() | boolean()}] } @type named_template :: :root_ca | :ca | :server @doc """ Returns a template, optionally customized with user-provided validity, hash and extensions options. The base template can be selected from a list of built-in named templates, or as a custom template. The following named templates are supported: * `:root_ca` - intended for a self-signed root CA. The default path length constraint is set to 1, meaning the root CA can be used to issue intermediate CAs, and those CAs can only sign end certificates. The value can be overridden by passing a custom value for the `:basic_constraints` extension. The default validity is 25 years. * `:ca` - intended for intermediate CA certificates. The default path length constraint is set to 0, meaning the CA can only sign end certificates. The value can be overridden by passing a custom value for the `:basic_constraints` extension (assuming the issuing CA allows it). The Extended Key Usage extension is set to TLS server & client. Many (but not all) TLS implementations will interpret this as a constraint on the type of certificates the CA is allowed to issue. This constraint can be removed by setting `:ext_key_usage` to `false`, or by overriding the value to set the desired constraints. The default validity is 10 years. * `:server` - intended for end-certificates. The Extended Key Usage extension is set to TLS server & client. For other types of end-certificates, set the `:ext_key_usage` extension to the desired value. It may be necessary to update the `:key_usage` value as well. The default validity is 1 year, plus a 30 day grace period. * `:ocsp_responder` - designated responder to sign OCSP responses on behalf of the issuing CA. The Extended Key Usage extension is set to allow OCSP signing only. Must be issued directly from the CA certificate for which OCSP responses will be signed. The OCSP Nocheck extension is included, to disable revocation checks for the OCSP responder certificate. To exclude this extension override it with a value of `false` (e.g. `extensions: [ocsp_nocheck: false]`) The default validity is just 30 days, due to the fact that revocation is not possible when OCSP Nocheck is set. All of the above templates generate a random 8 byte (64 bit) serial number, which can be overriden through the `:serial` option (see below). The `extensions` attribute of a template is a keyword list of extension name/value pairs, where the value should typically be an `X509.Certificate.Extension` record. The `subject_key_identifier` and `authority_key_identifier` extensions may simply be set to `true`: the actual values will be calculated during the certificate signing process. ## Options: * `:hash` - the hash algorithm to use when signing the certificate * `:serial` - the serial number of the certificate (an integer >0) or `{:random, n}` to generate an n-byte random serial number * `:validity` - override the validity period; can be specified as the number of days (integer) or a `X509.Certificate.Validity` value * `:extensions` - a keyword list of extensions to be merged into the template's defaults; set an extension value to `false` to exclude that extension from the certificate ## Examples: iex> X509.Certificate.Template.new(:root_ca, ...> hash: :sha512, serial: 1, ...> extensions: [authority_key_identifier: false] ...> ) %X509.Certificate.Template{ extensions: [ basic_constraints: {:Extension, {2, 5, 29, 19}, true, {:BasicConstraints, true, 1}}, key_usage: {:Extension, {2, 5, 29, 15}, true, [:digitalSignature, :keyCertSign, :cRLSign]}, subject_key_identifier: true, authority_key_identifier: false ], hash: :sha512, serial: 1, validity: 9131 } iex> X509.Certificate.Template.new(:server, extensions: [ ...> ext_key_usage: X509.Certificate.Extension.ext_key_usage([:codeSigning]) ...> ]) %X509.Certificate.Template{ extensions: [ basic_constraints: {:Extension, {2, 5, 29, 19}, false, {:BasicConstraints, false, :asn1_NOVALUE}}, key_usage: {:Extension, {2, 5, 29, 15}, true, [:digitalSignature, :keyEncipherment]}, subject_key_identifier: true, authority_key_identifier: true, ext_key_usage: {:Extension, {2, 5, 29, 37}, false, [{1, 3, 6, 1, 5, 5, 7, 3, 3}]} ], hash: :sha256, serial: {:random, 8}, validity: 395 } """ @spec new(named_template() | t(), Keyword.t()) :: t() def new(template, opts \\ []) def new(:root_ca, opts) do %__MODULE__{ # 25 years validity: round(25 * 365.2425), hash: :sha256, extensions: [ basic_constraints: basic_constraints(true, 1), key_usage: key_usage([:digitalSignature, :keyCertSign, :cRLSign]), subject_key_identifier: true, authority_key_identifier: true ] } |> new(opts) end def new(:ca, opts) do %__MODULE__{ # 10 years validity: round(10 * 365.2425), hash: :sha256, extensions: [ basic_constraints: basic_constraints(true, 0), key_usage: key_usage([:digitalSignature, :keyCertSign, :cRLSign]), ext_key_usage: ext_key_usage([:serverAuth, :clientAuth]), subject_key_identifier: true, authority_key_identifier: true ] } |> new(opts) end def new(:server, opts) do %__MODULE__{ # 1 year, plus a 30 days grace period validity: 365 + 30, hash: :sha256, extensions: [ basic_constraints: basic_constraints(false), key_usage: key_usage([:digitalSignature, :keyEncipherment]), ext_key_usage: ext_key_usage([:serverAuth, :clientAuth]), subject_key_identifier: true, authority_key_identifier: true ] } |> new(opts) end def new(:ocsp_responder, opts) do %__MODULE__{ # 30 days validity: 30, hash: :sha256, extensions: [ basic_constraints: basic_constraints(false), key_usage: key_usage([:digitalSignature]), ext_key_usage: ext_key_usage([:OCSPSigning]), subject_key_identifier: true, authority_key_identifier: true, ocsp_nocheck: ocsp_nocheck() ] } |> new(opts) end def new(template, opts) do override = opts |> Keyword.take([:hash, :serial, :validity]) |> Enum.into(%{}) extensions = template.extensions |> Keyword.merge(Keyword.get(opts, :extensions, [])) template |> Map.merge(override) |> Map.put(:extensions, extensions) end end
34.649533
84
0.648415
f77d0fd39da61e84e34db7c4a7105c9f6964f52c
5,261
ex
Elixir
clients/machine_learning/lib/google_api/machine_learning/v1/model/google_cloud_ml_v1__model.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
clients/machine_learning/lib/google_api/machine_learning/v1/model/google_cloud_ml_v1__model.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
clients/machine_learning/lib/google_api/machine_learning/v1/model/google_cloud_ml_v1__model.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_Model do @moduledoc """ Represents a machine learning solution. A model can have multiple versions, each of which is a deployed, trained model ready to receive prediction requests. The model itself is just a container. ## Attributes * `defaultVersion` (*type:* `GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_Version.t`, *default:* `nil`) - Output only. The default version of the model. This version will be used to handle prediction requests that do not specify a version. You can change the default version by calling projects.models.versions.setDefault. * `description` (*type:* `String.t`, *default:* `nil`) - Optional. The description specified for the model when it was created. * `etag` (*type:* `String.t`, *default:* `nil`) - `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a model from overwriting each other. It is strongly suggested that systems make use of the `etag` in the read-modify-write cycle to perform model updates in order to avoid race conditions: An `etag` is returned in the response to `GetModel`, and systems are expected to put that etag in the request to `UpdateModel` to ensure that their change will be applied to the model as intended. * `labels` (*type:* `map()`, *default:* `nil`) - Optional. One or more labels that you can add, to organize your models. Each label is a key-value pair, where both the key and the value are arbitrary strings that you supply. For more information, see the documentation on using labels. Note that this field is not updatable for mls1* models. * `name` (*type:* `String.t`, *default:* `nil`) - Required. The name specified for the model when it was created. The model name must be unique within the project it is created in. * `onlinePredictionConsoleLogging` (*type:* `boolean()`, *default:* `nil`) - Optional. If true, online prediction nodes send `stderr` and `stdout` streams to Cloud Logging. These can be more verbose than the standard access logs (see `onlinePredictionLogging`) and can incur higher cost. However, they are helpful for debugging. Note that [logs may incur a cost](/stackdriver/pricing), especially if your project receives prediction requests at a high QPS. Estimate your costs before enabling this option. Default is false. * `onlinePredictionLogging` (*type:* `boolean()`, *default:* `nil`) - Optional. If true, online prediction access logs are sent to Cloud Logging. These logs are like standard server access logs, containing information like timestamp and latency for each request. Note that [logs may incur a cost](/stackdriver/pricing), especially if your project receives prediction requests at a high queries per second rate (QPS). Estimate your costs before enabling this option. Default is false. * `regions` (*type:* `list(String.t)`, *default:* `nil`) - Optional. The list of regions where the model is going to be deployed. Only one region per model is supported. Defaults to 'us-central1' if nothing is set. See the available regions for AI Platform services. Note: * No matter where a model is deployed, it can always be accessed by users from anywhere, both for online and batch prediction. * The region for a batch prediction job is set by the region field when submitting the batch prediction job and does not take its value from this field. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :defaultVersion => GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_Version.t() | nil, :description => String.t() | nil, :etag => String.t() | nil, :labels => map() | nil, :name => String.t() | nil, :onlinePredictionConsoleLogging => boolean() | nil, :onlinePredictionLogging => boolean() | nil, :regions => list(String.t()) | nil } field(:defaultVersion, as: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_Version) field(:description) field(:etag) field(:labels, type: :map) field(:name) field(:onlinePredictionConsoleLogging) field(:onlinePredictionLogging) field(:regions, type: :list) end defimpl Poison.Decoder, for: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_Model do def decode(value, options) do GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_Model.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1_Model do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
77.367647
556
0.745296
f77d16d19f69d411bce6a2d6cc0e78667033ed9d
286
ex
Elixir
test/support/geo_json_validate.ex
hrzndhrn/geometry
bffdac0a9554f7f5fd05caceee0fa8f3c96d1c60
[ "MIT" ]
null
null
null
test/support/geo_json_validate.ex
hrzndhrn/geometry
bffdac0a9554f7f5fd05caceee0fa8f3c96d1c60
[ "MIT" ]
2
2020-10-25T10:06:07.000Z
2020-10-26T18:15:20.000Z
test/support/geo_json_validate.ex
hrzndhrn/geometry
bffdac0a9554f7f5fd05caceee0fa8f3c96d1c60
[ "MIT" ]
null
null
null
defmodule GeoJsonValidator do @moduledoc false @schema "test/fixtures/schema/GeoJSON.json" |> File.read!() |> Jason.decode!() |> Xema.from_json_schema() @spec valid?(term()) :: boolean def valid?(geo_json), do: Xema.valid?(@schema, geo_json) end
23.833333
58
0.625874
f77d2179267ea8569aff095f732855e1e690f51f
799
ex
Elixir
lib/we_whisper/signature.ex
he9qi/we_whisper_elixir
5c9dc87cf2ce159778942201eef363b083f9dad7
[ "MIT" ]
3
2016-10-09T00:07:44.000Z
2021-02-21T04:29:43.000Z
lib/we_whisper/signature.ex
he9qi/we_whisper_elixir
5c9dc87cf2ce159778942201eef363b083f9dad7
[ "MIT" ]
4
2016-10-08T01:27:01.000Z
2016-10-08T17:56:49.000Z
lib/we_whisper/signature.ex
he9qi/we_whisper_elixir
5c9dc87cf2ce159778942201eef363b083f9dad7
[ "MIT" ]
null
null
null
defmodule WeWhisper.Signature do @type t :: %{ token: binary, timestamp: binary, nonce: binary, encrypted: binary } @doc """ Create signature for encrypted message """ @spec sign(t) :: binary def sign(%{token: token, timestamp: timestamp, nonce: nonce, encrypted: encrypted}) do sign(token, timestamp, nonce, encrypted) end @doc """ Create signature for encrypted message """ @spec sign(binary, binary, binary, binary) :: binary def sign(token, timestamp, nonce, encrypted) do [token, timestamp, nonce, encrypted] |> Enum.reject(&(&1 == nil)) |> Enum.map(&("#{&1}")) |> Enum.sort |> Enum.join |> encrypt end defp encrypt(string) do :crypto.hash(:sha, string) |> Base.encode16(case: :lower) end end
21.594595
88
0.614518
f77d410ec8bf1a25f8b26976fd1455fcf3665825
201
ex
Elixir
lib/hypoxia.ex
itsemilano/hypoxia
d51cf51205bda5e95713ecd2b1e49a1bcce56bef
[ "Apache-2.0" ]
null
null
null
lib/hypoxia.ex
itsemilano/hypoxia
d51cf51205bda5e95713ecd2b1e49a1bcce56bef
[ "Apache-2.0" ]
null
null
null
lib/hypoxia.ex
itsemilano/hypoxia
d51cf51205bda5e95713ecd2b1e49a1bcce56bef
[ "Apache-2.0" ]
null
null
null
defmodule Hypoxia do @moduledoc """ Documentation for `Hypoxia`. """ @doc """ Hello world. ## Examples iex> Hypoxia.hello() :world """ def hello do :world end end
10.578947
30
0.557214
f77d74a0fdbc10c0e6759b57f1527eb233d0c17a
5
ex
Elixir
testData/org/elixir_lang/parser_definition/function_reference_parsing_test_case/Identifier.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/function_reference_parsing_test_case/Identifier.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/function_reference_parsing_test_case/Identifier.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
145
2015-01-15T11:37:16.000Z
2021-12-22T05:51:02.000Z
one/2
5
5
0.8
f77d9af8814c7eea21681ff40e433d3d218c434a
5,316
ex
Elixir
lib/ex_unit/lib/ex_unit/cli_formatter.ex
knewter/elixir
8310d62499e292d78d5c9d79d5d15a64e32fb738
[ "Apache-2.0" ]
null
null
null
lib/ex_unit/lib/ex_unit/cli_formatter.ex
knewter/elixir
8310d62499e292d78d5c9d79d5d15a64e32fb738
[ "Apache-2.0" ]
null
null
null
lib/ex_unit/lib/ex_unit/cli_formatter.ex
knewter/elixir
8310d62499e292d78d5c9d79d5d15a64e32fb738
[ "Apache-2.0" ]
null
null
null
defmodule ExUnit.CLIFormatter do @moduledoc false @timeout 30_000 @behaviour ExUnit.Formatter use GenServer.Behaviour import ExUnit.Formatter, only: [format_time: 2, format_test_failure: 3, format_test_case_failure: 3] defrecord Config, tests_counter: 0, invalids_counter: 0, failures_counter: 0, trace: false, color: true, previous: nil ## Behaviour def suite_started(opts) do { :ok, pid } = :gen_server.start_link(__MODULE__, opts, []) pid end def suite_finished(id, run_us, load_us) do :gen_server.call(id, { :suite_finished, run_us, load_us }, @timeout) end def case_started(id, test_case) do :gen_server.cast(id, { :case_started, test_case }) end def case_finished(id, test_case) do :gen_server.cast(id, { :case_finished, test_case }) end def test_started(id, test) do :gen_server.cast(id, { :test_started, test }) end def test_finished(id, test) do :gen_server.cast(id, { :test_finished, test }) end ## Callbacks def init(opts) do { :ok, Config.new(opts) } end def handle_call({ :suite_finished, run_us, load_us }, _from, config = Config[]) do print_suite(config, run_us, load_us) { :stop, :normal, config.failures_counter, config } end def handle_call(reqest, from, config) do super(reqest, from, config) end def handle_cast({ :test_started, ExUnit.Test[] = test }, config) do if config.trace, do: IO.write(" * #{trace_test_name test}") { :noreply, config } end def handle_cast({ :test_finished, ExUnit.Test[failure: nil] = test }, config = Config[]) do if config.trace do IO.puts success(trace_test_result(test), config) else IO.write success(".", config) end { :noreply, config.previous(:ok).update_tests_counter(&(&1 + 1)) } end def handle_cast({ :test_finished, ExUnit.Test[failure: { :invalid, _ }] = test }, config = Config[]) do if config.trace do IO.puts invalid(trace_test_result(test), config) else IO.write invalid("?", config) end { :noreply, config.previous(:invalid).update_tests_counter(&(&1 + 1)) .update_invalids_counter(&(&1 + 1)) } end def handle_cast({ :test_finished, test }, config) do if config.trace do IO.puts failure(trace_test_result(test), config) end config = print_test_failure(test, config) { :noreply, config.update_tests_counter(&(&1 + 1)) } end def handle_cast({ :case_started, ExUnit.TestCase[name: name] }, config) do if config.trace do IO.puts("\n#{inspect name}") end { :noreply, config } end def handle_cast({ :case_finished, test_case }, config) do if test_case.failure do config = print_test_case_failure(test_case, config) { :noreply, config } else { :noreply, config } end end def handle_cast(request, config) do super(request, config) end defp trace_test_result(test) do "\r * #{trace_test_name test} (#{trace_test_time(test)})" end defp trace_test_name(ExUnit.Test[name: name]) do case atom_to_binary(name) do "test_" <> rest -> rest "test " <> rest -> rest rest -> rest end end defp trace_test_time(ExUnit.Test[time: time]) do "#{format_us(time)}ms" end defp format_us(us) do us = div(us, 10) if us < 10 do "0.0#{us}" else us = div us, 10 "#{div(us, 10)}.#{rem(us, 10)}" end end defp print_suite(config = Config[], run_us, load_us) do IO.write "\n\n" IO.puts format_time(run_us, load_us) message = "#{config.tests_counter} tests, #{config.failures_counter} failures" if config.invalids_counter > 0 do message = message <> ", #{config.invalids_counter} invalid" end cond do config.failures_counter > 0 -> IO.puts failure(message, config) config.invalids_counter > 0 -> IO.puts invalid(message, config) true -> IO.puts success(message, config) end end defp print_test_failure(test, config) do formatted = format_test_failure(test, config.failures_counter + 1, &formatter(&1, &2, config)) print_any_failure formatted, config end defp print_test_case_failure(test_case, config) do formatted = format_test_case_failure(test_case, config.failures_counter + 1, &formatter(&1, &2, config)) print_any_failure formatted, config end defp print_any_failure(formatted, config = Config[]) do cond do config.trace -> IO.puts "" config.previous != :failure -> IO.puts "\n" true -> :ok end IO.puts formatted config.update_failures_counter(&(&1 + 1)).previous(:failure) end # Color styles defp colorize(escape, string, Config[color: color]) do IO.ANSI.escape_fragment("%{#{escape}}", color) <> string <> IO.ANSI.escape_fragment("%{reset}", color) end defp success(msg, config) do colorize("green", msg, config) end defp invalid(msg, config) do colorize("yellow", msg, config) end defp failure(msg, config) do colorize("red", msg, config) end defp formatter(:error_info, msg, config), do: colorize("red", msg, config) defp formatter(:location_info, msg, config), do: colorize("cyan", msg, config) defp formatter(_, msg, _config), do: msg end
26.984772
108
0.650113
f77d9c5439cc199ccdb4d2cd537dcc94261c040f
3,165
ex
Elixir
clients/cloud_build/lib/google_api/cloud_build/v1/model/operation.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/cloud_build/lib/google_api/cloud_build/v1/model/operation.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/cloud_build/lib/google_api/cloud_build/v1/model/operation.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.CloudBuild.V1.Model.Operation do @moduledoc """ This resource represents a long-running operation that is the result of a network API call. ## Attributes * `done` (*type:* `boolean()`, *default:* `nil`) - If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. * `error` (*type:* `GoogleApi.CloudBuild.V1.Model.Status.t`, *default:* `nil`) - The error result of the operation in case of failure or cancellation. * `metadata` (*type:* `map()`, *default:* `nil`) - Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. * `name` (*type:* `String.t`, *default:* `nil`) - The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. * `response` (*type:* `map()`, *default:* `nil`) - The normal response of the operation in case of success. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :done => boolean() | nil, :error => GoogleApi.CloudBuild.V1.Model.Status.t() | nil, :metadata => map() | nil, :name => String.t() | nil, :response => map() | nil } field(:done) field(:error, as: GoogleApi.CloudBuild.V1.Model.Status) field(:metadata, type: :map) field(:name) field(:response, type: :map) end defimpl Poison.Decoder, for: GoogleApi.CloudBuild.V1.Model.Operation do def decode(value, options) do GoogleApi.CloudBuild.V1.Model.Operation.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudBuild.V1.Model.Operation do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
53.644068
543
0.720695
f77d9c701755fd7ec193ffa9869a06a21487c6c6
102
exs
Elixir
test/cqrs/bounded_context_test.exs
sebaughman/elixir_cqrs_tools
3f226e23af568d0422765e8bb526d966d83d34da
[ "MIT" ]
17
2021-05-04T09:27:48.000Z
2022-02-02T00:53:28.000Z
test/cqrs/bounded_context_test.exs
sebaughman/elixir_cqrs_tools
3f226e23af568d0422765e8bb526d966d83d34da
[ "MIT" ]
18
2021-05-05T21:17:54.000Z
2021-12-08T19:25:21.000Z
test/cqrs/bounded_context_test.exs
sebaughman/elixir_cqrs_tools
3f226e23af568d0422765e8bb526d966d83d34da
[ "MIT" ]
2
2021-05-04T13:35:00.000Z
2021-07-08T22:28:32.000Z
defmodule Cqrs.BoundedContextTest do use ExUnit.Case, async: true doctest Cqrs.BoundedContext end
20.4
36
0.813725
f77dabb328904ef828500c671a79645f88177886
1,063
ex
Elixir
lib/amazon_product_advertising_client/search_items.ex
keslert/elixir-amazon-product-advertising-client
89643817c992c261a72afc35c485dcdad15b0bf6
[ "MIT" ]
27
2015-01-17T00:32:49.000Z
2018-08-07T02:04:12.000Z
lib/amazon_product_advertising_client/search_items.ex
keslert/elixir-amazon-product-advertising-client
89643817c992c261a72afc35c485dcdad15b0bf6
[ "MIT" ]
8
2015-03-01T20:23:53.000Z
2018-02-22T04:04:10.000Z
lib/amazon_product_advertising_client/search_items.ex
keslert/elixir-amazon-product-advertising-client
89643817c992c261a72afc35c485dcdad15b0bf6
[ "MIT" ]
19
2015-10-28T04:55:15.000Z
2018-08-07T02:12:36.000Z
defmodule AmazonProductAdvertisingClient.SearchItems do @moduledoc """ The [SearchItems](https://webservices.amazon.com/paapi5/documentation/search-items.html) operation """ alias AmazonProductAdvertisingClient.{SearchItems, Config} defstruct( Actor: nil, Artist: nil, Author: nil, Availability: nil, Brand: nil, BrowseNodeId: nil, Condition: nil, CurrencyOfPreference: nil, DeliveryFlags: nil, ItemCount: nil, ItemPage: nil, Keywords: nil, LanguagesOfPreference: nil, MaxPrice: nil, Merchant: nil, MinPrice: nil, MinReviewsRating: nil, MinSavingPercent: nil, OfferCount: nil, Properties: nil, Resources: nil, SearchIndex: nil, SortBy: nil, Title: nil ) @doc """ Execute a SearchItems operation """ def execute(params \\ %SearchItems{}, config \\ %Config{}) do AmazonProductAdvertisingClient.call_api( "com.amazon.paapi5.v1.ProductAdvertisingAPIv1.SearchItems", "/paapi5/searchitems", params, config ) end end
22.617021
100
0.670743
f77dad865d071cbc1043ccf16faf54506fb4d520
708
ex
Elixir
lib/hopper_web/gettext.ex
SquashConsulting/hopper
d68ac8b4749b2411959c2ba7be7cd9402a3e4b2b
[ "BSD-3-Clause" ]
1
2019-12-22T16:00:11.000Z
2019-12-22T16:00:11.000Z
lib/hopper_web/gettext.ex
SquashConsulting/hopper
d68ac8b4749b2411959c2ba7be7cd9402a3e4b2b
[ "BSD-3-Clause" ]
2
2021-03-10T02:31:42.000Z
2021-05-10T22:02:29.000Z
lib/hopper_web/gettext.ex
SquashConsulting/hopper
d68ac8b4749b2411959c2ba7be7cd9402a3e4b2b
[ "BSD-3-Clause" ]
null
null
null
defmodule HopperWeb.Gettext do @moduledoc """ A module providing Internationalization with a gettext-based API. By using [Gettext](https://hexdocs.pm/gettext), your module gains a set of macros for translations, for example: import HopperWeb.Gettext # Simple translation gettext("Here is the string to translate") # Plural translation ngettext("Here is the string to translate", "Here are the strings to translate", 3) # Domain-based translation dgettext("errors", "Here is the error message to translate") See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. """ use Gettext, otp_app: :hopper end
28.32
72
0.676554
f77e2e72f4455970a97442b1cb554cd6c6b6ee62
1,406
exs
Elixir
test/phantomchain/client/node_test.exs
PhantomChain/elixir-client
d776f84f9a407877a029043325973a8fdd2574a5
[ "MIT" ]
null
null
null
test/phantomchain/client/node_test.exs
PhantomChain/elixir-client
d776f84f9a407877a029043325973a8fdd2574a5
[ "MIT" ]
null
null
null
test/phantomchain/client/node_test.exs
PhantomChain/elixir-client
d776f84f9a407877a029043325973a8fdd2574a5
[ "MIT" ]
null
null
null
defmodule PhantomChain.Client.API.NodeTest do use ExUnit.Case import PhantomChain.Client.API.Node import Tesla.Mock @client PhantomChain.Client.new(%{ host: "http://127.0.0.1:4003/api", nethash: "578e820911f24e039733b45e4882b73e301f813a0d2c31330dafda84534ffa23", version: "1.1.1" }) setup do mock fn %{method: :get, url: "http://127.0.0.1:4003/api/node/status"} -> json(%{"success" => true, "data" => %{ synced: true }}) %{method: :get, url: "http://127.0.0.1:4003/api/node/syncing"} -> json(%{"success" => true, "data" => %{ syncing: true }}) %{method: :get, url: "http://127.0.0.1:4003/api/node/configuration"} -> json(%{"success" => true, "data" => %{ nethash: "dummyHash" }}) end :ok end test "call PhantomChain.Client.API.Node.status" do assert {:ok, response} = status(@client) assert response["data"]["synced"] == true assert response["success"] == true end test "call PhantomChain.Client.API.Node.syncing" do assert {:ok, response} = syncing(@client) assert response["data"]["syncing"] == true assert response["success"] == true end test "call PhantomChain.Client.API.Node.configuration" do assert {:ok, response} = configuration(@client) assert response["data"]["nethash"] == "dummyHash" assert response["success"] == true end end
32.697674
88
0.618065
f77e6cf3cf69732f1e206ee1c6c45d9699d0e1b4
486
ex
Elixir
lib/rasa_api/model/event.ex
whitedr/rasa-api-elixir
3ff932ee4cb4d04f0dd5ea66ec4b8f83195a003a
[ "Apache-2.0" ]
null
null
null
lib/rasa_api/model/event.ex
whitedr/rasa-api-elixir
3ff932ee4cb4d04f0dd5ea66ec4b8f83195a003a
[ "Apache-2.0" ]
null
null
null
lib/rasa_api/model/event.ex
whitedr/rasa-api-elixir
3ff932ee4cb4d04f0dd5ea66ec4b8f83195a003a
[ "Apache-2.0" ]
null
null
null
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). # https://openapi-generator.tech # Do not edit the class manually. defmodule RasaApi.Model.Event do @moduledoc """ """ @derive [Poison.Encoder] defstruct [ :event, :timestamp ] @type t :: %__MODULE__{ event: String.t, timestamp: integer() | nil } end defimpl Poison.Decoder, for: RasaApi.Model.Event do def decode(value, _options) do value end end
17.357143
91
0.670782
f77e8d523b2f5230074cc74ceada587aaa347d44
625
exs
Elixir
base/fc_support/test/fc_support/struct_test.exs
fleadope/freshcom
8d5944befaa6eea8d31e5f5995939be2a1a44262
[ "BSD-3-Clause" ]
46
2018-10-13T23:18:13.000Z
2021-08-07T07:46:51.000Z
base/fc_support/test/fc_support/struct_test.exs
fleadope/freshcom
8d5944befaa6eea8d31e5f5995939be2a1a44262
[ "BSD-3-Clause" ]
25
2018-10-14T00:56:07.000Z
2019-12-23T19:41:02.000Z
base/fc_support/test/fc_support/struct_test.exs
fleadope/freshcom
8d5944befaa6eea8d31e5f5995939be2a1a44262
[ "BSD-3-Clause" ]
5
2018-12-16T04:39:51.000Z
2020-10-01T12:17:03.000Z
defmodule FCSupport.StructTest do use ExUnit.Case import FCSupport.Struct defmodule TestStruct do defstruct [:id, :name] end test "merge/3" do assert merge(%TestStruct{}, %{"id" => 1}).id == 1 assert merge(%TestStruct{}, %{"id" => 1}, except: [:id]).id == nil assert merge(%TestStruct{}, %{id: 1}).id == 1 assert merge(%TestStruct{}, %{id: 1}, except: [:id]).id == nil assert merge(%TestStruct{}, %TestStruct{id: 1}).id == 1 assert merge(%TestStruct{}, %TestStruct{id: 1}, except: [:id]).id == nil assert merge(%TestStruct{}, %TestStruct{id: 1}, only: [:name]).id == nil end end
32.894737
76
0.608
f77e9497a26481bd9bbeeaba837f913330cc9e3e
1,228
ex
Elixir
lib/mix/tasks/cli/args_parser.ex
miros/excoveralls_linter
661e9d4019d9f8842340c172d78341e8822d4d6c
[ "Apache-2.0" ]
4
2019-11-25T15:32:45.000Z
2020-01-29T23:27:45.000Z
lib/mix/tasks/cli/args_parser.ex
miros/excoveralls_linter
661e9d4019d9f8842340c172d78341e8822d4d6c
[ "Apache-2.0" ]
null
null
null
lib/mix/tasks/cli/args_parser.ex
miros/excoveralls_linter
661e9d4019d9f8842340c172d78341e8822d4d6c
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Tasks.Coveralls.Lint.CLI.ArgsParser do @spec parse(command_line_args :: [binary]) :: Access.container() def parse(args) do result = cli_description() |> Optimus.parse!(args) result.options end defp cli_description do Optimus.new!( name: "coveralls.lint", allow_unknown_args: false, parse_double_dash: true, options: [ missed_lines_threshold: [ value_name: "MISSED_LINES_THRESHOLD", long: "--missed-lines-threshold", help: "Report files with MISSED_LINES_THRESHOLD or more missed lines in a row", parser: :integer, required: true ], required_file_coverage: [ value_name: "REQUIRED_FILE_COVERAGE", long: "--required-file-coverage", help: "Report files with less than REQUIRED_FILE_COVERAGE", parser: :float, required: true ], required_project_coverage: [ value_name: "REQUIRED_PROJECT_COVERAGE", long: "--required-project-coverage", help: "Total required coverage percentage for all files", parser: :float, default: 0.0, required: false ] ] ) end end
30.7
89
0.608306
f77eaa92200ce3604f510ebefe91c388ff03cca2
2,525
ex
Elixir
lib/sbom.ex
TraceyOnim/sbom
55ee8867d4c7f53b6e282a8aad584435c82d5379
[ "BSD-3-Clause" ]
null
null
null
lib/sbom.ex
TraceyOnim/sbom
55ee8867d4c7f53b6e282a8aad584435c82d5379
[ "BSD-3-Clause" ]
null
null
null
lib/sbom.ex
TraceyOnim/sbom
55ee8867d4c7f53b6e282a8aad584435c82d5379
[ "BSD-3-Clause" ]
1
2020-11-16T21:20:18.000Z
2020-11-16T21:20:18.000Z
defmodule SBoM do @moduledoc """ Collect dependency information for use in a Software Bill-of-Materials (SBOM). """ alias SBoM.Purl alias SBoM.Cpe @doc """ Builds a SBoM for the current Mix project. The result can be exported to CycloneDX XML format using the `SBoM.CycloneDX` module. Pass an environment of `nil` to include dependencies across all environments. Wrap the call to this function with `Mix.Project.in_project/3,4` to select a Mix project by path. """ def components_for_project(environment \\ :prod) do Mix.Project.get!() {deps, not_ok} = Mix.Dep.load_on_environment(env: environment) |> Enum.split_with(&ok?/1) case not_ok do [] -> components = deps |> Enum.map(&component_from_dep/1) |> Enum.reject(&is_nil/1) {:ok, components} _ -> {:error, :unresolved_dependency} end end defp ok?(dep) do Mix.Dep.ok?(dep) || Mix.Dep.compilable?(dep) end defp component_from_dep(%{opts: opts} = dep) do case Map.new(opts) do %{optional: true} -> # If the dependency is optional at the top level, then we don't include # it in the SBoM nil opts_map -> component_from_dep(dep, opts_map) end end defp component_from_dep(%{scm: Hex.SCM}, opts) do %{hex: name, lock: lock, dest: dest} = opts version = elem(lock, 2) sha256 = elem(lock, 3) hex_metadata_path = Path.expand("hex_metadata.config", dest) metadata = case :file.consult(hex_metadata_path) do {:ok, metadata} -> metadata _ -> [] end {_, description} = List.keyfind(metadata, "description", 0) {_, licenses} = List.keyfind(metadata, "licenses", 0, {"licenses", []}) %{ type: "library", name: name, version: version, purl: Purl.hex(name, version, opts[:repo]), cpe: Cpe.hex(name, version, opts[:repo]), hashes: %{ "SHA-256" => sha256 }, description: description, licenses: licenses } end defp component_from_dep(%{scm: Mix.SCM.Git, app: app}, opts) do %{git: git, lock: lock, dest: _dest} = opts version = case opts[:tag] do nil -> elem(lock, 2) tag -> tag end %{ type: "library", name: to_string(app), version: version, purl: Purl.git(to_string(app), git, version), licenses: [] } end defp component_from_dep(_dep, _opts), do: nil end
23.598131
80
0.592871
f77ec0e29a49a6528c68f1667200e07bae326952
2,570
ex
Elixir
lib/livebook.ex
kianmeng/livebook
8fe8d27d3d46b64d22126d1b97157330b87e611c
[ "Apache-2.0" ]
null
null
null
lib/livebook.ex
kianmeng/livebook
8fe8d27d3d46b64d22126d1b97157330b87e611c
[ "Apache-2.0" ]
null
null
null
lib/livebook.ex
kianmeng/livebook
8fe8d27d3d46b64d22126d1b97157330b87e611c
[ "Apache-2.0" ]
null
null
null
defmodule Livebook do @moduledoc """ Livebook is an interactive notebook system for Elixir. This module includes the public API. """ @doc """ Executes Livebook's config/runtime.exs. If you use Livebook as a dependency, you can add the following to your `config/runtime.exs` to trigger Livebook's config/runtime.exs configuration: Livebook.config_runtime() """ def config_runtime do import Config config :livebook, LivebookWeb.Endpoint, secret_key_base: Livebook.Config.secret!("LIVEBOOK_SECRET_KEY_BASE") || Base.encode64(:crypto.strong_rand_bytes(48)) if port = Livebook.Config.port!("LIVEBOOK_PORT") do config :livebook, LivebookWeb.Endpoint, http: [port: port] end if ip = Livebook.Config.ip!("LIVEBOOK_IP") do config :livebook, LivebookWeb.Endpoint, http: [ip: ip] end if password = Livebook.Config.password!("LIVEBOOK_PASSWORD") do config :livebook, authentication_mode: :password, password: password else config :livebook, token: Livebook.Utils.random_id() end if runtime = Livebook.Config.default_runtime!("LIVEBOOK_DEFAULT_RUNTIME") do config :livebook, :default_runtime, runtime end config :livebook, :cookie, Livebook.Config.cookie!("LIVEBOOK_COOKIE") || Livebook.Config.cookie!("RELEASE_COOKIE") || Livebook.Utils.random_cookie() root_path = Livebook.Config.root_path!("LIVEBOOK_ROOT_PATH") |> Livebook.FileSystem.Utils.ensure_dir_path() local_file_system = Livebook.FileSystem.Local.new(default_path: root_path) configured_file_systems = Livebook.Config.file_systems!("LIVEBOOK_FILE_SYSTEM_") config :livebook, :file_systems, [local_file_system | configured_file_systems] end @doc """ Parses the given Live Markdown document and converts it to Elixir source code. ## Limitations Note that the resulting script may not compile in some cases, for example if you define a macro in one cell and import it in another cell, it works fine in Livebook, because each cell is compiled separately. However, when running the script it gets compiled as a whole and consequently doing so doesn't work. Additionally, branching sections are commented out. """ @spec live_markdown_to_elixir(String.t()) :: String.t() def live_markdown_to_elixir(markdown) do {notebook, _messages} = Livebook.LiveMarkdown.Import.notebook_from_markdown(markdown) Livebook.Notebook.Export.Elixir.notebook_to_elixir(notebook) end end
32.125
89
0.719844
f77ec366697498c8c0cdd1ecbb4de006d71081e1
1,656
ex
Elixir
apps/idris_mix/lib/idris/mix/build.ex
vic/elixir_idris
3b5401700f528b05c45615c36076567b3587d982
[ "Apache-2.0" ]
2
2018-04-03T08:55:32.000Z
2018-12-15T23:09:11.000Z
apps/idris_mix/lib/idris/mix/build.ex
vic/elixir_idris
3b5401700f528b05c45615c36076567b3587d982
[ "Apache-2.0" ]
null
null
null
apps/idris_mix/lib/idris/mix/build.ex
vic/elixir_idris
3b5401700f528b05c45615c36076567b3587d982
[ "Apache-2.0" ]
null
null
null
defmodule Idris.Mix.Build do @moduledoc false alias Idris.Mix.Idris def compile(args) do config = Mix.Project.config() codegen = List.keyfind(config, :idris_codegen, 0) main = List.keyfind(config, :idris_main, 0) || List.keyfind(config, :idris_ipkg, 0) compile(main, codegen, args, config) end defp compile({:idris_main, main_file}, {:idris_codegen, codegen}, args, config) do compile_main_file(main_file, codegen, args, config) end defp compile_main_file(main_file, codegen, args, config) do {cg_name, cg_opts} = codegen cg = String.to_existing_atom("idris_codegen_#{cg_name}") {idris, cg_opts} = Idris.executable_from_opts(cg_opts) args = Enum.concat([cg_opts, deps_paths(config), args, [main_file]]) args = args |> Idris.opts_to_argv() |> cg.opts Idris.print_verbose_info(idris, args, {"idr", [main_file]}, true) env = Idris.env_prepend_path(cg.bin_path) Idris.run_with_callback(idris, &cg.run/1, args: args, env: env, cd: File.cwd!()) end defp deps_paths(config) do config[:deps] |> Enum.flat_map(&dep_path(&1, config)) end defp dep_path(dep, config) do deps_path = config[:deps_path] [name | rest] = dep |> Tuple.to_list() case Enum.reverse(rest) do [opts | _] when is_list(opts) -> cond do opts[:idris] == :source && opts[:path] -> path = Path.expand(opts[:path]) [idrispath: path] opts[:idris] == :source -> path = Path.expand(to_string(name), deps_path) [idrispath: path] :else -> [] end _ -> [] end end end
27.147541
87
0.621981
f77ee047dd0a919607b02deed221e7f765c6a9b4
3,084
ex
Elixir
lib/optimus/option.ex
corka149/optimus
12c0dc597691d04481513f4e2345812e38e63f73
[ "MIT" ]
null
null
null
lib/optimus/option.ex
corka149/optimus
12c0dc597691d04481513f4e2345812e38e63f73
[ "MIT" ]
null
null
null
lib/optimus/option.ex
corka149/optimus
12c0dc597691d04481513f4e2345812e38e63f73
[ "MIT" ]
null
null
null
defmodule Optimus.Option do defstruct [ :name, :value_name, :short, :long, :help, :multiple, :required, :default, :parser, :global, :hide ] def new(spec) do Optimus.Option.Builder.build(spec) end def parse(option, parsed, command_line) when length(command_line) > 0 do case parse_option_parts(option, command_line) do {:ok, raw_value, rest} -> key = {:option, option.name} if option.multiple || !Map.has_key?(parsed, key) do case option.parser.(raw_value) do {:ok, value} -> {:ok, Map.update(parsed, key, [value], &[value | &1]), rest} {:error, reason} -> {:error, "invalid value #{inspect(raw_value)} for #{Optimus.Format.format_in_error(option)} option: #{reason}", rest} end else {:error, "multiple occurrences of option #{Optimus.Format.format_in_error(option)}", rest} end :skip -> :skip end end def parse(_, _, _), do: :skip defp parse_option_parts(option, [item | items]) do case extract_value(option, item) do {:ok, value} -> {:ok, value, items} :none -> case items do [value_item | rest] -> if item == option.long or item == option.short do {:ok, value_item, rest} else :skip end _ -> :skip end end end defp extract_value(option, str) do if option.long do length = String.length(option.long) + 1 if option.long <> "=" == String.slice(str, 0..(length - 1)) do {:ok, String.slice(str, length..-1)} else :none end else :none end end def try_match([option | options], parsed, items) do case parse(option, parsed, items) do :skip -> try_match(options, parsed, items) value -> value end end def try_match([], _, _), do: :skip end defimpl Optimus.Format, for: Optimus.Option do def format(option) do [option.short, option.long] |> Enum.reject(&is_nil/1) |> Enum.join(", ") end def format_in_error(option) do case {option.long, option.short} do {long, nil} -> long {nil, short} -> short {long, short} -> "#{long}(#{short})" end end def format_in_usage(option) do option_name = option.long || option.short if option.required do "#{option_name} #{option.value_name}" else "[#{option_name} #{option.value_name}]" end end def help(option) do help_string = option.help || "" if option.default do default_value_string = if is_list(option.default) do option.default |> Enum.map(&to_s/1) |> inspect else to_s(option.default) end "#{help_string} (default: #{default_value_string})" else help_string end end def to_s(term) do if String.Chars.impl_for(term) do to_string(term) else inspect(term) end end end
21.87234
117
0.553502
f77eee15b6997e47c6e71437381461dbcf15cc77
329
exs
Elixir
config/config.exs
FloatingGhost/ex_aws_secrets
3a6be2867e042fdc4937ad5db2a07c72476340ad
[ "MIT" ]
null
null
null
config/config.exs
FloatingGhost/ex_aws_secrets
3a6be2867e042fdc4937ad5db2a07c72476340ad
[ "MIT" ]
null
null
null
config/config.exs
FloatingGhost/ex_aws_secrets
3a6be2867e042fdc4937ad5db2a07c72476340ad
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config config :ex_aws, access_key_id: [{:system, "AWS_ACCESS_KEY_ID"}, :instance_role], secret_access_key: [{:system, "AWS_SECRET_ACCESS_KEY"}, :instance_role] import_config "#{Mix.env()}.exs"
32.9
73
0.759878
f77ef17dabfb4567a890fbe01019362cdd3de0fd
1,051
exs
Elixir
05/part1.exs
seantanly/elixir-advent_of_code
1e39ac46bc01f5c8cffd2d2f79f9af0b71767291
[ "MIT" ]
3
2016-01-18T01:14:45.000Z
2017-05-11T09:14:49.000Z
05/part1.exs
seantanly/elixir-advent_of_code
1e39ac46bc01f5c8cffd2d2f79f9af0b71767291
[ "MIT" ]
null
null
null
05/part1.exs
seantanly/elixir-advent_of_code
1e39ac46bc01f5c8cffd2d2f79f9af0b71767291
[ "MIT" ]
null
null
null
defmodule NiceString do def at_least_3_vowels?(str) do str |> String.split("", trim: true) |> Enum.reduce(0, fn letter, acc -> if letter in ~w(a e i o u), do: acc + 1, else: acc end) >= 3 end def letter_appear_twice?(str), do: letter_appear_twice?(String.split(str, "", trim: true), nil) def letter_appear_twice?([], _), do: false def letter_appear_twice?([h | t], prev) do if h == prev, do: true, else: letter_appear_twice?(t, h) end def contains_bad_strings?(str) do ~w(ab cd pq xy) |> Enum.any?(&String.contains?(str, &1)) end def nice?(str) do with true <- NiceString.at_least_3_vowels?(str), true <- NiceString.letter_appear_twice?(str), false <- NiceString.contains_bad_strings?(str) do :ok end |> case do :ok -> true _ -> false end end end result = Path.join(__DIR__, "input.txt") |> File.read! |> String.split("\n", trim: true) |> Enum.reduce(0, fn(str, acc) -> if NiceString.nice?(str), do: acc + 1, else: acc end) |> IO.inspect ^result = 238
25.634146
97
0.618459
f77f0da5909de39bcd0926afc4976ecaaf3682e5
491
ex
Elixir
lib/sandwar_web/views/error_view.ex
DarkMarmot/sandwar
48d5a4b18e313b055f93088355fb0cf6685c836c
[ "Apache-2.0" ]
6
2019-08-30T17:40:40.000Z
2020-11-10T18:59:27.000Z
lib/sandwar_web/views/error_view.ex
DarkMarmot/sandwar
48d5a4b18e313b055f93088355fb0cf6685c836c
[ "Apache-2.0" ]
2
2021-03-09T12:39:20.000Z
2021-05-10T02:44:45.000Z
lib/sandwar_web/views/error_view.ex
DarkMarmot/sandwar
48d5a4b18e313b055f93088355fb0cf6685c836c
[ "Apache-2.0" ]
null
null
null
defmodule SandwarWeb.ErrorView do use SandwarWeb, :view # If you want to customize a particular status code # for a certain format, you may uncomment below. # def render("500.html", _assigns) do # "Internal Server Error" # end # By default, Phoenix returns the status message from # the template name. For example, "404.html" becomes # "Not Found". def template_not_found(template, _assigns) do Phoenix.Controller.status_message_from_template(template) end end
28.882353
61
0.735234
f77f24518fec915e08d5a2592ea002252bebe884
4,317
exs
Elixir
test/chat_api/conversations_test.exs
sladyn98/papercups
3b17ccc4c974ac6e16c9962a576e64a832dafdb9
[ "MIT" ]
null
null
null
test/chat_api/conversations_test.exs
sladyn98/papercups
3b17ccc4c974ac6e16c9962a576e64a832dafdb9
[ "MIT" ]
null
null
null
test/chat_api/conversations_test.exs
sladyn98/papercups
3b17ccc4c974ac6e16c9962a576e64a832dafdb9
[ "MIT" ]
null
null
null
defmodule ChatApi.ConversationsTest do use ChatApi.DataCase, async: true alias ChatApi.{Conversations, SlackConversationThreads} describe "conversations" do alias ChatApi.Conversations.Conversation alias ChatApi.SlackConversationThreads.SlackConversationThread @valid_attrs %{status: "open"} @update_attrs %{status: "closed"} @invalid_attrs %{status: nil} def valid_create_attrs do account = account_fixture() Enum.into(@valid_attrs, %{account_id: account.id}) end setup do account = account_fixture() customer = customer_fixture(account) conversation = conversation_fixture(account, customer) {:ok, account: account, conversation: conversation} end test "list_conversations/0 returns all conversations", %{ conversation: conversation } do result_ids = Enum.map(Conversations.list_conversations(), fn r -> r.id end) assert result_ids == [conversation.id] end test "list_conversations_by_account/1 returns all conversations for an account", %{ account: account, conversation: conversation } do different_account = account_fixture() different_customer = customer_fixture(different_account) _conversation = conversation_fixture(different_account, different_customer) result_ids = Enum.map(Conversations.list_conversations_by_account(account.id), & &1.id) assert result_ids == [conversation.id] end test "get_conversation!/1 returns the conversation with given id", %{ conversation: conversation } do assert Conversations.get_conversation!(conversation.id) == conversation end test "create_conversation/1 with valid data creates a conversation" do assert {:ok, %Conversation{} = conversation} = Conversations.create_conversation(valid_create_attrs()) assert conversation.status == "open" end test "create_conversation/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Conversations.create_conversation(@invalid_attrs) end test "update_conversation/2 with valid data updates the conversation", %{ conversation: conversation } do assert {:ok, %Conversation{} = conversation} = Conversations.update_conversation(conversation, @update_attrs) assert conversation.status == "closed" end test "update_conversation/2 with invalid data returns error changeset", %{ conversation: conversation } do assert {:error, %Ecto.Changeset{}} = Conversations.update_conversation(conversation, @invalid_attrs) assert conversation = Conversations.get_conversation!(conversation.id) end test "delete_conversation/1 deletes the conversation", %{conversation: conversation} do assert {:ok, %Conversation{}} = Conversations.delete_conversation(conversation) assert_raise Ecto.NoResultsError, fn -> Conversations.get_conversation!(conversation.id) end end test "delete_conversation/1 deletes the conversation if associated slack_conversation_threads exist", %{conversation: conversation} do assert {:ok, %Conversation{} = conversation} = Conversations.create_conversation(valid_create_attrs()) slack_conversation_thread_attrs = %{ slack_channel: "some slack_channel", slack_thread_ts: "some slack_thread_ts", conversation_id: conversation.id, account_id: valid_create_attrs().account_id } assert {:ok, %SlackConversationThread{} = slack_conversation_thread} = SlackConversationThreads.create_slack_conversation_thread( slack_conversation_thread_attrs ) assert {:ok, %Conversation{}} = Conversations.delete_conversation(conversation) assert_raise Ecto.NoResultsError, fn -> Conversations.get_conversation!(conversation.id) end assert_raise Ecto.NoResultsError, fn -> SlackConversationThreads.get_slack_conversation_thread!(slack_conversation_thread.id) end end test "change_conversation/1 returns a conversation changeset", %{conversation: conversation} do assert %Ecto.Changeset{} = Conversations.change_conversation(conversation) end end end
35.385246
105
0.712532
f77f4b881de1f7d1edd0e8e274fb5c334d2cd809
1,041
ex
Elixir
lib/hello_phoenix/endpoint.ex
victusfate/hello_phoenix
8a63878e5317386c693a214d4db836f9128621d2
[ "MIT" ]
null
null
null
lib/hello_phoenix/endpoint.ex
victusfate/hello_phoenix
8a63878e5317386c693a214d4db836f9128621d2
[ "MIT" ]
null
null
null
lib/hello_phoenix/endpoint.ex
victusfate/hello_phoenix
8a63878e5317386c693a214d4db836f9128621d2
[ "MIT" ]
null
null
null
defmodule HelloPhoenix.Endpoint do use Phoenix.Endpoint, otp_app: :hello_phoenix socket "/socket", HelloPhoenix.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: :hello_phoenix, gzip: false, only: ~w(css fonts images js favicon.ico robots.txt) # Code reloading can be explicitly enabled under the # :code_reloader configuration of your endpoint. if code_reloading? do socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket plug Phoenix.LiveReloader plug Phoenix.CodeReloader end plug Plug.RequestId plug Plug.Logger plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Poison plug Plug.MethodOverride plug Plug.Head plug Plug.Session, store: :cookie, key: "_hello_phoenix_key", signing_salt: "tq+VMl+r" plug HelloPhoenix.Router end
26.025
69
0.716619
f77f762fe1acf6acaed0ed64a4977f9d115f7a18
1,803
ex
Elixir
lib/phoenix_ecto/check_repo_status.ex
Jcambass/phoenix_ecto
d0bed6522ef286feb14bd00019c406acf5670002
[ "MIT" ]
null
null
null
lib/phoenix_ecto/check_repo_status.ex
Jcambass/phoenix_ecto
d0bed6522ef286feb14bd00019c406acf5670002
[ "MIT" ]
null
null
null
lib/phoenix_ecto/check_repo_status.ex
Jcambass/phoenix_ecto
d0bed6522ef286feb14bd00019c406acf5670002
[ "MIT" ]
null
null
null
defmodule Phoenix.Ecto.CheckRepoStatus do @moduledoc """ A plug that does some checks on your application repos. Checks if the storage is up (database is created) or if there are any pending migrations. Both checks can raise an error if the conditions are not met. ## Plug options * `:otp_app` - name of the application which the repos are fetched from """ @behaviour Plug alias Plug.Conn def init(opts) do Keyword.fetch!(opts, :otp_app) opts end def call(%Conn{} = conn, opts) do repos = Application.get_env(opts[:otp_app], :ecto_repos, []) for repo <- repos, Process.whereis(repo) do check_storage_up!(repo) check_pending_migrations!(repo, opts) end conn end defp check_storage_up!(repo) do try do adapter = repo.__adapter__() if Code.ensure_loaded?(adapter) && function_exported?(adapter, :storage_status, 1) do adapter.storage_status(repo.config()) end rescue _ -> :ok else :down -> raise Phoenix.Ecto.StorageNotCreatedError, repo: repo _ -> :ok end end defp check_pending_migrations!(repo, opts) do try do # If the dependency `ecto_sql` is not loaded we can't check if # there are pending migrations so we try to fail gracefully here fallback_get_migrations = if Code.ensure_loaded?(Ecto.Migrator), do: &Ecto.Migrator.migrations/1, else: fn _repo -> [] end get_migrations = Keyword.get(opts, :get_migrations_function, fallback_get_migrations) repo |> get_migrations.() |> Enum.any?(fn {status, _version, _migration} -> status == :down end) rescue _ -> :ok else true -> raise Phoenix.Ecto.PendingMigrationError, repo: repo false -> :ok end end end
25.394366
91
0.655019
f77fc80819638ec805033aecb7afce07a8864714
15,985
ex
Elixir
clients/compute/lib/google_api/compute/v1/api/region_ssl_certificates.ex
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/api/region_ssl_certificates.ex
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/api/region_ssl_certificates.ex
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Compute.V1.Api.RegionSslCertificates do @moduledoc """ API calls for all endpoints tagged `RegionSslCertificates`. """ alias GoogleApi.Compute.V1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Deletes the specified SslCertificate resource in the region. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `region` (*type:* `String.t`) - Name of the region scoping this request. * `ssl_certificate` (*type:* `String.t`) - Name of the SslCertificate resource to delete. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec compute_region_ssl_certificates_delete( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def compute_region_ssl_certificates_delete( connection, project, region, ssl_certificate, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/{project}/regions/{region}/sslCertificates/{sslCertificate}", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "region" => URI.encode(region, &URI.char_unreserved?/1), "sslCertificate" => URI.encode(ssl_certificate, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}]) end @doc """ Returns the specified SslCertificate resource in the specified region. Get a list of available SSL certificates by making a list() request. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `region` (*type:* `String.t`) - Name of the region scoping this request. * `ssl_certificate` (*type:* `String.t`) - Name of the SslCertificate resource to return. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.SslCertificate{}}` on success * `{:error, info}` on failure """ @spec compute_region_ssl_certificates_get( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.SslCertificate.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def compute_region_ssl_certificates_get( connection, project, region, ssl_certificate, 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}/regions/{region}/sslCertificates/{sslCertificate}", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "region" => URI.encode(region, &URI.char_unreserved?/1), "sslCertificate" => URI.encode(ssl_certificate, &(URI.char_unreserved?(&1) || &1 == ?/)) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.SslCertificate{}]) end @doc """ Creates a SslCertificate resource in the specified project and region using the data included in the request ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `region` (*type:* `String.t`) - Name of the region scoping this request. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). * `:body` (*type:* `GoogleApi.Compute.V1.Model.SslCertificate.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec compute_region_ssl_certificates_insert( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def compute_region_ssl_certificates_insert( connection, project, region, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :requestId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{project}/regions/{region}/sslCertificates", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "region" => URI.encode(region, &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.Compute.V1.Model.Operation{}]) end @doc """ Retrieves the list of SslCertificate resources available to the specified project in the specified region. ## Parameters * `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server * `project` (*type:* `String.t`) - Project ID for this request. * `region` (*type:* `String.t`) - Name of the region scoping this request. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`. For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`. You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ``` * `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`) * `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by `name` or `creationTimestamp desc` is supported. * `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Compute.V1.Model.SslCertificateList{}}` on success * `{:error, info}` on failure """ @spec compute_region_ssl_certificates_list( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Compute.V1.Model.SslCertificateList.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def compute_region_ssl_certificates_list( connection, project, region, 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}/regions/{region}/sslCertificates", %{ "project" => URI.encode(project, &URI.char_unreserved?/1), "region" => URI.encode(region, &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.Compute.V1.Model.SslCertificateList{}]) end end
49.33642
434
0.650109
f77fceb6c622a1858268c6dc43800c6a92d4d4bd
2,052
ex
Elixir
lib/quantum/cluster_task_supervisor_registry.ex
fatboypunk/quantum-core
f264e1c5d6b0e13e60f0920ae09c287f342b9d7c
[ "Apache-2.0" ]
null
null
null
lib/quantum/cluster_task_supervisor_registry.ex
fatboypunk/quantum-core
f264e1c5d6b0e13e60f0920ae09c287f342b9d7c
[ "Apache-2.0" ]
null
null
null
lib/quantum/cluster_task_supervisor_registry.ex
fatboypunk/quantum-core
f264e1c5d6b0e13e60f0920ae09c287f342b9d7c
[ "Apache-2.0" ]
null
null
null
defmodule Quantum.ClusterTaskSupervisorRegistry do @moduledoc false # Provide means to find all nodes running the task registry use GenServer alias __MODULE__.{InitOpts, StartOpts, State} @doc false @spec start_link(StartOpts.t()) :: GenServer.on_start() def start_link(%StartOpts{name: name} = opts) do GenServer.start_link( __MODULE__, struct!( InitOpts, opts |> Map.take([:task_supervisor_reference, :group_name]) |> Map.put_new(:group_name, Module.concat(name, Group)) ), name: name ) end @doc false @impl true def init(%InitOpts{task_supervisor_reference: task_supervisor, group_name: group_name}) do task_supervisor_pid = GenServer.whereis(task_supervisor) monitor_ref = Process.monitor(task_supervisor_pid) # TODO: Find better way without poluting the atom table :yes = Swarm.register_name( Module.concat(group_name, :"#{inspect(make_ref())}"), task_supervisor_pid ) :ok = Swarm.join(group_name, task_supervisor_pid) {:ok, %State{ group_name: group_name, task_supervisor_pid: task_supervisor_pid, monitor_ref: monitor_ref }} end @doc false @impl true def handle_call(:pids, _from, %State{group_name: group_name} = state) do {:reply, Swarm.members(group_name), state} end @doc false @impl true def handle_info( {:DOWN, monitor_ref, :process, task_supervisor_pid, _reason}, %State{ group_name: group_name, task_supervisor_pid: task_supervisor_pid, monitor_ref: monitor_ref } = state ) do Swarm.leave(group_name, task_supervisor_pid) {:stop, :terminate, state} end @doc false # Retrieve pids running the linked gen server def pids(server \\ __MODULE__) do GenServer.call(server, :pids) end @doc false # Retrieve pids running the linked gen server def nodes(server \\ __MODULE__) do server |> pids |> Enum.map(&node/1) |> Enum.uniq() end end
24.722892
92
0.663255
f77fd6c23dba8fab58fa1dc00a88d5a86bc3d9be
1,113
exs
Elixir
2017/day_05/ex/config/config.exs
nicbet/advent-of-code
a44a16c777081bdc9fabdfee72541a95c291ef18
[ "MIT" ]
null
null
null
2017/day_05/ex/config/config.exs
nicbet/advent-of-code
a44a16c777081bdc9fabdfee72541a95c291ef18
[ "MIT" ]
null
null
null
2017/day_05/ex/config/config.exs
nicbet/advent-of-code
a44a16c777081bdc9fabdfee72541a95c291ef18
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :ex, key: :value # # and access this configuration in your application as: # # Application.get_env(:ex, :key) # # You can also configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs"
35.903226
73
0.749326
f77fe91681260ed1b6a7d0f992baac5473145bc5
3,644
ex
Elixir
web/ex_admin/errors_helper.ex
devonestes/ex_admin
e135ae7c28de78fc87baf519ff8a32da12e8bf66
[ "MIT" ]
1,347
2015-10-05T18:23:49.000Z
2022-01-09T18:38:36.000Z
web/ex_admin/errors_helper.ex
fanduel/ex_admin
05806a718859a0e155d3447c3ffde8a536fd676a
[ "MIT" ]
402
2015-10-03T13:53:32.000Z
2021-07-08T09:52:22.000Z
web/ex_admin/errors_helper.ex
fanduel/ex_admin
05806a718859a0e155d3447c3ffde8a536fd676a
[ "MIT" ]
333
2015-10-12T22:56:57.000Z
2021-05-26T18:40:24.000Z
defmodule ExAdmin.ErrorsHelper do @moduledoc """ The primary purpose of this module is to take nested changeset errors created by many_to_many and has many through relationships and change them into a format that the forms can use to get the error message from the field name. Changes sets such as: #Ecto.Changeset<action: nil, changes: %{phone_numbers: [#Ecto.Changeset<action: :update, changes: %{}, errors: [], data: #ContactDemo.PhoneNumber<>, valid?: true>, #Ecto.Changeset<action: :update, changes: %{}, errors: [number: {"can't be blank", []}], data: #ContactDemo.PhoneNumber<>, valid?: false>, #Ecto.Changeset<action: :insert, changes: %{label: "Primary Phone"}, errors: [number: {"can't be blank", []}], data: #ContactDemo.PhoneNumber<>, valid?: false>]}, errors: [], data: #ContactDemo.Contact<>, valid?: false> need to be walked and each of the error messages needs to be flattened into its appropriately namespaced verison. To do this we need both the changeset and the schema used to generate the changeset. This is required because we need to look at the schema to properly create the neccesary form field names. For example, many_to_many association have attributes appended to the field name so that we know it is a many to many field. """ def create_errors(changeset, schema) do assoc_prefixes = create_prefix_map(schema) flatten_errors(changeset, assoc_prefixes) |> List.flatten |> Enum.filter(fn(x) -> x != nil end) end defp flatten_errors(errors_array, assoc_prefixes, prefix \\ nil) defp flatten_errors(%Ecto.Changeset{changes: changes, errors: errors}, assoc_prefixes, prefix) when errors == [] or is_nil(prefix) do changes = Enum.reject(changes, fn({_,v}) -> is_struct(v) end) |> Enum.into(%{}) errors ++ flatten_errors(changes, assoc_prefixes, prefix) end defp flatten_errors(%Ecto.Changeset{changes: changes, errors: errors}, assoc_prefixes, prefix) do Enum.map(errors, fn({k, v}) -> {concat_atoms(prefix, k), v} end) ++ flatten_errors(changes, assoc_prefixes, prefix) end defp flatten_errors(errors_array, assoc_prefixes, prefix) when is_list(errors_array) do Enum.with_index(errors_array) |> Enum.map(fn({x, i}) -> prefix = concat_atoms(prefix, String.to_atom(Integer.to_string(i))) flatten_errors(x, assoc_prefixes, prefix) end) end defp flatten_errors(%{__struct__: _struct}, _, _), do: nil defp flatten_errors(%{} = errors_map, assoc_prefixes, prefix) do Enum.map(errors_map, fn({k, x}) -> with k <- if(not is_atom(k), do: String.to_atom(k), else: k), k <- if(Keyword.has_key?(assoc_prefixes, k), do: concat_atoms(k, assoc_prefixes[k]), else: k), k <- if(prefix != nil, do: concat_atoms(prefix, k), else: k), do: flatten_errors(x, assoc_prefixes, k) end) end defp flatten_errors(_, _, _), do: nil defp concat_atoms(first, second) do "#{first}_#{second}" |> String.to_atom end defp create_prefix_map(schema) do schema.__schema__(:associations) |> Enum.map(&(schema.__schema__(:association, &1))) |> Enum.map(fn(a) -> case a do %Ecto.Association.HasThrough{field: field} -> { field, :attributes } %Ecto.Association.Has{field: field} -> { field, :attributes } %Ecto.Association.ManyToMany{field: field} -> { field, :attributes } _ -> nil end end) end defp is_struct(%{__struct__: _}), do: true defp is_struct(_), do: false end
40.043956
135
0.660538
f77ff9a9e9bbb4d68378b15acbc94beacd0d945e
9,501
ex
Elixir
lib/membrane_aac_fdk_plugin/encoder.ex
membraneframework/membrane_aac_fdk_plugin
8ae1cb60db82f4115cc167f08486d04164b7007b
[ "Apache-2.0" ]
null
null
null
lib/membrane_aac_fdk_plugin/encoder.ex
membraneframework/membrane_aac_fdk_plugin
8ae1cb60db82f4115cc167f08486d04164b7007b
[ "Apache-2.0" ]
2
2021-08-10T14:27:58.000Z
2021-08-10T14:58:25.000Z
lib/membrane_aac_fdk_plugin/encoder.ex
membraneframework/membrane_aac_fdk_plugin
8ae1cb60db82f4115cc167f08486d04164b7007b
[ "Apache-2.0" ]
null
null
null
defmodule Membrane.AAC.FDK.Encoder do @moduledoc """ Element encoding raw audio into AAC format """ use Membrane.Filter use Bunch.Typespec alias __MODULE__.Native alias Membrane.Buffer alias Membrane.Caps.Audio.Raw alias Membrane.Caps.Matcher use Membrane.Log, tags: :membrane_aac_fdk_plugin # AAC Constants @sample_size 2 @default_channels 2 @default_sample_rate 44_100 # MPEG-4 AAC Low Complexity @default_audio_object_type :mpeg4_lc @list_type allowed_channels :: [1, 2] @list_type allowed_aots :: [ :mpeg4_lc, :mpeg4_he, :mpeg4_he_v2, :mpeg2_lc, :mpeg2_he ] @list_type allowed_sample_rates :: [ 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000 ] @list_type allowed_bitrate_modes :: [0, 1, 2, 3, 4, 5] @supported_caps {Raw, format: :s16le, channels: Matcher.one_of(@allowed_channels), sample_rate: Matcher.one_of(@allowed_sample_rates)} def_options aot: [ description: """ Audio object type. See: https://github.com/mstorsjo/fdk-aac/blob/master/libAACenc/include/aacenc_lib.h#L1280 2: MPEG-4 AAC Low Complexity. 5: MPEG-4 AAC Low Complexity with Spectral Band Replication (HE-AAC). 29: MPEG-4 AAC Low Complexity with Spectral Band Replication and Parametric Stereo (HE-AAC v2). This configuration can be used only with stereo input audio data. 129: MPEG-2 AAC Low Complexity. 132: MPEG-2 AAC Low Complexity with Spectral Band Replication (HE-AAC). """, type: :atom, spec: allowed_aots(), default: @default_audio_object_type ], bitrate_mode: [ description: """ Bitrate Mode. See: http://wiki.hydrogenaud.io/index.php?title=Fraunhofer_FDK_AAC#Bitrate_Modes 0 - Constant Bitrate (default). 1-5 - Variable Bitrate """, type: :integer, spec: allowed_bitrate_modes(), default: 0 ], bitrate: [ description: """ Bitrate in bits/s for CBR. If set to nil (default value), the bitrate will be estimated based on the number of channels and sample rate. See: https://trac.ffmpeg.org/wiki/Encode/AAC#fdk_cbr Note that for VBR this parameter is ignored. """, type: :integer, spec: pos_integer() | nil, default: nil ], input_caps: [ description: """ Caps for the input pad. If set to nil (default value), caps are assumed to be received through the pad. If explicitly set to some caps, they cannot be changed by caps received through the pad. """, type: :caps, spec: Raw.t() | nil, default: nil ] def_output_pad :output, caps: :any def_input_pad :input, demand_unit: :bytes, caps: @supported_caps @impl true def handle_init(options) do state = options |> Map.from_struct() |> Map.merge(%{ native: nil, queue: <<>> }) {:ok, state} end @impl true def handle_stopped_to_prepared(_ctx, %{input_caps: nil} = state), do: {:ok, state} def handle_stopped_to_prepared(_ctx, state) do input_caps = Map.merge( %Raw{format: :s16le, channels: @default_channels, sample_rate: @default_sample_rate}, state.input_caps ) with {:ok, native} <- mk_native( input_caps.channels, input_caps.sample_rate, state.aot, state.bitrate_mode, state.bitrate ) do {:ok, %{state | native: native, input_caps: input_caps}} else {:error, reason} -> {{:error, reason}, state} end end @impl true def handle_prepared_to_stopped(_ctx, state) do {:ok, %{state | native: nil}} end @impl true def handle_demand(:output, size, :bytes, _ctx, state) do {{:ok, demand: {:input, size}}, state} end @impl true def handle_demand(:output, bufs, :buffers, _ctx, state) do {{:ok, demand: {:input, aac_frame_size(state.aot) * bufs}}, state} end @impl true def handle_caps(:input, caps, _ctx, %{input_caps: input_caps} = state) when input_caps in [nil, caps] do with {:ok, native} <- mk_native( caps.channels, caps.sample_rate, state.aot, state.bitrate_mode, state.bitrate ) do {:ok, %{state | native: native, input_caps: caps}} else {:error, reason} -> {{:error, reason}, state} end end def handle_caps(:input, caps, _ctx, %{input_caps: stored_caps}) do raise """ Received caps #{inspect(caps)} are different than defined in options #{inspect(stored_caps)}. If you want to allow converter to accept different input caps dynamically, use `nil` as input_caps. """ end @impl true def handle_process_list(:input, buffers, _ctx, state) do %{native: native, queue: queue} = state data = buffers |> Enum.map(& &1.payload) to_encode = [queue | data] |> IO.iodata_to_binary() raw_frame_size = aac_frame_size(state.aot) * state.input_caps.channels * @sample_size with {:ok, {encoded_buffers, bytes_used}} when bytes_used > 0 <- encode_buffer(to_encode, native, raw_frame_size) do <<_handled::binary-size(bytes_used), rest::binary>> = to_encode buffer_actions = [buffer: {:output, encoded_buffers}] {{:ok, buffer_actions ++ [redemand: :output]}, %{state | queue: rest}} else {:ok, {[], 0}} -> {:ok, %{state | queue: to_encode}} {:error, reason} -> {{:error, reason}, state} end end @impl true def handle_end_of_stream(:input, _ctx, state) do %{native: native, queue: queue} = state if queue != <<>>, do: warn("Processing queue is not empty, but EndOfStream event was received") actions = [end_of_stream: :output, notify: {:end_of_stream, :input}] with {:ok, encoded_frame} <- Native.encode_frame(<<>>, native) do buffer_actions = [buffer: {:output, %Buffer{payload: encoded_frame}}] {{:ok, buffer_actions ++ actions}, state} else {:error, :no_data} -> {{:ok, actions}, state} {:error, reason} -> {{:error, reason}, state} end end defp encode_buffer(buffer, native, raw_frame_size, acc \\ [], bytes_used \\ 0) # Encode a single frame if buffer contains at least one frame defp encode_buffer(buffer, native, raw_frame_size, acc, bytes_used) when byte_size(buffer) >= raw_frame_size do <<raw_frame::binary-size(raw_frame_size), rest::binary>> = buffer with {:ok, encoded_frame} <- Native.encode_frame(raw_frame, native) do encoded_buffer = %Buffer{payload: encoded_frame} # Continue encoding the rest until no more frames are available in the queue encode_buffer( rest, native, raw_frame_size, [encoded_buffer | acc], bytes_used + raw_frame_size ) else {:error, reason} -> {:error, reason} end end # Not enough samples for a frame defp encode_buffer(_partial_buffer, _native, _raw_frame_size, acc, bytes_used) do # Return accumulated encoded frames {:ok, {acc |> Enum.reverse(), bytes_used}} end defp mk_native(channels, sample_rate, aot, bitrate_mode, bitrate) do with {:ok, channels} <- validate_channels(channels), {:ok, sample_rate} <- validate_sample_rate(sample_rate), {:ok, aot} <- map_aot_to_value(aot), {:ok, bitrate_mode} <- validate_bitrate_mode(bitrate_mode), {:ok, native} <- Native.create( channels, sample_rate, aot, bitrate_mode, bitrate || 0 ) do {:ok, native} else {:error, reason} -> {:error, reason} end end # Frame size is 2 times larger for HE profiles. defp aac_frame_size(aot) when aot in [:mpeg4_he, :mpeg4_he_v2, :mpeg2_he], do: 2048 defp aac_frame_size(_), do: 1024 # Options validators defp map_aot_to_value(:mpeg4_lc), do: {:ok, 2} defp map_aot_to_value(:mpeg4_he), do: {:ok, 5} defp map_aot_to_value(:mpeg4_he_v2), do: {:ok, 29} defp map_aot_to_value(:mpeg2_lc), do: {:ok, 129} defp map_aot_to_value(:mpeg2_he), do: {:ok, 132} defp map_aot_to_value(_), do: {:error, :invalid_aot} defp validate_channels(channels) when channels in @allowed_channels, do: {:ok, channels} defp validate_channels(_), do: {:error, :invalid_channels} defp validate_sample_rate(sample_rate) when sample_rate in @allowed_sample_rates, do: {:ok, sample_rate} defp validate_sample_rate(_), do: {:error, :invalid_sample_rate} defp validate_bitrate_mode(bitrate_mode) when bitrate_mode in @allowed_bitrate_modes, do: {:ok, bitrate_mode} defp validate_bitrate_mode(_), do: {:error, :invalid_bitrate_mode} end
32.316327
177
0.591517
f77ffb011d759fb1ac21fdfc1f4227a88552a000
412
exs
Elixir
test/absinthe/integration/execution/input_object_test.exs
TheRealReal/absinthe
6eae5bc36283e58f42d032b8afd90de3ad64f97b
[ "MIT" ]
2
2021-04-22T23:45:04.000Z
2021-05-07T01:01:15.000Z
test/absinthe/integration/execution/input_object_test.exs
TheRealReal/absinthe
6eae5bc36283e58f42d032b8afd90de3ad64f97b
[ "MIT" ]
1
2019-09-23T21:26:01.000Z
2019-09-23T21:26:01.000Z
test/absinthe/integration/execution/input_object_test.exs
TheRealReal/absinthe
6eae5bc36283e58f42d032b8afd90de3ad64f97b
[ "MIT" ]
null
null
null
defmodule Elixir.Absinthe.Integration.Execution.InputObjectTest do use Absinthe.Case, async: true @query """ mutation { updateThing(id: "foo", thing: {value: 100}) { name value } } """ test "scenario #1" do assert {:ok, %{data: %{"updateThing" => %{"name" => "Foo", "value" => 100}}}} == Absinthe.run(@query, Absinthe.Fixtures.Things.MacroSchema, []) end end
22.888889
84
0.589806
f77ffdd088be9c0b78a89d82e3eb1e30aff4eca1
312
exs
Elixir
priv/repo/migrations/20151224093233_create_board.exs
gridgentoo/ElixirTrelloKanban
11b91d9d864d2e332a94838d43c7a9b1015e17c6
[ "MIT" ]
2,784
2016-01-06T03:16:07.000Z
2022-03-14T03:52:20.000Z
priv/repo/migrations/20151224093233_create_board.exs
gridgentoo/ElixirTrelloKanban
11b91d9d864d2e332a94838d43c7a9b1015e17c6
[ "MIT" ]
49
2016-01-07T11:48:10.000Z
2020-04-27T16:10:12.000Z
priv/repo/migrations/20151224093233_create_board.exs
gridgentoo/ElixirTrelloKanban
11b91d9d864d2e332a94838d43c7a9b1015e17c6
[ "MIT" ]
586
2016-01-11T17:02:13.000Z
2021-12-01T10:54:47.000Z
defmodule PhoenixTrello.Repo.Migrations.CreateBoard do use Ecto.Migration def change do create table(:boards) do add :name, :string, null: false add :user_id, references(:users, on_delete: :delete_all), null: false timestamps end create index(:boards, [:user_id]) end end
19.5
75
0.682692
f780011b0a67d98fa4f7c4b8edc057ffe8749885
700
exs
Elixir
exercism/elixir/scrabble-score/scrabble.exs
GimliLongBow/exercises
e06517eacccd37a889c5d68a702de7ffb7f4bf37
[ "MIT" ]
2
2017-05-19T18:31:38.000Z
2017-05-19T18:31:41.000Z
exercism/elixir/scrabble-score/scrabble.exs
GimliLongBow/exercises
e06517eacccd37a889c5d68a702de7ffb7f4bf37
[ "MIT" ]
null
null
null
exercism/elixir/scrabble-score/scrabble.exs
GimliLongBow/exercises
e06517eacccd37a889c5d68a702de7ffb7f4bf37
[ "MIT" ]
null
null
null
defmodule Scrabble do @letter_values %{ "a" => 1, "b" => 3, "c" => 3, "d" => 2, "e" => 1, "f" => 4, "g" => 2, "h" => 4, "i" => 1, "j" => 8, "k" => 5, "l" => 1, "m" => 3, "n" => 1, "o" => 1, "p" => 3, "q" => 10, "r" => 1, "s" => 1, "t" => 1, "u" => 1, "v" => 4, "w" => 1, "x" => 8, "y" => 4, "z" => 10 } @doc """ Calculate the scrabble score for the word. """ @spec score(String.t) :: non_neg_integer def score(word) do word |> String.downcase |> String.trim |> String.split("", trim: true) |> Enum.reduce(0, fn(x, acc) -> acc + @letter_values[x] end) end end
16.27907
64
0.37
f78013a9cdac9fcc71e8287ba1cbd68230de2bcb
910
ex
Elixir
lib/openflow/echo/reply.ex
shun159/tres
1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f
[ "Beerware" ]
5
2019-05-25T02:25:13.000Z
2020-10-06T17:00:03.000Z
lib/openflow/echo/reply.ex
shun159/tres
1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f
[ "Beerware" ]
5
2018-03-29T14:42:10.000Z
2019-11-19T07:03:09.000Z
lib/openflow/echo/reply.ex
shun159/tres
1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f
[ "Beerware" ]
1
2019-03-30T20:48:27.000Z
2019-03-30T20:48:27.000Z
defmodule Openflow.Echo.Reply do defstruct( version: 4, xid: 0, data: "", # virtual field datapath_id: nil, # virtual field aux_id: 0 ) alias __MODULE__ @type t :: %Reply{ version: 4, xid: 0..0xFFFFFFFF, data: String.t(), datapath_id: String.t() | nil, aux_id: 0..0xFFFF | nil } @spec ofp_type :: 3 def ofp_type, do: 3 @spec new(xid: 0..0xFFFFFFFF, data: String.t()) :: t() def new(options) when is_list(options) do %Reply{ xid: options[:xid] || 0, data: options[:data] || "" } end @spec new(String.t()) :: t() def new(data) when is_binary(data), do: %Reply{data: data} @spec new() :: t() def new, do: new([]) @spec read(String.t()) :: t() def read(data), do: %Reply{data: data} @spec to_binary(t()) :: String.t() def to_binary(%Reply{data: data}), do: data end
20.222222
60
0.545055
f7802d198143dad90b534f09c0fca65881cc133c
257
ex
Elixir
lib/phoenix_elm.ex
ejpcmac/phoenix_elm
cc43a2253610728fbf2db9bd87b5341e82a27e5e
[ "BSD-3-Clause" ]
null
null
null
lib/phoenix_elm.ex
ejpcmac/phoenix_elm
cc43a2253610728fbf2db9bd87b5341e82a27e5e
[ "BSD-3-Clause" ]
null
null
null
lib/phoenix_elm.ex
ejpcmac/phoenix_elm
cc43a2253610728fbf2db9bd87b5341e82a27e5e
[ "BSD-3-Clause" ]
null
null
null
defmodule PhoenixElm do @moduledoc """ PhoenixElm 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.7
66
0.758755
f7807cf3de552a108c65af2d9cff00760c0cfe7a
385
exs
Elixir
priv/repo/migrations/20210227015756_create_user_table.exs
librity/nlw_elixir
09476067f0695014705af0480dd60894f9e0a6d8
[ "MIT" ]
1
2021-02-26T17:31:13.000Z
2021-02-26T17:31:13.000Z
priv/repo/migrations/20210227015756_create_user_table.exs
librity/nlw_elixir
09476067f0695014705af0480dd60894f9e0a6d8
[ "MIT" ]
null
null
null
priv/repo/migrations/20210227015756_create_user_table.exs
librity/nlw_elixir
09476067f0695014705af0480dd60894f9e0a6d8
[ "MIT" ]
null
null
null
defmodule Rocketpay.Repo.Migrations.CreateUserTable do use Ecto.Migration def change do create table :users do add :name, :string add :nickname, :string add :email, :string add :password_hash, :string add :age, :integer timestamps() end create unique_index(:users, [:email]) create unique_index(:users, [:nickname]) end end
20.263158
54
0.651948
f7809dbd53b330894135659785461593b22e73d2
128
exs
Elixir
scripts/s3_log_sync.exs
findmypast/hexfmp
38a50f5e1057833fd98748faac230bf4b9cc26a3
[ "Apache-2.0" ]
null
null
null
scripts/s3_log_sync.exs
findmypast/hexfmp
38a50f5e1057833fd98748faac230bf4b9cc26a3
[ "Apache-2.0" ]
null
null
null
scripts/s3_log_sync.exs
findmypast/hexfmp
38a50f5e1057833fd98748faac230bf4b9cc26a3
[ "Apache-2.0" ]
null
null
null
File.mkdir("logs") Hexpm.Utils.shell(~s(aws s3 cp s3://logs.hex.pm logs --recursive --exclude "*" --include "hex/2016-01-27*"))
42.666667
108
0.664063
f780a10ffe0dc8ab29a1ece8bec74023f4eaaec7
476
exs
Elixir
priv/repo/migrations/20161124143407_add_stops_table.exs
tjefferson08/frizzle-server
8db3f31e4dae6583603fd2006415129f623827ba
[ "MIT" ]
null
null
null
priv/repo/migrations/20161124143407_add_stops_table.exs
tjefferson08/frizzle-server
8db3f31e4dae6583603fd2006415129f623827ba
[ "MIT" ]
null
null
null
priv/repo/migrations/20161124143407_add_stops_table.exs
tjefferson08/frizzle-server
8db3f31e4dae6583603fd2006415129f623827ba
[ "MIT" ]
null
null
null
defmodule Frizzle.Repo.Migrations.AddStopsTable do use Ecto.Migration def up do create table(:stops, primary_key: false) do add :stop_id, :integer, null: false, primary_key: true add :stop_name, :string, null: false add :stop_desc, :string, null: false end execute("SELECT AddGeometryColumn ('stops','location',4326,'POINT',2);") create index(:stops, :location, using: :gist) end def down do drop table(:stops) end end
26.444444
77
0.668067
f780b1f641bdca4612dfb2ed4843ef6dd80b7e1d
2,650
ex
Elixir
lib/cabishop/checkout.ex
gremly/cabishop
d5c1188ce6237ff671f2b98525b3ae7a0accad12
[ "MIT" ]
null
null
null
lib/cabishop/checkout.ex
gremly/cabishop
d5c1188ce6237ff671f2b98525b3ae7a0accad12
[ "MIT" ]
null
null
null
lib/cabishop/checkout.ex
gremly/cabishop
d5c1188ce6237ff671f2b98525b3ae7a0accad12
[ "MIT" ]
null
null
null
defmodule CabiShop.CheckoutSupervisor do @moduledoc """ Supervises shop orders. This supervisor allows to create one process for checkout order. """ use Supervisor # Client API def start_link(args) do Supervisor.start_link(__MODULE__, args, name: __MODULE__) end # Supervisor Callbacks def init(_args) do children = [{CabiShop.Checkout, restart: :transient}] opts = [strategy: :simple_one_for_one] Supervisor.init(children, opts) end end defmodule CabiShop.Checkout do @moduledoc """ This is a process responsible to manage a sale, adding products to the cart and computing price rules defined by product. """ use GenServer alias CabiShop.{Product, Discount} @supervisor CabiShop.CheckoutSupervisor # Client API @doc "Creates a checkout order ready to scan products." def start do Supervisor.start_child(@supervisor, []) end @doc "Finishes the checkout and turns off the current server." def finish(server) do GenServer.cast(server, :finish) end @doc """ Allows to add products to the current order. It validates if thereis a product identified with the given code. If succed returns the atom :ok, otherwise returns the atom :product_unavailable. """ def scan(server, code) do GenServer.call(server, {:scan, code}) end @doc "Returns the total value of the order with discounts applied." def total(server) do GenServer.call(server, :total) end def start_link(args) do GenServer.start_link(__MODULE__, args) end # GenServer callbacks def init(_args) do {:ok, %{products: Map.new()}} end def handle_call({:scan, code}, _from, %{products: products} = state) do {result, products} = add_product(code, products) {:reply, result, %{state| products: products}} end def handle_call(:total, _from, %{products: products} = state) do {:reply, totalize(products), state} end def handle_cast(:finish, state) do {:stop, :normal, state} end # Internal Functions defp add_product(code, products) do case product_exists?(code) do true -> {:ok, checkout_product(code, products)} false -> {:product_unavailable, products} end end defp checkout_product(code, products) do case Map.get(products, code) do nil -> Map.put(products, code, 1) qty -> Map.put(products, code, qty + 1) end end defp product_exists?(code) do Product.get(code) != nil end defp totalize(products) do Enum.reduce(products, 0, fn({code, qty}, acc) -> code |> Product.get() |> Discount.apply(qty) |> Kernel.+(acc) end) end end
22.844828
73
0.678868
f780b52754ba2577091863072769e67185f4fc6d
869
ex
Elixir
apps/admin_app/lib/admin_app_web/views/data_helpers.ex
gridgentoo/avia
139b68f4b3ccd830c4db296d81132680e253b731
[ "MIT" ]
null
null
null
apps/admin_app/lib/admin_app_web/views/data_helpers.ex
gridgentoo/avia
139b68f4b3ccd830c4db296d81132680e253b731
[ "MIT" ]
null
null
null
apps/admin_app/lib/admin_app_web/views/data_helpers.ex
gridgentoo/avia
139b68f4b3ccd830c4db296d81132680e253b731
[ "MIT" ]
null
null
null
defmodule AdminAppWeb.DataHelpers do @moduledoc """ Provides view related data. """ alias Snitch.Data.Model.State, as: StateModel alias Snitch.Data.Model.Country, as: CountryModel alias Snitch.Data.Model.Role, as: RoleModel alias Snitch.Data.Model.Permission @doc """ Creates formatted data to be used in dropdown selection for association in forms. return => [{display name, value}, ...] passed to like => <%= select_input f, :country_id, formated_list(:country) %> Can also be used elsewhere. """ def formatted_list(:state), do: StateModel.formatted_list() def formatted_list(:country), do: CountryModel.formatted_list() def formatted_list(:role), do: RoleModel.formatted_list() def formatted_list(:permissions), do: Permission.formatted_list() def formatted_list(country_id), do: StateModel.formatted_state_list(country_id) end
37.782609
83
0.747986
f780d46db01c41fec9a7a1a5928a7768808a5f9f
1,596
exs
Elixir
config/config.exs
trusty/elixir_google_spreadsheets
b7f74d75e61027dc0b12aa5260168563d0777c92
[ "MIT" ]
null
null
null
config/config.exs
trusty/elixir_google_spreadsheets
b7f74d75e61027dc0b12aa5260168563d0777c92
[ "MIT" ]
null
null
null
config/config.exs
trusty/elixir_google_spreadsheets
b7f74d75e61027dc0b12aa5260168563d0777c92
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. import Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :mongo_ecto, key: :value # # And access this configuration in your application as: # # Application.get_env(:mongo_ecto, :key) # # Or configure a 3rd-party app: # # config :logger, level: :info # # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # config :elixir_google_spreadsheets, json: "./config/service_account.json" |> File.read!() config :elixir_google_spreadsheets, max_rows_per_request: 301, default_column_from: 1, default_column_to: 26 config :elixir_google_spreadsheets, :client, request_workers: 50, max_demand: 100, max_interval: :timer.minutes(1), interval: 100, result_timeout: :timer.minutes(10), request_opts: [ timeout: :timer.seconds(8), recv_timeout: :timer.seconds(5) ] import_config "#{Mix.env()}.exs"
31.92
73
0.75
f780f40ae2edc7ab9b70e69968c78762d29974bf
10,180
ex
Elixir
lib/elixir/lib/port.ex
mattmatters/elixir
e0d1c2e4cae0277e69fec086b92d82f13d2aa033
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/port.ex
mattmatters/elixir
e0d1c2e4cae0277e69fec086b92d82f13d2aa033
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/port.ex
mattmatters/elixir
e0d1c2e4cae0277e69fec086b92d82f13d2aa033
[ "Apache-2.0" ]
null
null
null
defmodule Port do @moduledoc ~S""" Functions for interacting with the external world through ports. Ports provide a mechanism to start operating system processes external to the Erlang VM and communicate with them via message passing. ## Example iex> port = Port.open({:spawn, "cat"}, [:binary]) iex> send(port, {self(), {:command, "hello"}}) iex> send(port, {self(), {:command, "world"}}) iex> flush() {#Port<0.1444>, {:data, "hello"}} {#Port<0.1444>, {:data, "world"}} iex> send(port, {self(), :close}) :ok iex> flush() {#Port<0.1464>, :closed} :ok In the example above, we have created a new port that executes the program `cat`. `cat` is a program available on UNIX systems that receives data from multiple inputs and concatenates them in the output. After the port was created, we sent it two commands in the form of messages using `Kernel.send/2`. The first command has the binary payload of "hello" and the second has "world". After sending those two messages, we invoked the IEx helper `flush()`, which printed all messages received from the port, in this case we got "hello" and "world" back. Notice the messages are in binary because we passed the `:binary` option when opening the port in `Port.open/2`. Without such option, it would have yielded a list of bytes. Once everything was done, we closed the port. Elixir provides many conveniences for working with ports and some drawbacks. We will explore those below. ## Message and function APIs There are two APIs for working with ports. It can be either asynchronous via message passing, as in the example above, or by calling the functions on this module. The messages supported by ports and their counterpart function APIs are listed below: * `{pid, {:command, binary}}` - sends the given data to the port. See `command/3`. * `{pid, :close}` - closes the port. Unless the port is already closed, the port will reply with `{port, :closed}` message once it has flushed its buffers and effectively closed. See `close/1`. * `{pid, {:connect, new_pid}}` - sets the `new_pid` as the new owner of the port. Once a port is opened, the port is linked and connected to the caller process and communication to the port only happens through the connected process. This message makes `new_pid` the new connected processes. Unless the port is dead, the port will reply to the old owner with `{port, :connected}`. See `connect/2`. On its turn, the port will send the connected process the following messages: * `{port, {:data, data}}` - data sent by the port * `{port, :closed}` - reply to the `{pid, :close}` message * `{port, :connected}` - reply to the `{pid, {:connect, new_pid}}` message * `{:EXIT, port, reason}` - exit signals in case the port crashes. If reason is not `:normal`, this message will only be received if the owner process is trapping exits ## Open mechanisms The port can be opened through four main mechanisms. As a short summary, prefer to using the `:spawn` and `:spawn_executable` options mentioned below. The other two options, `:spawn_driver` and `:fd` are for advanced usage within the VM. Also consider using `System.cmd/3` if all you want is to execute a program and retrieve its return value. ### spawn The `:spawn` tuple receives a binary that is going to be executed as a full invocation. For example, we can use it to invoke "echo hello" directly: iex> port = Port.open({:spawn, "echo hello"}, [:binary]) iex> flush() {#Port<0.1444>, {:data, "hello\n"}} `:spawn` will retrieve the program name from the argument and traverse your OS `$PATH` environment variable looking for a matching program. Although the above is handy, it means it is impossible to invoke an executable that has whitespaces on its name or in any of its arguments. For those reasons, most times it is preferable to execute `:spawn_executable`. ### spawn_executable Spawn executable is a more restricted and explicit version of spawn. It expects full file paths to the executable you want to execute. If they are in your `$PATH`, they can be retrieved by calling `System.find_executable/1`: iex> path = System.find_executable("echo") iex> port = Port.open({:spawn_executable, path}, [:binary, args: ["hello world"]]) iex> flush() {#Port<0.1380>, {:data, "hello world\n"}} When using `:spawn_executable`, the list of arguments can be passed via the `:args` option as done above. For the full list of options, see the documentation for the Erlang function `:erlang.open_port/2`. ### fd The `:fd` name option allows developers to access `in` and `out` file descriptors used by the Erlang VM. You would use those only if you are reimplementing core part of the Runtime System, such as the `:user` and `:shell` processes. ## Zombie OS processes A port can be closed via the `close/1` function or by sending a `{pid, :close}` message. However, if the VM crashes, a long-running program started by the port will have its stdin and stdout channels closed but **it won't be automatically terminated**. While most UNIX command line tools will exit once its communication channels are closed, not all command line applications will do so. While we encourage graceful termination by detecting if stdin/stdout has been closed, we do not always have control over how 3rd party software terminates. In those cases, you can wrap the application in a script that checks for stdin. Here is such script in Bash: #!/bin/bash "$@" & pid=$! while read line ; do : done kill -KILL $pid Now instead of: Port.open( {:spawn_executable, "/path/to/program"}, args: ["a", "b", "c"] ) You may invoke: Port.open( {:spawn_executable, "/path/to/wrapper"}, args: ["/path/to/program", "a", "b", "c"] ) """ @type name :: {:spawn, charlist | binary} | {:spawn_driver, charlist | binary} | {:spawn_executable, charlist | atom} | {:fd, non_neg_integer, non_neg_integer} @doc """ Opens a port given a tuple `name` and a list of `options`. The module documentation above contains documentation and examples for the supported `name` values, summarized below: * `{:spawn, command}` - runs an external program. `command` must contain the program name and optionally a list of arguments separated by space. If passing programs or arguments with space in their name, use the next option. * `{:spawn_executable, filename}` - runs the executable given by the absolute file name `filename`. Arguments can be passed via the `:args` option. * `{:spawn_driver, command}` - spawns so-called port drivers. * `{:fd, fd_in, fd_out}` - accesses file descriptors, `fd_in` and `fd_out` opened by the VM. For more information and the list of options, see `:erlang.open_port/2`. Inlined by the compiler. """ @spec open(name, list) :: port def open(name, options) do :erlang.open_port(name, options) end @doc """ Closes the `port`. For more information, see `:erlang.port_close/1`. Inlined by the compiler. """ @spec close(port) :: true def close(port) do :erlang.port_close(port) end @doc """ Sends `data` to the port driver `port`. For more information, see `:erlang.port_command/2`. Inlined by the compiler. """ @spec command(port, iodata, [:force | :nosuspend]) :: boolean def command(port, data, options \\ []) do :erlang.port_command(port, data, options) end @doc """ Associates the `port` identifier with a `pid`. For more information, see `:erlang.port_connect/2`. Inlined by the compiler. """ @spec connect(port, pid) :: true def connect(port, pid) do :erlang.port_connect(port, pid) end @doc """ Returns information about the `port` or `nil` if the port is closed. For more information, see `:erlang.port_info/1`. """ def info(port) do nillify(:erlang.port_info(port)) end @doc """ Returns information about the `port` or `nil` if the port is closed. For more information, see `:erlang.port_info/2`. """ @spec info(port, atom) :: {atom, term} | nil def info(port, spec) def info(port, :registered_name) do case :erlang.port_info(port, :registered_name) do :undefined -> nil [] -> {:registered_name, []} other -> other end end def info(port, item) do nillify(:erlang.port_info(port, item)) end @doc """ Starts monitoring the given `port` from the calling process. Once the monitored port process dies, a message is delivered to the monitoring process in the shape of: {:DOWN, ref, :port, object, reason} where: * `ref` is a monitor reference returned by this function; * `object` is either the `port` being monitored (when monitoring by port id) or `{name, node}` (when monitoring by a port name); * `reason` is the exit reason. See `:erlang.monitor/2` for more info. Inlined by the compiler. """ @doc since: "1.6.0" @spec monitor(port | {name, node} | name) :: reference when name: atom def monitor(port) do :erlang.monitor(:port, port) end @doc """ Demonitors the monitor identified by the given `reference`. If `monitor_ref` is a reference which the calling process obtained by calling `monitor/1`, that monitoring is turned off. If the monitoring is already turned off, nothing happens. See `:erlang.demonitor/2` for more info. Inlined by the compiler. """ @doc since: "1.6.0" @spec demonitor(reference, options :: [:flush | :info]) :: boolean defdelegate demonitor(monitor_ref, options \\ []), to: :erlang @doc """ Returns a list of all ports in the current node. Inlined by the compiler. """ @spec list :: [port] def list do :erlang.ports() end @compile {:inline, nillify: 1} defp nillify(:undefined), do: nil defp nillify(other), do: other end
33.159609
88
0.675049
f781179b5788391dfd7764ada7643283182af4b0
138
ex
Elixir
debian/menu.ex
mikeyb/GameCredits
4c1844a3ffecfbd222ee68cbac1f1fc7ec2072e5
[ "MIT", "Unlicense" ]
12
2016-09-02T22:48:17.000Z
2022-01-07T03:00:20.000Z
debian/menu.ex
mikeyb/GameCredits
4c1844a3ffecfbd222ee68cbac1f1fc7ec2072e5
[ "MIT", "Unlicense" ]
1
2018-04-04T04:38:58.000Z
2021-04-13T02:39:22.000Z
debian/menu.ex
mikeyb/GameCredits
4c1844a3ffecfbd222ee68cbac1f1fc7ec2072e5
[ "MIT", "Unlicense" ]
5
2016-08-07T08:26:50.000Z
2020-10-11T20:45:44.000Z
?package(gamecredits):needs="X11|text|vc|wm" section="Applications/see-menu-manual"\ title="gamecredits" command="/usr/bin/gamecredits"
46
84
0.768116
f781260abbea70a8357b9f17ef13493d42a37d43
92
exs
Elixir
elixir/74.exs
merxer/kata
5dbbca8b4173029f9311398148de9437a329cf9a
[ "MIT" ]
null
null
null
elixir/74.exs
merxer/kata
5dbbca8b4173029f9311398148de9437a329cf9a
[ "MIT" ]
null
null
null
elixir/74.exs
merxer/kata
5dbbca8b4173029f9311398148de9437a329cf9a
[ "MIT" ]
null
null
null
fun1 = fn -> fn -> "Hello" end end fun1.() |> IO.inspect fun1.().() |> IO.inspect
9.2
24
0.48913
f7813abd745415105ced7d631c0f806900969a75
2,459
exs
Elixir
blinky/mix.exs
rob-brown/ElixirTraining2018
9724cc4961d767a1ba2450240e026b46ad5a0f1b
[ "MIT" ]
2
2018-02-01T22:56:09.000Z
2020-01-20T19:57:48.000Z
blinky/mix.exs
rob-brown/ElixirTraining2018
9724cc4961d767a1ba2450240e026b46ad5a0f1b
[ "MIT" ]
null
null
null
blinky/mix.exs
rob-brown/ElixirTraining2018
9724cc4961d767a1ba2450240e026b46ad5a0f1b
[ "MIT" ]
null
null
null
defmodule Blinky.MixProject do use Mix.Project @target System.get_env("MIX_TARGET") || "host" def project do [ app: :blinky, version: "0.1.0", elixir: "~> 1.4", target: @target, archives: [nerves_bootstrap: "~> 1.0.0"], deps_path: "deps/#{@target}", build_path: "_build/#{@target}", lockfile: "mix.lock.#{@target}", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, aliases: ["loadconfig": [&bootstrap/1]], deps: deps() ] end # Starting nerves_bootstrap adds the required aliases to Mix.Project.config() # Aliases are only added if MIX_TARGET is set. def bootstrap(args) do Application.start(:nerves_bootstrap) Mix.Task.run("loadconfig", args) end def application, do: application(@target) # Specify target specific application configurations # It is common that the application start function will start and supervise # applications which could cause the host to fail. Because of this, we only # invoke Blinky.start/2 when running on a target. def application("host") do [extra_applications: [:logger]] end def application(_target) do [mod: {Blinky.Application, []}, extra_applications: [:logger]] end defp deps do [{:nerves, "~> 1.0.0", runtime: false}] ++ deps(@target) end defp deps("host"), do: [] defp deps(target = "rpi0") do [ {:nerves_init_gadget, "~> 0.3.0"} ] ++ deps("all") ++ system(target) end defp deps(target) do [ {:shoehorn, "~> 0.2"}, {:nerves_runtime, "~> 0.4"}, {:poison, "~> 3.1.0"}, {:nerves_leds, "~> 0.8.0"}, {:nerves_network, "~> 0.3.0"} ] ++ system(target) end defp system("rpi"), do: [{:nerves_system_rpi, ">= 0.0.0", runtime: false}] defp system("rpi0"), do: [{:nerves_system_rpi0, ">= 0.0.0", runtime: false}] defp system("rpi2"), do: [{:nerves_system_rpi2, ">= 0.0.0", runtime: false}] defp system("rpi3"), do: [{:nerves_system_rpi3, ">= 0.0.0", runtime: false}] defp system("bbb"), do: [{:nerves_system_bbb, ">= 0.0.0", runtime: false}] defp system("ev3"), do: [{:nerves_system_ev3, ">= 0.0.0", runtime: false}] defp system("qemu_arm"), do: [{:nerves_system_qemu_arm, ">= 0.0.0", runtime: false}] defp system("x86_64"), do: [{:nerves_system_x86_64, ">= 0.0.0", runtime: false}] defp system("all"), do: [] defp system(target), do: Mix.raise "Unknown MIX_TARGET: #{target}" end
31.525641
86
0.616104
f78144aa91bebdc30401b1fd66518c4d9698267c
4,403
ex
Elixir
clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/model/company.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/model/company.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/android_device_provisioning/lib/google_api/android_device_provisioning/v1/model/company.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.AndroidDeviceProvisioning.V1.Model.Company do @moduledoc """ A reseller, vendor, or customer in the zero-touch reseller and customer APIs. ## Attributes * `adminEmails` (*type:* `list(String.t)`, *default:* `nil`) - Optional. Email address of customer's users in the admin role. Each email address must be associated with a Google Account. * `companyId` (*type:* `String.t`, *default:* `nil`) - Output only. The ID of the company. Assigned by the server. * `companyName` (*type:* `String.t`, *default:* `nil`) - Required. The name of the company. For example _XYZ Corp_. Displayed to the company's employees in the zero-touch enrollment portal. * `languageCode` (*type:* `String.t`, *default:* `nil`) - Input only. The preferred locale of the customer represented as a BCP47 language code. This field is validated on input and requests containing unsupported language codes will be rejected. Supported language codes: Arabic (ar) Chinese (Hong Kong) (zh-HK) Chinese (Simplified) (zh-CN) Chinese (Traditional) (zh-TW) Czech (cs) Danish (da) Dutch (nl) English (UK) (en-GB) English (US) (en-US) Filipino (fil) Finnish (fi) French (fr) German (de) Hebrew (iw) Hindi (hi) Hungarian (hu) Indonesian (id) Italian (it) Japanese (ja) Korean (ko) Norwegian (Bokmal) (no) Polish (pl) Portuguese (Brazil) (pt-BR) Portuguese (Portugal) (pt-PT) Russian (ru) Spanish (es) Spanish (Latin America) (es-419) Swedish (sv) Thai (th) Turkish (tr) Ukrainian (uk) Vietnamese (vi) * `name` (*type:* `String.t`, *default:* `nil`) - Output only. The API resource name of the company. The resource name is one of the following formats: * `partners/[PARTNER_ID]/customers/[CUSTOMER_ID]` * `partners/[PARTNER_ID]/vendors/[VENDOR_ID]` * `partners/[PARTNER_ID]/vendors/[VENDOR_ID]/customers/[CUSTOMER_ID]` Assigned by the server. * `ownerEmails` (*type:* `list(String.t)`, *default:* `nil`) - Required. Input only. Email address of customer's users in the owner role. At least one `owner_email` is required. Owners share the same access as admins but can also add, delete, and edit your organization's portal users. * `skipWelcomeEmail` (*type:* `boolean()`, *default:* `nil`) - Input only. If set to true, welcome email will not be sent to the customer. It is recommended to skip the welcome email if devices will be claimed with additional DEVICE_PROTECTION service, as the customer will receive separate emails at device claim time. This field is ignored if this is not a Zero-touch customer. * `termsStatus` (*type:* `String.t`, *default:* `nil`) - Output only. Whether any user from the company has accepted the latest Terms of Service (ToS). See TermsStatus. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :adminEmails => list(String.t()) | nil, :companyId => String.t() | nil, :companyName => String.t() | nil, :languageCode => String.t() | nil, :name => String.t() | nil, :ownerEmails => list(String.t()) | nil, :skipWelcomeEmail => boolean() | nil, :termsStatus => String.t() | nil } field(:adminEmails, type: :list) field(:companyId) field(:companyName) field(:languageCode) field(:name) field(:ownerEmails, type: :list) field(:skipWelcomeEmail) field(:termsStatus) end defimpl Poison.Decoder, for: GoogleApi.AndroidDeviceProvisioning.V1.Model.Company do def decode(value, options) do GoogleApi.AndroidDeviceProvisioning.V1.Model.Company.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AndroidDeviceProvisioning.V1.Model.Company do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
64.75
816
0.713377
f7815d3136df6fc7a4118c41dbcb3cf88eb6f71b
785
exs
Elixir
test/entitiex/options_test.exs
undr/entitiex
c6666909290b4077b47659ce11891659226e3b88
[ "MIT" ]
null
null
null
test/entitiex/options_test.exs
undr/entitiex
c6666909290b4077b47659ce11891659226e3b88
[ "MIT" ]
null
null
null
test/entitiex/options_test.exs
undr/entitiex
c6666909290b4077b47659ce11891659226e3b88
[ "MIT" ]
null
null
null
defmodule Entitiex.OptionsTest do use ExUnit.Case alias Entitiex.Options test "test" do assert(Options.merge([key1: :value2, key2: :value2], [key1: :value]) == [key2: :value2, key1: :value]) assert(Options.merge([format: :format1, key: :value], [format: :format2, key: :value2]) == [format: [:format1, :format2], key: :value2]) assert(Options.merge([format: [:format1], key: :value], [format: :format2, key: :value2]) == [format: [:format1, :format2], key: :value2]) assert(Options.merge([format: :format1, key: :value], [format: [:format2], key: :value2]) == [format: [:format1, :format2], key: :value2]) assert(Options.merge([format: [:format1], key: :value], [format: [:format2], key: :value2]) == [format: [:format1, :format2], key: :value2]) end end
56.071429
144
0.643312
f7815e7b6514193a2225e5e43b615d2ae8cd1cff
3,614
exs
Elixir
practica4/ServicioVistas/cliente_gv.exs
dmarcob/practicas1920_SSDD
8a3c0a428e21708102d840e7968009fa1cd0246a
[ "CC-BY-3.0" ]
null
null
null
practica4/ServicioVistas/cliente_gv.exs
dmarcob/practicas1920_SSDD
8a3c0a428e21708102d840e7968009fa1cd0246a
[ "CC-BY-3.0" ]
null
null
null
practica4/ServicioVistas/cliente_gv.exs
dmarcob/practicas1920_SSDD
8a3c0a428e21708102d840e7968009fa1cd0246a
[ "CC-BY-3.0" ]
null
null
null
Code.require_file("servidor_gv.exs", __DIR__) defmodule ClienteGV do @moduledoc """ modulo de un cliente de gestor de vistas funcionando como nodo """ # Constantes @tiempo_espera_de_respuesta 100 @doc """ Poner en marcha un nodo cliente del servicio de vistas Devolver atomo que referencia al nuevo nodo Elixir """ @spec startNodo(String.t(), String.t()) :: node def startNodo(nombre_nodo, host) do # fichero en curso NodoRemoto.start(nombre_nodo, host, __ENV__.file) end @doc """ Poner en marcha servicio trás esperar al pleno funcionamiento del nodo """ @spec startService(node, node) :: boolean def startService(nodoElixir, nodo_servidor_gv) do NodoRemoto.esperaNodoOperativo(nodoElixir, __MODULE__) # Poner en marcha la funcionalidad del cliente de gestor de vistas Node.spawn(nodoElixir, __MODULE__, :init_cl, [nodo_servidor_gv]) nodoElixir end @doc """ Solicitar al cliente que envie un latido al servidor de vistas """ @spec latido(node, integer) :: {ServidorGV.t_vista(), boolean} def latido(nodo_cliente, num_vista) do send({:cliente_gv, nodo_cliente}, {:envia_latido, num_vista, self()}) # esperar respuesta del latido receive do {:vista_tentativa, vista, is_ok?} -> {vista, is_ok?} after @tiempo_espera_de_respuesta -> {ServidorGV.vista_inicial(), false} end end @doc """ Solicitar al cliente que envie una petición de obtención de vista válida """ @spec obten_vista(atom) :: {ServidorGV.t_vista(), boolean} def obten_vista(nodo_cliente) do send({:cliente_gv, nodo_cliente}, {:obten_vista_valida, self()}) # esperar respuesta del latido receive do {:vista_valida, vista, is_ok?} -> {vista, is_ok?} after @tiempo_espera_de_respuesta -> {ServidorGV.vista_inicial(), false} # {%{num_vista: 0, primario: :pene, copia: :undefined}, true} end end @doc """ Solicitar al cliente que consiga el primario del servicio de vistas """ @spec primario(atom) :: node def primario(nodo_cliente) do resultado = obten_vista(nodo_cliente) case resultado do {vista, true} -> vista.primario {_vista, false} -> :undefined end end # ------------------ Funciones privadas def init_cl(nodo_servidor_gv) do Process.register(self(), :cliente_gv) bucle_recepcion(nodo_servidor_gv) end defp bucle_recepcion(nodo_servidor_gv) do receive do {:envia_latido, num_vista, pid_maestro} -> procesa_latido(nodo_servidor_gv, num_vista, pid_maestro) {:obten_vista_valida, pid_maestro} -> procesa_obten_vista(nodo_servidor_gv, pid_maestro) end bucle_recepcion(nodo_servidor_gv) end defp procesa_latido(nodo_servidor_gv, num_vista, pid_maestro) do send({:servidor_gv, nodo_servidor_gv}, {:latido, num_vista, Node.self()}) # esperar respuesta del latido receive do {:vista_tentativa, vista, encontrado?} -> send(pid_maestro, {:vista_tentativa, vista, encontrado?}) after @tiempo_espera_de_respuesta -> send(pid_maestro, {:vista_tentativa, ServidorGV.vista_inicial(), false}) end end defp procesa_obten_vista(nodo_servidor_gv, pid_maestro) do send({:servidor_gv, nodo_servidor_gv}, {:obten_vista_valida, self()}) receive do {:vista_valida, vista, coincide?} -> send(pid_maestro, {:vista_valida, vista, coincide?}) after @tiempo_espera_de_respuesta -> send(pid_maestro, {:vista_valida, ServidorGV.vista_inicial(), false}) end end end
28.456693
80
0.685667
f781996f474a461e0344df15a5699cae1e41db70
50
ex
Elixir
lib/web/views/session_view.ex
oestrich/grapevine-legacy
9d84f8e2d65dda5982686381ffa94a940142e1da
[ "MIT" ]
107
2018-10-05T18:20:32.000Z
2022-02-28T04:02:50.000Z
lib/web/views/session_view.ex
oestrich/grapevine-legacy
9d84f8e2d65dda5982686381ffa94a940142e1da
[ "MIT" ]
34
2019-03-06T17:53:29.000Z
2021-09-01T01:25:23.000Z
lib/web/views/session_view.ex
oestrich/grapevine-legacy
9d84f8e2d65dda5982686381ffa94a940142e1da
[ "MIT" ]
18
2019-02-03T03:08:20.000Z
2021-12-28T04:29:36.000Z
defmodule Web.SessionView do use Web, :view end
12.5
28
0.76
f781a7158faf97aadc79dbe2286c1ee6f3edd806
2,512
exs
Elixir
test/chat_api/conversations/helpers_test.exs
xprazak2/papercups
925e7c20ab868648e078a129e832856026c50424
[ "MIT" ]
1
2021-01-18T09:57:23.000Z
2021-01-18T09:57:23.000Z
test/chat_api/conversations/helpers_test.exs
xprazak2/papercups
925e7c20ab868648e078a129e832856026c50424
[ "MIT" ]
1
2021-01-17T10:42:34.000Z
2021-01-17T10:42:34.000Z
test/chat_api/conversations/helpers_test.exs
xprazak2/papercups
925e7c20ab868648e078a129e832856026c50424
[ "MIT" ]
null
null
null
defmodule ChatApi.Conversations.HelpersTest do use ChatApi.DataCase import ChatApi.Factory alias ChatApi.{Conversations, Conversations.Helpers} describe "ChatApi.Conversations.Helpers" do setup do account = insert(:account) customer = insert(:customer, account: account) conversation = insert(:conversation, account: account, customer: customer) {:ok, conversation: conversation, account: account, customer: customer} end test "send_conversation_state_update/2 sends a state update Slack when given a valid status or priority", %{conversation: conversation} do assert Helpers.send_conversation_state_update(conversation, %{"status" => "open"}) == {:ok, ":outbox_tray: This conversation has been reopened."} assert Helpers.send_conversation_state_update(conversation, %{"priority" => "priority"}) == {:ok, ":star: This conversation has been prioritized."} assert Helpers.send_conversation_state_update(conversation, %{"state" => "deleted"}) == {:ok, ":wastebasket: This conversation has been deleted."} end test "send_conversation_state_update/2 does not send an update to Slack when given an invalid status or priority", %{conversation: conversation} do assert Helpers.send_conversation_state_update(conversation, %{"status" => "BOOM"}) == {:error, "state_invalid"} assert Helpers.send_conversation_state_update(conversation, %{"priority" => "BOOM"}) == {:error, "state_invalid"} assert Helpers.send_conversation_state_update(conversation, %{"state" => "BOOM"}) == {:error, "state_invalid"} end test "send_multiple_archived_updates/2 sends archived updates to multiple conversations", %{account: account, customer: customer} do past = DateTime.add(DateTime.utc_now(), -:timer.hours(336)) insert_list(3, :conversation, %{ account: account, customer: customer, updated_at: past, status: "closed" }) archived_conversations = Conversations.query_conversations_closed_for(days: 14) assert Helpers.send_multiple_archived_updates(ChatApi.Repo.all(archived_conversations)) == [ ok: ":file_cabinet: This conversation has been archived.", ok: ":file_cabinet: This conversation has been archived.", ok: ":file_cabinet: This conversation has been archived." ] end end end
41.180328
118
0.673567
f781fb46c95962996978f50f4f3a88fb5310115b
445
exs
Elixir
priv/repo/migrations/one_institution/20200408204810_add_procedure_frequencies.exs
brownt23/crit19
c45c7b3ae580c193168d83144da0eeb9bc91c8a9
[ "MIT" ]
6
2019-07-16T19:31:23.000Z
2021-06-05T19:01:05.000Z
priv/repo/migrations/one_institution/20200408204810_add_procedure_frequencies.exs
brownt23/crit19
c45c7b3ae580c193168d83144da0eeb9bc91c8a9
[ "MIT" ]
null
null
null
priv/repo/migrations/one_institution/20200408204810_add_procedure_frequencies.exs
brownt23/crit19
c45c7b3ae580c193168d83144da0eeb9bc91c8a9
[ "MIT" ]
3
2020-02-24T23:38:27.000Z
2020-08-01T23:50:17.000Z
defmodule Crit.Repo.Migrations.AddProcedureFrequencies do use Ecto.Migration def change do create table(:procedure_frequencies) do add :name, :citext, null: false add :calculation_name, :string, null: false add :description, :text, null: false, default: "" end alter table(:procedures) do add :frequency_id, references(:procedure_frequencies, on_delete: :restrict), null: true end end end
26.176471
82
0.692135
f78226aebe4dc0d1e34ff06b8868c48875d414b4
2,524
ex
Elixir
clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_cloud_documentai_v1beta1_document_page_anchor_page_ref.ex
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "Apache-2.0" ]
null
null
null
clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_cloud_documentai_v1beta1_document_page_anchor_page_ref.ex
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "Apache-2.0" ]
null
null
null
clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_cloud_documentai_v1beta1_document_page_anchor_page_ref.ex
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "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.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageAnchorPageRef do @moduledoc """ Represents a weak reference to a page element within a document. ## Attributes * `boundingPoly` (*type:* `GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1BoundingPoly.t`, *default:* `nil`) - Optional. Identifies the bounding polygon of a layout element on the page. * `layoutId` (*type:* `String.t`, *default:* `nil`) - Optional. Deprecated. Use PageRef.bounding_poly instead. * `layoutType` (*type:* `String.t`, *default:* `nil`) - Optional. The type of the layout element that is being referenced if any. * `page` (*type:* `String.t`, *default:* `nil`) - Required. Index into the Document.pages element, for example using Document.pages to locate the related page element. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :boundingPoly => GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1BoundingPoly.t() | nil, :layoutId => String.t() | nil, :layoutType => String.t() | nil, :page => String.t() | nil } field(:boundingPoly, as: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1BoundingPoly ) field(:layoutId) field(:layoutType) field(:page) end defimpl Poison.Decoder, for: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageAnchorPageRef do def decode(value, options) do GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageAnchorPageRef.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiV1beta1DocumentPageAnchorPageRef do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.830769
205
0.737322
f78245c49ad18af0ea0db5cf7028516dcac733db
817
exs
Elixir
mix.exs
tanguilp/attribute_repository_riak
b4ad04c7b2e9d64e72193b1c3bcf9f738f3dd7fc
[ "Apache-2.0" ]
null
null
null
mix.exs
tanguilp/attribute_repository_riak
b4ad04c7b2e9d64e72193b1c3bcf9f738f3dd7fc
[ "Apache-2.0" ]
null
null
null
mix.exs
tanguilp/attribute_repository_riak
b4ad04c7b2e9d64e72193b1c3bcf9f738f3dd7fc
[ "Apache-2.0" ]
null
null
null
defmodule AttributeRepositoryRiak.MixProject do use Mix.Project def project do [ app: :attribute_repository_riak, version: "0.2.0", elixir: "~> 1.7", start_permanent: Mix.env() == :prod, deps: deps(), docs: [ main: "readme", extras: ["README.md"] ] ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:attribute_repository, github: "tanguilp/attribute_repository", tag: "v0.2.0"}, {:riak, github: "tanguilp/riak-elixir-client"}, {:dialyxir, "~> 1.0.0-rc.4", only: [:dev], runtime: false}, {:ex_doc, "~> 0.19", only: :dev, runtime: false} ] end end
23.342857
86
0.582619
f782683287f1570c18eb1ea832d50beca4fce9ea
831
ex
Elixir
lib/stix/object.ex
johnwunder/elixir-stix2
2b427694d45206acd556bf464de9fadd56095ba0
[ "MIT" ]
null
null
null
lib/stix/object.ex
johnwunder/elixir-stix2
2b427694d45206acd556bf464de9fadd56095ba0
[ "MIT" ]
null
null
null
lib/stix/object.ex
johnwunder/elixir-stix2
2b427694d45206acd556bf464de9fadd56095ba0
[ "MIT" ]
null
null
null
defmodule Stix.Object do @defaults %{creator_id: "identity--0f6532e2-7ed0-4614-9d2e-b99a27293a52"} def object(object_type, object_properties \\ %{}) do %{ type: object_type, id: Stix.id(object_type), created: Timex.format!(Timex.now, "{ISO:Extended:Z}"), modified: Timex.format!(Timex.now, "{ISO:Extended:Z}"), created_by_ref: Application.get_env(:stix, :creator_id) || @defaults.creator_id, spec_version: "2.1" } |> Map.merge(Enum.into(object_properties, %{})) |> Stix.Util.atomize() end def version(old_object, new_version) do old_object |> Map.put(:modified, Timex.format!(Timex.now, "{ISO:Extended:Z}")) |> Map.merge(Enum.into(new_version, %{})) end end
36.130435
96
0.576414
f78272b26c366e695ccc1b2f6e161a2d12f6a10f
79
ex
Elixir
chatourius/web/views/coherence/session_view.ex
Dmdv/ElixirPlayground
02d9e8a7fdd6e8742e200430debc9f0ec7fd28a1
[ "Apache-2.0" ]
null
null
null
chatourius/web/views/coherence/session_view.ex
Dmdv/ElixirPlayground
02d9e8a7fdd6e8742e200430debc9f0ec7fd28a1
[ "Apache-2.0" ]
null
null
null
chatourius/web/views/coherence/session_view.ex
Dmdv/ElixirPlayground
02d9e8a7fdd6e8742e200430debc9f0ec7fd28a1
[ "Apache-2.0" ]
null
null
null
defmodule Coherence.SessionView do use Chatourius.Coherence.Web, :view end
13.166667
37
0.797468
f782a07b70f966daca0b9a02614963440e82c8cb
10,582
exs
Elixir
lib/elixir/test/elixir/module/types/infer_test.exs
voltone/elixir
e208e1066e484c46726e4d931c18e54aba036f6e
[ "Apache-2.0" ]
null
null
null
lib/elixir/test/elixir/module/types/infer_test.exs
voltone/elixir
e208e1066e484c46726e4d931c18e54aba036f6e
[ "Apache-2.0" ]
null
null
null
lib/elixir/test/elixir/module/types/infer_test.exs
voltone/elixir
e208e1066e484c46726e4d931c18e54aba036f6e
[ "Apache-2.0" ]
null
null
null
Code.require_file("../../test_helper.exs", __DIR__) defmodule Module.Types.InferTest do use ExUnit.Case, async: true import Module.Types.Infer alias Module.Types defp unify_lift(left, right, context \\ new_context()) do unify(left, right, new_stack(), context) |> lift_result() end defp new_context() do Types.context("types_test.ex", TypesTest, {:test, 0}) end defp new_stack() do %{ Types.stack(:pattern) | last_expr: {:foo, [], nil} } end defp unify(left, right, context) do unify(left, right, new_stack(), context) end defp lift_result({:ok, type, context}) do {:ok, Types.lift_type(type, context)} end defp lift_result({:error, {Types, reason, location}}) do {:error, {reason, location}} end describe "unify/3" do test "literal" do assert unify_lift({:atom, :foo}, {:atom, :foo}) == {:ok, {:atom, :foo}} assert {:error, {{:unable_unify, {:atom, :foo}, {:atom, :bar}, _, _}, _}} = unify_lift({:atom, :foo}, {:atom, :bar}) end test "type" do assert unify_lift(:integer, :integer) == {:ok, :integer} assert unify_lift(:binary, :binary) == {:ok, :binary} assert unify_lift(:atom, :atom) == {:ok, :atom} assert unify_lift(:boolean, :boolean) == {:ok, :boolean} assert {:error, {{:unable_unify, :integer, :boolean, _, _}, _}} = unify_lift(:integer, :boolean) end test "subtype" do assert unify_lift(:boolean, :atom) == {:ok, :boolean} assert unify_lift(:atom, :boolean) == {:ok, :boolean} assert unify_lift(:boolean, {:atom, true}) == {:ok, {:atom, true}} assert unify_lift({:atom, true}, :boolean) == {:ok, {:atom, true}} assert unify_lift(:atom, {:atom, true}) == {:ok, {:atom, true}} assert unify_lift({:atom, true}, :atom) == {:ok, {:atom, true}} end test "tuple" do assert unify_lift({:tuple, []}, {:tuple, []}) == {:ok, {:tuple, []}} assert unify_lift({:tuple, [:integer]}, {:tuple, [:integer]}) == {:ok, {:tuple, [:integer]}} assert unify_lift({:tuple, [:boolean]}, {:tuple, [:atom]}) == {:ok, {:tuple, [:boolean]}} assert {:error, {{:unable_unify, {:tuple, [:integer]}, {:tuple, []}, _, _}, _}} = unify_lift({:tuple, [:integer]}, {:tuple, []}) assert {:error, {{:unable_unify, :integer, :atom, _, _}, _}} = unify_lift({:tuple, [:integer]}, {:tuple, [:atom]}) end test "list" do assert unify_lift({:list, :integer}, {:list, :integer}) == {:ok, {:list, :integer}} assert {:error, {{:unable_unify, :atom, :integer, _, _}, _}} = unify_lift({:list, :atom}, {:list, :integer}) end test "map" do assert unify_lift({:map, []}, {:map, []}) == {:ok, {:map, []}} assert unify_lift({:map, [{:integer, :atom}]}, {:map, []}) == {:ok, {:map, [{:integer, :atom}]}} assert unify_lift({:map, []}, {:map, [{:integer, :atom}]}) == {:ok, {:map, [{:integer, :atom}]}} assert unify_lift({:map, [{:integer, :atom}]}, {:map, [{:integer, :atom}]}) == {:ok, {:map, [{:integer, :atom}]}} assert unify_lift({:map, [{:integer, :atom}]}, {:map, [{:atom, :integer}]}) == {:ok, {:map, [{:integer, :atom}, {:atom, :integer}]}} assert unify_lift( {:map, [{{:atom, :foo}, :boolean}]}, {:map, [{{:atom, :foo}, :atom}]} ) == {:ok, {:map, [{{:atom, :foo}, :boolean}]}} assert {:error, {{:unable_unify, :integer, :atom, _, _}, _}} = unify_lift( {:map, [{{:atom, :foo}, :integer}]}, {:map, [{{:atom, :foo}, :atom}]} ) end test "union" do assert unify_lift({:union, []}, {:union, []}) == {:ok, {:union, []}} assert unify_lift({:union, [:integer]}, {:union, [:integer]}) == {:ok, {:union, [:integer]}} assert unify_lift({:union, [:integer, :atom]}, {:union, [:integer, :atom]}) == {:ok, {:union, [:integer, :atom]}} assert unify_lift({:union, [:integer, :atom]}, {:union, [:atom, :integer]}) == {:ok, {:union, [:integer, :atom]}} assert unify_lift({:union, [:atom]}, {:union, [:boolean]}) == {:ok, {:union, [:boolean]}} assert unify_lift({:union, [:boolean]}, {:union, [:atom]}) == {:ok, {:union, [:boolean]}} assert {:error, {{:unable_unify, {:union, [:integer]}, {:union, [:atom]}, _, _}, _}} = unify_lift({:union, [:integer]}, {:union, [:atom]}) end test "dynamic" do assert unify_lift({:atom, :foo}, :dynamic) == {:ok, {:atom, :foo}} assert unify_lift(:dynamic, {:atom, :foo}) == {:ok, {:atom, :foo}} assert unify_lift(:integer, :dynamic) == {:ok, :integer} assert unify_lift(:dynamic, :integer) == {:ok, :integer} end test "vars" do assert {{:var, 0}, var_context} = new_var({:foo, [version: 0], nil}, new_context()) assert {{:var, 1}, var_context} = new_var({:bar, [version: 1], nil}, var_context) assert {:ok, {:var, 0}, context} = unify({:var, 0}, :integer, var_context) assert Types.lift_type({:var, 0}, context) == :integer assert {:ok, {:var, 0}, context} = unify(:integer, {:var, 0}, var_context) assert Types.lift_type({:var, 0}, context) == :integer assert {:ok, {:var, _}, context} = unify({:var, 0}, {:var, 1}, var_context) assert {:var, _} = Types.lift_type({:var, 0}, context) assert {:var, _} = Types.lift_type({:var, 1}, context) assert {:ok, {:var, 0}, context} = unify({:var, 0}, :integer, var_context) assert {:ok, {:var, 1}, context} = unify({:var, 1}, :integer, context) assert {:ok, {:var, _}, _context} = unify({:var, 0}, {:var, 1}, context) assert {:ok, {:var, 0}, context} = unify({:var, 0}, :integer, var_context) assert {:ok, {:var, 1}, context} = unify({:var, 1}, :integer, context) assert {:ok, {:var, _}, _context} = unify({:var, 1}, {:var, 0}, context) assert {:ok, {:var, 0}, context} = unify({:var, 0}, :integer, var_context) assert {:ok, {:var, 1}, context} = unify({:var, 1}, :binary, context) assert {:error, {{:unable_unify, :integer, :binary, _, _}, _}} = unify_lift({:var, 0}, {:var, 1}, context) assert {:ok, {:var, 0}, context} = unify({:var, 0}, :integer, var_context) assert {:ok, {:var, 1}, context} = unify({:var, 1}, :binary, context) assert {:error, {{:unable_unify, :binary, :integer, _, _}, _}} = unify_lift({:var, 1}, {:var, 0}, context) end test "vars inside tuples" do assert {{:var, 0}, var_context} = new_var({:foo, [version: 0], nil}, new_context()) assert {{:var, 1}, var_context} = new_var({:bar, [version: 1], nil}, var_context) assert {:ok, {:tuple, [{:var, 0}]}, context} = unify({:tuple, [{:var, 0}]}, {:tuple, [:integer]}, var_context) assert Types.lift_type({:var, 0}, context) == :integer assert {:ok, {:var, 0}, context} = unify({:var, 0}, :integer, var_context) assert {:ok, {:var, 1}, context} = unify({:var, 1}, :integer, context) assert {:ok, {:tuple, [{:var, _}]}, _context} = unify({:tuple, [{:var, 0}]}, {:tuple, [{:var, 1}]}, context) assert {:ok, {:var, 1}, context} = unify({:var, 1}, {:tuple, [{:var, 0}]}, var_context) assert {:ok, {:var, 0}, context} = unify({:var, 0}, :integer, context) assert Types.lift_type({:var, 1}, context) == {:tuple, [:integer]} assert {:ok, {:var, 0}, context} = unify({:var, 0}, :integer, var_context) assert {:ok, {:var, 1}, context} = unify({:var, 1}, :binary, context) assert {:error, {{:unable_unify, :integer, :binary, _, _}, _}} = unify_lift({:tuple, [{:var, 0}]}, {:tuple, [{:var, 1}]}, context) end # TODO: Vars inside unions test "recursive type" do assert {{:var, 0}, var_context} = new_var({:foo, [version: 0], nil}, new_context()) assert {{:var, 1}, var_context} = new_var({:bar, [version: 1], nil}, var_context) assert {{:var, 2}, var_context} = new_var({:baz, [version: 2], nil}, var_context) assert {:ok, {:var, _}, context} = unify({:var, 0}, {:var, 1}, var_context) assert {:ok, {:var, _}, _context} = unify({:var, 1}, {:var, 0}, context) assert {:ok, {:var, _}, context} = unify({:var, 0}, {:var, 1}, var_context) assert {:ok, {:var, _}, context} = unify({:var, 1}, {:var, 2}, context) assert {:ok, {:var, _}, _context} = unify({:var, 2}, {:var, 0}, context) assert {:ok, {:var, _}, context} = unify({:var, 0}, {:var, 1}, var_context) assert {:error, {{:unable_unify, {:var, 0}, {:tuple, [{:var, 0}]}, _, _}, _}} = unify_lift({:var, 1}, {:tuple, [{:var, 0}]}, context) assert {:ok, {:var, _}, context} = unify({:var, 0}, {:var, 1}, var_context) assert {:ok, {:var, _}, context} = unify({:var, 1}, {:var, 2}, context) assert {:error, {{:unable_unify, {:var, 0}, {:tuple, [{:var, 0}]}, _, _}, _}} = unify_lift({:var, 2}, {:tuple, [{:var, 0}]}, context) end end test "subtype?/3" do assert subtype?({:atom, :foo}, :atom, new_context()) assert subtype?({:atom, true}, :boolean, new_context()) assert subtype?({:atom, true}, :atom, new_context()) assert subtype?(:boolean, :atom, new_context()) refute subtype?(:integer, :binary, new_context()) refute subtype?(:atom, {:atom, :foo}, new_context()) refute subtype?(:boolean, {:atom, true}, new_context()) refute subtype?(:atom, {:atom, true}, new_context()) refute subtype?(:atom, :boolean, new_context()) end test "to_union/2" do assert to_union([:atom], new_context()) == :atom assert to_union([:integer, :integer], new_context()) == :integer assert to_union([:boolean, :atom], new_context()) == :atom assert to_union([{:atom, :foo}, :boolean, :atom], new_context()) == :atom assert to_union([:binary, :atom], new_context()) == {:union, [:binary, :atom]} assert to_union([:atom, :binary, :atom], new_context()) == {:union, [:atom, :binary]} assert to_union([{:atom, :foo}, :binary, :atom], new_context()) == {:union, [:binary, :atom]} assert {{:var, 0}, var_context} = new_var({:foo, [version: 0], nil}, new_context()) assert to_union([{:var, 0}], var_context) == {:var, 0} assert to_union([{:tuple, [:integer]}, {:tuple, [:integer]}], new_context()) == {:tuple, [:integer]} end end
41.661417
98
0.534965
f782a495d120e5ed74d04bd29c7f1026fb4cb7fc
583
exs
Elixir
test/views/error_view_test.exs
whenther/chopsticks
ec8d9f90cb4e9afc9e80322c734d9c6bfe5e14e1
[ "MIT" ]
2
2016-11-08T18:17:41.000Z
2017-02-23T06:51:56.000Z
test/views/error_view_test.exs
will-wow/chopsticks
ec8d9f90cb4e9afc9e80322c734d9c6bfe5e14e1
[ "MIT" ]
null
null
null
test/views/error_view_test.exs
will-wow/chopsticks
ec8d9f90cb4e9afc9e80322c734d9c6bfe5e14e1
[ "MIT" ]
null
null
null
defmodule Chopsticks.ErrorViewTest do use Chopsticks.ConnCase, async: true # Bring render/3 and render_to_string/3 for testing custom views import Phoenix.View test "renders 404.html" do assert render_to_string(Chopsticks.ErrorView, "404.html", []) == "Page not found" end test "render 500.html" do assert render_to_string(Chopsticks.ErrorView, "500.html", []) == "Internal server error" end test "render any other" do assert render_to_string(Chopsticks.ErrorView, "505.html", []) == "Internal server error" end end
26.5
68
0.684391
f782b0b1231f6cb725c76896fab48304d85a0b2f
1,789
ex
Elixir
deps/ecto/lib/ecto/json.ex
rpillar/Top5_Elixir
9c450d2e9b291108ff1465dc066dfe442dbca822
[ "MIT" ]
null
null
null
deps/ecto/lib/ecto/json.ex
rpillar/Top5_Elixir
9c450d2e9b291108ff1465dc066dfe442dbca822
[ "MIT" ]
null
null
null
deps/ecto/lib/ecto/json.ex
rpillar/Top5_Elixir
9c450d2e9b291108ff1465dc066dfe442dbca822
[ "MIT" ]
null
null
null
# TODO: Remove Poison handling once we have fully migrated to Jason if Code.ensure_loaded?(Poison.Encoder) do defimpl Poison.Encoder, for: Decimal do def encode(decimal, _opts), do: <<?", Decimal.to_string(decimal, :normal)::binary, ?">> end end for encoder <- [Poison.Encoder, Jason.Encoder] do if Code.ensure_loaded?(encoder) do defimpl encoder, for: Ecto.Association.NotLoaded do def encode(%{__owner__: owner, __field__: field}, _) do raise """ cannot encode association #{inspect field} from #{inspect owner} to \ JSON because the association was not loaded. You can either preload the association: Repo.preload(#{inspect owner}, #{inspect field}) Or choose to not encode the association when converting the struct \ to JSON by explicitly listing the JSON fields in your schema: defmodule #{inspect owner} do # ... @derive {#{unquote(inspect encoder)}, only: [:name, :title, ...]} schema ... do """ end end defimpl encoder, for: Ecto.Schema.Metadata do def encode(%{schema: schema}, _) do raise """ cannot encode metadata from the :__meta__ field for #{inspect schema} \ to JSON. This metadata is used internally by ecto and should never be \ exposed externally. You can either map the schemas to remove the :__meta__ field before \ encoding to JSON, or explicit list the JSON fields in your schema: defmodule #{inspect schema} do # ... @derive {#{unquote(inspect encoder)}, only: [:name, :title, ...]} schema ... do """ end end end end
33.754717
92
0.595305
f782b5051e4eb9683b81d643b04d9d8bdc01e1fb
155
ex
Elixir
chapter3/challenges/mealcon/lib/mealcon_web/views/meals_view.ex
mCodex/rocketseat-ignite-elixir
bdb48db778c36b2325c75a41b4d6f7ef77b03cf5
[ "MIT" ]
1
2021-07-23T19:48:27.000Z
2021-07-23T19:48:27.000Z
chapter3/challenges/mealcon/lib/mealcon_web/views/meals_view.ex
mCodex/rocketseat-ignite-elixir
bdb48db778c36b2325c75a41b4d6f7ef77b03cf5
[ "MIT" ]
null
null
null
chapter3/challenges/mealcon/lib/mealcon_web/views/meals_view.ex
mCodex/rocketseat-ignite-elixir
bdb48db778c36b2325c75a41b4d6f7ef77b03cf5
[ "MIT" ]
null
null
null
defmodule MealconWeb.MealsView do use MealconWeb, :view alias Mealcon.Meal def render("meal.json", %{meal: %Meal{} = meal}), do: %{meal: meal} end
19.375
69
0.677419
f782c695d0cdb7cdbdf10f20cf9318684b4b9031
2,015
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/disk_aggregated_list_warning_data.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/compute/lib/google_api/compute/v1/model/disk_aggregated_list_warning_data.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/compute/lib/google_api/compute/v1/model/disk_aggregated_list_warning_data.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.Compute.V1.Model.DiskAggregatedListWarningData do @moduledoc """ ## Attributes * `key` (*type:* `String.t`, *default:* `nil`) - [Output Only] A key that provides more detail on the warning being returned. For example, for warnings where there are no results in a list request for a particular zone, this key might be scope and the key value might be the zone name. Other examples might be a key indicating a deprecated resource and a suggested replacement, or a warning about invalid network settings (for example, if an instance attempts to perform IP forwarding but is not enabled for IP forwarding). * `value` (*type:* `String.t`, *default:* `nil`) - [Output Only] A warning data value corresponding to the key. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :key => String.t() | nil, :value => String.t() | nil } field(:key) field(:value) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.DiskAggregatedListWarningData do def decode(value, options) do GoogleApi.Compute.V1.Model.DiskAggregatedListWarningData.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.DiskAggregatedListWarningData do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
40.3
527
0.740447
f782d9d0a3b67c48f8929db056e75716f8dd661b
2,866
ex
Elixir
lib/data_daemon/plug.ex
mariaclrd/data_daemon
f1b4dfd07959d9d0b23389005c41c883d0caf295
[ "MIT" ]
4
2019-02-16T01:09:30.000Z
2022-03-03T09:56:20.000Z
lib/data_daemon/plug.ex
mariaclrd/data_daemon
f1b4dfd07959d9d0b23389005c41c883d0caf295
[ "MIT" ]
5
2018-11-03T12:52:59.000Z
2019-04-27T10:13:33.000Z
lib/data_daemon/plug.ex
mariaclrd/data_daemon
f1b4dfd07959d9d0b23389005c41c883d0caf295
[ "MIT" ]
2
2020-02-06T10:28:38.000Z
2020-09-09T11:22:29.000Z
defmodule DataDaemon.Plug do @moduledoc false @doc false @spec safe_in(any, [atom | String.t()]) :: any def safe_in(data, []), do: data def safe_in(data, [field | fields]), do: safe_in(Map.get(data, field), fields) @doc false @spec enable :: term def enable do quote location: :keep do @behaviour Plug import DataDaemon.Plug, only: [safe_in: 2] import Plug.Conn, only: [register_before_send: 2] @doc false @spec init(Keyword.t()) :: atom() | binary() | [atom() | binary() | [any()] | number() | tuple() | map()] | number() | tuple() | %{ (atom() | binary() | [any()] | number() | tuple() | map()) => atom() | binary() | [any()] | number() | tuple() | map() } @impl Plug def init(opts) do tags = opts |> Keyword.get(:tags, []) |> Enum.map(fn conn = {:conn, field} when is_list(field) -> {:conn, field} {:conn, field} -> {:conn, [field]} env = {:system, _} -> env {k, {:conn, field}} when is_list(field) -> {to_string(k), {:conn, field}} {k, {:conn, field}} -> {to_string(k), {:conn, [field]}} {k, env = {:system, _}} -> {to_string(k), env} {k, v} -> {to_string(k), to_string(v)} v -> to_string(v) end) |> Enum.group_by(fn {:conn, _} -> :conn_tags {_, {:conn, _}} -> :conn_tags _ -> :tags end) %{ metric: opts[:metric] || raise("Need to set metric name."), tags: Map.get(tags, :tags, []), conn_tags: Map.get(tags, :conn_tags, []), exclude: opts[:exclude] || [] } end @doc false @spec call(Plug.Conn.t(), map) :: Plug.Conn.t() @impl Plug def call(conn = %{request_path: path}, %{ metric: metric, tags: tags, conn_tags: conn_tags, exclude: exclude }) do if path in exclude do conn else start_time = :erlang.monotonic_time(:milli_seconds) register_before_send(conn, fn conn -> time = :erlang.monotonic_time(:milli_seconds) - start_time conn_tags = Enum.map(conn_tags, fn {:conn, conn_tag} -> safe_in(conn, conn_tag) {k, {:conn, conn_tag}} -> {k, safe_in(conn, conn_tag)} end) spawn(fn -> timing( metric, time, tags: tags ++ conn_tags ) end) conn end) end end end end end
28.949495
87
0.437893
f782fda5ab769af429d92f6fc238cbb7768eca58
598
exs
Elixir
test/phoenix_elm_web/views/error_view_test.exs
ejpcmac/phoenix_elm
cc43a2253610728fbf2db9bd87b5341e82a27e5e
[ "BSD-3-Clause" ]
null
null
null
test/phoenix_elm_web/views/error_view_test.exs
ejpcmac/phoenix_elm
cc43a2253610728fbf2db9bd87b5341e82a27e5e
[ "BSD-3-Clause" ]
null
null
null
test/phoenix_elm_web/views/error_view_test.exs
ejpcmac/phoenix_elm
cc43a2253610728fbf2db9bd87b5341e82a27e5e
[ "BSD-3-Clause" ]
null
null
null
defmodule PhoenixElmWeb.ErrorViewTest do use PhoenixElmWeb.ConnCase, async: true # Bring render/3 and render_to_string/3 for testing custom views import Phoenix.View test "renders 404.html" do assert render_to_string(PhoenixElmWeb.ErrorView, "404.html", []) == "Page not found" end test "render 500.html" do assert render_to_string(PhoenixElmWeb.ErrorView, "500.html", []) == "Internal server error" end test "render any other" do assert render_to_string(PhoenixElmWeb.ErrorView, "505.html", []) == "Internal server error" end end
27.181818
71
0.692308
f7832130d9dd2982400a65dac4cd0b23a5093cbf
1,195
ex
Elixir
apps/snitch_core/lib/core/data/model/package_item.ex
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
456
2018-09-20T02:40:59.000Z
2022-03-07T08:53:48.000Z
apps/snitch_core/lib/core/data/model/package_item.ex
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
273
2018-09-19T06:43:43.000Z
2021-08-07T12:58:26.000Z
apps/snitch_core/lib/core/data/model/package_item.ex
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
122
2018-09-26T16:32:46.000Z
2022-03-13T11:44:19.000Z
defmodule Snitch.Data.Model.PackageItem do @moduledoc """ PackageItem API. """ use Snitch.Data.Model alias Snitch.Data.Schema.PackageItem # TODO: the CUD operations should update the parent package! @doc """ Creates a new `PackageItem`. """ @spec create(map) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} def create(params) do QH.create(PackageItem, params, Repo) end @doc """ Updates the `package_item` with `params`. """ @spec update(map, PackageItem.t()) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} def update(params, %PackageItem{} = package_item) do QH.update(PackageItem, params, package_item, Repo) end @doc """ Deletes the `package_item`. """ @spec delete(PackageItem.t()) :: {:ok, PackageItem.t()} | {:error, Ecto.Changeset.t()} | {:error, :not_found} def delete(%PackageItem{} = package_item) do QH.delete(PackageItem, package_item, Repo) end @spec get(non_neg_integer | map) :: {:ok, PackageItem.t()} | {:error, atom} def get(query_fields) do QH.get(PackageItem, query_fields, Repo) end @spec get_all :: list(PackageItem.t()) def get_all, do: Repo.all(PackageItem) end
27.159091
93
0.654393
f7833d756564c2c6771c9d196fbae507f62ec6cb
228
exs
Elixir
string_reduction.exs
hvnsweeting/elixir-hackerrank-fp
1b4c259c7e335b272b0bbc50d3ba92ddb724566f
[ "MIT" ]
null
null
null
string_reduction.exs
hvnsweeting/elixir-hackerrank-fp
1b4c259c7e335b272b0bbc50d3ba92ddb724566f
[ "MIT" ]
null
null
null
string_reduction.exs
hvnsweeting/elixir-hackerrank-fp
1b4c259c7e335b272b0bbc50d3ba92ddb724566f
[ "MIT" ]
null
null
null
# https://www.hackerrank.com/challenges/string-reductions defmodule Solution do def main() do IO.gets("") |> String.strip() |> String.to_charlist() |> Enum.uniq() |> IO.puts() end end Solution.main()
16.285714
57
0.618421
f783424280b9bc492f09b170d9b293bd54b29abd
54
exs
Elixir
test/test_helper.exs
RobertDober/earmark_ast_dsl
d7393cb1981b34a05ede5666b6dbb7bbc05972ca
[ "Apache-2.0" ]
1
2021-10-30T09:12:14.000Z
2021-10-30T09:12:14.000Z
test/test_helper.exs
RobertDober/earmark_ast_dsl
d7393cb1981b34a05ede5666b6dbb7bbc05972ca
[ "Apache-2.0" ]
4
2020-06-26T10:06:20.000Z
2021-12-29T07:04:23.000Z
test/test_helper.exs
RobertDober/earmark_ast_dsl
d7393cb1981b34a05ede5666b6dbb7bbc05972ca
[ "Apache-2.0" ]
null
null
null
ExUnit.start() # SPDX-License-Identifier: Apache-2.0
18
38
0.740741
f7835e257ea089adf25a8c3abcaa3fb232ab82b1
1,976
ex
Elixir
clients/service_management/lib/google_api/service_management/v1/model/metric_rule.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/service_management/lib/google_api/service_management/v1/model/metric_rule.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/service_management/lib/google_api/service_management/v1/model/metric_rule.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.ServiceManagement.V1.Model.MetricRule do @moduledoc """ Bind API methods to metrics. Binding a method to a metric causes that metric's configured quota behaviors to apply to the method call. ## Attributes * `metricCosts` (*type:* `map()`, *default:* `nil`) - Metrics to update when the selected methods are called, and the associated cost applied to each metric. The key of the map is the metric name, and the values are the amount increased for the metric against which the quota limits are defined. The value must not be negative. * `selector` (*type:* `String.t`, *default:* `nil`) - Selects the methods to which this rule applies. Refer to selector for syntax details. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :metricCosts => map() | nil, :selector => String.t() | nil } field(:metricCosts, type: :map) field(:selector) end defimpl Poison.Decoder, for: GoogleApi.ServiceManagement.V1.Model.MetricRule do def decode(value, options) do GoogleApi.ServiceManagement.V1.Model.MetricRule.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ServiceManagement.V1.Model.MetricRule do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
39.52
331
0.737348
f7836631156e6c6a700909c9a2e3cbb9024edc57
187
ex
Elixir
sandbox/test.ex
techgaun/dumpster
c2a5394afe759fb99041aea677e9b0bc4bf91aec
[ "Unlicense" ]
1
2019-12-10T22:25:31.000Z
2019-12-10T22:25:31.000Z
sandbox/test.ex
techgaun/dumpster
c2a5394afe759fb99041aea677e9b0bc4bf91aec
[ "Unlicense" ]
3
2020-10-25T04:40:05.000Z
2020-10-25T04:48:10.000Z
sandbox/test.ex
techgaun/dumpster
c2a5394afe759fb99041aea677e9b0bc4bf91aec
[ "Unlicense" ]
null
null
null
pet = %Cat{:name => "Alexander"} pet2 = %Dog{:name => "Fido"} pet3 = %Wolf{} pet4 = %Shark{} pets = [pet, pet2, pet3, pet4] for pet <- pets, Animal.friendly?(pet), do: Pet.checkup(pet)
20.777778
60
0.59893
f7837314ef3575912783c557ccb3faa60484d942
1,521
ex
Elixir
lib/honu/storage/disk.ex
elixir-honu/honu
e82cbc4c2457b3d64b929cc013c17cdb4fcc8f6c
[ "MIT" ]
1
2021-08-08T10:33:42.000Z
2021-08-08T10:33:42.000Z
lib/honu/storage/disk.ex
elixir-honu/honu
e82cbc4c2457b3d64b929cc013c17cdb4fcc8f6c
[ "MIT" ]
null
null
null
lib/honu/storage/disk.ex
elixir-honu/honu
e82cbc4c2457b3d64b929cc013c17cdb4fcc8f6c
[ "MIT" ]
null
null
null
defmodule Honu.Storage.Disk do alias Honu.Attachments.Blob alias Honu.Storage @behaviour Storage # If using the path from Plug.Upload, it is only available during the request # as Plug will remove it once the request completes # https://hexdocs.pm/phoenix/1.3.0-rc.2/file_uploads.html @impl true def put(blob = %Blob{}, opts \\ []) do make_path_for(blob.key, opts) if File.exists?(path_for(blob.key, opts)) || opts[:force] do {:error, "File already exists at upload destination"} else File.cp!(blob.path, path_for(blob.key, opts)) {:ok, blob} end end @impl true def delete(blob = %Blob{}, opts \\ []) do path_for(blob.key, opts) |> File.rm() |> case do :ok -> # TODO: Remove empty dir here? # recursive File.rmdir(String.replace_trailing(path_for(blob.key, opts), blob.key, "")) :ok {:error, error} -> {:error, "Could not remove file: #{error}"} end end @impl true def read(blob = %Blob{}, opts \\ []) do path_for(blob.key, opts) |> File.read() end @impl true def exists?(key, opts \\ []) do File.exists?(path_for(key, opts)) end def path_for(key, opts \\ []) do Path.join([Storage.config(:root_dir, opts), opts[:prefix] || "", folder_for(key), key]) end defp make_path_for(key, opts) do path_for(key, opts) |> Path.dirname() |> File.mkdir_p!() end defp folder_for(key) do "#{String.slice(key, 0..1)}/#{String.slice(key, 2..3)}" end end
24.532258
95
0.609467
f78388f86ee84be50f472c3b0e168595c2ad0600
173
exs
Elixir
config/config.exs
devoutsalsa/lib_lat_lon
a9fef01e67ad92f1b5ff042173f6986ad6f5fd48
[ "MIT" ]
11
2018-01-11T13:13:21.000Z
2021-04-18T09:48:00.000Z
config/config.exs
devoutsalsa/lib_lat_lon
a9fef01e67ad92f1b5ff042173f6986ad6f5fd48
[ "MIT" ]
1
2021-04-18T02:54:11.000Z
2021-04-18T02:54:11.000Z
config/config.exs
devoutsalsa/lib_lat_lon
a9fef01e67ad92f1b5ff042173f6986ad6f5fd48
[ "MIT" ]
2
2019-11-05T12:14:36.000Z
2021-04-17T17:03:07.000Z
use Mix.Config ### EXTERNALS config :porcelain, driver: Porcelain.Driver.Basic ### ENV-SPECIFIC if File.exists?("#{Mix.env()}.exs"), do: import_config("#{Mix.env()}.exs")
21.625
74
0.682081
f783974d4c0ca8dd203d10d4aed0c9cb423f33b2
1,236
ex
Elixir
lib/blue_heron/gatt/characteristic.ex
amclain/blue_heron
e1802097ef6a845e28a8be56076f3b81ebb56206
[ "Apache-2.0" ]
45
2020-10-17T13:34:15.000Z
2022-03-08T09:40:43.000Z
lib/blue_heron/gatt/characteristic.ex
amclain/blue_heron
e1802097ef6a845e28a8be56076f3b81ebb56206
[ "Apache-2.0" ]
20
2020-10-15T15:05:54.000Z
2022-03-27T15:54:36.000Z
lib/blue_heron/gatt/characteristic.ex
amclain/blue_heron
e1802097ef6a845e28a8be56076f3b81ebb56206
[ "Apache-2.0" ]
11
2020-10-23T17:18:57.000Z
2022-03-15T20:01:49.000Z
defmodule BlueHeron.GATT.Characteristic do @moduledoc """ Struct that represents a GATT characteristic. """ @opaque t() :: %__MODULE__{ id: any(), type: non_neg_integer(), properties: non_neg_integer(), handle: any(), value_handle: any() } defstruct [:id, :type, :properties, :handle, :value_handle] @doc """ Create a characteristic with fields taken from the map `args`. The following fields are required: - `id`: A user-defined term to identify the characteristic. Must be unique within the device profile. Can be any Erlang term. - `type`: The characteristic type UUID. Can be a 2- or 16-byte byte UUID. Integer. - `properties`: The characteristic property flags. Integer. ## Example: iex> BlueHeron.GATT.Characteristic.new(%{ ...> id: :fancy_key, ...> type: 0x2e0f8e717a7d4690998377626bc6b657, ...> properties: 0b00000010 ...> }) %BlueHeron.GATT.Characteristic{id: :fancy_key, type: 0x2e0f8e717a7d4690998377626bc6b657, properties: 2} """ @spec new(args :: map()) :: t() def new(args) do args = Map.take(args, [:id, :type, :properties]) struct!(__MODULE__, args) end end
31.692308
109
0.634304
f783a5cd91b41aed49cdf8ce0b5a2d3b17aa19db
2,312
exs
Elixir
spec/yaml_config_file_spec.exs
sampscl/qol_up
31fc3c670587b0ca810ae346d437f7d8c8a6d02e
[ "MIT" ]
null
null
null
spec/yaml_config_file_spec.exs
sampscl/qol_up
31fc3c670587b0ca810ae346d437f7d8c8a6d02e
[ "MIT" ]
null
null
null
spec/yaml_config_file_spec.exs
sampscl/qol_up
31fc3c670587b0ca810ae346d437f7d8c8a6d02e
[ "MIT" ]
null
null
null
defmodule YamlConfigFileSpec do use ESpec def temp_config_file(contents) do {:ok, cfg_file} = Briefly.create(directory: false) :ok = File.write!(cfg_file, contents) cfg_file end describe "QolUp.YamlConfigFile" do it "parses empty config files" do # make an empty temporary config file cfg_file = temp_config_file("") # note: it always parses config files on startup name = __ENV__.function |> then(&(elem(&1, 0))) {:ok, pid} = QolUp.YamlConfigFile.start_link(config_file: cfg_file, name: name) assert(pid |> to(be_pid())) GenServer.stop(name) end it "parses valid config files" do cfg_file = temp_config_file("---\nfoo: bar") name = __ENV__.function |> then(&(elem(&1, 0))) {:ok, pid} = QolUp.YamlConfigFile.start_link(config_file: cfg_file, name: name) assert(pid |> to(be_pid())) GenServer.stop(name) end it "reads config parameters" do cfg_file = temp_config_file("---\nfoo: bar") name = __ENV__.function |> then(&(elem(&1, 0))) {:ok, pid} = QolUp.YamlConfigFile.start_link(config_file: cfg_file, name: name) assert(pid |> to(be_pid())) expect(QolUp.YamlConfigFile.get_item!(name, "foo") |> to(eq("bar"))) GenServer.stop(name) end it "can start monitoring the filesystem" do cfg_file = temp_config_file("---\nfoo: bar") name = __ENV__.function |> then(&(elem(&1, 0))) {:ok, pid} = QolUp.YamlConfigFile.start_link(config_file: cfg_file, name: name, watch_fs: true) assert(pid |> to(be_pid())) expect(QolUp.YamlConfigFile.get_item!(name, "foo") |> to(eq("bar"))) GenServer.stop(name) end it "reloads configs when monitoring" do cfg_file = temp_config_file("---\nfoo: bar") name = __ENV__.function |> then(&(elem(&1, 0))) {:ok, pid} = QolUp.YamlConfigFile.start_link(config_file: cfg_file, name: name, watch_fs: true) assert(pid |> to(be_pid())) expect(QolUp.YamlConfigFile.get_item!(name, "foo") |> to(eq("bar"))) File.write!(cfg_file, "---\nfoo: baz") # Give a bit for change / notify system to process the change Process.sleep(1_500) expect(QolUp.YamlConfigFile.get_item!(name, "foo") |> to(eq("baz"))) GenServer.stop(name) end end end
37.290323
101
0.636246
f783b094a5a51003cc7d2c7282a3e41d03d89cf1
1,486
ex
Elixir
lib/erlef/blogs.ex
joaquinalcerro/website
52dc89c70cd0b42127ab233a4c0d10f626d2b698
[ "Apache-2.0" ]
1
2021-03-13T01:34:28.000Z
2021-03-13T01:34:28.000Z
lib/erlef/blogs.ex
joaquinalcerro/website
52dc89c70cd0b42127ab233a4c0d10f626d2b698
[ "Apache-2.0" ]
null
null
null
lib/erlef/blogs.ex
joaquinalcerro/website
52dc89c70cd0b42127ab233a4c0d10f626d2b698
[ "Apache-2.0" ]
null
null
null
defmodule Erlef.Blogs do @moduledoc """ Erlef.Blogs context """ import Ecto.Query alias Erlef.Repo.ETS alias Erlef.Blogs.Post @spec get_posts_by_tag(String.t()) :: [Post.t()] def get_posts_by_tag(tag) do all_posts() |> Enum.filter(fn p -> tag in p.tags end) |> sort_posts_by_datetime() end @spec latest_posts() :: [Post.t()] def latest_posts() do all_posts() |> sort_posts_by_datetime() |> Enum.take(3) end # Sorts from smallest to largest @spec all_tags() :: [String.t()] @doc """ Fetch and sort all available blog tags from smallest to largest byte size """ def all_tags() do Post |> ETS.all() |> Enum.flat_map(& &1.tags) |> Enum.uniq() |> Enum.sort(&(byte_size(&1) <= byte_size(&2))) end @spec all_posts() :: [Post.t()] def all_posts() do Post |> ETS.all() end @spec get_post_by_slug(String.t()) :: {:ok, Post.t()} | {:error, :not_found} def get_post_by_slug(slug) do case ETS.get_by(Post, slug: slug) do %{slug: ^slug} = post -> {:ok, post} _ -> {:error, :not_found} end end @spec get_posts_by_category(String.t()) :: [Post.t()] def get_posts_by_category(cat) do Post |> where([x], x.category == ^cat) |> ETS.all() end @spec sort_posts_by_datetime([Post.t()]) :: [Post.t()] def sort_posts_by_datetime(posts) do Enum.sort( posts, fn p1, p2 -> DateTime.compare(p1.datetime, p2.datetime) == :gt end ) end end
22.861538
78
0.603634
f783b991c0a6ff708507140509b8d8fee7e44e83
1,549
ex
Elixir
lib/google_apis/swagger_config.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
lib/google_apis/swagger_config.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
lib/google_apis/swagger_config.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "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. defmodule GoogleApis.SwaggerConfig do defstruct [:licenseHeader, :invokerPackage, :packageName] @license_header """ # 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. """ def from_api_config(api_config) do %__MODULE__{ licenseHeader: @license_header, invokerPackage: GoogleApis.ApiConfig.library_namespace(api_config), packageName: GoogleApis.ApiConfig.app_name(api_config) } end end
36.023256
76
0.743706
f783d082f767fbdea2e081834ada7a3586c659ae
1,741
ex
Elixir
clients/classroom/lib/google_api/classroom/v1/model/link.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/classroom/lib/google_api/classroom/v1/model/link.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/classroom/lib/google_api/classroom/v1/model/link.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 &quot;License&quot;); # 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 &quot;AS IS&quot; 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.Classroom.V1.Model.Link do @moduledoc """ URL item. ## Attributes * `thumbnailUrl` (*type:* `String.t`, *default:* `nil`) - URL of a thumbnail image of the target URL. Read-only. * `title` (*type:* `String.t`, *default:* `nil`) - Title of the target of the URL. Read-only. * `url` (*type:* `String.t`, *default:* `nil`) - URL to link to. This must be a valid UTF-8 string containing between 1 and 2024 characters. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :thumbnailUrl => String.t(), :title => String.t(), :url => String.t() } field(:thumbnailUrl) field(:title) field(:url) end defimpl Poison.Decoder, for: GoogleApi.Classroom.V1.Model.Link do def decode(value, options) do GoogleApi.Classroom.V1.Model.Link.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Classroom.V1.Model.Link do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
30.017241
105
0.690982
f783dc07836011ea0c364f0a8798e440c5037fec
6,047
ex
Elixir
deps/comeonin/lib/comeonin/base.ex
JoakimEskils/elixir-absinthe
d81e24ec7c7b1164e6d152101dd50422f192d7e9
[ "MIT" ]
null
null
null
deps/comeonin/lib/comeonin/base.ex
JoakimEskils/elixir-absinthe
d81e24ec7c7b1164e6d152101dd50422f192d7e9
[ "MIT" ]
null
null
null
deps/comeonin/lib/comeonin/base.ex
JoakimEskils/elixir-absinthe
d81e24ec7c7b1164e6d152101dd50422f192d7e9
[ "MIT" ]
null
null
null
for {module, alg} <- [{Argon2, "Argon2"}, {Bcrypt, "Bcrypt"}, {Pbkdf2, "Pbkdf2"}] do if Code.ensure_loaded?(module) do mod = Module.concat(Comeonin, module) defmodule mod do @moduledoc """ Password hashing module using the #{alg} algorithm. For more information about the #{alg} algorithm, see the `Choosing an algorithm` section in the Comeonin docs. For a lower-level API, see `#{alg}.Base`. """ @doc """ Hash a password and return it in a map, with the password set to nil. ## Options This function uses `#{alg}.hash_pwd_salt` as the hashing function. In addition to the options for hash_pwd_salt, there is also the following option: * hash_key - the name of the key for the password hash * the default is :password_hash ## Example with Ecto In this example, the `create_changeset` function below shows how a new user can be created: def create_changeset(%User{} = user, attrs) do user |> changeset(attrs) |> validate_password(:password) |> put_pass_hash() end The `validating the password` section will then look at writing a custom validator (validate_password), and the `adding the password hash` section will cover the use of the `add_hash` function (in put_pass_hash). ### Validating the password This section can be skipped if you are using a frontend solution to validating the password. The following is a basic example of the `validate_password` function: def validate_password(changeset, field, options \\ []) do validate_change(changeset, field, fn _, password -> case valid_password?(password) do {:ok, _} -> [] {:error, msg} -> [{field, options[:message] || msg}] end end) end In the example below, the `valid_password?` function checks that the password is at least 8 characters long. defp valid_password?(password) when byte_size(password) > 7 do {:ok, password} end defp valid_password?(_), do: {:error, "The password is too short"} Alternatively, you could use a dedicated password strength checker, such as [not_qwerty123](https://github.com/riverrun/not_qwerty123). For more information about password strength rules, see the latest [NIST guidelines](https://pages.nist.gov/800-63-3/sp800-63b.html). ### Adding the password hash In the following example, `add_hash` is used in the put_pass_hash function: defp put_pass_hash(%Ecto.Changeset{valid?: true, changes: %{password: password}} = changeset) do change(changeset, Comeonin.#{alg}.add_hash(password)) end defp put_pass_hash(changeset), do: changeset """ def add_hash(password, opts \\ []) do hash_key = opts[:hash_key] || :password_hash %{hash_key => unquote(module).hash_pwd_salt(password, opts), :password => nil} end @doc """ Check the password by comparing its hash with the password hash found in a user struct, or map. The password hash's key needs to be either `:password_hash` or `:encrypted_password`. After finding the password hash in the user struct, the password is checked by comparing it with the hash. Then the function returns {:ok, user} or {:error, message}. Note that the error message is meant to be used for logging purposes only; it should not be passed on to the end user. If the first argument is nil, meaning that there is no user with that name, a dummy verify function is run to make user enumeration, using timing information, more difficult. This can be disabled by adding `hide_user: false` to the opts. ## Examples The following is a simple example using Phoenix 1.3: def verify(attrs) do MyApp.Accounts.get_by(attrs) |> Comeonin.#{alg}.check_pass(password) end """ def check_pass(user, password, opts \\ []) def check_pass(nil, _password, opts) do unless opts[:hide_user] == false, do: unquote(module).no_user_verify(opts) {:error, "invalid user-identifier"} end def check_pass(user, password, _) when is_binary(password) do with {:ok, hash} <- get_hash(user) do unquote(module).verify_pass(password, hash) and {:ok, user} || {:error, "invalid password"} end end def check_pass(_, _, _) do {:error, "password is not a string"} end @doc """ Print out a report to help you configure the hash function. For more details, see the documentation for `#{alg}.Stats.report`. """ def report(opts \\ []) do mod = Module.concat(unquote(module), Stats) mod.report(opts) end @doc """ Hash the password with a randomly-generated salt. For more details, see the documentation for `#{alg}.hash_pwd_salt` and `#{alg}.Base.hash_password`. """ defdelegate hashpwsalt(password, opts \\ []), to: module, as: :hash_pwd_salt @doc """ Check the password by comparing it with the stored hash. For more details, see the documentation for `#{alg}.verify_pass`. """ defdelegate checkpw(password, hash), to: module, as: :verify_pass @doc """ Run a dummy check, which always returns false, to make user enumeration more difficult. For more details, see the documentation for `#{alg}.no_user_verify`. """ defdelegate dummy_checkpw(opts \\ []), to: module, as: :no_user_verify defp get_hash(%{password_hash: hash}), do: {:ok, hash} defp get_hash(%{encrypted_password: hash}), do: {:ok, hash} defp get_hash(_), do: {:error, "no password hash found in the user struct"} end end end
35.156977
86
0.625434
f783e31a0d8a46a838ce94e990ffe6d911fd4a17
687
ex
Elixir
lib/xgit/util/file_utils.ex
scouten/xgit
0e2f849c83cdf39a9249b319d63ff3682c482c2f
[ "Apache-2.0" ]
94
2019-05-28T05:29:54.000Z
2022-02-18T20:03:20.000Z
lib/xgit/util/file_utils.ex
scouten/xgit
0e2f849c83cdf39a9249b319d63ff3682c482c2f
[ "Apache-2.0" ]
156
2019-05-26T03:27:24.000Z
2020-10-08T05:44:26.000Z
lib/xgit/util/file_utils.ex
scouten/redo
0e2f849c83cdf39a9249b319d63ff3682c482c2f
[ "Apache-2.0" ]
5
2019-05-28T16:35:55.000Z
2021-06-16T14:25:17.000Z
defmodule Xgit.Util.FileUtils do @moduledoc false # Internal utility for recursively listing the contents of a directory. import Xgit.Util.ForceCoverage @doc ~S""" Recursively list the files of a directory. Directories are scanned, but their paths are not reported as part of the result. """ @spec recursive_files!(path :: Path.t()) :: [Path.t()] def recursive_files!(path \\ ".") do cond do File.regular?(path) -> cover [path] File.dir?(path) -> path |> File.ls!() |> Enum.map(&Path.join(path, &1)) |> Enum.map(&recursive_files!/1) |> Enum.concat() true -> cover [] end end end
22.16129
82
0.598253
f783f8a4662a43b9a71692534a37cc7c8fe6ff81
1,310
ex
Elixir
clients/cloud_shell/lib/google_api/cloud_shell/v1/model/authorize_environment_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/cloud_shell/lib/google_api/cloud_shell/v1/model/authorize_environment_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/cloud_shell/lib/google_api/cloud_shell/v1/model/authorize_environment_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.CloudShell.V1.Model.AuthorizeEnvironmentResponse do @moduledoc """ Response message for AuthorizeEnvironment. ## Attributes """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{} end defimpl Poison.Decoder, for: GoogleApi.CloudShell.V1.Model.AuthorizeEnvironmentResponse do def decode(value, options) do GoogleApi.CloudShell.V1.Model.AuthorizeEnvironmentResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudShell.V1.Model.AuthorizeEnvironmentResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
31.190476
90
0.772519
f784075523d909b2a583c4596011fcb906b3163b
225
ex
Elixir
apps/playground_api/lib/playground_api.ex
kimlindholm/elixir_playground
2a44404996b98d88e40faaee4f6b3a546618a1fd
[ "MIT" ]
null
null
null
apps/playground_api/lib/playground_api.ex
kimlindholm/elixir_playground
2a44404996b98d88e40faaee4f6b3a546618a1fd
[ "MIT" ]
null
null
null
apps/playground_api/lib/playground_api.ex
kimlindholm/elixir_playground
2a44404996b98d88e40faaee4f6b3a546618a1fd
[ "MIT" ]
null
null
null
defmodule PlaygroundApi do @moduledoc """ REST JSON:API. """ @doc """ Hello world. ## Examples iex> PlaygroundApi.hello() :world """ @spec hello() :: atom() def hello do :world end end
11.25
32
0.555556
f7840cabe07d9d3714f9fab0327b5cc9dff6eed1
1,272
ex
Elixir
apps/interface/lib/interface_web/views/error_helpers.ex
jeremy-miller/life-elixir
5c9396b187279110dc8da38a5070023d1ed02955
[ "MIT" ]
null
null
null
apps/interface/lib/interface_web/views/error_helpers.ex
jeremy-miller/life-elixir
5c9396b187279110dc8da38a5070023d1ed02955
[ "MIT" ]
null
null
null
apps/interface/lib/interface_web/views/error_helpers.ex
jeremy-miller/life-elixir
5c9396b187279110dc8da38a5070023d1ed02955
[ "MIT" ]
null
null
null
defmodule InterfaceWeb.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do Enum.map(Keyword.get_values(form.errors, field), fn (error) -> content_tag :span, translate_error(error), class: "help-block" end) end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # Because error messages were defined within Ecto, we must # call the Gettext module passing our Gettext backend. We # also use the "errors" domain as translations are placed # in the errors.po file. # Ecto will pass the :count keyword if the error message is # meant to be pluralized. # On your own code and templates, depending on whether you # need the message to be pluralized or not, this could be # written simply as: # # dngettext "errors", "1 file", "%{count} files", count # dgettext "errors", "is invalid" # if count = opts[:count] do Gettext.dngettext(InterfaceWeb.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(InterfaceWeb.Gettext, "errors", msg, opts) end end end
31.02439
78
0.67217
f7841c31580aa144d7fd15b1263691a8f3a56e70
77
ex
Elixir
lib/student_list_web/views/user_settings_view.ex
jwarwick/student_list
d35a2fcef2025d3de9b7915682965c48481c1d15
[ "MIT" ]
1
2021-06-27T20:02:11.000Z
2021-06-27T20:02:11.000Z
lib/student_list_web/views/user_settings_view.ex
jwarwick/student_list
d35a2fcef2025d3de9b7915682965c48481c1d15
[ "MIT" ]
null
null
null
lib/student_list_web/views/user_settings_view.ex
jwarwick/student_list
d35a2fcef2025d3de9b7915682965c48481c1d15
[ "MIT" ]
null
null
null
defmodule StudentListWeb.UserSettingsView do use StudentListWeb, :view end
19.25
44
0.844156
f784284384b3209f8c63c206e902679018233b29
10,348
exs
Elixir
apps/omg_child_chain/test/omg_child_chain/integration/fee_server_test.exs
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
1
2020-10-06T03:07:47.000Z
2020-10-06T03:07:47.000Z
apps/omg_child_chain/test/omg_child_chain/integration/fee_server_test.exs
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
9
2020-09-16T15:31:17.000Z
2021-03-17T07:12:35.000Z
apps/omg_child_chain/test/omg_child_chain/integration/fee_server_test.exs
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
1
2020-09-30T17:17:27.000Z
2020-09-30T17:17:27.000Z
# Copyright 2019-2020 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule OMG.ChildChain.Integration.FeeServerTest do @moduledoc false use ExUnitFixtures use ExUnit.Case, async: false import ExUnit.CaptureLog alias OMG.ChildChain.FeeServer alias OMG.Eth alias OMG.TestHelper @moduletag :integration @moduletag :child_chain @eth Eth.zero_address() @eth_hex Eth.Encoding.to_hex(@eth) @not_eth <<1::size(160)>> @not_eth_hex Eth.Encoding.to_hex(@not_eth) @payment_tx_type OMG.WireFormatTypes.tx_type_for(:tx_payment_v1) @fees %{ @payment_tx_type => %{ @eth_hex => %{ amount: 1, pegged_amount: 1, subunit_to_unit: 1_000_000_000_000_000_000, pegged_currency: "USD", pegged_subunit_to_unit: 100, updated_at: DateTime.from_unix!(1_546_336_800) }, @not_eth_hex => %{ amount: 2, pegged_amount: 1, subunit_to_unit: 1_000_000_000_000_000_000, pegged_currency: "USD", pegged_subunit_to_unit: 100, updated_at: DateTime.from_unix!(1_546_336_800) } }, 2 => %{ @eth_hex => %{ amount: 1, pegged_amount: 1, subunit_to_unit: 1_000_000_000_000_000_000, pegged_currency: "USD", pegged_subunit_to_unit: 100, updated_at: DateTime.from_unix!(1_546_336_800) } } } @parsed_fees %{ @payment_tx_type => %{ @eth => %{ amount: 1, pegged_amount: 1, subunit_to_unit: 1_000_000_000_000_000_000, pegged_currency: "USD", pegged_subunit_to_unit: 100, updated_at: DateTime.from_unix!(1_546_336_800), type: :fixed }, @not_eth => %{ amount: 2, pegged_amount: 1, subunit_to_unit: 1_000_000_000_000_000_000, pegged_currency: "USD", pegged_subunit_to_unit: 100, updated_at: DateTime.from_unix!(1_546_336_800), type: :fixed } }, 2 => %{ @eth => %{ amount: 1, pegged_amount: 1, subunit_to_unit: 1_000_000_000_000_000_000, pegged_currency: "USD", pegged_subunit_to_unit: 100, updated_at: DateTime.from_unix!(1_546_336_800), type: :fixed } } } setup do {:ok, apps} = Application.ensure_all_started(:omg_status) # make sure :ets managed to clear up before we start another Stream.repeatedly(fn -> Process.sleep(25) :undefined == :ets.info(:fees_bucket) end) |> Enum.take_while(fn b -> not b end) {:ok, file_path} = TestHelper.write_fee_file(@fees) on_exit(fn -> apps |> Enum.reverse() |> Enum.each(&Application.stop/1) File.rm(file_path) end) %{fee_file_path: file_path} end describe "fees in effect" do test "corrupted file does not make server crash", %{fee_file_path: file_path} do {:started, _log, exit_fn} = start_fee_server(file_path) new_fee = %{ amount: 5, subunit_to_unit: 100, pegged_amount: 2, pegged_currency: "SOMETHING", pegged_subunit_to_unit: 1000, updated_at: DateTime.from_unix!(1_546_336_800), type: :fixed } assert {:ok, @parsed_fees} == FeeServer.current_fees() # corrupt file, refresh, check fees did not change assert capture_log(fn -> overwrite_fee_file(file_path, "[not a json]") refresh_fees() end) =~ ~r/\[error\].*Unable to update fees/ assert {:ok, @parsed_fees} == FeeServer.current_fees() assert server_alive?() # fix file, reload, check changes applied overwrite_fee_file(file_path, %{@payment_tx_type => %{@eth_hex => new_fee}}) refresh_fees() assert {:ok, %{@payment_tx_type => %{@eth => new_fee}}} == FeeServer.current_fees() assert server_alive?() exit_fn.() end test "starting with corrupted file makes server die", %{fee_file_path: file_path} do overwrite_fee_file(file_path, "[not a json]") {:died, log} = start_fee_server(file_path) assert log =~ ~r/\[error\].*Unable to update fees/ assert false == server_alive?() end test "previous fees are nil when starting", %{fee_file_path: file_path} do {:started, _log, exit_fn} = start_fee_server(file_path) assert nil == :ets.lookup_element(:fees_bucket, :previous_fees, 2) assert {:ok, %{1 => %{@eth => [1], @not_eth => [2]}, 2 => %{@eth => [1]}}} == FeeServer.accepted_fees() exit_fn.() end test "previous fees are set when fees are updated", %{fee_file_path: file_path} do new_fee = %{ amount: 5, subunit_to_unit: 100, pegged_amount: 2, pegged_currency: "SOMETHING", pegged_subunit_to_unit: 1000, updated_at: DateTime.from_unix!(1_546_336_800), type: :fixed } {:started, _log, exit_fn} = start_fee_server(file_path) assert nil == :ets.lookup_element(:fees_bucket, :previous_fees, 2) assert {:ok, %{1 => %{@eth => [1], @not_eth => [2]}, 2 => %{@eth => [1]}}} == FeeServer.accepted_fees() overwrite_fee_file(file_path, %{@payment_tx_type => %{@eth_hex => new_fee}}) refresh_fees() assert @parsed_fees == :ets.lookup_element(:fees_bucket, :previous_fees, 2) assert {:ok, %{1 => %{@eth => [5, 1], @not_eth => [2]}, 2 => %{@eth => [1]}}} == FeeServer.accepted_fees() exit_fn.() end test "previous fees expire after the set duration", %{fee_file_path: file_path} do new_fee = %{ amount: 5, subunit_to_unit: 100, pegged_amount: 2, pegged_currency: "SOMETHING", pegged_subunit_to_unit: 1000, updated_at: DateTime.from_unix!(1_546_423_200), type: :fixed } {:started, _log, exit_fn} = start_fee_server(file_path) overwrite_fee_file(file_path, %{@payment_tx_type => %{@eth_hex => new_fee}}) refresh_fees() assert @parsed_fees == :ets.lookup_element(:fees_bucket, :previous_fees, 2) assert {:ok, %{1 => %{@eth => [5, 1], @not_eth => [2]}, 2 => %{@eth => [1]}}} == FeeServer.accepted_fees() sleep_time = Application.fetch_env!(:omg_child_chain, :fee_buffer_duration_ms) Process.sleep(sleep_time) assert nil == :ets.lookup_element(:fees_bucket, :previous_fees, 2) assert {:ok, %{1 => %{@eth => [5]}}} == FeeServer.accepted_fees() exit_fn.() end test "previous fees are not nil if fees updated during buffer period", %{fee_file_path: file_path} do # This test is to ensure that the timer is correcly cancelled when new fees # come in while in buffer period. new_fee_1 = %{ amount: 5, subunit_to_unit: 100, pegged_amount: nil, pegged_currency: nil, pegged_subunit_to_unit: nil, type: :fixed, updated_at: DateTime.from_unix!(1_546_423_200) } new_fee_2 = %{ amount: 2, subunit_to_unit: 100, pegged_amount: nil, pegged_currency: nil, pegged_subunit_to_unit: nil, type: :fixed, updated_at: DateTime.from_unix!(1_546_423_200) } {:started, _log, exit_fn} = start_fee_server(file_path) overwrite_fee_file(file_path, %{@payment_tx_type => %{@eth_hex => new_fee_1}}) refresh_fees() assert @parsed_fees == :ets.lookup_element(:fees_bucket, :previous_fees, 2) assert {:ok, %{1 => %{@eth => [5, 1], @not_eth => [2]}, 2 => %{@eth => [1]}}} == FeeServer.accepted_fees() half_buffer_duration = :omg_child_chain |> Application.fetch_env!(:fee_buffer_duration_ms) |> div(2) Process.sleep(half_buffer_duration) overwrite_fee_file(file_path, %{@payment_tx_type => %{@eth_hex => new_fee_2}}) refresh_fees() Process.sleep(half_buffer_duration) assert %{1 => %{@eth => new_fee_1}} == :ets.lookup_element(:fees_bucket, :previous_fees, 2) assert {:ok, %{1 => %{@eth => [2, 5]}}} == FeeServer.accepted_fees() exit_fn.() end end defp start_fee_server(file_path) do opts = Keyword.merge( OMG.ChildChain.Configuration.fee_server_opts(), fee_adapter: OMG.ChildChain.Fees.FileAdapter, fee_adapter_opts: [specs_file_path: file_path] ) log = capture_log(fn -> GenServer.start(FeeServer, opts, name: TestFeeServer) end) case GenServer.whereis(TestFeeServer) do pid when is_pid(pid) -> # switch of internal timer to don't interfere with tests if tref = Map.get(:sys.get_state(TestFeeServer), :tref) do {:ok, :cancel} = :timer.cancel(tref) end if buffer_timer = Map.get(:sys.get_state(TestFeeServer), :expire_fee_timer) do _ = Process.cancel_timer(buffer_timer) end {:started, log, fn -> GenServer.stop(pid) end} nil -> {:died, log} end end defp refresh_fees() do pid = GenServer.whereis(TestFeeServer) capture_log(fn -> logs = capture_log(fn -> Process.send(pid, :update_fee_specs, []) end) case logs do "" -> wait_for_log() logs -> logs end end) end defp wait_for_log() do # wait maximal 1s for logs Enum.reduce_while(1..100, nil, fn _, _ -> logs = capture_log(fn -> Process.sleep(10) end) case logs do "" -> {:cont, ""} logs -> {:halt, logs} end end) end defp server_alive?() do case GenServer.whereis(TestFeeServer) do pid when is_pid(pid) -> Process.alive?(pid) _ -> false end end defp overwrite_fee_file(file_path, content) do # file modification date is in seconds Process.sleep(1000) {:ok, ^file_path} = TestHelper.write_fee_file(content, file_path) end end
29.994203
112
0.619347
f7843cd407c94e12fe55c4ff0bdf2c34ff389346
5,676
ex
Elixir
lib/absinthe/relay/mutation/notation/classic.ex
scottming/absinthe_relay
685fb9b27ac0b9d5d2888d325cd52a48364d4a21
[ "MIT" ]
null
null
null
lib/absinthe/relay/mutation/notation/classic.ex
scottming/absinthe_relay
685fb9b27ac0b9d5d2888d325cd52a48364d4a21
[ "MIT" ]
null
null
null
lib/absinthe/relay/mutation/notation/classic.ex
scottming/absinthe_relay
685fb9b27ac0b9d5d2888d325cd52a48364d4a21
[ "MIT" ]
null
null
null
defmodule Absinthe.Relay.Mutation.Notation.Classic do @moduledoc """ Support for Relay Classic mutations with single inputs and client mutation IDs. The `payload` macro can be used by schema designers to support mutation fields that receive a single input object argument with a client mutation ID and return that ID as part of the response payload. More information can be found at https://facebook.github.io/relay/docs/guides-mutations.html ## Example In this example we add a mutation field `:simple_mutation` that accepts an `input` argument (which is defined for us automatically) which contains an `:input_data` field. We also declare the output will contain a field, `:result`. Notice the `resolve` function doesn't need to know anything about the wrapping `input` argument -- it only concerns itself with the contents -- and the client mutation ID doesn't need to be dealt with, either. It will be returned as part of the response payload automatically. ``` mutation do payload field :simple_mutation do input do field :input_data, non_null(:integer) end output do field :result, :integer end resolve fn %{input_data: input_data}, _ -> # Some mutation side-effect here {:ok, %{result: input_data * 2}} end end end ``` Here's a query document that would hit this field: ```graphql mutation DoSomethingSimple { simpleMutation(input: {inputData: 2, clientMutationId: "abc"}) { result clientMutationId } } ``` And here's the response: ```json { "data": { "simpleMutation": { "result": 4, "clientMutationId": "abc" } } } ``` Note the above code would create the following types in our schema, ad hoc: - `SimpleMutationInput` - `SimpleMutationPayload` For this reason, the identifier passed to `payload field` must be unique across your schema. ## The Escape Hatch The mutation macros defined here are just for convenience; if you want something that goes against these restrictions, don't worry! You can always just define your types and fields using normal (`field`, `arg`, `input_object`, etc) schema notation macros as usual. """ use Absinthe.Schema.Notation alias Absinthe.Blueprint alias Absinthe.Blueprint.Schema alias Absinthe.Relay.Schema.Notation @doc """ Define a mutation with a single input and a client mutation ID. See the module documentation for more information. """ defmacro payload({:field, meta, args}, do: block) do Notation.payload(meta, args, [default_private(), block]) end defmacro payload({:field, meta, args}) do Notation.payload(meta, args, default_private()) end defp default_private() do [ # This indicates to the Relay schema phase that this field should automatically # generate both input and payload types if they are not defined within the field # itself. The `input` notation also autogenerates the `input` argument to the field quote do private(:absinthe_relay, :input, {:fill, unquote(__MODULE__)}) private(:absinthe_relay, :payload, {:fill, unquote(__MODULE__)}) end ] end # # INPUT # @doc """ Defines the input type for your payload field. See the module documentation for an example. """ defmacro input(identifier, do: block) do Notation.input(__MODULE__, identifier, block) end # # PAYLOAD # @doc """ Defines the output (payload) type for your payload field. See the module documentation for an example. """ defmacro output(identifier, do: block) do Notation.output(__MODULE__, identifier, block) end def additional_types(:input, %Schema.FieldDefinition{identifier: field_ident}) do %Schema.InputObjectTypeDefinition{ name: Notation.ident(field_ident, :input) |> Atom.to_string() |> Macro.camelize(), identifier: Notation.ident(field_ident, :input), module: __MODULE__, __private__: [absinthe_relay: [input: {:fill, __MODULE__}]], __reference__: Absinthe.Schema.Notation.build_reference(__ENV__) } end def additional_types(:payload, %Schema.FieldDefinition{identifier: field_ident}) do %Schema.ObjectTypeDefinition{ name: Notation.ident(field_ident, :payload) |> Atom.to_string() |> Macro.camelize(), identifier: Notation.ident(field_ident, :payload), module: __MODULE__, __private__: [absinthe_relay: [payload: {:fill, __MODULE__}]], __reference__: Absinthe.Schema.Notation.build_reference(__ENV__) } end def additional_types(_, _), do: [] def fillout(:input, %Schema.FieldDefinition{} = field) do Absinthe.Relay.Mutation.Notation.Modern.add_input_arg(field) end def fillout(:input, %Schema.InputObjectTypeDefinition{} = input) do # We could add this to the additional_types above, but we also need to fill # out this field if the user specified the types. It's easier to leave it out # of the defaults, and then unconditionally apply it after the fact. %{input | fields: [client_mutation_id_field() | input.fields]} end def fillout(:payload, %Schema.ObjectTypeDefinition{} = payload) do %{payload | fields: [client_mutation_id_field() | payload.fields]} end def fillout(_, node) do node end defp client_mutation_id_field() do %Blueprint.Schema.FieldDefinition{ name: "client_mutation_id", identifier: :client_mutation_id, type: %Blueprint.TypeReference.NonNull{of_type: :string}, module: __MODULE__, __reference__: Absinthe.Schema.Notation.build_reference(__ENV__) } end end
31.186813
116
0.699436
f7847742253284ce05e4d60abbb0d64b9555f828
1,560
ex
Elixir
lib/oli_web/live/community_live/form.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
1
2022-03-17T20:35:47.000Z
2022-03-17T20:35:47.000Z
lib/oli_web/live/community_live/form.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
9
2021-11-02T16:52:09.000Z
2022-03-25T15:14:01.000Z
lib/oli_web/live/community_live/form.ex
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
null
null
null
defmodule OliWeb.CommunityLive.Form do use Surface.Component alias Surface.Components.Form alias Surface.Components.Form.{Checkbox, ErrorTag, Field, Label, TextArea, TextInput} prop(changeset, :changeset, required: true) prop(save, :event, required: true) prop(display_labels, :boolean, default: true) def render(assigns) do ~F""" <Form for={@changeset} submit={@save}> <Field name={:name} class="form-group"> {#if @display_labels} <Label class="control-label">Community Name</Label> {/if} <TextInput class="form-control" opts={placeholder: "Name", maxlength: "255"}/> <ErrorTag/> </Field> <Field name={:description} class="form-group"> {#if @display_labels} <Label class="control-label">Community Description</Label> {/if} <TextArea class="form-control" rows="4" opts={placeholder: "Description"}/> </Field> <Field name={:key_contact} class="form-group"> {#if @display_labels} <Label class="control-label">Community Contact</Label> {/if} <TextInput class="form-control" opts={placeholder: "Key Contact", maxlength: "255"}/> <ErrorTag/> </Field> <Field name={:global_access} class="form-check"> <Checkbox class="form-check-input"/> <Label class="form-check-label" text="Access to Global Project or Products"/> </Field> <button class="form-button btn btn-md btn-primary btn-block mt-3" type="submit">Save</button> </Form> """ end end
33.191489
99
0.626923
f784785377d0a3032e389a6ea2f20abff62e10fc
4,082
exs
Elixir
apps/admin_api/test/admin_api/v1/controllers/admin_auth/invite_controller_test.exs
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
null
null
null
apps/admin_api/test/admin_api/v1/controllers/admin_auth/invite_controller_test.exs
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
null
null
null
apps/admin_api/test/admin_api/v1/controllers/admin_auth/invite_controller_test.exs
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
null
null
null
defmodule AdminAPI.V1.AdminAuth.InviteControllerTest do use AdminAPI.ConnCase, async: true alias EWallet.Web.Date defp request(email, token, password, password_confirmation) do unauthenticated_request("/invite.accept", %{ "email" => email, "token" => token, "password" => password, "password_confirmation" => password_confirmation }) end describe "InviteController.accept/2" do test "returns success if invite is accepted successfully" do invite = insert(:invite) user = insert(:admin, %{invite: invite}) response = request(user.email, invite.token, "some_password", "some_password") expected = %{ "object" => "user", "id" => user.id, "socket_topic" => "user:#{user.id}", "provider_user_id" => nil, "username" => nil, "email" => user.email, "avatar" => %{"original" => nil, "large" => nil, "small" => nil, "thumb" => nil}, "metadata" => %{ "first_name" => user.metadata["first_name"], "last_name" => user.metadata["last_name"] }, "encrypted_metadata" => %{}, "created_at" => Date.to_iso8601(user.inserted_at), "updated_at" => Date.to_iso8601(user.updated_at) } assert response["success"] assert response["data"] == expected end test "returns :invite_not_found error if the email has not been invited" do invite = insert(:invite) _user = insert(:admin, %{invite: invite}) response = request("[email protected]", invite.token, "some_password", "some_password") refute response["success"] assert response["data"]["object"] == "error" assert response["data"]["code"] == "user:invite_not_found" assert response["data"]["description"] == "There is no invite corresponding to the provided email and token" end test "returns :invite_not_found error if the token is incorrect" do invite = insert(:invite) user = insert(:admin, %{invite: invite}) response = request(user.email, "wrong_token", "some_password", "some_password") refute response["success"] assert response["data"]["object"] == "error" assert response["data"]["code"] == "user:invite_not_found" assert response["data"]["description"] == "There is no invite corresponding to the provided email and token" end test "returns :passwords_mismatch error if the passwords do not match" do invite = insert(:invite) user = insert(:admin, %{invite: invite}) response = request(user.email, invite.token, "some_password", "mismatch_password") refute response["success"] assert response["data"]["object"] == "error" assert response["data"]["code"] == "user:passwords_mismatch" assert response["data"]["description"] == "The provided passwords do not match" end test "returns client:invalid_parameter error if the password has less than 8 characters" do invite = insert(:invite) user = insert(:admin, %{invite: invite}) response = request(user.email, invite.token, "short", "short") refute response["success"] assert response["data"]["object"] == "error" assert response["data"]["code"] == "client:invalid_parameter" assert response["data"]["description"] == "Invalid parameter provided `password` must be 8 characters or more." end test "returns :invalid_parameter error if a required parameter is missing" do invite = insert(:invite) user = insert(:admin, %{invite: invite}) # Missing passwords response = unauthenticated_request("/invite.accept", %{ "email" => user.email, "token" => invite.token }) refute response["success"] assert response["data"]["object"] == "error" assert response["data"]["code"] == "client:invalid_parameter" assert response["data"]["description"] == "'email', 'token', 'password', 'password_confirmation' are required" end end end
36.774775
95
0.624694
f7847cf1f95f89c843a5e7a276ecb39057971691
1,540
exs
Elixir
mix.exs
OwayTripGroup/httpoison
9b9debf168b6db45abbf5129721f5d01759d32f4
[ "MIT" ]
null
null
null
mix.exs
OwayTripGroup/httpoison
9b9debf168b6db45abbf5129721f5d01759d32f4
[ "MIT" ]
null
null
null
mix.exs
OwayTripGroup/httpoison
9b9debf168b6db45abbf5129721f5d01759d32f4
[ "MIT" ]
null
null
null
defmodule HTTPoison.Mixfile do use Mix.Project @description """ Yet Another HTTP client for Elixir powered by hackney """ def project do [ app: :httpoison, version: "1.5.1", elixir: "~> 1.5", name: "HTTPoison", description: @description, package: package(), deps: deps(), source_url: "https://github.com/edgurgel/httpoison", docs: [ main: "readme", logo: "logo.png", extras: [ "README.md", "CHANGELOG.md" ] ], dialyzer: [ plt_add_deps: :transitive, flags: [ # "-Wunmatched_returns", # "-Wrace_conditions", # "-Wunderspecs", # "-Wunknown", # "-Woverspecs", # "-Wspecdiffs", ] ] ] end def application do [applications: [:hackney]] end defp deps do [ {:hackney, git: "https://github.com/benoitc/hackney.git", branch: "master"}, {:mimic, "~> 0.1", only: :test}, {:exjsx, "~> 3.1", only: :test}, {:httparrot, "~> 1.2", only: :test}, {:earmark, "~> 1.0", only: :dev}, {:ex_doc, "~> 0.18", only: :dev}, {:dialyxir, "~> 1.0.0-rc.3", only: [:dev, :test], runtime: false} ] end defp package do [ maintainers: ["Eduardo Gurgel Pinho"], licenses: ["MIT"], links: %{ Changelog: "https://github.com/edgurgel/httpoison/blob/master/CHANGELOG.md", GitHub: "https://github.com/edgurgel/httpoison" } ] end end
22.985075
84
0.507143
f7849d0062d48c36ca3b7409e03bd7968a56a4c8
13,986
ex
Elixir
lib/codes/codes_o23.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_o23.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_o23.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
defmodule IcdCode.ICDCode.Codes_O23 do alias IcdCode.ICDCode def _O2300 do %ICDCode{full_code: "O2300", category_code: "O23", short_code: "00", full_name: "Infections of kidney in pregnancy, unspecified trimester", short_name: "Infections of kidney in pregnancy, unspecified trimester", category_name: "Infections of kidney in pregnancy, unspecified trimester" } end def _O2301 do %ICDCode{full_code: "O2301", category_code: "O23", short_code: "01", full_name: "Infections of kidney in pregnancy, first trimester", short_name: "Infections of kidney in pregnancy, first trimester", category_name: "Infections of kidney in pregnancy, first trimester" } end def _O2302 do %ICDCode{full_code: "O2302", category_code: "O23", short_code: "02", full_name: "Infections of kidney in pregnancy, second trimester", short_name: "Infections of kidney in pregnancy, second trimester", category_name: "Infections of kidney in pregnancy, second trimester" } end def _O2303 do %ICDCode{full_code: "O2303", category_code: "O23", short_code: "03", full_name: "Infections of kidney in pregnancy, third trimester", short_name: "Infections of kidney in pregnancy, third trimester", category_name: "Infections of kidney in pregnancy, third trimester" } end def _O2310 do %ICDCode{full_code: "O2310", category_code: "O23", short_code: "10", full_name: "Infections of bladder in pregnancy, unspecified trimester", short_name: "Infections of bladder in pregnancy, unspecified trimester", category_name: "Infections of bladder in pregnancy, unspecified trimester" } end def _O2311 do %ICDCode{full_code: "O2311", category_code: "O23", short_code: "11", full_name: "Infections of bladder in pregnancy, first trimester", short_name: "Infections of bladder in pregnancy, first trimester", category_name: "Infections of bladder in pregnancy, first trimester" } end def _O2312 do %ICDCode{full_code: "O2312", category_code: "O23", short_code: "12", full_name: "Infections of bladder in pregnancy, second trimester", short_name: "Infections of bladder in pregnancy, second trimester", category_name: "Infections of bladder in pregnancy, second trimester" } end def _O2313 do %ICDCode{full_code: "O2313", category_code: "O23", short_code: "13", full_name: "Infections of bladder in pregnancy, third trimester", short_name: "Infections of bladder in pregnancy, third trimester", category_name: "Infections of bladder in pregnancy, third trimester" } end def _O2320 do %ICDCode{full_code: "O2320", category_code: "O23", short_code: "20", full_name: "Infections of urethra in pregnancy, unspecified trimester", short_name: "Infections of urethra in pregnancy, unspecified trimester", category_name: "Infections of urethra in pregnancy, unspecified trimester" } end def _O2321 do %ICDCode{full_code: "O2321", category_code: "O23", short_code: "21", full_name: "Infections of urethra in pregnancy, first trimester", short_name: "Infections of urethra in pregnancy, first trimester", category_name: "Infections of urethra in pregnancy, first trimester" } end def _O2322 do %ICDCode{full_code: "O2322", category_code: "O23", short_code: "22", full_name: "Infections of urethra in pregnancy, second trimester", short_name: "Infections of urethra in pregnancy, second trimester", category_name: "Infections of urethra in pregnancy, second trimester" } end def _O2323 do %ICDCode{full_code: "O2323", category_code: "O23", short_code: "23", full_name: "Infections of urethra in pregnancy, third trimester", short_name: "Infections of urethra in pregnancy, third trimester", category_name: "Infections of urethra in pregnancy, third trimester" } end def _O2330 do %ICDCode{full_code: "O2330", category_code: "O23", short_code: "30", full_name: "Infections of other parts of urinary tract in pregnancy, unspecified trimester", short_name: "Infections of other parts of urinary tract in pregnancy, unspecified trimester", category_name: "Infections of other parts of urinary tract in pregnancy, unspecified trimester" } end def _O2331 do %ICDCode{full_code: "O2331", category_code: "O23", short_code: "31", full_name: "Infections of other parts of urinary tract in pregnancy, first trimester", short_name: "Infections of other parts of urinary tract in pregnancy, first trimester", category_name: "Infections of other parts of urinary tract in pregnancy, first trimester" } end def _O2332 do %ICDCode{full_code: "O2332", category_code: "O23", short_code: "32", full_name: "Infections of other parts of urinary tract in pregnancy, second trimester", short_name: "Infections of other parts of urinary tract in pregnancy, second trimester", category_name: "Infections of other parts of urinary tract in pregnancy, second trimester" } end def _O2333 do %ICDCode{full_code: "O2333", category_code: "O23", short_code: "33", full_name: "Infections of other parts of urinary tract in pregnancy, third trimester", short_name: "Infections of other parts of urinary tract in pregnancy, third trimester", category_name: "Infections of other parts of urinary tract in pregnancy, third trimester" } end def _O2340 do %ICDCode{full_code: "O2340", category_code: "O23", short_code: "40", full_name: "Unspecified infection of urinary tract in pregnancy, unspecified trimester", short_name: "Unspecified infection of urinary tract in pregnancy, unspecified trimester", category_name: "Unspecified infection of urinary tract in pregnancy, unspecified trimester" } end def _O2341 do %ICDCode{full_code: "O2341", category_code: "O23", short_code: "41", full_name: "Unspecified infection of urinary tract in pregnancy, first trimester", short_name: "Unspecified infection of urinary tract in pregnancy, first trimester", category_name: "Unspecified infection of urinary tract in pregnancy, first trimester" } end def _O2342 do %ICDCode{full_code: "O2342", category_code: "O23", short_code: "42", full_name: "Unspecified infection of urinary tract in pregnancy, second trimester", short_name: "Unspecified infection of urinary tract in pregnancy, second trimester", category_name: "Unspecified infection of urinary tract in pregnancy, second trimester" } end def _O2343 do %ICDCode{full_code: "O2343", category_code: "O23", short_code: "43", full_name: "Unspecified infection of urinary tract in pregnancy, third trimester", short_name: "Unspecified infection of urinary tract in pregnancy, third trimester", category_name: "Unspecified infection of urinary tract in pregnancy, third trimester" } end def _O23511 do %ICDCode{full_code: "O23511", category_code: "O23", short_code: "511", full_name: "Infections of cervix in pregnancy, first trimester", short_name: "Infections of cervix in pregnancy, first trimester", category_name: "Infections of cervix in pregnancy, first trimester" } end def _O23512 do %ICDCode{full_code: "O23512", category_code: "O23", short_code: "512", full_name: "Infections of cervix in pregnancy, second trimester", short_name: "Infections of cervix in pregnancy, second trimester", category_name: "Infections of cervix in pregnancy, second trimester" } end def _O23513 do %ICDCode{full_code: "O23513", category_code: "O23", short_code: "513", full_name: "Infections of cervix in pregnancy, third trimester", short_name: "Infections of cervix in pregnancy, third trimester", category_name: "Infections of cervix in pregnancy, third trimester" } end def _O23519 do %ICDCode{full_code: "O23519", category_code: "O23", short_code: "519", full_name: "Infections of cervix in pregnancy, unspecified trimester", short_name: "Infections of cervix in pregnancy, unspecified trimester", category_name: "Infections of cervix in pregnancy, unspecified trimester" } end def _O23521 do %ICDCode{full_code: "O23521", category_code: "O23", short_code: "521", full_name: "Salpingo-oophoritis in pregnancy, first trimester", short_name: "Salpingo-oophoritis in pregnancy, first trimester", category_name: "Salpingo-oophoritis in pregnancy, first trimester" } end def _O23522 do %ICDCode{full_code: "O23522", category_code: "O23", short_code: "522", full_name: "Salpingo-oophoritis in pregnancy, second trimester", short_name: "Salpingo-oophoritis in pregnancy, second trimester", category_name: "Salpingo-oophoritis in pregnancy, second trimester" } end def _O23523 do %ICDCode{full_code: "O23523", category_code: "O23", short_code: "523", full_name: "Salpingo-oophoritis in pregnancy, third trimester", short_name: "Salpingo-oophoritis in pregnancy, third trimester", category_name: "Salpingo-oophoritis in pregnancy, third trimester" } end def _O23529 do %ICDCode{full_code: "O23529", category_code: "O23", short_code: "529", full_name: "Salpingo-oophoritis in pregnancy, unspecified trimester", short_name: "Salpingo-oophoritis in pregnancy, unspecified trimester", category_name: "Salpingo-oophoritis in pregnancy, unspecified trimester" } end def _O23591 do %ICDCode{full_code: "O23591", category_code: "O23", short_code: "591", full_name: "Infection of other part of genital tract in pregnancy, first trimester", short_name: "Infection of other part of genital tract in pregnancy, first trimester", category_name: "Infection of other part of genital tract in pregnancy, first trimester" } end def _O23592 do %ICDCode{full_code: "O23592", category_code: "O23", short_code: "592", full_name: "Infection of other part of genital tract in pregnancy, second trimester", short_name: "Infection of other part of genital tract in pregnancy, second trimester", category_name: "Infection of other part of genital tract in pregnancy, second trimester" } end def _O23593 do %ICDCode{full_code: "O23593", category_code: "O23", short_code: "593", full_name: "Infection of other part of genital tract in pregnancy, third trimester", short_name: "Infection of other part of genital tract in pregnancy, third trimester", category_name: "Infection of other part of genital tract in pregnancy, third trimester" } end def _O23599 do %ICDCode{full_code: "O23599", category_code: "O23", short_code: "599", full_name: "Infection of other part of genital tract in pregnancy, unspecified trimester", short_name: "Infection of other part of genital tract in pregnancy, unspecified trimester", category_name: "Infection of other part of genital tract in pregnancy, unspecified trimester" } end def _O2390 do %ICDCode{full_code: "O2390", category_code: "O23", short_code: "90", full_name: "Unspecified genitourinary tract infection in pregnancy, unspecified trimester", short_name: "Unspecified genitourinary tract infection in pregnancy, unspecified trimester", category_name: "Unspecified genitourinary tract infection in pregnancy, unspecified trimester" } end def _O2391 do %ICDCode{full_code: "O2391", category_code: "O23", short_code: "91", full_name: "Unspecified genitourinary tract infection in pregnancy, first trimester", short_name: "Unspecified genitourinary tract infection in pregnancy, first trimester", category_name: "Unspecified genitourinary tract infection in pregnancy, first trimester" } end def _O2392 do %ICDCode{full_code: "O2392", category_code: "O23", short_code: "92", full_name: "Unspecified genitourinary tract infection in pregnancy, second trimester", short_name: "Unspecified genitourinary tract infection in pregnancy, second trimester", category_name: "Unspecified genitourinary tract infection in pregnancy, second trimester" } end def _O2393 do %ICDCode{full_code: "O2393", category_code: "O23", short_code: "93", full_name: "Unspecified genitourinary tract infection in pregnancy, third trimester", short_name: "Unspecified genitourinary tract infection in pregnancy, third trimester", category_name: "Unspecified genitourinary tract infection in pregnancy, third trimester" } end end
42.253776
105
0.658444
f7849ef4078459d15cc7aceb50229050b7983e76
562
exs
Elixir
config/prod.exs
the3hm/seraph_mud
c098a22184a0a6bcbd56cacf7b0f176dd173260d
[ "MIT" ]
2
2019-05-14T11:36:44.000Z
2020-07-01T08:54:04.000Z
config/prod.exs
nickwalton/ex_venture
d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb
[ "MIT" ]
null
null
null
config/prod.exs
nickwalton/ex_venture
d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb
[ "MIT" ]
1
2021-01-29T14:12:40.000Z
2021-01-29T14:12:40.000Z
import Config version = System.get_env("SHA") || "no sha" config :ex_venture, version: String.trim(version) config :ex_venture, Web.Endpoint, http: [port: 4000], server: true, cache_static_manifest: "priv/static/cache_manifest.json" config :ex_venture, :networking, port: 5555, server: true, socket_module: Networking.Protocol config :ex_venture, :game, npc: Game.NPC, zone: Game.Zone, room: Game.Room, environment: Game.Environment.Implementation, shop: Game.Shop, zone: Game.Zone, continue_wait: 500 config :logger, level: :info
21.615385
58
0.725979
f784a258cbb0118694359808168a82913a88b3c1
1,149
exs
Elixir
config/config.exs
jschomay/remote-file-streamer
d029c99b8cd116f00ad81a7bbb2ba80353fbad1b
[ "MIT" ]
5
2019-01-29T12:23:00.000Z
2020-05-05T15:32:26.000Z
config/config.exs
jschomay/remote-file-streamer
d029c99b8cd116f00ad81a7bbb2ba80353fbad1b
[ "MIT" ]
4
2018-07-20T15:23:10.000Z
2019-05-21T08:12:33.000Z
config/config.exs
jschomay/remote-file-streamer
d029c99b8cd116f00ad81a7bbb2ba80353fbad1b
[ "MIT" ]
2
2019-03-20T20:46:44.000Z
2019-03-21T22:28:43.000Z
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :remote_file_streamer, key: :value # # and access this configuration in your application as: # # Application.get_env(:remote_file_streamer, :key) # # You can also configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs"
37.064516
73
0.75718
f784b1fcd92e715b0c06e13345b8ef833ab4d7dd
1,082
ex
Elixir
lib/crew_web/channels/user_socket.ex
anamba/crew
c25f6a1d6ddbe0b58da9d556ff53a641c4d2a7b1
[ "BSL-1.0" ]
null
null
null
lib/crew_web/channels/user_socket.ex
anamba/crew
c25f6a1d6ddbe0b58da9d556ff53a641c4d2a7b1
[ "BSL-1.0" ]
5
2020-07-20T01:49:01.000Z
2021-09-08T00:17:04.000Z
lib/crew_web/channels/user_socket.ex
anamba/crew
c25f6a1d6ddbe0b58da9d556ff53a641c4d2a7b1
[ "BSL-1.0" ]
null
null
null
defmodule CrewWeb.UserSocket do use Phoenix.Socket ## Channels # channel "room:*", CrewWeb.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. @impl true 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: # # CrewWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) # # Returning `nil` makes this socket anonymous. @impl true def id(_socket), do: nil end
30.055556
83
0.692237
f784b69e2ccdaac3cbe9020cd7a8d001e3677cf1
1,655
ex
Elixir
server/lib/idai_field_server_web/controllers/databases_controller.ex
felixwolter/idai-field
146ab8dbdedb23035a4ba19eac95f02a1fa2329f
[ "Apache-2.0" ]
null
null
null
server/lib/idai_field_server_web/controllers/databases_controller.ex
felixwolter/idai-field
146ab8dbdedb23035a4ba19eac95f02a1fa2329f
[ "Apache-2.0" ]
null
null
null
server/lib/idai_field_server_web/controllers/databases_controller.ex
felixwolter/idai-field
146ab8dbdedb23035a4ba19eac95f02a1fa2329f
[ "Apache-2.0" ]
null
null
null
defmodule IdaiFieldServerWeb.DatabasesController do use IdaiFieldServerWeb, :controller alias IdaiFieldServer.CouchdbDatastore def index conn, _params do databases = CouchdbDatastore.list_databases() render(conn, "index.html", error_message: nil, databases: databases) end def new conn, _params do render(conn, "new.html", error_message: nil) end def delete conn, %{ "database" => %{ "admin_password" => password, "name" => name }} do if CouchdbDatastore.authorize("admin", password) do CouchdbDatastore.delete_database name answer = CouchdbDatastore.delete_user name conn |> put_flash(:info, "Database deleted successfully.") |> redirect(to: Routes.databases_path(conn, :index)) else conn = conn |> put_flash(:error, "Wrong password given.") render(conn, "edit.html", name: name) end end def create conn, %{ "database" => %{ "database_name" => name, "main_db_user_password" => password, "main_db_user_password_confirmation" => password_confirmation }} do if password != password_confirmation do conn = conn |> put_flash(:error, "passwords do not match") render conn, "new.html" else CouchdbDatastore.create_database name CouchdbDatastore.create_user name, password CouchdbDatastore.set_permissions name conn |> put_flash(:info, "Database created successfully.") |> redirect(to: Routes.databases_path(conn, :index)) end end def edit conn, %{ "name" => name } = _params do render(conn, "edit.html", error_message: nil, name: name) end end
28.050847
72
0.667674
f784dc41a6f139681c0e34e7d7385dab520a78a6
6,125
exs
Elixir
priv/repo/seeds.exs
spacexcorp/elixir-bank
b5cf0592598da469e3c2eb43befeb0a45592ad0a
[ "MIT" ]
null
null
null
priv/repo/seeds.exs
spacexcorp/elixir-bank
b5cf0592598da469e3c2eb43befeb0a45592ad0a
[ "MIT" ]
null
null
null
priv/repo/seeds.exs
spacexcorp/elixir-bank
b5cf0592598da469e3c2eb43befeb0a45592ad0a
[ "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: # # ElixirBank.Repo.insert!(%ElixirBank.SomeSchema{}) # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong. alias ElixirBank.Accounts.User alias ElixirBank.Records.{Category, Record} alias ElixirBank.Repo collections_category = Repo.insert!(%Category{name: "Collections"}) fastest_category = Repo.insert!(%Category{name: "Fastest"}) highest_category = Repo.insert!(%Category{name: "Highest"}) largest_category = Repo.insert!(%Category{name: "Largest"}) longest_category = Repo.insert!(%Category{name: "Longest"}) marathon_category = Repo.insert!(%Category{name: "Marathon"}) most_category = Repo.insert!(%Category{name: "Most"}) other_category = Repo.insert!(%Category{name: "Other"}) smallest_category = Repo.insert!(%Category{name: "Smallest"}) Repo.insert!(%Record{ category_id: most_category.id, title: "Most functional gadgets in a cosplay suit", description: "The most functional gadgets in a cosplay suit is 23, in a Batman suit created by Julian Checkley (UK), demonstrated in Galway, Ireland, on 1 November 2015.", image_url: "https://guinnessworldrecords.com/assets/1227600?width=780&height=497" }) Repo.insert!(%Record{ category_id: fastest_category.id, title: "Fastest Any% completion of Monster Hunter: World", description: "The fastest Any% completion of Monster Hunter: World is 5 hr 18 min 28 sec, and was achieved by mosstkm (Japan) on 10 February 2019, as verified by speedrun.com.", image_url: "https://guinnessworldrecords.com/assets/2064235?width=780&height=497" }) Repo.insert!(%Record{ category_id: largest_category.id, title: "Largest arcade machine", description: "The largest arcade machine is 4.41 m tall, 1.93 m wide and 1.06 metres deep, and was achieved by Jason Camberis (USA) as verified in Bensenville, Illinois, USA, on 23 March 2014.", image_url: "https://guinnessworldrecords.com/assets/2030296?width=780&height=497" }) Repo.insert!(%Record{ category_id: highest_category.id, title: "Highest margin of victory against computer on 2014 FIFA World Cup Brazil", description: "The highest margin of victory against computer on 2014 FIFA World Cup Brazil is 321 goals, achieved by Patrick Hadler (Germany), in Rethem, Germany, on 28 May 2014.", image_url: "https://guinnessworldrecords.com/assets/890142?width=780&height=497" }) Repo.insert!(%Record{ category_id: other_category.id, title: "First PlayStation 2 game to support online play", description: "The earliest Playstation 2 game to allow online play was Tony Hawk’s Pro Skater 3, published by Activision, released in 2001. Unlike later online titles this could be done without the need for an adaptor, by using a standard usB connector and a dial-up connection.", image_url: "https://guinnessworldrecords.com/assets/2064228?width=780&height=497" }) Repo.insert!(%Record{ category_id: other_category.id, title: "First robot table tennis tutor", description: "In October 2015, Japan’s Omron Corporation introduced its robotic table tennis tutor. Sensors above the table tennis table monitor the position of the ball 80 times per second, enabling the robot to show via a projected image where it will return the ball off its bat and even where it will bounce to. The aim is to help teach the game to human players,with the robot's software capable of assessing all aspects of the ball's motion when bouncing off the table and through the air. Developing the control algorithm required for the robot to position the bat and return the ball took many hours of effort: with timing precision down to one thousandth of a second, the robot is programmed to make an effort to return the ball by extending its arm even in response to a badly played ball by its human pupil that would be impossible to play.", image_url: "https://guinnessworldrecords.com/assets/1327617?width=780&height=497" }) Repo.insert!(%Record{ category_id: most_category.id, title: "Most robots dancing simultaneously", description: "The most robots dancing simultaneously is 1,372 and was achieved by TIM S.p.A. (Italy) in Rome, Italy, on 1 February 2018.", image_url: "https://guinnessworldrecords.com/assets/1677903?width=780&height=497" }) Repo.insert!(%Record{ category_id: other_category.id, title: "First hypertext browser", description: "In October 1990 Tim Berners-Lee (UK) started work on a global hypertext browser and WorldWideWeb — was made available on the Internet in the summer of 1991. Berners-Lee had originally proposed a global hypertext project to allow people to combine their knowledge in a web of hypertext documents in 1989.", image_url: "https://guinnessworldrecords.com/assets/1433696?width=780&height=497" }) Repo.insert!(%Record{ category_id: fastest_category.id, title: "Fastest robot to solve a Rubik's Cube", description: "The fastest robot to solve a Rubik's Cube is “Sub1 Reloaded” with a time of 0.637 seconds, built by Albert Beer (Germany), and demonstrated at the Infineon booth at the electronica trade fair in Munich, Germany, 09 November 2016.", image_url: "https://guinnessworldrecords.com/assets/1433717?width=780&height=497" }) Repo.insert!(%Record{ category_id: other_category.id, title: "First bionic arm fitted on an individual (male)", description: "Since 1993, Scottish hotel owner Campbell Aird, who had his right arm amputated in 1982 after doctors diagnosed muscular cancer, has been trying out a new bionic arm created by a team of five bio-engineers at the Margaret Rose Hospital, Edinburgh, UK. Two other motorised artificial arms have been developed in America, but these were essentially only powered elbows.", image_url: "https://guinnessworldrecords.com/assets/1433700?width=780&height=497" }) Repo.insert!(%User{ date_of_birth: ~D[2000-01-01], email: "[email protected]", name: "Jane Doe", pin: "0000", system: true })
53.72807
844
0.760163
f784fa58b7092851881825e62524ae4ea97c2548
6,863
ex
Elixir
lib/asciinema/accounts/accounts.ex
potherca-contrib/asciinema-server
c5ac6e45e8f117d4d59c9c33da6b59b448e40f0e
[ "Apache-2.0" ]
null
null
null
lib/asciinema/accounts/accounts.ex
potherca-contrib/asciinema-server
c5ac6e45e8f117d4d59c9c33da6b59b448e40f0e
[ "Apache-2.0" ]
null
null
null
lib/asciinema/accounts/accounts.ex
potherca-contrib/asciinema-server
c5ac6e45e8f117d4d59c9c33da6b59b448e40f0e
[ "Apache-2.0" ]
null
null
null
defmodule Asciinema.Accounts do import Ecto.Query, warn: false import Ecto, only: [assoc: 2, build_assoc: 2] alias Asciinema.Accounts.{User, ApiToken} alias Asciinema.{Repo, Asciicasts, Email, Mailer} def create_asciinema_user!() do attrs = %{username: "asciinema", name: "asciinema", email: "[email protected]"} user = case Repo.get_by(User, username: "asciinema") do nil -> %User{} |> User.create_changeset(attrs) |> Repo.insert! user -> user end if Repo.count(assoc(user, :asciicasts)) == 0 do upload = %Plug.Upload{path: "priv/welcome.json", filename: "asciicast.json", content_type: "application/json"} {:ok, _} = Asciicasts.create_asciicast(user, upload, %{private: false, snapshot_at: 76.2}) end :ok end def change_user(user) do User.changeset(user) end def update_user(user, params) do user |> User.update_changeset(params) |> Repo.update end def send_login_email(email_or_username) do with {:ok, %User{} = user} <- lookup_user(email_or_username) do do_send_login_email(user) end end defp lookup_user(email_or_username) do if String.contains?(email_or_username, "@") do lookup_user_by_email(email_or_username) else lookup_user_by_username(email_or_username) end end defp lookup_user_by_email(email) do case Repo.get_by(User, email: email) do %User{} = user -> {:ok, user} nil -> case User.signup_changeset(%{email: email}) do %{errors: [{:email, _}]} -> {:error, :email_invalid} %{errors: []} -> {:ok, %User{email: email}} end end end defp lookup_user_by_username(username) do case Repo.get_by(User, username: username) do %User{} = user -> {:ok, user} nil -> {:error, :user_not_found} end end defp do_send_login_email(%User{email: nil}) do {:error, :email_missing} end defp do_send_login_email(%User{id: nil, email: email}) do url = signup_url(email) Email.signup_email(email, url) |> Mailer.deliver_later {:ok, url} end defp do_send_login_email(%User{} = user) do url = login_url(user) Email.login_email(user.email, url) |> Mailer.deliver_later {:ok, url} end def signup_token(email) do Phoenix.Token.sign(AsciinemaWeb.Endpoint, "signup", email) end def signup_url(email) do token = signup_token(email) AsciinemaWeb.Router.Helpers.users_url(AsciinemaWeb.Endpoint, :new, t: token) end def login_token(%User{id: id, last_login_at: last_login_at}) do last_login_at = last_login_at && Timex.to_unix(last_login_at) Phoenix.Token.sign(AsciinemaWeb.Endpoint, "login", {id, last_login_at}) end def login_url(%User{} = user) do token = login_token(user) AsciinemaWeb.Router.Helpers.session_url(AsciinemaWeb.Endpoint, :new, t: token) end @login_token_max_age 15 * 60 # 15 minutes alias Phoenix.Token alias AsciinemaWeb.Endpoint def verify_signup_token(token) do with {:ok, email} <- Token.verify(Endpoint, "signup", token, max_age: @login_token_max_age), {:ok, %User{} = user} <- Repo.insert(User.signup_changeset(%{email: email})) do {:ok, user} else {:error, :invalid} -> {:error, :token_invalid} {:error, %Ecto.Changeset{}} -> {:error, :email_taken} {:error, _} -> {:error, :token_expired} end end def verify_login_token(token) do with {:ok, {user_id, last_login_at}} <- Token.verify(Endpoint, "login", token, max_age: @login_token_max_age), %User{} = user <- Repo.get(User, user_id), ^last_login_at <- user.last_login_at && Timex.to_unix(user.last_login_at) do {:ok, user} else {:error, :invalid} -> {:error, :token_invalid} nil -> {:error, :user_not_found} _ -> {:error, :token_expired} end end def get_user_with_api_token(token, tmp_username \\ nil) do case get_api_token(token) do {:ok, %ApiToken{user: user}} -> {:ok, user} {:error, :token_revoked} = res -> res {:error, :token_not_found} -> create_user_with_api_token(token, tmp_username) end end def create_user_with_api_token(token, tmp_username) do user_changeset = User.temporary_changeset(tmp_username) Repo.transaction(fn -> with {:ok, %User{} = user} <- Repo.insert(user_changeset), {:ok, %ApiToken{}} <- create_api_token(user, token) do user else {:error, %Ecto.Changeset{}} -> Repo.rollback(:token_invalid) {:error, reason} -> Repo.rollback(reason) result -> Repo.rollback(result) end end) end def create_api_token(%User{} = user, token) do result = user |> build_assoc(:api_tokens) |> ApiToken.create_changeset(token) |> Repo.insert case result do {:ok, api_token} -> {:ok, %{api_token | user: user}} {:error, %Ecto.Changeset{}} -> {:error, :token_invalid} end end def get_or_create_api_token(token, user) do with {:ok, token} <- get_api_token(token) do {:ok, token} else {:error, :token_not_found} -> create_api_token(user, token) otherwise -> otherwise end end def get_api_token(token) do api_token = ApiToken |> Repo.get_by(token: token) |> Repo.preload(:user) case api_token do nil -> {:error, :token_not_found} %ApiToken{revoked_at: nil} -> {:ok, api_token} %ApiToken{} -> {:error, :token_revoked} end end def get_api_token!(user, id) do Repo.get!(assoc(user, :api_tokens), id) end def get_api_token!(token) do Repo.get_by!(ApiToken, token: token) end def revoke_api_token!(api_token) do api_token |> ApiToken.revoke_changeset |> Repo.update! end def merge!(dst_user, src_user) do Repo.transaction(fn -> asciicasts_q = from(assoc(src_user, :asciicasts)) Repo.update_all(asciicasts_q, set: [user_id: dst_user.id, updated_at: Timex.now]) api_tokens_q = from(assoc(src_user, :api_tokens)) Repo.update_all(api_tokens_q, set: [user_id: dst_user.id, updated_at: Timex.now]) Repo.delete!(src_user) dst_user end) end def list_api_tokens(%User{} = user) do user |> assoc(:api_tokens) |> Repo.all end def add_admins(emails) do from(u in User, where: u.email in ^emails) |> Repo.update_all(set: [is_admin: true]) end def remove_admins(emails) do from(u in User, where: u.email in ^emails) |> Repo.update_all(set: [is_admin: false]) end end
26.913725
114
0.615474
f7850a95a11b93f62e34407a00c118ed9780074a
128
exs
Elixir
implementations/elixir/ockam/ockam_hub/test/test_helper.exs
piotr-cla/ockam
914cd3ec1620181ac64ad2fb13d843f3eb184464
[ "Apache-2.0" ]
null
null
null
implementations/elixir/ockam/ockam_hub/test/test_helper.exs
piotr-cla/ockam
914cd3ec1620181ac64ad2fb13d843f3eb184464
[ "Apache-2.0" ]
110
2021-08-06T17:16:52.000Z
2022-03-28T17:20:54.000Z
implementations/elixir/ockam/ockam_hub/test/test_helper.exs
piotr-cla/ockam
914cd3ec1620181ac64ad2fb13d843f3eb184464
[ "Apache-2.0" ]
null
null
null
Application.ensure_all_started(:ockam) Application.ensure_all_started(:ockam_hub) ExUnit.start(capture_log: true, trace: true)
25.6
44
0.835938
f7850b5d9e29b0c258cbf737eeaf384c7e871d3a
2,449
exs
Elixir
config/dev.exs
isabella232/console-2
d4a4aca0e11c945c9698f46cb171d4645177038a
[ "Apache-2.0" ]
null
null
null
config/dev.exs
isabella232/console-2
d4a4aca0e11c945c9698f46cb171d4645177038a
[ "Apache-2.0" ]
1
2021-04-03T09:29:31.000Z
2021-04-03T09:29:31.000Z
config/dev.exs
isabella232/console-2
d4a4aca0e11c945c9698f46cb171d4645177038a
[ "Apache-2.0" ]
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 :console, ConsoleWeb.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [yarn: ["run", "watch", cd: Path.expand("../assets", __DIR__)]] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # command from your terminal: # # openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem # # The `http:` config above can be replaced with: # # https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Watch static and templates for browser reloading. config :console, ConsoleWeb.Endpoint, live_reload: [ patterns: [ ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$}, ~r{priv/gettext/.*(po)$}, ~r{lib/console_web/views/.*(ex)$}, ~r{lib/console_web/templates/.*(eex)$} ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Configure your database config :console, Console.Repo, adapter: Ecto.Adapters.Postgres, username: "postgres", password: "postgres", database: "console_dev", hostname: "localhost", pool_size: 10 config :cloak, Cloak.AES.CTR, tag: "AES", default: true, keys: [ %{tag: <<1>>, key: :base64.decode("/QCxhn/9t2SM8GiLXVDR1jFO/vENLGCnXADGAhGPM30="), default: true} ] config :console, router_secrets: [ "1524243720:2JD3juUA9RGaOf3Fpj7fNOylAgZ/jAalgOe45X6+jW4sy9gyCy1ELJrIWKvrgMx/" ] config :console, Console.Mailer, adapter: Bamboo.LocalAdapter config :console, oui: 1 config :console, stripe_secret_key: "sk_test_Lvy2r3SRCzwjfh3tvZsOBTrG00Cm8M7v1q" config :console, allowed_ip_range: ["127.0.0.1"] config :logger, level: :debug
29.506024
170
0.708452
f7854149b2db8e62b2e6b3f61cda55317b13b213
585
ex
Elixir
oeml-sdk/elixir/lib/oeml_restapi/model/ord_status.ex
Martin-Molinero/coinapi-sdk
8633f61e0809e7ee4032100fe08454e8c4ad5e0c
[ "MIT" ]
357
2017-05-29T15:09:19.000Z
2022-03-30T15:34:10.000Z
oeml-sdk/elixir/lib/oeml_restapi/model/ord_status.ex
Martin-Molinero/coinapi-sdk
8633f61e0809e7ee4032100fe08454e8c4ad5e0c
[ "MIT" ]
68
2017-12-15T15:39:14.000Z
2022-02-11T11:28:17.000Z
oeml-sdk/elixir/lib/oeml_restapi/model/ord_status.ex
Martin-Molinero/coinapi-sdk
8633f61e0809e7ee4032100fe08454e8c4ad5e0c
[ "MIT" ]
199
2017-06-01T07:51:14.000Z
2022-03-25T11:52:28.000Z
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). # https://openapi-generator.tech # Do not edit the class manually. defmodule OEML-RESTAPI.Model.OrdStatus do @moduledoc """ Order statuses and the lifecycle are documented in the separate section: <a href=\"#oeml-order-lifecycle\">OEML / Starter Guide / Order Lifecycle</a> """ @derive [Poison.Encoder] defstruct [ ] @type t :: %__MODULE__{ } end defimpl Poison.Decoder, for: OEML-RESTAPI.Model.OrdStatus do def decode(value, _options) do value end end
22.5
152
0.704274