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
79319e99f1e3eff1291d4a41f6d13f9a571807d2
1,713
ex
Elixir
clients/docs/lib/google_api/docs/v1/model/delete_footer_request.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/docs/lib/google_api/docs/v1/model/delete_footer_request.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/docs/lib/google_api/docs/v1/model/delete_footer_request.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Docs.V1.Model.DeleteFooterRequest do @moduledoc """ Deletes a Footer from the document. ## Attributes * `footerId` (*type:* `String.t`, *default:* `nil`) - The id of the footer to delete. If this footer is defined on DocumentStyle, the reference to this footer is removed, resulting in no footer of that type for the first section of the document. If this footer is defined on a SectionStyle, the reference to this footer is removed and the footer of that type is now continued from the previous section. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :footerId => String.t() } field(:footerId) end defimpl Poison.Decoder, for: GoogleApi.Docs.V1.Model.DeleteFooterRequest do def decode(value, options) do GoogleApi.Docs.V1.Model.DeleteFooterRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Docs.V1.Model.DeleteFooterRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.446809
406
0.747227
7931acc9c846e5f76c6c2c6ba94273d8b5eaeddf
2,114
exs
Elixir
test/lib/code_corps/analytics/segment_traits_builder_test.exs
fikape/code-corps-api
c21674b0b2a19fa26945c94268db8894420ca181
[ "MIT" ]
275
2015-06-23T00:20:51.000Z
2021-08-19T16:17:37.000Z
test/lib/code_corps/analytics/segment_traits_builder_test.exs
fikape/code-corps-api
c21674b0b2a19fa26945c94268db8894420ca181
[ "MIT" ]
1,304
2015-06-26T02:11:54.000Z
2019-12-12T21:08:00.000Z
test/lib/code_corps/analytics/segment_traits_builder_test.exs
fikape/code-corps-api
c21674b0b2a19fa26945c94268db8894420ca181
[ "MIT" ]
140
2016-01-01T18:19:47.000Z
2020-11-22T06:24:47.000Z
defmodule CodeCorps.Analytics.SegmentTraitsBuilderTest do @moduledoc false use CodeCorps.DbAccessCase alias CodeCorps.Analytics.SegmentTraitsBuilder describe "build/1" do # NOTE: These tests only make sure there's a function clause for each # supported struct and do not assert the traits content. Simply put, the # only way to assert that would mean we're practically re-implementing the # builder within tests test "works for all supported struct types" do assert :comment |> insert |> SegmentTraitsBuilder.build assert :donation_goal |> insert |> SegmentTraitsBuilder.build assert :github_app_installation |> insert |> SegmentTraitsBuilder.build assert :github_repo |> insert |> SegmentTraitsBuilder.build assert :project |> insert |> SegmentTraitsBuilder.build assert :project_skill |> insert |> SegmentTraitsBuilder.build assert :project_user |> insert |> SegmentTraitsBuilder.build data = %{ acceptor: insert(:user), project_user: insert(:project_user) } assert SegmentTraitsBuilder.build(data) assert :stripe_connect_account |> insert |> SegmentTraitsBuilder.build assert :stripe_connect_charge |> insert |> SegmentTraitsBuilder.build assert :stripe_connect_plan |> insert |> SegmentTraitsBuilder.build assert :stripe_connect_subscription |> insert |> SegmentTraitsBuilder.build assert :stripe_platform_card |> insert |> SegmentTraitsBuilder.build assert :stripe_platform_customer |> insert |> SegmentTraitsBuilder.build assert :task |> insert |> SegmentTraitsBuilder.build assert :task_skill |> insert |> SegmentTraitsBuilder.build assert :user |> insert |> SegmentTraitsBuilder.build assert :user_category |> insert |> SegmentTraitsBuilder.build assert :user_role |> insert |> SegmentTraitsBuilder.build assert :user_skill |> insert |> SegmentTraitsBuilder.build assert :user_task |> insert |> SegmentTraitsBuilder.build assert %{token: "foo", user_id: 1} |> SegmentTraitsBuilder.build end end end
40.653846
81
0.727058
7931cf622f4c8fd609aad84a7bc99b41a4a56a37
874
ex
Elixir
lib/tanegashima/user.ex
massn/Tanegashima
d7a473500dfccf6e15f89848f22e4194b87108cb
[ "MIT" ]
4
2016-02-17T13:15:51.000Z
2017-04-29T16:12:55.000Z
lib/tanegashima/user.ex
massn/Tanegashima
d7a473500dfccf6e15f89848f22e4194b87108cb
[ "MIT" ]
1
2017-05-25T06:55:18.000Z
2021-02-27T21:03:15.000Z
lib/tanegashima/user.ex
massn/Tanegashima
d7a473500dfccf6e15f89848f22e4194b87108cb
[ "MIT" ]
1
2017-04-29T16:12:56.000Z
2017-04-29T16:12:56.000Z
defmodule Tanegashima.User do @moduledoc""" Elixir wrapper for Pushbullet-User-API. """ defstruct [:active, :created, :email, :email_normalized, :iden, :image_url, :max_upload_size, :modified, :name, :referred_count, :referrer_iden] @type t :: %__MODULE__{} @user_api "https://api.pushbullet.com/v2/users/me" @doc""" get your user info. """ @spec get :: {:ok, Tanegashima.User.t} | {:error, term} def get do with {:ok, %{status_code: status_code, body: response}} <- HTTPoison.get(@user_api, [{"Access-Token", Tanegashima.access_token}]), {:error, [status_code: 200, response: ^response]} <- {:error, [status_code: status_code, response: response]}, {:ok, poison_struct} <- Poison.decode(response, as: %{}), do: Tanegashima.to_struct(Tanegashima.User, poison_struct) end end
32.37037
95
0.636156
7931d29530e1b6cfd32d0b376d43927b0e7774b7
199
exs
Elixir
chatourius/test/controllers/page_controller_test.exs
Dmdv/ElixirPlayground
02d9e8a7fdd6e8742e200430debc9f0ec7fd28a1
[ "Apache-2.0" ]
null
null
null
chatourius/test/controllers/page_controller_test.exs
Dmdv/ElixirPlayground
02d9e8a7fdd6e8742e200430debc9f0ec7fd28a1
[ "Apache-2.0" ]
null
null
null
chatourius/test/controllers/page_controller_test.exs
Dmdv/ElixirPlayground
02d9e8a7fdd6e8742e200430debc9f0ec7fd28a1
[ "Apache-2.0" ]
null
null
null
defmodule Chatourius.PageControllerTest do use Chatourius.ConnCase test "GET /", %{conn: conn} do conn = get conn, "/" assert html_response(conn, 200) =~ "Welcome to Phoenix!" end end
22.111111
60
0.683417
7931f24657287631b15756c77d648482f7b9211c
4,040
exs
Elixir
apps/ewallet_db/test/ewallet_db/user_backup_code_test.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
322
2018-02-28T07:38:44.000Z
2020-05-27T23:09:55.000Z
apps/ewallet_db/test/ewallet_db/user_backup_code_test.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
643
2018-02-28T12:05:20.000Z
2020-05-22T08:34:38.000Z
apps/ewallet_db/test/ewallet_db/user_backup_code_test.exs
AndonMitev/EWallet
898cde38933d6f134734528b3e594eedf5fa50f3
[ "Apache-2.0" ]
63
2018-02-28T10:57:06.000Z
2020-05-27T23:10:38.000Z
# Copyright 2018-2019 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule EWalletDB.UserBackupCodeTest do use EWalletDB.SchemaCase, async: true import EWalletDB.Factory alias EWalletDB.{UserBackupCode} alias Utils.Helpers.Crypto describe "insert/1" do test "returns :ok when given hashed_backup_codes and user_uuid" do user = insert(:user) backup_codes = ["1234", "5678"] expected_hashed_backup_codes = Enum.map(backup_codes, &Crypto.hash_secret/1) assert {:ok, user_backup_codes} = UserBackupCode.insert_multiple(%{ backup_codes: backup_codes, user_uuid: user.uuid }) # Verify all inserted hashed_backup_codes are matched with the given backup_codes assert Enum.map(user_backup_codes, fn {_, user_backup_code} -> user_backup_code.hashed_backup_code end) == expected_hashed_backup_codes # Verify all user_backup_codes are belong to given user. # Verify all user_backup_codes.used_at are nil assert Enum.all?(user_backup_codes, fn {_, user_backup_code} -> user_backup_code.user_uuid == user.uuid and user_backup_code.used_at == nil end) end test "returns {:error, :invalid_parameter} when the user_uuid is nil or missing" do attrs = %{ backup_codes: ["1234"], user_uuid: nil } assert UserBackupCode.insert_multiple(attrs) == {:error, :invalid_parameter} end end describe "all_for_user/1" do test "returns all user_backup_codes belong to the user when given a valid uuid" do %{uuid: user_uuid} = insert(:user) backup_codes = ["1234", "5678"] UserBackupCode.insert_multiple(%{ backup_codes: backup_codes, user_uuid: user_uuid }) assert [user_backup_code_1, user_backup_code_2] = UserBackupCode.all_for_user(user_uuid) assert user_backup_code_1.user_uuid == user_uuid assert user_backup_code_2.user_uuid == user_uuid end test "return empty list when the user_backup_codes are not found for given user" do user = insert(:user) assert UserBackupCode.all_for_user(user.uuid) == [] end end describe "delete_for_user/1" do test "returns :ok when delete all user_backup_codes belong to the given user_uuid" do user = insert(:user) backup_codes = ["1234", "5678"] UserBackupCode.insert_multiple(%{ backup_codes: backup_codes, user_uuid: user.uuid }) assert UserBackupCode.delete_for_user(user.uuid) == :ok assert UserBackupCode.all_for_user(user.uuid) == [] end end describe "invalidate/1" do test "return {:ok, updated_user_backup_code} and set given user_backup_code.used_at to now when specify a valid user_backup_code" do user = insert(:user) backup_codes = ["1234", "5678"] expected_hashed_backup_code_1 = Crypto.hash_secret(hd(backup_codes)) {:ok, attrs} = UserBackupCode.insert_multiple(%{ backup_codes: backup_codes, user_uuid: user.uuid }) # Invalidate the first backup code assert {:ok, updated_user_backup_code} = UserBackupCode.invalidate(attrs.insert_user_backup_code_0) # Assert the first backup code has non-nil `used_at`, so we can't use later. assert updated_user_backup_code.hashed_backup_code == expected_hashed_backup_code_1 assert updated_user_backup_code.used_at != nil end end end
35.130435
136
0.690842
7931fd8fe50f006a518d19a32dad83a2557942d1
3,612
ex
Elixir
lib/helper.ex
heywhy/elixir-request-validator
928094c9eed3808844b3cc0bfca445148a6df710
[ "MIT" ]
2
2020-10-07T05:23:37.000Z
2022-01-11T05:44:12.000Z
lib/helper.ex
heywhy/elixir-request-validator
928094c9eed3808844b3cc0bfca445148a6df710
[ "MIT" ]
null
null
null
lib/helper.ex
heywhy/elixir-request-validator
928094c9eed3808844b3cc0bfca445148a6df710
[ "MIT" ]
1
2020-10-04T03:55:42.000Z
2020-10-04T03:55:42.000Z
defmodule Request.Validator.Helper do alias Request.Validator.Rules.Map_ @doc """ A wrapper around the `{:in_list, options}` rule. iex> Request.Validator.Helper.in_list(["male", "female"]) {:in_list, ~w[male female]} iex> Request.Validator.Helper.in_list(~w[tech law finance]) {:in_list, ["tech", "law", "finance"]} iex> Request.Validator.Helper.in_list(~w[doctor nurse nurse midwife specialist midwife doctor]) {:in_list, ~w[doctor nurse midwife specialist]} """ @spec in_list(list(any())) :: {:in_list, list(any())} def in_list(options) when is_list(options), do: {:in_list, Enum.uniq(options)} @doc """ A wrapper around the `{:gt, field}` rule. iex> Request.Validator.Helper.gt(:age) {:gt, :age} iex> Request.Validator.Helper.gt(:year) {:gt, :year} """ @spec gt(atom()) :: {:gt, atom()} def gt(field), do: {:gt, field} @doc """ A wrapper around the `{:lt, field}` rule. iex> Request.Validator.Helper.lt(:age) {:lt, :age} iex> Request.Validator.Helper.lt(:year) {:lt, :year} """ @spec lt(atom()) :: {:lt, atom()} def lt(field), do: {:lt, field} @doc """ A wrapper around the `{:max, value}` rule. iex> Request.Validator.Helper.max(30) {:max, 30} iex> Request.Validator.Helper.max(40) {:max, 40} """ @spec max(number()) :: {:max, number()} def max(value) when is_number(value), do: {:max, value} @doc """ A wrapper around the `{:min, value}` rule. iex> Request.Validator.Helper.min(30) {:min, 30} iex> Request.Validator.Helper.min(40) {:min, 40} """ @spec min(number()) :: {:min, number()} def min(value), do: {:min, value} @doc """ A wrapper around the `required` rule. iex> Request.Validator.Helper.required(:string) ~w[required string]a iex> Request.Validator.Helper.required([:string, :email, {:max, 100}]) [:required, :string, :email, {:max, 100}] iex> Request.Validator.Helper.required({:max, 100}) [:required, {:max, 100}] """ def required(rule) when is_atom(rule), do: required([rule]) def required(rule) when is_tuple(rule), do: required([rule]) def required(rules) when is_list(rules), do: [:required] ++ rules @doc """ A wrapper around the `{:size, value}` rule. iex> Request.Validator.Helper.size(30) {:size, 30} iex> Request.Validator.Helper.size(40) {:size, 40} """ @spec size(number()) :: {:size, number()} def size(value), do: {:size, value} @doc """ Makes a nested map input validation nullable. iex> alias Request.Validator.{Helper, Rules} [Request.Validator.Helper, Request.Validator.Rules] iex> Helper.nullable(Rules.map(name: ~w[required string]a)) %Rules.Map_{attrs: [name: ~w[required string]a], nullable: true} iex> Rules.map(name: ~w[required string]a) %Rules.Map_{attrs: [name: ~w[required string]a], nullable: false} """ def nullable(%Map_{} = map), do: struct!(map, %{nullable: true}) @doc """ A wrapper around the `{:unique, callback}` rule. iex> alias Request.Validator.Helper Request.Validator.Helper iex> {:unique, _} = Helper.unique(&(&1 == 10)) """ def unique(callback), do: {:unique, callback} @doc """ A wrapper around the `{:exists, callback}` rule. iex> alias Request.Validator.Helper Request.Validator.Helper iex> {:exists, _} = Helper.exists(&(&1 == 10)) """ def exists(callback), do: {:exists, callback} @doc """ A wrapper around the `{:phone_number, region}` rule. iex> alias Request.Validator.Helper Request.Validator.Helper iex> {:phone_number, _} = Helper.phone_number(&(&1 == 10)) """ def phone_number(region), do: {:phone_number, region} end
28.896
97
0.643411
7931fe003a4bcb12c753738754aa850c0619ad3f
1,799
ex
Elixir
lib/files_sorted_by_sizes.ex
innaky/files_sorted_by_sizes
9f4db07e273886a502944d1cca4db2d12ed02e48
[ "MIT" ]
null
null
null
lib/files_sorted_by_sizes.ex
innaky/files_sorted_by_sizes
9f4db07e273886a502944d1cca4db2d12ed02e48
[ "MIT" ]
1
2020-06-24T02:33:19.000Z
2020-06-24T02:33:19.000Z
lib/files_sorted_by_sizes.ex
innaky/files_sorted_by_sizes
9f4db07e273886a502944d1cca4db2d12ed02e48
[ "MIT" ]
null
null
null
defmodule FilesSortedBySizes do @moduledoc """ Return a list of list with filenames of a directory sorted by size. """ @doc """ List greater Directory. Return a list of list with filenames of a directory sorted by size. But is functional only with a file directory. ## Examples iex> FilesSortedBySizes.lg_dir(".") """ def lg_dir(filedir) do lst_name_size = lg_name_size(filedir) Enum.sort(lst_name_size, fn x, y -> List.last(x) > List.last(y) end) end @doc """ List Greater. Return a list of list with filenames of a directory sorted by size. if `filename` is not a directory, return a list with the filename and the size of this file. ## Examples iex> FilesSortedBySizes.lg(".") """ def lg(filename) do {:ok, file} = File.lstat(filename) if file.type != :directory do [filename, file.size] else lg_dir(filename) end end @doc """ Return a list of list with filenames of a directory. ## Examples iex> FilesSortedBySizes.lg_name_size(".") """ def lg_name_size(filedir) do {:ok, lst_files} = File.ls(filedir) lst_files_abs = lg_abs(filedir, lst_files) lg_size(lst_files_abs) end @doc """ Concatenate the output of `File.ls/1` with the `base_path` for all filenames. """ def lg_abs(base_path, []), do: [] def lg_abs(base_path, [h|t]) do [base_path <> "/" <> h | lg_abs(base_path, t)] end @doc """ Extract the filename and the file.size of a list of files. Job with absolute filepaths """ def lg_size([]), do: [] def lg_size([h|t]) do [name_size(h) | lg_size(t)] end @doc """ Return a list with the filename and filesize. """ def name_size(filename) do {:ok, file} = File.lstat(filename) [filename, file.size] end end
22.772152
93
0.645914
79324202145c52f493364155a80a5eaf75b1f06f
71
ex
Elixir
test/support/function_int.ex
olafura/beam_to_ex_ast
5451d189105c3a4b52aedbf4fbc4f0beca3b9b80
[ "Apache-2.0" ]
16
2016-02-12T15:15:58.000Z
2021-08-24T21:48:34.000Z
test/support/function_int.ex
olafura/beam_to_ex_ast
5451d189105c3a4b52aedbf4fbc4f0beca3b9b80
[ "Apache-2.0" ]
1
2016-02-17T04:58:38.000Z
2016-02-17T04:58:38.000Z
test/support/function_int.ex
olafura/beam_to_ex_ast
5451d189105c3a4b52aedbf4fbc4f0beca3b9b80
[ "Apache-2.0" ]
2
2016-02-17T03:21:23.000Z
2016-03-08T09:23:27.000Z
defmodule TestFunctionInt do def hello() do IO.puts(1) end end
11.833333
28
0.690141
79326389d9693d8b482fc97dac52f43dd41c010d
1,181
ex
Elixir
clients/policy_simulator/lib/google_api/policy_simulator/v1/connection.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/policy_simulator/lib/google_api/policy_simulator/v1/connection.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/policy_simulator/lib/google_api/policy_simulator/v1/connection.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.PolicySimulator.V1.Connection do @moduledoc """ Handle Tesla connections for GoogleApi.PolicySimulator.V1. """ @type t :: Tesla.Env.client() use GoogleApi.Gax.Connection, scopes: [ # See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account. "https://www.googleapis.com/auth/cloud-platform" ], otp_app: :google_api_policy_simulator, base_url: "https://policysimulator.googleapis.com/" end
35.787879
114
0.744285
793268554fdef2ea89cde2abd392cbe311edd03c
1,580
exs
Elixir
test/rendering/wrapped_attributes_test.exs
thepeoplesbourgeois/slime
55c4d738632ed6540a0a03e0a4022b02e398c2d9
[ "MIT" ]
312
2015-12-28T05:25:47.000Z
2022-02-16T05:18:16.000Z
test/rendering/wrapped_attributes_test.exs
thepeoplesbourgeois/slime
55c4d738632ed6540a0a03e0a4022b02e398c2d9
[ "MIT" ]
105
2015-12-27T21:20:58.000Z
2022-02-24T05:23:38.000Z
test/rendering/wrapped_attributes_test.exs
thepeoplesbourgeois/slime
55c4d738632ed6540a0a03e0a4022b02e398c2d9
[ "MIT" ]
45
2016-01-12T04:02:01.000Z
2021-09-14T16:19:18.000Z
defmodule RenderWrappedAttributesTest do use ExUnit.Case, async: true import Slime, only: [render: 1, render: 2] test "rendering of boolean attributes" do assert render(~s(div [ab="ab" a] a)) == ~s(<div a ab="ab">a</div>) assert render(~s(div [a b="b"] c)) == ~s(<div a b="b">c</div>) assert render(~S(div ab="#{b} a" a), b: "b") == ~s(<div ab="b a">a</div>) assert render(~S(div[ab="a #{b}" a] a), b: "b") == ~s(<div a ab="a b">a</div>) assert render(~S<div[ab="a #{b.("c")}" a] a>, b: & &1) == ~s(<div a ab="a c">a</div>) assert render(~S<div[ab="a #{b.({"c", "d"})}" a] a>, b: fn {_, r} -> r end) == ~s(<div a ab="a d">a</div>) assert render(~s(script[defer async src="..."])) == ~s(<script async defer src="..."></script>) end test "render of wrapped attributes with elixir code values" do slime = ~s(meta[name=other content="one two"]) assert render(slime, other: "1") == ~s(<meta content="one two" name="1">) end test "render of disabled wrapped attributes" do slime = "p {c=true}" assert render(slime) == ~s(<p>{c=true}</p>) end test "render of disabled wrapped attributes without space" do slime = "p{c=true}" assert render(slime) == ~s(<p>{c=true}</p>) end test ~s(show error message for div[id="test"} case) do assert_raise(Slime.TemplateSyntaxError, fn -> render(~S(div[id="test"})) end) end test ~s(show error message for div [id="test"} case with leading space) do assert_raise(Slime.TemplateSyntaxError, fn -> render(~S(div [id="test"})) end) end end
36.744186
110
0.584177
79327d6294b9c2ec9056a1b93b335dce9fbbc98f
1,270
ex
Elixir
lib/rocketseat_nlw_heat_impulse_elixir_web/router.ex
jobsonita/rocketseat_nlw_heat_impulse_elixir
13b5dc0fe2137c1acbc42afee1d40c43e7f9883f
[ "MIT" ]
null
null
null
lib/rocketseat_nlw_heat_impulse_elixir_web/router.ex
jobsonita/rocketseat_nlw_heat_impulse_elixir
13b5dc0fe2137c1acbc42afee1d40c43e7f9883f
[ "MIT" ]
null
null
null
lib/rocketseat_nlw_heat_impulse_elixir_web/router.ex
jobsonita/rocketseat_nlw_heat_impulse_elixir
13b5dc0fe2137c1acbc42afee1d40c43e7f9883f
[ "MIT" ]
null
null
null
defmodule RocketseatNlwHeatImpulseElixirWeb.Router do use RocketseatNlwHeatImpulseElixirWeb, :router pipeline :api do plug :accepts, ["json"] end scope "/api", RocketseatNlwHeatImpulseElixirWeb do pipe_through :api post "/message", MessagesController, :create end # Enables LiveDashboard only for development # # If you want to use the LiveDashboard in production, you should put # it behind authentication and allow only admins to access it. # If your application does not have an admins-only section yet, # you can use Plug.BasicAuth to set up some basic authentication # as long as you are also using SSL (which you should anyway). if Mix.env() in [:dev, :test] do import Phoenix.LiveDashboard.Router scope "/" do pipe_through [:fetch_session, :protect_from_forgery] live_dashboard "/dashboard", metrics: RocketseatNlwHeatImpulseElixirWeb.Telemetry end end # Enables the Swoosh mailbox preview in development. # # Note that preview only shows emails that were sent by the same # node running the Phoenix server. if Mix.env() == :dev do scope "/dev" do pipe_through [:fetch_session, :protect_from_forgery] forward "/mailbox", Plug.Swoosh.MailboxPreview end end end
30.238095
87
0.729134
793287b829b003c7689bde96a2fec31f4dce55ce
21,886
ex
Elixir
lib/ex_unit/lib/ex_unit/case.ex
razuf/elixir
a80b6d00738668f5ca2325bfc8c3581af5d531dc
[ "Apache-2.0" ]
null
null
null
lib/ex_unit/lib/ex_unit/case.ex
razuf/elixir
a80b6d00738668f5ca2325bfc8c3581af5d531dc
[ "Apache-2.0" ]
null
null
null
lib/ex_unit/lib/ex_unit/case.ex
razuf/elixir
a80b6d00738668f5ca2325bfc8c3581af5d531dc
[ "Apache-2.0" ]
null
null
null
defmodule ExUnit.DuplicateTestError do defexception [:message] end defmodule ExUnit.DuplicateDescribeError do defexception [:message] end defmodule ExUnit.Case do @moduledoc """ Helpers for defining test cases. This module must be used in other modules as a way to configure and prepare them for testing. When used, it accepts the following options: * `:async` - configures tests in this module to run concurrently with tests in other modules. Tests in the same module never run concurrently. It should be enabled only if tests do not change any global state. Defaults to `false`. This module automatically includes all callbacks defined in `ExUnit.Callbacks`. See that module for more information on `setup`, `start_supervised`, `on_exit` and the test process life cycle. For grouping tests together, see `describe/2` in this module. ## Examples defmodule AssertionTest do # Use the module use ExUnit.Case, async: true # The "test" macro is imported by ExUnit.Case test "always pass" do assert true end end ## Context All tests receive a context as an argument. The context is particularly useful for sharing information between callbacks and tests: defmodule KVTest do use ExUnit.Case setup do {:ok, pid} = KV.start_link() {:ok, pid: pid} end test "stores key-value pairs", context do assert KV.put(context[:pid], :hello, :world) == :ok assert KV.get(context[:pid], :hello) == :world end end As the context is a map, it can be pattern matched on to extract information: test "stores key-value pairs", %{pid: pid} = _context do assert KV.put(pid, :hello, :world) == :ok assert KV.get(pid, :hello) == :world end ## Tags The context is used to pass information from the callbacks to the test. In order to pass information from the test to the callback, ExUnit provides tags. By tagging a test, the tag value can be accessed in the context, allowing the developer to customize the test. Let's see an example: defmodule FileTest do # Changing directory cannot be async use ExUnit.Case, async: false setup context do # Read the :cd tag value if cd = context[:cd] do prev_cd = File.cwd!() File.cd!(cd) on_exit(fn -> File.cd!(prev_cd) end) end :ok end @tag cd: "fixtures" test "reads UTF-8 fixtures" do File.read("README.md") end end In the example above, we have defined a tag called `:cd` that is read in the setup callback to configure the working directory the test is going to run on. Tags are also very effective when used with case templates (`ExUnit.CaseTemplate`) allowing callbacks in the case template to customize the test behaviour. Note a tag can be set in two different ways: @tag key: value @tag :key # equivalent to setting @tag key: true If a tag is given more than once, the last value wins. ### Module and describe tags A tag can be set for all tests in a module or describe block by setting `@moduletag` or `@describetag` inside each context respectively: defmodule ApiTest do use ExUnit.Case @moduletag :external describe "makes calls to the right endpoint" do @describetag :endpoint # ... end end If you are setting a `@moduletag` or `@describetag` attribute, you must set them after your call to `use ExUnit.Case` otherwise you will see compilation errors. If the same key is set via `@tag`, the `@tag` value has higher precedence. ### Known tags The following tags are set automatically by ExUnit and are therefore reserved: * `:module` - the module on which the test was defined * `:file` - the file on which the test was defined * `:line` - the line on which the test was defined * `:test` - the test name * `:async` - if the test case is in async mode * `:registered` - used for `ExUnit.Case.register_attribute/3` values * `:describe` - the describe block the test belongs to The following tags customize how tests behave: * `:capture_log` - see the "Log Capture" section below * `:skip` - skips the test with the given reason * `:timeout` - customizes the test timeout in milliseconds (defaults to 60000). Accepts `:infinity` as a timeout value. * `:tmp_dir` - (since v1.11.0) see the "Tmp Dir" section below The `:test_type` tag is automatically set by ExUnit, but is **not** reserved. This tag is available for users to customize if they desire. ## Filters Tags can also be used to identify specific tests, which can then be included or excluded using filters. The most common functionality is to exclude some particular tests from running, which can be done via `ExUnit.configure/1`: # Exclude all external tests from running ExUnit.configure(exclude: [external: true]) From now on, ExUnit will not run any test that has the `:external` option set to `true`. This behaviour can be reversed with the `:include` option which is usually passed through the command line: mix test --include external:true Run `mix help test` for more information on how to run filters via Mix. Another use case for tags and filters is to exclude all tests that have a particular tag by default, regardless of its value, and include only a certain subset: ExUnit.configure(exclude: :os, include: [os: :unix]) A given include/exclude filter can be given more than once: ExUnit.configure(exclude: [os: :unix, os: :windows]) Keep in mind that all tests are included by default, so unless they are excluded first, the `include` option has no effect. ## Log Capture ExUnit can optionally suppress printing of log messages that are generated during a test. Log messages generated while running a test are captured and only if the test fails are they printed to aid with debugging. You can opt into this behaviour for individual tests by tagging them with `:capture_log` or enable log capture for all tests in the ExUnit configuration: ExUnit.start(capture_log: true) This default can be overridden by `@tag capture_log: false` or `@moduletag capture_log: false`. Since `setup_all` blocks don't belong to a specific test, log messages generated in them (or between tests) are never captured. If you want to suppress these messages as well, remove the console backend globally by setting: config :logger, backends: [] ## Tmp Dir ExUnit automatically creates a temporary directory for tests tagged with `:tmp_dir` and puts the path to that directory into the test context. The directory is removed before being created to ensure we start with a blank slate. The temporary directory path is unique (includes the test module and test name) and thus appropriate for running tests concurrently. You can customize the path further by setting the tag to a string, e.g.: `tmp_dir: "my_path"`, which would make the final path to be: `tmp/<module>/<test>/my_path`. Example: defmodule MyTest do use ExUnit.Case, async: true @tag :tmp_dir test "with tmp_dir", %{tmp_dir: tmp_dir} do assert tmp_dir =~ "with tmp_dir" assert File.dir?(tmp_dir) end end As with other tags, `:tmp_dir` can also be set as `@moduletag` and `@describetag`. """ @type env :: module() | Macro.Env.t() @reserved [:module, :file, :line, :test, :async, :registered, :describe] @doc false defmacro __using__(opts) do unless Process.whereis(ExUnit.Server) do raise "cannot use ExUnit.Case without starting the ExUnit application, " <> "please call ExUnit.start() or explicitly start the :ex_unit app" end quote do unless Module.has_attribute?(__MODULE__, :ex_unit_tests) do tag_check = [:moduletag, :describetag, :tag] |> Enum.any?(&Module.has_attribute?(__MODULE__, &1)) if tag_check do raise "you must set @tag, @describetag, and @moduletag after the call to \"use ExUnit.Case\"" end attributes = [ :ex_unit_tests, :tag, :describetag, :moduletag, :ex_unit_registered_test_attributes, :ex_unit_registered_describe_attributes, :ex_unit_registered_module_attributes, :ex_unit_used_describes ] Enum.each(attributes, &Module.register_attribute(__MODULE__, &1, accumulate: true)) @before_compile ExUnit.Case @after_compile ExUnit.Case @ex_unit_async false @ex_unit_describe nil use ExUnit.Callbacks end async = unquote(opts)[:async] if is_boolean(async) do @ex_unit_async async end import ExUnit.Callbacks import ExUnit.Assertions import ExUnit.Case, only: [describe: 2, test: 1, test: 2, test: 3] import ExUnit.DocTest end end @doc """ Defines a test with `message`. The test may also define a `var`, which will pattern match on the test context. For more information on contexts, see `ExUnit.Callbacks`. ## Examples test "true is equal to true" do assert true == true end """ defmacro test(message, var \\ quote(do: _), contents) do contents = case contents do [do: block] -> quote do unquote(block) :ok end _ -> quote do try(unquote(contents)) :ok end end var = Macro.escape(var) contents = Macro.escape(contents, unquote: true) quote bind_quoted: [var: var, contents: contents, message: message] do name = ExUnit.Case.register_test(__ENV__, :test, message, []) def unquote(name)(unquote(var)), do: unquote(contents) end end @doc """ Defines a not implemented test with a string. Provides a convenient macro that allows a test to be defined with a string, but not yet implemented. The resulting test will always fail and print a "Not implemented" error message. The resulting test case is also tagged with `:not_implemented`. ## Examples test "this will be a test in future" """ defmacro test(message) do quote bind_quoted: binding() do name = ExUnit.Case.register_test(__ENV__, :test, message, [:not_implemented]) def unquote(name)(_), do: flunk("Not implemented") end end @doc """ Describes tests together. Every describe block receives a name which is used as prefix for upcoming tests. Inside a block, `ExUnit.Callbacks.setup/1` may be invoked and it will define a setup callback to run only for the current block. The describe name is also added as a tag, allowing developers to run tests for specific blocks. ## Examples defmodule StringTest do use ExUnit.Case, async: true describe "String.capitalize/1" do test "first grapheme is in uppercase" do assert String.capitalize("hello") == "Hello" end test "converts remaining graphemes to lowercase" do assert String.capitalize("HELLO") == "Hello" end end end When using Mix, you can run all tests in a describe block by name: mix test --only describe:"String.capitalize/1" or by passing the exact line the describe block starts on: mix test path/to/file:123 Note describe blocks cannot be nested. Instead of relying on hierarchy for composition, developers should build on top of named setups. For example: defmodule UserManagementTest do use ExUnit.Case, async: true describe "when user is logged in and is an admin" do setup [:log_user_in, :set_type_to_admin] test ... end describe "when user is logged in and is a manager" do setup [:log_user_in, :set_type_to_manager] test ... end defp log_user_in(context) do # ... end end By forbidding hierarchies in favor of named setups, it is straightforward for the developer to glance at each describe block and know exactly the setup steps involved. """ defmacro describe(message, do: block) do quote do ExUnit.Case.__describe__(__MODULE__, __ENV__.line, unquote(message)) try do unquote(block) after @ex_unit_describe nil Module.delete_attribute(__MODULE__, :describetag) for attribute <- Module.get_attribute(__MODULE__, :ex_unit_registered_describe_attributes) do Module.delete_attribute(__MODULE__, attribute) end end end end @doc false def __describe__(module, line, message) do if Module.get_attribute(module, :ex_unit_describe) do raise "cannot call \"describe\" inside another \"describe\". See the documentation " <> "for ExUnit.Case.describe/2 on named setups and how to handle hierarchies" end cond do not is_binary(message) -> raise ArgumentError, "describe name must be a string, got: #{inspect(message)}" message in Module.get_attribute(module, :ex_unit_used_describes) -> raise ExUnit.DuplicateDescribeError, "describe #{inspect(message)} is already defined in #{inspect(module)}" true -> :ok end if Module.get_attribute(module, :describetag) != [] do raise "@describetag must be set inside describe/2 blocks" end Module.put_attribute(module, :ex_unit_describe, {line, message}) Module.put_attribute(module, :ex_unit_used_describes, message) :ok end @doc false defmacro __before_compile__(_) do quote do def __ex_unit__ do %ExUnit.TestModule{name: __MODULE__, tests: @ex_unit_tests} end end end @doc false def __after_compile__(%{module: module}, _) do if Module.get_attribute(module, :ex_unit_async) do ExUnit.Server.add_async_module(module) else ExUnit.Server.add_sync_module(module) end end @doc """ Registers a function to run as part of this case. This is used by third-party projects, like QuickCheck, to implement macros like `property/3` that works like `test` but instead defines a property. See `test/3` implementation for an example of invoking this function. The test type will be converted to a string and pluralized for display. You can use `ExUnit.plural_rule/2` to set a custom pluralization. """ def register_test(%{module: mod, file: file, line: line}, test_type, name, tags) do unless Module.has_attribute?(mod, :ex_unit_tests) do raise "cannot define #{test_type}. Please make sure you have invoked " <> "\"use ExUnit.Case\" in the current module" end registered_attribute_keys = [ :ex_unit_registered_module_attributes, :ex_unit_registered_describe_attributes, :ex_unit_registered_test_attributes ] registered = for key <- registered_attribute_keys, attribute <- Module.get_attribute(mod, key), into: %{} do {attribute, Module.get_attribute(mod, attribute)} end moduletag = Module.get_attribute(mod, :moduletag) tag = Module.delete_attribute(mod, :tag) async = Module.get_attribute(mod, :ex_unit_async) {name, describe, describe_line, describetag} = case Module.get_attribute(mod, :ex_unit_describe) do {line, describe} -> description = :"#{test_type} #{describe} #{name}" {description, describe, line, Module.get_attribute(mod, :describetag)} _ -> {:"#{test_type} #{name}", nil, nil, []} end if Module.defines?(mod, {name, 1}) do raise ExUnit.DuplicateTestError, ~s("#{name}" is already defined in #{inspect(mod)}) end tags = (tags ++ tag ++ describetag ++ moduletag) |> normalize_tags |> validate_tags |> Map.merge(%{ line: line, file: file, registered: registered, async: async, describe: describe, describe_line: describe_line, test_type: test_type }) test = %ExUnit.Test{name: name, case: mod, tags: tags, module: mod} Module.put_attribute(mod, :ex_unit_tests, test) for attribute <- Module.get_attribute(mod, :ex_unit_registered_test_attributes) do Module.delete_attribute(mod, attribute) end name end @doc """ Registers a new attribute to be used during `ExUnit.Case` tests. The attribute values will be available through `context.registered`. Registered values are cleared after each `test/3` similar to `@tag`. This function takes the same options as `Module.register_attribute/3`. ## Examples defmodule MyTest do use ExUnit.Case ExUnit.Case.register_attribute(__MODULE__, :fixtures, accumulate: true) @fixtures :user @fixtures {:post, insert: false} test "using custom attribute", context do assert context.registered.fixtures == [{:post, insert: false}, :user] end test "custom attributes are cleared per test", context do assert context.registered.fixtures == [] end end """ @spec register_attribute(env, atom, keyword) :: :ok def register_attribute(env, name, opts \\ []) def register_attribute(%{module: mod}, name, opts), do: register_attribute(mod, name, opts) def register_attribute(mod, name, opts) when is_atom(mod) and is_atom(name) and is_list(opts) do register_attribute(:ex_unit_registered_test_attributes, mod, name, opts) end @doc """ Registers a new describe attribute to be used during `ExUnit.Case` tests. The attribute values will be available through `context.registered`. Registered values are cleared after each `describe/2` similar to `@describetag`. This function takes the same options as `Module.register_attribute/3`. ## Examples defmodule MyTest do use ExUnit.Case ExUnit.Case.register_describe_attribute(__MODULE__, :describe_fixtures, accumulate: true) describe "using custom attribute" do @describe_fixtures :user @describe_fixtures {:post, insert: false} test "has attribute", context do assert context.registered.describe_fixtures == [{:post, insert: false}, :user] end end describe "custom attributes are cleared per describe" do test "doesn't have attributes", context do assert context.registered.describe_fixtures == [] end end end """ @doc since: "1.10.0" @spec register_describe_attribute(env, atom, keyword) :: :ok def register_describe_attribute(env, name, opts \\ []) def register_describe_attribute(%{module: mod}, name, opts) do register_describe_attribute(mod, name, opts) end def register_describe_attribute(mod, name, opts) when is_atom(mod) and is_atom(name) and is_list(opts) do register_attribute(:ex_unit_registered_describe_attributes, mod, name, opts) end @doc """ Registers a new module attribute to be used during `ExUnit.Case` tests. The attribute values will be available through `context.registered`. This function takes the same options as `Module.register_attribute/3`. ## Examples defmodule MyTest do use ExUnit.Case ExUnit.Case.register_module_attribute(__MODULE__, :module_fixtures, accumulate: true) @module_fixtures :user @module_fixtures {:post, insert: false} test "using custom attribute", context do assert context.registered.fixtures == [{:post, insert: false}, :user] end test "still using custom attribute", context do assert context.registered.fixtures == [{:post, insert: false}, :user] end end """ @doc since: "1.10.0" @spec register_module_attribute(env, atom, keyword) :: :ok def register_module_attribute(env, name, opts \\ []) def register_module_attribute(%{module: mod}, name, opts) do register_module_attribute(mod, name, opts) end def register_module_attribute(mod, name, opts) when is_atom(mod) and is_atom(name) and is_list(opts) do register_attribute(:ex_unit_registered_module_attributes, mod, name, opts) end defp register_attribute(type, mod, name, opts) do validate_registered_attribute!(type, mod, name) Module.register_attribute(mod, name, opts) Module.put_attribute(mod, type, name) end defp validate_registered_attribute!(type, mod, name) do registered_attribute_keys = [ :ex_unit_registered_module_attributes, :ex_unit_registered_describe_attributes, :ex_unit_registered_test_attributes ] for key <- registered_attribute_keys, type != key and name in Module.get_attribute(mod, key) do raise ArgumentError, "cannot register attribute #{inspect(name)} multiple times" end if Module.has_attribute?(mod, name) do raise "you must set @#{name} after it has been registered" end end defp validate_tags(tags) do for tag <- @reserved, Map.has_key?(tags, tag) do raise "cannot set tag #{inspect(tag)} because it is reserved by ExUnit" end unless is_atom(tags[:test_type]) do raise("value for tag \":test_type\" must be an atom") end tags end defp normalize_tags(tags) do Enum.reduce(Enum.reverse(tags), %{}, fn tag, acc when is_atom(tag) -> Map.put(acc, tag, true) tag, acc when is_list(tag) -> tag |> Enum.into(acc) end) end end
30.229282
103
0.66723
7932923663f6fd09892c729f69ed87fdbbaf12e5
99
exs
Elixir
auth/test/views/layout_view_test.exs
renovate-bot/elixir-samples
91da795ecdfac83eb6fcac63bc532da98c69d520
[ "Apache-2.0" ]
274
2017-08-25T06:39:51.000Z
2022-03-15T21:03:27.000Z
auth/test/views/layout_view_test.exs
renovate-bot/elixir-samples
91da795ecdfac83eb6fcac63bc532da98c69d520
[ "Apache-2.0" ]
15
2017-10-03T17:05:48.000Z
2021-11-23T00:33:23.000Z
auth/test/views/layout_view_test.exs
renovate-bot/elixir-samples
91da795ecdfac83eb6fcac63bc532da98c69d520
[ "Apache-2.0" ]
42
2017-08-28T20:08:47.000Z
2022-01-18T07:51:02.000Z
defmodule GoogleOAuth2Example.LayoutViewTest do use GoogleOAuth2Example.ConnCase, async: true end
33
47
0.868687
7932b90761b146b01f2d0069551b60a87483870a
1,549
exs
Elixir
test/references_test.exs
sandisk/tentacat
523791d47d8454e87dc75cf77181b1fc78c125cf
[ "MIT" ]
null
null
null
test/references_test.exs
sandisk/tentacat
523791d47d8454e87dc75cf77181b1fc78c125cf
[ "MIT" ]
null
null
null
test/references_test.exs
sandisk/tentacat
523791d47d8454e87dc75cf77181b1fc78c125cf
[ "MIT" ]
1
2018-11-02T15:59:28.000Z
2018-11-02T15:59:28.000Z
defmodule Tentacat.ReferencesTest do use ExUnit.Case, async: false use ExVCR.Mock, adapter: ExVCR.Adapter.Hackney import Tentacat.References doctest Tentacat.References @client Tentacat.Client.new(%{access_token: "8e663c8614ced27c09b963f806ac46776a29db50"}) setup_all do HTTPoison.start() end test "list/3" do use_cassette "references#list" do assert elem(list(@client, "soudqwiggle", "elixir-conspiracy"), 1) == [] end end test "find/4" do use_cassette "references#find" do {_, %{"ref" => ref}, _} = find(@client, "soudqwiggle", "elixir-conspiracy", "pull/2/merge") assert ref == "refs/pull/2/merge" end end test "create/4" do use_cassette "references#create" do body = %{ "ref" => "refs/heads/old-readme", "sha" => "2ff6f7942773c268dc9ab0e11e9dffad402c1860" } {status_code, _, _} = create(@client, "soudqwiggle", "elixir-conspiracy", body) assert status_code == 201 end end test "update/5" do body = %{ "sha" => "bf7c4ab53fe7503b82b9654d5979ebe8c24ea009", "force" => true } use_cassette "references#update" do {_, %{"ref" => ref}, _} = update(@client, "soudqwiggle", "elixir-conspiracy", "heads/master", body) assert ref == "refs/heads/master" end end test "remove/4" do use_cassette "references#remove" do {status_code, _, _} = remove(@client, "soudqwiggle", "elixir-conspiracy", 'heads/old-readme') assert status_code == 204 end end end
24.983871
97
0.635249
7932df4bda555b66e138a951a896d2a44322adc5
10,075
ex
Elixir
lib/phoenix/channel/server.ex
keichan34/phoenix
e0e5284c6e9910743a0fdef7251d461fd06d4d5e
[ "MIT" ]
null
null
null
lib/phoenix/channel/server.ex
keichan34/phoenix
e0e5284c6e9910743a0fdef7251d461fd06d4d5e
[ "MIT" ]
null
null
null
lib/phoenix/channel/server.ex
keichan34/phoenix
e0e5284c6e9910743a0fdef7251d461fd06d4d5e
[ "MIT" ]
null
null
null
defmodule Phoenix.Channel.Server do use GenServer require Logger alias Phoenix.PubSub alias Phoenix.Socket alias Phoenix.Socket.Broadcast alias Phoenix.Socket.Message alias Phoenix.Socket.Reply @moduledoc false ## Transport API @doc """ Joins the channel in socket with authentication payload. """ @spec join(Socket.t, map) :: {:ok, map, pid} | {:error, map} def join(socket, auth_payload) do ref = make_ref() case GenServer.start_link(__MODULE__, {socket, auth_payload, self(), ref}) do {:ok, pid} -> receive do: ({^ref, reply} -> {:ok, reply, pid}) :ignore -> receive do: ({^ref, reply} -> {:error, reply}) {:error, reason} -> Logger.error fn -> Exception.format_exit(reason) end {:error, %{reason: "join crashed"}} end end @doc """ Notifies the channel the client closed. This event is synchronous as we want to guarantee proper termination of the channel. """ def close(pid, timeout \\ 5000) do # We need to guarantee that the channel has been closed # otherwise the link in the transport will trigger it to # crash. ref = Process.monitor(pid) GenServer.cast(pid, :close) receive do {:DOWN, ^ref, _, _, _} -> :ok after timeout -> Process.exit(pid, :kill) receive do {:DOWN, ^ref, _, _, _} -> :ok end end end @doc """ Gets the socket from the channel. """ def socket(pid) do GenServer.call(pid, :socket) end ## Channel API @doc """ Broadcasts on the given pubsub server with the given `topic`, `event` and `payload`. The message is encoded as `Phoenix.Socket.Broadcast`. """ def broadcast(pubsub_server, topic, event, payload) when is_binary(topic) and is_binary(event) and is_map(payload) do PubSub.broadcast pubsub_server, topic, %Broadcast{ topic: topic, event: event, payload: payload } end def broadcast(_, _, _, _), do: raise_invalid_message @doc """ Broadcasts on the given pubsub server with the given `topic`, `event` and `payload`. Raises in case of crashes. """ def broadcast!(pubsub_server, topic, event, payload) when is_binary(topic) and is_binary(event) and is_map(payload) do PubSub.broadcast! pubsub_server, topic, %Broadcast{ topic: topic, event: event, payload: payload } end def broadcast!(_, _, _, _), do: raise_invalid_message @doc """ Broadcasts on the given pubsub server with the given `from`, `topic`, `event` and `payload`. The message is encoded as `Phoenix.Socket.Broadcast`. """ def broadcast_from(pubsub_server, from, topic, event, payload) when is_binary(topic) and is_binary(event) and is_map(payload) do PubSub.broadcast_from pubsub_server, from, topic, %Broadcast{ topic: topic, event: event, payload: payload } end def broadcast_from(_, _, _, _, _), do: raise_invalid_message @doc """ Broadcasts on the given pubsub server with the given `from`, `topic`, `event` and `payload`. Raises in case of crashes. """ def broadcast_from!(pubsub_server, from, topic, event, payload) when is_binary(topic) and is_binary(event) and is_map(payload) do PubSub.broadcast_from! pubsub_server, from, topic, %Broadcast{ topic: topic, event: event, payload: payload } end def broadcast_from!(_, _, _, _, _), do: raise_invalid_message @doc """ Pushes a message with the given topic, event and payload to the given process. """ def push(pid, topic, event, payload, serializer) when is_binary(topic) and is_binary(event) and is_map(payload) do encoded_msg = serializer.encode!(%Message{topic: topic, event: event, payload: payload}) send pid, encoded_msg :ok end def push(_, _, _, _), do: raise_invalid_message @doc """ Replies to a given ref to the transport process. """ def reply(pid, ref, topic, {status, payload}, serializer) when is_binary(topic) and is_map(payload) do send pid, serializer.encode!( %Reply{topic: topic, ref: ref, status: status, payload: payload} ) :ok end def reply(_, _, _, _, _), do: raise_invalid_message defp raise_invalid_message do raise ArgumentError, "topic and event must be strings, message must be a map" end ## Callbacks @doc false def init({socket, auth_payload, parent, ref}) do socket = %{socket | channel_pid: self()} case socket.channel.join(socket.topic, auth_payload, socket) do {:ok, socket} -> join(socket, %{}, parent, ref) {:ok, reply, socket} -> join(socket, reply, parent, ref) {:error, reply} -> send(parent, {ref, reply}) :ignore other -> raise """ Channel join is expected to return one of: {:ok, Socket.t} | {:ok, reply :: map, Socket.t} | {:error, reply :: map} got #{inspect other} """ end end @doc false def code_change(old, socket, extra) do socket.channel.code_change(old, socket, extra) end defp join(socket, reply, parent, ref) do PubSub.subscribe(socket.pubsub_server, socket.topic, link: true, fastlane: {socket.transport_pid, socket.serializer, socket.channel.__intercepts__()}) send(parent, {ref, reply}) {:ok, %{socket | joined: true}} end @doc false def handle_call(:socket, _from, socket) do {:reply, socket, socket} end @doc false def handle_cast(:close, socket) do handle_result({:stop, {:shutdown, :closed}, socket}, :handle_in) end @doc false def handle_info(%Message{topic: topic, event: "phx_join"}, %{topic: topic} = socket) do Logger.warn fn -> "#{inspect socket.channel} received join event with topic \"#{topic}\" but channel already joined" end handle_result({:reply, {:error, %{reason: "already joined"}}, socket}, :handle_in) end def handle_info(%Message{topic: topic, event: "phx_leave", ref: ref}, %{topic: topic} = socket) do handle_result({:stop, {:shutdown, :left}, :ok, put_in(socket.ref, ref)}, :handle_in) end def handle_info(%Message{topic: topic, event: event, payload: payload, ref: ref}, %{topic: topic} = socket) do event |> socket.channel.handle_in(payload, put_in(socket.ref, ref)) |> handle_result(:handle_in) end def handle_info(%Broadcast{topic: topic, event: event, payload: payload}, %{topic: topic} = socket) do event |> socket.channel.handle_out(payload, socket) |> handle_result(:handle_out) end def handle_info(msg, socket) do msg |> socket.channel.handle_info(socket) |> handle_result(:handle_info) end @doc false def terminate(reason, socket) do socket.channel.terminate(reason, socket) end @doc false def fastlane(subscribers, from, %Broadcast{event: event} = msg) do Enum.reduce(subscribers, %{}, fn {pid, _fastlanes}, cache when pid == from -> cache {pid, nil}, cache -> send(pid, msg) cache {pid, {fastlane_pid, serializer, event_intercepts}}, cache -> if event in event_intercepts do send(pid, msg) cache else case Map.fetch(cache, serializer) do {:ok, encoded_msg} -> send(fastlane_pid, encoded_msg) cache :error -> encoded_msg = serializer.fastlane!(msg) send(fastlane_pid, encoded_msg) Map.put(cache, serializer, encoded_msg) end end end) end def fastlane(subscribers, from, msg) do Enum.each(subscribers, fn {pid, _} when pid == from -> :noop {pid, _} -> send(pid, msg) end) end ## Handle results defp handle_result({:reply, reply, %Socket{} = socket}, callback) do handle_reply(socket, reply, callback) {:noreply, put_in(socket.ref, nil)} end defp handle_result({:stop, reason, reply, socket}, callback) do handle_reply(socket, reply, callback) {:stop, reason, socket} end defp handle_result({:stop, reason, socket}, _callback) do {:stop, reason, socket} end defp handle_result({:noreply, socket}, _callback) do {:noreply, put_in(socket.ref, nil)} end defp handle_result(result, :handle_in) do raise """ Expected `handle_in/3` to return one of: {:noreply, Socket.t} | {:reply, {status :: atom, response :: map}, Socket.t} | {:reply, status :: atom, Socket.t} | {:stop, reason :: term, Socket.t} | {:stop, reason :: term, {status :: atom, response :: map}, Socket.t} | {:stop, reason :: term, status :: atom, Socket.t} got #{inspect result} """ end defp handle_result(result, callback) do raise """ Expected `#{callback}` to return one of: {:noreply, Socket.t} | {:stop, reason :: term, Socket.t} | got #{inspect result} """ end ## Handle replies defp handle_reply(socket, {status, payload}, :handle_in) when is_atom(status) and is_map(payload) do reply(socket.transport_pid, socket.ref, socket.topic, {status, payload}, socket.serializer) end defp handle_reply(socket, status, :handle_in) when is_atom(status) do handle_reply(socket, {status, %{}}, :handle_in) end defp handle_reply(_socket, reply, :handle_in) do raise """ Channel replies from `handle_in/3` are expected to be one of: status :: atom {status :: atom, response :: map} for example: {:reply, :ok, socket} {:reply, {:ok, %{}}, socket} {:stop, :shutdown, {:error, %{}}, socket} got #{inspect reply} """ end defp handle_reply(_socket, _reply, _other) do raise """ Channel replies can only be sent from a `handle_in/3` callback. Use `push/3` to send an out-of-band message down the socket """ end end
27.377717
124
0.619355
7932e4595610c26627b9458ac93dd7575960ea3d
1,565
ex
Elixir
test/support/repo_case.ex
OleMchls/incident
220e46598719fc50d10c96e5a848080172bf6f9b
[ "MIT" ]
null
null
null
test/support/repo_case.ex
OleMchls/incident
220e46598719fc50d10c96e5a848080172bf6f9b
[ "MIT" ]
null
null
null
test/support/repo_case.ex
OleMchls/incident
220e46598719fc50d10c96e5a848080172bf6f9b
[ "MIT" ]
null
null
null
defmodule Incident.RepoCase do @moduledoc """ This module defines the setup for tests requiring access to the application's data layer. You may define functions here to be used as helpers in your tests. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate alias Ecto.Adapters.SQL.Sandbox alias Ecto.Changeset alias Incident.EventStore.TestRepo, as: EventStoreTestRepo alias Incident.ProjectionStore.TestRepo, as: ProjectionStoreTestRepo using do quote do import Incident.RepoCase end end setup tags do :ok = Sandbox.checkout(EventStoreTestRepo) :ok = Sandbox.checkout(ProjectionStoreTestRepo) unless tags[:async] do Sandbox.mode(EventStoreTestRepo, {:shared, self()}) Sandbox.mode(ProjectionStoreTestRepo, {:shared, self()}) end :ok end @doc """ A helper that transform changeset errors to a map of messages. assert {:error, changeset} = Accounts.create_user(%{password: "short"}) assert "password is too short" in errors_on(changeset).password assert %{password: ["password is too short"]} = errors_on(changeset) """ def errors_on(changeset) do Changeset.traverse_errors(changeset, fn {message, opts} -> Enum.reduce(opts, message, fn {key, value}, acc -> String.replace(acc, "%{#{key}}", to_string(value)) end) end) end end
27.946429
77
0.704792
793307ade2e0af490f0244f0c5ac371e4faad020
163
ex
Elixir
exercises/lists/reduce.ex
v6/elixir-workshop
93d8a7e52671d7f9a9135ad41864b21c58d4cda2
[ "MIT" ]
null
null
null
exercises/lists/reduce.ex
v6/elixir-workshop
93d8a7e52671d7f9a9135ad41864b21c58d4cda2
[ "MIT" ]
null
null
null
exercises/lists/reduce.ex
v6/elixir-workshop
93d8a7e52671d7f9a9135ad41864b21c58d4cda2
[ "MIT" ]
1
2020-08-19T23:09:15.000Z
2020-08-19T23:09:15.000Z
defmodule MyList do def reduce([], value, _) do value end def reduce([head | tail], value, func) do reduce(tail, func.(head, value), func) end end
18.111111
43
0.631902
7933136ae1eb3770ac156ed6b7adb5d60af41693
210
exs
Elixir
priv/repo/migrations/20200611220612_add_test_result_id_to_abouts.exs
RatioPBC/epi-viaduct-nys
99fb637785ea207aee5449fa01fa59dd18ec8bf2
[ "MIT" ]
2
2021-06-22T21:01:49.000Z
2021-11-04T18:36:48.000Z
priv/repo/migrations/20200611220612_add_test_result_id_to_abouts.exs
RatioPBC/epi-viaduct-nys
99fb637785ea207aee5449fa01fa59dd18ec8bf2
[ "MIT" ]
null
null
null
priv/repo/migrations/20200611220612_add_test_result_id_to_abouts.exs
RatioPBC/epi-viaduct-nys
99fb637785ea207aee5449fa01fa59dd18ec8bf2
[ "MIT" ]
null
null
null
defmodule NYSETL.Repo.Migrations.AddTestResultIdToAbouts do use Ecto.Migration def change do alter table(:abouts) do add :test_result_id, references(:test_results), null: false end end end
21
65
0.742857
7933241d80559421937a3a2b64cea11aeb41bc23
6,849
exs
Elixir
test/ecto/model/schema_test.exs
yrashk/ecto
1462d5ad4cbb7bf74c292ec405852bc196808daf
[ "Apache-2.0" ]
1
2016-08-15T21:23:28.000Z
2016-08-15T21:23:28.000Z
test/ecto/model/schema_test.exs
yrashk/ecto
1462d5ad4cbb7bf74c292ec405852bc196808daf
[ "Apache-2.0" ]
null
null
null
test/ecto/model/schema_test.exs
yrashk/ecto
1462d5ad4cbb7bf74c292ec405852bc196808daf
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.Model.SchemaTest do use ExUnit.Case, async: true defmodule User do use Ecto.Model schema "users" do # Type defaults to string field :name end end defmodule Comment do defstruct [] end defmodule DefaultUser do @schema_defaults primary_key: {:uuid, :string, []}, foreign_key_type: :string use Ecto.Model schema "users" do field :name belongs_to :comment, Comment end end test "uses @schema_defauls" do assert %DefaultUser{uuid: "abc"}.uuid == "abc" assert DefaultUser.__schema__(:field_type, :comment_id) == :string end defmodule MyModel do use Ecto.Model schema "mymodel" do field :name, :string, default: "eric" field :email, :string, uniq: true field :temp, :any, default: "temp", virtual: true field :array, {:array, :string} belongs_to :comment, Comment end def test_attr(:source), do: @ecto_source def model_from do from(c in __MODULE__, where: c.name == nil) end end test "imports Ecto.Query functions" do assert %Ecto.Query{} = MyModel.model_from end test "schema attributes" do assert MyModel.test_attr(:source) == "mymodel" end test "schema metadata" do assert MyModel.__schema__(:source) == "mymodel" assert MyModel.__schema__(:field_names) == [:id, :name, :email, :array, :comment_id] assert MyModel.__schema__(:field_type, :id) == :integer assert MyModel.__schema__(:field_type, :name) == :string assert MyModel.__schema__(:field_type, :email) == :string assert MyModel.__schema__(:field_type, :array) == {:array, :string} assert MyModel.__schema__(:field_type, :comment_id) == :integer end test "assign metadata" do assert MyModel.__assign__ == %{name: :string, email: :string, array: {:array, :string}, comment_id: :integer, temp: :any} end test "field name clash" do assert_raise ArgumentError, "field/association `name` is already set on schema", fn -> defmodule ModelFieldNameClash do use Ecto.Model schema "clash" do field :name, :string field :name, :integer end end end end test "invalid field type" do assert_raise ArgumentError, "unknown field type `{:apa}`", fn -> defmodule ModelInvalidFieldType do use Ecto.Model schema "invalidtype" do field :name, {:apa} end end end end test "fail custom primary key" do assert_raise ArgumentError, "primary key already defined as `id`", fn -> defmodule ModelFailCustomPK do use Ecto.Model schema "custompk" do field :x, :string field :pk, :integer, primary_key: true end end end end test "dont fail custom primary key" do defmodule ModelDontFailCustomPK do use Ecto.Model schema "custompk", primary_key: false do field :x, :string field :pk, :integer, primary_key: true end end end defmodule ModelAssocs do use Ecto.Model schema "assocs" do has_many :posts, Post has_one :author, User belongs_to :comment, Comment end end test "associations" do assert ModelAssocs.__schema__(:association, :not_a_field) == nil assert ModelAssocs.__schema__(:field_names) == [:id, :comment_id] end test "has_many association" do refl = %Ecto.Reflections.HasMany{field: :posts, owner: ModelAssocs, associated: Post, key: :id, assoc_key: :model_assocs_id} assert refl == ModelAssocs.__schema__(:association, :posts) r = %ModelAssocs{} assoc = r.posts assert assoc.__assoc__(:name) == :posts assert assoc.__assoc__(:target) == ModelAssocs assert assoc.__assoc__(:primary_key) == r.id end test "has_one association" do refl = %Ecto.Reflections.HasOne{field: :author, owner: ModelAssocs, associated: User, key: :id, assoc_key: :model_assocs_id} assert refl == ModelAssocs.__schema__(:association, :author) r = %ModelAssocs{} assoc = r.author assert assoc.__assoc__(:name) == :author assert assoc.__assoc__(:target) == ModelAssocs end test "belongs_to association" do refl = %Ecto.Reflections.BelongsTo{field: :comment, owner: ModelAssocs, associated: Comment, key: :comment_id, assoc_key: :id} assert refl == ModelAssocs.__schema__(:association, :comment) r = %ModelAssocs{} assoc = r.comment assert assoc.__assoc__(:name) == :comment assert assoc.__assoc__(:target) == ModelAssocs end test "belongs_to association foreign_key type" do defmodule ForeignKeyType do use Ecto.Model schema "fk" do belongs_to :comment, Comment, type: :datetime end end defmodule DefaultForeignKeyType do @queryable_defaults foreign_key_type: :string use Ecto.Model schema "defaults" do ## :type option overrides any @queryable_defaults belongs_to :comment, Comment, type: :uuid end end assert ForeignKeyType.__schema__(:field_type, :comment_id) == :datetime assert DefaultForeignKeyType.__schema__(:field_type, :comment_id) == :uuid end defmodule ModelAssocOpts do use Ecto.Model schema "assoc", primary_key: {:pk, :integer, []} do has_many :posts, Post, references: :pk, foreign_key: :fk has_one :author, User, references: :pk, foreign_key: :fk belongs_to :permalink, Permalink, references: :pk, foreign_key: :fk belongs_to :permalink2, Permalink, references: :pk end end test "has_many options" do refl = ModelAssocOpts.__schema__(:association, :posts) assert :pk == refl.key assert :fk == refl.assoc_key end test "has_one options" do refl = ModelAssocOpts.__schema__(:association, :author) assert :pk == refl.key assert :fk == refl.assoc_key end test "belongs_to options" do refl = ModelAssocOpts.__schema__(:association, :permalink) assert :pk == refl.assoc_key assert :fk == refl.key refl = ModelAssocOpts.__schema__(:association, :permalink2) assert :pk == refl.assoc_key assert :permalink2_id == refl.key end test "references option has to match a field on model" do message = "model does not have the field :pk used by association :posts, " <> "please set the :references option accordingly" assert_raise ArgumentError, message, fn -> defmodule ModelPkAssocMisMatch do use Ecto.Model schema "assoc" do has_many :posts, Post, references: :pk has_one :author, User, references: :pk end end end end end
28.185185
100
0.641846
793347d737590ea6a0ee0329669c4de552f51c78
16,617
exs
Elixir
lib/mix/test/mix/tasks/release_test.exs
steven-solomon/elixir
ee83248b8dd78ad67ef1282efc791006e8712d9e
[ "Apache-2.0" ]
null
null
null
lib/mix/test/mix/tasks/release_test.exs
steven-solomon/elixir
ee83248b8dd78ad67ef1282efc791006e8712d9e
[ "Apache-2.0" ]
null
null
null
lib/mix/test/mix/tasks/release_test.exs
steven-solomon/elixir
ee83248b8dd78ad67ef1282efc791006e8712d9e
[ "Apache-2.0" ]
null
null
null
Code.require_file("../../test_helper.exs", __DIR__) defmodule Mix.Tasks.ReleaseTest do use MixTest.Case @erts_version :erlang.system_info(:version) @hostname :inet_db.gethostname() defmacrop release_node(name), do: :"#{name}@#{@hostname}" describe "customize" do test "rel with eex" do in_fixture("release_test", fn -> Mix.Project.in_project(:release_test, ".", fn _ -> File.mkdir_p!("rel") for file <- ~w(rel/vm.args.eex rel/env.sh.eex rel/env.bat.eex) do File.write!(file, """ #{file} FOR <%= @release.name %> """) end root = Path.absname("_build/dev/rel/release_test") Mix.Task.run("release") assert_received {:mix_shell, :info, ["* assembling release_test-0.1.0 on MIX_ENV=dev"]} assert root |> Path.join("releases/0.1.0/env.sh") |> File.read!() == "rel/env.sh.eex FOR release_test\n" assert root |> Path.join("releases/0.1.0/env.bat") |> File.read!() == "rel/env.bat.eex FOR release_test\n" assert root |> Path.join("releases/0.1.0/vm.args") |> File.read!() == "rel/vm.args.eex FOR release_test\n" end) end) end test "steps" do in_fixture("release_test", fn -> last_step = fn release -> send(self(), {:last_step, release}) release end first_step = fn release -> send(self(), {:first_step, release}) update_in(release.steps, &(&1 ++ [last_step])) end config = [releases: [demo: [steps: [first_step, :assemble]]]] Mix.Project.in_project(:release_test, ".", config, fn _ -> Mix.Task.run("release") assert_received {:mix_shell, :info, ["* assembling demo-0.1.0 on MIX_ENV=dev"]} # Discard info messages from inbox for upcoming assertions Mix.shell().flush(& &1) {:messages, [ {:first_step, %Mix.Release{steps: [:assemble]}}, {:last_step, %Mix.Release{steps: []}} ]} = Process.info(self(), :messages) end) end) end test "include_executables_for" do in_fixture("release_test", fn -> config = [releases: [release_test: [include_executables_for: []]]] Mix.Project.in_project(:release_test, ".", config, fn _ -> root = Path.absname("_build/dev/rel/release_test") Mix.Task.run("release") assert_received {:mix_shell, :info, ["* assembling release_test-0.1.0 on MIX_ENV=dev"]} refute root |> Path.join("bin/start") |> File.exists?() refute root |> Path.join("bin/start.bat") |> File.exists?() refute root |> Path.join("releases/0.1.0/elixir") |> File.exists?() refute root |> Path.join("releases/0.1.0/elixir.bat") |> File.exists?() refute root |> Path.join("releases/0.1.0/iex") |> File.exists?() refute root |> Path.join("releases/0.1.0/iex.bat") |> File.exists?() end) end) end end test "assembles a bootable release with ERTS" do in_fixture("release_test", fn -> Mix.Project.in_project(:release_test, ".", fn _ -> root = Path.absname("_build/dev/rel/release_test") # Assert command Mix.Task.run("release") assert_received {:mix_shell, :info, ["* assembling release_test-0.1.0 on MIX_ENV=dev"]} assert_received {:mix_shell, :info, ["\nRelease created at _build/dev/rel/release_test!" <> _]} assert_received {:mix_shell, :info, ["* skipping runtime configuration" <> _]} # Assert structure assert root |> Path.join("erts-#{@erts_version}") |> File.exists?() assert root |> Path.join("lib/release_test-0.1.0/ebin") |> File.exists?() assert root |> Path.join("lib/release_test-0.1.0/priv/hello") |> File.exists?() assert root |> Path.join("releases/COOKIE") |> File.exists?() assert root |> Path.join("releases/start_erl.data") |> File.exists?() assert root |> Path.join("releases/0.1.0/release_test.rel") |> File.exists?() assert root |> Path.join("releases/0.1.0/sys.config") |> File.exists?() assert root |> Path.join("releases/0.1.0/env.sh") |> File.exists?() assert root |> Path.join("releases/0.1.0/env.bat") |> File.exists?() assert root |> Path.join("releases/0.1.0/vm.args") |> File.exists?() assert root |> Path.join("releases/0.1.0/sys.config") |> File.read!() =~ "RUNTIME_CONFIG=false" assert root |> Path.join("lib/release_test-0.1.0/priv") |> File.read_link() |> elem(0) == :error cookie = File.read!(Path.join(root, "releases/COOKIE")) # Assert runtime open_port(Path.join(root, "bin/release_test"), ['start']) assert %{ app_dir: app_dir, cookie_env: ^cookie, mode: :embedded, node: release_node("release_test"), protocols_consolidated?: true, release_name: "release_test", release_node: "release_test", release_root: release_root, release_vsn: "0.1.0", root_dir: root_dir, static_config: {:ok, :was_set}, runtime_config: :error, sys_config_env: sys_config_env, sys_config_init: sys_config_init, encoding: {:"£", "£", '£'} } = wait_until_decoded(Path.join(root, "RELEASE_BOOTED")) if match?({:win32, _}, :os.type()) do # `RELEAS~1` is the DOS path name (8 character) for the `release_test` directory assert app_dir =~ ~r"_build/dev/rel/(release_test|RELEAS~1)/lib/release_test-0\.1\.0$" assert release_root =~ ~r"_build\\dev\\rel\\(release_test|RELEAS~1)$" assert root_dir =~ ~r"_build/dev/rel/(release_test|RELEAS~1)$" assert String.ends_with?(sys_config_env, "releases\\0.1.0\\sys") assert String.ends_with?(sys_config_init, "releases\\0.1.0\\sys") else assert app_dir == Path.join(root, "lib/release_test-0.1.0") assert release_root == root assert root_dir == root assert sys_config_env == Path.join(root, "releases/0.1.0/sys") assert sys_config_init == Path.join(root, "releases/0.1.0/sys") end end) end) end test "assembles a bootable release with runtime configuration" do in_fixture("release_test", fn -> config = [releases: [runtime_config: []]] Mix.Project.in_project(:release_test, ".", config, fn _ -> File.write!("config/releases.exs", """ import Config config :release_test, :runtime, :was_set config :release_test, :encoding, {:runtime, :"£", "£", '£'} """) root = Path.absname("_build/dev/rel/runtime_config") # Assert command Mix.Task.run("release", ["runtime_config"]) assert_received {:mix_shell, :info, ["* assembling runtime_config-0.1.0 on MIX_ENV=dev"]} assert_received {:mix_shell, :info, ["* using config/releases.exs to configure the release at runtime"]} # Assert structure assert root |> Path.join("releases/0.1.0/sys.config") |> File.read!() =~ "RUNTIME_CONFIG=true" # Assert runtime open_port(Path.join(root, "bin/runtime_config"), ['start']) assert %{ mode: :embedded, node: release_node("runtime_config"), protocols_consolidated?: true, release_name: "runtime_config", release_node: "runtime_config", release_vsn: "0.1.0", static_config: {:ok, :was_set}, runtime_config: {:ok, :was_set}, sys_config_env: sys_config_env, sys_config_init: sys_config_init, encoding: {:runtime, :"£", "£", '£'} } = wait_until_decoded(Path.join(root, "RELEASE_BOOTED")) if match?({:win32, _}, :os.type()) do assert sys_config_env =~ "tmp\\runtime_config-0.1.0" assert sys_config_init =~ "tmp\\runtime_config-0.1.0" else assert sys_config_env =~ "tmp/runtime_config-0.1.0" assert sys_config_init =~ "tmp/runtime_config-0.1.0" end end) end) end test "assembles a release without ERTS and with custom options" do in_fixture("release_test", fn -> config = [releases: [demo: [include_erts: false, cookie: "abcdefghijk"]]] Mix.Project.in_project(:release_test, ".", config, fn _ -> root = Path.absname("demo") Mix.Task.run("release", ["demo", "--path", "demo", "--version", "0.2.0", "--quiet"]) refute_received {:mix_shell, :info, ["* assembling " <> _]} refute_received {:mix_shell, :info, ["\nRelease created " <> _]} # Assert structure assert root |> Path.join("bin/demo") |> File.exists?() refute root |> Path.join("erts-#{@erts_version}") |> File.exists?() assert root |> Path.join("lib/release_test-0.1.0/ebin") |> File.exists?() assert root |> Path.join("lib/release_test-0.1.0/priv/hello") |> File.exists?() assert root |> Path.join("releases/COOKIE") |> File.exists?() assert root |> Path.join("releases/start_erl.data") |> File.exists?() assert root |> Path.join("releases/0.2.0/demo.rel") |> File.exists?() assert root |> Path.join("releases/0.2.0/sys.config") |> File.exists?() assert root |> Path.join("releases/0.2.0/vm.args") |> File.exists?() # Assert runtime open_port(Path.join(root, "bin/demo"), ['start']) assert %{ app_dir: app_dir, cookie_env: "abcdefghijk", mode: :embedded, node: release_node("demo"), protocols_consolidated?: true, release_name: "demo", release_node: "demo", release_root: release_root, release_vsn: "0.2.0", root_dir: root_dir, static_config: {:ok, :was_set}, runtime_config: :error } = wait_until_decoded(Path.join(root, "RELEASE_BOOTED")) if match?({:win32, _}, :os.type()) do assert String.ends_with?(app_dir, "demo/lib/release_test-0.1.0") assert String.ends_with?(release_root, "demo") else assert app_dir == Path.join(root, "lib/release_test-0.1.0") assert release_root == root end assert root_dir == :code.root_dir() |> to_string() end) end) end @tag :epmd test "executes rpc instructions" do in_fixture("release_test", fn -> config = [releases: [permanent1: [include_erts: false]]] Mix.Project.in_project(:release_test, ".", config, fn _ -> root = Path.absname("_build/dev/rel/permanent1") Mix.Task.run("release") script = Path.join(root, "bin/permanent1") open_port(script, ['start']) wait_until_decoded(Path.join(root, "RELEASE_BOOTED")) assert System.cmd(script, ["rpc", "ReleaseTest.hello_world"]) == {"hello world\n", 0} assert {pid, 0} = System.cmd(script, ["pid"]) assert pid != "\n" assert System.cmd(script, ["stop"]) == {"", 0} end) end) end test "runs eval and version commands" do # In some Windows setups (mostly with Docker), `System.cmd/3` fails because # the path to the command/executable and one or more arguments contain spaces. tmp_dir = Path.join(inspect(__MODULE__), "runs_eval_and_version_commands") in_fixture("release_test", tmp_dir, fn -> config = [releases: [eval: [include_erts: false, cookie: "abcdefghij"]]] Mix.Project.in_project(:release_test, ".", config, fn _ -> File.write!("config/releases.exs", """ import Config config :release_test, :runtime, :was_set """) root = Path.absname("_build/dev/rel/eval") Mix.Task.run("release") script = Path.join(root, "bin/eval") {version, 0} = System.cmd(script, ["version"]) assert String.trim_trailing(version) == "eval 0.1.0" refute File.exists?(Path.join(root, "RELEASE_BOOTED")) {hello_world, 0} = System.cmd(script, ["eval", "IO.puts :hello_world"]) assert String.trim_trailing(hello_world) == "hello_world" refute File.exists?(Path.join(root, "RELEASE_BOOTED")) open_port(script, ['eval', 'Application.ensure_all_started(:release_test)']) assert %{ cookie_env: "abcdefghij", mode: :interactive, node: :nonode@nohost, protocols_consolidated?: true, release_name: "eval", release_node: "eval", release_root: root, release_vsn: "0.1.0", static_config: {:ok, :was_set}, runtime_config: {:ok, :was_set} } = wait_until_decoded(Path.join(root, "RELEASE_BOOTED")) end) end) end @tag :unix test "runs in daemon mode" do in_fixture("release_test", fn -> config = [releases: [permanent2: [include_erts: false, cookie: "abcdefghij"]]] Mix.Project.in_project(:release_test, ".", config, fn _ -> root = Path.absname("_build/dev/rel/permanent2") Mix.Task.run("release") script = Path.join(root, "bin/permanent2") open_port(script, ['daemon_iex']) assert %{ app_dir: app_dir, cookie_env: "abcdefghij", mode: :embedded, node: release_node("permanent2"), protocols_consolidated?: true, release_name: "permanent2", release_node: "permanent2", release_root: ^root, release_vsn: "0.1.0", root_dir: root_dir, static_config: {:ok, :was_set}, runtime_config: :error, sys_config_env: sys_config_env, sys_config_init: sys_config_init } = wait_until_decoded(Path.join(root, "RELEASE_BOOTED")) assert app_dir == Path.join(root, "lib/release_test-0.1.0") assert root_dir == :code.root_dir() |> to_string() assert sys_config_env == Path.join(root, "releases/0.1.0/sys") assert sys_config_init == Path.join(root, "releases/0.1.0/sys") assert wait_until(fn -> File.read!(Path.join(root, "tmp/log/erlang.log.1")) =~ "iex(permanent2@#{@hostname})1> " end) assert System.cmd(script, ["rpc", "ReleaseTest.hello_world"]) == {"hello world\n", 0} assert System.cmd(script, ["stop"]) == {"", 0} end) end) end test "requires confirmation if release already exists unless overwriting" do in_fixture("release_test", fn -> Mix.Project.in_project(:release_test, ".", fn _ -> Mix.Task.rerun("release") assert_received {:mix_shell, :info, ["* assembling release_test-0.1.0 on MIX_ENV=dev"]} send(self(), {:mix_shell_input, :yes?, false}) Mix.Task.rerun("release") refute_received {:mix_shell, :info, ["* assembling release_test-0.1.0 on MIX_ENV=dev"]} assert_received {:mix_shell, :yes?, ["Release release_test-0.1.0 already exists. Overwrite?"]} Mix.Task.rerun("release", ["--overwrite"]) assert_received {:mix_shell, :info, ["* assembling release_test-0.1.0 on MIX_ENV=dev"]} end) end) end test "requires a matching name" do in_fixture("release_test", fn -> Mix.Project.in_project(:release_test, ".", fn _ -> assert_raise Mix.Error, ~r"Unknown release :unknown", fn -> Mix.Task.run("release", ["unknown"]) end end) end) end defp open_port(command, args) do Port.open({:spawn_executable, to_charlist(command)}, [:hide, args: args]) end defp wait_until_decoded(file) do wait_until(fn -> case File.read(file) do {:ok, bin} when byte_size(bin) > 0 -> :erlang.binary_to_term(bin) _ -> nil end end) end defp wait_until(fun) do if value = fun.() do value else Process.sleep(10) wait_until(fun) end end end
38.376443
97
0.566649
79334cae67056795f12041695cfa0789371f7d65
421
ex
Elixir
lib/ex_pwned/utils.ex
techgaun/ex_pwned
776dc6638aaa17b0e2c11afee6295054b87aeffd
[ "Apache-2.0" ]
18
2017-03-04T11:35:34.000Z
2020-04-29T22:24:26.000Z
lib/ex_pwned/utils.ex
techgaun/ex_pwned
776dc6638aaa17b0e2c11afee6295054b87aeffd
[ "Apache-2.0" ]
11
2018-05-16T04:36:57.000Z
2020-04-07T19:47:40.000Z
lib/ex_pwned/utils.ex
techgaun/ex_pwned
776dc6638aaa17b0e2c11afee6295054b87aeffd
[ "Apache-2.0" ]
8
2018-05-16T18:15:51.000Z
2020-06-23T16:58:52.000Z
defmodule ExPwned.Utils do @moduledoc """ Collection of helper functions for ExPwned """ def ua, do: {"User-Agent", Application.get_env(:ex_pwned, :user_agent) || "ExPwned Elixir Client"} def api_version, do: {"api-version", 2} def headers, do: [ua(), api_version()] def base_url, do: "https://haveibeenpwned.com/api" def json_library, do: Application.get_env(:ex_pwned, :json_library) || Jason end
30.071429
94
0.695962
793399e9ee7b7adfce41800d896948dab886b3ea
2,187
ex
Elixir
web/models/currency_balance.ex
lexa62/hb
c6b2169ad3e5af546da3f7ad0d499f5d5d29d044
[ "MIT" ]
null
null
null
web/models/currency_balance.ex
lexa62/hb
c6b2169ad3e5af546da3f7ad0d499f5d5d29d044
[ "MIT" ]
null
null
null
web/models/currency_balance.ex
lexa62/hb
c6b2169ad3e5af546da3f7ad0d499f5d5d29d044
[ "MIT" ]
null
null
null
defmodule Hb.CurrencyBalance do use Hb.Web, :model alias Hb.{Account, Currency, Repo, Transaction} schema "currency_balances" do field :initial_amount, Money.Ecto.Type field :current_amount, Money.Ecto.Type belongs_to :account, Account belongs_to :currency, Currency timestamps() end @doc """ Builds a changeset based on the `struct` and `params`. """ def changeset(struct, params \\ %{}) do struct |> cast(params, [:initial_amount, :current_amount, :account_id, :currency_id]) |> validate_required([:initial_amount, :current_amount, :account_id, :currency_id]) end def calculate_current_amount(model) do query = from t in Transaction, where: (t.source_account_id == ^(model.account_id) or t.destination_account_id == ^(model.account_id)) and t.currency_id == ^(model.currency_id), select: {t.type, t.amount, t.source_account_id, t.destination_account_id} current_amount = Repo.all(query) |> Enum.reduce(Money.new(0), fn(t, acc) -> case t do {:expense, amount, _source_account_id, _destination_account_id} -> Money.subtract(acc, amount) {:income, amount, _source_account_id, _destination_account_id} -> Money.add(acc, amount) {:transfer, amount, source_account_id, destination_account_id} -> cond do source_account_id == model.account_id -> Money.subtract(acc, amount) destination_account_id == model.account_id -> Money.add(acc, amount) end end end) |> Money.add(model.initial_amount) changeset(model, %{current_amount: current_amount}) end defimpl Poison.Encoder, for: Hb.CurrencyBalance do def encode(model, options) do model |> Map.take([:id, :currency, :account_id]) |> Map.put(:current_amount, Money.to_string(model.current_amount)) |> Map.put(:initial_amount, Money.to_string(model.initial_amount)) |> Poison.Encoder.encode(options) end end end
37.067797
108
0.616827
7933e996bf230447202f419c4115a81d09913afe
402
ex
Elixir
lib/app_web/auth_error_handler.ex
ThanhUong/Chronos
5e1b0823c585b784f5c51212513d518cab53a571
[ "MIT" ]
null
null
null
lib/app_web/auth_error_handler.ex
ThanhUong/Chronos
5e1b0823c585b784f5c51212513d518cab53a571
[ "MIT" ]
null
null
null
lib/app_web/auth_error_handler.ex
ThanhUong/Chronos
5e1b0823c585b784f5c51212513d518cab53a571
[ "MIT" ]
null
null
null
defmodule AppWeb.AuthErrorHandler do import Plug.Conn @behaviour Guardian.Plug.ErrorHandler @impl Guardian.Plug.ErrorHandler @spec auth_error(Plug.Conn.t(), {any, any}, any) :: Plug.Conn.t() def auth_error(conn, {type, _reason}, _opts) do body = Jason.encode!(%{message: to_string(type)}) conn |> put_resp_content_type("application/json") |> send_resp(401, body) end end
25.125
67
0.699005
7933f96819c8e338db9561a70e69e1de84bae5c1
493
ex
Elixir
lib/bus_kiosk_web/views/error_view.ex
mitchellhenke/bus_kiosk
9814b0b10190bb06c823b00315616391100c5bfa
[ "BSD-3-Clause" ]
2
2020-02-21T15:40:27.000Z
2020-12-06T21:50:39.000Z
lib/bus_kiosk_web/views/error_view.ex
mitchellhenke/bus_kiosk
9814b0b10190bb06c823b00315616391100c5bfa
[ "BSD-3-Clause" ]
3
2020-02-19T17:06:24.000Z
2020-04-20T14:33:07.000Z
lib/bus_kiosk_web/views/error_view.ex
mitchellhenke/bus_kiosk
9814b0b10190bb06c823b00315616391100c5bfa
[ "BSD-3-Clause" ]
null
null
null
defmodule BusKioskWeb.ErrorView do use BusKioskWeb, :view # If you want to customize a particular status code # for a certain format, you may uncomment below. # def render("500.html", _assigns) do # "Internal Server Error" # end # By default, Phoenix returns the status message from # the template name. For example, "404.html" becomes # "Not Found". def template_not_found(template, _assigns) do Phoenix.Controller.status_message_from_template(template) end end
29
61
0.736308
7933f99c1e837d57b3ebbfdaf437daec0f0311fb
183
exs
Elixir
priv/repo/migrations/20190605192812_add_deleted_at_to_teams.exs
smartlogic/Challenge_gov
b4203d1fcfb742dd17ecfadb9e9c56ad836d4254
[ "CC0-1.0" ]
9
2020-02-26T20:24:38.000Z
2022-03-22T21:14:52.000Z
priv/repo/migrations/20190605192812_add_deleted_at_to_teams.exs
smartlogic/Challenge_gov
b4203d1fcfb742dd17ecfadb9e9c56ad836d4254
[ "CC0-1.0" ]
15
2020-04-22T19:33:24.000Z
2022-03-26T15:11:17.000Z
priv/repo/migrations/20190605192812_add_deleted_at_to_teams.exs
smartlogic/Challenge_gov
b4203d1fcfb742dd17ecfadb9e9c56ad836d4254
[ "CC0-1.0" ]
4
2020-04-27T22:58:57.000Z
2022-01-14T13:42:09.000Z
defmodule ChallengeGov.Repo.Migrations.AddDeletedAtToTeams do use Ecto.Migration def change do alter table(:teams) do add(:deleted_at, :utc_datetime) end end end
18.3
61
0.73224
79340c0ce97ca6f049ad6e4034b115841f91a3f0
2,198
exs
Elixir
config/prod.exs
raincrash/pasteboard
e6b6f027bd18e1e4494c62c8127b89363b7466f5
[ "MIT" ]
null
null
null
config/prod.exs
raincrash/pasteboard
e6b6f027bd18e1e4494c62c8127b89363b7466f5
[ "MIT" ]
null
null
null
config/prod.exs
raincrash/pasteboard
e6b6f027bd18e1e4494c62c8127b89363b7466f5
[ "MIT" ]
null
null
null
use Mix.Config # For production, we configure the host to read the PORT # from the system environment. Therefore, you will need # to set PORT=80 before running your server. # # You should also configure the url host to something # meaningful, we use this information when generating URLs. # # Finally, we also include the path to a manifest # containing the digested version of static files. This # manifest is generated by the mix phoenix.digest task # which you typically run after static files are built. config :pasteboard, Pasteboard.Endpoint, http: [port: {:system, "PORT"}], url: [host: "example.com", port: 80], cache_static_manifest: "priv/static/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 :pasteboard, Pasteboard.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [port: 443, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH")] # # Where those two env variables return an absolute path to # the key and cert in disk or a relative path inside priv, # for example "priv/ssl/server.key". # # We also recommend setting `force_ssl`, ensuring no data is # ever sent via http, always redirecting to https: # # config :pasteboard, Pasteboard.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # ## Using releases # # If you are doing OTP releases, you need to instruct Phoenix # to start the server for all endpoints: # # config :phoenix, :serve_endpoints, true # # Alternatively, you can configure exactly which server to # start per endpoint: # # config :pasteboard, Pasteboard.Endpoint, server: true # # You will also need to set the application root to `.` in order # for the new static assets to be served after a hot upgrade: # # config :pasteboard, Pasteboard.Endpoint, root: "." # Finally import the config/prod.secret.exs # which should be versioned separately. import_config "prod.secret.exs"
33.30303
67
0.716106
79346045d6e4a8c0beb48e981fb4750b1c90ea77
2,345
ex
Elixir
lib/j_viewer.ex
mtvch/j-viewer
54d5a0a8bc6a37a77e94d2b4c5bf9db0c0c6e5a7
[ "MIT" ]
1
2021-08-05T05:39:00.000Z
2021-08-05T05:39:00.000Z
lib/j_viewer.ex
mtvch/j-viewer
54d5a0a8bc6a37a77e94d2b4c5bf9db0c0c6e5a7
[ "MIT" ]
null
null
null
lib/j_viewer.ex
mtvch/j-viewer
54d5a0a8bc6a37a77e94d2b4c5bf9db0c0c6e5a7
[ "MIT" ]
null
null
null
defmodule JViewer do @moduledoc """ JViewer is an excellent way to declaratively represent elixir data in a JSON encodable format. """ alias JViewer.Types.Object @type schema() :: JViewer.Types.Object.t() @spec represent(map, schema(), any()) :: map() @doc """ Represents __data__ in a JSON encodable format according to __schema__. If __data__ cannot be represented, an exception is thrown. ## Example iex> import JViewer ...> iex> schema = iex> object( iex> fields: [ iex> field( iex> key: "id", iex> type: number() iex> ), iex> field( iex> key: "title", iex> type: string() iex> ) iex> ] iex> ) ...> iex> data = %{ iex> id: 1, iex> info: "I ate bread for breakfast", iex> title: "Notes" iex> } ...> iex> represent(data, schema) %{ "id" => 1, "title" => "Notes" } """ def represent(data, schema, general_handlers_params \\ %{}) def represent(%{} = data, %JViewer.Types.Object{} = schema, general_handlers_params) do Object.apply_schema(schema, data, general_handlers_params) end # Functions for building return schemas. @spec object(keyword()) :: struct() def object(args) do build_struct(%JViewer.Types.Object{}, args) end @spec field(keyword()) :: struct() def field(args) do build_struct(%JViewer.Types.Object.Field{}, args) end @spec number(keyword()) :: struct() def number(args \\ []) do build_struct(%JViewer.Types.Number{}, args) end @spec boolean(keyword()) :: struct() def boolean(args \\ []) do build_struct(%JViewer.Types.Boolean{}, args) end @spec array(keyword()) :: struct() def array(args) do build_struct(%JViewer.Types.Array{}, args) end @spec string(keyword()) :: struct() def string(args \\ []) do build_struct(%JViewer.Types.String{}, args) end defp build_struct(type, args) do if !Keyword.keyword?(args), do: raise(ArgumentError) type |> Map.keys() |> Enum.reduce(type, fn key, res -> value = case Keyword.get(args, key) do nil -> Map.get(type, key) v -> v end Map.put(res, key, value) end) end end
23.686869
96
0.570149
79346ad8a25fa24fedde1646c5a93709faae9881
900
ex
Elixir
clients/video_intelligence/lib/google_api/video_intelligence/v1/metadata.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/video_intelligence/lib/google_api/video_intelligence/v1/metadata.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/video_intelligence/lib/google_api/video_intelligence/v1/metadata.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.VideoIntelligence.V1 do @moduledoc """ API client metadata for GoogleApi.VideoIntelligence.V1. """ @discovery_revision "20200602" def discovery_revision(), do: @discovery_revision end
33.333333
74
0.763333
79347b1384739054c7319dd0cd8f9cc8942aa863
1,851
ex
Elixir
lib/liveview_todos/list_aggregate.ex
mwindholtz/liveview_todos
1f6a2e576be4a41f49d0bfe2b01da97d268d0d0d
[ "Apache-2.0" ]
null
null
null
lib/liveview_todos/list_aggregate.ex
mwindholtz/liveview_todos
1f6a2e576be4a41f49d0bfe2b01da97d268d0d0d
[ "Apache-2.0" ]
2
2021-03-09T14:03:26.000Z
2021-05-10T06:02:53.000Z
lib/liveview_todos/list_aggregate.ex
mwindholtz/liveview_todos
1f6a2e576be4a41f49d0bfe2b01da97d268d0d0d
[ "Apache-2.0" ]
null
null
null
defmodule LiveviewTodos.ListAggregate do @moduledoc """ """ @deps %{repo: LiveviewTodos.Repo} use GenServer, restart: :transient alias LiveviewTodos.List alias LiveviewTodos.ListAggregate.State alias LiveviewTodos.TargetedTopic alias LiveviewTodos.DomainEvent require Logger defmodule State do @enforce_keys [:list_id, :name, :deps] defstruct [:list_id, :name, :deps] end # --------- Client Interface ------------- def start_link(list_id) do GenServer.start_link(__MODULE__, list_id, name: via_tuple(list_id)) end # --------- Server ------------- def init(list_id) when is_integer(list_id) do state = %State{list_id: list_id, name: "TBD", deps: @deps} {:ok, state, {:continue, :ok}} end def handle_continue(:ok, %State{} = state) do list = list(state) TargetedTopic.subscribe(list.id) state = %{state | name: list.name} {:noreply, state} end def handle_info(%DomainEvent{name: :toggle_item_requested, attrs: attrs}, state) do state |> list() |> List.toggle_item(attrs.item_title) {:noreply, state} end def handle_info(%DomainEvent{name: :create_item_requested, attrs: attrs}, state) do state |> list() |> List.create_item(%{"description" => attrs.description}) {:noreply, state} end def handle_info(%DomainEvent{name: :delete_list_requested}, state) do list = list(state) List.delete(list) TargetedTopic.unsubscribe(list.id) {:stop, :normal, state} end # catchall -------------- def handle_info(%DomainEvent{}, state) do {:noreply, state} end # ---------- Implementation ------ def via_tuple(list_id) do {:via, Registry, {LiveviewTodos.ListAggregateRegistry, "#{list_id}"}} end defp list(%State{list_id: list_id, deps: deps}) do deps.repo.get_list(list_id) end end
23.43038
85
0.650999
7934afc9933a728e0dd345303c39fe82a3f03a3b
358
ex
Elixir
lib/ambry/media/media/chapter.ex
doughsay/ambry
c04e855bf06a6b00b8053c6eacb2eac14a56a37c
[ "MIT" ]
12
2021-09-30T20:51:49.000Z
2022-01-27T04:09:32.000Z
lib/ambry/media/media/chapter.ex
doughsay/ambry
c04e855bf06a6b00b8053c6eacb2eac14a56a37c
[ "MIT" ]
76
2021-10-01T05:45:11.000Z
2022-03-28T04:12:39.000Z
lib/ambry/media/media/chapter.ex
doughsay/ambry
c04e855bf06a6b00b8053c6eacb2eac14a56a37c
[ "MIT" ]
2
2021-10-04T19:27:28.000Z
2022-01-13T22:36:38.000Z
defmodule Ambry.Media.Media.Chapter do @moduledoc """ A chapter """ use Ecto.Schema import Ecto.Changeset @primary_key false @derive {Jason.Encoder, only: [:time, :title]} embedded_schema do field :time, :decimal field :title, :string end def changeset(chapter, attrs) do cast(chapter, attrs, [:time, :title]) end end
15.565217
48
0.664804
7934c8f7c246dbe20b4f92c3dff99e631aec1e57
3,664
exs
Elixir
test/integration/chromium/cdp_session_test.exs
dbrody/playwright-elixir
48611c08dbdb8e36aa4dd8aa2d97a4014b753815
[ "MIT" ]
30
2021-06-01T16:59:35.000Z
2022-03-25T16:56:19.000Z
test/integration/chromium/cdp_session_test.exs
dbrody/playwright-elixir
48611c08dbdb8e36aa4dd8aa2d97a4014b753815
[ "MIT" ]
35
2021-06-10T17:05:31.000Z
2022-02-11T22:30:36.000Z
test/integration/chromium/cdp_session_test.exs
dbrody/playwright-elixir
48611c08dbdb8e36aa4dd8aa2d97a4014b753815
[ "MIT" ]
4
2021-08-13T20:38:18.000Z
2022-01-31T04:32:35.000Z
defmodule Playwright.Chromium.CDPSessionTest do use Playwright.TestCase, async: true alias Playwright.{Browser, BrowserContext, CDPSession, Page} describe "BrowserContext.new_cdp_session/1" do test "a page-attached CDP session", %{page: page} do context = Page.context(page) assert %CDPSession{} = BrowserContext.new_cdp_session(context, page) end test "a frame-attached CDP session", %{page: page} do context = Page.context(page) frame = Page.main_frame(page) assert %CDPSession{} = BrowserContext.new_cdp_session(context, frame) end end describe "CDPSession.send/2" do test "using `Runtime` methods", %{page: page} do context = Page.context(page) session = BrowserContext.new_cdp_session(context, page) CDPSession.send(session, "Runtime.enable") %{result: result} = CDPSession.send(session, "Runtime.evaluate", %{ expression: "window.foo = 'bar'; 'expression result'" }) assert result == %{type: "string", value: "expression result"} assert "bar" == Page.evaluate(page, "() => window.foo") end end describe "CDPSession.on/3" do test "handling Runtime console events`", %{page: page} do pid = self() context = Page.context(page) session = BrowserContext.new_cdp_session(context, page) CDPSession.send(session, "Runtime.enable") CDPSession.on(session, "Runtime.consoleAPICalled", fn event -> send(pid, {:args, event.params.args}) end) CDPSession.send(session, "Runtime.evaluate", %{ expression: "console.log('log message');" }) assert_received({:args, [%{type: "string", value: "log message"}]}) end test "handling Network events", %{assets: assets, page: page} do pid = self() url = assets.empty context = Page.context(page) session = BrowserContext.new_cdp_session(context, page) CDPSession.send(session, "Network.enable") CDPSession.on(session, "Network.requestWillBeSent", fn event -> send(pid, {:request_url, event.params.documentURL}) end) Page.goto(page, url) assert_received({:request_url, ^url}) end end describe "CDPSession.detach/1" do test "detaches the sesssion", %{page: page} do context = Page.context(page) session = BrowserContext.new_cdp_session(context, page) CDPSession.send(session, "Runtime.enable") %{result: result} = CDPSession.send(session, "Runtime.evaluate", %{ expression: "3 + 1" }) assert result.value == 4 CDPSession.detach(session) {:error, %{message: message}} = CDPSession.send(session, "Runtime.evaluate", %{ expression: "3 + 1" }) assert message == "Target page, context or browser has been closed" end @tag exclude: [:page] test "does not break Page.close/2", %{browser: browser} do context = Browser.new_context(browser) page = BrowserContext.new_page(context) session = BrowserContext.new_cdp_session(context, page) CDPSession.detach(session) Page.close(page) BrowserContext.close(context) end end describe "CDPSession lifecycle" do @tag without: [:page] test "detaches on Page.close/2", %{browser: browser} do context = Browser.new_context(browser) page = BrowserContext.new_page(context) session = BrowserContext.new_cdp_session(context, page) Page.close(page) {:error, %{message: message}} = CDPSession.detach(session) assert message == "Target page, context or browser has been closed" end end end
29.548387
75
0.646834
7934d3f1ebc67cf6c5a07e0bf890f6381acdc4c8
2,066
ex
Elixir
clients/app_engine/lib/google_api/app_engine/v1/model/location_metadata.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/app_engine/lib/google_api/app_engine/v1/model/location_metadata.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/app_engine/lib/google_api/app_engine/v1/model/location_metadata.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.AppEngine.V1.Model.LocationMetadata do @moduledoc """ Metadata for the given google.cloud.location.Location. ## Attributes * `flexibleEnvironmentAvailable` (*type:* `boolean()`, *default:* `nil`) - App Engine flexible environment is available in the given location.@OutputOnly * `searchApiAvailable` (*type:* `boolean()`, *default:* `nil`) - Output only. Search API (https://cloud.google.com/appengine/docs/standard/python/search) is available in the given location. * `standardEnvironmentAvailable` (*type:* `boolean()`, *default:* `nil`) - App Engine standard environment is available in the given location.@OutputOnly """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :flexibleEnvironmentAvailable => boolean() | nil, :searchApiAvailable => boolean() | nil, :standardEnvironmentAvailable => boolean() | nil } field(:flexibleEnvironmentAvailable) field(:searchApiAvailable) field(:standardEnvironmentAvailable) end defimpl Poison.Decoder, for: GoogleApi.AppEngine.V1.Model.LocationMetadata do def decode(value, options) do GoogleApi.AppEngine.V1.Model.LocationMetadata.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AppEngine.V1.Model.LocationMetadata do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.981132
193
0.74153
7934f5c9730b240fbaf7e4b474fe49038b461e62
4,887
ex
Elixir
deps/phoenix/lib/phoenix/router/scope.ex
hallebadkapp/rumbl-ms
ae2ef9975658115f8c4d5c49c28d8bde00a74b83
[ "MIT" ]
null
null
null
deps/phoenix/lib/phoenix/router/scope.ex
hallebadkapp/rumbl-ms
ae2ef9975658115f8c4d5c49c28d8bde00a74b83
[ "MIT" ]
null
null
null
deps/phoenix/lib/phoenix/router/scope.ex
hallebadkapp/rumbl-ms
ae2ef9975658115f8c4d5c49c28d8bde00a74b83
[ "MIT" ]
null
null
null
defmodule Phoenix.Router.Scope do alias Phoenix.Router.Scope @moduledoc false @stack :phoenix_router_scopes @pipes :phoenix_pipeline_scopes defstruct path: nil, alias: nil, as: nil, pipes: [], host: nil, private: %{}, assigns: %{} @doc """ Initializes the scope. """ def init(module) do Module.put_attribute(module, @stack, [%Scope{}]) Module.put_attribute(module, @pipes, MapSet.new) end @doc """ Builds a route based on the top of the stack. """ def route(module, kind, verb, "/" <> _ = path, plug, plug_opts, opts) do private = Keyword.get(opts, :private, %{}) assigns = Keyword.get(opts, :assigns, %{}) as = Keyword.get(opts, :as, Phoenix.Naming.resource_name(plug, "Controller")) {path, host, alias, as, pipes, private, assigns} = join(module, path, plug, as, private, assigns) Phoenix.Router.Route.build(kind, verb, path, host, alias, plug_opts, as, pipes, private, assigns) end def route(module, kind, verb, path, plug, plug_opts, opts) when is_binary(path) do IO.write :stderr, """ warning: router paths should begin with a forward slash. #{Exception.format_stacktrace} """ route(module, kind, verb, "/" <> path, plug, plug_opts, opts) end def route(_module, _kind, _verb, path, _plug, _plug_opts, _opts) do raise ArgumentError, "router paths must be strings, got: #{inspect path}" end @doc """ Defines the given pipeline. """ def pipeline(module, pipe) when is_atom(pipe) do update_pipes module, &MapSet.put(&1, pipe) end @doc """ Appends the given pipes to the current scope pipe through. """ def pipe_through(module, pipes) do pipes = List.wrap(pipes) update_stack(module, fn [scope|stack] -> scope = put_in scope.pipes, scope.pipes ++ pipes [scope|stack] end) end @doc """ Pushes a scope into the module stack. """ def push(module, path) when is_binary(path) do push(module, path: path) end def push(module, opts) when is_list(opts) do path = Keyword.get(opts, :path) if path && String.at(path, 0) != "/" do IO.write :stderr, """ warning: router paths should begin with a forward slash. #{Exception.format_stacktrace} """ end path = path && Plug.Router.Utils.split(path) alias = Keyword.get(opts, :alias) alias = alias && Atom.to_string(alias) scope = %Scope{path: path, alias: alias, as: Keyword.get(opts, :as), host: Keyword.get(opts, :host), pipes: [], private: Keyword.get(opts, :private, %{}), assigns: Keyword.get(opts, :assigns, %{})} update_stack(module, fn stack -> [scope|stack] end) end @doc """ Pops a scope from the module stack. """ def pop(module) do update_stack(module, fn [_|stack] -> stack end) end @doc """ Returns true if the module's definition is currently within a scope block """ def inside_scope?(module), do: length(get_stack(module)) > 1 defp join(module, path, alias, as, private, assigns) do stack = get_stack(module) {join_path(stack, path), find_host(stack), join_alias(stack, alias), join_as(stack, as), join_pipe_through(stack), join_private(stack, private), join_assigns(stack, assigns)} end defp join_path(stack, path) do "/" <> ([Plug.Router.Utils.split(path)|extract(stack, :path)] |> Enum.reverse() |> Enum.concat() |> Enum.join("/")) end defp join_alias(stack, alias) when is_atom(alias) do [alias|extract(stack, :alias)] |> Enum.reverse() |> Module.concat() end defp join_as(_stack, nil), do: nil defp join_as(stack, as) when is_atom(as) or is_binary(as) do [as|extract(stack, :as)] |> Enum.reverse() |> Enum.join("_") end defp join_private(stack, private) do Enum.reduce stack, private, &Map.merge(&1.private, &2) end defp join_assigns(stack, assigns) do Enum.reduce stack, assigns, &Map.merge(&1.assigns, &2) end defp join_pipe_through(stack) do for scope <- Enum.reverse(stack), item <- scope.pipes, do: item end defp find_host(stack) do Enum.find_value(stack, & &1.host) end defp extract(stack, attr) do for scope <- stack, item = Map.fetch!(scope, attr), do: item end defp get_stack(module) do get_attribute(module, @stack) end defp update_stack(module, fun) do update_attribute(module, @stack, fun) end defp update_pipes(module, fun) do update_attribute(module, @pipes, fun) end defp get_attribute(module, attr) do Module.get_attribute(module, attr) || raise "Phoenix router scope was not initialized" end defp update_attribute(module, attr, fun) do Module.put_attribute(module, attr, fun.(get_attribute(module, attr))) end end
27.301676
101
0.634745
7934f5f1d17831e8c28a8b2a70cad2fc7a7e3a2a
61
ex
Elixir
lib/ledemo_web/views/layout_view.ex
andyl/live_editable_demo
645d628d8717d706da207db9fe9f6f71ecfce303
[ "MIT" ]
null
null
null
lib/ledemo_web/views/layout_view.ex
andyl/live_editable_demo
645d628d8717d706da207db9fe9f6f71ecfce303
[ "MIT" ]
7
2021-05-10T15:57:48.000Z
2021-05-27T13:05:14.000Z
lib/ledemo_web/views/layout_view.ex
andyl/live_editable_demo
645d628d8717d706da207db9fe9f6f71ecfce303
[ "MIT" ]
null
null
null
defmodule LedemoWeb.LayoutView do use LedemoWeb, :view end
15.25
33
0.803279
7934fe579bdfdd7ace06d75e558203a1b24b02ff
1,058
exs
Elixir
clients/plus/test/test_helper.exs
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/plus/test/test_helper.exs
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/plus/test/test_helper.exs
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. ExUnit.start() defmodule GoogleApi.Plus.TestHelper do defmacro __using__(opts) do quote do use ExUnit.Case, unquote(opts) import GoogleApi.Plus.TestHelper end end def for_scope(scopes) when is_list(scopes), do: for_scope(Enum.join(scopes, " ")) def for_scope(scope) do {:ok, token} = Goth.Token.for_scope(scope) token.token end end
29.388889
83
0.73724
793501e8c56286f335814f66a9f47067f310faee
435
ex
Elixir
lib/http/client_api.ex
LucidModules/ueberauth_line
686e41ddeef83ecaf55e21ca0bf0337645deb9c1
[ "MIT" ]
null
null
null
lib/http/client_api.ex
LucidModules/ueberauth_line
686e41ddeef83ecaf55e21ca0bf0337645deb9c1
[ "MIT" ]
null
null
null
lib/http/client_api.ex
LucidModules/ueberauth_line
686e41ddeef83ecaf55e21ca0bf0337645deb9c1
[ "MIT" ]
null
null
null
defmodule Http.ClientApi do @type t :: module @type body :: map() @type headers :: tuple() @type url :: String.t() @type response :: map() # TODO: types like post_params, get_params, etc? @doc """ HTTP GET request. """ @callback get(headers, url) :: {:ok, response} | {:error, String.t()} @doc """ HTTP POST request """ @callback post(body, headers, url) :: {:ok, response} | {:error, String.t()} end
19.772727
78
0.590805
793512221e25a421154f9ae2478aa6fb3478b693
2,707
ex
Elixir
lib/game/socials.ex
the3hm/seraph_mud
c098a22184a0a6bcbd56cacf7b0f176dd173260d
[ "MIT" ]
2
2019-05-14T11:36:44.000Z
2020-07-01T08:54:04.000Z
lib/game/socials.ex
nickwalton/ex_venture
d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb
[ "MIT" ]
null
null
null
lib/game/socials.ex
nickwalton/ex_venture
d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb
[ "MIT" ]
1
2021-01-29T14:12:40.000Z
2021-01-29T14:12:40.000Z
defmodule Game.Socials do @moduledoc """ Agent for keeping track of socials in the system """ use GenServer alias Data.Social alias Data.Repo @key :socials @doc false def start_link() do GenServer.start_link(__MODULE__, [], name: __MODULE__) end @spec social(integer()) :: Social.t() | nil def social(instance = %Social{}) do social(instance.id) end def social(id) when is_integer(id) do _fetch_from_cache(@key, id) end def social(command) when is_binary(command) do _fetch_from_cache(@key, command) end @spec socials([integer()]) :: [Social.t()] def socials(ids) do ids |> Enum.map(&social/1) |> Enum.reject(&is_nil/1) end @doc """ Fetch all socials """ @spec all() :: [Social.t()] def all() do Cachex.execute!(@key, fn cache -> {:ok, keys} = Cachex.keys(cache) keys = Enum.filter(keys, &is_integer/1) socials = keys |> Enum.map(&_fetch_from_cache(cache, &1)) |> Enum.reject(&is_nil/1) socials end) end defp _fetch_from_cache(cache, key) do case Cachex.get(cache, key) do {:ok, nil} -> nil {:ok, social} -> social _ -> nil end end @doc """ Insert a new social into the loaded data """ @spec insert(Social.t()) :: :ok def insert(social) do members = :pg2.get_members(@key) Enum.map(members, fn member -> GenServer.call(member, {:insert, social}) end) end @doc """ Trigger a social reload """ @spec reload(Social.t()) :: :ok def reload(social), do: insert(social) @doc """ Clean out an old command if it was updated """ @spec remove_command(String.t()) :: :ok def remove_command(command) do members = :pg2.get_members(@key) Enum.map(members, fn member -> GenServer.call(member, {:remove_command, command}) end) end @doc """ For testing only: clear the EST table """ def clear() do Cachex.clear(@key) end # # Server # def init(_) do :ok = :pg2.create(@key) :ok = :pg2.join(@key, self()) GenServer.cast(self(), :load_socials) {:ok, %{}} end def handle_cast(:load_socials, state) do socials = Social |> Repo.all() Enum.each(socials, fn social -> Cachex.put(@key, social.id, social) Cachex.put(@key, social.command, social) end) {:noreply, state} end def handle_call({:insert, social}, _from, state) do Cachex.put(@key, social.id, social) Cachex.put(@key, social.command, social) {:reply, :ok, state} end def handle_call({:remove_command, command}, _from, state) do Cachex.del(@key, command) {:reply, :ok, state} end end
18.93007
62
0.599557
793514f4cb3a33adf582eeef78af8465692f2e57
983
ex
Elixir
client/lib/rudp_client.ex
vfournie/rudp-playground
33b72e69e9bfab75df2febeab0c8c3e9b5fffd16
[ "MIT" ]
1
2017-07-14T03:19:56.000Z
2017-07-14T03:19:56.000Z
client/lib/rudp_client.ex
vfournie/rudp-playground
33b72e69e9bfab75df2febeab0c8c3e9b5fffd16
[ "MIT" ]
null
null
null
client/lib/rudp_client.ex
vfournie/rudp-playground
33b72e69e9bfab75df2febeab0c8c3e9b5fffd16
[ "MIT" ]
null
null
null
defmodule RudpClient do use Application require Logger def start(_type, _args) do import Supervisor.Spec, warn: false children = [ supervisor(RudpClient.Collector.Supervisor, []), supervisor(RudpClient.Worker.Supervisor, []), ] opts = [strategy: :one_for_one, name: RudpClient.Supervisor] Supervisor.start_link(children, opts) end def start_client(client_id, address \\ "127.0.0.1", port \\ Application.get_env(:rudp_client, :udp_port)) do RudpClient.Worker.Supervisor.start_child(address, port, client_id) end def start_clients(nb_clients, address \\ "127.0.0.1", port \\ Application.get_env(:rudp_client, :udp_port)) do Enum.each(1..nb_clients, fn(client_id) -> {:ok, client} = start_client(client_id, address, port) initial_delay = Enum.random(50..300) RudpClient.Worker.start_ping(client, initial_delay) end) end end
32.766667
114
0.646999
79351d2d2fc3b8fcf66ae4d0d7041ff15f6109c3
2,317
exs
Elixir
mix.exs
kek/wobserver
b58fbf70b398517f1ffd44c43dc9fc6df350784e
[ "MIT" ]
null
null
null
mix.exs
kek/wobserver
b58fbf70b398517f1ffd44c43dc9fc6df350784e
[ "MIT" ]
null
null
null
mix.exs
kek/wobserver
b58fbf70b398517f1ffd44c43dc9fc6df350784e
[ "MIT" ]
null
null
null
defmodule Wobserver.Mixfile do use Mix.Project def project do [ app: :wobserver, version: "0.1.8", elixir: "~> 1.4", description: "Web based metrics, monitoring, and observer.", package: package(), build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, deps: deps(), # Testing test_coverage: [tool: ExCoveralls], preferred_cli_env: [ coveralls: :test, "coveralls.detail": :test, "coveralls.post": :test, "coveralls.html": :test ], dialyzer: [ignore_warnings: "dialyzer.ignore-warnings"], # Docs name: "Wobserver", source_url: "https://github.com/shinyscorpion/wobserver", homepage_url: "https://github.com/shinyscorpion/wobserver", docs: [ main: "readme", extras: ["README.md"] ] ] end def package do [ name: :wobserver, maintainers: ["Ian Luites"], licenses: ["MIT"], files: [ # Elixir "lib/wobserver", "lib/wobserver.ex", "mix.exs", "README*", "LICENSE*" ], links: %{ "GitHub" => "https://github.com/shinyscorpion/wobserver" } ] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do # Specify extra applications you'll use from Erlang/Elixir [ extra_applications: [ :logger, :httpoison ], mod: {Wobserver.Application, []} ] end # Dependencies can be Hex packages: # # {:my_dep, "~> 0.3.0"} # # Or git/path repositories: # # {:my_dep, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} # # Type "mix help deps" for more examples and options defp deps do [ {:cowboy, "~> 1.1 or ~> 2.8"}, {:credo, "~> 0.7", only: [:dev, :test]}, {:dialyxir, "~> 0.5", only: [:dev], runtime: false}, {:ex_doc, "~> 0.15", only: :dev}, {:excoveralls, "~> 0.6", only: :test}, {:httpoison, "~> 0.11 or ~> 0.12 or ~> 1.8"}, {:inch_ex, "~> 0.5", only: [:dev, :test]}, {:meck, "~> 0.8.4", only: :test}, {:plug, "~> 1.3 or ~> 1.4"}, {:poison, "~> 2.0 or ~> 3.1"}, {:websocket_client, "~> 1.2"} ] end end
25.184783
79
0.524817
7935236a6bc9274a5dd26590a22ea1896b68b3d4
1,977
ex
Elixir
deps/credo/lib/credo/check/refactor/function_arity.ex
robot-overlord/starter_kit
254153221d0a3a06324c65ad8e89d610de2429c3
[ "MIT" ]
1
2020-01-31T10:23:37.000Z
2020-01-31T10:23:37.000Z
deps/credo/lib/credo/check/refactor/function_arity.ex
robot-overlord/starter_kit
254153221d0a3a06324c65ad8e89d610de2429c3
[ "MIT" ]
null
null
null
deps/credo/lib/credo/check/refactor/function_arity.ex
robot-overlord/starter_kit
254153221d0a3a06324c65ad8e89d610de2429c3
[ "MIT" ]
null
null
null
defmodule Credo.Check.Refactor.FunctionArity do @moduledoc """ A function can take as many parameters as needed, but even in a functional language there can be too many parameters. Can optionally ignore private functions (check configuration options). """ @explanation [ check: @moduledoc, params: [ max_arity: "The maximum number of parameters which a function should take.", ignore_defp: "Set to `true` to ignore private functions." ] ] @default_params [max_arity: 5, ignore_defp: false] @def_ops [:def, :defp, :defmacro] alias Credo.Code.Parameters use Credo.Check @doc false def run(%SourceFile{ast: ast} = source_file, params \\ []) do issue_meta = IssueMeta.for(source_file, params) max_arity = Params.get(params, :max_arity, @default_params) ignore_defp = Params.get(params, :ignore_defp, @default_params) Credo.Code.prewalk(ast, &traverse(&1, &2, issue_meta, max_arity, ignore_defp)) end for op <- @def_ops do defp traverse({unquote(op) = op, meta, arguments} = ast, issues, issue_meta, max_arity, ignore_defp) when is_list(arguments) do arity = Parameters.count(ast) if issue?(op, ignore_defp, arity, max_arity) do fun_name = CodeHelper.def_name(ast) {ast, issues ++ [issue_for(issue_meta, meta[:line], fun_name, max_arity, arity)]} else {ast, issues} end end end defp traverse(ast, issues, _issue_meta, _max_arity, _ignore_defp) do {ast, issues} end def issue?(:defp, true, _, _), do: false def issue?(_, _, arity, max_arity) when arity > max_arity, do: true def issue?(_, _, _, _), do: false def issue_for(issue_meta, line_no, trigger, max_value, actual_value) do format_issue issue_meta, message: "Function takes too many parameters (arity is #{actual_value}, max is #{max_value}).", trigger: trigger, line_no: line_no, severity: Severity.compute(actual_value, max_value) end end
32.409836
131
0.686394
7935406804ba66e4243f21ce7c82c479bda1aec0
1,362
ex
Elixir
clients/cloud_search/lib/google_api/cloud_search/v1/model/media.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/cloud_search/lib/google_api/cloud_search/v1/model/media.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/cloud_search/lib/google_api/cloud_search/v1/model/media.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.CloudSearch.V1.Model.Media do @moduledoc """ Media resource. ## Attributes * `resourceName` (*type:* `String.t`, *default:* `nil`) - Name of the media resource. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :resourceName => String.t() | nil } field(:resourceName) end defimpl Poison.Decoder, for: GoogleApi.CloudSearch.V1.Model.Media do def decode(value, options) do GoogleApi.CloudSearch.V1.Model.Media.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudSearch.V1.Model.Media do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
28.978723
89
0.729075
79354c3b525bba28b0f699e859b447d79ca33d1a
1,578
ex
Elixir
lib/community_web/endpoint.ex
aleccool213/elixir-graphql-example
8f89f4898cda7b7544321ff8dda2f76ea22d4c58
[ "MIT" ]
1
2018-01-16T10:28:38.000Z
2018-01-16T10:28:38.000Z
lib/community_web/endpoint.ex
aleccool213/elixir-graphql-example
8f89f4898cda7b7544321ff8dda2f76ea22d4c58
[ "MIT" ]
null
null
null
lib/community_web/endpoint.ex
aleccool213/elixir-graphql-example
8f89f4898cda7b7544321ff8dda2f76ea22d4c58
[ "MIT" ]
null
null
null
defmodule CommunityWeb.Endpoint do use Phoenix.Endpoint, otp_app: :community socket "/socket", CommunityWeb.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: :community, 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 plug Phoenix.CodeReloader end plug Plug.RequestId plug Plug.Logger plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Poison plug Plug.MethodOverride plug Plug.Head # The session will be stored in the cookie and signed, # this means its contents can be read but not tampered with. # Set :encryption_salt if you would also like to encrypt it. plug Plug.Session, store: :cookie, key: "_community_key", signing_salt: "HnDytM3j" plug CommunityWeb.Router @doc """ Callback invoked for dynamically configuring the endpoint. It receives the endpoint configuration and checks if configuration should be loaded from the system environment. """ def init(_key, config) do if config[:load_from_system_env] do port = System.get_env("PORT") || raise "expected the PORT environment variable to be set" {:ok, Keyword.put(config, :http, [:inet6, port: port])} else {:ok, config} end end end
28.178571
95
0.705323
79354e12a3ce229e4667faa9249000fe5731caaa
2,512
exs
Elixir
test/config_test.exs
alejandrodnm/elixir_agent
b2264d8f54244d136950cadd02f2533967a8e7cb
[ "Apache-2.0" ]
null
null
null
test/config_test.exs
alejandrodnm/elixir_agent
b2264d8f54244d136950cadd02f2533967a8e7cb
[ "Apache-2.0" ]
1
2019-02-08T01:08:31.000Z
2019-02-20T00:24:51.000Z
test/config_test.exs
alejandrodnm/elixir_agent
b2264d8f54244d136950cadd02f2533967a8e7cb
[ "Apache-2.0" ]
null
null
null
defmodule ConfigTest do use ExUnit.Case test "Version read from file" do assert NewRelic.Config.agent_version() == Mix.Project.config()[:version] end test "Logger output device" do inital_logger = NewRelic.Logger.initial_logger() System.put_env("NEW_RELIC_LOG", "stdout") assert :stdio == NewRelic.Logger.initial_logger() System.put_env("NEW_RELIC_LOG", "some_file.log") assert {:file, "some_file.log"} == NewRelic.Logger.initial_logger() System.put_env("NEW_RELIC_LOG", "Logger") assert :logger == NewRelic.Logger.initial_logger() System.delete_env("NEW_RELIC_LOG") assert inital_logger == NewRelic.Logger.initial_logger() end test "hydrate automatic attributes" do System.put_env("ENV_VAR_NAME", "env-var-value") Application.put_env( :new_relic_agent, :automatic_attributes, env_var: {:system, "ENV_VAR_NAME"}, function_call: {String, :upcase, ["fun"]}, raw: "attribute" ) assert NewRelic.Config.automatic_attributes() == %{ env_var: "env-var-value", raw: "attribute", function_call: "FUN" } Application.put_env(:new_relic_agent, :automatic_attributes, []) System.delete_env("ENV_VAR_NAME") end test "Can configure error collecting via ENV and Application" do System.put_env("NEW_RELIC_ERROR_COLLECTOR_ENABLED", "false") refute NewRelic.Config.feature?(:error_collector) System.delete_env("NEW_RELIC_ERROR_COLLECTOR_ENABLED") assert NewRelic.Config.feature?(:error_collector) System.put_env("NEW_RELIC_ERROR_COLLECTOR_ENABLED", "true") Application.get_env(:new_relic_agent, :error_collector_enabled, false) assert NewRelic.Config.feature?(:error_collector) System.delete_env("NEW_RELIC_ERROR_COLLECTOR_ENABLED") end test "Parse multiple app names" do System.put_env("NEW_RELIC_APP_NAME", "One Name; Two Names ") assert "Two Names" in NewRelic.Config.app_name() assert length(NewRelic.Config.app_name()) == 2 System.put_env("NEW_RELIC_APP_NAME", "One Name") assert length(NewRelic.Config.app_name()) == 1 System.delete_env("NEW_RELIC_APP_NAME") end test "Parse labels" do System.put_env("NEW_RELIC_LABELS", "key1:value1;key2:value2; key3 :value3;stray ") labels = NewRelic.Config.labels() assert ["key3", "value3"] in labels assert length(labels) == 3 System.delete_env("NEW_RELIC_LABELS") assert [] == NewRelic.Config.labels() end end
29.209302
86
0.701035
793591cf2def2caea76d29ca3f26129b25ec6e13
3,046
ex
Elixir
lib/ex_change_rate_web/schemas.ex
ding-an-sich/ex_change_rate
89858694dc98cef6d21089599120600a075c93db
[ "MIT" ]
null
null
null
lib/ex_change_rate_web/schemas.ex
ding-an-sich/ex_change_rate
89858694dc98cef6d21089599120600a075c93db
[ "MIT" ]
null
null
null
lib/ex_change_rate_web/schemas.ex
ding-an-sich/ex_change_rate
89858694dc98cef6d21089599120600a075c93db
[ "MIT" ]
null
null
null
defmodule ExChangeRateWeb.Schemas do @moduledoc """ Open Api schema """ alias OpenApiSpex.Schema require OpenApiSpex defmodule ExchangeRateCreateParams do @moduledoc """ ExchangeRateCreateParams schema """ OpenApiSpex.schema(%{ title: "Exchange rate operation create params", description: "Creates a new exchange rate request to be processed by the application", type: :object, properties: %{ user_id: %Schema{ type: :string, description: "User UUID" }, from: %Schema{ type: :string, description: "Three letter origin currency code" }, to: %Schema{ type: :string, description: "Three letter target currency code" }, from_value: %Schema{ type: :integer, description: "Value in cents in origin currency" } }, required: [:user_id, :from, :to, :from_value], example: %{ "user_id" => "a5965bb5-5228-4d6b-9a1e-07c10b09cd74", "from" => "USD", "to" => "BRL", "from_value" => 250_000 } }) end defmodule ExchangeRate do @moduledoc """ ExchangeRate schema """ OpenApiSpex.schema(%{ title: "Exchange rate operation", description: "Holds exchange rate information for a pair of currencies", type: :object, properties: %{ id: %Schema{ type: :string, description: "Exchange rate request UUID" }, user_id: %Schema{ type: :string, description: "User UUID" }, from: %Schema{ type: :string, description: "Three letter origin currency code" }, to: %Schema{ type: :string, description: "Three letter target currency code" }, from_value: %Schema{ type: :string, description: "Value in origin currency" }, to_value: %Schema{ type: :string, description: "Value in target currency" }, rate: %Schema{ type: :string, description: "Rate used for conversion of origin currency to target currency" }, status: %Schema{ type: :string, description: "Current status of operation", enum: ["pending", "completed", "failed"] }, failure_reason: %Schema{ type: :string, description: "Failure reason of the operation, if any" }, timestamp: %Schema{ type: :string, description: "Request creation datetime in UTC", format: :"date-time" } }, required: [:user_id, :from, :to, :from_value] }) end defmodule ExchangeRatesResponse do @moduledoc """ ExchangeRatesResponse schema """ OpenApiSpex.schema(%{ title: "Exchange rates response", description: "Response schema for a list of exchange rates", type: :array, items: ExchangeRate }) end end
27.196429
92
0.554826
7935a3593760becaadc602cc506be3dc8bafa43c
264
exs
Elixir
priv/repo/migrations/20160702103007_create_user.exs
mijkenator/elapi
55a85edf6fcadd89e390a682404c79bab93282b0
[ "Artistic-2.0" ]
null
null
null
priv/repo/migrations/20160702103007_create_user.exs
mijkenator/elapi
55a85edf6fcadd89e390a682404c79bab93282b0
[ "Artistic-2.0" ]
null
null
null
priv/repo/migrations/20160702103007_create_user.exs
mijkenator/elapi
55a85edf6fcadd89e390a682404c79bab93282b0
[ "Artistic-2.0" ]
null
null
null
defmodule Elapi.Repo.Migrations.CreateUser do use Ecto.Migration def change do create table(:users) do add :email, :string, null: false add :password_hash, :string timestamps end create unique_index(:users, [:email]) end end
17.6
45
0.670455
7935a806ce7791c8ec35ce74c6297556a42aac37
2,487
ex
Elixir
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p5beta1_annotate_file_response.ex
chingor13/elixir-google-api
85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p5beta1_annotate_file_response.ex
chingor13/elixir-google-api
85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b
[ "Apache-2.0" ]
null
null
null
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p5beta1_annotate_file_response.ex
chingor13/elixir-google-api
85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b
[ "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.Vision.V1.Model.GoogleCloudVisionV1p5beta1AnnotateFileResponse do @moduledoc """ Response to a single file annotation request. A file may contain one or more images, which individually have their own responses. ## Attributes * `inputConfig` (*type:* `GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p5beta1InputConfig.t`, *default:* `nil`) - Information about the file for which this response is generated. * `responses` (*type:* `list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p5beta1AnnotateImageResponse.t)`, *default:* `nil`) - Individual responses to images found within the file. * `totalPages` (*type:* `integer()`, *default:* `nil`) - This field gives the total number of pages in the file. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :inputConfig => GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p5beta1InputConfig.t(), :responses => list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p5beta1AnnotateImageResponse.t()), :totalPages => integer() } field(:inputConfig, as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p5beta1InputConfig) field( :responses, as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p5beta1AnnotateImageResponse, type: :list ) field(:totalPages) end defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p5beta1AnnotateFileResponse do def decode(value, options) do GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p5beta1AnnotateFileResponse.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p5beta1AnnotateFileResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.681818
185
0.749899
7935c98cfdc08786961af0c60a2253304c070c90
1,161
ex
Elixir
apps/neoscan_sync/lib/neoscan_sync/token_syncer.ex
decentralisedkev/neo-scan
c8a35a0952e8c46d40365e0ac76bce361ac5e558
[ "MIT" ]
null
null
null
apps/neoscan_sync/lib/neoscan_sync/token_syncer.ex
decentralisedkev/neo-scan
c8a35a0952e8c46d40365e0ac76bce361ac5e558
[ "MIT" ]
null
null
null
apps/neoscan_sync/lib/neoscan_sync/token_syncer.ex
decentralisedkev/neo-scan
c8a35a0952e8c46d40365e0ac76bce361ac5e558
[ "MIT" ]
null
null
null
defmodule NeoscanSync.TokenSyncer do alias Neoscan.Repo alias Neoscan.Asset use GenServer require Logger @update_interval 30_000 def start_link do GenServer.start_link(__MODULE__, :ok, name: __MODULE__) end @impl true def init(:ok) do Process.send_after(self(), :sync, 0) {:ok, nil} end @impl true def handle_info(:sync, state) do Process.send_after(self(), :sync, @update_interval) sync_tokens() {:noreply, state} end def sync_tokens do case NeoscanNode.get_tokens() do {:ok, tokens} -> tokens = Enum.map(tokens, &convert_token_to_asset/1) Repo.insert_all(Asset, tokens, on_conflict: :nothing) _ -> nil end end def convert_token_to_asset(token) do %{ admin: <<0>>, amount: 0.0, name: [%{"lang" => "en", "name" => token.token.name}], owner: <<0>>, precision: token.token.decimals, type: "NEP5", issued: 0.0, block_time: DateTime.utc_now(), contract: <<0>>, transaction_hash: token.contract.hash, inserted_at: DateTime.utc_now(), updated_at: DateTime.utc_now() } end end
20.732143
61
0.620155
7935d5699bf8698096e7360e5e88ccb60b1ed1ff
123
ex
Elixir
elixir/little-elixir-otp/metex/lib/api/weather.ex
marcinbiegun/exercises
36ad942e8d40d6471136326a3f6d09285bbd90aa
[ "MIT" ]
1
2018-12-11T14:09:14.000Z
2018-12-11T14:09:14.000Z
elixir/little-elixir-otp/metex/lib/api/weather.ex
marcinbiegun/exercises
36ad942e8d40d6471136326a3f6d09285bbd90aa
[ "MIT" ]
null
null
null
elixir/little-elixir-otp/metex/lib/api/weather.ex
marcinbiegun/exercises
36ad942e8d40d6471136326a3f6d09285bbd90aa
[ "MIT" ]
null
null
null
defmodule Metex.API.Weather do def temperature_of(location) do Process.sleep(500) "#{location}: 3.5°C" end end
17.571429
33
0.691057
7935d852b8a5b65f9e70def121f419a10e876c63
199
exs
Elixir
priv/repo/migrations/20190522191038_add_speaker_name_to_videos.exs
topherhunt/reassembling-the-line
c6823b3394ee98d9b0149fa3d09448928ac5c0db
[ "MIT" ]
1
2019-04-27T15:39:20.000Z
2019-04-27T15:39:20.000Z
priv/repo/migrations/20190522191038_add_speaker_name_to_videos.exs
topherhunt/reassembling-the-line
c6823b3394ee98d9b0149fa3d09448928ac5c0db
[ "MIT" ]
11
2020-07-16T11:40:53.000Z
2021-08-16T07:03:33.000Z
priv/repo/migrations/20190522191038_add_speaker_name_to_videos.exs
topherhunt/reassembling-the-line
c6823b3394ee98d9b0149fa3d09448928ac5c0db
[ "MIT" ]
null
null
null
defmodule RTL.Repo.Migrations.AddSpeakerNameToVideos do use Ecto.Migration def change do alter table(:videos) do add :speaker_name, :string remove :source_name end end end
18.090909
55
0.713568
7935e72db131b66236c7a072ae56fee4776d4eee
38
ex
Elixir
host_core/lib/host_core/web_assembly.ex
sleipnir/wasmcloud-otp
aef10f2f07257e65c527be6030006aaed2b85ff9
[ "Apache-2.0" ]
null
null
null
host_core/lib/host_core/web_assembly.ex
sleipnir/wasmcloud-otp
aef10f2f07257e65c527be6030006aaed2b85ff9
[ "Apache-2.0" ]
null
null
null
host_core/lib/host_core/web_assembly.ex
sleipnir/wasmcloud-otp
aef10f2f07257e65c527be6030006aaed2b85ff9
[ "Apache-2.0" ]
null
null
null
defmodule HostCore.WebAssembly do end
12.666667
33
0.868421
7935f0aa6ec3e8a4847c7e3c4e025bea4b3a46b7
571
exs
Elixir
config/database.exs
crosscloudci/ex_ci_proxy
906b8d2f51f4324893f205ab647edaf34c271170
[ "Apache-2.0" ]
null
null
null
config/database.exs
crosscloudci/ex_ci_proxy
906b8d2f51f4324893f205ab647edaf34c271170
[ "Apache-2.0" ]
2
2019-12-18T18:08:10.000Z
2020-11-30T23:01:37.000Z
config/database.exs
crosscloudci/ex_ci_proxy
906b8d2f51f4324893f205ab647edaf34c271170
[ "Apache-2.0" ]
null
null
null
use Mix.Config config :ex_ci_proxy, ExCiProxy.Repo, adapter: Ecto.Adapters.Postgres, username: System.get_env("DB_USERNAME"), password: System.get_env("DB_PASSWORD"), database: System.get_env("DB_NAME"), hostname: System.get_env("DB_HOST"), pool_size: System.get_env("DB_POOL_SIZE") # config :guardian, Guardian, # allowed_algos: ["HS256"], # optional # secret_key: System.get_env("JWT_KEY"), # # verify_module: Guardian.JWT, # optional # issuer: System.get_env("JWT_ISSUER") # ttl: { 30, :days }, # allowed_drift: 2000, # verify_issuer: true, # optional
31.722222
46
0.723292
7936223fb2bd413a4372d2adcfa7832671ecfcf2
2,733
ex
Elixir
lib/exred_nodetest.ex
exredorg/exred_nodetest
62f3eb374c6fb77494e07410613f2fbf07e6bbe7
[ "MIT" ]
null
null
null
lib/exred_nodetest.ex
exredorg/exred_nodetest
62f3eb374c6fb77494e07410613f2fbf07e6bbe7
[ "MIT" ]
null
null
null
lib/exred_nodetest.ex
exredorg/exred_nodetest
62f3eb374c6fb77494e07410613f2fbf07e6bbe7
[ "MIT" ]
null
null
null
defmodule Exred.NodeTest do @moduledoc """ A helper module to set up tests for Exred nodes. See example usage below. The `module` and `config` arguments can be specified either on the `use` line or in the `start_node` call. `module is the node module that will be tested `config` is the config overrides to start the node with (overrides the config in the actual node being tested) `start_node/0` will start the node. It will add the `:pid` and `:node` keys to the test context. `:pid` is the process id of the running node GenServer `:node` is the node attributes map: %{ module :: atom, id :: atom name :: string, category :: string, info :: string, config :: map, ui_attributes :: map } ## Example (this would go into a test file) defmodule Exred.Node.MynodeTest do use ExUnit.Case use Exred.NodeTest, module: Exred.Node.Mynode setup_all do start_node() end test "runnnig", context do assert is_pid(context.pid) end end """ defmacro __using__(opts) do quote do require Logger def start_node(), do: start_node(Keyword.get(unquote(opts), :module), Keyword.get(unquote(opts), :config, %{})) def start_node(module), do: start_node(module, %{}) def start_node(module, config) do # figure out the node attributes we need to start the module up with # (merge config into the default attributes) modattrs = module.attributes() node_attributes = %{modattrs | config: Map.merge(modattrs.config, config)} assert is_map(node_attributes) node = node_attributes |> Map.put(:module, module) |> Map.put(:id, module) if node.category == "daemon" do # start child processes child_specs = node.module.daemon_child_specs(node.config) assert is_list(child_specs) log("Starting #{length(child_specs)} child process(es)") child_specs |> Enum.each(&start_supervised!/1) end # create a dummy event sending function send_event_fun = fn event, payload -> log("EVENT: #{inspect(event)} | PAYLOAD: #{inspect(payload)}") end # start the node start_args = [node.id, node.config, send_event_fun] child_spec = Supervisor.child_spec({node.module, start_args}, id: node.id) pid = start_supervised!(child_spec) [pid: pid, node: node] end def log(msg) do Logger.info("TEST OUTPUT: " <> msg) end end end end
28.175258
112
0.594951
79362e0b697b7666d0ee9f9fd4ea6e6156ba89e9
1,107
exs
Elixir
test/krill_execute_test.exs
eksperimental/krill
9db9b917f4bde12626b6a72f4fb7283b7dd701e9
[ "MIT" ]
null
null
null
test/krill_execute_test.exs
eksperimental/krill
9db9b917f4bde12626b6a72f4fb7283b7dd701e9
[ "MIT" ]
null
null
null
test/krill_execute_test.exs
eksperimental/krill
9db9b917f4bde12626b6a72f4fb7283b7dd701e9
[ "MIT" ]
null
null
null
defmodule Krill_ExecuteTest do use ExUnit.Case, async: false require Command.Sample require Logger import Krill import ExUnit.CaptureIO setup do conf = local_config(:sample) {:ok, conf: conf} end test "Mix.Tasks.Krill.Execute.run(:sample)", %{conf: conf} do assert capture_io(fn -> Command.Sample.run(conf) end) == capture_io(fn -> Mix.Tasks.Krill.Execute.run(["sample"]) end) assert capture_io(:stderr, fn -> Command.Sample.run(conf) end) == capture_io(:stderr, fn -> Mix.Tasks.Krill.Execute.run(["sample"]) end) end test "Krill.execute one task", %{conf: conf} do assert capture_io(fn -> Command.Sample.run(conf) end) == capture_io(fn -> execute(["sample"]) end) assert capture_io(:stderr, fn -> Command.Sample.run(conf) end) == capture_io(:stderr, fn -> execute(["sample"]) end) end #test "Krill.execute :config" do # assert execute([":config"]) == {:ok, %{}} # assert execute([":all"]) == {:ok, %{}} # assert execute(["sample"]) == {:ok, %{}} #end end
23.0625
63
0.598013
7936603715696391c6d786d881d4b041d8563600
696
ex
Elixir
test/support/live_views/live_in_component.ex
gaslight/live_element
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
[ "MIT" ]
null
null
null
test/support/live_views/live_in_component.ex
gaslight/live_element
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
[ "MIT" ]
null
null
null
test/support/live_views/live_in_component.ex
gaslight/live_element
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
[ "MIT" ]
null
null
null
defmodule LiveElementTest.LiveInComponent.Root do use LiveElement def mount(_params, _session, socket) do {:ok, socket} end def render(assigns) do ~H"<%= live_component LiveElementTest.LiveInComponent.Component, id: :nested_component %>" end end defmodule LiveElementTest.LiveInComponent.Component do use Phoenix.LiveComponent def render(assigns) do ~H""" <div> <%= live_render @socket, LiveElementTest.LiveInComponent.Live, id: :nested_live %>" </div> """ end end defmodule LiveElementTest.LiveInComponent.Live do use LiveElement def mount(_params, _session, socket) do {:ok, socket} end def render(assigns) do ~H"" end end
19.333333
94
0.70546
79366e1f6373f3a4c980af7d4938e49f1bc6ea07
12,451
ex
Elixir
lib/oli_web/live/projects/visibility.ex
ChristianMurphy/oli-torus
ffeee4996b66b7c6c6eb3e0082d030b8cc6cea97
[ "MIT" ]
null
null
null
lib/oli_web/live/projects/visibility.ex
ChristianMurphy/oli-torus
ffeee4996b66b7c6c6eb3e0082d030b8cc6cea97
[ "MIT" ]
null
null
null
lib/oli_web/live/projects/visibility.ex
ChristianMurphy/oli-torus
ffeee4996b66b7c6c6eb3e0082d030b8cc6cea97
[ "MIT" ]
null
null
null
defmodule OliWeb.Projects.VisibilityLive do use Phoenix.LiveView alias Oli.Authoring.Course alias Oli.Accounts alias Oli.Institutions alias Oli.Publishing use Phoenix.HTML def mount( _params, %{ "project_slug" => project_slug }, socket ) do project = Course.get_project_by_slug(project_slug) project_visibilities = Publishing.get_all_project_visibilities(project.id) {:ok, assign(socket, project: project, project_visibilities: project_visibilities, user_emails: [], institution_names: [], tab: :users )} end def render(assigns) do ~L""" <div class="card"> <div class="card-body "> <div class="row "> <div class="col-sm-8 p-3"> <h4 class="card-title">Course builder visibility</h4> </div> </div> <div class="row"> <div class="col-sm-8"> <div class="form-check form-switch"> <form phx-change="option" id="visibility_option"> <div class="form-group"> <%= radio_button :visibility, :option, "authors", class: "form-check-input", checked: if @project.visibility == :authors, do: true, else: false %> <%= label :visibility_option, "Only direct authors to this course", class: "form-check-label" %> </div> <div class="form-group"> <%= radio_button :visibility, :option, "global", class: "form-check-input", checked: if @project.visibility == :global, do: true, else: false %> <%= label :visibility_option, "Any user with instructor access", class: "form-check-label" %> </div> <div class="form-group"> <%= radio_button :visibility, :option, "selected", class: "form-check-input", checked: if @project.visibility == :selected, do: true, else: false %> <%= label :visibility_option, "Only the list of selected users or institutions below", class: "form-check-label" %> </div> </form> </div> </div> </div> <%= if @project.visibility == :selected do %> <div class="row"> <div class="col-sm-8 text-center"> <p class="card-text">Below is a list of users and/or institutions that have been granted permission to create course instances in their LMS using this project</p> </div> </div> <div class="row"> <div class="col-sm-8"> <ul class="nav nav-tabs"> <li class="nav-item"> <a phx-click="users_tab" class="nav-link <%= if @tab == :users, do: "active" %>" data-toggle="tab" href="#users">Users</a> </li> <li class="nav-item"> <a phx-click="institutions_tab" class="nav-link <%= if @tab == :institutions, do: "active" %>" data-toggle="tab" href="#institutions">Institutions</a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div id="users" class="container tab-pane <%= if @tab == :users, do: "active", else: "fade" %>"> <br> <h3>Users</h3> <div class="card"> <div> <form phx-change="search" class="form-inline form-grow"> <%= text_input :search_field, :query, placeholder: "Search for users by email here", class: "form-control form-control-sm mb-2 mb-sm-0 title container-fluid flex-fill", autofocus: true, "phx-debounce": "300" %> <%= hidden_input :search_field, :entity, value: "instructors" %> </form> </div> <div class="row justify-content-center"> <%= if !Enum.empty?(@user_emails) do %> <div class="flex-fill"> <p>Select from the list below and submit</p> <form phx-submit="selected_email" id="user_submit"> <%= multiple_select :multi, :emails, @user_emails, class: "form-control w-100" %> <%= submit "Submit", class: "btn btn-primary" %> </form> </div> <% end %> <div class="flex-fill"> <ul class="list-group list-group-flush"> <%= for v <- @project_visibilities do %> <%= if v.author != nil do %> <li class="list-group-item"> <div class="d-flex"> <div class="flex-fill"><%= v.author.email %> </div> <div> <button id="delete_<%= v.visibility.id %>" phx-click="delete_visibility" phx-value-id="<%= v.visibility.id %>" data-backdrop="static" data-keyboard="false" class="ml-1 btn btn-sm btn-danger"> <i class="fas fa-trash-alt fa-lg"></i> </button></div> </div> </li> <% end %> <% end %> </ul> </div> </div> </div> </div> <div id="institutions" class="container tab-pane <%= if @tab == :institutions, do: "active", else: "fade" %>"><br> <h3>Institutions</h3> <div class="card"> <div> <form phx-change="search" class="form-inline form-grow"> <%= text_input :search_field, :query, placeholder: "Search for institutions by name here", class: "form-control form-control-sm mb-2 mb-sm-0 title container-fluid flex-fill", autofocus: true, "phx-debounce": "300" %> <%= hidden_input :search_field, :entity, value: "institution" %> </form> </div> <div class="row justify-content-center"> <%= if !Enum.empty?(@institution_names) do %> <div class="flex-fill"> <p>Select from the list below and submit</p> <form phx-submit="selected_institution" id="institutions_submit"> <%= multiple_select :multi, :institutions, @institution_names , class: "form-control w-100" %> <%= submit "Submit", class: "btn btn-primary" %> </form> </div> <% end %> <div class="flex-fill"> <ul class="list-group list-group-flush"> <%= for v <- @project_visibilities do %> <%= if v.institution != nil do %> <li class="list-group-item"> <div class="d-flex"> <div class="flex-fill"><%= v.institution.name %></div> <div> <button id="delete_<%= v.visibility.id %>" phx-click="delete_visibility" phx-value-id="<%= v.visibility.id %>" data-backdrop="static" data-keyboard="false" class="ml-1 btn btn-sm btn-danger"> <i class="fas fa-trash-alt fa-lg"></i> </button></div> </div> </li> <% end %> <% end %> </ul> </div> </div> </div> </div> </div> </div> </div> <% end %> </div> </div> """ end def handle_event("search", %{"search_field" => %{"entity" => entity, "query" => query}}, socket) do case entity do "instructors" -> list = if String.length(query) > 1 do Accounts.search_authors_matching(query) else [] end list = Enum.map(list, fn a -> {a.email, a.id} end) |> Enum.sort_by(& &1) list = list |> Enum.filter(fn e -> {_, id} = e f = Enum.find(socket.assigns.project_visibilities, fn x -> x.author != nil && x.author.id == id end) if f == nil do true else false end end) {:noreply, assign(socket, :user_emails, list)} "institution" -> list = if String.length(query) > 1 do Institutions.search_institutions_matching(query) else [] end list = Enum.map(list, fn a -> {a.name, a.id} end) |> Enum.sort_by(& &1) list = list |> Enum.filter(fn e -> {_, id} = e f = Enum.find(socket.assigns.project_visibilities, fn x -> x.institution != nil && x.institution.id == id end) if f == nil do true else false end end) {:noreply, assign(socket, :institution_names, list)} end end def handle_event("option", %{"visibility" => %{"option" => option}}, socket) do {:ok, project} = Course.update_project(socket.assigns.project, %{visibility: option}) {:noreply, assign(socket, :project, project)} end def handle_event("selected_email", %{"multi" => %{"emails" => emails}}, socket) do emails |> Enum.each(fn e -> {id, _} = Integer.parse(e) f = Enum.find(socket.assigns.project_visibilities, fn x -> x.author != nil && x.author.id == id end) if f == nil do Publishing.insert_visibility(%{project_id: socket.assigns.project.id, author_id: id}) end end) project_visibilities = Publishing.get_all_project_visibilities(socket.assigns.project.id) {:noreply, assign(socket, project_visibilities: project_visibilities, user_emails: [])} end def handle_event( "selected_institution", %{"multi" => %{"institutions" => institutions}}, socket ) do institutions |> Enum.each(fn e -> {id, _} = Integer.parse(e) f = Enum.find(socket.assigns.project_visibilities, fn x -> x.institution != nil && x.institution.id == id end) if f == nil do Publishing.insert_visibility(%{project_id: socket.assigns.project.id, institution_id: id}) end end) project_visibilities = Publishing.get_all_project_visibilities(socket.assigns.project.id) {:noreply, assign(socket, project_visibilities: project_visibilities, institution_names: [])} end def handle_event("users_tab", _option, socket) do {:noreply, assign(socket, :tab, :users)} end def handle_event("institutions_tab", _option, socket) do {:noreply, assign(socket, :tab, :institutions)} end def handle_event("delete_visibility", %{"id" => visibility_id}, socket) do {id, _} = Integer.parse(visibility_id) v = Enum.find(socket.assigns.project_visibilities, fn x -> x.visibility != nil && x.visibility.id == id end) if v != nil do Publishing.remove_visibility(v.visibility) end project_visibilities = Publishing.get_all_project_visibilities(socket.assigns.project.id) {:noreply, assign(socket, project_visibilities: project_visibilities)} end end
39.652866
167
0.464621
7936a646295c5921fdf60fe1cc8052bebd952db3
1,749
ex
Elixir
lib/bandit/initial_handler.ex
moogle19/bandit
610aebaac2ddf76d53faac109b07e519727affb6
[ "MIT" ]
null
null
null
lib/bandit/initial_handler.ex
moogle19/bandit
610aebaac2ddf76d53faac109b07e519727affb6
[ "MIT" ]
null
null
null
lib/bandit/initial_handler.ex
moogle19/bandit
610aebaac2ddf76d53faac109b07e519727affb6
[ "MIT" ]
null
null
null
defmodule Bandit.InitialHandler do @moduledoc false # The initial protocol implementation used for all connections. Switches to a # specific protocol implementation based on configuration, ALPN negotiation, and # line heuristics. use ThousandIsland.Handler # Attempts to guess the protocol in use, returning the applicable next handler and any # data consumed in the course of guessing which must be processed by the actual protocol handler @impl ThousandIsland.Handler def handle_connection(socket, state) do {alpn_protocol(socket), sniff_wire(socket, state.read_timeout)} |> case do {Bandit.HTTP2.Handler, Bandit.HTTP2.Handler} -> {:switch, Bandit.HTTP2.Handler, state} {Bandit.HTTP1.Handler, {:no_match, data}} -> {:switch, Bandit.HTTP1.Handler, data, state} {:no_match, Bandit.HTTP2.Handler} -> {:switch, Bandit.HTTP2.Handler, state} {:no_match, {:no_match, data}} -> {:switch, Bandit.HTTP1.Handler, data, state} _other -> {:error, "Could not determine a protocol", state} end end # Returns the protocol as negotiated via ALPN, if applicable defp alpn_protocol(socket) do case ThousandIsland.Socket.negotiated_protocol(socket) do {:ok, "h2"} -> Bandit.HTTP2.Handler {:ok, "http/1.1"} -> Bandit.HTTP1.Handler _ -> :no_match end end # Returns the protocol as suggested by received data, if possible defp sniff_wire(socket, read_timeout) do case ThousandIsland.Socket.recv(socket, 24, read_timeout) do {:ok, "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"} -> Bandit.HTTP2.Handler {:ok, data} -> {:no_match, data} {:error, error} -> {:error, error} end end end
31.8
98
0.671812
7936aa8eccf19ce2dd71e2e269031719b3329cc7
955
exs
Elixir
test/acceptance/html/links_images/simple_pure_links_test.exs
manuel-rubio/earmark
d747d73d31e8b8fa39389b01fc67cc53d946b707
[ "Apache-1.1" ]
734
2015-01-05T19:08:00.000Z
2022-03-28T14:04:21.000Z
test/acceptance/html/links_images/simple_pure_links_test.exs
manuel-rubio/earmark
d747d73d31e8b8fa39389b01fc67cc53d946b707
[ "Apache-1.1" ]
343
2015-01-01T04:56:57.000Z
2022-02-15T11:00:57.000Z
test/acceptance/html/links_images/simple_pure_links_test.exs
manuel-rubio/earmark
d747d73d31e8b8fa39389b01fc67cc53d946b707
[ "Apache-1.1" ]
169
2015-02-26T15:18:05.000Z
2022-03-18T08:00:42.000Z
defmodule Acceptance.Html.LinksImages.SimplePureLinksTest do use Support.AcceptanceTestCase describe "simple pure links not yet enabled" do test "old behavior" do markdown = "https://github.com/pragdave/earmark" html = "<p>\nhttps://github.com/pragdave/earmark</p>\n" messages = [] assert as_html(markdown, pure_links: false) == {:ok, html, messages} end end describe "enabled pure links" do test "two in a row" do url1 = "https://github.com/pragdave/earmark" url2 = "https://github.com/RobertDober/extractly" markdown = "#{url1} #{url2}" html = "<p>\n<a href=\"https://github.com/pragdave/earmark\">https://github.com/pragdave/earmark</a> <a href=\"https://github.com/RobertDober/extractly\">https://github.com/RobertDober/extractly</a></p>\n" messages = [] assert as_html(markdown) == {:ok, html, messages} end end end # SPDX-License-Identifier: Apache-2.0
34.107143
212
0.660733
7936add5c7fe155dfb68472ced7ed9d9e56139bf
2,792
ex
Elixir
apps/rig_inbound_gateway/lib/rig_inbound_gateway/request_logger/kafka.ex
maxglassie/reactive-interaction-gateway
36b68fc75c71b9b4c3b6bd70fb11900c67172137
[ "Apache-2.0" ]
null
null
null
apps/rig_inbound_gateway/lib/rig_inbound_gateway/request_logger/kafka.ex
maxglassie/reactive-interaction-gateway
36b68fc75c71b9b4c3b6bd70fb11900c67172137
[ "Apache-2.0" ]
null
null
null
apps/rig_inbound_gateway/lib/rig_inbound_gateway/request_logger/kafka.ex
maxglassie/reactive-interaction-gateway
36b68fc75c71b9b4c3b6bd70fb11900c67172137
[ "Apache-2.0" ]
null
null
null
defmodule RigInboundGateway.RequestLogger.Kafka do @moduledoc """ Kafka request logger implementation. """ use Rig.Config, [:log_topic] require Logger alias Rig.Kafka, as: RigKafka alias RigAuth.Jwt.Utils, as: Jwt alias UUID @behaviour RigInboundGateway.RequestLogger @impl RigInboundGateway.RequestLogger @spec log_call(Proxy.endpoint(), Proxy.api_definition(), %Plug.Conn{}) :: :ok def log_call( %{"not_secured" => false} = endpoint, %{"auth_type" => "jwt"} = api_definition, conn ) do claims = extract_claims!(conn) username = Map.fetch!(claims, "username") jti = case Map.get(claims, "jti") do nil -> Logger.warn("jti not found in claims (#{inspect(claims)})") nil jti -> jti end message = %{ id: UUID.uuid4(), username: username, jti: jti, type: "PROXY_API_CALL", version: "1.0", timestamp: Timex.now() |> Timex.to_unix(), level: 0, payload: %{ endpoint: inspect(endpoint), api_definition: inspect(api_definition), request_path: conn.request_path, remote_ip: conn.remote_ip |> format_ip } } message_json = message |> Poison.encode!() conf = config() # If topic does not exist, it will be created automatically, provided the server is # configured that way. However, this call then returns with {:error, :LeaderNotAvailable}, # as at that point there won't be a partition leader yet. RigKafka.produce(conf.log_topic, _key = username, _plaintext = message_json) rescue err -> case err do %KeyError{key: "username", term: claims} -> Logger.warn(""" A username is required for publishing to the right Kafka topic, \ but no such field is found in the given claims: #{inspect(claims)} """) _ -> Logger.error(""" Failed to log API call: #{inspect(err)} endpoint=#{inspect(endpoint)} api_definition=#{inspect(api_definition)} """) end {:error, err} end def log_call(_endpoint, _api_definition, _conn) do # Unauthenticated calls are not sent to Kafka. :ok end @spec extract_claims!(%Plug.Conn{}) :: Jwt.claims() defp extract_claims!(conn) do # we assume there is exactly one valid token: [token] = conn |> Plug.Conn.get_req_header("authorization") |> Stream.filter(&Jwt.valid?/1) |> Enum.take(1) {:ok, claims} = Jwt.decode(token) claims end @spec format_ip({integer, integer, integer, integer}) :: String.t() defp format_ip(ip_tuple) do ip_tuple |> Tuple.to_list() |> Enum.map(&Integer.to_string/1) |> Enum.join(".") end end
27.372549
94
0.608166
7937137b63b0f3adbf4c6e6b30cd939fc8af0b0e
1,624
ex
Elixir
installer/phoenix/templates/phx_api/password_reset_controller.ex
elixircnx/sanction
5b270fd6eef980d37c06429271f64ec14e0f622d
[ "BSD-3-Clause" ]
130
2016-06-21T07:58:46.000Z
2022-01-01T21:45:23.000Z
installer/phoenix/templates/phx_api/password_reset_controller.ex
elixircnx/sanction
5b270fd6eef980d37c06429271f64ec14e0f622d
[ "BSD-3-Clause" ]
50
2016-06-29T16:01:42.000Z
2019-08-07T21:33:49.000Z
installer/phoenix/templates/phx_api/password_reset_controller.ex
elixircnx/sanction
5b270fd6eef980d37c06429271f64ec14e0f622d
[ "BSD-3-Clause" ]
20
2016-07-02T11:37:33.000Z
2018-10-26T19:12:41.000Z
defmodule <%= base %>.PasswordResetController do use <%= base %>.Web, :controller alias <%= base %>.{Mailer, User} plug Openmaize.ResetPassword, [mail_function: &Mailer.receipt_confirm/1] when action in [:update] def create(conn, %{"password_reset" => %{"email" => email} = user_params}) do {key, link} = Openmaize.ConfirmEmail.gen_token_link(email) send_token(conn, Repo.get_by(User, email: email), user_params, {key, email, link}) end def update(%Plug.Conn{private: %{openmaize_error: message}} = conn, _) do conn |> put_status(:unprocessable_entity) |> render(<%= base %>.PasswordResetView, "error.json", error: message) end def update(%Plug.Conn{private: %{openmaize_info: message}} = conn, _) do render(conn, <%= base %>.PasswordResetView, "info.json", %{info: message}) end defp send_token(conn, nil, _, _) do conn |> put_status(:unprocessable_entity) |> render(<%= base %>.ChangesetView, "error.json") end defp send_token(conn, user, user_params, {key, email, link}) do changeset = User.reset_changeset(Repo.get_by(User, email: email), user_params, key) case Repo.update(changeset) do {:ok, _user} -> Mailer.ask_reset(email, link) message = "Check your inbox for instructions on how to reset your password" conn |> put_status(:created) |> render(<%= base %>.PasswordResetView, "info.json", %{info: message}) {:error, changeset} -> conn |> put_status(:unprocessable_entity) |> render(<%= base %>.ChangesetView, "error.json", changeset: changeset) end end end
36.909091
87
0.650862
793721649ac59092aab768df46bfc31790c6d17e
1,082
exs
Elixir
test/two_argument_test.exs
ludwikbukowski/decorator
697c688bc89961d738939d7771f7eeea6251eea1
[ "MIT" ]
null
null
null
test/two_argument_test.exs
ludwikbukowski/decorator
697c688bc89961d738939d7771f7eeea6251eea1
[ "MIT" ]
null
null
null
test/two_argument_test.exs
ludwikbukowski/decorator
697c688bc89961d738939d7771f7eeea6251eea1
[ "MIT" ]
null
null
null
# two arguments defmodule DecoratorTest.Fixture.TwoArgumentDecorator do use Decorator.Define, [two: 2] def two(one, two, body, _context) do quote do {unquote(one), unquote(two), unquote(body)} end end end defmodule DecoratorTest.Fixture.MyTwoFunctionTestModule do use DecoratorTest.Fixture.TwoArgumentDecorator @decorate two(1, 2) def result(a) do a end end defmodule DecoratorTest.Fixture.FunctionDocTestModule do use DecoratorTest.Fixture.TwoArgumentDecorator @doc "result function which does some things" def result(a) do a end @doc "result function which does some things" @decorate two(1, 2) def result2(a) do a end end defmodule DecoratorTest.TwoArgument do use ExUnit.Case alias DecoratorTest.Fixture.{ MyTwoFunctionTestModule, FunctionDocTestModule } test "Two arguments" do assert {1, 2, 3} == MyTwoFunctionTestModule.result(3) end test "Functions with module doc" do assert 3 == FunctionDocTestModule.result(3) assert {1, 2, 3} == FunctionDocTestModule.result2(3) end end
20.415094
58
0.727357
79372fde5d0fea22567ae43793c5beebca249e8e
1,459
exs
Elixir
config/config.exs
rerb/ueberauth_example
1a08d578dfeaca5b77d213b1abbc53913f2a3b37
[ "MIT" ]
210
2015-11-19T01:54:04.000Z
2021-11-14T18:14:57.000Z
config/config.exs
rerb/ueberauth_example
1a08d578dfeaca5b77d213b1abbc53913f2a3b37
[ "MIT" ]
63
2015-11-19T00:08:29.000Z
2021-09-07T03:04:36.000Z
config/config.exs
rerb/ueberauth_example
1a08d578dfeaca5b77d213b1abbc53913f2a3b37
[ "MIT" ]
102
2015-11-20T11:47:12.000Z
2022-03-23T11:10:38.000Z
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. # # This configuration file is loaded before any dependency and # is restricted to this project. # General application configuration import Config # Configures the endpoint config :ueberauth_example, UeberauthExampleWeb.Endpoint, url: [host: "localhost"], secret_key_base: "cmFHOAeb4fOkx/XBcXe0pnKNfgcuicWd0eVrvIb8vZlEQRb1nnvaWcs7dTABVcdN", render_errors: [view: UeberauthExampleWeb.ErrorView, accepts: ~w(html json), layout: false], pubsub_server: UeberauthExample.PubSub # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:request_id] # Use Jason for JSON parsing in Phoenix config :phoenix, :json_library, Jason config :ueberauth, Ueberauth, providers: [ facebook: {Ueberauth.Strategy.Facebook, []}, github: {Ueberauth.Strategy.Github, [default_scope: "user:email"]}, google: {Ueberauth.Strategy.Google, []}, identity: {Ueberauth.Strategy.Identity, [ callback_methods: ["POST"], uid_field: :username, nickname_field: :username ]}, slack: {Ueberauth.Strategy.Slack, []}, twitter: {Ueberauth.Strategy.Twitter, []} ] # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. import_config "#{Mix.env()}.exs"
33.159091
94
0.730637
7937453d3fab57a090da13598f83fc0d9189100f
5,548
ex
Elixir
lib/bson/types.ex
Talkdesk/mongodb
d6c240c4faf2f73d408b24a028e96f0b30fcb031
[ "Apache-2.0" ]
null
null
null
lib/bson/types.ex
Talkdesk/mongodb
d6c240c4faf2f73d408b24a028e96f0b30fcb031
[ "Apache-2.0" ]
null
null
null
lib/bson/types.ex
Talkdesk/mongodb
d6c240c4faf2f73d408b24a028e96f0b30fcb031
[ "Apache-2.0" ]
null
null
null
defmodule BSON.Binary do @moduledoc """ Represents BSON binary type """ defstruct [binary: nil, subtype: :generic] defimpl Inspect do def inspect(%BSON.Binary{binary: value, subtype: :generic}, _opts) do "#BSON.Binary<#{Base.encode16(value, case: :lower)}>" end def inspect(%BSON.Binary{binary: value, subtype: subtype}, _opts) do "#BSON.Binary<#{Base.encode16(value, case: :lower)}, #{subtype}>" end end end defmodule BSON.ObjectId do @moduledoc """ Represents BSON ObjectId type """ defstruct [:value] @doc """ Creates a new ObjectId from the consisting parts """ def new(machine_id, proc_id, secs, counter) do value = <<secs :: unsigned-big-32, machine_id :: unsigned-big-24, proc_id :: unsigned-big-16, counter :: unsigned-big-24>> %BSON.ObjectId{value: value} end @doc """ Converts string representation of ObjectId to a BSON.ObjectId struct """ def decode!(<< c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23 >>) do << d(c0)::4, d(c1)::4, d(c2)::4, d(c3)::4, d(c4)::4, d(c5)::4, d(c6)::4, d(c7)::4, d(c8)::4, d(c9)::4, d(c10)::4, d(c11)::4, d(c12)::4, d(c13)::4, d(c14)::4, d(c15)::4, d(c16)::4, d(c17)::4, d(c18)::4, d(c19)::4, d(c20)::4, d(c21)::4, d(c22)::4, d(c23)::4 >> catch :throw, :error -> raise ArgumentError else value -> %BSON.ObjectId{value: value} end @doc """ Converts BSON.ObjectId struct to a string representation """ def encode!(%BSON.ObjectId{value: value}), do: do_encode(value) def do_encode(<< l0::4, h0::4, l1::4, h1::4, l2::4, h2::4, l3::4, h3::4, l4::4, h4::4, l5::4, h5::4, l6::4, h6::4, l7::4, h7::4, l8::4, h8::4, l9::4, h9::4, l10::4, h10::4, l11::4, h11::4 >>) do << e(l0), e(h0), e(l1), e(h1), e(l2), e(h2), e(l3), e(h3), e(l4), e(h4), e(l5), e(h5), e(l6), e(h6), e(l7), e(h7), e(l8), e(h8), e(l9), e(h9), e(l10), e(h10), e(l11), e(h11) >> catch :throw, :error -> raise ArgumentError else value -> value end @compile {:inline, :d, 1} @compile {:inline, :e, 1} @chars Enum.concat(?0..?9, ?a..?f) for {char, int} <- Enum.with_index(@chars) do defp d(unquote(char)), do: unquote(int) defp e(unquote(int)), do: unquote(char) end for {char, int} <- Enum.with_index(?A..?F) do defp d(unquote(char)), do: unquote(int) end defp d(_), do: throw :error defp e(_), do: throw :error defimpl Inspect do def inspect(objectid, _opts) do encoded = BSON.ObjectId.encode!(objectid) "#BSON.ObjectId<#{encoded}>" end end end defmodule BSON.DateTime do @moduledoc """ Represents BSON DateTime type """ defstruct [:utc] @epoch :calendar.datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}}) @doc """ Converts `BSON.DateTime` into a `{{year, month, day}, {hour, min, sec, usec}}` tuple. """ def to_datetime(%BSON.DateTime{utc: utc}) do seconds = div(utc, 1000) + @epoch usec = rem(utc, 1000) * 1000 {date, {hour, min, sec}} = :calendar.gregorian_seconds_to_datetime(seconds) {date, {hour, min, sec, usec}} end @doc """ Converts `{{year, month, day}, {hour, min, sec, usec}}` into a `BSON.DateTime` struct. """ def from_datetime({date, {hour, min, sec, usec}}) do greg_secs = :calendar.datetime_to_gregorian_seconds({date, {hour, min, sec}}) epoch_secs = greg_secs - @epoch %BSON.DateTime{utc: epoch_secs * 1000 + div(usec, 1000)} end @doc """ Converts `BSON.DateTime` to its ISO8601 representation """ def to_iso8601(%BSON.DateTime{} = datetime) do {{year, month, day}, {hour, min, sec, usec}} = to_datetime(datetime) str = zero_pad(year, 4) <> "-" <> zero_pad(month, 2) <> "-" <> zero_pad(day, 2) <> "T" <> zero_pad(hour, 2) <> ":" <> zero_pad(min, 2) <> ":" <> zero_pad(sec, 2) case usec do 0 -> str <> "Z" _ -> str <> "." <> zero_pad(usec, 6) <> "Z" end end defp zero_pad(val, count) do num = Integer.to_string(val) :binary.copy("0", count - byte_size(num)) <> num end defimpl Inspect do def inspect(%BSON.DateTime{} = datetime, _opts) do "#BSON.DateTime<#{BSON.DateTime.to_iso8601(datetime)}>" end end end defmodule BSON.Regex do @moduledoc """ Represents BSON Regex type """ defstruct [:pattern, :options] defimpl Inspect do def inspect(%BSON.Regex{pattern: pattern, options: nil}, _opts) do "#BSON.Regex<#{inspect pattern}>" end def inspect(%BSON.Regex{pattern: pattern, options: options}, _opts) do "#BSON.Regex<#{inspect pattern}, #{inspect options}>" end end end defmodule BSON.JavaScript do @moduledoc """ Represents BSON JavaScript (with and without scope) types """ defstruct [:code, :scope] defimpl Inspect do def inspect(%BSON.JavaScript{code: code, scope: nil}, _opts) do "#BSON.JavaScript<#{inspect code}>" end def inspect(%BSON.JavaScript{code: code, scope: scope}, _opts) do "#BSON.JavaScript<#{inspect code}, #{inspect(scope)}>" end end end defmodule BSON.Timestamp do @moduledoc """ Represents BSON Timestamp type """ defstruct [:value] defimpl Inspect do def inspect(%BSON.Timestamp{value: value}, _opts) do "#BSON.Timestamp<#{value}>" end end end
26.673077
93
0.580029
793761c52622ae42312b2967c2d2f077390860f4
923
ex
Elixir
test/support/channel_case.ex
joshnuss/phoenix-billing-demo
f72f4de6c975624b2b8b6c189126df32992b5936
[ "MIT" ]
62
2015-09-19T02:06:39.000Z
2021-03-15T04:35:50.000Z
test/support/channel_case.ex
joshnuss/phoenix-billing-demo
f72f4de6c975624b2b8b6c189126df32992b5936
[ "MIT" ]
4
2015-09-23T03:42:23.000Z
2017-01-14T18:03:20.000Z
test/support/channel_case.ex
joshnuss/phoenix-billing-demo
f72f4de6c975624b2b8b6c189126df32992b5936
[ "MIT" ]
8
2015-09-19T16:14:40.000Z
2020-10-28T21:38:18.000Z
defmodule Store.ChannelCase do @moduledoc """ This module defines the test case to be used by channel tests. Such tests rely on `Phoenix.ChannelTest` and also imports other functionality to make it easier to build and query models. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with channels use Phoenix.ChannelTest alias Store.Repo import Ecto.Model import Ecto.Query, only: [from: 2] # The default endpoint for testing @endpoint Store.Endpoint end end setup tags do unless tags[:async] do Ecto.Adapters.SQL.restart_test_transaction(Store.Repo, []) end :ok end end
22.512195
64
0.700975
79378c7078a14873e3f7d8b8e48d8ac1aaa71721
6,214
ex
Elixir
clients/monitoring/lib/google_api/monitoring/v3/model/metric_threshold.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
1
2021-10-01T09:20:41.000Z
2021-10-01T09:20:41.000Z
clients/monitoring/lib/google_api/monitoring/v3/model/metric_threshold.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/monitoring/lib/google_api/monitoring/v3/model/metric_threshold.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Monitoring.V3.Model.MetricThreshold do @moduledoc """ A condition type that compares a collection of time series against a threshold. ## Attributes * `aggregations` (*type:* `list(GoogleApi.Monitoring.V3.Model.Aggregation.t)`, *default:* `nil`) - Specifies the alignment of data points in individual time series as well as how to combine the retrieved time series together (such as when aggregating multiple streams on each resource to a single stream for each resource or when aggregating streams across all members of a group of resrouces). Multiple aggregations are applied in the order specified.This field is similar to the one in the ListTimeSeries request (https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list). It is advisable to use the ListTimeSeries method when debugging this field. * `comparison` (*type:* `String.t`, *default:* `nil`) - The comparison to apply between the time series (indicated by filter and aggregation) and the threshold (indicated by threshold_value). The comparison is applied on each time series, with the time series on the left-hand side and the threshold on the right-hand side.Only COMPARISON_LT and COMPARISON_GT are supported currently. * `denominatorAggregations` (*type:* `list(GoogleApi.Monitoring.V3.Model.Aggregation.t)`, *default:* `nil`) - Specifies the alignment of data points in individual time series selected by denominatorFilter as well as how to combine the retrieved time series together (such as when aggregating multiple streams on each resource to a single stream for each resource or when aggregating streams across all members of a group of resources).When computing ratios, the aggregations and denominator_aggregations fields must use the same alignment period and produce time series that have the same periodicity and labels. * `denominatorFilter` (*type:* `String.t`, *default:* `nil`) - A filter (https://cloud.google.com/monitoring/api/v3/filters) that identifies a time series that should be used as the denominator of a ratio that will be compared with the threshold. If a denominator_filter is specified, the time series specified by the filter field will be used as the numerator.The filter must specify the metric type and optionally may contain restrictions on resource type, resource labels, and metric labels. This field may not exceed 2048 Unicode characters in length. * `duration` (*type:* `String.t`, *default:* `nil`) - The amount of time that a time series must violate the threshold to be considered failing. Currently, only values that are a multiple of a minute--e.g., 0, 60, 120, or 300 seconds--are supported. If an invalid value is given, an error will be returned. When choosing a duration, it is useful to keep in mind the frequency of the underlying time series data (which may also be affected by any alignments specified in the aggregations field); a good duration is long enough so that a single outlier does not generate spurious alerts, but short enough that unhealthy states are detected and alerted on quickly. * `filter` (*type:* `String.t`, *default:* `nil`) - Required. A filter (https://cloud.google.com/monitoring/api/v3/filters) that identifies which time series should be compared with the threshold.The filter is similar to the one that is specified in the ListTimeSeries request (https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list) (that call is useful to verify the time series that will be retrieved / processed). The filter must specify the metric type and the resource type. Optionally, it can specify resource labels and metric labels. This field must not exceed 2048 Unicode characters in length. * `thresholdValue` (*type:* `float()`, *default:* `nil`) - A value against which to compare the time series. * `trigger` (*type:* `GoogleApi.Monitoring.V3.Model.Trigger.t`, *default:* `nil`) - The number/percent of time series for which the comparison must hold in order for the condition to trigger. If unspecified, then the condition will trigger if the comparison is true for any of the time series that have been identified by filter and aggregations, or by the ratio, if denominator_filter and denominator_aggregations are specified. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :aggregations => list(GoogleApi.Monitoring.V3.Model.Aggregation.t()) | nil, :comparison => String.t() | nil, :denominatorAggregations => list(GoogleApi.Monitoring.V3.Model.Aggregation.t()) | nil, :denominatorFilter => String.t() | nil, :duration => String.t() | nil, :filter => String.t() | nil, :thresholdValue => float() | nil, :trigger => GoogleApi.Monitoring.V3.Model.Trigger.t() | nil } field(:aggregations, as: GoogleApi.Monitoring.V3.Model.Aggregation, type: :list) field(:comparison) field(:denominatorAggregations, as: GoogleApi.Monitoring.V3.Model.Aggregation, type: :list) field(:denominatorFilter) field(:duration) field(:filter) field(:thresholdValue) field(:trigger, as: GoogleApi.Monitoring.V3.Model.Trigger) end defimpl Poison.Decoder, for: GoogleApi.Monitoring.V3.Model.MetricThreshold do def decode(value, options) do GoogleApi.Monitoring.V3.Model.MetricThreshold.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Monitoring.V3.Model.MetricThreshold do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
91.382353
677
0.761506
7937f542bdc2e74e98c835e37446527c4106ab72
2,243
ex
Elixir
clients/monitoring/lib/google_api/monitoring/v3/model/metric_descriptor_metadata.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/monitoring/lib/google_api/monitoring/v3/model/metric_descriptor_metadata.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/monitoring/lib/google_api/monitoring/v3/model/metric_descriptor_metadata.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.Monitoring.V3.Model.MetricDescriptorMetadata do @moduledoc """ Additional annotations that can be used to guide the usage of a metric. ## Attributes * `ingestDelay` (*type:* `String.t`, *default:* `nil`) - The delay of data points caused by ingestion. Data points older than this age are guaranteed to be ingested and available to be read, excluding data loss due to errors. * `launchStage` (*type:* `String.t`, *default:* `nil`) - Deprecated. Please use the MetricDescriptor.launch_stage instead. The launch stage of the metric definition. * `samplePeriod` (*type:* `String.t`, *default:* `nil`) - The sampling period of metric data points. For metrics which are written periodically, consecutive data points are stored at this time interval, excluding data loss due to errors. Metrics with a higher granularity have a smaller sampling period. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :ingestDelay => String.t(), :launchStage => String.t(), :samplePeriod => String.t() } field(:ingestDelay) field(:launchStage) field(:samplePeriod) end defimpl Poison.Decoder, for: GoogleApi.Monitoring.V3.Model.MetricDescriptorMetadata do def decode(value, options) do GoogleApi.Monitoring.V3.Model.MetricDescriptorMetadata.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Monitoring.V3.Model.MetricDescriptorMetadata do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
42.320755
307
0.742309
7938634a945a1319c942f5f215a85e79fdc47d3a
1,930
ex
Elixir
lib/identicon.ex
el-ro/identicon
44c5ddf8a79d9f4ed061331c85d32423a68f042b
[ "MIT" ]
null
null
null
lib/identicon.ex
el-ro/identicon
44c5ddf8a79d9f4ed061331c85d32423a68f042b
[ "MIT" ]
null
null
null
lib/identicon.ex
el-ro/identicon
44c5ddf8a79d9f4ed061331c85d32423a68f042b
[ "MIT" ]
null
null
null
defmodule Identicon do @moduledoc """ Documentation for `Identicon`. """ @doc """ Hello world. ## Examples iex> Identicon.hello() :world """ def main(input) do input |> hash_input |> pick_color |> build_grid |> filter_odd_squares |> build_pixel_map |> draw_image |> save_image(input) end def save_image(image, input) do File.write("#{input}.png", image) end def draw_image(%Identicon.Image{color: color, pixel_map: pixel_map}) do image = :egd.create(250, 250) fill = :egd.color(color) Enum.each(pixel_map, fn {start, stop} -> :egd.filledRectangle(image, start, stop, fill) end) :egd.render(image) end def build_pixel_map(%Identicon.Image{grid: grid} = image) do pixel_map = Enum.map(grid, fn {_code, index} -> horizontal = rem(index, 5) * 50 vertical = div(index, 5) * 50 top_left = {horizontal, vertical} bottom_right = {horizontal + 50, vertical + 50} {top_left, bottom_right} end) %Identicon.Image{image | pixel_map: pixel_map} end def filter_odd_squares(%Identicon.Image{grid: grid} = image) do grid = Enum.filter(grid, fn {code, _index} -> rem(code, 2) == 0 end) %Identicon.Image{image | grid: grid} end def build_grid(%Identicon.Image{hex: hex} = image) do grid = hex |> Enum.chunk_every(3, 3, :discard) |> Enum.map(&mirror_row/1) |> List.flatten() |> Enum.with_index() %Identicon.Image{image | grid: grid} end def mirror_row(row) do [first, second | _tail] = row row ++ [second, first] end def pick_color(%Identicon.Image{hex: [r, g, b | _tail]} = image) do %Identicon.Image{image | color: {r, g, b}} end def hash_input(input) do hex = :crypto.hash(:md5, input) |> :binary.bin_to_list() %Identicon.Image{hex: hex} end end
20.978261
73
0.598964
793866ef790765b16641daa4d0e3273c954fb9bb
595
exs
Elixir
mix.exs
pal-alex/form
9dd1496db37d26233f3f0263477f0f1cc991d274
[ "ISC" ]
null
null
null
mix.exs
pal-alex/form
9dd1496db37d26233f3f0263477f0f1cc991d274
[ "ISC" ]
null
null
null
mix.exs
pal-alex/form
9dd1496db37d26233f3f0263477f0f1cc991d274
[ "ISC" ]
null
null
null
defmodule FORM.Mixfile do use Mix.Project def application, do: [mod: {:form, []}] def project do [ app: :form, version: "4.11.14", description: "FORM Business X-Forms", package: package(), deps: deps() ] end def package do [ files: ~w(doc include man lib priv src mix.exs rebar.config LICENSE), licenses: ["ISC"], maintainers: ["Namdak Tonpa"], links: %{"GitHub" => "https://github.com/synrc/form"} ] end def deps do [ {:ex_doc, "~> 0.11", only: :dev}, {:nitro, "~> 4.11.12"} ] end end
19.193548
75
0.536134
79388257e6e253440147edf4cf29524e92c555dc
1,466
ex
Elixir
lib/cotoami_web/controllers/oauth2_controller.ex
fmorita/cotoami
e3eb92ad15829f99cf3e8974077f135e789924cf
[ "Apache-2.0" ]
null
null
null
lib/cotoami_web/controllers/oauth2_controller.ex
fmorita/cotoami
e3eb92ad15829f99cf3e8974077f135e789924cf
[ "Apache-2.0" ]
null
null
null
lib/cotoami_web/controllers/oauth2_controller.ex
fmorita/cotoami
e3eb92ad15829f99cf3e8974077f135e789924cf
[ "Apache-2.0" ]
null
null
null
defmodule CotoamiWeb.OAuth2Controller do use CotoamiWeb, :controller require Logger alias Cotoami.AmishiService alias CotoamiWeb.AuthPlug alias CotoamiWeb.OAuth2.Google alias CotoamiWeb.OAuth2.GitHub def providers do :cotoami |> Application.get_env(__MODULE__, []) |> Keyword.get(:providers) end def index(conn, %{"provider" => provider}) do if provider in providers() do redirect conn, external: authorize_url!(provider) else send_resp(conn, :unauthorized, "") end end def callback(conn, %{"provider" => provider, "code" => code}) do client = get_token!(provider, code) user = get_user!(provider, client) amishi = AmishiService.insert_or_update!(user) conn |> AuthPlug.start_session(amishi) |> put_session(:access_token, client.token.access_token) |> redirect(to: "/") |> halt() end defp authorize_url!("google"), do: Google.authorize_url!(scope: "https://www.googleapis.com/auth/userinfo.email") defp authorize_url!("github"), do: GitHub.authorize_url! defp authorize_url!(_), do: raise "No matching provider available" defp get_token!("google", code), do: Google.get_token!(code: code) defp get_token!("github", code), do: GitHub.get_token!(code: code) defp get_token!(_, _), do: raise "No matching provider available" defp get_user!("google", client), do: Google.get_user!(client) defp get_user!("github", client), do: GitHub.get_user!(client) end
32.577778
115
0.699181
793882650adc08f585748fd1e76dbe55bc2c148e
1,146
exs
Elixir
mix.exs
illiatdesdindes/hivebot
694cd58f0d8b9b9db467cfad3a1a585b8e8fb3ae
[ "MIT" ]
1
2016-08-09T21:27:53.000Z
2016-08-09T21:27:53.000Z
mix.exs
illiatdesdindes/hivebot
694cd58f0d8b9b9db467cfad3a1a585b8e8fb3ae
[ "MIT" ]
null
null
null
mix.exs
illiatdesdindes/hivebot
694cd58f0d8b9b9db467cfad3a1a585b8e8fb3ae
[ "MIT" ]
null
null
null
defmodule Hivebot.Mixfile do use Mix.Project def project do [ app: :hivebot, version: "0.1.0", elixir: "~> 1.8", build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, deps: deps() ] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do [applications: [:logger, :slack, :httpoison], mod: {Hivebot, []}] end # Dependencies can be Hex packages: # # {:mydep, "~> 0.3.0"} # # Or git/path repositories: # # {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"} # # Type "mix help deps" for more examples and options defp deps do [ {:slack, "~> 0.6.0"}, {:websocket_client, git: "https://github.com/jeremyong/websocket_client", override: true}, {:envy, "~> 1.0.0"}, {:httpoison, "~> 0.8"}, {:mix_test_watch, "~> 0.2", only: :dev}, {:dialyxir, "~> 0.3.5", only: [:dev]}, {:mr_t, "~> 0.5.0", only: [:test, :dev]}, {:ex_unit_notifier, "~> 0.1", only: :test}, {:mock, "~> 0.1.1", only: :test} ] end end
25.466667
96
0.546248
7938a9eabd2d13caedee05f76d9c1338b18fe223
585
ex
Elixir
apps/artemis/lib/artemis/contexts/auth_provider/create_auth_provider.ex
chrislaskey/atlas_platform
969aea95814f62d3471f93000ee5ad77edb9d1bf
[ "MIT" ]
10
2019-07-05T19:59:20.000Z
2021-05-23T07:36:11.000Z
apps/artemis/lib/artemis/contexts/auth_provider/create_auth_provider.ex
chrislaskey/atlas_platform
969aea95814f62d3471f93000ee5ad77edb9d1bf
[ "MIT" ]
7
2019-07-12T21:41:01.000Z
2020-08-17T21:29:22.000Z
apps/artemis/lib/artemis/contexts/auth_provider/create_auth_provider.ex
chrislaskey/atlas_platform
969aea95814f62d3471f93000ee5ad77edb9d1bf
[ "MIT" ]
4
2019-07-05T20:04:08.000Z
2021-05-13T16:28:33.000Z
defmodule Artemis.CreateAuthProvider do use Artemis.Context alias Artemis.AuthProvider alias Artemis.Repo def call!(params, user) do case call(params, user) do {:error, _} -> raise(Artemis.Context.Error, "Error creating auth provider") {:ok, result} -> result end end def call(params, user) do with_transaction(fn -> params |> insert_record |> Event.broadcast("auth-provider:created", user) end) end defp insert_record(params) do %AuthProvider{} |> AuthProvider.changeset(params) |> Repo.insert() end end
20.892857
81
0.659829
7938bfad7beefe398c601e331012da94f12e17f4
1,740
ex
Elixir
clients/cloud_tasks/lib/google_api/cloud_tasks/v2beta2/model/test_iam_permissions_request.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/cloud_tasks/lib/google_api/cloud_tasks/v2beta2/model/test_iam_permissions_request.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/cloud_tasks/lib/google_api/cloud_tasks/v2beta2/model/test_iam_permissions_request.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.CloudTasks.V2beta2.Model.TestIamPermissionsRequest do @moduledoc """ Request message for `TestIamPermissions` method. ## Attributes * `permissions` (*type:* `list(String.t)`, *default:* `nil`) - The set of permissions to check for the `resource`. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. For more information see [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :permissions => list(String.t()) } field(:permissions, type: :list) end defimpl Poison.Decoder, for: GoogleApi.CloudTasks.V2beta2.Model.TestIamPermissionsRequest do def decode(value, options) do GoogleApi.CloudTasks.V2beta2.Model.TestIamPermissionsRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudTasks.V2beta2.Model.TestIamPermissionsRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.8
135
0.741954
7938ea7e309e380a55a4a12db5e15379b248d034
501
ex
Elixir
lib/elixirdo/instance/monad_trans/maybe/monad_state.ex
slepher/elixirdo
9417f275f1c908f9144e93325e6c52717896058f
[ "Xnet", "X11" ]
null
null
null
lib/elixirdo/instance/monad_trans/maybe/monad_state.ex
slepher/elixirdo
9417f275f1c908f9144e93325e6c52717896058f
[ "Xnet", "X11" ]
5
2018-07-20T12:36:25.000Z
2018-08-01T04:55:46.000Z
lib/elixirdo/instance/monad_trans/maybe/monad_state.ex
slepher/elixirdo
9417f275f1c908f9144e93325e6c52717896058f
[ "Xnet", "X11" ]
null
null
null
defmodule Elixirdo.Instance.MonadTrans.Maybe.MonadState do use Elixirdo.Base use Elixirdo.Typeclass.Monad.State, import_monad_state: true alias Elixirdo.Instance.MonadTrans.Maybe, as: MaybeT import_type MaybeT.maybe_t() definstance monad_state(maybe_t(m), m: monad_state) do def get() do MonadState.lift_get(m, maybe_t) end def put(s) do MonadState.lift_put(s, m, maybe_t) end def state(f) do MonadState.lift_state(f, m, maybe_t) end end end
21.782609
62
0.710579
79390c8da3a0a57dfd9ce262d9737d826716daa2
1,297
ex
Elixir
test/support/conn_case.ex
Baradoy/intermdiategit
3a7b7efc32e361d2347057cbe3c8997f44135522
[ "MIT" ]
null
null
null
test/support/conn_case.ex
Baradoy/intermdiategit
3a7b7efc32e361d2347057cbe3c8997f44135522
[ "MIT" ]
null
null
null
test/support/conn_case.ex
Baradoy/intermdiategit
3a7b7efc32e361d2347057cbe3c8997f44135522
[ "MIT" ]
null
null
null
defmodule IntermediateGitWeb.ConnCase do @moduledoc """ This module defines the test case to be used by tests that require setting up a connection. Such tests rely on `Phoenix.ConnTest` and also import other functionality to make it easier to build common data structures and query the data layer. Finally, if the test case interacts with the database, we enable the SQL sandbox, so changes done to the database are reverted at the end of every test. If you are using PostgreSQL, you can even run database tests asynchronously by setting `use IntermediateGitWeb.ConnCase, async: true`, although this option is not recommended for other databases. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections import Plug.Conn import Phoenix.ConnTest import IntermediateGitWeb.ConnCase alias IntermediateGitWeb.Router.Helpers, as: Routes # The default endpoint for testing @endpoint IntermediateGitWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(IntermediateGit.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(IntermediateGit.Repo, {:shared, self()}) end {:ok, conn: Phoenix.ConnTest.build_conn()} end end
29.477273
77
0.736315
79390fca5434ff53ea3f121d81a2fbf918a5aa14
1,808
ex
Elixir
clients/sheets/lib/google_api/sheets/v4/model/refresh_data_source_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/sheets/lib/google_api/sheets/v4/model/refresh_data_source_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/sheets/lib/google_api/sheets/v4/model/refresh_data_source_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Sheets.V4.Model.RefreshDataSourceResponse do @moduledoc """ The response from refreshing one or multiple data source objects. ## Attributes * `statuses` (*type:* `list(GoogleApi.Sheets.V4.Model.RefreshDataSourceObjectExecutionStatus.t)`, *default:* `nil`) - All the refresh status for the data source object references specified in the request. If is_all is specified, the field contains only those in failure status. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :statuses => list(GoogleApi.Sheets.V4.Model.RefreshDataSourceObjectExecutionStatus.t()) } field(:statuses, as: GoogleApi.Sheets.V4.Model.RefreshDataSourceObjectExecutionStatus, type: :list ) end defimpl Poison.Decoder, for: GoogleApi.Sheets.V4.Model.RefreshDataSourceResponse do def decode(value, options) do GoogleApi.Sheets.V4.Model.RefreshDataSourceResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Sheets.V4.Model.RefreshDataSourceResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.16
281
0.760509
7939139ee12d9b79be71b3b7474a37e0305bc94e
362
exs
Elixir
test/absinthe/integration/execution/aliases/weird_test.exs
hauptbenutzer/absinthe
f1d76e5c249ca337187971b0c96b1870f53716ed
[ "MIT" ]
null
null
null
test/absinthe/integration/execution/aliases/weird_test.exs
hauptbenutzer/absinthe
f1d76e5c249ca337187971b0c96b1870f53716ed
[ "MIT" ]
null
null
null
test/absinthe/integration/execution/aliases/weird_test.exs
hauptbenutzer/absinthe
f1d76e5c249ca337187971b0c96b1870f53716ed
[ "MIT" ]
1
2018-11-16T02:34:40.000Z
2018-11-16T02:34:40.000Z
defmodule Elixir.Absinthe.Integration.Execution.Aliases.WeirdTest do use ExUnit.Case, async: true @query """ query { thing(id: "foo") { fOO_Bar_baz: name } } """ test "scenario #1" do assert {:ok, %{data: %{"thing" => %{"fOO_Bar_baz" => "Foo"}}}} == Absinthe.run(@query, Absinthe.Fixtures.ThingsSchema, []) end end
21.294118
69
0.59116
7939389c49314da92627118a505cf849695e7a4f
239
ex
Elixir
lib/phone/es/s.ex
mrjfernando/phone
3febb243fcd8bdb1c333601a637f449a94caef88
[ "Apache-2.0" ]
97
2016-04-05T13:08:41.000Z
2021-12-25T13:08:34.000Z
lib/phone/es/s.ex
mrjfernando/phone
3febb243fcd8bdb1c333601a637f449a94caef88
[ "Apache-2.0" ]
70
2016-06-14T00:56:00.000Z
2022-02-10T19:43:14.000Z
lib/phone/es/s.ex
mrjfernando/phone
3febb243fcd8bdb1c333601a637f449a94caef88
[ "Apache-2.0" ]
31
2016-04-21T22:26:12.000Z
2022-01-24T21:40:00.000Z
defmodule Phone.ES.S do @moduledoc false use Helper.Area def regex, do: ~r/^(34)(942|842)(.{6})$/ def area_name, do: "Cantabria" def area_type, do: "province" def area_abbreviation, do: "S" matcher(["34942", "34842"]) end
18.384615
42
0.644351
7939394be3a84bf0e3a69ee6288d5c70b811bbd8
544
ex
Elixir
lib/phxpay_web/controllers/accounts_controller.ex
ramonlimaramos/phxpay
accf0ada9581a8f8f396849fdfe10e1a1c4ae2af
[ "MIT" ]
null
null
null
lib/phxpay_web/controllers/accounts_controller.ex
ramonlimaramos/phxpay
accf0ada9581a8f8f396849fdfe10e1a1c4ae2af
[ "MIT" ]
null
null
null
lib/phxpay_web/controllers/accounts_controller.ex
ramonlimaramos/phxpay
accf0ada9581a8f8f396849fdfe10e1a1c4ae2af
[ "MIT" ]
null
null
null
defmodule PhxpayWeb.AccountsController do use PhxpayWeb, :controller alias Phxpay.Account action_fallback PhxpayWeb.FallbackController def deposit(conn, params) do with {:ok, %Account{} = account} <- Phxpay.deposit(params) do conn |> put_status(:ok) |> render("update.json", account: account) end end def withdraw(conn, params) do with {:ok, %Account{} = account} <- Phxpay.withdraw(params) do conn |> put_status(:ok) |> render("update.json", account: account) end end end
21.76
66
0.652574
7939565917d50b8744f03520bb330621d7f9c786
131
exs
Elixir
test/system_test.exs
Phiriq/chlorine
30da3362949a8264125ce2d90a96f0f5318cf589
[ "MIT" ]
1
2021-06-30T03:40:47.000Z
2021-06-30T03:40:47.000Z
test/system_test.exs
Phiriq/chlorine
30da3362949a8264125ce2d90a96f0f5318cf589
[ "MIT" ]
null
null
null
test/system_test.exs
Phiriq/chlorine
30da3362949a8264125ce2d90a96f0f5318cf589
[ "MIT" ]
null
null
null
defmodule Chlorine.SystemTest do use ExUnit.Case defmodule MockSystem do use Chlorine.System, for: [Age, Human] end end
16.375
42
0.740458
7939b3eef9db8f8e855fcd5dfabd5dad5e0fd249
83
exs
Elixir
test/views/page_view_test.exs
avval-alumni/alumni_book
17b27da849919312a332aaa3b39ce5c65032f2b4
[ "MIT" ]
null
null
null
test/views/page_view_test.exs
avval-alumni/alumni_book
17b27da849919312a332aaa3b39ce5c65032f2b4
[ "MIT" ]
null
null
null
test/views/page_view_test.exs
avval-alumni/alumni_book
17b27da849919312a332aaa3b39ce5c65032f2b4
[ "MIT" ]
null
null
null
defmodule AlumniBook.PageViewTest do use AlumniBookWeb.ConnCase, async: true end
20.75
41
0.831325
7939c25a259b711c54726692552d9914a1376328
1,208
ex
Elixir
lib/ext/api/sync_group.ex
bahanni/custom_rpi4
ddefa85d30bacaae40151a63a9a0ebbf4ad30ed5
[ "MIT" ]
null
null
null
lib/ext/api/sync_group.ex
bahanni/custom_rpi4
ddefa85d30bacaae40151a63a9a0ebbf4ad30ed5
[ "MIT" ]
null
null
null
lib/ext/api/sync_group.ex
bahanni/custom_rpi4
ddefa85d30bacaae40151a63a9a0ebbf4ad30ed5
[ "MIT" ]
null
null
null
defmodule FarmbotOS.API.SyncGroup do @moduledoc "Handles dependency ordering." alias FarmbotOS.Asset.{ Device, FarmEvent, FarmwareEnv, FbosConfig, FirmwareConfig, Peripheral, PinBinding, Point, PointGroup, Regimen, SensorReading, Sensor, Sequence, Tool } def all_groups, do: group_0() ++ group_1() ++ group_2() ++ group_3() ++ group_4() @doc "Assets in Group 0 are required for FarmBot to operate." def group_0, do: [ Device, FbosConfig, FirmwareConfig, FarmwareEnv ] @doc "Group 1 should have no external requirements" def group_1, do: [ Peripheral, Point, SensorReading, Sensor, Tool ] @doc "Group 2 relies on assets in Group 1" def group_2, do: [ # Requires Peripheral, Point, Sensor, SensorReading, Tool Sequence, PointGroup ] @doc "Group 3 relies on assets in Group 2" def group_3, do: [ # Requires Sequence Regimen, # Requires Sequence PinBinding ] @doc "Group 4 relies on assets in Group 3" def group_4, do: [ # Requires Regimen and Sequence FarmEvent ] end
18.029851
69
0.603477
7939c5a59ff414ca56e55739de6134e9e8854a83
7,802
exs
Elixir
test/webclient_test.exs
bitpay/elixir-client
cccf8abbad5da7ad3d01d186bd14bf69eca68770
[ "MIT" ]
35
2015-01-18T02:16:11.000Z
2021-11-14T01:55:34.000Z
test/webclient_test.exs
philosodad/bitpay-elixir
cccf8abbad5da7ad3d01d186bd14bf69eca68770
[ "MIT" ]
3
2015-06-24T15:18:57.000Z
2017-05-17T17:52:05.000Z
test/webclient_test.exs
bitpay/elixir-client
cccf8abbad5da7ad3d01d186bd14bf69eca68770
[ "MIT" ]
13
2015-01-16T21:11:22.000Z
2021-10-29T23:23:59.000Z
defmodule WebClientTest do use ExUnit.Case, async: false alias BitPay.WebClient, as: WebClient import Mock test 'post method does not try to get token if public facade input' do client = %WebClient{} with_mock HTTPotion, [post: fn("https://bitpay.com/testpoint", _body, _headers) -> %HTTPotion.Response{status_code: 200, body: "{\"data\":[{\"policies\":[{\"policy\":\"id\",\"method\":\"unclaimed\",\"params\":[]}],\"resource\":\"4e2rQDFK6Y1X4eU5ugw8AYy9FFih6jRicv6dxeccgS8r\",\"token\":\"BHMA5LMxUdEvePuAaEPmuW5tPYbGpw65jirDHzbXLfkt\",\"facade\":\"pos\",\"dateCreated\":1440003119142,\"pairingExpiration\":1440089519142,\"pairingCode\":\"8GSQvjb\"}]}" } end] do response = WebClient.post("testpoint", %{with_facade: :public}, client) assert response.body.data |> List.first |> Access.get(:token) == "BHMA5LMxUdEvePuAaEPmuW5tPYbGpw65jirDHzbXLfkt" end end test 'get_pairing_code makes a public call to the tokens endpoint' do client = %WebClient{} with_mock HTTPotion, [post: fn("https://bitpay.com/tokens", _body, _headers) -> %HTTPotion.Response{status_code: 200, body: "{\"data\":[{\"policies\":[{\"policy\":\"id\",\"method\":\"unclaimed\",\"params\":[]}],\"resource\":\"4e2rQDFK6Y1X4eU5ugw8AYy9FFih6jRicv6dxeccgS8r\",\"token\":\"BHMA5LMxUdEvePuAaEPmuW5tPYbGpw65jirDHzbXLfkt\",\"facade\":\"pos\",\"dateCreated\":1440003119142,\"pairingExpiration\":1440089519142,\"pairingCode\":\"8GSQvjb\"}]}" } end] do {:ok, pairingCode} = WebClient.get_pairing_code(client) assert pairingCode == "8GSQvjb" end end test 'get_pairing_code accepts "merchant" or "pos" arguments' do client = %WebClient{} with_mock HTTPotion, [post: fn("https://bitpay.com/tokens", _body, _headers) -> %HTTPotion.Response{status_code: 200, body: "{\"data\":[{\"policies\":[{\"policy\":\"id\",\"method\":\"unclaimed\",\"params\":[]}],\"resource\":\"4e2rQDFK6Y1X4eU5ugw8AYy9FFih6jRicv6dxeccgS8r\",\"token\":\"BHMA5LMxUdEvePuAaEPmuW5tPYbGpw65jirDHzbXLfkt\",\"facade\":\"pos\",\"dateCreated\":1440003119142,\"pairingExpiration\":1440089519142,\"pairingCode\":\"8GSQvjb\"}]}" } end] do {:ok, pairingCode} = WebClient.get_pairing_code(client, :merchant) assert pairingCode == "8GSQvjb" end end test 'post method gets specified token if input' do client = %WebClient{} with_mock HTTPotion, [get: fn("https://bitpay.com/tokens", _body, _headers) -> %HTTPotion.Response{status_code: 228, body: "{\"data\":[{\"testfacade\":\"EBtD6Dae9VXvK8ky7zYkCMfwZCzcsGsDiEfqmZB3Et9K\"},{\"pos/invoice\":\"ED2H47jWZbQKnPTwRLeZcfQ7eN9NyiRFVnRexmoWLScu\"}]}"} end, post: fn("https://bitpay.com/testpoint", _body, _headers) -> %HTTPotion.Response{status_code: 200, body: "{\"data\":[{\"policies\":[{\"policy\":\"id\",\"method\":\"unclaimed\",\"params\":[]}],\"resource\":\"4e2rQDFK6Y1X4eU5ugw8AYy9FFih6jRicv6dxeccgS8r\",\"token\":\"BHMA5LMxUdEvePuAaEPmuW5tPYbGpw65jirDHzbXLfkt\",\"facade\":\"pos\",\"dateCreated\":1440003119142,\"pairingExpiration\":1440089519142,\"pairingCode\":\"8GSQvjb\"}]}" } end] do response = WebClient.post("testpoint", %{with_facade: :testfacade}, client) assert response.body.data |> List.first |> Access.get(:token) == "BHMA5LMxUdEvePuAaEPmuW5tPYbGpw65jirDHzbXLfkt" end end test 'get method' do with_mock HTTPotion, [get: fn("https://bitpay.com/blocks", _body, _headers) -> %HTTPotion.Response{status_code: 228, body: "{\"data\":[{\"pos\":\"EBtD6Dae9VXvK8ky7zYkCMfwZCzcsGsDiEfqmZB3Et9K\"},{\"pos/invoice\":\"ED2H47jWZbQKnPTwRLeZcfQ7eN9NyiRFVnRexmoWLScu\"}]}"} end] do assert WebClient.get("blocks", %WebClient{}).status == 228 end end test 'pairing short circuits with invalid code' do illegal_pairing_codes() |> Enum.each fn(item) -> assert WebClient.pair_pos_client(item, %WebClient{}) == {:error, "pairing code is not legal"} end end test 'pairing handles errors gracefully' do with_mock HTTPotion, [post: fn("https://bitpay.com/tokens", _body, _headers) -> %HTTPotion.Response{status_code: 403, body: "{\n \"error\": \"this is a 403 error\"\n}"} end] do assert {:error, "403: this is a 403 error"} == WebClient.pair_pos_client "aBD3fhg", %WebClient{} end end test "create invoice fails gracefully with improper price" do params = %{price: "100,00", currency: "USD", token: "anything"} assert {:error, "Illegal Argument: Price must be formatted as a float"} == WebClient.create_invoice(params, %BitPay.WebClient{}) end test "create invoice retrieves tokens from server" do params = %{price: 100, currency: "USD"} with_mock HTTPotion, [get: fn("https://bitpay.com/tokens", _body, _headers) -> %HTTPotion.Response{status_code: 228, body: "{\"data\":[{\"pos\":\"EBtD6Dae9VXvK8ky7zYkCMfwZCzcsGsDiEfqmZB3Et9K\"},{\"pos/invoice\":\"ED2H47jWZbQKnPTwRLeZcfQ7eN9NyiRFVnRexmoWLScu\"}]}"} end, post: fn("https://bitpay.com/invoices", _body, _headers) -> %HTTPotion.Response{status_code: 200, body: "{\"facade\":\"pos/invoice\",\"data\":{\"url\":\"https://test.bitpay.com/invoice?id=A41p1sHqruaA38YaKC83L7\",\"status\":\"new\",\"btcPrice\":\"0.388736\",\"btcDue\":\"0.388736\",\"price\":100,\"currency\":\"USD\",\"exRates\":{\"USD\":257.24390946963365},\"invoiceTime\":1439829619654,\"expirationTime\":1439830519654,\"currentTime\":1439829619916,\"guid\":\"ebf5fe06-b738-4d51-bb9c-f5dcd6613124\",\"id\":\"A41p1sHqruaA38YaKC83L7\",\"btcPaid\":\"0.000000\",\"rate\":257.24,\"exceptionStatus\":false,\"paymentUrls\":{\"BIP21\":\"bitcoin:mtzuBK37L5CxsvPVfP1E711gk6h7VJQ3rJ?amount=0.388736\",\"BIP72\":\"bitcoin:mtzuBK37L5CxsvPVfP1E711gk6h7VJQ3rJ?amount=0.388736&r=https://test.bitpay.com/i/A41p1sHqruaA38YaKC83L7\",\"BIP72b\":\"bitcoin:?r=https://test.bitpay.com/i/A41p1sHqruaA38YaKC83L7\",\"BIP73\":\"https://test.bitpay.com/i/A41p1sHqruaA38YaKC83L7\"},\"token\":\"8CWU2YMJSozc2SKoYJygRkuqmyiuCAQSQrShMpzGT4f77BPABLt9EovsxkmVkUWvPE\"}}" } end] do {:ok, response} = WebClient.create_invoice(params, %WebClient{}) assert 1439829619916 == response.currentTime end end test "create invoice handles BTC" do params = %{price: "0.004", currency: "BTC", token: "anything"} with_mock HTTPotion, [post: fn("https://bitpay.com/invoices", _body, _headers) -> %HTTPotion.Response{status_code: 200, body: "{\"facade\":\"pos/invoice\",\"data\":{\"url\":\"https://test.bitpay.com/invoice?id=A41p1sHqruaA38YaKC83L7\",\"status\":\"new\",\"btcPrice\":\"0.388736\",\"btcDue\":\"0.388736\",\"price\":100,\"currency\":\"USD\",\"exRates\":{\"USD\":257.24390946963365},\"invoiceTime\":1439829619654,\"expirationTime\":1439830519654,\"currentTime\":1439829619916,\"guid\":\"ebf5fe06-b738-4d51-bb9c-f5dcd6613124\",\"id\":\"A41p1sHqruaA38YaKC83L7\",\"btcPaid\":\"0.000000\",\"rate\":257.24,\"exceptionStatus\":false,\"paymentUrls\":{\"BIP21\":\"bitcoin:mtzuBK37L5CxsvPVfP1E711gk6h7VJQ3rJ?amount=0.388736\",\"BIP72\":\"bitcoin:mtzuBK37L5CxsvPVfP1E711gk6h7VJQ3rJ?amount=0.388736&r=https://test.bitpay.com/i/A41p1sHqruaA38YaKC83L7\",\"BIP72b\":\"bitcoin:?r=https://test.bitpay.com/i/A41p1sHqruaA38YaKC83L7\",\"BIP73\":\"https://test.bitpay.com/i/A41p1sHqruaA38YaKC83L7\"},\"token\":\"8CWU2YMJSozc2SKoYJygRkuqmyiuCAQSQrShMpzGT4f77BPABLt9EovsxkmVkUWvPE\"}}" } end] do {:ok, response} = WebClient.create_invoice(params, %BitPay.WebClient{}) assert 1439829619916 == response.currentTime end end test "create invoice fails gracefully with improper currency" do params = %{price: 100.00, currency: "USDa", token: "anything"} assert {:error, "Illegal Argument: Currency is invalid."} == WebClient.create_invoice(params, %BitPay.WebClient{}) end defp illegal_pairing_codes do ["abcdefgh", "habcdefg", "abcd-fg"] end end
86.688889
1,322
0.694309
7939cfe723a3f716feef550795b24db2af7a5074
625
ex
Elixir
lib/chain/transactionreceipt.ex
diodechain/diode_server
1692788bd92cc17654965878abd059d13b5e236c
[ "Apache-2.0" ]
8
2021-03-12T15:35:09.000Z
2022-03-06T06:37:49.000Z
lib/chain/transactionreceipt.ex
diodechain/diode_server_ex
5cf47e5253a0caafd335d0af4dba711d4dcad42d
[ "Apache-2.0" ]
15
2019-09-06T07:58:01.000Z
2021-03-06T17:04:46.000Z
lib/chain/transactionreceipt.ex
diodechain/diode_server
1692788bd92cc17654965878abd059d13b5e236c
[ "Apache-2.0" ]
5
2021-10-01T12:52:28.000Z
2022-02-02T19:29:56.000Z
# Diode Server # Copyright 2021 Diode # Licensed under the Diode License, Version 1.1 defmodule Chain.TransactionReceipt do defstruct msg: nil, # state: nil, evmout: nil, gas_used: nil, return_data: nil, data: nil, logs: [], trace: nil @type t :: %Chain.TransactionReceipt{ msg: binary() | :ok | :evmc_revert, # state: Chain.State.t() | nil, evmout: any(), gas_used: non_neg_integer() | nil, return_data: binary() | nil, data: binary() | nil, logs: [] } end
26.041667
47
0.512
7939e7d11f97d913d6fc93394268501f2d82acc4
86
exs
Elixir
test/makeup_live_web/views/page_view_test.exs
axelson/makeup_live_format
122cd01b6b8c89099ede56a8cadea43523d62c51
[ "MIT" ]
6
2020-01-18T15:57:42.000Z
2020-07-05T08:28:56.000Z
test/makeup_live_web/views/page_view_test.exs
axelson/makeup_live_format
122cd01b6b8c89099ede56a8cadea43523d62c51
[ "MIT" ]
2
2020-01-17T18:26:24.000Z
2020-02-04T01:34:48.000Z
test/makeup_live_web/views/page_view_test.exs
axelson/makeup_live_format
122cd01b6b8c89099ede56a8cadea43523d62c51
[ "MIT" ]
1
2020-01-13T17:56:00.000Z
2020-01-13T17:56:00.000Z
defmodule MakeupLiveWeb.PageViewTest do use MakeupLiveWeb.ConnCase, async: true end
21.5
41
0.837209
793a041bfbb068cdd6948c6ebdaa23231b546d32
3,187
ex
Elixir
apps/ewallet/lib/ewallet/web/v1/serializers/wallet_serializer.ex
enyan94/ewallet
e938e686319867d133b21cd0eb5496e213ae7620
[ "Apache-2.0" ]
null
null
null
apps/ewallet/lib/ewallet/web/v1/serializers/wallet_serializer.ex
enyan94/ewallet
e938e686319867d133b21cd0eb5496e213ae7620
[ "Apache-2.0" ]
null
null
null
apps/ewallet/lib/ewallet/web/v1/serializers/wallet_serializer.ex
enyan94/ewallet
e938e686319867d133b21cd0eb5496e213ae7620
[ "Apache-2.0" ]
null
null
null
# Copyright 2018-2019 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 EWallet.Web.V1.WalletSerializer do @moduledoc """ Serializes address data into V1 JSON response format. """ alias Ecto.Association.NotLoaded alias EWallet.Web.{Paginator, BalanceLoader} alias EWallet.Web.V1.{ AccountSerializer, BalanceSerializer, ListSerializer, PaginatorSerializer, UserSerializer } alias EWalletDB.{Wallet, Helpers.Preloader} alias Utils.Helpers.{Assoc, DateFormatter} def serialize(%Paginator{} = paginator) do PaginatorSerializer.serialize(paginator, &serialize/1) end def serialize(wallets) when is_list(wallets) do wallets |> Enum.map(&serialize/1) |> ListSerializer.serialize() end def serialize(%NotLoaded{}), do: nil def serialize(nil), do: nil def serialize(%Wallet{} = wallet) do wallet = case Map.get(wallet, :balances) do nil -> {:ok, wallet} = BalanceLoader.add_balances(wallet) wallet _ -> wallet end %{ object: "wallet", socket_topic: "wallet:#{wallet.address}", address: wallet.address, name: wallet.name, identifier: wallet.identifier, metadata: wallet.metadata, encrypted_metadata: wallet.encrypted_metadata, user_id: Assoc.get(wallet, [:user, :id]), user: UserSerializer.serialize(wallet.user), account_id: Assoc.get(wallet, [:account, :id]), account: AccountSerializer.serialize(wallet.account), balances: serialize_balances(wallet.balances), enabled: wallet.enabled, created_at: DateFormatter.to_iso8601(wallet.inserted_at), updated_at: DateFormatter.to_iso8601(wallet.updated_at) } end def serialize_without_balances(%Wallet{} = wallet) do wallet = Preloader.preload(wallet, [:user, :account]) %{ object: "wallet", socket_topic: "wallet:#{wallet.address}", address: wallet.address, name: wallet.name, identifier: wallet.identifier, metadata: wallet.metadata, encrypted_metadata: wallet.encrypted_metadata, user_id: Assoc.get(wallet, [:user, :id]), user: UserSerializer.serialize(wallet.user), account_id: Assoc.get(wallet, [:account, :id]), account: AccountSerializer.serialize(wallet.account), balances: nil, enabled: wallet.enabled, created_at: DateFormatter.to_iso8601(wallet.inserted_at), updated_at: DateFormatter.to_iso8601(wallet.updated_at) } end def serialize_without_balances(_), do: nil defp serialize_balances(balances) do Enum.map(balances, &BalanceSerializer.serialize/1) end end
30.644231
74
0.696266
793a15015cd2f0d9c5f90827ced6d67a901413e6
5,269
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/backend_bucket_cdn_policy.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/backend_bucket_cdn_policy.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/backend_bucket_cdn_policy.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Compute.V1.Model.BackendBucketCdnPolicy do @moduledoc """ Message containing Cloud CDN configuration for a backend bucket. ## Attributes * `cacheMode` (*type:* `String.t`, *default:* `nil`) - Specifies the cache setting for all responses from this backend. The possible values are: USE_ORIGIN_HEADERS Requires the origin to set valid caching headers to cache content. Responses without these headers will not be cached at Google's edge, and will require a full trip to the origin on every request, potentially impacting performance and increasing load on the origin server. FORCE_CACHE_ALL Cache all content, ignoring any "private", "no-store" or "no-cache" directives in Cache-Control response headers. Warning: this may result in Cloud CDN caching private, per-user (user identifiable) content. CACHE_ALL_STATIC Automatically cache static content, including common image formats, media (video and audio), and web assets (JavaScript and CSS). Requests and responses that are marked as uncacheable, as well as dynamic content (including HTML), will not be cached. * `clientTtl` (*type:* `integer()`, *default:* `nil`) - Specifies a separate client (e.g. browser client) maximum TTL. This is used to clamp the max-age (or Expires) value sent to the client. With FORCE_CACHE_ALL, the lesser of client_ttl and default_ttl is used for the response max-age directive, along with a "public" directive. For cacheable content in CACHE_ALL_STATIC mode, client_ttl clamps the max-age from the origin (if specified), or else sets the response max-age directive to the lesser of the client_ttl and default_ttl, and also ensures a "public" cache-control directive is present. If a client TTL is not specified, a default value (1 hour) will be used. The maximum allowed value is 86400s (1 day). * `defaultTtl` (*type:* `integer()`, *default:* `nil`) - Specifies the default TTL for cached content served by this origin for responses that do not have an existing valid TTL (max-age or s-max-age). Setting a TTL of "0" means "always revalidate". The value of defaultTTL cannot be set to a value greater than that of maxTTL, but can be equal. When the cacheMode is set to FORCE_CACHE_ALL, the defaultTTL will overwrite the TTL set in all responses. The maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. * `maxTtl` (*type:* `integer()`, *default:* `nil`) - Specifies the maximum allowed TTL for cached content served by this origin. Cache directives that attempt to set a max-age or s-maxage higher than this, or an Expires header more than maxTTL seconds in the future will be capped at the value of maxTTL, as if it were the value of an s-maxage Cache-Control directive. Headers sent to the client will not be modified. Setting a TTL of "0" means "always revalidate". The maximum allowed value is 31,622,400s (1 year), noting that infrequently accessed objects may be evicted from the cache before the defined TTL. * `signedUrlCacheMaxAgeSec` (*type:* `String.t`, *default:* `nil`) - Maximum number of seconds the response to a signed URL request will be considered fresh. After this time period, the response will be revalidated before being served. Defaults to 1hr (3600s). When serving responses to signed URL requests, Cloud CDN will internally behave as though all responses from this backend had a "Cache-Control: public, max-age=[TTL]" header, regardless of any existing Cache-Control header. The actual headers served in responses will not be altered. * `signedUrlKeyNames` (*type:* `list(String.t)`, *default:* `nil`) - [Output Only] Names of the keys for signing request URLs. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :cacheMode => String.t(), :clientTtl => integer(), :defaultTtl => integer(), :maxTtl => integer(), :signedUrlCacheMaxAgeSec => String.t(), :signedUrlKeyNames => list(String.t()) } field(:cacheMode) field(:clientTtl) field(:defaultTtl) field(:maxTtl) field(:signedUrlCacheMaxAgeSec) field(:signedUrlKeyNames, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.BackendBucketCdnPolicy do def decode(value, options) do GoogleApi.Compute.V1.Model.BackendBucketCdnPolicy.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.BackendBucketCdnPolicy do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
77.485294
720
0.752325
793a2d49523e3df53e98d9610e43bf9554548ed2
652
ex
Elixir
test/support/repos.ex
ottobar/paper_trail
046590026ec50605f3cabfaf48354b8acbf969a9
[ "MIT" ]
484
2016-06-19T19:33:31.000Z
2022-03-30T00:04:06.000Z
test/support/repos.ex
ottobar/paper_trail
046590026ec50605f3cabfaf48354b8acbf969a9
[ "MIT" ]
125
2016-12-13T14:28:45.000Z
2022-03-01T00:07:06.000Z
test/support/repos.ex
ottobar/paper_trail
046590026ec50605f3cabfaf48354b8acbf969a9
[ "MIT" ]
80
2016-09-09T02:12:41.000Z
2022-03-29T20:51:12.000Z
defmodule PaperTrail.Repo do use Ecto.Repo, otp_app: :paper_trail, adapter: Ecto.Adapters.Postgres end defmodule PaperTrail.UUIDRepo do use Ecto.Repo, otp_app: :paper_trail, adapter: Ecto.Adapters.Postgres end defmodule PaperTrail.UUIDWithCustomNameRepo do use Ecto.Repo, otp_app: :paper_trail, adapter: Ecto.Adapters.Postgres end defmodule User do use Ecto.Schema import Ecto.Changeset schema "users" do field(:token, :string) field(:username, :string) timestamps() end def changeset(model, params \\ %{}) do model |> cast(params, [:token, :username]) |> validate_required([:token, :username]) end end
21.032258
71
0.722393
793a50605a327b34a24816a0e8d30def44d49e18
2,998
exs
Elixir
test/booklist_web/controllers/library_controller_test.exs
allen-garvey/booklist-phoenix
b3c87713d742b64684c222cd3e5869dc9fbd2bd2
[ "MIT" ]
4
2019-10-04T16:11:15.000Z
2021-08-18T21:00:13.000Z
apps/booklist/test/booklist_web/controllers/library_controller_test.exs
allen-garvey/phoenix-umbrella
1d444bbd62a5e7b5f51d317ce2be71ee994125d5
[ "MIT" ]
5
2020-03-16T23:52:25.000Z
2021-09-03T16:52:17.000Z
test/booklist_web/controllers/library_controller_test.exs
allen-garvey/booklist-phoenix
b3c87713d742b64684c222cd3e5869dc9fbd2bd2
[ "MIT" ]
null
null
null
defmodule BooklistWeb.LibraryControllerTest do use BooklistWeb.ConnCase alias Booklist.Admin @create_attrs %{name: "some name", super_search_key: "some super_search_key", url: "some url"} @update_attrs %{name: "some updated name", super_search_key: "some updated super_search_key", url: "some updated url"} @invalid_attrs %{name: nil, super_search_key: nil, url: nil} def fixture(:library) do {:ok, library} = Admin.create_library(@create_attrs) library end describe "index" do test "lists all libraries", %{conn: conn} do conn = get(conn, Routes.library_path(conn, :index)) assert html_response(conn, 200) =~ "Listing Libraries" end end describe "new library" do test "renders form", %{conn: conn} do conn = get(conn, Routes.library_path(conn, :new)) assert html_response(conn, 200) =~ "New Library" end end describe "create library" do test "redirects to show when data is valid", %{conn: conn} do conn = post(conn, Routes.library_path(conn, :create), library: @create_attrs) assert %{id: id} = redirected_params(conn) assert redirected_to(conn) == Routes.library_path(conn, :show, id) conn = get(conn, Routes.library_path(conn, :show, id)) assert html_response(conn, 200) =~ "Show Library" end test "renders errors when data is invalid", %{conn: conn} do conn = post(conn, Routes.library_path(conn, :create), library: @invalid_attrs) assert html_response(conn, 200) =~ "New Library" end end describe "edit library" do setup [:create_library] test "renders form for editing chosen library", %{conn: conn, library: library} do conn = get(conn, Routes.library_path(conn, :edit, library)) assert html_response(conn, 200) =~ "Edit Library" end end describe "update library" do setup [:create_library] test "redirects when data is valid", %{conn: conn, library: library} do conn = put(conn, Routes.library_path(conn, :update, library), library: @update_attrs) assert redirected_to(conn) == Routes.library_path(conn, :show, library) conn = get(conn, Routes.library_path(conn, :show, library)) assert html_response(conn, 200) =~ "some updated name" end test "renders errors when data is invalid", %{conn: conn, library: library} do conn = put(conn, Routes.library_path(conn, :update, library), library: @invalid_attrs) assert html_response(conn, 200) =~ "Edit Library" end end describe "delete library" do setup [:create_library] test "deletes chosen library", %{conn: conn, library: library} do conn = delete(conn, Routes.library_path(conn, :delete, library)) assert redirected_to(conn) == Routes.library_path(conn, :index) assert_error_sent 404, fn -> get(conn, Routes.library_path(conn, :show, library)) end end end defp create_library(_) do library = fixture(:library) {:ok, library: library} end end
33.685393
120
0.676785
793a5b743632b999571a83994d44531863403f41
2,345
ex
Elixir
lib/nx_math.ex
zacky1972/nx_math
c8995ece124287ddc1af8c88eefdd21b79d2e9c4
[ "Apache-2.0" ]
null
null
null
lib/nx_math.ex
zacky1972/nx_math
c8995ece124287ddc1af8c88eefdd21b79d2e9c4
[ "Apache-2.0" ]
null
null
null
lib/nx_math.ex
zacky1972/nx_math
c8995ece124287ddc1af8c88eefdd21b79d2e9c4
[ "Apache-2.0" ]
null
null
null
defmodule NxMath do import Nx.Defn @moduledoc """ Documentation for `NxMath`. """ @log2 Nx.log(2) defnp factorial(x) do {factorial, _} = while {factorial = 1, x}, Nx.greater(x, 1) do {factorial * x, x - 1} end factorial end defnp broadcast(s, t, {type, bit}) do Nx.broadcast(Nx.tensor(s, type: {type, bit}), Nx.shape(t)) end defnp c(n) do if n == 1 do 1 - Nx.log(2) else -Nx.power(Nx.log(2), n) end end defnp(f(x, i), do: c(i) / factorial(i) * Nx.power(x, i)) @doc """ Calculates the exponential of each element in the tensor. This argorithm is based on ["Fast Exponential Computation on SIMD Architecture" by A. Cristiano et al., in the proceedings *HiPEAC 2015: 1st Workshop On Approximate Computing (WAPCO),* Amsterdam, NL, Jan, 2015, DOI:10.13140/2.1.4362.3207.](https://www.researchgate.net/publication/272178514_Fast_Exponential_Computation_on_SIMD_Architectures) ## Examples iex> NxMath.exp16(0) #Nx.Tensor< f16 1.0 > """ defn exp16(t0) do t0 = rewrite_types( t0, max_float_type: {:f, 16}, max_signed_type: {:f, 16}, max_unsigned_type: {:f, 16} ) greater_equal_12 = Nx.greater_equal(t0, 12) less_12 = Nx.less(t0, 12) t = (t0 / @log2) |> Nx.as_type({:f, 16}) xf = (t - Nx.floor(t)) |> Nx.as_type({:f, 16}) {kxf, _, _} = while {kxf = broadcast(0, t, {:f, 16}), n = 1, xf}, Nx.less(n, 4) do { (kxf + f(xf, n)) |> Nx.as_type({:f, 16}), n + 1, xf } end is_zero = Nx.equal(t, 0) isnt_zero = Nx.not_equal(t, 0) value_zero = is_zero * broadcast(1, t, {:f, 16}) value = Nx.round(1024 * (t - kxf + 15) * less_12) |> Nx.as_type({:u, 16}) is_inf = Nx.logical_or(Nx.greater(value, 0x7BFF), greater_equal_12) isnt_inf = Nx.logical_or(Nx.greater(value, 0x7BFF), greater_equal_12) |> Nx.logical_not() value_not_zero = (Nx.logical_and(isnt_inf, isnt_zero) * value) |> Nx.as_type({:u, 16}) |> Nx.bitcast({:f, 16}) value_not_inf = (value_zero + value_not_zero) |> Nx.bitcast({:u, 16}) (value_not_inf + is_inf * 0x7C00) |> Nx.as_type({:u, 16}) |> Nx.bitcast({:f, 16}) end end
22.76699
133
0.562047
793a68359e8ed0652af12ad76f1c50541f6135bc
1,026
exs
Elixir
integration_test/cases/browser/visible_test.exs
carl-al/wallaby
a4c9811902370b15db17fc62d451035ee7464eea
[ "MIT" ]
1
2019-01-30T12:08:17.000Z
2019-01-30T12:08:17.000Z
integration_test/cases/browser/visible_test.exs
carl-al/wallaby
a4c9811902370b15db17fc62d451035ee7464eea
[ "MIT" ]
2
2019-04-10T08:23:27.000Z
2021-01-25T16:37:23.000Z
integration_test/cases/browser/visible_test.exs
carl-al/wallaby
a4c9811902370b15db17fc62d451035ee7464eea
[ "MIT" ]
1
2019-01-29T16:03:55.000Z
2019-01-29T16:03:55.000Z
defmodule Wallaby.Integration.Browser.VisibleTest do use Wallaby.Integration.SessionCase, async: true describe "visible?/1" do setup :visit_page test "determines if the element is visible to the user", %{page: page} do page |> find(Query.css("#visible")) |> Element.visible? |> assert page |> find(Query.css("#invisible", visible: false)) |> Element.visible? |> refute end test "handles elements that are not on the page", %{page: page} do element = find(page, Query.css("#off-the-page", visible: false)) assert Element.visible?(element) == false end end describe "visible?/2" do setup :visit_page test "returns a boolean", %{page: page} do assert page |> visible?(Query.css("#visible")) == true assert page |> visible?(Query.css("#invisible")) == false end end def visit_page(%{session: session}) do page = session |> visit("page_1.html") {:ok, page: page} end end
22.304348
77
0.607212
793a830bad84822485778174937449344a2a8ff7
2,578
ex
Elixir
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/client_user.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/client_user.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/client_user.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.AdExchangeBuyer.V2beta1.Model.ClientUser do @moduledoc """ A client user is created under a client buyer and has restricted access to the Marketplace and certain other sections of the Authorized Buyers UI based on the role granted to the associated client buyer. The only way a new client user can be created is via accepting an email invitation (see the accounts.clients.invitations.create method). All fields are required unless otherwise specified. ## Attributes * `clientAccountId` (*type:* `String.t`, *default:* `nil`) - Numerical account ID of the client buyer with which the user is associated; the buyer must be a client of the current sponsor buyer. The value of this field is ignored in an update operation. * `email` (*type:* `String.t`, *default:* `nil`) - User's email address. The value of this field is ignored in an update operation. * `status` (*type:* `String.t`, *default:* `nil`) - The status of the client user. * `userId` (*type:* `String.t`, *default:* `nil`) - The unique numerical ID of the client user that has accepted an invitation. The value of this field is ignored in an update operation. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :clientAccountId => String.t(), :email => String.t(), :status => String.t(), :userId => String.t() } field(:clientAccountId) field(:email) field(:status) field(:userId) end defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.ClientUser do def decode(value, options) do GoogleApi.AdExchangeBuyer.V2beta1.Model.ClientUser.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.ClientUser do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.805556
105
0.715283
793a8feed9b4ceb832c70b3fd6928ac8c2e8ed82
2,826
ex
Elixir
lib/asciinema/asciicasts/asciicast.ex
spearheadsys/asciinema-server
6c8874e5dcfbbf9be176f831dd1ea421c43d375f
[ "Apache-2.0" ]
893
2017-09-14T14:18:29.000Z
2022-03-31T21:45:08.000Z
lib/asciinema/asciicasts/asciicast.ex
spearheadsys/asciinema-server
6c8874e5dcfbbf9be176f831dd1ea421c43d375f
[ "Apache-2.0" ]
103
2017-09-29T22:15:33.000Z
2022-03-27T21:47:43.000Z
lib/asciinema/asciicasts/asciicast.ex
spearheadsys/asciinema-server
6c8874e5dcfbbf9be176f831dd1ea421c43d375f
[ "Apache-2.0" ]
152
2017-09-07T12:43:15.000Z
2022-03-10T18:47:47.000Z
defmodule Asciinema.Asciicasts.Asciicast do use Ecto.Schema import Ecto.Changeset alias Asciinema.Accounts.User alias Asciinema.Asciicasts.Asciicast @default_theme "asciinema" @timestamps_opts [type: :utc_datetime_usec] schema "asciicasts" do field :version, :integer field :filename, :string field :path, :string field :terminal_columns, :integer field :terminal_lines, :integer field :terminal_type, :string field :private, :boolean field :featured, :boolean field :secret_token, :string field :duration, :float field :title, :string field :description, :string field :theme_name, :string field :theme_fg, :string field :theme_bg, :string field :theme_palette, :string field :snapshot_at, :float field :snapshot, Asciinema.Ecto.Type.JsonArray field :command, :string field :shell, :string field :uname, :string field :user_agent, :string field :recorded_at, :utc_datetime_usec field :idle_time_limit, :float field :views_count, :integer, default: 0 field :archivable, :boolean, default: true field :archived_at, :utc_datetime_usec timestamps(inserted_at: :created_at) belongs_to :user, User # legacy field :stdout_data, :string field :stdout_timing, :string end defimpl Phoenix.Param, for: Asciicast do def to_param(%Asciicast{private: true, secret_token: secret_token}) do secret_token end def to_param(%Asciicast{id: id}) do Integer.to_string(id) end end defp changeset(struct, attrs) do struct |> cast(attrs, [:title, :private, :snapshot_at]) |> validate_required([:private]) end def create_changeset(struct, attrs) do struct |> changeset(attrs) |> cast(attrs, [ :version, :duration, :terminal_columns, :terminal_lines, :terminal_type, :command, :shell, :uname, :user_agent, :recorded_at, :theme_fg, :theme_bg, :theme_palette, :idle_time_limit, :snapshot ]) |> validate_required([:user_id, :version, :duration, :terminal_columns, :terminal_lines]) |> generate_secret_token end def update_changeset(struct, attrs) do struct |> changeset(attrs) |> cast(attrs, [:description, :theme_name]) end def snapshot_changeset(struct, snapshot) do cast(struct, %{snapshot: snapshot}, [:snapshot]) end defp generate_secret_token(changeset) do put_change(changeset, :secret_token, Crypto.random_token(25)) end def snapshot_at(%Asciicast{snapshot_at: snapshot_at, duration: duration}) do snapshot_at || duration / 2 end def theme_name(%Asciicast{theme_name: a_theme_name}, %User{theme_name: u_theme_name}) do a_theme_name || u_theme_name || @default_theme end end
25.459459
93
0.681529
793abab0df34f0c37b727c74c61268afa0427cb0
150
ex
Elixir
elixir/64.ex
merxer/kata
5dbbca8b4173029f9311398148de9437a329cf9a
[ "MIT" ]
null
null
null
elixir/64.ex
merxer/kata
5dbbca8b4173029f9311398148de9437a329cf9a
[ "MIT" ]
null
null
null
elixir/64.ex
merxer/kata
5dbbca8b4173029f9311398148de9437a329cf9a
[ "MIT" ]
null
null
null
defmodule Example do @attr "one" def first, do: @attr @attr "two" def second, do: @attr end IO.puts "#{Example.first} #{Example.second}"
11.538462
44
0.633333
793acd891a7dcce4a3c61bcfffc209e66796e202
385
ex
Elixir
test/support/commands/increment_counter.ex
toniqsystems/event_store
2d3c8cb2b477bc0e3ef2dc048a924f9874e0abe0
[ "Apache-2.0" ]
103
2018-02-09T23:13:21.000Z
2021-08-18T04:22:41.000Z
test/support/commands/increment_counter.ex
tonic-sys/event_store
2d3c8cb2b477bc0e3ef2dc048a924f9874e0abe0
[ "Apache-2.0" ]
20
2018-04-05T16:10:53.000Z
2021-07-01T08:21:50.000Z
test/support/commands/increment_counter.ex
tonic-sys/event_store
2d3c8cb2b477bc0e3ef2dc048a924f9874e0abe0
[ "Apache-2.0" ]
3
2018-09-13T06:03:10.000Z
2019-07-11T15:22:53.000Z
defmodule Maestro.SampleAggregate.Commands.IncrementCounter do @moduledoc """ increment counter command """ alias Maestro.Types.Event @behaviour Maestro.Aggregate.CommandHandler def eval(aggregate, _command) do [ %Event{ aggregate_id: aggregate.id, type: "counter_incremented", body: %{"message" => "increment"} } ] end end
19.25
62
0.657143
793aec3f9a863bb11804aa791b0e728763c4224e
1,113
exs
Elixir
test/recurly/transaction_test.exs
calibr/recurly-client-elixir
a1160a10f90e0919adacf39bd95df3784e11fdcc
[ "MIT" ]
8
2016-08-11T00:45:46.000Z
2020-05-04T18:55:48.000Z
test/recurly/transaction_test.exs
calibr/recurly-client-elixir
a1160a10f90e0919adacf39bd95df3784e11fdcc
[ "MIT" ]
10
2016-08-15T20:01:56.000Z
2019-05-10T02:09:35.000Z
test/recurly/transaction_test.exs
calibr/recurly-client-elixir
a1160a10f90e0919adacf39bd95df3784e11fdcc
[ "MIT" ]
4
2017-10-16T14:29:58.000Z
2019-05-09T23:20:56.000Z
defmodule Recurly.TransactionTest do use ExUnit.Case, async: true alias Recurly.Transaction import Utils @readable_fields ~w( account action amount_in_cents currency details invoice ip_address original_transaction payment_method recurring_type reference refundable_type source subscription tax_in_cents test_type transaction_code uuid voidable_type )a @writeable_fields ~w( action amount_in_cents currency ip_address payment_method recurring_type reference refundable_type source tax_in_cents test_type transaction_code uuid voidable_type )a test "should maintain the list of writeable fields" do compare_writeable_fields(Transaction, @writeable_fields) end test "should maintain the list of readable fields" do compare_readable_fields(Transaction, @readable_fields) end test "Transactions#path should resolve to the transactions endpoint" do uuid = "abcdef1234567890" assert Transaction.path(uuid) == "/transactions/#{uuid}" end end
19.189655
73
0.71788
793aed93081a2f58437cd1ffc953b6aed6b06041
1,483
ex
Elixir
clients/you_tube/lib/google_api/you_tube/v3/model/activity_content_details_upload.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/you_tube/lib/google_api/you_tube/v3/model/activity_content_details_upload.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/you_tube/lib/google_api/you_tube/v3/model/activity_content_details_upload.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.YouTube.V3.Model.ActivityContentDetailsUpload do @moduledoc """ Information about the uploaded video. ## Attributes * `videoId` (*type:* `String.t`, *default:* `nil`) - The ID that YouTube uses to uniquely identify the uploaded video. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :videoId => String.t() | nil } field(:videoId) end defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.ActivityContentDetailsUpload do def decode(value, options) do GoogleApi.YouTube.V3.Model.ActivityContentDetailsUpload.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.ActivityContentDetailsUpload do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
31.553191
122
0.745111
793af3eae50272ad79226b144365de9a0dd0c819
5,461
exs
Elixir
priv/repo/seeds.exs
ClubNix/academy
962be0defc1d8eedc5d19ac0a65e931c794c6538
[ "MIT" ]
3
2016-06-18T17:46:14.000Z
2020-01-21T03:19:41.000Z
priv/repo/seeds.exs
ClubNix/academy
962be0defc1d8eedc5d19ac0a65e931c794c6538
[ "MIT" ]
18
2016-06-18T18:05:43.000Z
2018-03-06T08:19:41.000Z
priv/repo/seeds.exs
ClubNix/academy
962be0defc1d8eedc5d19ac0a65e931c794c6538
[ "MIT" ]
3
2016-10-26T19:51:06.000Z
2018-09-18T09:06:14.000Z
# Script for populating the database. You can run it as: # # mix run priv/repo/seeds.exs # # Inside the script, you can read and write to any of your # repositories directly: # # Academy.Repo.insert!(%Academy.SomeModel{}) # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong. alias Academy.Repo alias Academy.SkillCategory alias Academy.Skill programming_category = Repo.insert! %SkillCategory{name: "Programming Languages"} networking_category = Repo.insert! %SkillCategory{name: "Networking"} frameworks_category = Repo.insert! %SkillCategory{name: "Frameworks & CMS"} administration_category = Repo.insert! %SkillCategory{name: "Administration"} web_category = Repo.insert! %SkillCategory{name: "Web"} electronic_category = Repo.insert! %SkillCategory{name: "Electronic"} hardware_category = Repo.insert! %SkillCategory{name: "Hardware"} # ================= # == Programming == # ================= Repo.insert! %Skill{ name: "C", description: "The emblematic low-level language", category_id: programming_category.id } Repo.insert! %Skill{ name: "C++", description: "A low-level object oriented language", category_id: programming_category.id } Repo.insert! %Skill{ name: "Java", description: "A high-level object oriented language", category_id: programming_category.id } Repo.insert! %Skill{ name: "Python", description: "A simple, high-level, dynamic language", category_id: programming_category.id } Repo.insert! %Skill{ name: "Javascript", description: "A scripting language, usually used in the browser", category_id: programming_category.id } Repo.insert! %Skill{ name: "Elixir", description: "A functional, concurrent language", category_id: programming_category.id } Repo.insert! %Skill{ name: "OpenGL", description: "Graphical, cross-language programming interface", category_id: programming_category.id } # ================ # == Networking == # ================ Repo.insert! %Skill{ name: "NAT", description: "Network-Address-Translation", category_id: networking_category.id } Repo.insert! %Skill{ name: "TCP", description: "Transport-Control-Protocol", category_id: networking_category.id } Repo.insert! %Skill{ name: "IPv4", description: "Knowledge of IPv4 functionning", category_id: networking_category.id } Repo.insert! %Skill{ name: "DNS", description: "Domain-Name-system", category_id: networking_category.id } Repo.insert! %Skill{ name: "Reverse-Proxy", description: "Implementation of a reverse proxy", category_id: networking_category.id } # ================ # == Frameworks == # ================ Repo.insert! %Skill{ name: "Symphony", description: "A PHP web framework around the MVC model", category_id: frameworks_category.id } Repo.insert! %Skill{ name: "Wordpress", description: "A CMS based on PHP and MySQL", category_id: frameworks_category.id } Repo.insert! %Skill{ name: "Phoenix", description: "A productive web framework using Elixir", category_id: frameworks_category.id } # ==================== # == Administration == # ==================== Repo.insert! %Skill{ name: "GNU/Linux", description: "A POSIX compliant operating system.", category_id: administration_category.id } Repo.insert! %Skill{ name: "Debian / Ubuntu", description: "A Linux distribution", category_id: administration_category.id } Repo.insert! %Skill{ name: "RedHat / CentOS", description: "A Linux distribution", category_id: administration_category.id } Repo.insert! %Skill{ name: "Systemd", description: "A Linux init system", category_id: administration_category.id } Repo.insert! %Skill{ name: "System V", description: "A Linux init system", category_id: administration_category.id } Repo.insert! %Skill{ name: "Virtualization", description: "Create virtual operating system runtimes", category_id: administration_category.id } # ========= # == Web == # ========= Repo.insert! %Skill{ name: "HTML5", description: "HyperText Markup Language", category_id: web_category.id } Repo.insert! %Skill{ name: "CSS3", description: "Cascade Style Sheets", category_id: web_category.id } Repo.insert! %Skill{ name: "SVG", description: "Scalable Vector Graphics", category_id: web_category.id } # ================ # == Electronic == # ================ Repo.insert! %Skill{ name: "VHDL / Verilog", description: "Hardware description language", category_id: electronic_category.id } Repo.insert! %Skill{ name: "Arduino", description: "Open-Source microcontroller", category_id: electronic_category.id } Repo.insert! %Skill{ name: "PIC", description: "Embedded system microcontroller", category_id: electronic_category.id } # ============== # == Hardware == # ============== Repo.insert! %Skill{ name: "Processors", description: "Processors", category_id: hardware_category.id } Repo.insert! %Skill{ name: "Graphic Cards", description: "Graphic cards", category_id: hardware_category.id } Repo.insert! %Skill{ name: "Motherboards", description: "Motherboards", category_id: hardware_category.id }
23.437768
84
0.658854
793afcbb56513dc00971bd3e510432ef522538bc
2,697
exs
Elixir
test/facebook/config_test.exs
Copser/facebook.ex
bd7590a9d39d2d26ff1b06be790c2affc18a515d
[ "MIT" ]
138
2015-01-16T06:20:33.000Z
2022-01-14T20:15:50.000Z
test/facebook/config_test.exs
Copser/facebook.ex
bd7590a9d39d2d26ff1b06be790c2affc18a515d
[ "MIT" ]
57
2015-01-04T20:14:05.000Z
2021-04-07T13:25:01.000Z
test/facebook/config_test.exs
Copser/facebook.ex
bd7590a9d39d2d26ff1b06be790c2affc18a515d
[ "MIT" ]
70
2015-04-18T12:15:56.000Z
2022-02-02T07:08:33.000Z
defmodule Facebook.ConfigTest do use ExUnit.Case, async: false alias Facebook.Config describe "init/1" do test "uses default values when no other values are specified" do :ok = Application.stop(:facebook) {:ok, _} = Application.ensure_all_started(:facebook) assert Config.graph_url() == "https://graph.facebook.com" assert Config.request_conn_timeout() == nil end test "uses values from config when they are present" do :ok = Application.stop(:facebook) set_config(%{ graph_url: "https://graph.facebook.com/v1", request_conn_timeout: 100 }) {:ok, _} = Application.ensure_all_started(:facebook) assert Config.graph_url() == "https://graph.facebook.com/v1" assert Config.request_conn_timeout() == 100 end test "reads environment variables when {:system, _} tuple is used" do :ok = Application.stop(:facebook) set_config(%{ graph_url: {:system, "GRAPH_URL"}, request_conn_timeout: {:system, :integer, "REQUEST_CONN_TIMEOUT"} }) set_envs(%{ "GRAPH_URL" => "https://graph.facebook.com/v1", "REQUEST_CONN_TIMEOUT" => "100" }) {:ok, _} = Application.ensure_all_started(:facebook) assert Config.graph_url() == "https://graph.facebook.com/v1" assert Config.request_conn_timeout() == 100 end test "fails to start when {:system, _} tuple is used but env is missing" do :ok = Application.stop(:facebook) set_config(%{ graph_url: {:system, "GRAPH_URL"}, request_conn_timeout: {:system, :integer, "REQUEST_CONN_TIMEOUT"} }) assert {:error, {:facebook, {{:shutdown, {:failed_to_start_child, Facebook.Config, {%ArgumentError{ message: "could not fetch environment variable \"GRAPH_URL\" because it is not set" }, _}}}, {Facebook, :start, [:normal, []]}}}} = Application.ensure_all_started(:facebook) end end defp set_config(values) do original_config = Application.get_all_env(:facebook) for {key, value} <- values do Application.put_env(:facebook, key, value) end on_exit(fn -> for {key, _value} <- values do Application.put_env(:facebook, key, Keyword.get(original_config, key)) end {:ok, _} = Application.ensure_all_started(:facebook) end) end defp set_envs(envs) do for {key, value} <- envs do System.put_env(key, value) end on_exit(fn -> for {key, _value} <- envs do System.delete_env(key) end end) end end
28.389474
97
0.605858
793b05558e0721f2ca93ee3ba99430a8c69d7234
88
exs
Elixir
test/lucidboard_web/views/layout_view_test.exs
borodark/lucidboard
487a9a54053977ea9704121d4a6a4343012d4421
[ "MIT" ]
86
2019-01-07T20:49:04.000Z
2021-10-02T21:15:42.000Z
test/lucidboard_web/views/layout_view_test.exs
borodark/lucidboard
487a9a54053977ea9704121d4a6a4343012d4421
[ "MIT" ]
26
2019-03-27T12:06:52.000Z
2020-09-20T05:21:09.000Z
test/lucidboard_web/views/layout_view_test.exs
borodark/lucidboard
487a9a54053977ea9704121d4a6a4343012d4421
[ "MIT" ]
19
2015-01-06T19:02:49.000Z
2020-05-25T08:54:00.000Z
defmodule LucidboardWeb.LayoutViewTest do use LucidboardWeb.ConnCase, async: true end
22
41
0.840909
793b1726a557a7d7433b6b10588550a8aa49c410
155
ex
Elixir
lib/la_famiglia_web/plugs/timer.ex
cruessler/lafamiglia
084915a2d44a5e69fb6ad9321eac08ced0e3016a
[ "MIT" ]
5
2016-10-20T10:00:59.000Z
2017-11-19T08:14:18.000Z
lib/la_famiglia_web/plugs/timer.ex
cruessler/lafamiglia
084915a2d44a5e69fb6ad9321eac08ced0e3016a
[ "MIT" ]
39
2020-04-22T05:27:32.000Z
2022-03-13T17:22:26.000Z
lib/la_famiglia_web/plugs/timer.ex
cruessler/lafamiglia
084915a2d44a5e69fb6ad9321eac08ced0e3016a
[ "MIT" ]
null
null
null
defmodule LaFamigliaWeb.Plugs.Timer do def init(default), do: default def call(conn, _default) do LaFamiglia.DateTime.clock!() conn end end
17.222222
38
0.716129
793b29cfaaeec6494a4eef6862d473e86bc07982
1,965
exs
Elixir
clients/search_console/mix.exs
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/search_console/mix.exs
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/search_console/mix.exs
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "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.SearchConsole.Mixfile do use Mix.Project @version "0.17.0" def project() do [ app: :google_api_search_console, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/search_console" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.4"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Google Search Console API client library. The Search Console API provides access to both Search Console data (verified users only) and to public information on an URL basis (anyone) """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/search_console", "Homepage" => "https://developers.google.com/webmaster-tools/search-console-api/" } ] end end
29.328358
185
0.667176