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
797d441bcf9e1130928e98acc6711623c53f6a9f
3,118
ex
Elixir
lib/membrane/element/base/filter.ex
mkaput/membrane-core
f65ae3d847f2c10f3ab20d0c7aa75b0faa274ec7
[ "Apache-2.0" ]
null
null
null
lib/membrane/element/base/filter.ex
mkaput/membrane-core
f65ae3d847f2c10f3ab20d0c7aa75b0faa274ec7
[ "Apache-2.0" ]
null
null
null
lib/membrane/element/base/filter.ex
mkaput/membrane-core
f65ae3d847f2c10f3ab20d0c7aa75b0faa274ec7
[ "Apache-2.0" ]
null
null
null
defmodule Membrane.Element.Base.Filter do @moduledoc """ Module defining behaviour for filters - elements processing data. Behaviours for filters are specified, besides this place, in modules `Membrane.Element.Base.Mixin.CommonBehaviour`, `Membrane.Element.Base.Mixin.SourceBehaviour`, and `Membrane.Element.Base.Mixin.SinkBehaviour`. Filters can have both sink and source pads. Job of a usual filter is to receive some data on a sink pad, process the data and send it through the source pad. If these pads work in pull mode, which is the most common case, then filter is also responsible for receiving demands on the source pad and requesting them on the sink pad (for more details, see `c:Membrane.Element.Base.Mixin.SourceBehaviour.handle_demand/5` callback). Filters, like all elements, can of course have multiple pads if needed to provide more complex solutions. """ alias Membrane.{Buffer, Element} alias Element.Base.Mixin alias Element.{CallbackContext, Pad} @doc """ Callback that is to process buffers. For pads in pull mode it is called when buffers have been demanded (by returning `:demand` action from any callback). For pads in push mode it is invoked when buffers arrive. """ @callback handle_process( pad :: Pad.name_t(), buffers :: list(Buffer.t()), context :: CallbackContext.Process.t(), state :: Element.state_t() ) :: Mixin.CommonBehaviour.callback_return_t() @doc """ Callback that is to process buffers. In contrast to `c:handle_process/4`, it is passed only a single buffer. Called by default implementation of `c:handle_process/4`. """ @callback handle_process1( pad :: Pad.name_t(), buffer :: Buffer.t(), context :: CallbackContext.Process.t(), state :: Element.state_t() ) :: Mixin.CommonBehaviour.callback_return_t() defmacro __using__(_) do quote location: :keep do use Mixin.CommonBehaviour use Mixin.SourceBehaviour use Mixin.SinkBehaviour @behaviour unquote(__MODULE__) @impl true def membrane_element_type, do: :filter @impl true def handle_caps(_pad, caps, _context, state), do: {{:ok, forward: caps}, state} @impl true def handle_event(_pad, event, _context, state), do: {{:ok, forward: event}, state} @impl true def handle_demand(_pad, _size, _unit, _context, state), do: {{:error, :handle_demand_not_implemented}, state} @impl true def handle_process1(_pad, _buffer, _context, state), do: {{:error, :handle_process_not_implemented}, state} @impl true def handle_process(pad, buffers, context, state) do args_list = buffers |> Enum.map(&[pad, &1, context]) {{:ok, split: {:handle_process1, args_list}}, state} end defoverridable handle_caps: 4, handle_event: 4, handle_demand: 5, handle_process: 4, handle_process1: 4 end end end
34.644444
88
0.659076
797d4bfd06fa4332701c16524d9b806eee2eca4c
3,584
ex
Elixir
lib/safira/accounts/attendee.ex
cesium/safira
10dd45357c20e8afc22563f114f49ccb74008114
[ "MIT" ]
40
2018-07-04T19:13:45.000Z
2021-12-16T23:53:43.000Z
lib/safira/accounts/attendee.ex
cesium/safira
07a02f54f9454db1cfb5a510da68f40c47dcd916
[ "MIT" ]
94
2018-07-25T13:13:39.000Z
2022-02-15T04:09:42.000Z
lib/safira/accounts/attendee.ex
cesium/safira
10dd45357c20e8afc22563f114f49ccb74008114
[ "MIT" ]
5
2018-11-26T17:19:03.000Z
2021-02-23T08:09:37.000Z
defmodule Safira.Accounts.Attendee do use Ecto.Schema use Arc.Ecto.Schema import Ecto.Changeset alias Safira.Accounts.User alias Safira.Contest.Redeem alias Safira.Contest.Badge alias Safira.Contest.Referral alias Safira.Contest.DailyToken alias Safira.Store.Redeemable alias Safira.Store.Buy alias Safira.Roulette.Prize alias Safira.Roulette.AttendeePrize @primary_key {:id, :binary_id, autogenerate: true} @derive {Phoenix.Param, key: :id} schema "attendees" do field :nickname, :string field :volunteer, :boolean, default: false field :avatar, Safira.Avatar.Type field :name, :string field :token_balance, :integer, default: 0 field :entries, :integer, default: 0 field :discord_association_code, Ecto.UUID, autogenerate: true field :discord_id, :string belongs_to :user, User many_to_many :badges, Badge, join_through: Redeem has_many :referrals, Referral has_many :daily_tokens, DailyToken many_to_many :redeemables, Redeemable, join_through: Buy many_to_many :prizes, Prize, join_through: AttendeePrize field :badge_count, :integer, default: 0, virtual: true timestamps() end def changeset(attendee, attrs) do attendee |> cast(attrs, [:name, :nickname, :volunteer, :user_id]) |> cast_attachments(attrs, [:avatar]) |> cast_assoc(:user) |> validate_required([:name, :nickname, :volunteer]) |> validate_length(:nickname, min: 2, max: 15) |> validate_format(:nickname, ~r/^[a-zA-Z0-9]+([a-zA-Z0-9](_|-)[a-zA-Z0-9])*[a-zA-Z0-9]+$/) |> unique_constraint(:nickname) end def update_changeset_sign_up(attendee, attrs) do attendee |> cast(attrs, [:name, :nickname, :user_id]) |> cast_attachments(attrs, [:avatar]) |> cast_assoc(:user) |> validate_required([:name, :nickname]) |> validate_length(:nickname, min: 2, max: 15) |> validate_format(:nickname, ~r/^[a-zA-Z0-9]+([a-zA-Z0-9](_|-)[a-zA-Z0-9])*[a-zA-Z0-9]+$/) |> unique_constraint(:nickname) end def update_changeset(attendee, attrs) do attendee |> cast(attrs, [:nickname]) |> cast_attachments(attrs, [:avatar]) |> validate_required([:nickname]) |> validate_length(:nickname, min: 2, max: 15) |> validate_format(:nickname, ~r/^[a-zA-Z0-9]+([a-zA-Z0-9](_|-)[a-zA-Z0-9])*[a-zA-Z0-9]+$/) |> unique_constraint(:nickname) end def update_changeset_discord_association(attendee, attrs) do attendee |> cast(attrs, [:discord_id]) end def volunteer_changeset(attendee, attrs) do attendee |> cast(attrs, [:volunteer]) |> validate_required([:volunteer]) end def only_user_changeset(attendee, attrs) do attendee |> cast(attrs, [:user_id, :name]) |> cast_assoc(:user) |> validate_required([:user_id, :name]) end def update_token_balance_changeset(attendee, attrs) do attendee |> cast(attrs, [:token_balance]) |> validate_required([:token_balance]) |> validate_number(:token_balance, greater_than_or_equal_to: 0, message: "Token balance is insufficient.") end def update_entries_changeset(attendee, attrs) do attendee |> cast(attrs, [:entries]) |> validate_required([:entries]) |> validate_number(:entries, greater_than_or_equal_to: 0) end def update_on_redeem_changeset(attendee, attrs) do attendee |> cast(attrs, [:token_balance, :entries]) |> validate_required([:token_balance, :entries]) |> validate_number(:token_balance, greater_than_or_equal_to: 0) |> validate_number(:entries, greater_than_or_equal_to: 0) end end
32
110
0.686663
797d5e6a09dcb027d495484f1570390c69fcbc1e
1,621
ex
Elixir
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/get_publisher_profiles_by_account_id_response.ex
ericrwolfe/elixir-google-api
3dc0f17edd5e2d6843580c16ddae3bf84b664ffd
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/get_publisher_profiles_by_account_id_response.ex
ericrwolfe/elixir-google-api
3dc0f17edd5e2d6843580c16ddae3bf84b664ffd
[ "Apache-2.0" ]
null
null
null
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/get_publisher_profiles_by_account_id_response.ex
ericrwolfe/elixir-google-api
3dc0f17edd5e2d6843580c16ddae3bf84b664ffd
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.AdExchangeBuyer.V14.Model.GetPublisherProfilesByAccountIdResponse do @moduledoc """ ## Attributes - profiles (List[PublisherProfileApiProto]): Profiles for the requested publisher Defaults to: `null`. """ defstruct [ :profiles ] end defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V14.Model.GetPublisherProfilesByAccountIdResponse do import GoogleApi.AdExchangeBuyer.V14.Deserializer def decode(value, options) do value |> deserialize( :profiles, :list, GoogleApi.AdExchangeBuyer.V14.Model.PublisherProfileApiProto, options ) end end defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V14.Model.GetPublisherProfilesByAccountIdResponse do def encode(value, options) do GoogleApi.AdExchangeBuyer.V14.Deserializer.serialize_non_nil(value, options) end end
30.018519
104
0.763109
797d76535f57d8cc650d501bab528617bde0047f
1,232
exs
Elixir
clients/vision/mix.exs
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/vision/mix.exs
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/vision/mix.exs
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
defmodule GoogleApi.Vision.V1.Mixfile do use Mix.Project @version "0.9.0" def project() do [ app: :google_api_vision, version: @version, elixir: "~> 1.4", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/vision" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.1.0"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Integrates Google Vision features, including image labeling, face, logo, and landmark detection, optical character recognition (OCR), and detection of explicit content, into applications. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/vision", "Homepage" => "https://cloud.google.com/vision/" } ] end end
24.64
106
0.605519
797d96c8ed0eba9c4ccd8a6f9c68db7aff95f851
3,695
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/list_population_term.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/list_population_term.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/list_population_term.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DFAReporting.V33.Model.ListPopulationTerm do @moduledoc """ Remarketing List Population Rule Term. ## Attributes * `contains` (*type:* `boolean()`, *default:* `nil`) - Will be true if the term should check if the user is in the list and false if the term should check if the user is not in the list. This field is only relevant when type is set to LIST_MEMBERSHIP_TERM. False by default. * `negation` (*type:* `boolean()`, *default:* `nil`) - Whether to negate the comparison result of this term during rule evaluation. This field is only relevant when type is left unset or set to CUSTOM_VARIABLE_TERM or REFERRER_TERM. * `operator` (*type:* `String.t`, *default:* `nil`) - Comparison operator of this term. This field is only relevant when type is left unset or set to CUSTOM_VARIABLE_TERM or REFERRER_TERM. * `remarketingListId` (*type:* `String.t`, *default:* `nil`) - ID of the list in question. This field is only relevant when type is set to LIST_MEMBERSHIP_TERM. * `type` (*type:* `String.t`, *default:* `nil`) - List population term type determines the applicable fields in this object. If left unset or set to CUSTOM_VARIABLE_TERM, then variableName, variableFriendlyName, operator, value, and negation are applicable. If set to LIST_MEMBERSHIP_TERM then remarketingListId and contains are applicable. If set to REFERRER_TERM then operator, value, and negation are applicable. * `value` (*type:* `String.t`, *default:* `nil`) - Literal to compare the variable to. This field is only relevant when type is left unset or set to CUSTOM_VARIABLE_TERM or REFERRER_TERM. * `variableFriendlyName` (*type:* `String.t`, *default:* `nil`) - Friendly name of this term's variable. This is a read-only, auto-generated field. This field is only relevant when type is left unset or set to CUSTOM_VARIABLE_TERM. * `variableName` (*type:* `String.t`, *default:* `nil`) - Name of the variable (U1, U2, etc.) being compared in this term. This field is only relevant when type is set to null, CUSTOM_VARIABLE_TERM or REFERRER_TERM. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :contains => boolean(), :negation => boolean(), :operator => String.t(), :remarketingListId => String.t(), :type => String.t(), :value => String.t(), :variableFriendlyName => String.t(), :variableName => String.t() } field(:contains) field(:negation) field(:operator) field(:remarketingListId) field(:type) field(:value) field(:variableFriendlyName) field(:variableName) end defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.ListPopulationTerm do def decode(value, options) do GoogleApi.DFAReporting.V33.Model.ListPopulationTerm.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.ListPopulationTerm do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
54.338235
419
0.724763
797da6d8ceca028088aee973a03606dc322e43b8
2,368
ex
Elixir
lib/absinthe/phase/telemetry.ex
pulkit110/absinthe
fa2060307a401d0943bde72d08267602e4027889
[ "MIT" ]
4,101
2016-03-02T03:49:20.000Z
2022-03-31T05:46:01.000Z
lib/absinthe/phase/telemetry.ex
pulkit110/absinthe
fa2060307a401d0943bde72d08267602e4027889
[ "MIT" ]
889
2016-03-02T16:06:59.000Z
2022-03-31T20:24:12.000Z
lib/absinthe/phase/telemetry.ex
pulkit110/absinthe
fa2060307a401d0943bde72d08267602e4027889
[ "MIT" ]
564
2016-03-02T07:49:59.000Z
2022-03-06T14:40:59.000Z
defmodule Absinthe.Phase.Telemetry do @moduledoc """ Gather and report telemetry about an operation. """ @operation_start [:absinthe, :execute, :operation, :start] @operation_stop [:absinthe, :execute, :operation, :stop] @subscription_start [:absinthe, :subscription, :publish, :start] @subscription_stop [:absinthe, :subscription, :publish, :stop] use Absinthe.Phase def run(blueprint, options) do event = Keyword.fetch!(options, :event) do_run(blueprint, event, options) end defp do_run(blueprint, [:execute, :operation, :start], options) do id = :erlang.unique_integer() system_time = System.system_time() start_time_mono = System.monotonic_time() :telemetry.execute( @operation_start, %{system_time: system_time}, %{id: id, telemetry_span_context: id, blueprint: blueprint, options: options} ) {:ok, %{ blueprint | source: blueprint.input, telemetry: %{id: id, start_time_mono: start_time_mono} }} end defp do_run(blueprint, [:subscription, :publish, :start], options) do id = :erlang.unique_integer() system_time = System.system_time() start_time_mono = System.monotonic_time() :telemetry.execute( @subscription_start, %{system_time: system_time}, %{id: id, telemetry_span_context: id, blueprint: blueprint, options: options} ) {:ok, %{ blueprint | telemetry: %{id: id, start_time_mono: start_time_mono} }} end defp do_run(blueprint, [:subscription, :publish, :stop], options) do end_time_mono = System.monotonic_time() with %{id: id, start_time_mono: start_time_mono} <- blueprint.telemetry do :telemetry.execute( @subscription_stop, %{duration: end_time_mono - start_time_mono}, %{id: id, telemetry_span_context: id, blueprint: blueprint, options: options} ) end {:ok, blueprint} end defp do_run(blueprint, [:execute, :operation, :stop], options) do end_time_mono = System.monotonic_time() with %{id: id, start_time_mono: start_time_mono} <- blueprint.telemetry do :telemetry.execute( @operation_stop, %{duration: end_time_mono - start_time_mono}, %{id: id, telemetry_span_context: id, blueprint: blueprint, options: options} ) end {:ok, blueprint} end end
28.53012
85
0.663851
797dbcc601cf7ce28869218a5640bd9e5f0615cd
1,801
ex
Elixir
clients/games_configuration/lib/google_api/games_configuration/v1configuration/model/localized_string.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/games_configuration/lib/google_api/games_configuration/v1configuration/model/localized_string.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/games_configuration/lib/google_api/games_configuration/v1configuration/model/localized_string.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.GamesConfiguration.V1configuration.Model.LocalizedString do @moduledoc """ A localized string resource. ## Attributes * `kind` (*type:* `String.t`, *default:* `nil`) - Uniquely identifies the type of this resource. Value is always the fixed string `gamesConfiguration#localizedString`. * `locale` (*type:* `String.t`, *default:* `nil`) - The locale string. * `value` (*type:* `String.t`, *default:* `nil`) - The string value. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :kind => String.t(), :locale => String.t(), :value => String.t() } field(:kind) field(:locale) field(:value) end defimpl Poison.Decoder, for: GoogleApi.GamesConfiguration.V1configuration.Model.LocalizedString do def decode(value, options) do GoogleApi.GamesConfiguration.V1configuration.Model.LocalizedString.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.GamesConfiguration.V1configuration.Model.LocalizedString do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.981132
171
0.722932
797dfef36ac332fb8ac44225e69d51cfeab09ddf
282
ex
Elixir
lib/ex_euler.ex
weiland/ex_euler
8699a4e9bc3f83d80bdcf75429a7e724b8be5922
[ "WTFPL" ]
1
2017-01-02T19:14:16.000Z
2017-01-02T19:14:16.000Z
lib/ex_euler.ex
weiland/ex_euler
8699a4e9bc3f83d80bdcf75429a7e724b8be5922
[ "WTFPL" ]
null
null
null
lib/ex_euler.ex
weiland/ex_euler
8699a4e9bc3f83d80bdcf75429a7e724b8be5922
[ "WTFPL" ]
null
null
null
defmodule ExEuler do @moduledoc """ Documentation for ExEuler. """ @doc """ Show the results in the Terminal. """ def run do IO.puts "Problem 001" IO.inspect ExEuler.Problem001.solve IO.puts "Problem 002" IO.inspect ExEuler.Problem002.solve end end
17.625
39
0.666667
797e3a6376a0b0ee2188daa1d0078a2d2baaac9f
2,133
exs
Elixir
mix.exs
davydog187/phoenix_live_dashboard
c3dc00b2f5d825573163b10d9d7218612e7cca5b
[ "MIT" ]
1
2020-04-23T11:36:03.000Z
2020-04-23T11:36:03.000Z
mix.exs
davydog187/phoenix_live_dashboard
c3dc00b2f5d825573163b10d9d7218612e7cca5b
[ "MIT" ]
null
null
null
mix.exs
davydog187/phoenix_live_dashboard
c3dc00b2f5d825573163b10d9d7218612e7cca5b
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveDashboard.MixProject do use Mix.Project @version "0.2.0" def project do [ app: :phoenix_live_dashboard, version: @version, elixir: "~> 1.7", compilers: [:phoenix] ++ Mix.compilers(), elixirc_paths: elixirc_paths(Mix.env()), deps: deps(), package: package(), name: "LiveDashboard", docs: docs(), homepage_url: "http://www.phoenixframework.org", description: "Real-time performance dashboard for Phoenix" ] end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Run "mix help compile.app" to learn about applications. def application do [ mod: {Phoenix.LiveDashboard.Application, []}, extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:phoenix_live_view, "~> 0.12.0", phoenix_live_view_opts()}, {:telemetry_metrics, "~> 0.4.0"}, {:phoenix_html, "~> 2.14.1 or ~> 2.15"}, {:telemetry_poller, "~> 0.4", only: :dev}, {:phoenix_live_reload, "~> 1.2", only: :dev}, {:plug_cowboy, "~> 2.0", only: :dev}, {:jason, "~> 1.0", only: [:dev, :test, :docs]}, {:floki, "~> 0.24.0", only: :test}, {:ex_doc, "~> 0.21", only: :docs} ] end defp phoenix_live_view_opts do if path = System.get_env("LIVE_VIEW_PATH") do [path: path] else [] end end defp docs do [ main: "Phoenix.LiveDashboard", source_ref: "v#{@version}", source_url: "https://github.com/phoenixframework/phoenix_live_dashboard", extra_section: "GUIDES", extras: extras(), nest_modules_by_prefix: [Phoenix.LiveDashboard] ] end defp extras do [ "guides/metrics.md", "guides/request_logger.md" ] end defp package do [ maintainers: ["Michael Crumm", "Chris McCord", "José Valim"], licenses: ["MIT"], links: %{github: "https://github.com/phoenixframework/phoenix_live_dashboard"}, files: ~w(lib priv CHANGELOG.md LICENSE.md mix.exs README.md) ] end end
25.698795
85
0.595874
797e57401aa7406a1a6576f46cae32a987a4b8a2
79
exs
Elixir
apps/core/priv/repo/seeds/05_provision_influx_v3.exs
michaeljguarino/forge
50ee583ecb4aad5dee4ef08fce29a8eaed1a0824
[ "Apache-2.0" ]
59
2021-09-16T19:29:39.000Z
2022-03-31T20:44:24.000Z
apps/core/priv/repo/seeds/05_provision_influx_v3.exs
svilenkov/plural
ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026
[ "Apache-2.0" ]
111
2021-08-15T09:56:37.000Z
2022-03-31T23:59:32.000Z
apps/core/priv/repo/seeds/05_provision_influx_v3.exs
svilenkov/plural
ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026
[ "Apache-2.0" ]
4
2021-12-13T09:43:01.000Z
2022-03-29T18:08:44.000Z
import Botanist alias Core.Services.Metrics seed do Metrics.provision() end
11.285714
27
0.797468
797e5ac4bd602a3cbc8c0a36726ea49b9379be07
5,804
ex
Elixir
lib/ecto_mnesia/record/context/match_spec.ex
jdoig/ecto_mnesia
592cc47219a18158176e1445132370890a4f0be3
[ "MIT" ]
null
null
null
lib/ecto_mnesia/record/context/match_spec.ex
jdoig/ecto_mnesia
592cc47219a18158176e1445132370890a4f0be3
[ "MIT" ]
null
null
null
lib/ecto_mnesia/record/context/match_spec.ex
jdoig/ecto_mnesia
592cc47219a18158176e1445132370890a4f0be3
[ "MIT" ]
null
null
null
defmodule EctoMnesia.Record.Context.MatchSpec do @moduledoc """ This module provides a context that is able to rebuild Mnesia `match_spec` by `Ecto.Query` AST whenever new query is assigned to a context. Specs: - [QLC](http://erlang.org/doc/man/qlc.html) - [Match Specification](http://erlang.org/doc/apps/erts/match_spec.html) """ alias EctoMnesia.Record.Context defstruct head: [], conditions: [], body: [] def update(%Context{query: %Context.Query{sources: sources}} = context, %Ecto.Query{} = query) do %{context | match_spec: %{ context.match_spec | body: match_body(context, sources), head: match_head(context), conditions: match_conditions(query, sources, context) } } end def dump(%Context.MatchSpec{head: head, conditions: conditions, body: body}) do [{head, conditions, [body]}] end # Build match_spec head part (data placeholders) defp match_head(%Context{table: %Context.Table{name: table_name}} = context) do context |> Context.get_fields_placeholders() |> Enum.into([table_name]) |> List.to_tuple() end # Select was present defp match_body(%Context{query: %Context.Query{select: %Ecto.Query.SelectExpr{fields: expr}}} = context, sources) do expr |> select_fields(sources) |> Enum.map(&Context.find_field_placeholder!(&1, context)) end # Select wasn't present, so we select everything defp match_body(%Context{query: %Context.Query{select: select}} = context, _sources) when is_list(select) do Enum.map(select, &Context.find_field_placeholder!(&1, context)) end defp select_fields({:&, [], [0, fields, _]}, _sources), do: fields defp select_fields({{:., [], [{:&, [], [0]}, field]}, _, []}, _sources), do: [field] defp select_fields({:^, [], [_]} = expr, sources), do: [unbind(expr, sources)] defp select_fields(exprs, sources) when is_list(exprs) do Enum.flat_map(exprs, &select_fields(&1, sources)) end # Resolve params defp match_conditions(%Ecto.Query{wheres: wheres}, sources, context), do: match_conditions(wheres, sources, context, []) defp match_conditions([], _sources, _context, acc), do: acc defp match_conditions([%{expr: expr, params: params} | tail], sources, context, acc) do condition = condition_expression(expr, merge_sources(sources, params), context) match_conditions(tail, sources, context, [condition | acc]) end # `expr.params` seems to be always empty, but we need to deal with cases when it's not defp merge_sources(sources1, sources2) when is_list(sources1) and is_list(sources2), do: sources1 ++ sources2 defp merge_sources(sources, nil), do: sources # Unbinding parameters def condition_expression({:^, [], [_]} = binding, sources, _context), do: unbind(binding, sources) def condition_expression({op, [], [field, {:^, [], [_]} = binding]}, sources, context) do parameters = unbind(binding, sources) condition_expression({op, [], [field, parameters]}, sources, context) end # `is_nil` is a special case when we need to :== with nil value def condition_expression({:is_nil, [], [field]}, sources, context) do {:==, condition_expression(field, sources, context), nil} end # `:in` is a special case when we need to expand it to multiple `:or`'s def condition_expression({:in, [], [field, parameters]}, sources, context) when is_list(parameters) do field = condition_expression(field, sources, context) expr = parameters |> unbind(sources) |> Enum.map(fn parameter -> {:==, field, condition_expression(parameter, sources, context)} end) if expr == [] do {:==, true, false} # Hack to return zero values else expr |> List.insert_at(0, :or) |> List.to_tuple() end end def condition_expression({:in, [], [_field, _parameters]}, _sources, _context) do raise RuntimeError, "Complex :in queries is not supported by the Mnesia adapter." end # Conditions that have one argument. Functions (is_nil, not). def condition_expression({op, [], [field]}, sources, context) do {guard_function_operation(op), condition_expression(field, sources, context)} end # Other conditions with multiple arguments (<, >, ==, !=, etc) def condition_expression({op, [], [field, parameter]}, sources, context) do { guard_function_operation(op), condition_expression(field, sources, context), condition_expression(parameter, sources, context) } end # Fields def condition_expression({{:., [], [{:&, [], [0]}, field]}, _, []}, _sources, context) do Context.find_field_placeholder!(field, context) end # Recursively expand ecto query expressions and build conditions def condition_expression({op, [], [left, right]}, sources, context) do { guard_function_operation(op), condition_expression(left, sources, context), condition_expression(right, sources, context) } end # Another part of this function is to use binded variables values def condition_expression(%Ecto.Query.Tagged{value: value}, _sources, _context), do: value def condition_expression(raw_value, sources, _context), do: unbind(raw_value, sources) def unbind({:^, [], [start_at, end_at]}, sources) do Enum.slice(sources, Range.new(start_at, end_at)) end def unbind({:^, [], [index]}, sources) do sources |> Enum.at(index) |> get_binded() end def unbind(value, _sources), do: value # Binded variable value defp get_binded({value, {_, _}}), do: value defp get_binded(value), do: value # Convert Ecto.Query operations to MatchSpec analogs. (Only ones that doesn't match.) defp guard_function_operation(:!=), do: :'/=' defp guard_function_operation(:<=), do: :'=<' defp guard_function_operation(op), do: op end
37.445161
118
0.679704
797e70a8fd1cf2edc26563ae13a9e63889aa116c
1,348
ex
Elixir
lib/iris.ex
jrbart/deeppipe2
ac242f680c8a523dca0cd7bb1cbe7192823ee356
[ "BSD-2-Clause" ]
99
2020-02-12T23:15:57.000Z
2022-01-09T08:05:29.000Z
lib/iris.ex
jrbart/deeppipe2
ac242f680c8a523dca0cd7bb1cbe7192823ee356
[ "BSD-2-Clause" ]
27
2020-03-01T09:54:55.000Z
2021-09-18T21:38:43.000Z
lib/iris.ex
jrbart/deeppipe2
ac242f680c8a523dca0cd7bb1cbe7192823ee356
[ "BSD-2-Clause" ]
8
2020-04-19T22:14:32.000Z
2021-03-12T07:05:10.000Z
defmodule Iris do import Network alias Deeppipe, as: DP @moduledoc """ test with iris dataset """ defnetwork init_network0(_x) do _x |> w(4, 100) |> b(100) |> relu |> w(100, 50) |> b(50) |> relu |> w(50, 3) |> b(3) |> softmax end def sgd(m, n) do image = train_image() onehot = train_label_onehot() network = init_network0(0) test_image = image test_label = train_label() DP.train(network, image, onehot, test_image, test_label, :cross, :sgd, m, n) end def train_image() do {_, x} = File.read("iris/iris.data") x |> String.split("\n") |> Enum.take(150) |> Enum.map(fn y -> train_image1(y) end) end def train_image1(x) do x1 = x |> String.split(",") |> Enum.take(4) x1 |> Enum.map(fn y -> String.to_float(y) end) |> DP.normalize(0, 1) end def train_label() do {_, x} = File.read("iris/iris.data") x |> String.split("\n") |> Enum.take(150) |> Enum.map(fn y -> train_label1(y) end) end def train_label1(x) do [x1] = x |> String.split(",") |> Enum.drop(4) cond do x1 == "Iris-setosa" -> 0 x1 == "Iris-versicolor" -> 1 x1 == "Iris-virginica" -> 2 end end def train_label_onehot() do train_label() |> Enum.map(fn x -> DP.to_onehot(x, 2) end) end end
18.985915
80
0.551187
797e99f3140d45f2242893cf5ba0519966af9939
2,811
ex
Elixir
clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/google_devtools_remoteworkers_v1test2_file_metadata.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/google_devtools_remoteworkers_v1test2_file_metadata.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/google_devtools_remoteworkers_v1test2_file_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.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2FileMetadata do @moduledoc """ The metadata for a file. Similar to the equivalent message in the Remote Execution API. ## Attributes * `contents` (*type:* `String.t`, *default:* `nil`) - If the file is small enough, its contents may also or alternatively be listed here. * `digest` (*type:* `GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2Digest.t`, *default:* `nil`) - A pointer to the contents of the file. The method by which a client retrieves the contents from a CAS system is not defined here. * `isExecutable` (*type:* `boolean()`, *default:* `nil`) - Properties of the file * `path` (*type:* `String.t`, *default:* `nil`) - The path of this file. If this message is part of the CommandOutputs.outputs fields, the path is relative to the execution root and must correspond to an entry in CommandTask.outputs.files. If this message is part of a Directory message, then the path is relative to the root of that directory. All paths MUST be delimited by forward slashes. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :contents => String.t() | nil, :digest => GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2Digest.t() | nil, :isExecutable => boolean() | nil, :path => String.t() | nil } field(:contents) field(:digest, as: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2Digest ) field(:isExecutable) field(:path) end defimpl Poison.Decoder, for: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2FileMetadata do def decode(value, options) do GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2FileMetadata.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemoteworkersV1test2FileMetadata do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
41.955224
396
0.737816
797eafd6b963f226c20a6e14fa0059f96aee5d09
12,452
ex
Elixir
lib/repo.ex
superfly/fly_postgres_elixir
a8e0580e750cf2f3ee66c74a8f329a2848ebf991
[ "Apache-2.0" ]
36
2021-11-03T04:48:21.000Z
2022-03-19T20:13:41.000Z
lib/repo.ex
superfly/fly_postgres_elixir
a8e0580e750cf2f3ee66c74a8f329a2848ebf991
[ "Apache-2.0" ]
13
2021-11-01T23:01:38.000Z
2022-03-23T13:40:14.000Z
lib/repo.ex
superfly/fly_postgres_elixir
a8e0580e750cf2f3ee66c74a8f329a2848ebf991
[ "Apache-2.0" ]
6
2021-11-11T20:28:59.000Z
2022-03-14T05:55:09.000Z
defmodule Fly.Repo do @moduledoc """ This wraps the built-in `Ecto.Repo` functions to proxy writable functions like insert, update and delete to be performed on the an Elixir node in the primary region. To use it, rename your existing repo module and add a new module with the same name as your original repo like this. Original code: ```elixir defmodule MyApp.Repo do use Ecto.Repo, otp_app: :my_app, adapter: Ecto.Adapters.Postgres end ``` Changes to: ```elixir defmodule MyApp.Repo.Local do use Ecto.Repo, otp_app: :my_app, adapter: Ecto.Adapters.Postgres # Dynamically configure the database url based for runtime environment. def init(_type, config) do {:ok, Keyword.put(config, :url, Fly.Postgres.database_url())} end end defmodule Core.Repo do use Fly.Repo, local_repo: MyApp.Repo.Local end ``` Using the same name allows your existing code to seamlessly work with the new repo. When explicitly managing database transactions like using Multi or `start_transaction`, when used to modify data, those functions should be called by an RPC so they run in the primary region. ```elixir Fly.RPC.rpc_region(:primary, MyModule, :my_function_that_uses_multi, [my, args], opts) ``` """ defmacro __using__(opts) do quote bind_quoted: [opts: opts] do @local_repo Keyword.fetch!(opts, :local_repo) @timeout Keyword.get(opts, :timeout, 5_000) @replication_timeout Keyword.get(opts, :replication_timeout, 5_000) # Here we are injecting as little as possible then calling out to the # library functions. @doc """ See `Ecto.Repo.config/0` for full documentation. """ @spec config() :: Keyword.t() def config do @local_repo.config() end @doc """ Calculate the given `aggregate`. See `Ecto.Repo.aggregate/3` for full documentation. """ def aggregate(queryable, aggregate, opts \\ []) do unquote(__MODULE__).__exec_local__(:aggregate, [queryable, aggregate, opts]) end @doc """ Calculate the given `aggregate` over the given `field`. See `Ecto.Repo.aggregate/4` for full documentation. """ def aggregate(queryable, aggregate, field, opts) do unquote(__MODULE__).__exec_local__(:aggregate, [queryable, aggregate, field, opts]) end @doc """ Fetches all entries from the data store matching the given query. See `Ecto.Repo.all/2` for full documentation. """ def all(queryable, opts \\ []) do unquote(__MODULE__).__exec_local__(:all, [queryable, opts]) end @doc """ Deletes a struct using its primary key. See `Ecto.Repo.delete/2` for full documentation. """ def delete(struct_or_changeset, opts \\ []) do unquote(__MODULE__).__exec_on_primary__(:delete, [struct_or_changeset, opts], opts) end @doc """ Same as `delete/2` but returns the struct or raises if the changeset is invalid. See `Ecto.Repo.delete!/2` for full documentation. """ def delete!(struct_or_changeset, opts \\ []) do unquote(__MODULE__).__exec_on_primary__(:delete!, [struct_or_changeset, opts], opts) end @doc """ Deletes all entries matching the given query. See `Ecto.Repo.delete_all/2` for full documentation. """ def delete_all(queryable, opts \\ []) do unquote(__MODULE__).__exec_on_primary__(:delete_all, [queryable, opts], opts) end @doc """ Checks if there exists an entry that matches the given query. See `Ecto.Repo.exists?/2` for full documentation. """ def exists?(queryable, opts \\ []) do unquote(__MODULE__).__exec_local__(:exists?, [queryable, opts]) end @doc """ Fetches a single struct from the data store where the primary key matches the given id. See `Ecto.Repo.get/3` for full documentation. """ def get(queryable, id, opts \\ []) do unquote(__MODULE__).__exec_local__(:get, [queryable, id, opts]) end @doc """ Similar to `get/3` but raises `Ecto.NoResultsError` if no record was found. See `Ecto.Repo.get!/3` for full documentation. """ def get!(queryable, id, opts \\ []) do unquote(__MODULE__).__exec_local__(:get!, [queryable, id, opts]) end @doc """ Fetches a single result from the query. See `Ecto.Repo.get_by/3` for full documentation. """ def get_by(queryable, clauses, opts \\ []) do unquote(__MODULE__).__exec_local__(:get_by, [queryable, clauses, opts]) end @doc """ Similar to `get_by/3` but raises `Ecto.NoResultsError` if no record was found. See `Ecto.Repo.get_by!/3` for full documentation. """ def get_by!(queryable, clauses, opts \\ []) do unquote(__MODULE__).__exec_local__(:get_by!, [queryable, clauses, opts]) end @doc """ Returns the atom name or pid of the current repository. See `Ecto.Repo.get_dynamic_repo/0` for full documentation. """ @spec get_dynamic_repo() :: Keyword.t() def get_dynamic_repo do @local_repo.get_dynamic_repo() end @doc """ Inserts a struct defined via Ecto.Schema or a changeset. See `Ecto.Repo.insert/2` for full documentation. """ def insert(struct_or_changeset, opts \\ []) do unquote(__MODULE__).__exec_on_primary__(:insert, [struct_or_changeset, opts], opts) end @doc """ Same as `insert/2` but returns the struct or raises if the changeset is invalid. See `Ecto.Repo.insert!/2` for full documentation. """ def insert!(struct_or_changeset, opts \\ []) do unquote(__MODULE__).__exec_on_primary__(:insert!, [struct_or_changeset, opts], opts) end @doc """ Inserts all entries into the repository. See `Ecto.Repo.insert_all/3` for full documentation. """ def insert_all(schema_or_source, entries_or_query, opts \\ []) do unquote(__MODULE__).__exec_on_primary__( :insert_all, [ schema_or_source, entries_or_query, opts ], opts ) end @doc """ Inserts or updates a changeset depending on whether the struct is persisted or not See `Ecto.Repo.insert_or_update/2` for full documentation. """ def insert_or_update(changeset, opts \\ []) do unquote(__MODULE__).__exec_on_primary__(:insert_or_update, [changeset, opts], opts) end @doc """ Same as `insert_or_update!/2` but returns the struct or raises if the changeset is invalid. See `Ecto.Repo.insert_or_update!/2` for full documentation. """ def insert_or_update!(changeset, opts \\ []) do unquote(__MODULE__).__exec_on_primary__(:insert_or_update!, [changeset, opts], opts) end @doc """ Fetches a single result from the query. See `Ecto.Repo.one/2` for full documentation. """ def one(queryable, opts \\ []) do unquote(__MODULE__).__exec_local__(:one, [queryable, opts]) end @doc """ Similar to a `one/2` but raises Ecto.NoResultsError if no record was found. See `Ecto.Repo.one!/2` for full documentation. """ def one!(queryable, opts \\ []) do unquote(__MODULE__).__exec_local__(:one!, [queryable, opts]) end @doc """ Preloads all associations on the given struct or structs. See `Ecto.Repo.preload/3` for full documentation. """ def preload(structs_or_struct_or_nil, preloads, opts \\ []) do unquote(__MODULE__).__exec_local__(:preload, [ structs_or_struct_or_nil, preloads, opts ]) end @doc """ A user customizable callback invoked for query-based operations. See `Ecto.Repo.preload/3` for full documentation. """ def prepare_query(operation, query, opts \\ []) do unquote(__MODULE__).__exec_local__(:prepare_query, [operation, query, opts]) end @doc """ Sets the dynamic repository to be used in further interactions. See `Ecto.Repo.put_dynamic_repo/1` for full documentation. """ def put_dynamic_repo(name_or_pid) do unquote(__MODULE__).__exec_local__(:put_dynamic_repo, [name_or_pid]) end @doc """ The same as `query`, but raises on invalid queries. See `Ecto.Adapters.SQL.query/4` for full documentation. """ def query(query, params \\ [], opts \\ []) do unquote(__MODULE__).__exec_local__(:query, [query, params, opts]) end @doc """ Run a custom SQL query. See `Ecto.Adapters.SQL.query!/4` for full documentation. """ def query!(query, params \\ [], opts \\ []) do unquote(__MODULE__).__exec_local__(:query!, [query, params, opts]) end @doc """ Reloads a given schema or schema list from the database. See `Ecto.Repo.reload/2` for full documentation. """ def reload(struct_or_structs, opts \\ []) do unquote(__MODULE__).__exec_local__(:reload, [struct_or_structs, opts]) end @doc """ Similar to `reload/2`, but raises when something is not found. See `Ecto.Repo.reload!/2` for full documentation. """ def reload!(struct_or_structs, opts \\ []) do unquote(__MODULE__).__exec_local__(:reload, [struct_or_structs, opts]) end @doc """ Rolls back the current transaction. Defaults to the primary database repo. Assumes the transaction was used for data modification. See `Ecto.Repo.rollback/1` for full documentation. """ def rollback(value) do unquote(__MODULE__).__exec_local__(:rollback, [value]) end @doc """ Returns a lazy enumerable that emits all entries from the data store matching the given query. See `Ecto.Repo.stream/2` for full documentation. """ def stream(queryable, opts \\ []) do unquote(__MODULE__).__exec_local__(:stream, [queryable, opts]) end @doc """ Runs the given function or Ecto.Multi inside a transaction. This defaults to the primary (writable) repo as it is assumed this is being used for data modification. Override to operate on the replica. See `Ecto.Repo.transaction/2` for full documentation. """ def transaction(fun_or_multi, opts \\ []) do unquote(__MODULE__).__exec_local__(:transaction, [fun_or_multi, opts]) end @doc """ Updates a changeset using its primary key. See `Ecto.Repo.update/2` for full documentation. """ def update(changeset, opts \\ []) do unquote(__MODULE__).__exec_on_primary__(:update, [changeset, opts], opts) end @doc """ Same as `update/2` but returns the struct or raises if the changeset is invalid. See `Ecto.Repo.update!/2` for full documentation. """ def update!(changeset, opts \\ []) do unquote(__MODULE__).__exec_on_primary__(:update!, [changeset, opts], opts) end @doc """ Updates all entries matching the given query with the given values. See `Ecto.Repo.update_all/3` for full documentation. """ def update_all(queryable, updates, opts \\ []) do unquote(__MODULE__).__exec_on_primary__(:update_all, [queryable, updates, opts], opts) end def __exec_local__(func, args) do apply(@local_repo, func, args) end def __exec_on_primary__(func, args, opts) do # Default behavior is to wait for replication. If `:await` is set to # false/falsey then skip the LSN query and waiting for replication. if Keyword.get(opts, :await, true) do rpc_timeout = Keyword.get(opts, :rpc_timeout, @timeout) replication_timeout = Keyword.get(opts, :replication_timeout, @replication_timeout) Fly.Postgres.rpc_and_wait(@local_repo, func, args, rpc_timeout: rpc_timeout, replication_timeout: replication_timeout, tracker: Keyword.get(opts, :tracker) ) else Fly.rpc_primary(@local_repo, func, args, timeout: @timeout) end end end end end
31.13
100
0.632669
797ec8c86fe3dcbc07acd84bb833b07c50cbbeef
549
ex
Elixir
deps/postgrex/lib/postgrex/extensions/bool.ex
rpillar/Top5_Elixir
9c450d2e9b291108ff1465dc066dfe442dbca822
[ "MIT" ]
null
null
null
deps/postgrex/lib/postgrex/extensions/bool.ex
rpillar/Top5_Elixir
9c450d2e9b291108ff1465dc066dfe442dbca822
[ "MIT" ]
null
null
null
deps/postgrex/lib/postgrex/extensions/bool.ex
rpillar/Top5_Elixir
9c450d2e9b291108ff1465dc066dfe442dbca822
[ "MIT" ]
null
null
null
defmodule Postgrex.Extensions.Bool do @moduledoc false import Postgrex.BinaryUtils, warn: false use Postgrex.BinaryExtension, send: "boolsend" def encode(_) do quote location: :keep do true -> <<1 :: int32, 1>> false -> <<1 :: int32, 0>> other -> raise DBConnection.EncodeError, Postgrex.Utils.encode_msg(other, "a boolean") end end def decode(_) do quote location: :keep do <<1 :: int32, 1>> -> true <<1 :: int32, 0>> -> false end end end
22.875
86
0.566485
797edd91648f7609ef6f16db65e207050f8592a3
7,086
ex
Elixir
lib/mix/tasks/prom_ex.gen.config.ex
keatz55/prom_ex
ccf1066f63982938a6f0116528b2d07b4960187a
[ "MIT" ]
null
null
null
lib/mix/tasks/prom_ex.gen.config.ex
keatz55/prom_ex
ccf1066f63982938a6f0116528b2d07b4960187a
[ "MIT" ]
null
null
null
lib/mix/tasks/prom_ex.gen.config.ex
keatz55/prom_ex
ccf1066f63982938a6f0116528b2d07b4960187a
[ "MIT" ]
null
null
null
defmodule Mix.Tasks.PromEx.Gen.Config do @moduledoc """ This Mix Task generates a PromEx config module in your project. This config file acts as a starting point with instructions on how to set up PromEx in your application, some default PromEx metrics plugins, and their accompanying dashboards. The following CLI flags are supported: ```md -d, --datasource The datasource that the dashboards will be reading from to populate their time series data. This `datasource` value should align with what is configured in Grafana from the Prometheus instance's `datasource_id`. -o, --otp_app The OTP application that PromEx is being installed in. This should be provided as the snake case atom (minus the leading colon). For example, if the `:app` value in your `mix.exs` file is `:my_cool_app`, this argument should be provided as `my_cool_app`. By default PromEx will read your `mix.exs` file to determine the OTP application value so this is an OPTIONAL argument. ``` """ @shortdoc "Generates a PromEx configuration module" use Mix.Task alias Mix.Shell.IO @impl true def run(args) do # Compile the project Mix.Task.run("compile") # Get CLI args %{otp_app: otp_app, datasource: datasource_id} = args |> parse_options() |> Map.put_new_lazy(:otp_app, fn -> Mix.Project.config() |> Keyword.get(:app) |> Atom.to_string() end) |> case do %{otp_app: _otp_app, datasource: _datasource_id} = required_args -> required_args _ -> raise "Missing required arguments. Run mix help prom_ex.gen.config for usage instructions" end # Generate relevant path info project_root = File.cwd!() path = Path.join([project_root, "lib", otp_app, "prom_ex.ex"]) dirname = Path.dirname(path) unless File.exists?(dirname) do raise "Required directory path #{dirname} does not exist. " <> "Be sure that the --otp-app argument or that you Mix project file is correct." end write_file = if File.exists?(path) do IO.yes?("File already exists at #{path}. Overwrite?") else true end if write_file do # Write out the config file create_config_file(path, otp_app, datasource_id) IO.info("Successfully wrote out #{path}") first_line = "| Be sure to follow the @moduledoc instructions in #{Macro.camelize(otp_app)}.PromEx |" line_length = String.length(first_line) - 2 second_line = "| to complete the PromEx setup process" <> String.duplicate(" ", line_length - 37) <> "|" divider = "+" <> String.duplicate("-", line_length) <> "+" IO.info(Enum.join(["", divider, first_line, second_line, divider], "\n")) else IO.info("Did not write file out to #{path}") end end defp parse_options(args) do cli_options = [otp_app: :string, datasource: :string] cli_aliases = [o: :otp_app, d: :datasource] args |> OptionParser.parse(aliases: cli_aliases, strict: cli_options) |> case do {options, _remaining_args, [] = _errors} -> Map.new(options) {_options, _remaining_args, errors} -> raise "Invalid CLI args were provided: #{inspect(errors)}" end end defp create_config_file(path, otp_app, datasource_id) do module_name = Macro.camelize(otp_app) assigns = [ datasource_id: datasource_id, module_name: module_name, otp_app: otp_app ] module_template = prom_ex_module_template() |> EEx.eval_string(assigns: assigns) path |> File.write!(module_template) end defp prom_ex_module_template do """ defmodule <%= @module_name %>.PromEx do @moduledoc \"\"\" Be sure to add the following to finish setting up PromEx: 1. Update your configuration (config.exs, dev.exs, prod.exs, releases.exs, etc) to configure the necessary bit of PromEx. Be sure to check out `PromEx.Config` for more details regarding configuring PromEx: ``` config :<%= @otp_app %>, <%= @module_name %>.PromEx, manual_metrics_start_delay: :no_delay, drop_metrics_groups: [], grafana: :disabled, metrics_server: :disabled ``` 2. Add this module to your application supervision tree. It should be one of the first things that is started so that no Telemetry events are missed. For example, if PromEx is started after your Repo module, you will miss Ecto's init events and the dashbaords will be missing some data points: ``` def start(_type, _args) do children = [ <%= @module_name %>.PromEx, ... ] ... end ``` 3. Update your `endpoint.ex` file to expose your metrics (or configure a standalone server using the `:metrics_server` config options). Be sure to put this plug before your `Plug.Telemetry` entry so that you can avoid having calls to your `/metrics` endpoint create their own metrics and logs which can pollute your logs/metrics given that Prometheus will scrape at a regular interval and that can get noisy: ``` defmodule <%= @module_name %>Web.Endpoint do use Phoenix.Endpoint, otp_app: :<%= @otp_app %> ... plug PromEx.Plug, prom_ex_module: <%= @module_name %>.PromEx ... end ``` 4. Update the list of plugins in the `plugins/0` function return list to reflect your application's dependencies. Also update the list of dashboards that are to be uploaded to Grafana in the `dashboards/0` function. \"\"\" use PromEx, otp_app: :<%= @otp_app %> alias PromEx.Plugins @impl true def plugins do [ # PromEx built in plugins Plugins.Application, Plugins.Beam # {Plugins.Phoenix, router: <%= @module_name %>Web.Router}, # Plugins.Ecto, # Plugins.Oban, # Plugins.PhoenixLiveView # Add your own PromEx metrics plugins # <%= @module_name %>.Users.PromExPlugin ] end @impl true def dashboard_assigns do [ datasource_id: "<%= @datasource_id %>" ] end @impl true def dashboards do [ # PromEx built in Grafana dashboards {:prom_ex, "application.json"}, {:prom_ex, "beam.json"} # {:prom_ex, "phoenix.json"}, # {:prom_ex, "ecto.json"}, # {:prom_ex, "oban.json"}, # {:prom_ex, "phoenix_live_view.json"} # Add your dashboard definitions here with the format: {:otp_app, "path_in_priv"} # {:<%= @otp_app %>, "/grafana_dashboards/user_metrics.json"} ] end end """ end end
32.504587
110
0.606266
797f125424a8328cbbff2c50ded3aeae656adb57
1,533
exs
Elixir
test/resource/actions/update_test.exs
MrFlorius/ash
247abbb8333d252da5440a58ddf4f1b7f184342f
[ "MIT" ]
528
2019-12-08T01:51:54.000Z
2022-03-30T10:09:45.000Z
test/resource/actions/update_test.exs
MrFlorius/ash
247abbb8333d252da5440a58ddf4f1b7f184342f
[ "MIT" ]
278
2019-12-04T15:25:06.000Z
2022-03-31T03:40:51.000Z
test/resource/actions/update_test.exs
MrFlorius/ash
247abbb8333d252da5440a58ddf4f1b7f184342f
[ "MIT" ]
53
2020-08-17T22:08:09.000Z
2022-03-24T01:58:59.000Z
defmodule Ash.Test.Dsl.Resource.Actions.UpdateTest do use ExUnit.Case, async: true defmacrop defposts(do: body) do quote do defmodule Post do use Ash.Resource, data_layer: Ash.DataLayer.Ets attributes do uuid_primary_key :id end unquote(body) end end end describe "representation" do test "it creates an action" do defposts do actions do defaults [] update :update end end assert [ %Ash.Resource.Actions.Update{ name: :update, primary?: true, type: :update } ] = Ash.Resource.Info.actions(Post) end end describe "validation" do test "it fails if `name` is not an atom" do assert_raise( Ash.Error.Dsl.DslError, "[Ash.Resource.Dsl.Update]\n actions -> update -> default:\n expected :name to be an atom, got: \"default\"", fn -> defposts do actions do update "default" end end end ) end test "it fails if `primary?` is not a boolean" do assert_raise( Ash.Error.Dsl.DslError, "[Ash.Resource.Dsl.Update]\n actions -> update -> update:\n expected :primary? to be a boolean, got: 10", fn -> defposts do actions do update :update, primary?: 10 end end end ) end end end
22.544118
118
0.516634
797f1d000eef305b2902ed80c8b0f08316b591f8
6,435
exs
Elixir
test/zss_service/message_test.exs
nickve28/zss_service_suite_service
6474fe4656141e283360ce9bdec1f522651eb72f
[ "MIT" ]
null
null
null
test/zss_service/message_test.exs
nickve28/zss_service_suite_service
6474fe4656141e283360ce9bdec1f522651eb72f
[ "MIT" ]
13
2017-05-20T12:19:37.000Z
2017-07-16T10:31:34.000Z
test/zss_service/message_test.exs
nickve28/zss_service_suite_service_ex
6474fe4656141e283360ce9bdec1f522651eb72f
[ "MIT" ]
null
null
null
defmodule ZssService.MessageTest do use ExUnit.Case alias ZssService.{Message, Address} doctest Message doctest Address describe "when converting to frames (to_frames)" do test "should encode Integer payload" do message = Message.new "SUBSCRIPTION", "CREATE" message = %Message{message | payload: 1} [payload | _] = message |> Message.to_frames |> Enum.reverse assert Msgpax.unpack!(payload) === 1 end test "should encode Boolean true payload" do message = Message.new "SUBSCRIPTION", "CREATE" message = %Message{message | payload: true} [payload | _] = message |> Message.to_frames |> Enum.reverse assert Msgpax.unpack!(payload) === true end test "should encode Boolean false payload" do message = Message.new "SUBSCRIPTION", "CREATE" message = %Message{message | payload: false} [payload | _] = message |> Message.to_frames |> Enum.reverse assert Msgpax.unpack!(payload) === false end test "should encode nil payload" do message = Message.new "SUBSCRIPTION", "CREATE" message = %Message{message | payload: nil} [payload | _] = message |> Message.to_frames |> Enum.reverse assert Msgpax.unpack!(payload) === nil end test "should encode Float payload" do message = Message.new "SUBSCRIPTION", "CREATE" message = %Message{message | payload: 1.5} [payload | _] = message |> Message.to_frames |> Enum.reverse assert Msgpax.unpack!(payload) === 1.5 end test "should encode String payload" do message = Message.new "SUBSCRIPTION", "CREATE" message = %Message{message | payload: "String"} [payload | _] = message |> Message.to_frames |> Enum.reverse assert Msgpax.unpack!(payload) === "String" end test "should encode Charlist payload" do message = Message.new "SUBSCRIPTION", "CREATE" message = %Message{message | payload: 'Charlist'} [payload | _] = message |> Message.to_frames |> Enum.reverse assert Msgpax.unpack!(payload) === 'Charlist' end test "should encode Array payload" do message = Message.new "SUBSCRIPTION", "CREATE" message = %Message{message | payload: [1, 2]} [payload | _] = message |> Message.to_frames |> Enum.reverse assert Msgpax.unpack!(payload) === [1, 2] end test "should encode Map payload" do message = Message.new "SUBSCRIPTION", "CREATE" message = %Message{message | payload: %{a: [1, "b"]}} [payload | _] = message |> Message.to_frames |> Enum.reverse assert Msgpax.unpack!(payload) === %{"a" => [1, "b"]} end end describe "when converting frames to a message" do test "should decode Integer payload" do encoded_address = %{sid: "SUBSCRIPTION", verb: "CREATE", sversion: "*"} |> Msgpax.pack! encoded_headers = %{"headers" => %{"X-REQUEST-ID" => "123"}} |> Msgpax.pack! encoded_payload = 1 |> Msgpax.pack! result = ["ZSS:0.0", "REP", "123", encoded_address, encoded_headers, "200", encoded_payload] |> Message.parse assert %Message{payload: 1} = result end test "should decode Boolean true payload" do encoded_address = %{sid: "SUBSCRIPTION", verb: "CREATE", sversion: "*"} |> Msgpax.pack! encoded_headers = %{"headers" => %{"X-REQUEST-ID" => "123"}} |> Msgpax.pack! encoded_payload = true |> Msgpax.pack! result = ["ZSS:0.0", "REP", "123", encoded_address, encoded_headers, "200", encoded_payload] |> Message.parse assert %Message{payload: true} = result end test "should decode Boolean false payload" do encoded_address = %{sid: "SUBSCRIPTION", verb: "CREATE", sversion: "*"} |> Msgpax.pack! encoded_headers = %{"headers" => %{"X-REQUEST-ID" => "123"}} |> Msgpax.pack! encoded_payload = false |> Msgpax.pack! result = ["ZSS:0.0", "REP", "123", encoded_address, encoded_headers, "200", encoded_payload] |> Message.parse assert %Message{payload: false} = result end test "should decode nil payload" do encoded_address = %{sid: "SUBSCRIPTION", verb: "CREATE", sversion: "*"} |> Msgpax.pack! encoded_headers = %{"headers" => %{"X-REQUEST-ID" => "123"}} |> Msgpax.pack! encoded_payload = nil |> Msgpax.pack! result = ["ZSS:0.0", "REP", "123", encoded_address, encoded_headers, "200", encoded_payload] |> Message.parse assert %Message{payload: nil} = result end test "should decode Float payload" do encoded_address = %{sid: "SUBSCRIPTION", verb: "CREATE", sversion: "*"} |> Msgpax.pack! encoded_headers = %{"headers" => %{"X-REQUEST-ID" => "123"}} |> Msgpax.pack! encoded_payload = 1.5 |> Msgpax.pack! result = ["ZSS:0.0", "REP", "123", encoded_address, encoded_headers, "200", encoded_payload] |> Message.parse assert %Message{payload: 1.5} = result end test "should decode String payload" do encoded_address = %{sid: "SUBSCRIPTION", verb: "CREATE", sversion: "*"} |> Msgpax.pack! encoded_headers = %{"headers" => %{"X-REQUEST-ID" => "123"}} |> Msgpax.pack! encoded_payload = "String" |> Msgpax.pack! result = ["ZSS:0.0", "REP", "123", encoded_address, encoded_headers, "200", encoded_payload] |> Message.parse assert %Message{payload: "String"} = result end test "should decode Array payload" do encoded_address = %{sid: "SUBSCRIPTION", verb: "CREATE", sversion: "*"} |> Msgpax.pack! encoded_headers = %{"headers" => %{"X-REQUEST-ID" => "123"}} |> Msgpax.pack! encoded_payload = [1, 2] |> Msgpax.pack! result = ["ZSS:0.0", "REP", "123", encoded_address, encoded_headers, "200", encoded_payload] |> Message.parse assert %Message{payload: [1, 2]} = result end test "should decode Map payload" do encoded_address = %{sid: "SUBSCRIPTION", verb: "CREATE", sversion: "*"} |> Msgpax.pack! encoded_headers = %{"headers" => %{"X-REQUEST-ID" => "123"}} |> Msgpax.pack! encoded_payload = %{"a" => [1, "b"]} |> Msgpax.pack! result = ["ZSS:0.0", "REP", "123", encoded_address, encoded_headers, "200", encoded_payload] |> Message.parse assert %Message{payload: %{"a" => [1, "b"]}} = result end end end
31.237864
98
0.608858
797f29f3c328f7d7a606e5df083e9a8ee3cae673
9,570
ex
Elixir
lib/ecto/adapters/riak/object.ex
TanYewWei/ecto
916c6467d5f7368fa10ecd7cfcfd2d4a9924a282
[ "Apache-2.0" ]
1
2015-08-27T13:17:10.000Z
2015-08-27T13:17:10.000Z
lib/ecto/adapters/riak/object.ex
TanYewWei/ecto
916c6467d5f7368fa10ecd7cfcfd2d4a9924a282
[ "Apache-2.0" ]
null
null
null
lib/ecto/adapters/riak/object.ex
TanYewWei/ecto
916c6467d5f7368fa10ecd7cfcfd2d4a9924a282
[ "Apache-2.0" ]
null
null
null
!defmodule Ecto.Adapters.Riak.Object do alias :riakc_obj, as: RiakObject alias Ecto.Adapters.Riak.DateTime alias Ecto.Adapters.Riak.RequiredFieldUndefinedError alias Ecto.Adapters.Riak.Util, as: RiakUtil @type statebox :: :statebox.statebox @type ecto_type :: Ecto.DateTime | Ecto.Interval | Ecto.Binary @type entity_type :: Ecto.Entity @type entity :: Ecto.Entity.t @type json :: HashDict.t | ListDict.t @type object :: :riakc_obj.object @content_type 'application/json' @sb_key_model_name :ectomodel @json_key_model_name "ectomodel_s" @json_key_statebox_ts "ectots_l" @spec entity_to_object(entity) :: object def entity_to_object(entity) do validate_entity(entity) ## raise error if validation fails context = entity.riak_context ts = timestamp kws = RiakUtil.entity_keyword(entity) kws = Enum.reduce(kws, [], fn { key, val }, acc -> hash = context[key] val_hash = value_hash(val) type = RiakUtil.entity_field_type(entity, key) json_key = yz_key(to_string(key), type) json_val = cond do is_record(val, Ecto.DateTime) -> DateTime.to_str(val) is_record(val, Ecto.Interval) -> DateTime.to_str(val) is_record(val, Ecto.Binary) -> :base64.encode(val.value) is_record(val, Ecto.Array) -> val.value true -> val end if nil?(hash) || val_hash == hash do ## value did not change since last update [{ json_key, json_val } | acc] else ## append statebox timestamp ts_key = statebox_timestamp_key(key) [{ ts_key, ts }, { json_key, json_val } | acc] end end) kws = [{ @json_key_model_name, to_string(entity.model) } | kws] ## Form riak object bucket = RiakUtil.bucket(entity) key = entity.primary_key value = JSON.encode!(kws) new_object = RiakObject.new(bucket, key, value, @content_type) cond do is_binary(entity.riak_vclock) -> RiakObject.set_vclock(new_object, entity.riak_vclock) true -> new_object end end @spec object_to_entity(object) :: entity def object_to_entity(object) do case RiakObject.get_values(object) do [] -> ## attempt lookup of updatedvalue field value = elem(object, tuple_size(object)-1) resolve_value(value, object) [ value ] -> resolve_value(value, object) values -> resolve_siblings(values, object) end end defp statebox_timestamp_key(key) do "_sb_ts_#{key}_l" end def build_riak_context(entity) do kws = RiakUtil.entity_keyword(entity) context = Enum.map(kws, fn { key, val } -> { key, if(nil?(val), do: nil, else: value_hash(val)) } end) entity.riak_context(context) end @doc """ Creates a globally unique primary key for an entity if it didn't already exist. """ @spec create_primary_key(entity) :: entity def create_primary_key(entity) do if is_binary(entity.primary_key) do entity else :crypto.rand_bytes(18) |> :base64.encode |> String.replace("/", "_") ## '/', '+', and '-' are disallowed in Solr |> String.replace("+", ".") |> entity.primary_key end end @spec resolve_value(binary, object) :: entity defp resolve_value(value, object) do entity = resolve_to_statebox(value) |> statebox_to_entity if is_binary(object.vclock) do entity.riak_vclock(object.vclock) else entity end end @spec resolve_siblings([binary | json], object) :: entity def resolve_siblings(values, object) do stateboxes = Enum.map(values, &resolve_to_statebox/1) statebox = :statebox_orddict.from_values(stateboxes) statebox = :statebox.truncate(0, statebox) entity = statebox_to_entity(statebox) if is_binary(object.vclock) do entity.riak_vclock(object.vclock) else entity end end @spec resolve_to_statebox(binary | json) :: statebox def resolve_to_statebox(nil), do: nil def resolve_to_statebox(bin) when is_binary(bin) do JSON.decode!(bin, as: HashDict) |> resolve_to_statebox end def resolve_to_statebox(json) do { ops, ## timestamp-independent ops timestamp, ## timestamp to do :statebox.modify/3 with ts_ops ## timestamp-dependent ops } = Enum.reduce(json, { [], 2, [] }, fn kv, acc -> { json_key, json_val } = kv { _ops, _timestamp, _ts_ops } = acc key_str = key_from_yz(json_key) key = RiakUtil.to_atom(key_str) if is_list(json_val) do ## always use add-wins behaviour with lists { [:statebox_orddict.f_union(key, json_val) | _ops], _timestamp, _ts_ops } else ## resolve last write with all other values ts_key = statebox_timestamp_key(key_str) ts = Dict.get(json, ts_key) if ts do ts = if ts > _timestamp, do: ts, else: _timestamp { _ops, ts, [:statebox_orddict.f_store(key, json_val) | _ts_ops] } else { [:statebox_orddict.f_store(key, json_val) | _ops], _timestamp, _ts_ops } end end end) ## Construct statebox with straightforward ops, ## then modify with timestamped ops box = :statebox.modify(1, ops, :statebox.new(0, fn -> [] end)) :statebox.modify(timestamp, ts_ops, box) end def statebox_to_entity(statebox) do values = statebox.value model = Dict.get(values, @sb_key_model_name) |> RiakUtil.to_atom entity_module = entity_name_from_model(model) ## Use module to get available fields ## and create new entity entity_fields = entity_module.__entity__(:field_names) Enum.map(entity_fields, fn field -> case :orddict.find(field, values) do { :ok, value } -> type = entity_module.__entity__(:field_type, field) { field, ecto_value(value, type) } _ -> nil end end) |> Enum.filter(&(nil != &1)) |> model.new |> build_riak_context |> validate_entity end defp ecto_value(nil, _), do: nil defp ecto_value(Ecto.Array[value: value], _), do: value defp ecto_value(val, type) do case type do :binary -> if is_binary(val) do :base64.decode(val) else nil end :datetime -> DateTime.to_datetime(val) :interval -> DateTime.to_interval(val) :integer when is_binary(val) -> case Integer.parse(val) do { i, _ } -> i _ -> nil end :float when is_binary(val) -> case Float.parse(val) do { f, _ } -> f _ -> nil end _ -> val end end defp timestamp() do :statebox_clock.timestamp end @spec entity_name_from_model(binary | atom) :: atom defp entity_name_from_model(name) when is_binary(name) or is_atom(name) do name_str = to_string(name) suffix = ".Entity" if String.ends_with?(name_str, suffix) do name |> RiakUtil.to_atom else (name_str <> suffix) |> RiakUtil.to_atom end end ## ---------------------------------------------------------------------- ## Validation ## ---------------------------------------------------------------------- defmacrop raise_required_field_error(field, entity) do quote do raise RequiredFieldUndefinedError, field: unquote(field), entity: unquote(entity) end end defp validate_entity(entity) do ## checks that all fields needed for Riak ## migrations are defined cond do entity.primary_key == nil || size(entity.primary_key) == 0 -> raise_required_field_error(:primary_key, entity) ! function_exported?(entity, :riak_version, 0) -> raise_required_field_error(:riak_version, entity) ! is_integer(entity.riak_version) -> raise_required_field_error(:riak_version, entity) ! function_exported?(entity, :riak_context, 0) -> raise_required_field_error(:riak_context, entity) true -> entity end end ## ---------------------------------------------------------------------- ## Key and Value De/Serialization ## ---------------------------------------------------------------------- @yz_key_regex ~r"_(i|is|f|fs|b|bs|b64_s|b64_ss|s|ss|i_dt|i_dts|dt|dts)$" @spec key_from_yz(binary) :: binary def key_from_yz(key) do ## Removes the default YZ schema suffix from a key. ## schema ref: https://github.com/basho/yokozuna/blob/develop/priv/default_schema.xml Regex.replace(@yz_key_regex, to_string(key), "") end @spec yz_key(binary, atom | { :array, atom }) :: binary def yz_key(key, type) do ## Adds a YZ schema suffix to a key depending on its type. to_string(key) <> "_" <> case type do :integer -> "i" :float -> "f" :binary -> "b64_s" :string -> "s" :boolean -> "b" :datetime -> "dt" :interval -> "i_dt" { :array, list_type } -> case list_type do :integer -> "is" :float -> "fs" :binary -> "b64_ss" :string -> "ss" :boolean -> "bs" :datetime -> "dts" :interval -> "i_dts" end end end defp value_hash(term) do bin = :erlang.term_to_binary(term, minor_version: 1) :crypto.hash(:sha256, bin) end end
29.813084
89
0.59279
797f70689a2c36848f7da0c563e626319b8fd248
1,209
exs
Elixir
test/unit/compiler_error_parser_test.exs
elbow-jason/zigler
3de4d6fe4def265b689bd21d3e0abad551bd2d50
[ "MIT" ]
null
null
null
test/unit/compiler_error_parser_test.exs
elbow-jason/zigler
3de4d6fe4def265b689bd21d3e0abad551bd2d50
[ "MIT" ]
null
null
null
test/unit/compiler_error_parser_test.exs
elbow-jason/zigler
3de4d6fe4def265b689bd21d3e0abad551bd2d50
[ "MIT" ]
null
null
null
defmodule ZiglerTest.CompilerErrorParserTest do use ExUnit.Case, async: true alias Zigler.Parser.Error @moduletag :parser describe "when passing code lines to the parser" do test "a non-tag line is an error" do assert {:error, _, _, _, _, _} = Error.check_ref("fn foo(x: i64) i64 {") end test "a tag line is an success" do assert {:ok, ["/foo/bar/test.ex", "10"], _, _, _, _} = Error.check_ref("// ref: /foo/bar/test.ex line: 10") end end @dummy_file_path "test/unit/assets/error_parser_dummy.zig" describe "when error parsing a dummy file" do test "content in the header is correctly mapped" do assert {@dummy_file_path, 2} = Error.backreference(@dummy_file_path, 2) end test "content in the first section is correctly mapped" do assert {"/path/to/foo.ex", 15} = Error.backreference(@dummy_file_path, 7) end test "content in the second section is correctly mapped" do assert {"/path/to/foo.ex", 48} = Error.backreference(@dummy_file_path, 14) end test "content in the footer is correctly mapped" do assert {@dummy_file_path, 29} = Error.backreference(@dummy_file_path, 29) end end end
31.815789
80
0.669148
797fe961a4440f1c7b23e8fa0ddf6e0c2461a4ea
807
ex
Elixir
lib/apa_comp.ex
razuf/apa
1052973da9a726c2914182562fa1f433fe303c8d
[ "Apache-2.0" ]
4
2020-04-22T05:31:13.000Z
2020-06-23T08:20:17.000Z
lib/apa_comp.ex
razuf/apa
1052973da9a726c2914182562fa1f433fe303c8d
[ "Apache-2.0" ]
null
null
null
lib/apa_comp.ex
razuf/apa
1052973da9a726c2914182562fa1f433fe303c8d
[ "Apache-2.0" ]
null
null
null
defmodule ApaComp do @moduledoc """ APA : Arbitrary Precision Arithmetic - Comparision - ApaComp. """ @doc """ Comparison - internal function - please call Apa.comp(left, right, sclae, precision) The 'precision' of an ApaNumber is the total count of significant digits in the whole number, that is, the number of digits to both sides of the decimal point. The 'scale' of an ApaNumber is the count of decimal digits in the fractional part, to the right of the decimal point """ @spec bc_comp(String.t(), String.t(), integer(), integer()) :: integer() | Exception def bc_comp(left, right, precision, scale) do diff = Apa.sub(left, right, precision, scale) cond do Apa.from_string(diff) == {0, 0} -> 0 String.first(diff) == "-" -> -1 true -> 1 end end end
36.681818
161
0.672862
797fefe4c9b0e1660092f1e6a79fa33d98401fe3
251
ex
Elixir
test/support/rbac/resources/registry.ex
kernel-io/ash_policy_authorizer
cf9f44398e156dad3c38eb56d5f3fd25ebaa704a
[ "MIT" ]
null
null
null
test/support/rbac/resources/registry.ex
kernel-io/ash_policy_authorizer
cf9f44398e156dad3c38eb56d5f3fd25ebaa704a
[ "MIT" ]
1
2020-06-05T01:06:15.000Z
2020-06-05T01:06:15.000Z
test/support/rbac/resources/registry.ex
ash-project/ash_policy_access
a954bf12e3a65c9ea0b0eb888162064cae786cbd
[ "MIT" ]
null
null
null
defmodule AshPolicyAuthorizer.Test.Rbac.Registry do @moduledoc false use Ash.Registry alias AshPolicyAuthorizer.Test.Rbac entries do entry(Rbac.User) entry(Rbac.Organization) entry(Rbac.Membership) entry(Rbac.File) end end
17.928571
51
0.74502
797ffa786a595fdd80b8dab1aa687d09b016350e
1,995
ex
Elixir
lib/api/map.ex
emeric-martineau/cloud_stack_lang
50c9164c06b2a683d3de84c493aaddd3e55de8b8
[ "Apache-2.0" ]
null
null
null
lib/api/map.ex
emeric-martineau/cloud_stack_lang
50c9164c06b2a683d3de84c493aaddd3e55de8b8
[ "Apache-2.0" ]
null
null
null
lib/api/map.ex
emeric-martineau/cloud_stack_lang
50c9164c06b2a683d3de84c493aaddd3e55de8b8
[ "Apache-2.0" ]
null
null
null
# # Copyright 2020 Cloud Stack Lang Contributors # # 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 CloudStackLang.Map do @moduledoc """ This module contains all routine to help access to map value with key. ## Examples iex> CloudStackLang.Map.reduce([{:string, 1, "c"}], {:map, %{"c" => {:int, 1}}}) {:int, 1} iex> CloudStackLang.Map.reduce([{:string, 1, "c"}], nil) {:error, 1, "Trying get a value with key 'c' on nil value"} iex> CloudStackLang.Map.reduce([{:string, 1, "c"}], 1) {:error, 1, "Trying get a value with key 'c' on non-map value"} """ def reduce(access_keys, {:map, state}) do [first_key | keys] = access_keys {_type, _line, key} = first_key reduce(keys, state[key]) end def reduce(access_keys, {:array, state}) do [first_key | keys] = access_keys {_type, line, key} = first_key case key < length(state) do true -> reduce(keys, Enum.at(state, key)) false -> {:error, line, "Index '#{key}' is out of range (#{length(state)} items in array)"} end end def reduce(access_keys, nil) do [first_key | _keys] = access_keys {_type, line, key} = first_key {:error, line, "Trying get a value with key '#{key}' on nil value"} end def reduce([], state), do: state def reduce(access_keys, _state) do [first_key | _keys] = access_keys {_type, line, key} = first_key {:error, line, "Trying get a value with key '#{key}' on non-map value"} end end
30.692308
97
0.655138
7980143489149f6eb7e0f23b252828dea71dfcac
5,674
ex
Elixir
lib/archcomposer.ex
themaxhero/Arch-Composer
5c93e72c7c2fce9d7e0d63ad81ef0b86f0c5b4a6
[ "MIT" ]
null
null
null
lib/archcomposer.ex
themaxhero/Arch-Composer
5c93e72c7c2fce9d7e0d63ad81ef0b86f0c5b4a6
[ "MIT" ]
10
2020-09-02T19:16:17.000Z
2020-09-04T16:49:23.000Z
lib/archcomposer.ex
themaxhero/Arch-Composer
5c93e72c7c2fce9d7e0d63ad81ef0b86f0c5b4a6
[ "MIT" ]
null
null
null
defmodule Archcomposer do @moduledoc """ Documentation for `Archcomposer`. """ @doc """ get_config Extracts the config from the config file. """ def get_config(config) do config end @doc """ get_disk_information """ def get_disk_information(config) do config end @doc """ get_user_settings """ def get_user_settings(config) do config end @doc """ setup_disks """ def setup_disks(config) do config end @doc """ prepare_disks """ def prepare_disks(config) do config |> get_disk_information # Gets Disk's Information for partitioning |> get_user_settings # Prompts the user asking for his the password and then asks for Root's password. |> setup_disks # Sets up disks accordingly with the user settings end @doc """ bootstrap_system Does the pacstrap with base. """ def bootstrap_system(config) do config end @doc """ set_local_time """ def set_local_time(config) do config end @doc """ setup_time """ def setup_time(config) do config end @doc """ add_locales """ def add_locales(config) do config end @doc """ set_default_locale """ def set_default_locale(config) do config end @doc """ generate_locales """ def generate_locales(config) do config end @doc """ configure_keyboard_layout """ def configure_keyboard_layout(config) do config end @doc """ setup_localization """ def setup_localization(config) do config |> set_local_time # Sets localtime for the new system. |> setup_time # Sets up the time |> add_locales # Sets locales for the new system. |> set_default_locale # Sets the default locale. |> generate_locales # Generates all the selected locales |> configure_keyboard_layout # Sets up keyboard layout for both terminal, terminal emulators and Desktop Environments end @doc """ setup_users Gets the user list and make all the users accordingly with the config """ def setup_users(config) do config end @doc """ set_host_name """ def set_host_name(config) do config end @doc """ set_hosts """ def set_hosts(config) do config end @doc """ setup_networking """ def setup_networking(config) do config |> set_host_name # Sets up the hostname |> set_hosts # Sets up the hosts file end @doc """ add_mirrors """ def add_mirrors(config) do config end @doc """ add_repos """ def add_repos(config) do config end @doc """ setup_pacman_key """ def setup_pacman_key(config) do config end @doc """ trust_repo_keys """ def trust_repo_keys(config) do config end @doc """ update_after_pacstrap """ def update_after_pacstrap(config) do config end @doc """ setup_pacman """ def setup_pacman(config) do config |> add_mirrors # Sets up pacman's official mirrors |> add_repos # Sets up custom repositories |> setup_pacman_key # Sets up pacman-key |> trust_repo_keys # Trusts custom repositories' keys |> update_after_pacstrap # Runs Pacman -Syu for updating the databases and getting eventual updates end @doc """ install_pacman_packages """ def install_pacman_packages(config) do config end @doc """ install_aur_packages """ def install_aur_packages(config) do config end @doc """ install_packages """ def install_packages(config) do config |> install_pacman_packages # Install all pacman packages listed in the config |> install_aur_packages # Install all aur packages listed in the config end @doc """ setup_theming """ def setup_theming(config) do config end @doc """ edit_config_files Settings (Edit some configuration files) (can include disable password asking for wheels (sudo) for example) """ def edit_config_files(config) do config end @doc """ enable_services Enables the services listed in the config file """ def enable_services(config) do config end @doc """ create_initial_ramdisk runs mkinitcpio for all installed kernels """ def create_initial_ramdisk(config) do config end @doc """ install_bootloader Install bootloader """ def install_bootloader(config) do config end @doc """ create_bootloader_entries Creates bootloader entries """ def create_bootloader_entries(config) do config end @doc """ clear_pacman_cache Clears Pacman's Cache """ def clear_pacman_cache(config) do config end @doc """ reboot Duh """ def reboot(config) do config end def main(args) do options = [switches: [file: :string], aliases: [f: :file]] {opts, _, _} = OptionParser.parse(args, options) IO.inspect(opts, label: "Command Line Arguments") opts[:file] |> Code.require_file |> get_config |> prepare_disks |> bootstrap_system |> setup_localization |> setup_users |> setup_networking |> setup_pacman |> setup_theming |> edit_config_files |> enable_services |> create_initial_ramdisk |> install_bootloader |> create_bootloader_entries |> clear_pacman_cache |> reboot end end
19.104377
135
0.615615
79802f4c9a9cfd3ee0e1437c0165f464db872347
5,250
ex
Elixir
lib/spandex_tesla.ex
thiamsantos/spandex_tesla
b1dab3045cb7227cad054be40e25a948ab1106d3
[ "Apache-2.0" ]
5
2020-02-16T23:10:55.000Z
2022-03-18T09:25:41.000Z
lib/spandex_tesla.ex
thiamsantos/spandex_tesla
b1dab3045cb7227cad054be40e25a948ab1106d3
[ "Apache-2.0" ]
31
2020-07-21T12:23:06.000Z
2022-03-28T02:09:52.000Z
lib/spandex_tesla.ex
thiamsantos/spandex_tesla
b1dab3045cb7227cad054be40e25a948ab1106d3
[ "Apache-2.0" ]
7
2020-07-18T01:41:41.000Z
2021-11-26T17:08:42.000Z
defmodule SpandexTesla do @external_resource "README.md" @moduledoc "README.md" |> File.read!() |> String.split("<!-- MDOC !-->") |> Enum.fetch!(1) defmodule Error do @moduledoc """ Struct used to identify the errors. """ defexception [:message] end @doc """ Telemetry handler. Attach it to the telemetry tesla events in order to trace the tesla calls. """ def handle_event([:tesla, :request, :start], _measurements, _metadata, _config) do if tracer().current_trace_id([]) do tracer().start_span("request", []) Logger.metadata( trace_id: to_string(tracer().current_trace_id([])), span_id: to_string(tracer().current_span_id([])) ) end end def handle_event( [:tesla, :request, :stop], measurements, %{error: error, env: env} = metadata, config ) do now = clock_adapter().system_time() %{duration: duration} = measurements %{url: url, method: method} = env trace_opts = format_trace_options( %{duration: duration, status: nil, method: method, now: now, url: url}, metadata, config || [] ) tracer().span_error( %Error{message: Atom.to_string(error)}, nil, trace_opts ) tracer().finish_span([]) end def handle_event([:tesla, :request, :stop], measurements, metadata, config) do if tracer().current_trace_id([]) do now = clock_adapter().system_time() %{duration: duration} = measurements %{status: status, url: url, method: method} = metadata[:env] trace_opts = format_trace_options( %{duration: duration, method: method, now: now, status: status, url: url}, metadata, config || [] ) case status do x when x not in 200..299 -> tracer().span_error( %Error{message: "Request has failed with status response #{status}"}, nil, trace_opts ) _ -> tracer().update_span(trace_opts) end tracer().finish_span([]) end end def handle_event([:tesla, :request, :exception], _measurements, metadata, _config) do if tracer().current_trace_id([]) do reason = metadata[:reason] || metadata[:error] tracer().span_error(%Error{message: inspect(reason)}, nil, []) tracer().finish_span([]) Logger.metadata( trace_id: to_string(tracer().current_trace_id([])), span_id: to_string(tracer().current_span_id([])) ) end end def handle_event([:tesla, :request], measurements, metadata, config) do if tracer().current_trace_id([]) do now = clock_adapter().system_time() |> System.convert_time_unit(:native, :nanosecond) %{request_time: request_time} = measurements %{result: result} = metadata tracer().start_span("request", []) Logger.metadata( trace_id: to_string(tracer().current_trace_id([])), span_id: to_string(tracer().current_span_id([])) ) span_result(result, %{request_time: request_time, now: now}, metadata, config || []) tracer().finish_span([]) end end defp span_result({:ok, request}, measurements, metadata, config) do %{request_time: request_time, now: now} = measurements %{status: status, url: url, method: method} = request duration = System.convert_time_unit(request_time, :microsecond, :nanosecond) trace_opts = format_trace_options( %{duration: duration, method: method, now: now, status: status, url: url}, metadata, config ) tracer().update_span(trace_opts) end defp span_result({:error, reason}, _measurements, _metadata, _config) do tracer().span_error(%Error{message: inspect(reason)}, nil, []) end defp format_trace_options( %{duration: duration, method: method, now: now, status: status, url: url}, metadata, config ) do upcased_method = method |> to_string() |> String.upcase() [ start: now - duration, completion_time: now, service: service(), resource: resource_name(metadata, config), type: :web, http: [ url: url, status_code: status, method: upcased_method ] ] end defp resource_name(metadata, config) do get_resource_name = Keyword.get(config, :resource, &default_resource_name/1) get_resource_name.(metadata) end defp default_resource_name(%{env: %{url: url, method: method, opts: opts}}) do upcased_method = method |> to_string() |> String.upcase() resource_url = Keyword.get(opts, :req_url, url) "#{upcased_method} #{resource_url}" end defp default_resource_name(%{result: {:ok, %{method: method, url: url, opts: opts}}}) do upcased_method = method |> to_string() |> String.upcase() resource_url = Keyword.get(opts, :req_url, url) "#{upcased_method} #{resource_url}" end defp tracer do Application.fetch_env!(:spandex_tesla, :tracer) end defp service do Application.get_env(:spandex_tesla, :service, :tesla) end defp clock_adapter do Application.get_env(:spandex_tesla, :clock_adapter, System) end end
27.631579
95
0.618286
79804543524abfab86afd31213eb0048b0d657b5
1,953
ex
Elixir
clients/drive_activity/lib/google_api/drive_activity/v2/model/permission_change.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/drive_activity/lib/google_api/drive_activity/v2/model/permission_change.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/drive_activity/lib/google_api/drive_activity/v2/model/permission_change.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DriveActivity.V2.Model.PermissionChange do @moduledoc """ A change of the permission setting on an item. ## Attributes * `addedPermissions` (*type:* `list(GoogleApi.DriveActivity.V2.Model.Permission.t)`, *default:* `nil`) - The set of permissions added by this change. * `removedPermissions` (*type:* `list(GoogleApi.DriveActivity.V2.Model.Permission.t)`, *default:* `nil`) - The set of permissions removed by this change. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :addedPermissions => list(GoogleApi.DriveActivity.V2.Model.Permission.t()), :removedPermissions => list(GoogleApi.DriveActivity.V2.Model.Permission.t()) } field(:addedPermissions, as: GoogleApi.DriveActivity.V2.Model.Permission, type: :list) field(:removedPermissions, as: GoogleApi.DriveActivity.V2.Model.Permission, type: :list) end defimpl Poison.Decoder, for: GoogleApi.DriveActivity.V2.Model.PermissionChange do def decode(value, options) do GoogleApi.DriveActivity.V2.Model.PermissionChange.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DriveActivity.V2.Model.PermissionChange do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
39.06
157
0.749104
798052ccd6bb9accfc9d31886da427e98b0b568b
894
ex
Elixir
clients/security_center/lib/google_api/security_center/v1/metadata.ex
myskoach/elixir-google-api
4f8cbc2fc38f70ffc120fd7ec48e27e46807b563
[ "Apache-2.0" ]
null
null
null
clients/security_center/lib/google_api/security_center/v1/metadata.ex
myskoach/elixir-google-api
4f8cbc2fc38f70ffc120fd7ec48e27e46807b563
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/security_center/lib/google_api/security_center/v1/metadata.ex
myskoach/elixir-google-api
4f8cbc2fc38f70ffc120fd7ec48e27e46807b563
[ "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.SecurityCenter.V1 do @moduledoc """ API client metadata for GoogleApi.SecurityCenter.V1. """ @discovery_revision "20201211" def discovery_revision(), do: @discovery_revision end
33.111111
74
0.761745
7980aeb4b016e8b513357858a02af6e88d8c971a
701
ex
Elixir
lib/langue/langue.ex
gitter-badger/accent-1
b2fdf26e598d832550eceaa40cd8055f93bca216
[ "BSD-3-Clause" ]
null
null
null
lib/langue/langue.ex
gitter-badger/accent-1
b2fdf26e598d832550eceaa40cd8055f93bca216
[ "BSD-3-Clause" ]
null
null
null
lib/langue/langue.ex
gitter-badger/accent-1
b2fdf26e598d832550eceaa40cd8055f93bca216
[ "BSD-3-Clause" ]
null
null
null
defmodule Langue do @formats [ Android, CSV, Es6Module, Gettext, JavaProperties, JavaPropertiesXml, Json, Rails, SimpleJson, Strings ] for format <- @formats, module = Module.concat([Langue, Formatter, format]), name = module.name() do def parser_from_format(unquote(name)), do: {:ok, &unquote(module).parse(&1)} end def parser_from_format(_), do: {:error, :unknown_parser} for format <- @formats, module = Module.concat([Langue, Formatter, format]), name = module.name() do def serializer_from_format(unquote(name)), do: {:ok, &unquote(module).serialize(&1)} end def serializer_from_format(_), do: {:error, :unknown_serializer} end
25.962963
102
0.670471
7980b20d826f617ad16620b407cc7fad343c1016
1,239
ex
Elixir
lib/changelog_web/controllers/episode_request_controller.ex
gustavoarmoa/changelog.com
e898a9979a237ae66962714821ed8633a4966f37
[ "MIT" ]
2,599
2016-10-25T15:02:53.000Z
2022-03-26T02:34:42.000Z
lib/changelog_web/controllers/episode_request_controller.ex
sdrees/changelog.com
955cdcf93d74991062f19a03e34c9f083ade1705
[ "MIT" ]
253
2016-10-25T20:29:24.000Z
2022-03-29T21:52:36.000Z
lib/changelog_web/controllers/episode_request_controller.ex
sdrees/changelog.com
955cdcf93d74991062f19a03e34c9f083ade1705
[ "MIT" ]
298
2016-10-25T15:18:31.000Z
2022-01-18T21:25:52.000Z
defmodule ChangelogWeb.EpisodeRequestController do use ChangelogWeb, :controller alias Changelog.{EpisodeRequest} plug RequireUser, "before submitting" when action in [:create] def new(conn = %{assigns: %{podcasts: podcasts}}, params) do podcast = Enum.find(podcasts, fn p -> p.slug == params["slug"] end) {conn, podcast_id} = case podcast do nil -> {conn, 1} p -> {assign(conn, :podcast, p), p.id} end changeset = EpisodeRequest.submission_changeset(%EpisodeRequest{podcast_id: podcast_id}) conn |> assign(:changeset, changeset) |> render(:new) end def create(conn = %{assigns: %{current_user: user}}, %{"episode_request" => request_params}) do request = %EpisodeRequest{submitter_id: user.id, status: :fresh} changeset = EpisodeRequest.submission_changeset(request, request_params) case Repo.insert(changeset) do {:ok, _request} -> conn |> put_flash(:success, "We received your episode request! Stay awesome 💚") |> redirect(to: Routes.root_path(conn, :index)) {:error, changeset} -> conn |> put_flash(:error, "Something went wrong. 😭") |> render(:new, changeset: changeset) end end end
30.219512
97
0.650525
7980bc017cfa9a18a0a0e7c7b430feb9e9b25afb
2,146
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/target_grpc_proxy_list_warning.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/target_grpc_proxy_list_warning.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/compute/lib/google_api/compute/v1/model/target_grpc_proxy_list_warning.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.Compute.V1.Model.TargetGrpcProxyListWarning do @moduledoc """ [Output Only] Informational warning message. ## Attributes * `code` (*type:* `String.t`, *default:* `nil`) - [Output Only] A warning code, if applicable. For example, Compute Engine returns NO_RESULTS_ON_PAGE if there are no results in the response. * `data` (*type:* `list(GoogleApi.Compute.V1.Model.TargetGrpcProxyListWarningData.t)`, *default:* `nil`) - [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": "scope", "value": "zones/us-east1-d" } * `message` (*type:* `String.t`, *default:* `nil`) - [Output Only] A human-readable description of the warning code. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :code => String.t(), :data => list(GoogleApi.Compute.V1.Model.TargetGrpcProxyListWarningData.t()), :message => String.t() } field(:code) field(:data, as: GoogleApi.Compute.V1.Model.TargetGrpcProxyListWarningData, type: :list) field(:message) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.TargetGrpcProxyListWarning do def decode(value, options) do GoogleApi.Compute.V1.Model.TargetGrpcProxyListWarning.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.TargetGrpcProxyListWarning do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
39.740741
194
0.724604
7980d1c490e41bb86e2b144099c9cffeb3c85ef5
1,171
ex
Elixir
example/backend/lib/backend_web/channels/presence_channel.ex
farolanf/phoenix-socket-dart
3fb441c53a25e2f7ea6f8f0ca9e7bfc25e45cdfd
[ "BSD-3-Clause" ]
30
2020-11-10T07:32:36.000Z
2022-02-06T20:34:34.000Z
example/backend/lib/backend_web/channels/presence_channel.ex
farolanf/phoenix-socket-dart
3fb441c53a25e2f7ea6f8f0ca9e7bfc25e45cdfd
[ "BSD-3-Clause" ]
22
2020-11-28T20:23:34.000Z
2022-03-23T22:32:52.000Z
example/backend/lib/backend_web/channels/presence_channel.ex
farolanf/phoenix-socket-dart
3fb441c53a25e2f7ea6f8f0ca9e7bfc25e45cdfd
[ "BSD-3-Clause" ]
19
2020-11-10T14:22:05.000Z
2022-02-15T10:22:43.000Z
defmodule BackendWeb.PresenceChannel do use BackendWeb, :channel alias BackendWeb.Presence @impl true def join("presence:lobby", payload, socket) do if authorized?(payload) do send(self(), :after_join) {:ok, socket} else {:error, %{reason: "unauthorized"}} end end # # Channels can be used in a request/response fashion # # by sending replies to requests from the client # @impl true # def handle_in("ping", payload, socket) do # {:reply, {:ok, payload}, socket} # end # # It is also common to receive messages from the client and # # broadcast to everyone in the current topic (presence:lobby). # @impl true # def handle_in("shout", payload, socket) do # broadcast socket, "shout", payload # {:noreply, socket} # end # Add authorization logic here as required. defp authorized?(_payload) do true end @impl true def handle_info(:after_join, socket) do {:ok, _} = Presence.track(socket, socket.assigns.user_id, %{ online_at: inspect(System.system_time(:second)) }) push(socket, "presence_state", Presence.list(socket)) {:noreply, socket} end end
25.456522
66
0.659266
7980d5bc5741518cdc3151327b52f69ed6930d9b
582
ex
Elixir
apps/ello_v3/lib/ello_v3/application.ex
ello/apex
4acb096b3ce172ff4ef9a51e5d068d533007b920
[ "MIT" ]
16
2017-06-21T21:31:20.000Z
2021-05-09T03:23:26.000Z
apps/ello_v3/lib/ello_v3/application.ex
ello/apex
4acb096b3ce172ff4ef9a51e5d068d533007b920
[ "MIT" ]
25
2017-06-07T12:18:28.000Z
2018-06-08T13:27:43.000Z
apps/ello_v3/lib/ello_v3/application.ex
ello/apex
4acb096b3ce172ff4ef9a51e5d068d533007b920
[ "MIT" ]
3
2018-06-14T15:34:07.000Z
2022-02-28T21:06:13.000Z
defmodule Ello.V3.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do # List all child processes to be supervised children = [ # Starts a worker by calling: Ello.V3.Worker.start_link(arg) # {Ello.V3.Worker, arg}, ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Ello.V3.Supervisor] Supervisor.start_link(children, opts) end end
27.714286
66
0.702749
7980d7f707f3ac317b607c0fb888e762a5ec82c5
3,656
ex
Elixir
backend/lib/honeyland/error.ex
bejolithic/honeyland
8c4a0d3b56543648d3acb96cc6906df86526743b
[ "Apache-2.0" ]
null
null
null
backend/lib/honeyland/error.ex
bejolithic/honeyland
8c4a0d3b56543648d3acb96cc6906df86526743b
[ "Apache-2.0" ]
null
null
null
backend/lib/honeyland/error.ex
bejolithic/honeyland
8c4a0d3b56543648d3acb96cc6906df86526743b
[ "Apache-2.0" ]
null
null
null
# # This file is part of Honeyland. # # Copyright 2022 Nervive Studio # # 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 Honeyland.Error do @moduledoc """ Module used to normalize all errors in Honeyland, so that they can be shown by the API. """ require Logger alias __MODULE__ defstruct [:code, :message, :status_code, :key] # Error Tuples # Regular errors def normalize({:error, reason}) do handle(reason) end # Ecto transaction errors def normalize({:error, _operation, reason, _changes}) do handle(reason) end # Unhandled errors def normalize(other) do handle(other) end defp handle(code) when is_atom(code) do {status, message} = metadata(code) %Error{ code: code, message: message, status_code: status } end defp handle(errors) when is_list(errors) do Enum.map(errors, &handle/1) end defp handle(%Ecto.Changeset{} = changeset) do changeset |> Ecto.Changeset.traverse_errors(fn {err, _opts} -> err end) |> Enum.map(fn {_k, v} when is_map(v) -> # Nested changeset, inner errors are already a rendered map from_rendered_changeset_errors(v) {k, v} -> %Error{ code: :validation, message: String.capitalize("#{k} #{v}"), status_code: 422 } end) end defp handle(%{status: status, response: response} = error) when is_struct(error, Astarte.Client.APIError) or is_struct(error, Astarte.Client.APIError) do case response do # detail already includes an error message %{"errors" => %{"detail" => error_message}} -> %Error{ code: :astarte_api_error, message: error_message, status_code: status } # This probably comes from a changeset error, translate it %{"errors" => errors} when is_map(errors) and status == 422 -> from_rendered_changeset_errors(errors) # If something else comes up, we return the status and print out an error response -> Logger.warn("Unhandled API Error: #{inspect(response)}") %Error{ code: :astarte_api_error, message: Jason.encode!(response), status_code: status } end end defp handle(other) do Logger.warn("Unhandled error term: #{inspect(other)}") handle(:unknown) end defp from_rendered_changeset_errors(changeset_errors) do Enum.map(changeset_errors, fn {k, error_messages} -> # Emit an error struct for each error message on a key Enum.map(error_messages, fn error_message -> %Error{ code: :astarte_api_error, message: String.capitalize("#{k} #{error_message}"), status_code: 422 } end) end) end defp metadata(:unauthenticated), do: {401, "Login required"} defp metadata(:unauthorized), do: {403, "Unauthorized"} defp metadata(:not_found), do: {404, "Resource not found"} defp metadata(:unknown), do: {500, "Something went wrong"} defp metadata(code) do Logger.warn("Unhandled error code: #{inspect(code)}") {422, to_string(code)} end end
27.283582
89
0.650985
798105efa39508ed6ba9f1e153a60e7188d073b8
696
ex
Elixir
lib/social_network/image.ex
Symbolk/social_network
11df1ba9bc19fd140b630ac2abbd4b13b42def92
[ "MIT" ]
17
2017-01-02T10:38:28.000Z
2021-02-28T22:16:54.000Z
lib/social_network/image.ex
Symbolk/social_network
11df1ba9bc19fd140b630ac2abbd4b13b42def92
[ "MIT" ]
null
null
null
lib/social_network/image.ex
Symbolk/social_network
11df1ba9bc19fd140b630ac2abbd4b13b42def92
[ "MIT" ]
2
2017-01-09T13:02:13.000Z
2018-06-16T22:01:53.000Z
defmodule Image do use Arc.Definition # def __storage, do: Arc.Storage.Local @versions [:original, :thumb] @extension_whitelist ~w(.jpg .jpeg .gif .png) def acl(:thumb, _), do: :public_read def validate({file, _}) do file_extension = file.file_name |> Path.extname |> String.downcase Enum.member?(@extension_whitelist, file_extension) end def transform(:thumb, _) do {:convert, "-thumbnail 100x100^ -gravity center -extent 100x100 -format png", :png} end def filename(version, _) do version end def storage_dir(_, {file, id}) do "priv/static/uploads/posts/#{id}" end def default_url(:thumb) do "https://placehold.it/100x100" end end
23.2
87
0.676724
79810a68a4524870393d8d3157b983ba6465a573
3,636
exs
Elixir
test/plug/telemetry_test.exs
outstand/plug
e75d542b3028b5c1f348ac9d128306c46a6b6e70
[ "Apache-2.0" ]
1,218
2017-07-14T15:13:32.000Z
2022-03-30T16:42:42.000Z
test/plug/telemetry_test.exs
outstand/plug
e75d542b3028b5c1f348ac9d128306c46a6b6e70
[ "Apache-2.0" ]
502
2017-07-19T15:36:44.000Z
2022-03-31T06:47:36.000Z
test/plug/telemetry_test.exs
outstand/plug
e75d542b3028b5c1f348ac9d128306c46a6b6e70
[ "Apache-2.0" ]
376
2017-07-17T15:47:55.000Z
2022-03-23T19:24:30.000Z
Application.ensure_all_started(:telemetry) defmodule Plug.TelemetryTest do use ExUnit.Case, async: true use Plug.Test defmodule MyPlug do use Plug.Builder plug Plug.Telemetry, event_prefix: [:pipeline], extra_options: :hello plug :send_resp, 200 defp send_resp(conn, status) do Plug.Conn.send_resp(conn, status, "Response") end end defmodule MyNoSendPlug do use Plug.Builder plug Plug.Telemetry, event_prefix: [:nosend, :pipeline] end defmodule MyCrashingPlug do use Plug.Builder plug Plug.Telemetry, event_prefix: [:crashing, :pipeline] plug :raise_error plug :send_resp, 200 defp raise_error(_conn, _) do raise "Crash!" end defp send_resp(conn, status) do Plug.Conn.send_resp(conn, status, "Response") end end setup do start_handler_id = {:start, :rand.uniform(100)} stop_handler_id = {:stop, :rand.uniform(100)} on_exit(fn -> :telemetry.detach(start_handler_id) :telemetry.detach(stop_handler_id) end) {:ok, start_handler: start_handler_id, stop_handler: stop_handler_id} end test "emits an event before the pipeline and before sending the response", %{ start_handler: start_handler, stop_handler: stop_handler } do attach(start_handler, [:pipeline, :start]) attach(stop_handler, [:pipeline, :stop]) MyPlug.call(conn(:get, "/"), []) assert_received {:event, [:pipeline, :start], measurements, metadata} assert map_size(measurements) == 1 assert %{system_time: system_time} = measurements assert is_integer(system_time) and system_time > 0 assert map_size(metadata) == 2 assert %{conn: %Plug.Conn{}, options: [extra_options: :hello]} = metadata assert_received {:event, [:pipeline, :stop], measurements, metadata} assert map_size(measurements) == 1 assert %{duration: duration} = measurements assert is_integer(duration) assert map_size(metadata) == 2 assert %{conn: conn, options: [extra_options: :hello]} = metadata assert conn.state == :set assert conn.status == 200 end test "doesn't emit a stop event if the response is not sent", %{ start_handler: start_handler, stop_handler: stop_handler } do attach(start_handler, [:nosend, :pipeline, :start]) attach(stop_handler, [:nosend, :pipeline, :stop]) MyNoSendPlug.call(conn(:get, "/"), []) assert_received {:event, [:nosend, :pipeline, :start], _, _} refute_received {:event, [:nosend, :pipeline, :stop], _, _} end test "raises if event prefix is not provided" do assert_raise ArgumentError, ~r/^:event_prefix is required$/, fn -> Plug.Telemetry.init([]) end end test "raises if event prefix is not a list of atoms" do assert_raise ArgumentError, ~r/^expected :event_prefix to be a list of atoms, got: 1$/, fn -> Plug.Telemetry.init(event_prefix: 1) end end test "doesn't emit a stop event when the pipeline crashes", %{ start_handler: start_handler, stop_handler: stop_handler } do attach(start_handler, [:crashing, :pipeline, :start]) attach(stop_handler, [:crashing, :pipeline, :stop]) assert_raise RuntimeError, fn -> MyCrashingPlug.call(conn(:get, "/"), []) end assert_received {:event, [:crashing, :pipeline, :start], _, _} refute_received {:event, [:crashing, :pipeline, :stop], _, _} end defp attach(handler_id, event) do :telemetry.attach( handler_id, event, fn event, measurements, metadata, _ -> send(self(), {:event, event, measurements, metadata}) end, nil ) end end
28.186047
97
0.670792
79812e062eb977266d8f642d4be3cfae7a8aafd5
505
ex
Elixir
lib/threehundred60_web/views/error_view.ex
nesimtunc/ThreeHundred60
1dd8465b44f037ecf7d43be9ebd99b9eadcee6af
[ "MIT" ]
13
2020-06-03T08:17:45.000Z
2021-03-11T04:37:52.000Z
lib/threehundred60_web/views/error_view.ex
nesimtunc/ThreeHundred60
1dd8465b44f037ecf7d43be9ebd99b9eadcee6af
[ "MIT" ]
null
null
null
lib/threehundred60_web/views/error_view.ex
nesimtunc/ThreeHundred60
1dd8465b44f037ecf7d43be9ebd99b9eadcee6af
[ "MIT" ]
1
2020-06-26T16:53:14.000Z
2020-06-26T16:53:14.000Z
defmodule Threehundred60Web.ErrorView do use Threehundred60Web, :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.705882
61
0.742574
798158b25ce2729c8bc074d865abdfda2a66f581
894
ex
Elixir
clients/private_ca/lib/google_api/private_ca/v1beta1/metadata.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/private_ca/lib/google_api/private_ca/v1beta1/metadata.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/private_ca/lib/google_api/private_ca/v1beta1/metadata.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "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.PrivateCA.V1beta1 do @moduledoc """ API client metadata for GoogleApi.PrivateCA.V1beta1. """ @discovery_revision "20210506" def discovery_revision(), do: @discovery_revision end
33.111111
74
0.761745
7981600df48c5953813bd583c8b847df158b41f1
12,693
ex
Elixir
lib/con_cache.ex
stefanchrobot/con_cache
9a497cbf1a1295310480598538ba50686b349ef8
[ "MIT" ]
null
null
null
lib/con_cache.ex
stefanchrobot/con_cache
9a497cbf1a1295310480598538ba50686b349ef8
[ "MIT" ]
null
null
null
lib/con_cache.ex
stefanchrobot/con_cache
9a497cbf1a1295310480598538ba50686b349ef8
[ "MIT" ]
null
null
null
defmodule ConCache.Item do @moduledoc """ This struct can be used in place of naked values to set per-item TTL values. """ defstruct value: nil, ttl: :infinity @type t :: %ConCache.Item{ value: ConCache.value(), ttl: pos_integer | :infinity | :renew | :no_update } end defmodule ConCache do require Logger @moduledoc """ Implements an ETS based key/value storage with following additional features: - row level synchronized writes (inserts, read/modify/write updates, deletes) - TTL support - modification callbacks Example usage: ConCache.start_link(name: :my_cache, ttl_check_interval: false) ConCache.put(:my_cache, :foo, 1) ConCache.get(:my_cache, :foo) # 1 The following rules apply: - Modifications are by isolated per row. Two processes can't modify the same row at the same time. Dirty operations are available through `dirty_` equivalents. - Reads are dirty by default. You can use `isolated/4` to perform isolated custom operations. - Operations are always performed in the caller process. Custom lock implementation is used to ensure synchronism. See `README.md` for more details. - In this example, items don't expire. See `start_link/1` for details on how to setup expiry. See `start_link/1` for more details. """ alias ConCache.Owner alias ConCache.Operations defstruct [ :owner_pid, :ets, :ttl_manager, :ttl, :acquire_lock_timeout, :callback, :touch_on_read, :lock_pids ] @type t :: pid | atom | {:global, any} | {:via, atom, any} @type key :: any @type value :: any @type store_value :: value | ConCache.Item.t() @type callback_fun :: ({:update, pid, key, value} | {:delete, pid, key} -> any) @type ets_option :: :named_table | :compressed | {:heir, pid} | {:write_concurrency, boolean} | {:read_concurrency, boolean} | :ordered_set | :set | :bag | :duplicate_bag | {:name, atom} @type options :: [ {:name, atom} | {:global_ttl, non_neg_integer} | {:acquire_lock_timeout, pos_integer} | {:callback, callback_fun} | {:touch_on_read, boolean} | {:ttl_check_interval, non_neg_integer | false} | {:time_size, pos_integer} | {:ets_options, [ets_option]} ] @type update_fun :: (value -> {:ok, store_value} | {:error, any}) @type store_fun :: (() -> store_value) @doc """ Starts the server and creates an ETS table. Options: - `{:name, atom} - A name of the cache process.` - `{:ttl_check_interval, time_ms | false}` - Required. A check interval for TTL expiry. Provide a positive integer for expiry to work, or pass `false` to disable ttl checks. See below for more details on expiry. - `{:global_ttl, time_ms | :infinity}` - The time after which an item expires. When an item expires, it is removed from the cache. Updating the item extends its expiry time. - `{:touch_on_read, true | false}` - Controls whether read operation extends expiry of items. False by default. - `{:callback, callback_fun}` - If provided, this function is invoked __after__ an item is inserted or updated, or __before__ it is deleted. - `{:acquire_lock_timeout, timeout_ms}` - The time a client process waits for the lock. Default is 5000. - `{:ets_options, [ets_option]` – The options for ETS process. In addition, following ETS options are supported: - `:set` - An ETS table will be of the `:set` type (default). - `:ordered_set` - An ETS table will be of the `:ordered_set` type. - `:bag` - An ETS table will be of the `:bag` type. - `:duplicate_bag` - An ETS table will be of the `:duplicate_bag` type. - `:named_table` - `:name` - `:heir` - `:write_concurrency` - `:read_concurrency` ## Child specification To insert your cache into the supervision tree, pass the child specification in the shape of `{ConCache, con_cache_options}`. For example: ``` {ConCache, [name: :my_cache, ttl_check_interval: false]} ``` ## Expiry To configure expiry, you need to provide positive integer for the `:ttl_check_interval` option. This integer represents the millisecond interval in which the expiry is performed. You also need to provide the `:global_ttl` option, which represents the default TTL time for the item. TTL of each item is by default extended only on modifications. This can be changed with the `touch_on_read: true` option. If you need a granular control of expiry per each item, you can pass a `ConCache.Item` struct when storing data. If you don't want a modification of an item to extend its TTL, you can pass a `ConCache.Item` struct, with `:ttl` field set to `:no_update`. ### Choosing ttl_check_interval time When expiry is configured, the owner process works in discrete steps, doing cleanups every `ttl_check_interval` milliseconds. This approach allows the owner process to do fairly small amount of work in each discrete step. Assuming there's no huge system overload, an item's max lifetime is thus `global_ttl + ttl_check_interval` [ms], after the last item's update. Thus, a lower value of ttl_check_interval time means more frequent purging which may reduce your memory consumption, but could also cause performance penalties. Higher values put less pressure on processing, but item expiry is less precise. """ @spec start_link(options) :: Supervisor.on_start() def start_link(options) do options = Keyword.merge(options, ttl: options[:global_ttl], ttl_check: options[:ttl_check_interval]) with :ok <- validate_ttl(options[:ttl_check_interval], options[:global_ttl]) do Supervisor.start_link( [ {ConCache.LockSupervisor, System.schedulers_online()}, {Owner, options} ], [strategy: :one_for_all] ++ Keyword.take(options, [:name]) ) end end defp validate_ttl(false, nil), do: :ok defp validate_ttl(false, _global_ttl), do: raise( ArgumentError, "ConCache ttl_check_interval is false and global_ttl is set. Either remove your global_ttl or set ttl_check_interval to a time" ) defp validate_ttl(nil, _global_ttl), do: raise(ArgumentError, "ConCache ttl_check_interval must be supplied") defp validate_ttl(_ttl_check_interval, nil), do: raise(ArgumentError, "ConCache global_ttl must be supplied") defp validate_ttl(_ttl_check_interval, _global_ttl), do: :ok @doc false @spec child_spec(options) :: Supervisor.child_spec() def child_spec(opts) do %{ id: __MODULE__, start: {__MODULE__, :start_link, [opts]}, type: :supervisor } end @doc """ Returns the ets table managed by the cache. """ @spec ets(t) :: :ets.tab() def ets(cache_id), do: Operations.ets(Owner.cache(cache_id)) @doc """ Reads the item from the cache. A read is always "dirty", meaning it doesn't block while someone is updating the item under the same key. A read doesn't expire TTL of the item, unless `touch_on_read` option is set while starting the cache. """ @spec get(t, key) :: value def get(cache_id, key), do: Operations.get(Owner.cache(cache_id), key) @doc """ Stores the item into the cache. """ @spec put(t, key, store_value) :: :ok def put(cache_id, key, value), do: Operations.put(Owner.cache(cache_id), key, value) @doc """ Returns the number of items stored in the cache. """ @spec size(t) :: non_neg_integer def size(cache_id), do: Operations.size(Owner.cache(cache_id)) @doc """ Dirty equivalent of `put/3`. """ @spec dirty_put(t, key, store_value) :: :ok def dirty_put(cache_id, key, value), do: Operations.dirty_put(Owner.cache(cache_id), key, value) @doc """ Inserts the item into the cache unless it exists. """ @spec insert_new(t, key, store_value) :: :ok | {:error, :already_exists} def insert_new(cache_id, key, value), do: Operations.insert_new(Owner.cache(cache_id), key, value) @doc """ Dirty equivalent of `insert_new/3`. """ @spec dirty_insert_new(t, key, store_value) :: :ok | {:error, :already_exists} def dirty_insert_new(cache_id, key, value), do: Operations.insert_new(Owner.cache(cache_id), key, value) @doc """ Updates the item, or stores new item if it doesn't exist. The `update_fun` is invoked after the item is locked. Here, you can be certain that no other process will update this item, unless they are doing dirty updates or writing directly to the underlying ETS table. This function is not supported by `:bag` or `:duplicate_bag` ETS tables. The updater lambda must return one of the following: - `{:ok, value}` - causes the value to be stored into the table - `{:error, reason}` - the value won't be stored and `{:error, reason}` will be returned """ @spec update(t, key, update_fun) :: :ok | {:error, any} def update(cache_id, key, update_fun), do: Operations.update(Owner.cache(cache_id), key, update_fun) @doc """ Dirty equivalent of `update/3`. """ @spec dirty_update(t, key, update_fun) :: :ok | {:error, any} def dirty_update(cache_id, key, update_fun), do: Operations.dirty_update(Owner.cache(cache_id), key, update_fun) @doc """ Updates the item only if it exists. Otherwise works just like `update/3`. """ @spec update_existing(t, key, update_fun) :: :ok | {:error, :not_existing} | {:error, any} def update_existing(cache_id, key, update_fun), do: Operations.update_existing(Owner.cache(cache_id), key, update_fun) @doc """ Dirty equivalent of `update_existing/3`. """ @spec dirty_update_existing(t, key, update_fun) :: :ok | {:error, :not_existing} | {:error, any} def dirty_update_existing(cache_id, key, update_fun), do: Operations.dirty_update_existing(Owner.cache(cache_id), key, update_fun) @doc """ Deletes the item from the cache. """ @spec delete(t, key) :: :ok def delete(cache_id, key), do: Operations.delete(Owner.cache(cache_id), key) @doc """ Dirty equivalent of `delete/2`. """ @spec dirty_delete(t, key) :: :ok def dirty_delete(cache_id, key), do: Operations.dirty_delete(Owner.cache(cache_id), key) @doc """ Retrieves the item from the cache, or inserts the new item. If the item exists in the cache, it is retrieved. Otherwise, the lambda function is executed and its result is stored under the given key. This function is not supported by `:bag` and `:duplicate_bag` ETS tables. Note: if the item is already in the cache, this function amounts to a simple get without any locking, so you can expect it to be fairly fast. """ @spec get_or_store(t, key, store_fun) :: value def get_or_store(cache_id, key, store_fun), do: Operations.get_or_store(Owner.cache(cache_id), key, store_fun) @doc """ Dirty equivalent of `get_or_store/3`. """ @spec dirty_get_or_store(t, key, store_fun) :: value def dirty_get_or_store(cache_id, key, store_fun), do: Operations.dirty_get_or_store(Owner.cache(cache_id), key, store_fun) @doc """ Manually touches the item to prolongate its expiry. """ @spec touch(t, key) :: :ok def touch(cache_id, key), do: Operations.touch(Owner.cache(cache_id), key) @doc """ Isolated execution over arbitrary lock in the cache. You can do whatever you want in the function, not necessarily related to the cache. The return value is the result of the provided lambda. This allows you to perform flexible isolation. If you use the key of your item as a `key`, then this operation will be exclusive to updates. This can be used e.g. to perform isolated reads: # Process A: ConCache.isolated(:my_cache, :my_item_key, fn() -> ... end) # Process B: ConCache.update(:my_cache, :my_item, fn(old_value) -> ... end) These two operations are mutually exclusive. """ @spec isolated(t, key, nil | pos_integer, (() -> any)) :: any def isolated(cache_id, key, timeout \\ nil, fun), do: Operations.isolated(Owner.cache(cache_id), key, timeout, fun) @doc """ Similar to `isolated/4` except it doesn't wait for the lock to be available. If the lock can be acquired immediately, it will be acquired and the function will be invoked. Otherwise, an error is returned immediately. """ @spec try_isolated(t, key, nil | pos_integer, (() -> any)) :: {:error, :locked} | {:ok, any} def try_isolated(cache_id, key, timeout \\ nil, on_success), do: Operations.try_isolated(Owner.cache(cache_id), key, timeout, on_success) end
35.160665
135
0.682108
798160c4c034134dd5588d2257efb9074650786e
1,775
ex
Elixir
clients/play_custom_app/lib/google_api/play_custom_app/v1/model/custom_app.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
1
2021-10-01T09:20:41.000Z
2021-10-01T09:20:41.000Z
clients/play_custom_app/lib/google_api/play_custom_app/v1/model/custom_app.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/play_custom_app/lib/google_api/play_custom_app/v1/model/custom_app.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.PlayCustomApp.V1.Model.CustomApp do @moduledoc """ This resource represents a custom app. ## Attributes * `languageCode` (*type:* `String.t`, *default:* `nil`) - Default listing language in BCP 47 format. * `packageName` (*type:* `String.t`, *default:* `nil`) - Output only. Package name of the created Android app. Only present in the API response. * `title` (*type:* `String.t`, *default:* `nil`) - Title for the Android app. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :languageCode => String.t() | nil, :packageName => String.t() | nil, :title => String.t() | nil } field(:languageCode) field(:packageName) field(:title) end defimpl Poison.Decoder, for: GoogleApi.PlayCustomApp.V1.Model.CustomApp do def decode(value, options) do GoogleApi.PlayCustomApp.V1.Model.CustomApp.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.PlayCustomApp.V1.Model.CustomApp do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.490566
148
0.709859
7981769f21591a018772aeb76c8d6627871dd087
1,677
exs
Elixir
ttrack-backend/mix.exs
kacper-marzecki/ttrack
603cbe91800feb680996827f66eafd458b9b8a90
[ "MIT" ]
null
null
null
ttrack-backend/mix.exs
kacper-marzecki/ttrack
603cbe91800feb680996827f66eafd458b9b8a90
[ "MIT" ]
null
null
null
ttrack-backend/mix.exs
kacper-marzecki/ttrack
603cbe91800feb680996827f66eafd458b9b8a90
[ "MIT" ]
null
null
null
defmodule Ttrack.MixProject do use Mix.Project def project do [ app: :ttrack, version: "0.1.0", elixir: "~> 1.5", elixirc_paths: elixirc_paths(Mix.env()), compilers: [:phoenix, :gettext] ++ Mix.compilers(), start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps() ] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [ mod: {Ttrack.Application, []}, extra_applications: [:logger, :runtime_tools] ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Specifies your project dependencies. # # Type `mix help deps` for examples and options. defp deps do [ {:phoenix, "~> 1.4.11"}, {:phoenix_pubsub, "~> 1.1"}, {:phoenix_ecto, "~> 4.0"}, {:ecto_sql, "~> 3.1"}, {:postgrex, ">= 0.0.0"}, {:phoenix_html, "~> 2.11"}, {:phoenix_live_reload, "~> 1.2", only: :dev}, {:gettext, "~> 0.11"}, {:jason, "~> 1.0"}, {:plug_cowboy, "~> 2.0"}, {:doorman, "~> 0.6.2"} ] end # Aliases are shortcuts or tasks specific to the current project. # For example, to create, migrate and run the seeds file at once: # # $ mix ecto.setup # # See the documentation for `Mix` for more info on aliases. defp aliases do [ "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], test: ["ecto.create --quiet", "ecto.migrate", "test"] ] end end
26.203125
79
0.571855
79818c8ccdc292a99b5fe22a1e9ba82c6dfe9d2a
996
exs
Elixir
test/ex_doc/formatter/html/erlang_test.exs
mayel/ex_doc
6e5ecfa7d6248fd8038caf4e9f4ac02eb13d0d0f
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
test/ex_doc/formatter/html/erlang_test.exs
mayel/ex_doc
6e5ecfa7d6248fd8038caf4e9f4ac02eb13d0d0f
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
test/ex_doc/formatter/html/erlang_test.exs
mayel/ex_doc
6e5ecfa7d6248fd8038caf4e9f4ac02eb13d0d0f
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
defmodule ExDoc.Formatter.HTML.ErlangTest do use ExUnit.Case import TestHelper @moduletag :otp_eep48 @moduletag :tmp_dir test "it works", c do erlc(c, :foo, ~S""" %% @doc %% foo module. -module(foo). -export([foo/1]). -export_type([t/0]). %% @doc %% f/0 function. -spec foo(atom()) -> atom(). foo(X) -> X. -type t() :: atom(). %% t/0 type. """) doc = generate_docs(c) assert [_] = Floki.find(doc, "pre:fl-contains('foo(atom()) -> atom().')") assert [_] = Floki.find(doc, "pre:fl-contains('t() :: atom().')") end defp generate_docs(c) do config = [ version: "1.0.0", project: "Foo", formatter: "html", output: Path.join(c.tmp_dir, "doc"), source_beam: Path.join(c.tmp_dir, "ebin"), extras: [] ] ExDoc.generate_docs(config[:project], config[:version], config) [c.tmp_dir, "doc", "foo.html"] |> Path.join() |> File.read!() |> Floki.parse_document!() end end
21.652174
92
0.549197
79818d43814d396717ba8807f5332f3c2648d7c2
1,817
ex
Elixir
clients/game_services/lib/google_api/game_services/v1/model/preview_update_game_server_cluster_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/game_services/lib/google_api/game_services/v1/model/preview_update_game_server_cluster_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/game_services/lib/google_api/game_services/v1/model/preview_update_game_server_cluster_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.GameServices.V1.Model.PreviewUpdateGameServerClusterResponse do @moduledoc """ Response message for GameServerClustersService.PreviewUpdateGameServerCluster ## Attributes * `etag` (*type:* `String.t`, *default:* `nil`) - The ETag of the game server cluster. * `targetState` (*type:* `GoogleApi.GameServices.V1.Model.TargetState.t`, *default:* `nil`) - The target state. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :etag => String.t() | nil, :targetState => GoogleApi.GameServices.V1.Model.TargetState.t() | nil } field(:etag) field(:targetState, as: GoogleApi.GameServices.V1.Model.TargetState) end defimpl Poison.Decoder, for: GoogleApi.GameServices.V1.Model.PreviewUpdateGameServerClusterResponse do def decode(value, options) do GoogleApi.GameServices.V1.Model.PreviewUpdateGameServerClusterResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.GameServices.V1.Model.PreviewUpdateGameServerClusterResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.942308
115
0.749587
79819a2f671bafe540f30e71481bb5a71405b466
3,948
exs
Elixir
test/phoenix/integration/websocket_socket_test.exs
clickavia/phoenix
60ff50fc7c8cf4fbac462961cbbdd370049df6b3
[ "MIT" ]
null
null
null
test/phoenix/integration/websocket_socket_test.exs
clickavia/phoenix
60ff50fc7c8cf4fbac462961cbbdd370049df6b3
[ "MIT" ]
null
null
null
test/phoenix/integration/websocket_socket_test.exs
clickavia/phoenix
60ff50fc7c8cf4fbac462961cbbdd370049df6b3
[ "MIT" ]
null
null
null
Code.require_file("../../support/websocket_client.exs", __DIR__) defmodule Phoenix.Integration.WebSocketTest do use ExUnit.Case, async: true import ExUnit.CaptureLog alias Phoenix.Integration.WebsocketClient alias __MODULE__.Endpoint @moduletag :capture_log @port 5907 @path "ws://127.0.0.1:#{@port}/ws/websocket" Application.put_env( :phoenix, Endpoint, https: false, http: [port: @port], debug_errors: false, server: true ) defmodule UserSocket do @behaviour Phoenix.Socket.Transport def child_spec(opts) do :value = Keyword.fetch!(opts, :custom) Supervisor.Spec.worker(Task, [fn -> :ok end], restart: :transient) end def connect(map) do %{endpoint: Endpoint, params: params, transport: :websocket} = map {:ok, {:params, params}} end def init({:params, _} = state) do {:ok, state} end def handle_in({"params", opts}, {:params, params} = state) do :text = Keyword.fetch!(opts, :opcode) {:reply, :ok, {:text, inspect(params)}, state} end def handle_in({"ping", opts}, state) do :text = Keyword.fetch!(opts, :opcode) send(self(), :ping) {:ok, state} end def handle_info(:ping, state) do {:push, {:text, "pong"}, state} end def terminate(_reason, {:params, _}) do :ok end end defmodule Endpoint do use Phoenix.Endpoint, otp_app: :phoenix socket "/ws", UserSocket, websocket: [check_origin: ["//example.com"], subprotocols: ["sip"], timeout: 200], custom: :value socket "/custom/some_path", UserSocket, websocket: [path: "nested/path", check_origin: ["//example.com"], timeout: 200], custom: :value socket "/custom/:socket_var", UserSocket, websocket: [path: ":path_var/path", check_origin: ["//example.com"], timeout: 200], custom: :value end setup_all do capture_log(fn -> Endpoint.start_link() end) :ok end test "refuses unallowed origins" do capture_log(fn -> headers = [{"origin", "https://example.com"}] assert {:ok, _} = WebsocketClient.start_link(self(), @path, :noop, headers) headers = [{"origin", "http://notallowed.com"}] assert {:error, {403, _}} = WebsocketClient.start_link(self(), @path, :noop, headers) end) end test "refuses unallowed Websocket subprotocols" do assert capture_log(fn -> headers = [{"sec-websocket-protocol", "sip"}] assert {:ok, _} = WebsocketClient.start_link(self(), @path, :noop, headers) headers = [] assert {:ok, _} = WebsocketClient.start_link(self(), @path, :noop, headers) headers = [{"sec-websocket-protocol", "mqtt"}] assert {:error, {403, _}} = WebsocketClient.start_link(self(), @path, :noop, headers) end) =~ "Could not check Websocket subprotocols" end test "returns params with sync request" do assert {:ok, client} = WebsocketClient.start_link(self(), "#{@path}?key=value", :noop) WebsocketClient.send_message(client, "params") assert_receive {:text, ~s(%{"key" => "value"})} end test "returns pong from async request" do assert {:ok, client} = WebsocketClient.start_link(self(), "#{@path}?key=value", :noop) WebsocketClient.send_message(client, "ping") assert_receive {:text, "pong"} end test "allows a custom path" do path = "ws://127.0.0.1:#{@port}/custom/some_path/nested/path" assert {:ok, _} = WebsocketClient.start_link(self(), "#{path}?key=value", :noop) end @tag :cowboy2 test "allows a path with variables" do path = "ws://127.0.0.1:#{@port}/custom/123/456/path" assert {:ok, client} = WebsocketClient.start_link(self(), "#{path}?key=value", :noop) WebsocketClient.send_message(client, "params") assert_receive {:text, params} assert params =~ ~s("key" => "value") assert params =~ ~s("socket_var" => "123") assert params =~ ~s(path_var" => "456") end end
29.909091
91
0.631966
7981a55447e9f975aa600cd2117be4faa81ac8a6
2,263
exs
Elixir
server/test/events_app/events_test.exs
kylesmith-1/blazeneu
83cb68b8112bac8d51c9f92e709720d7e7ba1472
[ "MIT" ]
null
null
null
server/test/events_app/events_test.exs
kylesmith-1/blazeneu
83cb68b8112bac8d51c9f92e709720d7e7ba1472
[ "MIT" ]
null
null
null
server/test/events_app/events_test.exs
kylesmith-1/blazeneu
83cb68b8112bac8d51c9f92e709720d7e7ba1472
[ "MIT" ]
1
2021-04-10T18:37:30.000Z
2021-04-10T18:37:30.000Z
defmodule CompanyTest.EventsTest do use CompanyTest.DataCase alias CompanyTest.Events describe "events" do alias CompanyTest.Events.Event @valid_attrs %{body: "some body", date: "some date", event_title: "some event_title"} @update_attrs %{body: "some updated body", date: "some updated date", event_title: "some updated event_title"} @invalid_attrs %{body: nil, date: nil, event_title: nil} def event_fixture(attrs \\ %{}) do {:ok, event} = attrs |> Enum.into(@valid_attrs) |> Events.create_event() event end test "list_events/0 returns all events" do event = event_fixture() assert Events.list_events() == [event] end test "get_event!/1 returns the event with given id" do event = event_fixture() assert Events.get_event!(event.id) == event end test "create_event/1 with valid data creates a event" do assert {:ok, %Event{} = event} = Events.create_event(@valid_attrs) assert event.body == "some body" assert event.date == "some date" assert event.event_title == "some event_title" end test "create_event/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Events.create_event(@invalid_attrs) end test "update_event/2 with valid data updates the event" do event = event_fixture() assert {:ok, %Event{} = event} = Events.update_event(event, @update_attrs) assert event.body == "some updated body" assert event.date == "some updated date" assert event.event_title == "some updated event_title" end test "update_event/2 with invalid data returns error changeset" do event = event_fixture() assert {:error, %Ecto.Changeset{}} = Events.update_event(event, @invalid_attrs) assert event == Events.get_event!(event.id) end test "delete_event/1 deletes the event" do event = event_fixture() assert {:ok, %Event{}} = Events.delete_event(event) assert_raise Ecto.NoResultsError, fn -> Events.get_event!(event.id) end end test "change_event/1 returns a event changeset" do event = event_fixture() assert %Ecto.Changeset{} = Events.change_event(event) end end end
32.797101
114
0.665488
7981be007e7e1ff8282fee6e9f7e7646c552813d
1,329
exs
Elixir
backend/test/spades_chat/chat_server_test.exs
mreishus/spades
3e06fa5c2415ff43258ec4c231f8d6c49c683fe0
[ "MIT" ]
9
2019-10-28T08:48:50.000Z
2021-03-05T09:44:46.000Z
backend/test/spades_chat/chat_server_test.exs
mreishus/spades
3e06fa5c2415ff43258ec4c231f8d6c49c683fe0
[ "MIT" ]
227
2019-10-28T08:52:58.000Z
2022-02-27T04:31:42.000Z
backend/test/spades_chat/chat_server_test.exs
mreishus/spades
3e06fa5c2415ff43258ec4c231f8d6c49c683fe0
[ "MIT" ]
4
2020-04-18T19:38:37.000Z
2021-08-02T19:43:03.000Z
defmodule ChatServerTest do use ExUnit.Case, async: true alias SpadesChat.{ChatServer} describe "start_link/1" do test "spawns a process" do chat_name = generate_chat_name() assert {:ok, _pid} = ChatServer.start_link(chat_name) end test "each name can only have one process" do chat_name = generate_chat_name() assert {:ok, _pid} = ChatServer.start_link(chat_name) assert {:error, _reason} = ChatServer.start_link(chat_name) end end describe "add_message/2 and messages/1" do test "general message persistance" do chat_name = generate_chat_name() assert {:ok, _pid} = ChatServer.start_link(chat_name) ChatServer.add_message(chat_name, "m1") ChatServer.add_message(chat_name, "m2") ChatServer.add_message(chat_name, "m3") messages = ChatServer.messages(chat_name) assert messages == ["m1", "m2", "m3"] end test "message limit 250" do chat_name = generate_chat_name() assert {:ok, _pid} = ChatServer.start_link(chat_name) 1..1000 |> Enum.each(fn _ -> ChatServer.add_message(chat_name, "hi") end) messages = ChatServer.messages(chat_name) assert length(messages) == 250 end end defp generate_chat_name do "chat-#{:rand.uniform(1_000_000)}" end end
26.58
65
0.665914
7981cbe899b98074705a63ade21958d75468a561
7,191
ex
Elixir
lib/sitemap/builders/url.ex
ikeikeikeike/ex_sitemap_generator
bab8cdc153b07ddd1183cdc4d01e966bfebfcfdc
[ "MIT" ]
103
2016-04-26T17:31:58.000Z
2022-02-15T12:26:06.000Z
lib/sitemap/builders/url.ex
ikeikeikeike/ex_sitemap_generator
bab8cdc153b07ddd1183cdc4d01e966bfebfcfdc
[ "MIT" ]
31
2016-06-02T17:26:56.000Z
2021-11-17T13:19:26.000Z
lib/sitemap/builders/url.ex
ikeikeikeike/ex_sitemap_generator
bab8cdc153b07ddd1183cdc4d01e966bfebfcfdc
[ "MIT" ]
24
2016-09-09T23:45:25.000Z
2021-02-15T16:36:43.000Z
defmodule Sitemap.Builders.Url do alias Sitemap.Funcs alias Sitemap.Config import XmlBuilder def to_xml(link, attrs \\ []) do elms = element( :url, Funcs.eraser([ element(:loc, Path.join(Config.get().host, link || "")), element( :lastmod, Funcs.iso8601(Keyword.get_lazy(attrs, :lastmod, fn -> Funcs.iso8601() end)) ), element(:expires, attrs[:expires]), element(:changefreq, attrs[:changefreq]), element(:priority, attrs[:priority]) ]) ) elms = ifput(attrs[:mobile], elms, &append_last(&1, mobile())) elms = ifput(attrs[:geo], elms, &append_last(&1, geo(attrs[:geo]))) elms = ifput(attrs[:news], elms, &append_last(&1, news(attrs[:news]))) elms = ifput(attrs[:pagemap], elms, &append_last(&1, pagemap(attrs[:pagemap]))) elms = ifput(attrs[:images], elms, &append_last(&1, images(attrs[:images]))) elms = ifput(attrs[:videos], elms, &append_last(&1, videos(attrs[:videos]))) elms = ifput(attrs[:alternates], elms, &append_last(&1, alternates(attrs[:alternates]))) elms end defp ifput(bool, elms, fun) do if bool do fun.(elms) else elms end end defp append_last(elements, element) do combine = elem(elements, 2) ++ [element] elements |> Tuple.delete_at(2) |> Tuple.append(combine) end defp news(data) do element( :"news:news", Funcs.eraser([ element( :"news:publication", Funcs.eraser([ element(:"news:name", data[:publication_name]), element(:"news:language", data[:publication_language]) ]) ), element(:"news:title", data[:title]), element(:"news:access", data[:access]), element(:"news:genres", data[:genres]), element(:"news:keywords", data[:keywords]), element(:"news:stock_tickers", data[:stock_tickers]), element(:"news:publication_date", Funcs.iso8601(data[:publication_date])) ]) ) end defp images(list, elements \\ []) defp images([], elements), do: elements defp images([{_, _} | _] = list, elements) do # Make sure keyword list images([list], elements) end defp images([data | tail], elements) do elm = element( :"image:image", Funcs.eraser([ element(:"image:loc", data[:loc]), unless(is_nil(data[:title]), do: element(:"image:title", data[:title])), unless(is_nil(data[:license]), do: element(:"image:license", data[:license])), unless(is_nil(data[:caption]), do: element(:"image:caption", data[:caption])), unless(is_nil(data[:geo_location]), do: element(:"image:geo_location", data[:geo_location]) ) ]) ) images(tail, elements ++ [elm]) end defp videos(list, elements \\ []) defp videos([], elements), do: elements defp videos([{_, _} | _] = list, elements) do # Make sure keyword list videos([list], elements) end defp videos([data | tail], elements) do elm = element( :"video:video", Funcs.eraser([ element(:"video:title", data[:title]), element(:"video:description", data[:description]), if data[:player_loc] do attrs = %{allow_embed: Funcs.yes_no(data[:allow_embed])} attrs = ifput( data[:autoplay], attrs, &Map.put(&1, :autoplay, Funcs.autoplay(data[:autoplay])) ) element(:"video:player_loc", attrs, data[:player_loc]) end, element(:"video:content_loc", data[:content_loc]), element(:"video:thumbnail_loc", data[:thumbnail_loc]), element(:"video:duration", data[:duration]), unless(is_nil(data[:gallery_loc]), do: element(:"video:gallery_loc", %{title: data[:gallery_title]}, data[:gallery_loc]) ), unless(is_nil(data[:rating]), do: element(:"video:rating", data[:rating])), unless(is_nil(data[:view_count]), do: element(:"video:view_count", data[:view_count])), unless(is_nil(data[:expiration_date]), do: element(:"video:expiration_date", Funcs.iso8601(data[:expiration_date])) ), unless(is_nil(data[:publication_date]), do: element(:"video:publication_date", Funcs.iso8601(data[:publication_date])) ), unless(is_nil(data[:tags]), do: Enum.map(data[:tags] || [], &element(:"video:tag", &1))), unless(is_nil(data[:tag]), do: element(:"video:tag", data[:tag])), unless(is_nil(data[:category]), do: element(:"video:category", data[:category])), unless(is_nil(data[:family_friendly]), do: element(:"video:family_friendly", Funcs.yes_no(data[:family_friendly])) ), unless is_nil(data[:restriction]) do attrs = %{relationship: Funcs.allow_deny(data[:relationship])} element(:"video:restriction", attrs, data[:restriction]) end, unless is_nil(data[:uploader]) do attrs = %{} attrs = ifput(data[:uploader_info], attrs, &Map.put(&1, :info, data[:uploader_info])) element(:"video:uploader", attrs, data[:uploader]) end, unless(is_nil(data[:price]), do: element(:"video:price", video_price_attrs(data), data[:price]) ), unless(is_nil(data[:live]), do: element(:"video:live", Funcs.yes_no(data[:live]))), unless(is_nil(data[:requires_subscription]), do: element(:"video:requires_subscription", Funcs.yes_no(data[:requires_subscription])) ) ]) ) videos(tail, elements ++ [elm]) end defp video_price_attrs(data) do attrs = %{} attrs = Map.put(attrs, :currency, data[:price_currency]) attrs = ifput(data[:price_type], attrs, &Map.put(&1, :type, data[:price_type])) attrs = ifput(data[:price_type], attrs, &Map.put(&1, :resolution, data[:price_resolution])) attrs end defp alternates(list, elements \\ []) defp alternates([], elements), do: elements defp alternates([{_, _} | _] = list, elements) do # Make sure keyword list alternates([list], elements) end defp alternates([data | tail], elements) do rel = if data[:nofollow], do: "alternate nofollow", else: "alternate" attrs = %{rel: rel, href: data[:href]} attrs = Map.put(attrs, :hreflang, data[:lang]) attrs = Map.put(attrs, :media, data[:media]) alternates(tail, elements ++ [element(:"xhtml:link", attrs)]) end defp geo(data) do element(:"geo:geo", [ element(:"geo:format", data[:format]) ]) end defp mobile do element(:"mobile:mobile") end defp pagemap(data) do element( :PageMap, Enum.map(data[:dataobjects] || [], fn obj -> element( :DataObject, %{type: obj[:type], id: obj[:id]}, Enum.map(obj[:attributes] || [], fn attr -> element(:Attribute, %{name: attr[:name]}, attr[:value]) end) ) end) ) end end
33.291667
99
0.573773
7981cdf2ee05f9f75532f92b8443b5ab6d15099b
11,903
ex
Elixir
lib/live_element/upload.ex
gaslight/live_element
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
[ "MIT" ]
null
null
null
lib/live_element/upload.ex
gaslight/live_element
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
[ "MIT" ]
null
null
null
lib/live_element/upload.ex
gaslight/live_element
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
[ "MIT" ]
null
null
null
defmodule LiveElement.Upload do # Operations integrating LiveElement.Socket with UploadConfig. @moduledoc false alias LiveElement.{Socket, Utils, UploadConfig, UploadEntry} @refs_to_names :__phoenix_refs_to_names__ @doc """ Allows an upload. """ def allow_upload(%Socket{} = socket, name, opts) when is_atom(name) and is_list(opts) do case uploaded_entries(socket, name) do {[], []} -> :ok {_, _} -> raise ArgumentError, """ cannot allow_upload on an existing upload with active entries. Use cancel_upload and/or consume_upload to handle the active entries before allowing a new upload. """ end ref = Utils.random_id() uploads = socket.assigns[:uploads] || %{} upload_config = UploadConfig.build(name, ref, opts) new_uploads = uploads |> Map.put(name, upload_config) |> Map.update(@refs_to_names, %{ref => name}, fn refs -> Map.put(refs, ref, name) end) Utils.assign(socket, :uploads, new_uploads) end @doc """ Disallows a previously allowed upload. """ def disallow_upload(%Socket{} = socket, name) when is_atom(name) do case uploaded_entries(socket, name) do {[], []} -> uploads = socket.assigns[:uploads] || %{} upload_config = uploads |> Map.fetch!(name) |> UploadConfig.disallow() new_refs = Enum.reduce(uploads[@refs_to_names], uploads[@refs_to_names], fn {ref, ^name}, acc -> Map.delete(acc, ref) {_ref, _name}, acc -> acc end) new_uploads = uploads |> Map.put(name, upload_config) |> Map.update!(@refs_to_names, fn _ -> new_refs end) Utils.assign(socket, :uploads, new_uploads) {_completed, _inprogress} -> raise RuntimeError, "unable to disallow_upload for an upload with active entries" end end @doc """ Cancels an upload entry. """ def cancel_upload(socket, name, entry_ref) do upload_config = Map.fetch!(socket.assigns[:uploads] || %{}, name) %UploadEntry{} = entry = UploadConfig.get_entry_by_ref(upload_config, entry_ref) upload_config |> UploadConfig.cancel_entry(entry) |> update_uploads(socket) end @doc """ Cancels all uploads that exist. Returns the new socket with the cancelled upload configs. """ def maybe_cancel_uploads(socket) do uploads = socket.assigns[:uploads] || %{} uploads |> Map.delete(@refs_to_names) |> Enum.reduce({socket, []}, fn {name, conf}, {socket_acc, conf_acc} -> new_socket = Enum.reduce(conf.entries, socket_acc, fn entry, inner_acc -> cancel_upload(inner_acc, name, entry.ref) end) {new_socket, [conf | conf_acc]} end) end @doc """ Updates the entry metadata. """ def update_upload_entry_meta(%Socket{} = socket, upload_conf_name, %UploadEntry{} = entry, meta) do socket.assigns.uploads |> Map.fetch!(upload_conf_name) |> UploadConfig.update_entry_meta(entry.ref, meta) |> update_uploads(socket) end @doc """ Updates the entry progress. Progress is either an integer percently between 0 and 100, or a map with an `"error"` key containing the information for a failed upload while in progress on the client. """ def update_progress(%Socket{} = socket, config_ref, entry_ref, progress) when is_integer(progress) and progress >= 0 and progress <= 100 do socket |> get_upload_by_ref!(config_ref) |> UploadConfig.update_progress(entry_ref, progress) |> update_uploads(socket) end def update_progress(%Socket{} = socket, config_ref, entry_ref, %{"error" => reason}) when is_binary(reason) do conf = get_upload_by_ref!(socket, config_ref) put_upload_error(socket, conf.name, entry_ref, :external_client_failure) end @doc """ Puts the entries into the `%UploadConfig{}`. """ def put_entries(%Socket{} = socket, %UploadConfig{} = conf, entries, cid) do case UploadConfig.put_entries(%UploadConfig{conf | cid: cid}, entries) do {:ok, new_config} -> {:ok, update_uploads(new_config, socket)} {:error, new_config} -> errors_resp = Enum.map(new_config.errors, fn {ref, msg} -> [ref, msg] end) {:error, %{ref: conf.ref, error: errors_resp}, update_uploads(new_config, socket)} end end @doc """ Unregisters a completed entry from an `LiveElement.UploadChannel` process. """ def unregister_completed_entry_upload(%Socket{} = socket, %UploadConfig{} = conf, entry_ref) do conf |> UploadConfig.unregister_completed_entry(entry_ref) |> update_uploads(socket) end @doc """ Registers a new entry upload for an `LiveElement.UploadChannel` process. """ def register_entry_upload(%Socket{} = socket, %UploadConfig{} = conf, pid, entry_ref) when is_pid(pid) do case UploadConfig.register_entry_upload(conf, pid, entry_ref) do {:ok, new_config} -> entry = UploadConfig.get_entry_by_ref(new_config, entry_ref) {:ok, update_uploads(new_config, socket), entry} {:error, reason} -> {:error, reason} end end @doc """ Populates the errors for a given entry. """ def put_upload_error(%Socket{} = socket, conf_name, entry_ref, reason) do conf = Map.fetch!(socket.assigns.uploads, conf_name) conf |> UploadConfig.put_error(entry_ref, reason) |> update_uploads(socket) end @doc """ Retrieves the `%UploadConfig{}` from the socket for the provided ref or raises. """ def get_upload_by_ref!(%Socket{} = socket, config_ref) do uploads = socket.assigns[:uploads] || raise(ArgumentError, no_upload_allowed_message(socket)) name = Map.fetch!(uploads[@refs_to_names], config_ref) Map.fetch!(uploads, name) end defp no_upload_allowed_message(socket) do "no uploads have been allowed on " <> if(socket.assigns[:myself], do: "component running inside ", else: "") <> "LiveView named #{inspect(socket.view)}" end @doc """ Returns the `%UploadConfig{}` from the socket for the `LiveElement.UploadChannel` pid. """ def get_upload_by_pid(socket, pid) when is_pid(pid) do Enum.find_value(socket.assigns[:uploads] || %{}, fn {@refs_to_names, _} -> false {_name, %UploadConfig{} = conf} -> UploadConfig.get_entry_by_pid(conf, pid) && conf end) end @doc """ Returns the completed and in progress entries for the upload. """ def uploaded_entries(%Socket{} = socket, name) do entries = case Map.fetch(socket.assigns[:uploads] || %{}, name) do {:ok, conf} -> conf.entries :error -> [] end Enum.reduce(entries, {[], []}, fn entry, {done, in_progress} -> if entry.done? do {[entry | done], in_progress} else {done, [entry | in_progress]} end end) end @doc """ Consumes the uploaded entries or raises if entries are still in progress. """ def consume_uploaded_entries(%Socket{} = socket, name, func) when is_function(func, 2) do conf = socket.assigns[:uploads][name] || raise ArgumentError, "no upload allowed for #{inspect(name)}" case uploaded_entries(socket, name) do {[_ | _] = done_entries, []} -> consume_entries(conf, done_entries, func) {_, [_ | _]} -> raise ArgumentError, "cannot consume uploaded files when entries are still in progress" {[], []} -> [] end end @doc """ Consumes an individual entry or raises if it is still in progress. """ def consume_uploaded_entry(%Socket{} = socket, %UploadEntry{} = entry, func) when is_function(func, 1) do unless entry.done?, do: raise(ArgumentError, "cannot consume uploaded files when entries are still in progress") conf = Map.fetch!(socket.assigns[:uploads], entry.upload_config) [result] = consume_entries(conf, [entry], func) result end @doc """ Drops all entries from the upload. """ def drop_upload_entries(%Socket{} = socket, %UploadConfig{} = conf, entry_refs) do conf.entries |> Enum.filter(fn entry -> entry.ref in entry_refs end) |> Enum.reduce(conf, fn entry, acc -> UploadConfig.drop_entry(acc, entry) end) |> update_uploads(socket) end defp update_uploads(%UploadConfig{} = new_conf, %Socket{} = socket) do new_uploads = Map.update!(socket.assigns.uploads, new_conf.name, fn _ -> new_conf end) Utils.assign(socket, :uploads, new_uploads) end defp consume_entries(%UploadConfig{} = conf, entries, func) when is_list(entries) and is_function(func) do if conf.external do results = entries |> Enum.map(fn entry -> meta = Map.fetch!(conf.entry_refs_to_metas, entry.ref) cond do is_function(func, 1) -> func.(meta) is_function(func, 2) -> func.(meta, entry) end end) entry_refs = for entry <- entries, do: entry.ref LiveElement.Channel.drop_upload_entries(conf, entry_refs) results else entries |> Enum.map(fn entry -> {entry, UploadConfig.entry_pid(conf, entry)} end) |> Enum.filter(fn {_entry, pid} -> is_pid(pid) end) |> Enum.map(fn {entry, pid} -> LiveElement.UploadChannel.consume(pid, entry, func) end) end end @doc """ Generates a preflight response by calling the `:external` function. """ def generate_preflight_response(%Socket{} = socket, name, cid) do %UploadConfig{} = conf = Map.fetch!(socket.assigns.uploads, name) client_meta = %{ max_file_size: conf.max_file_size, max_entries: conf.max_entries, chunk_size: conf.chunk_size } {new_socket, new_conf, new_entries} = mark_preflighted(socket, conf) case new_conf.external do false -> channel_preflight(new_socket, new_conf, new_entries, cid, client_meta) func when is_function(func) -> external_preflight(new_socket, new_conf, new_entries, client_meta) end end defp mark_preflighted(socket, conf) do {new_conf, new_entries} = UploadConfig.mark_preflighted(conf) new_socket = update_uploads(new_conf, socket) {new_socket, new_conf, new_entries} end defp channel_preflight( %Socket{} = socket, %UploadConfig{} = conf, entries, cid, %{} = client_config_meta ) do reply_entries = for entry <- entries, into: %{} do token = LiveElement.Static.sign_token(socket.endpoint, %{ pid: self(), ref: {conf.ref, entry.ref}, cid: cid }) {entry.ref, token} end {:ok, %{ref: conf.ref, config: client_config_meta, entries: reply_entries}, socket} end defp external_preflight(%Socket{} = socket, %UploadConfig{} = conf, entries, client_config_meta) do reply_entries = Enum.reduce_while(entries, {:ok, %{}, socket}, fn entry, {:ok, metas, acc} -> case conf.external.(entry, acc) do {:ok, %{} = meta, new_socket} -> new_socket = update_upload_entry_meta(new_socket, conf.name, entry, meta) {:cont, {:ok, Map.put(metas, entry.ref, meta), new_socket}} {:error, %{} = meta, new_socket} -> {:halt, {:error, {entry.ref, meta}, new_socket}} end end) case reply_entries do {:ok, entry_metas, new_socket} -> {:ok, %{ref: conf.ref, config: client_config_meta, entries: entry_metas}, new_socket} {:error, {entry_ref, meta_reason}, new_socket} -> new_socket = put_upload_error(new_socket, conf.name, entry_ref, meta_reason) {:error, %{ref: conf.ref, error: [[entry_ref, meta_reason]]}, new_socket} end end def register_cid(%Socket{} = socket, ref, cid) do socket |> get_upload_by_ref!(ref) |> UploadConfig.register_cid(cid) |> update_uploads(socket) end end
31.24147
106
0.642527
7981e59ce7711e3c597a88add370fae7f6d74e9c
108
ex
Elixir
backend/lib/getaways/repo.ex
Prumme/Projet_phx_ex_gql
6324af91f94f96ee1f8403d5397ab930347e3e4f
[ "Unlicense" ]
null
null
null
backend/lib/getaways/repo.ex
Prumme/Projet_phx_ex_gql
6324af91f94f96ee1f8403d5397ab930347e3e4f
[ "Unlicense" ]
6
2020-01-31T19:44:15.000Z
2021-09-02T04:26:49.000Z
backend/lib/getaways/repo.ex
Prumme/Projet_phx_ex_gql
6324af91f94f96ee1f8403d5397ab930347e3e4f
[ "Unlicense" ]
null
null
null
defmodule Getaways.Repo do use Ecto.Repo, otp_app: :getaways, adapter: Ecto.Adapters.Postgres end
18
35
0.731481
79821ace54626601a7ebe36ce585eddf2019e0c0
484
ex
Elixir
web/lib/squitter_web/application.ex
electricshaman/squitter
7a0dfbc125118b764d192f02b42b36596f6d4ac6
[ "MIT" ]
34
2017-08-30T02:29:41.000Z
2021-05-29T20:21:43.000Z
web/lib/squitter_web/application.ex
electricshaman/squitter
7a0dfbc125118b764d192f02b42b36596f6d4ac6
[ "MIT" ]
7
2017-09-12T05:27:23.000Z
2020-01-06T22:07:52.000Z
web/lib/squitter_web/application.ex
electricshaman/squitter
7a0dfbc125118b764d192f02b42b36596f6d4ac6
[ "MIT" ]
9
2017-09-11T22:17:55.000Z
2022-01-31T03:07:58.000Z
defmodule Squitter.Web.Application do use Application require Logger def start(_type, _args) do import Supervisor.Spec Logger.debug("Squitter web starting up") children = [ supervisor(Squitter.Web.Endpoint, []) ] opts = [strategy: :one_for_one, name: Squitter.Web.Supervisor] Supervisor.start_link(children, opts) end def config_change(changed, _new, removed) do Squitter.Web.Endpoint.config_change(changed, removed) :ok end end
21.043478
66
0.706612
79823eb2e89e85654de3c381ba1397167dc6d31b
424
ex
Elixir
server/apps/boardr/lib/boardr/release.ex
AlphaHydrae/boardr
98eed02801f88c065a24bf13051c5cf96270a5f7
[ "MIT" ]
1
2021-04-08T17:26:27.000Z
2021-04-08T17:26:27.000Z
server/apps/boardr/lib/boardr/release.ex
AlphaHydrae/boardr
98eed02801f88c065a24bf13051c5cf96270a5f7
[ "MIT" ]
1
2022-02-13T05:50:46.000Z
2022-02-13T05:50:46.000Z
server/apps/boardr/lib/boardr/release.ex
AlphaHydrae/boardr
98eed02801f88c065a24bf13051c5cf96270a5f7
[ "MIT" ]
null
null
null
defmodule Boardr.Release do @app :boardr def migrate do for repo <- repos() do {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :up, all: true)) end end def rollback(repo, version) do {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version)) end defp repos do Application.load(@app) Application.fetch_env!(@app, :ecto_repos) end end
22.315789
91
0.641509
798266ba0303557bddcda4deee0bd577ac0c28ec
719
ex
Elixir
lib/syn_osc/relative_base.ex
camshaft/syn_osc_ex
c7ed257f2ea772f197096d356467e812a0d5e59a
[ "MIT" ]
1
2020-12-08T01:44:03.000Z
2020-12-08T01:44:03.000Z
lib/syn_osc/relative_base.ex
camshaft/syn_osc_ex
c7ed257f2ea772f197096d356467e812a0d5e59a
[ "MIT" ]
null
null
null
lib/syn_osc/relative_base.ex
camshaft/syn_osc_ex
c7ed257f2ea772f197096d356467e812a0d5e59a
[ "MIT" ]
null
null
null
defmodule SynOSC.RelativeBase do defstruct id: nil, cents: nil, numerator: nil, denominator: nil end defimpl OSC.Encoder, for: SynOSC.RelativeBase do use SynOSC def encode(message, options) do message |> call("BASE") |> set_arguments(format_base(message)) |> OSC.Encoder.encode(options) end defp format_base(%{cents: cents}) when is_integer(cents) do [false, cents] end defp format_base(%{numerator: numerator, denominator: denominator}) when is_integer(numerator) and is_integer(denominator) do [true, numerator, denominator] end defp format_base(message) do throw {:missing_cents_or_ratio, message} end def flag(_), do: [] end
23.966667
127
0.681502
7982840f4d19c920e7b3660138bbed782054faf1
2,458
exs
Elixir
config/prod.exs
EssenceOfChaos/lil_links
8666d317063b7388296cf11a4dec00a0c339db39
[ "MIT" ]
1
2019-04-24T03:02:27.000Z
2019-04-24T03:02:27.000Z
config/prod.exs
EssenceOfChaos/lil_links
8666d317063b7388296cf11a4dec00a0c339db39
[ "MIT" ]
null
null
null
config/prod.exs
EssenceOfChaos/lil_links
8666d317063b7388296cf11a4dec00a0c339db39
[ "MIT" ]
null
null
null
use Mix.Config # For production, don't forget to configure the url host # to something meaningful, Phoenix uses this information # when generating URLs. # # Note we also include the path to a cache manifest # containing the digested version of static files. This # manifest is generated by the `mix phx.digest` task, # which you should run after static files are built and # before starting your production server. config :lil_links, LilLinksWeb.Endpoint, http: [:inet6, port: System.get_env("PORT") || 4000], url: [host: "example.com", port: 80], cache_static_manifest: "priv/static/cache_manifest.json" # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :lil_links, LilLinksWeb.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [ # :inet6, # port: 443, # cipher_suite: :strong, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH") # ] # # The `cipher_suite` is set to `:strong` to support only the # latest and more secure SSL ciphers. This means old browsers # and clients may not be supported. You can set it to # `:compatible` for wider support. # # `:keyfile` and `:certfile` expect an absolute path to the key # and cert in disk or a relative path inside priv, for example # "priv/ssl/server.key". For all supported SSL configuration # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 # # We also recommend setting `force_ssl` in your endpoint, ensuring # no data is ever sent via http, always redirecting to https: # # config :lil_links, LilLinksWeb.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # ## Using releases (distillery) # # 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 :lil_links, LilLinksWeb.Endpoint, server: true # # Note you can't rely on `System.get_env/1` when using releases. # See the releases documentation accordingly. # Finally import the config/prod.secret.exs which should be versioned # separately. import_config "prod.secret.exs"
34.138889
69
0.714402
7982cf3c4c061dc0a256cf88eae871294fbfcc82
325
ex
Elixir
lib/json/parser.ex
azukiapp/exjson
6021434570092b5e31ff379b17a12abb47e7a45c
[ "Apache-2.0" ]
1
2015-06-13T03:35:41.000Z
2015-06-13T03:35:41.000Z
lib/json/parser.ex
azukiapp/exjson
6021434570092b5e31ff379b17a12abb47e7a45c
[ "Apache-2.0" ]
null
null
null
lib/json/parser.ex
azukiapp/exjson
6021434570092b5e31ff379b17a12abb47e7a45c
[ "Apache-2.0" ]
null
null
null
defmodule JSON.Parser do def parse(thing) when is_binary(thing) do parse(binary_to_list(thing)) end def parse(thing) when is_list(thing) do tokens = JSON.Scanner.scan(thing) parse(tokens) end def parse({:ok, list, _}) do result = :json_parser.parse(list) elem(result, 1) end end
18.055556
43
0.652308
7983059f9c86696caa1813a6e780c05f1c1e4cbf
279
ex
Elixir
lib/phoenix_api_auth_starter.ex
CMcDonald82/phoenix-api-auth-starter
916db91ceba32399b8d30cc6a6e35804bc0d18b1
[ "MIT" ]
null
null
null
lib/phoenix_api_auth_starter.ex
CMcDonald82/phoenix-api-auth-starter
916db91ceba32399b8d30cc6a6e35804bc0d18b1
[ "MIT" ]
null
null
null
lib/phoenix_api_auth_starter.ex
CMcDonald82/phoenix-api-auth-starter
916db91ceba32399b8d30cc6a6e35804bc0d18b1
[ "MIT" ]
null
null
null
defmodule PhoenixApiAuthStarter do @moduledoc """ PhoenixApiAuthStarter keeps the contexts that define your domain and business logic. Contexts are also responsible for managing your data, regardless if it comes from the database, an external API or others. """ end
27.9
66
0.777778
79831ed3d4e700febf4b0ce8aed2e24f20afe54a
2,545
ex
Elixir
test/support/test_adapter.ex
prosapient/spandex_phoenix
487a635f3334e9aa0a4c86c7abc656ac00a6acc8
[ "MIT" ]
69
2018-09-14T18:17:50.000Z
2022-01-11T01:20:55.000Z
test/support/test_adapter.ex
prosapient/spandex_phoenix
487a635f3334e9aa0a4c86c7abc656ac00a6acc8
[ "MIT" ]
49
2018-10-11T02:47:58.000Z
2022-03-17T09:10:07.000Z
test/support/test_adapter.ex
prosapient/spandex_phoenix
487a635f3334e9aa0a4c86c7abc656ac00a6acc8
[ "MIT" ]
27
2018-09-19T14:14:06.000Z
2022-03-07T21:16:33.000Z
defmodule TestAdapter do @moduledoc false @behaviour Spandex.Adapter require Logger alias Spandex.{SpanContext, Tracer} @max_id 9_223_372_036_854_775_807 @impl Spandex.Adapter def trace_id(), do: :rand.uniform(@max_id) @impl Spandex.Adapter def span_id(), do: trace_id() @impl Spandex.Adapter def now(), do: :os.system_time(:nano_seconds) @impl Spandex.Adapter def default_sender() do TestSender end @doc """ Fetches the test trace & parent IDs from the conn request headers if they are present. """ @impl Spandex.Adapter @spec distributed_context(conn :: Plug.Conn.t(), Keyword.t()) :: {:ok, SpanContext.t()} | {:error, :no_distributed_trace} def distributed_context(%Plug.Conn{} = conn, _opts) do trace_id = get_first_header(conn, "x-test-trace-id") parent_id = get_first_header(conn, "x-test-parent-id") # We default the priority to 1 so that we capture all traces by default until we implement trace sampling priority = get_first_header(conn, "x-test-sampling-priority") || 1 if is_nil(trace_id) || is_nil(parent_id) do {:error, :no_distributed_trace} else {:ok, %SpanContext{trace_id: trace_id, parent_id: parent_id, priority: priority}} end end @doc """ Injects test HTTP headers to represent the specified SpanContext """ @impl Spandex.Adapter @spec inject_context(Spandex.headers(), SpanContext.t(), Tracer.opts()) :: Spandex.headers() def inject_context(headers, %SpanContext{} = span_context, _opts) when is_list(headers) do span_context |> tracing_headers() |> Kernel.++(headers) end def inject_context(headers, %SpanContext{} = span_context, _opts) when is_map(headers) do span_context |> tracing_headers() |> Enum.into(%{}) |> Map.merge(headers) end # Private Helpers @spec get_first_header(conn :: Plug.Conn.t(), header_name :: binary) :: binary | nil defp get_first_header(conn, header_name) do conn |> Plug.Conn.get_req_header(header_name) |> List.first() |> parse_header() end defp parse_header(header) when is_bitstring(header) do case Integer.parse(header) do {int, _} -> int _ -> nil end end defp parse_header(_header), do: nil defp tracing_headers(%SpanContext{trace_id: trace_id, parent_id: parent_id, priority: priority}) do [ {"x-test-trace-id", to_string(trace_id)}, {"x-test-parent-id", to_string(parent_id)}, {"x-test-sampling-priority", to_string(priority)} ] end end
28.277778
109
0.682515
7983206913835e89a70523c195ae7854e6d55a96
279
exs
Elixir
priv/repo/migrations/20160702161258_create_user.exs
elixir-carbon/carbon
9537596c9a409e4573cb7cb75cfa0a2e31d9b153
[ "Apache-2.0" ]
13
2016-07-04T00:44:18.000Z
2016-07-11T22:02:11.000Z
priv/repo/migrations/20160702161258_create_user.exs
elixir-carbon/carbon
9537596c9a409e4573cb7cb75cfa0a2e31d9b153
[ "Apache-2.0" ]
1
2016-07-12T23:09:45.000Z
2016-07-13T01:19:11.000Z
priv/repo/migrations/20160702161258_create_user.exs
elixirdrops/carbon
9537596c9a409e4573cb7cb75cfa0a2e31d9b153
[ "Apache-2.0" ]
1
2016-12-10T07:27:04.000Z
2016-12-10T07:27:04.000Z
defmodule Carbon.Repo.Migrations.CreateUser do use Ecto.Migration def change do create table(:users) do add :email, :string add :password_hash, :string add :password_reset_token, :string timestamps end create index(:users, [:email]) end end
18.6
46
0.684588
79832ee0cf6adfd3084ff31278d0d296ede82c73
721
ex
Elixir
nucleotide-count/lib/nucleotide_count.ex
rapidfireworks/exercism.ex
7739c60db0510099fe8d37fd6bd76eee37623d05
[ "MIT" ]
null
null
null
nucleotide-count/lib/nucleotide_count.ex
rapidfireworks/exercism.ex
7739c60db0510099fe8d37fd6bd76eee37623d05
[ "MIT" ]
null
null
null
nucleotide-count/lib/nucleotide_count.ex
rapidfireworks/exercism.ex
7739c60db0510099fe8d37fd6bd76eee37623d05
[ "MIT" ]
null
null
null
defmodule NucleotideCount do @nucleotides [?A, ?C, ?G, ?T] @doc """ Counts individual nucleotides in a DNA strand. ## Examples iex> NucleotideCount.count('AATAA', ?A) 4 iex> NucleotideCount.count('AATAA', ?T) 1 """ @spec count(charlist(), char()) :: non_neg_integer() def count(strand, nucleotide) when nucleotide in @nucleotides do histogram(strand)[nucleotide] end @doc """ Returns a summary of counts by nucleotide. ## Examples iex> NucleotideCount.histogram('AATAA') %{?A => 4, ?T => 1, ?C => 0, ?G => 0} """ @spec histogram(charlist()) :: map() def histogram(strand) do @nucleotides |> Map.new(&{&1, 0}) |> Map.merge(Enum.frequencies(strand)) end end
20.6
66
0.626907
79833c38578c0b1db4e9780a1f239755049e0c99
98
exs
Elixir
robotica_common/config/docker.exs
brianmay/robotica-elixir
8656510e54b7e32a547e3a54bf946f0e327911c9
[ "RSA-MD" ]
1
2019-04-23T09:16:44.000Z
2019-04-23T09:16:44.000Z
robotica_common/config/docker.exs
brianmay/robotica-elixir
8656510e54b7e32a547e3a54bf946f0e327911c9
[ "RSA-MD" ]
107
2019-05-26T08:03:26.000Z
2022-02-03T19:13:56.000Z
robotica_common/config/docker.exs
brianmay/robotica-elixir
8656510e54b7e32a547e3a54bf946f0e327911c9
[ "RSA-MD" ]
1
2019-08-10T20:44:24.000Z
2019-08-10T20:44:24.000Z
use Mix.Config config :robotica_common, compile_config_files: false, config_common_file: nil
16.333333
30
0.806122
79836d05eff038b818d4cec4fb9ff2b2fb7074a5
301
exs
Elixir
priv/repo/migrations/20200120043228_create_links_statuses.exs
chrisbodhi/nuzzelish
4273dc34e5cc2eab11a6c512272b03a60f302e64
[ "MIT" ]
2
2020-09-07T03:42:36.000Z
2021-05-04T23:58:43.000Z
priv/repo/migrations/20200120043228_create_links_statuses.exs
chrisbodhi/nuzzelish
4273dc34e5cc2eab11a6c512272b03a60f302e64
[ "MIT" ]
20
2020-01-15T03:26:48.000Z
2020-02-02T20:53:39.000Z
priv/repo/migrations/20200120043228_create_links_statuses.exs
chrisbodhi/nuzzelish
4273dc34e5cc2eab11a6c512272b03a60f302e64
[ "MIT" ]
null
null
null
defmodule Nuzzelish.Repo.Migrations.CreateLinksStatuses do use Ecto.Migration def change do create table(:links_statuses) do add :link_id, references(:links) add :status_id, references(:statuses) end create unique_index(:links_statuses, [:link_id, :status_id]) end end
23.153846
64
0.727575
79837aadf7158c369ab57a9d103269be4c32bdd7
756
exs
Elixir
elixir/worker.exs
nkokkos/rabbitmq-tutorials
949d94ba475bc98736313632ac954461f2b05e36
[ "Apache-2.0" ]
2
2019-03-27T00:42:58.000Z
2019-03-28T02:32:09.000Z
elixir/worker.exs
nkokkos/rabbitmq-tutorials
949d94ba475bc98736313632ac954461f2b05e36
[ "Apache-2.0" ]
8
2019-11-04T10:50:05.000Z
2022-02-09T01:02:33.000Z
elixir/worker.exs
nkokkos/rabbitmq-tutorials
949d94ba475bc98736313632ac954461f2b05e36
[ "Apache-2.0" ]
1
2019-04-17T10:10:02.000Z
2019-04-17T10:10:02.000Z
defmodule Worker do def wait_for_messages(channel) do receive do {:basic_deliver, payload, meta} -> IO.puts " [x] Received #{payload}" payload |> to_char_list |> Enum.count(fn x -> x == ?. end) |> Kernel.*(1000) |> :timer.sleep IO.puts " [x] Done." AMQP.Basic.ack(channel, meta.delivery_tag) wait_for_messages(channel) end end end {:ok, connection} = AMQP.Connection.open {:ok, channel} = AMQP.Channel.open(connection) AMQP.Queue.declare(channel, "task_queue", durable: true) AMQP.Basic.qos(channel, prefetch_count: 1) AMQP.Basic.consume(channel, "task_queue") IO.puts " [*] Waiting for messages. To exit press CTRL+C, CTRL+C" Worker.wait_for_messages(channel)
26.068966
65
0.641534
798392d7819d2d4e3b465122b916b0622c8a683f
2,469
exs
Elixir
test/mix/tasks/ecto.rollback_test.exs
hauleth/ecto_sql
1d7f4b73bfa04e02a26bba8b3ea79a457850af0f
[ "Apache-2.0" ]
384
2018-10-03T17:52:39.000Z
2022-03-24T17:54:21.000Z
test/mix/tasks/ecto.rollback_test.exs
hauleth/ecto_sql
1d7f4b73bfa04e02a26bba8b3ea79a457850af0f
[ "Apache-2.0" ]
357
2018-10-06T13:47:33.000Z
2022-03-29T08:18:02.000Z
test/mix/tasks/ecto.rollback_test.exs
hauleth/ecto_sql
1d7f4b73bfa04e02a26bba8b3ea79a457850af0f
[ "Apache-2.0" ]
251
2018-10-04T11:06:41.000Z
2022-03-29T07:22:53.000Z
defmodule Mix.Tasks.Ecto.RollbackTest do use ExUnit.Case import Mix.Tasks.Ecto.Rollback, only: [run: 2] import Support.FileHelpers @migrations_path Path.join([tmp_path(), inspect(Ecto.Migrate), "migrations"]) setup do File.mkdir_p!(@migrations_path) :ok end defmodule Repo do def start_link(_) do Process.put(:started, true) Task.start_link fn -> Process.flag(:trap_exit, true) receive do {:EXIT, _, :normal} -> :ok end end end def stop() do :ok end def __adapter__ do EctoSQL.TestAdapter end def config do [priv: "tmp/#{inspect(Ecto.Migrate)}", otp_app: :ecto_sql] end end defmodule StartedRepo do def start_link(_) do {:error, {:already_started, :whatever}} end def stop() do raise "should not be called" end def __adapter__ do EctoSQL.TestAdapter end def config do [priv: "tmp/#{inspect(Ecto.Migrate)}", otp_app: :ecto_sql] end end test "runs the migrator after starting repo" do run ["-r", to_string(Repo)], fn _, _, _, _ -> Process.put(:migrated, true) [] end assert Process.get(:migrated) assert Process.get(:started) end test "runs the migrator with already started repo" do run ["-r", to_string(StartedRepo)], fn _, _, _, _ -> Process.put(:migrated, true) [] end assert Process.get(:migrated) end test "runs the migrator yielding the repository and migrations path" do run ["-r", to_string(Repo), "--prefix", "foo"], fn repo, [path], direction, opts -> assert repo == Repo refute path =~ ~r/_build/ assert direction == :down assert opts[:step] == 1 assert opts[:prefix] == "foo" [] end assert Process.get(:started) end test "raises when migrations path does not exist" do File.rm_rf!(@migrations_path) assert_raise Mix.Error, fn -> run ["-r", to_string(Repo)], fn _, _, _, _ -> [] end end assert !Process.get(:started) end test "uses custom paths" do path1 = Path.join([unquote(tmp_path()), inspect(Ecto.Migrate), "migrations_1"]) path2 = Path.join([unquote(tmp_path()), inspect(Ecto.Migrate), "migrations_2"]) File.mkdir_p!(path1) File.mkdir_p!(path2) run ["-r", to_string(Repo), "--migrations-path", path1, "--migrations-path", path2], fn Repo, [^path1, ^path2], _, _ -> [] end end end
23.970874
88
0.610369
79839dad3057eb598f21b8f1d112f045559a1a05
74
ex
Elixir
web/views/coherence/session_view.ex
bagilevi/uptom
50894abb8f7bd052e12c37155b5c33450abcc9bd
[ "MIT" ]
6
2017-05-12T04:20:09.000Z
2020-11-07T02:00:56.000Z
web/views/coherence/session_view.ex
bagilevi/uptom
50894abb8f7bd052e12c37155b5c33450abcc9bd
[ "MIT" ]
null
null
null
web/views/coherence/session_view.ex
bagilevi/uptom
50894abb8f7bd052e12c37155b5c33450abcc9bd
[ "MIT" ]
2
2020-05-18T08:06:22.000Z
2020-12-19T14:24:40.000Z
defmodule Coherence.SessionView do use Uptom.Coherence.Web, :view end
12.333333
34
0.783784
7983a6aee7607fa4b9c7048ae7cbcdee97069ba9
44,571
ex
Elixir
deps/ecto/lib/ecto/query.ex
JoakimEskils/elixir-absinthe
d81e24ec7c7b1164e6d152101dd50422f192d7e9
[ "MIT" ]
1
2017-11-27T06:00:32.000Z
2017-11-27T06:00:32.000Z
deps/ecto/lib/ecto/query.ex
JoakimEskils/elixir-absinthe
d81e24ec7c7b1164e6d152101dd50422f192d7e9
[ "MIT" ]
null
null
null
deps/ecto/lib/ecto/query.ex
JoakimEskils/elixir-absinthe
d81e24ec7c7b1164e6d152101dd50422f192d7e9
[ "MIT" ]
null
null
null
defmodule Ecto.SubQuery do @moduledoc """ Stores subquery information. """ defstruct [:query, :params, :select, :cache] end defmodule Ecto.Query do @moduledoc ~S""" Provides the Query DSL. Queries are used to retrieve and manipulate data from a repository (see `Ecto.Repo`). Ecto queries come in two flavors: keyword-based and macro-based. Most examples will use the keyword-based syntax, the macro one will be explored in later sections. Let's see a sample query: # Imports only from/2 of Ecto.Query import Ecto.Query, only: [from: 2] # Create a query query = from u in "users", where: u.age > 18, select: u.name # Send the query to the repository Repo.all(query) In the example above, we are directly querying the "users" table from the database. ## Query expressions Ecto allows a limited set of expressions inside queries. In the query below, for example, we use `u.age` to access a field, the `>` comparison operator and the literal `0`: query = from u in "users", where: u.age > 0, select: u.name You can find the full list of operations in `Ecto.Query.API`. Besides the operations listed there, the following literals are supported in queries: * Integers: `1`, `2`, `3` * Floats: `1.0`, `2.0`, `3.0` * Booleans: `true`, `false` * Binaries: `<<1, 2, 3>>` * Strings: `"foo bar"`, `~s(this is a string)` * Arrays: `[1, 2, 3]`, `~w(interpolate words)` All other types and dynamic values must be passed as a parameter using interpolation as explained below. ## Interpolation and casting External values and Elixir expressions can be injected into a query expression with `^`: def with_minimum(age, height_ft) do from u in "users", where: u.age > ^age and u.height > ^(height_ft * 3.28), select: u.name end with_minimum(18, 5.0) When interpolating values, you may want to explicitly tell Ecto what is the expected type of the value being interpolated: age = "18" Repo.all(from u in "users", where: u.age > type(^age, :integer), select: u.name) In the example above, Ecto will cast the age to type integer. When a value cannot be cast, `Ecto.Query.CastError` is raised. To avoid the repetition of always specifying the types, you may define an `Ecto.Schema`. In such cases, Ecto will analyze your queries and automatically cast the interpolated "age" when compared to the `u.age` field, as long as the age field is defined with type `:integer` in your schema: age = "18" Repo.all(from u in User, where: u.age > ^age, select: u.name) Another advantage of using schemas is that we no longer need to specify the select option in queries, as by default Ecto will retrieve all fields specified in the schema: age = "18" Repo.all(from u in User, where: u.age > ^age) For this reason, we will use schemas on the remaining examples but remember Ecto does not require them in order to write queries. ## Composition Ecto queries are composable. For example, the query above can actually be defined in two parts: # Create a query query = from u in User, where: u.age > 18 # Extend the query query = from u in query, select: u.name Composing queries uses the same syntax as creating a query. The difference is that, instead of passing a schema like `User` on the right side of `in`, we passed the query itself. Any value can be used on the right-side of `in` as long as it implements the `Ecto.Queryable` protocol. For now, we know the protocol is implemented for both atoms (like `User`) and strings (like "users"). In any case, regardless if a schema has been given or not, Ecto queries are always composable thanks to its binding system. ### Query bindings On the left side of `in` we specify the query bindings. This is done inside from and join clauses. In the query below `u` is a binding and `u.age` is a field access using this binding. query = from u in User, where: u.age > 18 Bindings are not exposed from the query. When composing queries you must specify bindings again for each refinement query. For example to further narrow-down above query we again need to tell Ecto what bindings to expect: query = from u in query, select: u.city Bindings in Ecto are positional, and the names do not have to be consistent between input and refinement queries. For example, the query above could also be written as: query = from q in query, select: q.city It would make no difference to Ecto. This is important because it allows developers to compose queries without caring about the bindings used in the initial query. When using joins, the bindings should be matched in the order they are specified: # Create a query query = from p in Post, join: c in Comment, where: c.post_id == p.id # Extend the query query = from [p, c] in query, select: {p.title, c.body} You are not required to specify all bindings when composing. For example, if we would like to order the results above by post insertion date, we could further extend it as: query = from q in query, order_by: q.inserted_at The example above will work if the input query has 1 or 10 bindings. In the example above, we will always sort by the `inserted_at` column from the `from` source. Similarly, if you are interested only on the last binding (or the last bindings) in a query, you can use ... to specify "all bindings before" and match on the last one. For instance, imagine you wrote: posts_with_comments = from p in query, join: c in Comment, where: c.post_id == p.id And now we want to make sure to return both the post title and the comment body. Although we may not know how many bindings there are in the query, we are sure posts is the first binding and comments are the last one, so we can write: from [p, ..., c] in posts_with_comments, select: {p.title, c.body} In other words, `...` will include all the binding between the first and the last, which may be no binding at all, one or many. Using `...` can be handy from time to time but most of its uses can be avoided by relying on the keyword query syntax when writing queries. ### Bindingless operations Although bindings are extremely useful when working with joins, they are not necessary when the query has only the `from` clause. For such cases, Ecto supports a way for building queries without specifying the binding: from Post, where: [category: "fresh and new"], order_by: [desc: :published_at], select: [:id, :title, :body] The query above will select all posts with category "fresh and new", order by the most recently published, and return Post structs with only the id, title and body fields set. It is equivalent to: from p in Post, where: p.category == "fresh and new", order_by: [desc: p.published_at], select: struct(p, [:id, :title, :body]) One advantage of bindingless queries is that they are data-driven and therefore useful for dynamically building queries. For example, the query above could also be written as: where = [category: "fresh and new"] order_by = [desc: :published_at] select = [:id, :title, :body] from Post, where: ^where, order_by: ^order_by, select: ^select This feature is very useful when queries need to be built based on some user input, like web search forms, CLIs and so on. ## Fragments If you need an escape hatch, Ecto provides fragments (see `Ecto.Query.API.fragment/1`) to inject SQL (and non-SQL) fragments into queries. For example, to get all posts while running the "lower(?)" function in the database where `p.title` is interpolated in place of `?`, one can write: from p in Post, where: is_nil(p.published_at) and fragment("lower(?)", p.title) == ^title Also, most adapters provide direct APIs for queries, like `Ecto.Adapters.SQL.query/4`, allowing developers to completely bypass Ecto queries. ## Macro API In all examples so far we have used the **keywords query syntax** to create a query: import Ecto.Query from u in "users", where: u.age > 18, select: u.name Due to the prevalence of the pipe operator in Elixir, Ecto also supports a pipe-based syntax: "users" |> where([u], u.age > 18) |> select([u], u.name) The keyword-based and pipe-based examples are equivalent. The downside of using macros is that the binding must be specified for every operation. However, since keyword-based and pipe-based examples are equivalent, the bindingless syntax also works for macros: "users" |> where([u], u.age > 18) |> select([:name]) Such allows developers to write queries using bindings only in more complex query expressions. This module documents each of those macros, providing examples in both the keywords query and pipe expression formats. ## Query Prefix It is possible to set a prefix for the queries. For Postgres users, this will specify the schema where the table is located, while for MySQL users this will specify the database where the table is located. When no prefix is set, Postgres queries are assumed to be in the public schema, while MySQL queries are assumed to be in the database set in the config for the repo. To set the prefix on a query: results = query # May be User or an Ecto.Query itself |> Ecto.Queryable.to_query |> Map.put(:prefix, "foo") |> Repo.all When a prefix is set in a query, all loaded structs will belong to that prefix, so operations like update and delete will be applied to the proper prefix. In case you want to manually set the prefix for new data, specially on insert, use `Ecto.put_meta/2`. """ defstruct [prefix: nil, sources: nil, from: nil, joins: [], wheres: [], select: nil, order_bys: [], limit: nil, offset: nil, group_bys: [], updates: [], havings: [], preloads: [], assocs: [], distinct: nil, lock: nil] @type t :: %__MODULE__{} defmodule DynamicExpr do @moduledoc false defstruct [:fun, :binding, :file, :line] end defmodule QueryExpr do @moduledoc false defstruct [:expr, :file, :line, params: []] end defmodule BooleanExpr do @moduledoc false defstruct [:op, :expr, :file, :line, params: []] end defmodule SelectExpr do @moduledoc false defstruct [:expr, :file, :line, :fields, params: [], take: %{}] end defmodule JoinExpr do @moduledoc false defstruct [:qual, :source, :on, :file, :line, :assoc, :ix, params: []] end defmodule Tagged do @moduledoc false # * value is the tagged value # * tag is the directly tagged value, like Ecto.DateTime # * type is the underlying tag type, like :datetime defstruct [:value, :tag, :type] end alias Ecto.Query.Builder alias Ecto.Query.Builder.{Distinct, Dynamic, Filter, From, GroupBy, Join, LimitOffset, Lock, OrderBy, Preload, Select, Update} @doc """ Builds a dynamic query expression. Dynamic query expressions allows developers to build queries expression bit by bit so they are later interpolated in a query. ## Examples For example, imagine you have a set of conditions you want to build your query on: dynamic = false dynamic = if params["is_public"] do dynamic([p], p.is_public or ^dynamic) else dynamic end dynamic = if params["allow_reviewers"] do dynamic([p, a], a.reviewer == true or ^dynamic) else dynamic end from query, where: ^dynamic In the example above, we were able to build the query expressions bit by bit, using different bindings, and later interpolate it all at once inside the query. A dynamic expression can always be interpolated inside another dynamic expression and into the constructs described below. ## `where`, `having` and a `join`'s `on' `dynamic` can be interpolated at the root of a `where`, `having` or a `join`'s `on`. For example, the following is forbidden because it is not at the root of a `where`: from q in query, where: q.some_condition and ^dynamic Fortunately that's easily solvable by simply rewriting it to: dynamic = dynamic([q], q.some_condition and ^dynamic) from query, where: ^dynamic ## Updates Dynamic is also supported as each field in an update, for example: update_to = dynamic([p], p.sum / p.count) from query, update: [set: [average: ^update_to]] """ defmacro dynamic(binding \\ [], expr) do Dynamic.build(binding, expr, __CALLER__) end @doc """ Converts a query into a subquery. If a subquery is given, returns the subquery itself. If any other value is given, it is converted to a query via `Ecto.Queryable` and wrapped in the `Ecto.SubQuery` struct. Subqueries are currently only supported in the `from` and `join` fields. ## Examples # Get the average salary of the top 10 highest salaries query = from Employee, order_by: [desc: :salary], limit: 10 from e in subquery(query), select: avg(e.salary) A prefix can be specified for a subquery, similar to standard repo operations: query = from Employee, order_by: [desc: :salary], limit: 10 from e in subquery(query, prefix: "my_prefix"), select: avg(e.salary) Although subqueries are not allowed in WHERE expressions, most subqueries in WHERE expression can be rewritten as JOINs. Imagine you want to write this query: UPDATE posts SET sync_started_at = $1 WHERE id IN ( SELECT id FROM posts WHERE synced = false AND (sync_started_at IS NULL OR sync_started_at < $1) LIMIT $2 ) If you attempt to write it as `where: p.id in ^subquery(foo)`, Ecto won't accept such query. However, the subquery above can be written as a JOIN, which is supported by Ecto. The final Ecto query will look like this: subset_query = from(p in Post, where: p.synced == false and (is_nil(p.sync_started_at) or p.sync_started_at < ^min_sync_started_at), limit: ^batch_size ) Repo.update_all( from(p in Post, join: s in subquery(subset_query), on: s.id == p.id), set: [sync_started_at: NaiveDateTime.utc_now()] end) """ def subquery(query, opts \\ []) do subquery = wrap_in_subquery(query) case Keyword.fetch(opts, :prefix) do {:ok, prefix} when is_binary(prefix) -> put_in(subquery.query.prefix, prefix) :error -> subquery end end defp wrap_in_subquery(%Ecto.SubQuery{} = subquery), do: subquery defp wrap_in_subquery(%Ecto.Query{} = query), do: %Ecto.SubQuery{query: query} defp wrap_in_subquery(queryable), do: %Ecto.SubQuery{query: Ecto.Queryable.to_query(queryable)} @doc """ Resets a previously set field on a query. It can reset any query field except the query source (`from`). ## Example query |> Ecto.Query.exclude(:select) """ def exclude(%Ecto.Query{} = query, field), do: do_exclude(query, field) def exclude(query, field), do: do_exclude(Ecto.Queryable.to_query(query), field) defp do_exclude(%Ecto.Query{} = query, :join), do: %{query | joins: []} defp do_exclude(%Ecto.Query{} = query, :where), do: %{query | wheres: []} defp do_exclude(%Ecto.Query{} = query, :order_by), do: %{query | order_bys: []} defp do_exclude(%Ecto.Query{} = query, :group_by), do: %{query | group_bys: []} defp do_exclude(%Ecto.Query{} = query, :having), do: %{query | havings: []} defp do_exclude(%Ecto.Query{} = query, :distinct), do: %{query | distinct: nil} defp do_exclude(%Ecto.Query{} = query, :select), do: %{query | select: nil} defp do_exclude(%Ecto.Query{} = query, :limit), do: %{query | limit: nil} defp do_exclude(%Ecto.Query{} = query, :offset), do: %{query | offset: nil} defp do_exclude(%Ecto.Query{} = query, :lock), do: %{query | lock: nil} defp do_exclude(%Ecto.Query{} = query, :preload), do: %{query | preloads: [], assocs: []} @doc """ Creates a query. It can either be a keyword query or a query expression. If it is a keyword query the first argument must be either an `in` expression, or a value that implements the `Ecto.Queryable` protocol. If the query needs a reference to the data source in any other part of the expression, then an `in` must be used to create a reference variable. The second argument should be a keyword query where the keys are expression types and the values are expressions. If it is a query expression the first argument must be a value that implements the `Ecto.Queryable` protocol and the second argument the expression. ## Keywords example from(c in City, select: c) ## Expressions example City |> select([c], c) ## Examples def paginate(query, page, size) do from query, limit: ^size, offset: ^((page-1) * size) end The example above does not use `in` because `limit` and `offset` do not require a reference to the data source. However, extending the query with a where expression would require the use of `in`: def published(query) do from p in query, where: not(is_nil(p.published_at)) end Notice we have created a `p` variable to reference the query's original data source. This assumes that the original query only had one source. When the given query has more than one source, a variable must be given for each in the order they were bound: def published_multi(query) do from [p,o] in query, where: not(is_nil(p.published_at)) and not(is_nil(o.published_at)) end Note the variables `p` and `o` can be named whatever you like as they have no importance in the query sent to the database. """ defmacro from(expr, kw \\ []) do unless Keyword.keyword?(kw) do raise ArgumentError, "second argument to `from` must be a compile time keyword list" end {quoted, binds, count_bind} = From.build(expr, __CALLER__) from(kw, __CALLER__, count_bind, quoted, binds) end @binds [:where, :or_where, :select, :distinct, :order_by, :group_by, :having, :or_having, :limit, :offset, :preload, :update, :select_merge] @no_binds [:lock] @joins [:join, :inner_join, :cross_join, :left_join, :right_join, :full_join, :inner_lateral_join, :left_lateral_join] defp from([{type, expr}|t], env, count_bind, quoted, binds) when type in @binds do # If all bindings are integer indexes keep AST Macro expandable to %Query{}, # otherwise ensure that quoted code is evaluated before macro call quoted = if Enum.all?(binds, fn {_, value} -> is_integer(value) end) do quote do Ecto.Query.unquote(type)(unquote(quoted), unquote(binds), unquote(expr)) end else quote do query = unquote(quoted) Ecto.Query.unquote(type)(query, unquote(binds), unquote(expr)) end end from(t, env, count_bind, quoted, binds) end defp from([{type, expr}|t], env, count_bind, quoted, binds) when type in @no_binds do quoted = quote do Ecto.Query.unquote(type)(unquote(quoted), unquote(expr)) end from(t, env, count_bind, quoted, binds) end defp from([{join, expr}|t], env, count_bind, quoted, binds) when join in @joins do qual = case join do :join -> :inner :full_join -> :full :left_join -> :left :right_join -> :right :inner_join -> :inner :cross_join -> :cross :left_lateral_join -> :left_lateral :inner_lateral_join -> :inner_lateral end {t, on} = collect_on(t, nil) {quoted, binds, count_bind} = Join.build(quoted, qual, binds, expr, on, count_bind, env) from(t, env, count_bind, quoted, binds) end defp from([{:on, _value}|_], _env, _count_bind, _quoted, _binds) do Builder.error! "`on` keyword must immediately follow a join" end defp from([{key, _value}|_], _env, _count_bind, _quoted, _binds) do Builder.error! "unsupported #{inspect key} in keyword query expression" end defp from([], _env, _count_bind, quoted, _binds) do quoted end defp collect_on([{:on, expr}|t], nil), do: collect_on(t, expr) defp collect_on([{:on, expr}|t], acc), do: collect_on(t, {:and, [], [acc, expr]}) defp collect_on(other, acc), do: {other, acc} @doc """ A join query expression. Receives a source that is to be joined to the query and a condition for the join. The join condition can be any expression that evaluates to a boolean value. The join is by default an inner join, the qualifier can be changed by giving the atoms: `:inner`, `:left`, `:right`, `:cross`, `:full`, `:inner_lateral` or `:left_lateral`. For a keyword query the `:join` keyword can be changed to: `:inner_join`, `:left_join`, `:right_join`, `:cross_join`, `:full_join`, `:inner_lateral_join` or `:left_lateral_join`. Currently it is possible to join on: * an `Ecto.Schema`, such as `p in Post` * an Ecto query with zero or more where clauses, such as `from "posts", where: [public: true]` * an association, such as `c in assoc(post, :comments)` * a query fragment, such as `c in fragment("SOME COMPLEX QUERY")` * a subquery, such as `c in subquery(another_query)` The fragment support exists mostly for handling lateral joins. See "Joining with fragments" below. ## Keywords examples from c in Comment, join: p in Post, on: p.id == c.post_id, select: {p.title, c.text} from p in Post, left_join: c in assoc(p, :comments), select: {p, c} Keywords can also be given or interpolated as part of `on`: from c in Comment, join: p in Post, on: [id: c.post_id], select: {p.title, c.text} Any key in `on` will apply to the currently joined expression. It is also possible to interpolate an Ecto query on the right side of `in`. For example, the query above can also be written as: posts = Post from c in Comment, join: p in ^posts, on: [id: c.post_id], select: {p.title, c.text} The above is specially useful to dynamically join on existing queries, for example, choosing between public posts or posts that have been recently published: posts = if params["drafts"] do from p in Post, where: [drafts: true] else from p in Post, where: [public: true] end from c in Comment, join: p in ^posts, on: [id: c.post_id], select: {p.title, c.text} Only simple queries with `where` expressions can be interpolated in join. ## Expressions examples Comment |> join(:inner, [c], p in Post, c.post_id == p.id) |> select([c, p], {p.title, c.text}) Post |> join(:left, [p], c in assoc(p, :comments)) |> select([p, c], {p, c}) Post |> join(:left, [p], c in Comment, c.post_id == p.id and c.is_visible == true) |> select([p, c], {p, c}) ## Joining with fragments When you need to join on a complex query, Ecto supports fragments in joins: Comment |> join(:inner, [c], p in fragment("SOME COMPLEX QUERY", c.id, ^some_param)) Although using fragments in joins is discouraged in favor of Ecto Query syntax, they are necessary when writing lateral joins as lateral joins require a subquery that refer to previous bindings: Game |> join(:inner_lateral, [g], gs in fragment("SELECT * FROM games_sold AS gs WHERE gs.game_id = ? ORDER BY gs.sold_on LIMIT 2", g.id)) |> select([g, gs], {g.name, gs.sold_on}) """ defmacro join(query, qual, binding \\ [], expr, on \\ nil) do Join.build(query, qual, binding, expr, on, nil, __CALLER__) |> elem(0) end @doc """ A select query expression. Selects which fields will be selected from the schema and any transformations that should be performed on the fields. Any expression that is accepted in a query can be a select field. Select also allows each expression to be wrapped in lists, tuples or maps as shown in the examples below. A full schema can also be selected. There can only be one select expression in a query, if the select expression is omitted, the query will by default select the full schema. If select is given more than once, an error is raised. Use `exclude/2` if you would like to remove a previous select for overriding or see `select_merge/3` for a limited version of `select` that is composable and can be called multiple times. `select` also accepts a list of atoms where each atom refers to a field in the source to be selected. ## Keywords examples from(c in City, select: c) # returns the schema as a struct from(c in City, select: {c.name, c.population}) from(c in City, select: [c.name, c.county]) from(c in City, select: %{n: c.name, answer: 42}) from(c in City, select: %{c | alternative_name: c.name}) from(c in City, select: %Data{name: c.name}) It is also possible to select a struct and limit the returned fields at the same time: from(City, select: [:name]) The syntax above is equivalent to: from(city in City, select: struct(city, [:name])) You can also write: from(city in City, select: map(city, [:name])) If you want a map with only the selected fields to be returned. For more information, read the docs for `Ecto.Query.API.struct/2` and `Ecto.Query.API.map/2`. ## Expressions examples City |> select([c], c) City |> select([c], {c.name, c.country}) City |> select([c], %{"name" => c.name}) City |> select([:name]) City |> select([c], struct(c, [:name])) City |> select([c], map(c, [:name])) """ defmacro select(query, binding \\ [], expr) do Select.build(:select, query, binding, expr, __CALLER__) end @doc """ Mergeable select query expression. This macro is similar to `select/3` except it may be specified multiple times as long as every entry is a map. This is useful for merging and composing selects. For example: query = from p in Post, select: %{} query = if include_title? do from p in query, select_merge: %{title: p.title} else query end query = if include_visits? do from p in query, select_merge: %{visits: p.visits} else query end In the example above, the query is built little by little by merging into a final map. If both conditions above are true, the final query would be equivalent to: from p in Post, select: %{title: p.title, visits: p.visits} If `:select_merge` is called and there is no value selected previously, it will default to the source, `p` in the example above. The left-side of a merge can be a struct or a map. The right side must always be a map. If the left-side is a struct, the fields on the right side must be part of the struct, otherwise an error is raised. """ defmacro select_merge(query, binding \\ [], expr) do Select.build(:merge, query, binding, expr, __CALLER__) end @doc """ A distinct query expression. When true, only keeps distinct values from the resulting select expression. If supported by your database, you can also pass query expressions to distinct and it will generate a query with DISTINCT ON. In such cases, `distinct` accepts exactly the same expressions as `order_by` and any `distinct` expression will be automatically prepended to the `order_by` expressions in case there is any `order_by` expression. ## Keywords examples # Returns the list of different categories in the Post schema from(p in Post, distinct: true, select: p.category) # If your database supports DISTINCT ON(), # you can pass expressions to distinct too from(p in Post, distinct: p.category, order_by: [p.date]) # The DISTINCT ON() also supports ordering similar to ORDER BY. from(p in Post, distinct: [desc: p.category], order_by: [p.date]) # Using atoms from(p in Post, distinct: :category, order_by: :date) ## Expressions example Post |> distinct(true) |> order_by([p], [p.category, p.author]) """ defmacro distinct(query, binding \\ [], expr) do Distinct.build(query, binding, expr, __CALLER__) end @doc """ An AND where query expression. `where` expressions are used to filter the result set. If there is more than one where expression, they are combined with an `and` operator. All where expressions have to evaluate to a boolean value. `where` also accepts a keyword list where the field given as key is going to be compared with the given value. The fields will always refer to the source given in `from`. ## Keywords example from(c in City, where: c.country == "Sweden") from(c in City, where: [country: "Sweden"]) It is also possible to interpolate the whole keyword list, allowing you to dynamically filter the source: filters = [country: "Sweden"] from(c in City, where: ^filters) ## Expressions example City |> where([c], c.country == "Sweden") City |> where(country: "Sweden") """ defmacro where(query, binding \\ [], expr) do Filter.build(:where, :and, query, binding, expr, __CALLER__) end @doc """ An OR where query expression. Behaves exactly the same as `where` except it combines with any previous expression by using an `OR`. All expressions have to evaluate to a boolean value. `or_where` also accepts a keyword list where each key is a field to be compared with the given value. Each key-value pair will be combined using `AND`, exactly as in `where`. ## Keywords example from(c in City, where: [country: "Sweden"], or_where: [country: "Brazil"]) If interpolating keyword lists, the keyword list entries are combined using ANDs and joined to any existing expression with an OR: filters = [country: "USA", name: "New York"] from(c in City, where: [country: "Sweden"], or_where: ^filters) is equivalent to: from c in City, where: (c.country == "Sweden") or (c.country == "USA" and c.name == "New York") The behaviour above is by design to keep the changes between `where` and `or_where` minimal. Plus, if you have a keyword list and you would like each pair to be combined using `or`, it can be easily done with `Enum.reduce/3`: filters = [country: "USA", is_tax_exempt: true] Enum.reduce(filters, City, fn {key, value}, query -> from q in query, or_where: field(q, ^key) == ^value end) which will be equivalent to: from c in City, or_where: (c.country == "USA"), or_where: c.is_tax_exempt == true ## Expressions example City |> where([c], c.country == "Sweden") |> or_where([c], c.country == "Brazil") """ defmacro or_where(query, binding \\ [], expr) do Filter.build(:where, :or, query, binding, expr, __CALLER__) end @doc """ An order by query expression. Orders the fields based on one or more fields. It accepts a single field or a list of fields. The default direction is ascending (`:asc`) and can be customized in a keyword list as shown in the examples. There can be several order by expressions in a query and new expressions are always appended to the previous ones. `order_by` also accepts a list of atoms where each atom refers to a field in source or a keyword list where the direction is given as key and the field to order as value. ## Keywords examples from(c in City, order_by: c.name, order_by: c.population) from(c in City, order_by: [c.name, c.population]) from(c in City, order_by: [asc: c.name, desc: c.population]) from(c in City, order_by: [:name, :population]) from(c in City, order_by: [asc: :name, desc: :population]) A keyword list can also be interpolated: values = [asc: :name, desc: :population] from(c in City, order_by: ^values) ## Expressions example City |> order_by([c], asc: c.name, desc: c.population) City |> order_by(asc: :name) # Sorts by the cities name """ defmacro order_by(query, binding \\ [], expr) do OrderBy.build(query, binding, expr, __CALLER__) end @doc """ A limit query expression. Limits the number of rows returned from the result. Can be any expression but has to evaluate to an integer value and it can't include any field. If `limit` is given twice, it overrides the previous value. ## Keywords example from(u in User, where: u.id == ^current_user, limit: 1) ## Expressions example User |> where([u], u.id == ^current_user) |> limit(1) """ defmacro limit(query, binding \\ [], expr) do LimitOffset.build(:limit, query, binding, expr, __CALLER__) end @doc """ An offset query expression. Offsets the number of rows selected from the result. Can be any expression but it must evaluate to an integer value and it can't include any field. If `offset` is given twice, it overrides the previous value. ## Keywords example # Get all posts on page 4 from(p in Post, limit: 10, offset: 30) ## Expressions example Post |> limit(10) |> offset(30) """ defmacro offset(query, binding \\ [], expr) do LimitOffset.build(:offset, query, binding, expr, __CALLER__) end @doc ~S""" A lock query expression. Provides support for row-level pessimistic locking using `SELECT ... FOR UPDATE` or other, database-specific, locking clauses. `expr` can be any expression but has to evaluate to a boolean value or to a string and it can't include any fields. If `lock` is used more than once, the last one used takes precedence. Ecto also supports [optimistic locking](http://en.wikipedia.org/wiki/Optimistic_concurrency_control) but not through queries. For more information on optimistic locking, have a look at the `Ecto.Changeset.optimistic_lock/3` function ## Keywords example from(u in User, where: u.id == ^current_user, lock: "FOR SHARE NOWAIT") ## Expressions example User |> where(u.id == ^current_user) |> lock("FOR SHARE NOWAIT") """ defmacro lock(query, expr) do Lock.build(query, expr, __CALLER__) end @doc ~S""" An update query expression. Updates are used to update the filtered entries. In order for updates to be applied, `c:Ecto.Repo.update_all/3` must be invoked. ## Keywords example from(u in User, update: [set: [name: "new name"]]) ## Expressions example User |> update([u], set: [name: "new name"]) User |> update(set: [name: "new name"]) ## Interpolation new_name = "new name" from(u in User, update: [set: [name: ^new_name]]) new_name = "new name" from(u in User, update: [set: [name: fragment("upper(?)", ^new_name)]]) ## Operators The update expression in Ecto supports the following operators: * `set` - sets the given field in the table to the given value from(u in User, update: [set: [name: "new name"]]) * `inc` - increments (or decrements if the value is negative) the given field in the table by the given value from(u in User, update: [inc: [accesses: 1]]) * `push` - pushes (appends) the given value to the end of the array field from(u in User, update: [push: [tags: "cool"]]) * `pull` - pulls (removes) the given value from the array field from(u in User, update: [pull: [tags: "not cool"]]) """ defmacro update(query, binding \\ [], expr) do Update.build(query, binding, expr, __CALLER__) end @doc """ A group by query expression. Groups together rows from the schema that have the same values in the given fields. Using `group_by` "groups" the query giving it different semantics in the `select` expression. If a query is grouped, only fields that were referenced in the `group_by` can be used in the `select` or if the field is given as an argument to an aggregate function. `group_by` also accepts a list of atoms where each atom refers to a field in source. ## Keywords examples # Returns the number of posts in each category from(p in Post, group_by: p.category, select: {p.category, count(p.id)}) # Using atoms from(p in Post, group_by: :category, select: {p.category, count(p.id)}) ## Expressions example Post |> group_by([p], p.category) |> select([p], count(p.id)) """ defmacro group_by(query, binding \\ [], expr) do GroupBy.build(query, binding, expr, __CALLER__) end @doc """ An AND having query expression. Like `where`, `having` filters rows from the schema, but after the grouping is performed giving it the same semantics as `select` for a grouped query (see `group_by/3`). `having` groups the query even if the query has no `group_by` expression. ## Keywords example # Returns the number of posts in each category where the # average number of comments is above ten from(p in Post, group_by: p.category, having: avg(p.num_comments) > 10, select: {p.category, count(p.id)}) ## Expressions example Post |> group_by([p], p.category) |> having([p], avg(p.num_comments) > 10) |> select([p], count(p.id)) """ defmacro having(query, binding \\ [], expr) do Filter.build(:having, :and, query, binding, expr, __CALLER__) end @doc """ An OR having query expression. Like `having` but combines with the previous expression by using `OR`. `or_having` behaves for `having` the same way `or_where` behaves for `where`. ## Keywords example # Augment a previous group_by with a having condition. from(p in query, or_having: avg(p.num_comments) > 10) ## Expressions example # Augment a previous group_by with a having condition. Post |> or_having([p], avg(p.num_comments) > 10) """ defmacro or_having(query, binding \\ [], expr) do Filter.build(:having, :or, query, binding, expr, __CALLER__) end @doc """ Preloads the associations into the given struct. Preloading allows developers to specify associations that are preloaded into the struct. Consider this example: Repo.all from p in Post, preload: [:comments] The example above will fetch all posts from the database and then do a separate query returning all comments associated with the given posts. However, often times, you want posts and comments to be selected and filtered in the same query. For such cases, you can explicitly tell the association to be preloaded into the struct: Repo.all from p in Post, join: c in assoc(p, :comments), where: c.published_at > p.updated_at, preload: [comments: c] In the example above, instead of issuing a separate query to fetch comments, Ecto will fetch posts and comments in a single query. Nested associations can also be preloaded in both formats: Repo.all from p in Post, preload: [comments: :likes] Repo.all from p in Post, join: c in assoc(p, :comments), join: l in assoc(c, :likes), where: l.inserted_at > c.updated_at, preload: [comments: {c, likes: l}] Keep in mind neither format can be nested arbitrarily. For example, the query below is invalid because we cannot preload likes with the join association `c`. Repo.all from p in Post, join: c in assoc(p, :comments), preload: [comments: {c, :likes}] ## Preload queries Preload also allows queries to be given, allowing you to filter or customize how the preloads are fetched: comments_query = from c in Comment, order_by: c.published_at Repo.all from p in Post, preload: [comments: ^comments_query] The example above will issue two queries, one for loading posts and then another for loading the comments associated with the posts. Comments will be ordered by `published_at`. Note: keep in mind operations like limit and offset in the preload query will affect the whole result set and not each association. For example, the query below: comments_query = from c in Comment, order_by: c.popularity, limit: 5 Repo.all from p in Post, preload: [comments: ^comments_query] won't bring the top of comments per post. Rather, it will only bring the 5 top comments across all posts. ## Preload functions Preload also allows functions to be given. In such cases, the function receives the IDs to be fetched and it must return the associated data. This data will then be mapped and sorted: comment_preloader = fn post_ids -> fetch_comments_by_post_ids(post_ids) end Repo.all from p in Post, preload: [comments: ^comment_preloader] This is useful when the whole dataset was already loaded or must be explicitly fetched from elsewhere. ## Keywords example # Returns all posts, their associated comments, and the associated # likes for those comments. from(p in Post, preload: [:comments, comments: :likes], select: p) ## Expressions examples Post |> preload(:comments) |> select([p], p) Post |> join(:left, [p], c in assoc(p, :comments)) |> preload([p, c], [:user, comments: c]) |> select([p], p) """ defmacro preload(query, bindings \\ [], expr) do Preload.build(query, bindings, expr, __CALLER__) end @doc """ Restricts the query to return the first result ordered by primary key. The query will be automatically ordered by the primary key unless `order_by` is given or `order_by` is set in the query. Limit is always set to 1. ## Examples Post |> first |> Repo.one query |> first(:inserted_at) |> Repo.one """ def first(queryable, order_by \\ nil) def first(%Ecto.Query{} = query, nil) do query = %{query | limit: limit()} case query do %{order_bys: []} -> %{query | order_bys: [order_by_pk(query, :asc)]} %{} -> query end end def first(queryable, nil), do: first(Ecto.Queryable.to_query(queryable), nil) def first(queryable, key), do: first(order_by(queryable, ^key), nil) @doc """ Restricts the query to return the last result ordered by primary key. The query ordering will be automatically reversed, with ASC columns becoming DESC columns (and vice-versa) and limit is set to 1. If there is no ordering, the query will be automatically ordered decreasingly by primary key. ## Examples Post |> last |> Repo.one query |> last(:inserted_at) |> Repo.one """ def last(queryable, order_by \\ nil) def last(%Ecto.Query{} = query, nil) do query = %{query | limit: limit()} update_in query.order_bys, fn [] -> [order_by_pk(query, :desc)] order_bys -> for %{expr: expr} = order_by <- order_bys do %{order_by | expr: Enum.map(expr, fn {:desc, ast} -> {:asc, ast} {:asc, ast} -> {:desc, ast} end)} end end end def last(queryable, nil), do: last(Ecto.Queryable.to_query(queryable), nil) def last(queryable, key), do: last(order_by(queryable, ^key), nil) defp limit do %QueryExpr{expr: 1, params: [], file: __ENV__.file, line: __ENV__.line} end defp field(ix, field) when is_integer(ix) and is_atom(field) do {{:., [], [{:&, [], [ix]}, field]}, [], []} end defp order_by_pk(query, dir) do schema = assert_schema!(query) pks = schema.__schema__(:primary_key) expr = for pk <- pks, do: {dir, field(0, pk)} %QueryExpr{expr: expr, file: __ENV__.file, line: __ENV__.line} end defp assert_schema!(%{from: {_source, schema}}) when schema != nil, do: schema defp assert_schema!(query) do raise Ecto.QueryError, query: query, message: "expected a from expression with a schema" end end
32.94235
139
0.663929
7983b1dbcf1b5239242e399e68ecc3d710bfb44e
1,186
exs
Elixir
spec/haml_spec.exs
marnen/hamlex
38322997b12972f60a16d40e44f81d0c178e2523
[ "MIT" ]
null
null
null
spec/haml_spec.exs
marnen/hamlex
38322997b12972f60a16d40e44f81d0c178e2523
[ "MIT" ]
null
null
null
spec/haml_spec.exs
marnen/hamlex
38322997b12972f60a16d40e44f81d0c178e2523
[ "MIT" ]
null
null
null
defmodule HamlSpec do use ESpec, async: true {:ok, json} = File.read "#{__DIR__}/haml_spec/tests.json" tests = Poison.Parser.parse! json @context_names [ "headers", "basic Haml tags and CSS", "tags with unusual HTML characters", "tags with unusual CSS identifiers", "tags with inline content", "tags with nested content", "tags with HTML-style attributes", "tags with Ruby-style attributes", "silent comments", ] for {context_name, example_data} <- tests, context_name in @context_names do context context_name do import String, only: [to_atom: 1] for {name, %{"haml" => haml, "html" => html} = fields} <- example_data do opts = for field_name <- ["config", "locals"], into: [] do opt = Map.get fields, field_name, %{} {field_name |> to_atom, (for {key, value} <- opt, into: %{}, do: {key |> String.to_atom, value})} end specify name do result = Hamlex.render unquote(haml), unquote(Macro.escape opts) normalized_result = String.replace result, ~r/^ +/m, "" expect(normalized_result).to eq unquote(html) end end end end end
32.054054
107
0.618044
7983bd963777bb5559099434951403790bd8e61d
2,004
exs
Elixir
config/prod.exs
AminArria/sponsorly
fa78ead63076a54cb1cb1f9d4f4c5fd7a4a78fac
[ "MIT" ]
null
null
null
config/prod.exs
AminArria/sponsorly
fa78ead63076a54cb1cb1f9d4f4c5fd7a4a78fac
[ "MIT" ]
null
null
null
config/prod.exs
AminArria/sponsorly
fa78ead63076a54cb1cb1f9d4f4c5fd7a4a78fac
[ "MIT" ]
null
null
null
import Config # For production, don't forget to configure the url host # to something meaningful, Phoenix uses this information # when generating URLs. # # Note we also include the path to a cache manifest # containing the digested version of static files. This # manifest is generated by the `mix phx.digest` task, # which you should run after static files are built and # before starting your production server. config :sponsorly, SponsorlyWeb.Endpoint, url: [host: "sponsorly.aminarria.tech", port: 80], cache_static_manifest: "priv/static/cache_manifest.json" # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :sponsorly, SponsorlyWeb.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [ # port: 443, # cipher_suite: :strong, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH"), # transport_options: [socket_opts: [:inet6]] # ] # # The `cipher_suite` is set to `:strong` to support only the # latest and more secure SSL ciphers. This means old browsers # and clients may not be supported. You can set it to # `:compatible` for wider support. # # `:keyfile` and `:certfile` expect an absolute path to the key # and cert in disk or a relative path inside priv, for example # "priv/ssl/server.key". For all supported SSL configuration # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 # # We also recommend setting `force_ssl` in your endpoint, ensuring # no data is ever sent via http, always redirecting to https: # # config :sponsorly, SponsorlyWeb.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # Finally import the config/prod.secret.exs which loads secrets # and configuration from environment variables.
36.436364
66
0.716567
7983cc472b19116c2708bebc9555d591674985cc
1,638
ex
Elixir
clients/content/lib/google_api/content/v2/model/orders_create_test_return_response.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/orders_create_test_return_response.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/content/lib/google_api/content/v2/model/orders_create_test_return_response.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Content.V2.Model.OrdersCreateTestReturnResponse do @moduledoc """ ## Attributes * `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "content#ordersCreateTestReturnResponse". * `returnId` (*type:* `String.t`, *default:* `nil`) - The ID of the newly created test order return. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :kind => String.t(), :returnId => String.t() } field(:kind) field(:returnId) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.OrdersCreateTestReturnResponse do def decode(value, options) do GoogleApi.Content.V2.Model.OrdersCreateTestReturnResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.OrdersCreateTestReturnResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
32.76
161
0.73199
7983d2940c21b6655bc4f0e5245beb551fbf80ea
550
ex
Elixir
apps/graphql/lib/graphql/middleware/filter_argument.ex
ehealth-ua/ehealth.api
4ffe26a464fe40c95fb841a4aa2e147068f65ca2
[ "Apache-2.0" ]
8
2019-06-14T11:34:49.000Z
2021-08-05T19:14:24.000Z
apps/graphql/lib/graphql/middleware/filter_argument.ex
edenlabllc/ehealth.api.public
4ffe26a464fe40c95fb841a4aa2e147068f65ca2
[ "Apache-2.0" ]
1
2019-07-08T15:20:22.000Z
2019-07-08T15:20:22.000Z
apps/graphql/lib/graphql/middleware/filter_argument.ex
ehealth-ua/ehealth.api
4ffe26a464fe40c95fb841a4aa2e147068f65ca2
[ "Apache-2.0" ]
6
2018-05-11T13:59:32.000Z
2022-01-19T20:15:22.000Z
defmodule GraphQL.Middleware.FilterArgument do @moduledoc """ This middleware prepares the `filter` argument on connection fields as condition for `Ecto.Query.where/2` """ @behaviour Absinthe.Middleware @filter_arg :filter def call(%{state: :unresolved, arguments: arguments} = resolution, _) do filter = arguments |> Map.get(@filter_arg, %{}) |> Map.to_list() arguments = Map.put(arguments, @filter_arg, filter) %{resolution | arguments: arguments} end def call(resolution, _), do: resolution end
23.913043
107
0.687273
7984422728b54bdbcf9d74c7039a91924f8d3f4b
174
exs
Elixir
test/fontais/option/doctest1_test.exs
ianrumford/plymio_fontais
828d6726223d2fa038f2c1374fcd2f4b67371544
[ "MIT" ]
null
null
null
test/fontais/option/doctest1_test.exs
ianrumford/plymio_fontais
828d6726223d2fa038f2c1374fcd2f4b67371544
[ "MIT" ]
null
null
null
test/fontais/option/doctest1_test.exs
ianrumford/plymio_fontais
828d6726223d2fa038f2c1374fcd2f4b67371544
[ "MIT" ]
null
null
null
defmodule PlymioFontaisOptionDoctest1Test do use ExUnit.Case, async: true use PlymioFontaisHelperTest import Plymio.Fontais.Option doctest Plymio.Fontais.Option end
21.75
44
0.827586
79844c72e6fb046802cc0709674c2344de32ade4
257
ex
Elixir
lib/radiator_web/graphql/admin/resolvers/session.ex
bhtabor/radiator
39c137a18d36d6f418f9d1ffb7aa2c99011d66cf
[ "MIT" ]
92
2019-01-03T11:46:23.000Z
2022-02-19T21:28:44.000Z
lib/radiator_web/graphql/admin/resolvers/session.ex
bhtabor/radiator
39c137a18d36d6f418f9d1ffb7aa2c99011d66cf
[ "MIT" ]
350
2019-04-11T07:55:51.000Z
2021-08-03T11:19:05.000Z
lib/radiator_web/graphql/admin/resolvers/session.ex
bhtabor/radiator
39c137a18d36d6f418f9d1ffb7aa2c99011d66cf
[ "MIT" ]
10
2019-04-18T12:47:27.000Z
2022-01-25T20:49:15.000Z
defmodule RadiatorWeb.GraphQL.Admin.Resolvers.Session do alias RadiatorWeb.GraphQL.Helpers.UserHelpers def prolong_authenticated_session(_parent, _params, %{context: %{current_user: user}}) do UserHelpers.new_session_for_valid_user(user) end end
32.125
91
0.81323
79845854752045c0855c28a1056822f042aacccb
2,182
ex
Elixir
test/support/live_views/update.ex
gaslight/live_element
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
[ "MIT" ]
null
null
null
test/support/live_views/update.ex
gaslight/live_element
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
[ "MIT" ]
null
null
null
test/support/live_views/update.ex
gaslight/live_element
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
[ "MIT" ]
null
null
null
defmodule LiveElementTest.TZLive do use LiveElement def render(%{name: "NestedAppend"} = assigns) do ~H""" time: <%= @time %> <%= @name %> <div id={"append-" <> @name} phx-update="append"><%= for item <- @items do %> <!-- example --> <div id={"item-" <> item}><%= item %></div> <% end %></div> """ end def render(assigns) do ~H""" time: <%= @time %> <%= @name %> """ end def mount(:not_mounted_at_router, session, socket) do {:ok, assign(socket, time: "12:00", items: [], name: session["name"] || "NY")} end def handle_call({:append, items}, _, socket), do: {:reply, :ok, assign(socket, items: items)} end defmodule LiveElementTest.AppendLive do use LiveElement def render(assigns) do ~L""" <div <%= @id && {:safe, "id=#{inspect(@id)}"} %> phx-update="<%= @update_type %>"> <%= for %{id: id, name: name} <- @time_zones do %> <h1 <%= id && {:safe, "id=title-#{id}"} %>><%= name %></h1> <%= live_render(@socket, LiveElementTest.TZLive, id: "tz-#{id}", session: %{"name" => name}) %> <% end %> </div> """ end def mount(_params, %{"time_zones" => {update_type, time_zones}}, socket) do {:ok, assign(socket, update_type: update_type, time_zones: time_zones, id: "times"), temporary_assigns: [time_zones: []]} end def handle_event("remove-id", _, socket) do {:noreply, assign(socket, :id, nil)} end def handle_event("add-tz", %{"id" => id, "name" => name}, socket) do {:noreply, assign(socket, :time_zones, [%{id: id, name: name}])} end end defmodule LiveElementTest.ShuffleLive do use LiveElement def render(assigns) do ~H""" <%= for zone <- @time_zones do %> <div id={"score-" <> zone["id"]}> <%= live_render(@socket, LiveElementTest.TZLive, id: "tz-#{zone["id"]}", session: %{"name" => zone["name"]}) %> </div> <% end %> """ end def mount(_params, %{"time_zones" => time_zones}, socket) do {:ok, assign(socket, time_zones: time_zones)} end def handle_event("reverse", _, socket) do {:noreply, assign(socket, :time_zones, Enum.reverse(socket.assigns.time_zones))} end end
28.710526
119
0.570577
7984a95dcad80462c03d530de6c7b83a3c3414b7
4,975
ex
Elixir
lib/rules/default.ex
Mendor/mudkip
65d265508ffe474835237d9302d1851da6cc0a27
[ "WTFPL" ]
1
2017-02-18T04:36:16.000Z
2017-02-18T04:36:16.000Z
lib/rules/default.ex
Mendor/mudkip
65d265508ffe474835237d9302d1851da6cc0a27
[ "WTFPL" ]
null
null
null
lib/rules/default.ex
Mendor/mudkip
65d265508ffe474835237d9302d1851da6cc0a27
[ "WTFPL" ]
null
null
null
defmodule Mudkip.Rules.Default do @moduledoc """ Default rendering rules set. The other rendering rules may be written using this one as an example. Every rules set should has method `render/1` accepting the list of binary strings as the only parameter. Then this list should be compiled to HTML in any way you prefer. TODO: `___bold italic___`, HTML escaping """ alias Mudkip.Helpers, as: MH @doc """ API method for rules set. Run compilation line-by-line. """ def render(data) do MH.join(lc line inlist data do try_render_line(line) end) end @doc """ Line renderer. Every `apply_*` method just tries to find and process Markdown elements. """ defp try_render_line(line) do preline = apply_pre(line) if line == preline do line |> apply_header |> apply_rulers |> apply_images |> apply_links |> apply_lists |> apply_bold |> apply_italic |> apply_monospace |> apply_blockquotes |> apply_linebreaks_fix |> apply_paragraphs else preline end end @doc """ Preformatted text (indented using at least 4 spaces or 1 tab from the lines start). """ defp apply_pre(line) do case Regex.run(%r/^(?:\s{4}|\t)(.*)$/s, line) do nil -> line [_, found] -> MH.format(:pre, Regex.replace(%r/(?:\n\s{4}|\t)(.*)/, found, "\\1")) end end @doc """ Headers (lines stared from one or more `#` character or "underlined" with `-` or `=` character). """ defp apply_header(line) do case Regex.run(%r/^(#+)\s(.+)/, line) do [_line, hsize, value] -> MH.format("h" <> %s(#{byte_size(hsize)}), Regex.replace(%r/(.*)\s#+$/, value, "\\1")) nil -> line2 = Regex.replace(%r/(.+)\n===+/, line, MH.format(:h1, "\\1")) Regex.replace(%r/(.+)\n\-\-\-+/, line2, MH.format(:h2, "\\1")) end end @doc """ Rulers (a line of `.`, `-` or `*` characters, may be separated with spaces). """ defp apply_rulers(line) do Regex.replace(%r/^([\.\-\*]\s*){3,100}$/, line, "<hr />") end @doc """ Lists (lines started from `*`, `+` or `-` character or from a number). TODO: embedded lists """ defp apply_lists(line) do uls = case Regex.run(%r/^\s?[\*\+\-]\s(.*)$/s, line) do nil -> line [_, found] -> MH.format(:ul, MH.join(lc item inlist String.split(found, %r/\n\s?[\*\+\-]\s/) do MH.format(:li, item) end)) end case Regex.run(%r/^\s?[0-9]\.\s(.*)$/s, uls) do nil -> uls [_, found] -> MH.format(:ol, MH.join(lc item inlist String.split(found, %r/\n\s?[0-9]\.\s/) do MH.format(:li, item) end)) end end @doc """ Images (just a links with `!` characters beforehand). """ defp apply_images(line) do line2 = Regex.replace(%r/\!\[([^\]]+)\]\(([^\)\s]+)\)/, line, MH.format_img("src=\"\\2\" alt=\"\\1\"")) Regex.replace(%r/\!\[([^\]]+)\]\(([^\)\s]+)\s([^\)]+)\)/, line2, MH.format_img("title=\\3 src=\"\\2\" alt=\"\\1\"")) end @doc """ Links (`<link>`, `[text](link)` or `[text](link "alternate title")`). TODO: reference links, shortcut references """ defp apply_links(line) do line2 = Regex.replace(%r/<((?!img\s).+(\:\/\/|@).+)>/, line, MH.format_link("href=\"\\1\"", "\\1")) line3 = Regex.replace(%r/\[([^\]]+)\]\(([^\)\s]+)\)/, line2, MH.format_link("href=\"\\2\"", "\\1")) Regex.replace(%r/\[([^\]]+)\]\(([^\)\s]+)\s([^\)]+)\)/, line3, MH.format_link("title=\\3 href=\"\\2\"", "\\1")) end @doc """ Bold text (`__text__` or `**text**`). """ defp apply_bold(line) do line2 = Regex.replace(%r/(\*\*)([^\*]+)(\*\*)/, line, MH.format(:strong, "\\2")) Regex.replace(%r/(__)([^_]+)(__)/, line2, MH.format(:strong, "\\2")) end @doc """ Italic text (`_text_` or `*text*`). """ defp apply_italic(line) do line2 = Regex.replace(%r/(\*)(.+)(\*)/, line, MH.format(:em, "\\2")) Regex.replace(%r/(_)(.+)(_)/, line2, MH.format(:em, "\\2")) end @doc """ Monospace text (text in ``` characters). """ defp apply_monospace(line) do Regex.replace(%r/`([^`]+)`/, line, MH.format(:pre, "\\1")) end @doc """ Blockquotes (lines started from `>` character). """ defp apply_blockquotes(line) do case Regex.run(%r/^>\s?(.*)/, line) do nil -> line [_, line2] -> Mudkip.Helpers.format(:blockquote, line2) end end @doc """ Remove unnecessary `\n`. """ defp apply_linebreaks_fix(line) do Regex.replace(%r/\n([^>\s].*)/, line, " \\1") end @doc """ If the formatted line isn't header, blockquote, list or preformatted block, mark it as a paragraph. """ defp apply_paragraphs(line) do Regex.replace(%r/^((?!(<h|<blo|<ul|<ol|<pre)).*)$/s, line, MH.format(:p, "\\1")) end end
27.638889
100
0.526633
7984cb6a7446a6649af2324787e6a2f245af2357
1,492
ex
Elixir
lib/space_raiders_web/views/error_helpers.ex
abinader89/Space-Raiders
d5e01a3200a54d22824b890238613a00f32a7d62
[ "CC-BY-3.0" ]
null
null
null
lib/space_raiders_web/views/error_helpers.ex
abinader89/Space-Raiders
d5e01a3200a54d22824b890238613a00f32a7d62
[ "CC-BY-3.0" ]
null
null
null
lib/space_raiders_web/views/error_helpers.ex
abinader89/Space-Raiders
d5e01a3200a54d22824b890238613a00f32a7d62
[ "CC-BY-3.0" ]
null
null
null
defmodule SpaceRaidersWeb.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do Enum.map(Keyword.get_values(form.errors, field), fn error -> content_tag(:span, translate_error(error), class: "help-block") end) end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # When using gettext, we typically pass the strings we want # to translate as a static argument: # # # Translate "is invalid" in the "errors" domain # dgettext("errors", "is invalid") # # # Translate the number of files with plural rules # dngettext("errors", "1 file", "%{count} files", count) # # Because the error messages we show in our forms and APIs # are defined inside Ecto, we need to translate them dynamically. # This requires us to call the Gettext module passing our gettext # backend as first argument. # # Note we use the "errors" domain, which means translations # should be written to the errors.po file. The :count option is # set by Ecto and indicates we should also apply plural rules. if count = opts[:count] do Gettext.dngettext(SpaceRaidersWeb.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(SpaceRaidersWeb.Gettext, "errors", msg, opts) end end end
33.155556
81
0.673592
7984e10b90d1c49e1e2257dcee07226bff4a53db
1,759
ex
Elixir
getting-started/lib/getting_started_elixir_web.ex
renovate-bot/elixir-samples
91da795ecdfac83eb6fcac63bc532da98c69d520
[ "Apache-2.0" ]
274
2017-08-25T06:39:51.000Z
2022-03-15T21:03:27.000Z
getting-started/lib/getting_started_elixir_web.ex
renovate-bot/elixir-samples
91da795ecdfac83eb6fcac63bc532da98c69d520
[ "Apache-2.0" ]
15
2017-10-03T17:05:48.000Z
2021-11-23T00:33:23.000Z
getting-started/lib/getting_started_elixir_web.ex
renovate-bot/elixir-samples
91da795ecdfac83eb6fcac63bc532da98c69d520
[ "Apache-2.0" ]
42
2017-08-28T20:08:47.000Z
2022-01-18T07:51:02.000Z
defmodule GettingStartedElixirWeb do @moduledoc """ The entrypoint for defining your web interface, such as controllers, views, channels and so on. This can be used in your application as: use GettingStartedElixirWeb, :controller use GettingStartedElixirWeb, :view The definitions below will be executed for every view, controller, etc, so keep them short and clean, focused on imports, uses and aliases. Do NOT define functions inside the quoted expressions below. Instead, define any helper function in modules and import those modules here. """ def controller do quote do use Phoenix.Controller, namespace: GettingStartedElixirWeb import Plug.Conn import GettingStartedElixirWeb.Router.Helpers import GettingStartedElixirWeb.Gettext end end def view do quote do use Phoenix.View, root: "lib/getting_started_elixir_web/templates", namespace: GettingStartedElixirWeb # Import convenience functions from controllers import Phoenix.Controller, only: [get_flash: 2, view_module: 1] # Use all HTML functionality (forms, tags, etc) use Phoenix.HTML import GettingStartedElixirWeb.Router.Helpers import GettingStartedElixirWeb.ErrorHelpers import GettingStartedElixirWeb.Gettext end end def router do quote do use Phoenix.Router import Plug.Conn import Phoenix.Controller end end def channel do quote do use Phoenix.Channel import GettingStartedElixirWeb.Gettext end end @doc """ When used, dispatch to the appropriate controller/view/etc. """ defmacro __using__(which) when is_atom(which) do apply(__MODULE__, which, []) end end
25.867647
73
0.714611
7984f04a141ad70ef21a557f5a5a78d625a0b34d
4,590
ex
Elixir
lib/white_bread/outputers/json.ex
ejscunha/white-bread
1c2eed1c98545beeb70b590426ce9026a8455e97
[ "MIT" ]
209
2015-03-03T14:14:28.000Z
2020-10-26T03:23:48.000Z
lib/white_bread/outputers/json.ex
ejscunha/white-bread
1c2eed1c98545beeb70b590426ce9026a8455e97
[ "MIT" ]
83
2015-03-23T11:46:51.000Z
2020-11-04T09:47:06.000Z
lib/white_bread/outputers/json.ex
ejscunha/white-bread
1c2eed1c98545beeb70b590426ce9026a8455e97
[ "MIT" ]
46
2015-06-12T17:37:21.000Z
2020-10-30T09:52:45.000Z
defmodule WhiteBread.Outputers.JSON do use GenServer @moduledoc """ This generic server accumulates information about White Bread scenarios then formats them as JSON and outputs them to a file in one go. """ defstruct path: nil, data: [] ## Client Interface @doc false def start do {:ok, outputer} = GenServer.start __MODULE__, [] outputer end @doc false def stop(outputer) do GenServer.cast(outputer, :stop) end ## Interface to Generic Server Machinery def init(_) do Process.flag(:trap_exit, true) {:ok, %__MODULE__{path: document_path()}} end def handle_cast({:final_results, results}, state) do all_features = results[:successes] ++ results[:failures] {:noreply, Map.put(state, :data, Enum.map(all_features, &map_feature/1))} end def handle_cast(:stop, state) do {:stop, :normal, state} end def handle_cast(_x, state) do {:noreply, state} end def terminate(_, state = %__MODULE__{path: path}) do report(state, path) end ## Internal defp result_for_step(_step, {:ok, _name}) do %{ status: "passed", duration: 1, } end defp result_for_step(step, {:failed, {error, failed_step, error2}}) do cond do step.line < failed_step.line -> %{status: "passed", duration: 1} step.line > failed_step.line -> %{status: "skipped", duration: 1} step.line == failed_step.line -> %{ status: "failed", duration: 1, error_message: format_error_message(error, failed_step, error2) } end end defp format_error_message(error, _failed_step, {error_object, stacktrace}) when is_atom(error) do Exception.format(:error, error_object, stacktrace) end defp format_error_message(_error, _failed_step, assertion_error) do assertion_error.message end defp find_scenario_result(scenario, feature_result) do all_results = feature_result[:successes] ++ feature_result[:failures] Enum.find(all_results, fn({inner_scenario, _details}) -> inner_scenario.line == scenario.line && inner_scenario.name == scenario.name end) end defp step_keyword(%Gherkin.Elements.Steps.Given{}), do: "Given " defp step_keyword(%Gherkin.Elements.Steps.When{}), do: "When " defp step_keyword(%Gherkin.Elements.Steps.Then{}), do: "Then " defp step_keyword(%Gherkin.Elements.Steps.And{}), do: "And " defp step_keyword(%Gherkin.Elements.Steps.But{}), do: "But " defp normalize_name(name) do name |> String.downcase() |> String.replace(~r/\s/, "-") end defp document_path do case Keyword.fetch!(outputers(), __MODULE__) do [path: "/"] -> raise WhiteBread.Outputers.JSON.PathError [path: x] when is_binary(x) -> Path.expand x end end defp write(content, path) do File.mkdir_p!(parent path) && File.write!(path, content) end defp parent(path) do Path.join(drop(Path.split path)) end defp drop(x) when is_list(x), do: x -- [List.last(x)] defmodule PathError do defexception message: "Given root directory." end defp report(state, path) do state.data |> Poison.encode!(pretty: true, iodata: true) |> write(path) end defp outputers do Application.fetch_env!(:white_bread, :outputers) end defp map_feature({feature, result}) do %{ id: normalize_name(feature.name), name: feature.name, uri: feature.file, keyword: "Feature", type: "scenario", line: feature.line, description: feature.description, elements: Enum.map(feature.scenarios, &(map_scenario(&1, feature, result))), tags: feature.tags |> Enum.map(fn(tag) -> %{name: tag, line: feature.line - 1} end), } end defp map_scenario(scenario, feature, feature_result) do scenario_result = find_scenario_result(scenario, feature_result) %{ keyword: "Scenario", id: [feature.name, scenario.name] |> Enum.map(&normalize_name/1) |> Enum.join(";"), name: scenario.name, tags: scenario.tags |> Enum.map(fn(tag) -> %{name: tag, line: scenario.line - 1} end), steps: Enum.map(scenario.steps, &(map_step(&1, scenario_result))), } end defp map_step(step, scenario_result) do {_scenario, scenario_result_details} = scenario_result %{ keyword: step_keyword(step), name: step.text, line: step.line, doc_string: %{ content_type: "", value: step.doc_string, line: step.line + 1 }, match: %{}, result: result_for_step(step, scenario_result_details), } end end
27.159763
99
0.652941
798501e7287d503171f64e6f16566c23c15206ff
1,862
ex
Elixir
test/support/fixtures.ex
Ross65536/ex_oauth2_provider
348debc7b5cd068d1b5a03bacfe67c2c89f8077e
[ "MIT" ]
null
null
null
test/support/fixtures.ex
Ross65536/ex_oauth2_provider
348debc7b5cd068d1b5a03bacfe67c2c89f8077e
[ "MIT" ]
1
2022-03-26T12:42:37.000Z
2022-03-26T12:42:37.000Z
test/support/fixtures.ex
Ross65536/ex_oauth2_provider
348debc7b5cd068d1b5a03bacfe67c2c89f8077e
[ "MIT" ]
1
2022-02-21T12:45:09.000Z
2022-02-21T12:45:09.000Z
defmodule ExOauth2Provider.Test.Fixtures do @moduledoc false alias ExOauth2Provider.AccessTokens alias Dummy.{OauthApplications.OauthApplication, OauthAccessGrants.OauthAccessGrant, Repo, Users.User} alias Ecto.Changeset def resource_owner(attrs \\ []) do attrs = Keyword.merge([email: "[email protected]"], attrs) User |> struct() |> Changeset.change(attrs) |> Repo.insert!() end def application(attrs \\ []) do resource_owner = Keyword.get(attrs, :resource_owner) || resource_owner() attrs = [ owner_id: resource_owner.id, uid: "test", secret: "secret", name: "OAuth Application", redirect_uri: "urn:ietf:wg:oauth:2.0:oob", scopes: "public read write"] |> Keyword.merge(attrs) |> Keyword.drop([:resource_owner]) %OauthApplication{} |> Changeset.change(attrs) |> Repo.insert!() end def access_token(attrs \\ []) do {:ok, access_token} = attrs |> Keyword.get(:resource_owner) |> Kernel.||(resource_owner()) |> AccessTokens.create_token(Enum.into(attrs, %{}), otp_app: :ex_oauth2_provider) access_token end def application_access_token(attrs \\ []) do {:ok, access_token} = attrs |> Keyword.get(:application) |> Kernel.||(application()) |> AccessTokens.create_application_token(Enum.into(attrs, %{}), otp_app: :ex_oauth2_provider) access_token end def access_grant(application, user, code, redirect_uri, extra_attrs \\ []) do attrs = [ expires_in: 900, redirect_uri: "urn:ietf:wg:oauth:2.0:oob", application_id: application.id, resource_owner_id: user.id, token: code, scopes: "read", redirect_uri: redirect_uri ] ++ extra_attrs %OauthAccessGrant{} |> Changeset.change(attrs) |> Repo.insert!() end end
26.225352
104
0.641783
798510e2d74ad2e1cdb9a045cc1beaf4232d4e68
823
exs
Elixir
test/outputers/style_test.exs
ejscunha/white-bread
1c2eed1c98545beeb70b590426ce9026a8455e97
[ "MIT" ]
209
2015-03-03T14:14:28.000Z
2020-10-26T03:23:48.000Z
test/outputers/style_test.exs
ejscunha/white-bread
1c2eed1c98545beeb70b590426ce9026a8455e97
[ "MIT" ]
83
2015-03-23T11:46:51.000Z
2020-11-04T09:47:06.000Z
test/outputers/style_test.exs
ejscunha/white-bread
1c2eed1c98545beeb70b590426ce9026a8455e97
[ "MIT" ]
46
2015-06-12T17:37:21.000Z
2020-10-30T09:52:45.000Z
defmodule WhiteBread.Outputers.StyleTests do use ExUnit.Case alias WhiteBread.Outputers.Style test "check failed message is in `red` colour encoding" do styled_binary = Style.failed("Exception was thrown") assert styled_binary == "\e[31mException was thrown\e[0m" end test "check success message is in `green` colour encoding" do styled_binary = Style.success("Success message") assert styled_binary == "\e[32mSuccess message\e[0m" end test "decide how to colour a failed message with red" do styled_binary = Style.decide_color(:failed, "Exception was thrown"); assert String.contains? styled_binary, "\e[31m" end test "no colour style atom then return plain message" do styled_binary = Style.decide_color(:no_color, "I'm just a message"); assert styled_binary == "I'm just a message" end end
32.92
70
0.753341
798518b345b1efdf3816f97eccd4013750b0b426
1,192
ex
Elixir
lib/vega/warning_color_rule.ex
Fudoshiki/vega
0577024afc734933048645976705784512fbc1f4
[ "MIT" ]
4
2020-03-22T22:12:29.000Z
2020-07-01T22:32:01.000Z
lib/vega/warning_color_rule.ex
Fudoshiki/vega
0577024afc734933048645976705784512fbc1f4
[ "MIT" ]
3
2021-03-10T11:53:41.000Z
2021-10-17T11:18:54.000Z
lib/vega/warning_color_rule.ex
Fudoshiki/vega
0577024afc734933048645976705784512fbc1f4
[ "MIT" ]
3
2020-03-30T19:03:23.000Z
2022-01-17T20:21:42.000Z
defmodule Vega.WarningColorRule do @moduledoc false use Yildun.Collection alias Vega.WarningColorRule document do attribute :color, String.t() ## the default color attribute :n, non_neg_integer() ## threshold attribute :warning, String.t() ## the warning color end def new(color, n, warning) do %WarningColorRule{color: color, n: n, warning: warning} |> filter_default() end def calc_color(nil, _n) do [] end def calc_color(%WarningColorRule{color: "default", n: max, warning: warning}, n) when max > 0 do case n > max do true -> warning false -> [] end end def calc_color(%WarningColorRule{color: color, n: max, warning: warning}, n) when max > 0 do case n > max do true -> warning false -> color end end def calc_color(%WarningColorRule{color: color}, _n) do color end @doc """ Filter default color rule. If the color and the warning color is "none", then the color rule has no effect, so it can be removed from the list. """ def filter_default(%WarningColorRule{color: "none", n: _n, warning: "none"}) do nil end def filter_default(other) do other end end
24.833333
98
0.656879
79853e293d5412ffbffe18a652d1b189fe66d873
2,265
ex
Elixir
clients/games_configuration/lib/google_api/games_configuration/v1configuration/model/leaderboard_configuration_list_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/games_configuration/lib/google_api/games_configuration/v1configuration/model/leaderboard_configuration_list_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/games_configuration/lib/google_api/games_configuration/v1configuration/model/leaderboard_configuration_list_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.GamesConfiguration.V1configuration.Model.LeaderboardConfigurationListResponse do @moduledoc """ A ListConfigurations response. ## Attributes * `items` (*type:* `list(GoogleApi.GamesConfiguration.V1configuration.Model.LeaderboardConfiguration.t)`, *default:* `nil`) - The leaderboard configurations. * `kind` (*type:* `String.t`, *default:* `nil`) - Uniquely identifies the type of this resource. Value is always the fixed string `gamesConfiguration#leaderboardConfigurationListResponse`. * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - The pagination token for the next page of results. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :items => list(GoogleApi.GamesConfiguration.V1configuration.Model.LeaderboardConfiguration.t()), :kind => String.t(), :nextPageToken => String.t() } field(:items, as: GoogleApi.GamesConfiguration.V1configuration.Model.LeaderboardConfiguration, type: :list ) field(:kind) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.GamesConfiguration.V1configuration.Model.LeaderboardConfigurationListResponse do def decode(value, options) do GoogleApi.GamesConfiguration.V1configuration.Model.LeaderboardConfigurationListResponse.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.GamesConfiguration.V1configuration.Model.LeaderboardConfigurationListResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.952381
192
0.746137
7985478cbc2541abe4ed9955df191fa074d4d127
4,136
ex
Elixir
lib/livebook_web/live/settings_live.ex
Fudoshiki/livebook
0b30fd02d9a50b84873725f3e05974d62fee398f
[ "Apache-2.0" ]
null
null
null
lib/livebook_web/live/settings_live.ex
Fudoshiki/livebook
0b30fd02d9a50b84873725f3e05974d62fee398f
[ "Apache-2.0" ]
null
null
null
lib/livebook_web/live/settings_live.ex
Fudoshiki/livebook
0b30fd02d9a50b84873725f3e05974d62fee398f
[ "Apache-2.0" ]
null
null
null
defmodule LivebookWeb.SettingsLive do use LivebookWeb, :live_view import LivebookWeb.UserHelpers alias LivebookWeb.{SidebarHelpers, PageHelpers} @impl true def mount(_params, _session, socket) do file_systems = Livebook.Config.file_systems() file_systems_env = Livebook.Config.file_systems_as_env(file_systems) {:ok, assign(socket, file_systems: file_systems, file_systems_env: file_systems_env )} end @impl true def render(assigns) do ~H""" <div class="flex flex-grow h-full"> <SidebarHelpers.sidebar> <SidebarHelpers.logo_item socket={@socket} /> <SidebarHelpers.break_item /> <SidebarHelpers.link_item icon="settings-3-fill" label="Settings" path={Routes.settings_path(@socket, :page)} active={false} /> <SidebarHelpers.user_item current_user={@current_user} path={Routes.settings_path(@socket, :user)} /> </SidebarHelpers.sidebar> <div class="flex-grow px-6 py-8 overflow-y-auto"> <div class="max-w-screen-md w-full mx-auto px-4 pb-8 space-y-8"> <div> <PageHelpers.title text="Settings" socket={@socket} /> <p class="mt-4 text-gray-700"> Here you can change global Livebook configuration. Keep in mind that this configuration is not persisted and gets discarded as soon as you stop the application. </p> </div> <!-- File systems configuration --> <div class="flex flex-col space-y-4"> <div class="flex justify-between items-center"> <h2 class="text-xl text-gray-800 font-semibold"> File systems </h2> <span class="tooltip top" data-tooltip="Copy as environment variables"> <button class="icon-button" aria-label="copy as environment variables" id={"file-systems-env-clipcopy"} phx-hook="ClipCopy" data-target-id={"file-systems-env-source"} disabled={@file_systems_env == ""}> <.remix_icon icon="clipboard-line" class="text-lg" /> </button> <span class="hidden" id="file-systems-env-source"><%= @file_systems_env %></span> </span> </div> <LivebookWeb.SettingsLive.FileSystemsComponent.render file_systems={@file_systems} socket={@socket} /> </div> </div> </div> </div> <%= if @live_action == :user do %> <.current_user_modal return_to={Routes.settings_path(@socket, :page)} current_user={@current_user} /> <% end %> <%= if @live_action == :add_file_system do %> <.modal class="w-full max-w-3xl" return_to={Routes.settings_path(@socket, :page)}> <.live_component module={LivebookWeb.SettingsLive.AddFileSystemComponent} id="add-file-system" return_to={Routes.settings_path(@socket, :page)} /> </.modal> <% end %> <%= if @live_action == :detach_file_system do %> <.modal class="w-full max-w-xl" return_to={Routes.settings_path(@socket, :page)}> <.live_component module={LivebookWeb.SettingsLive.RemoveFileSystemComponent} id="detach-file-system" return_to={Routes.settings_path(@socket, :page)} file_system={@file_system} /> </.modal> <% end %> """ end @impl true def handle_params(%{"file_system_index" => index}, _url, socket) do index = String.to_integer(index) file_system = Enum.at(socket.assigns.file_systems, index) {:noreply, assign(socket, :file_system, file_system)} end def handle_params(_params, _url, socket), do: {:noreply, socket} @impl true def handle_info({:file_systems_updated, file_systems}, socket) do file_systems_env = Livebook.Config.file_systems_as_env(file_systems) {:noreply, assign(socket, file_systems: file_systems, file_systems_env: file_systems_env)} end def handle_info(_message, socket), do: {:noreply, socket} end
36.928571
109
0.611944
7985832f0840e474e95dea01a1cb7ecdddefaf8f
8,314
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v35/api/campaign_creative_associations.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v35/api/campaign_creative_associations.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v35/api/campaign_creative_associations.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.DFAReporting.V35.Api.CampaignCreativeAssociations do @moduledoc """ API calls for all endpoints tagged `CampaignCreativeAssociations`. """ alias GoogleApi.DFAReporting.V35.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Associates a creative with the specified campaign. This method creates a default ad with dimensions matching the creative in the campaign if such a default ad does not exist already. ## Parameters * `connection` (*type:* `GoogleApi.DFAReporting.V35.Connection.t`) - Connection to server * `profile_id` (*type:* `String.t`) - User profile ID associated with this request. * `campaign_id` (*type:* `String.t`) - Campaign ID in this association. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.DFAReporting.V35.Model.CampaignCreativeAssociation.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.DFAReporting.V35.Model.CampaignCreativeAssociation{}}` on success * `{:error, info}` on failure """ @spec dfareporting_campaign_creative_associations_insert( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.DFAReporting.V35.Model.CampaignCreativeAssociation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def dfareporting_campaign_creative_associations_insert( connection, profile_id, campaign_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url( "/dfareporting/v3.5/userprofiles/{profileId}/campaigns/{campaignId}/campaignCreativeAssociations", %{ "profileId" => URI.encode(profile_id, &URI.char_unreserved?/1), "campaignId" => URI.encode(campaign_id, &URI.char_unreserved?/1) } ) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.DFAReporting.V35.Model.CampaignCreativeAssociation{}] ) end @doc """ Retrieves the list of creative IDs associated with the specified campaign. This method supports paging. ## Parameters * `connection` (*type:* `GoogleApi.DFAReporting.V35.Connection.t`) - Connection to server * `profile_id` (*type:* `String.t`) - User profile ID associated with this request. * `campaign_id` (*type:* `String.t`) - Campaign ID in this association. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:maxResults` (*type:* `integer()`) - Maximum number of results to return. * `:pageToken` (*type:* `String.t`) - Value of the nextPageToken from the previous result page. * `:sortOrder` (*type:* `String.t`) - Order of sorted results. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.DFAReporting.V35.Model.CampaignCreativeAssociationsListResponse{}}` on success * `{:error, info}` on failure """ @spec dfareporting_campaign_creative_associations_list( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.DFAReporting.V35.Model.CampaignCreativeAssociationsListResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def dfareporting_campaign_creative_associations_list( connection, profile_id, campaign_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :maxResults => :query, :pageToken => :query, :sortOrder => :query } request = Request.new() |> Request.method(:get) |> Request.url( "/dfareporting/v3.5/userprofiles/{profileId}/campaigns/{campaignId}/campaignCreativeAssociations", %{ "profileId" => URI.encode(profile_id, &URI.char_unreserved?/1), "campaignId" => URI.encode(campaign_id, &URI.char_unreserved?/1) } ) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.DFAReporting.V35.Model.CampaignCreativeAssociationsListResponse{}] ) end end
42.635897
196
0.631224
79858e45350d8106d921c697f2c47f693eb82c6a
2,941
ex
Elixir
lib/transport/tcp.ex
ityonemo/transporter
7dfbc736b383421f29d3f5418fd1b92b5a0a0eff
[ "BSD-3-Clause" ]
1
2021-04-28T15:14:45.000Z
2021-04-28T15:14:45.000Z
lib/transport/tcp.ex
ityonemo/transport
7dfbc736b383421f29d3f5418fd1b92b5a0a0eff
[ "BSD-3-Clause" ]
null
null
null
lib/transport/tcp.ex
ityonemo/transport
7dfbc736b383421f29d3f5418fd1b92b5a0a0eff
[ "BSD-3-Clause" ]
null
null
null
defmodule Transport.Tcp do @moduledoc """ implements a tcp transport strategy. """ @behaviour Transport alias Transport @type socket :: Transport.socket @connection_opts [:binary, active: false] @spec send(socket, iodata) :: :ok | {:error, term} @doc "Callback implementation for `c:Transport.send/2`, via `:gen_tcp.send/2`" defdelegate send(sock, content), to: :gen_tcp @spec recv(socket, non_neg_integer) :: {:ok, binary} | {:error, term} @doc "Callback implementation for `c:Transport.recv/2`, via `:gen_tcp.recv/2`." defdelegate recv(sock, length), to: :gen_tcp @spec recv(socket, non_neg_integer, timeout) :: {:ok, binary} | {:error, term} @doc "Callback implementation for `c:Transport.recv/3`, via `:gen_tcp.recv/3`." defdelegate recv(sock, length, timeout), to: :gen_tcp @impl true @spec type :: :tcp def type, do: :tcp @impl true @spec listen(:inet.port_number, keyword) :: {:ok, socket} | {:error, term} @doc section: :server @doc """ Callback implementation for `c:Transport.listen/2`. NB: `Transport.Tcp` defaults to using a binary tcp port. """ def listen(port, opts \\ []) do :gen_tcp.listen(port, @connection_opts ++ opts) end @spec accept(socket, timeout) :: {:ok, socket} | {:error, term} @doc section: :server @doc "Callback implementation for `c:Transport.accept/2`." defdelegate accept(sock, timeout), to: :gen_tcp @impl true @spec handshake(:inet.socket, keyword) :: {:ok, Api.socket} @doc section: :server @doc """ Callback implementation for `c:Transport.handshake/2`. Does not request the client-side for an upgrade to an authenticated or encrypted channel, but this is also where you should set post-connection options (such as setting `active: true`) """ def handshake(socket, opts!) do opts! = Keyword.take(opts!, [:active]) case :inet.setopts(socket, opts!) do :ok -> {:ok, socket} any -> any end end @impl true @spec connect(term, :inet.port_number) :: {:ok, socket} | {:error, term} @spec connect(term, :inet.port_number, keyword) :: {:ok, socket} | {:error, term} @doc section: :client @doc "Callback implementation for `c:Transport.connect/3`." def connect(host, port, opts! \\ []) do timeout = opts![:timeout] || :infinity opts! = Keyword.drop(opts!, [:timeout]) :gen_tcp.connect(host, port, @connection_opts ++ opts!, timeout) end @impl true @spec upgrade(socket, keyword) :: {:ok, :inet.socket} | {:error, term} @doc section: :client @doc """ Callback implementation for `c:Transport.upgrade/2`. Does not perform any cryptographic authentication, but this is where you should set post-connection options (such as setting `active: true`) """ def upgrade(socket, opts!) do opts! = Keyword.drop(opts!, [:tls_opts, :timeout]) case :inet.setopts(socket, opts!) do :ok -> {:ok, socket} error -> error end end end
31.967391
83
0.66372
7985eaef96fed90dcb56b045d234cda8d7260025
1,812
ex
Elixir
clients/content/lib/google_api/content/v2/model/orderinvoices_create_charge_invoice_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/orderinvoices_create_charge_invoice_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/orderinvoices_create_charge_invoice_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.Content.V2.Model.OrderinvoicesCreateChargeInvoiceResponse do @moduledoc """ ## Attributes * `executionStatus` (*type:* `String.t`, *default:* `nil`) - The status of the execution. Acceptable values are: - "`duplicate`" - "`executed`" * `kind` (*type:* `String.t`, *default:* `content#orderinvoicesCreateChargeInvoiceResponse`) - Identifies what kind of resource this is. Value: the fixed string "content#orderinvoicesCreateChargeInvoiceResponse". """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :executionStatus => String.t(), :kind => String.t() } field(:executionStatus) field(:kind) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.OrderinvoicesCreateChargeInvoiceResponse do def decode(value, options) do GoogleApi.Content.V2.Model.OrderinvoicesCreateChargeInvoiceResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.OrderinvoicesCreateChargeInvoiceResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.555556
216
0.737307
7985ecd04a9e92dd16f4ec2f88e56c616592d64d
4,339
ex
Elixir
lib/oban/migrations.ex
iautom8things/oban
5f1dfc277c2933fdc0dada812dbbca31c6d55fa0
[ "Apache-2.0" ]
null
null
null
lib/oban/migrations.ex
iautom8things/oban
5f1dfc277c2933fdc0dada812dbbca31c6d55fa0
[ "Apache-2.0" ]
null
null
null
lib/oban/migrations.ex
iautom8things/oban
5f1dfc277c2933fdc0dada812dbbca31c6d55fa0
[ "Apache-2.0" ]
null
null
null
defmodule Oban.Migrations do @moduledoc """ Migrations create and modify the database tables Oban needs to funtion. ## Usage To use migrations in your application you'll need to generate an `Ecto.Migration` that wraps calls to `Oban.Migrations`: ```bash mix ecto.gen.migration add_oban ``` Open the generated migration in your editor and call the `up` and `down` functions on `Oban.Migrations`: ```elixir defmodule MyApp.Repo.Migrations.AddOban do use Ecto.Migration def up, do: Oban.Migrations.up() def down, do: Oban.Migrations.down() end ``` This will run all of Oban's versioned migrations for your database. Migrations between versions are idempotent. As new versions are released you may need to run additional migrations. Now, run the migration to create the table: ```bash mix ecto.migrate ``` ## Isolation with Prefixes Oban supports namespacing through PostgreSQL schemas, also called "prefixes" in Ecto. With prefixes your jobs table can reside outside of your primary schema (usually public) and you can have multiple separate job tables. To use a prefix you first have to specify it within your migration: ```elixir defmodule MyApp.Repo.Migrations.AddPrefixedObanJobsTable do use Ecto.Migration def up, do: Oban.Migrations.up(prefix: "private") def down, do: Oban.Migrations.down(prefix: "private") end ``` The migration will create the "private" schema and all tables, functions and triggers within that schema. With the database migrated you'll then specify the prefix in your configuration: ```elixir config :my_app, Oban, prefix: "private", ... ``` """ use Ecto.Migration alias Oban.Repo @initial_version 1 @current_version 10 @default_prefix "public" @doc """ Run the `up` changes for all migrations between the initial version and the current version. ## Example Run all migrations up to the current version: Oban.Migrations.up() Run migrations up to a specified version: Oban.Migrations.up(version: 2) Run migrations in an alternate prefix: Oban.Migrations.up(prefix: "payments") """ def up(opts \\ []) when is_list(opts) do prefix = Keyword.get(opts, :prefix, @default_prefix) version = Keyword.get(opts, :version, @current_version) initial = min(migrated_version(repo(), prefix) + 1, @current_version) if initial < version do change(prefix, initial..version, :up) record_version(prefix, version) end end @doc """ Run the `down` changes for all migrations between the current version and the initial version. ## Example Run all migrations from current version down to the first: Oban.Migrations.down() Run migrations down to a specified version: Oban.Migrations.down(version: 5) Run migrations in an alternate prefix: Oban.Migrations.down(prefix: "payments") """ def down(opts \\ []) when is_list(opts) do prefix = Keyword.get(opts, :prefix, @default_prefix) version = Keyword.get(opts, :version, @initial_version) initial = max(migrated_version(repo(), prefix), @initial_version) if initial >= version do change(prefix, initial..version, :down) record_version(prefix, version - 1) end end @doc false def initial_version, do: @initial_version @doc false def current_version, do: @current_version @doc false def migrated_version(repo, prefix) do query = """ SELECT description FROM pg_class LEFT JOIN pg_description ON pg_description.objoid = pg_class.oid LEFT JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace WHERE pg_class.relname = 'oban_jobs' AND pg_namespace.nspname = '#{prefix}' """ case Repo.query(%{repo: repo, prefix: prefix}, query) do {:ok, %{rows: [[version]]}} when is_binary(version) -> String.to_integer(version) _ -> 0 end end defp change(prefix, range, direction) do for index <- range do pad_idx = String.pad_leading(to_string(index), 2, "0") [__MODULE__, "V#{pad_idx}"] |> Module.concat() |> apply(direction, [prefix]) end end defp record_version(_prefix, 0), do: :ok defp record_version(prefix, version) do execute "COMMENT ON TABLE #{prefix}.oban_jobs IS '#{version}'" end end
25.982036
97
0.694861
7985f064177e0281a5b8200845f337ff9dccd669
399
exs
Elixir
config/config.exs
maxneuvians/maple
9785945c9fce814d7bd63e0c055cc7e71765e322
[ "MIT" ]
24
2017-10-03T17:22:35.000Z
2021-06-09T20:19:43.000Z
config/config.exs
maxneuvians/pique
1f153d98e18cf58736abadf6efa73386eedb077c
[ "MIT" ]
2
2017-11-20T04:17:26.000Z
2018-12-12T23:39:07.000Z
config/config.exs
maxneuvians/pique
1f153d98e18cf58736abadf6efa73386eedb077c
[ "MIT" ]
4
2017-10-29T17:03:08.000Z
2018-08-30T20:57:24.000Z
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. # # This configuration file is loaded before any dependency and # is restricted to this project. use Mix.Config # 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"
36.272727
68
0.789474
7986097ecc394001588305974f9487b35d8c69a3
1,019
ex
Elixir
lib/bex/piece.ex
ckampfe/bex
cfbfdd600e03ebb9ef60c3f2f8cb61b0640455ff
[ "BSD-3-Clause" ]
null
null
null
lib/bex/piece.ex
ckampfe/bex
cfbfdd600e03ebb9ef60c3f2f8cb61b0640455ff
[ "BSD-3-Clause" ]
null
null
null
lib/bex/piece.ex
ckampfe/bex
cfbfdd600e03ebb9ef60c3f2f8cb61b0640455ff
[ "BSD-3-Clause" ]
null
null
null
defmodule Bex.Piece do defstruct [:index, :length] @type t :: %__MODULE__{index: non_neg_integer(), length: pos_integer()} @spec read(t, :file.io_device()) :: {:ok, term} | :eof | {:error, term} def read(%__MODULE__{length: length} = piece, file) do location = byte_location(piece) :file.pread(file, location, length) end @spec write(t, :file.io_device(), binary()) :: :ok | {:error, term} def write(%__MODULE__{} = piece, file, piece_bytes) do location = byte_location(piece) :file.pwrite(file, location, piece_bytes) end @spec verify(t, :file.io_device(), binary()) :: boolean() | {:error, term} def verify(%__MODULE__{} = piece, file, expected_hash) do case read(piece, file) do {:ok, bytes} -> Bex.Torrent.hash(bytes) == expected_hash {:error, _error} = e -> e end end @spec byte_location(t) :: non_neg_integer() def byte_location(%__MODULE__{index: index, length: length} = _piece) when index >= 0 do index * length end end
29.970588
90
0.638862
798613c6255288df67a7c5a1d18ae9ef449c519a
1,477
ex
Elixir
ros/ros_ui_runner/lib/ros_ui_runner_web/endpoint.ex
kujua/elixir-handbook
4185ad8da7f652fdb59c799dc58bcb33fda10475
[ "Apache-2.0" ]
1
2019-07-01T18:47:28.000Z
2019-07-01T18:47:28.000Z
ros/ros_ui_runner/lib/ros_ui_runner_web/endpoint.ex
kujua/elixir-handbook
4185ad8da7f652fdb59c799dc58bcb33fda10475
[ "Apache-2.0" ]
4
2020-07-17T16:57:18.000Z
2021-05-09T23:50:52.000Z
ros/ros_ui_runner/lib/ros_ui_runner_web/endpoint.ex
kujua/elixir-handbook
4185ad8da7f652fdb59c799dc58bcb33fda10475
[ "Apache-2.0" ]
null
null
null
defmodule Ros.RunnerWeb.Endpoint do use Phoenix.Endpoint, otp_app: :ros_ui_runner socket "/socket", Ros.RunnerWeb.UserSocket, websocket: true, longpoll: false # Serve at "/" the static files from "priv/static" directory. # # You should set gzip to true if you are running phx.digest # when deploying your static files in production. plug Plug.Static, at: "/", from: :ros_ui_runner, gzip: false, only: ~w(css fonts images js favicon.ico robots.txt) # Code reloading can be explicitly enabled under the # :code_reloader configuration of your endpoint. if code_reloading? do socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket plug Phoenix.LiveReloader plug Phoenix.CodeReloader end plug Plug.RequestId plug Plug.Logger plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Phoenix.json_library() 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: "_ros_ui_runner_key", signing_salt: "tX2efS+8" plug Ros.RunnerWeb.Router def init(_key, config) do runner_number = System.get_env("RUNNER_NUMBER", "1") config = config |> Keyword.put(:runner_number, runner_number) {:ok, config} end end
26.854545
69
0.701422
7986174ff036219fc2be49db2bc63cf03c2c51c3
762
ex
Elixir
lib/redex/command/mset.ex
esmaeilpour/redex
c2c6e29e3dec0df265fdcd9f24cd2471c8615ee7
[ "Apache-2.0" ]
173
2019-03-15T15:05:11.000Z
2022-01-10T08:21:48.000Z
lib/redex/command/mset.ex
esmaeilpour/redex
c2c6e29e3dec0df265fdcd9f24cd2471c8615ee7
[ "Apache-2.0" ]
null
null
null
lib/redex/command/mset.ex
esmaeilpour/redex
c2c6e29e3dec0df265fdcd9f24cd2471c8615ee7
[ "Apache-2.0" ]
9
2019-07-28T01:20:43.000Z
2021-08-18T03:41:44.000Z
defmodule Redex.Command.MSET do use Redex.Command def exec(pairs = [_, _ | _], state = %State{quorum: quorum, db: db}) do if length(pairs) |> rem(2) != 0 do wrong_arg_error("MSET") else if readonly?(quorum) do {:error, "READONLY You can't write against a read only replica."} else case Mnesia.sync_transaction(fn -> mset(db, pairs) end) do {:atomic, :ok} -> :ok _ -> {:error, "ERR mset operation failed"} end end end |> reply(state) end def exec(_, state), do: wrong_arg_error("MSET") |> reply(state) defp mset(_db, []), do: :ok defp mset(db, [key, value | rest]) do Mnesia.write(:redex, {:redex, {db, key}, value, nil}, :write) mset(db, rest) end end
26.275862
73
0.577428
798625274cda34a8bb99c38d4260a846e2866414
63
ex
Elixir
web/views/coherence/layout_view.ex
bagilevi/uptom
50894abb8f7bd052e12c37155b5c33450abcc9bd
[ "MIT" ]
6
2017-05-12T04:20:09.000Z
2020-11-07T02:00:56.000Z
web/views/coherence/layout_view.ex
bagilevi/uptom
50894abb8f7bd052e12c37155b5c33450abcc9bd
[ "MIT" ]
null
null
null
web/views/coherence/layout_view.ex
bagilevi/uptom
50894abb8f7bd052e12c37155b5c33450abcc9bd
[ "MIT" ]
2
2020-05-18T08:06:22.000Z
2020-12-19T14:24:40.000Z
defmodule Coherence.LayoutView do use Uptom.Web, :view end
10.5
33
0.761905
798626835a2d18b9c8174c980521f36bb0650b92
1,726
ex
Elixir
apps/financial_system_web/lib/financial_system_web.ex
juniornelson123/tech-challenge-stone
e27b767514bf42a5ade5228de56c3c7ea38459d7
[ "MIT" ]
null
null
null
apps/financial_system_web/lib/financial_system_web.ex
juniornelson123/tech-challenge-stone
e27b767514bf42a5ade5228de56c3c7ea38459d7
[ "MIT" ]
2
2021-03-10T03:19:32.000Z
2021-09-02T04:33:17.000Z
apps/financial_system_web/lib/financial_system_web.ex
juniornelson123/tech-challenge-stone
e27b767514bf42a5ade5228de56c3c7ea38459d7
[ "MIT" ]
null
null
null
defmodule FinancialSystemWeb do @moduledoc """ The entrypoint for defining your web interface, such as controllers, views, channels and so on. This can be used in your application as: use FinancialSystemWeb, :controller use FinancialSystemWeb, :view The definitions below will be executed for every view, controller, etc, so keep them short and clean, focused on imports, uses and aliases. Do NOT define functions inside the quoted expressions below. Instead, define any helper function in modules and import those modules here. """ def controller do quote do use Phoenix.Controller, namespace: FinancialSystemWeb import Plug.Conn import FinancialSystemWeb.Gettext alias FinancialSystemWeb.Router.Helpers, as: Routes end end def view do quote do use Phoenix.View, root: "lib/financial_system_web/templates", namespace: FinancialSystemWeb # Import convenience functions from controllers import Phoenix.Controller, only: [get_flash: 1, get_flash: 2, view_module: 1] # Use all HTML functionality (forms, tags, etc) use Phoenix.HTML import FinancialSystemWeb.ErrorHelpers import FinancialSystemWeb.Gettext alias FinancialSystemWeb.Router.Helpers, as: Routes end end def router do quote do use Phoenix.Router import Plug.Conn import Phoenix.Controller end end def channel do quote do use Phoenix.Channel import FinancialSystemWeb.Gettext end end @doc """ When used, dispatch to the appropriate controller/view/etc. """ defmacro __using__(which) when is_atom(which) do apply(__MODULE__, which, []) end end
25.014493
83
0.706837
7986546236b4977a5e4d24c054205784d99d95c9
7,199
ex
Elixir
lib/horde/supervisor.ex
SvenW/horde
6db5b835d188382b2ad6ebe026871bf7558224b2
[ "MIT" ]
null
null
null
lib/horde/supervisor.ex
SvenW/horde
6db5b835d188382b2ad6ebe026871bf7558224b2
[ "MIT" ]
null
null
null
lib/horde/supervisor.ex
SvenW/horde
6db5b835d188382b2ad6ebe026871bf7558224b2
[ "MIT" ]
null
null
null
defmodule Horde.Supervisor do @moduledoc """ A distributed supervisor. Horde.Supervisor implements a distributed DynamicSupervisor backed by a add-wins last-write-wins δ-CRDT (provided by `DeltaCrdt.AWLWWMap`). This CRDT is used for both tracking membership of the cluster and tracking supervised processes. Using CRDTs guarantees that the distributed, shared state will eventually converge. It also means that Horde.Supervisor is eventually-consistent, and is optimized for availability and partition tolerance. This can result in temporary inconsistencies under certain conditions (when cluster membership is changing, for example). Cluster membership is managed with `Horde.Cluster`. Joining a cluster can be done with `Horde.Cluster.set_members/2`. To take a node out of the cluster, call `Horde.Cluster.set_members/2` without that node in the list. Each Horde.Supervisor node wraps its own local instance of `DynamicSupervisor`. `Horde.Supervisor.start_child/2` (for example) delegates to the local instance of DynamicSupervisor to actually start and monitor the child. The child spec is also written into the processes CRDT, along with a reference to the node on which it is running. When there is an update to the processes CRDT, Horde makes a comparison and corrects any inconsistencies (for example, if a conflict has been resolved and there is a process that no longer should be running on its node, it will kill that process and remove it from the local supervisor). So while most functions map 1:1 to the equivalent DynamicSupervisor functions, the eventually consistent nature of Horde requires extra behaviour not present in DynamicSupervisor. ## Divergence from standard DynamicSupervisor behaviour While Horde wraps DynamicSupervisor, it does keep track of processes by the `id` in the child specification. This is a divergence from the behaviour of DynamicSupervisor, which ignores ids altogether. Using DynamicSupervisor is useful for its shutdown behaviour (it shuts down all child processes simultaneously, unlike `Supervisor`). ## Graceful shutdown When a node is stopped (either manually or by calling `:init.stop`), Horde restarts the child processes of the stopped node on another node. The state of child processes is not preserved, they are simply restarted. To implement graceful shutdown of worker processes, a few extra steps are necessary. 1. Trap exits. Running `Process.flag(:trap_exit)` in the `init/1` callback of any `worker` processes will convert exit signals to messages and allow running `terminate/2` callbacks. It is also important to include the `shutdown` option in your child spec (the default is 5000ms). 2. Use `:init.stop()` to shut down your node. How you accomplish this is up to you, but by simply calling `:init.stop()` somewhere, graceful shutdown will be triggered. ## Module-based Supervisor Horde supports module-based supervisors to enable dynamic runtime configuration. ```elixir defmodule MySupervisor do use Horde.Supervisor def init(options) do {:ok, Keyword.put(options, :members, get_members())} end defp get_members() do # ... end end ``` Then you can use `MySupervisor.child_spec/1` and `MySupervisor.start_link/1` in the same way as you'd use `Horde.Supervisor.child_spec/1` and `Horde.Supervisor.start_link/1`. """ defmacro __using__(_opts) do quote do @behaviour Horde.Supervisor def child_spec(options) do options = Keyword.put_new(options, :id, __MODULE__) %{ id: Keyword.get(options, :id, __MODULE__), start: {__MODULE__, :start_link, [options]}, type: :supervisor } end def start_link(options) do Horde.Supervisor.start_link(Keyword.put(options, :init_module, __MODULE__)) end end end @callback init(options()) :: {:ok, options()} @doc """ See `start_link/2` for options. """ @spec child_spec(options :: options()) :: Supervisor.child_spec() def child_spec(options \\ []) do supervisor_options = Keyword.take(options, [ :name, :strategy, :max_restarts, :max_seconds, :max_children, :extra_arguments, :distribution_strategy, :shutdown, :members ]) options = Keyword.take(options, [:id, :restart, :shutdown, :type]) %{ id: Keyword.get(options, :id, __MODULE__), start: {__MODULE__, :start_link, [supervisor_options]}, type: :supervisor, shutdown: Keyword.get(options, :shutdown, :infinity) } |> Supervisor.child_spec(options) end @type options() :: [option()] @type option :: {:name, name :: atom()} | {:strategy, Supervisor.strategy()} | {:max_restarts, integer()} | {:max_seconds, integer()} | {:extra_arguments, [term()]} | {:distribution_strategy, Horde.DistributionStrategy.t()} | {:shutdown, integer()} | {:members, [Horde.Cluster.member()]} @doc """ Works like `DynamicSupervisor.start_link/1`. Extra options are documented here: - `:distribution_strategy`, defaults to `Horde.UniformDistribution` but can also be set to `Horde.UniformQuorumDistribution`. `Horde.UniformQuorumDistribution` enforces a quorum and will shut down all processes on a node if it is split from the rest of the cluster. """ def start_link(options) do root_name = Keyword.get(options, :name, nil) if is_nil(root_name) do raise "must specify :name in options, got: #{inspect(options)}" end options = Keyword.put(options, :root_name, root_name) Supervisor.start_link(Horde.SupervisorSupervisor, options, name: :"#{root_name}.Supervisor") end @doc """ Works like `DynamicSupervisor.stop/3`. """ def stop(supervisor, reason \\ :normal, timeout \\ :infinity), do: Supervisor.stop(:"#{supervisor}.Supervisor", reason, timeout) @doc """ Works like `DynamicSupervisor.start_child/2`. """ def start_child(supervisor, child_spec) do child_spec = Supervisor.child_spec(child_spec, []) call(supervisor, {:start_child, child_spec}) end @doc """ Terminate a child process. Unlike `DynamicSupervisor.terminate_child/2`, this function expects a child_id, and not a pid. """ @spec terminate_child(Supervisor.supervisor(), child_id :: term()) :: :ok | {:error, :not_found} def terminate_child(supervisor, child_id), do: call(supervisor, {:terminate_child, child_id}) @doc """ Works like `DynamicSupervisor.which_children/1`. This function delegates to all supervisors in the cluster and returns the aggregated output. Where memory warnings apply to `DynamicSupervisor.which_children`, these count double for `Horde.Supervisor.which_children`. """ def which_children(supervisor), do: call(supervisor, :which_children) @doc """ Works like `DynamicSupervisor.count_children/1`. This function delegates to all supervisors in the cluster and returns the aggregated output. """ def count_children(supervisor), do: call(supervisor, :count_children) defp call(supervisor, msg), do: GenServer.call(supervisor, msg, :infinity) end
43.896341
805
0.718572
7986767aab2fbca9ec708d8b02e8c7157a842230
1,970
ex
Elixir
lib/chat_api/accounts.ex
primeithard/livachat
b338467d3205ba2afc49a31af2fc1438f75aab47
[ "MIT" ]
null
null
null
lib/chat_api/accounts.ex
primeithard/livachat
b338467d3205ba2afc49a31af2fc1438f75aab47
[ "MIT" ]
null
null
null
lib/chat_api/accounts.ex
primeithard/livachat
b338467d3205ba2afc49a31af2fc1438f75aab47
[ "MIT" ]
null
null
null
defmodule ChatApi.Accounts do @moduledoc """ The Accounts context. """ import Ecto.Query, warn: false alias ChatApi.Repo alias ChatApi.Accounts.Account @doc """ Returns the list of accounts. ## Examples iex> list_accounts() [%Account{}, ...] """ def list_accounts do Repo.all(Account) end @spec get_account!(any) :: nil | [%{optional(atom) => any}] | %{optional(atom) => any} @doc """ Gets a single account. Raises `Ecto.NoResultsError` if the Account does not exist. ## Examples iex> get_account!(123) %Account{} iex> get_account!(456) ** (Ecto.NoResultsError) """ def get_account!(id) do Account |> Repo.get!(id) |> Repo.preload([:users, :widget_settings]) end @doc """ Creates a account. ## Examples iex> create_account(%{field: value}) {:ok, %Account{}} iex> create_account(%{field: bad_value}) {:error, %Ecto.Changeset{}} """ def create_account(attrs \\ %{}) do %Account{} |> Account.changeset(attrs) |> Repo.insert() end @doc """ Updates a account. ## Examples iex> update_account(account, %{field: new_value}) {:ok, %Account{}} iex> update_account(account, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ def update_account(%Account{} = account, attrs) do account |> Account.changeset(attrs) |> Repo.update() end @doc """ Deletes a account. ## Examples iex> delete_account(account) {:ok, %Account{}} iex> delete_account(account) {:error, %Ecto.Changeset{}} """ def delete_account(%Account{} = account) do Repo.delete(account) end @doc """ Returns an `%Ecto.Changeset{}` for tracking account changes. ## Examples iex> change_account(account) %Ecto.Changeset{data: %Account{}} """ def change_account(%Account{} = account, attrs \\ %{}) do Account.changeset(account, attrs) end end
18.240741
88
0.601015
7986816748257f4fd6e5dc78efbc66bb599868de
473
ex
Elixir
lib/probe/supervisor.ex
atlas-forks/instruments
9df31ecf5388916fbd7a5ebb331ebac371df3e9d
[ "MIT" ]
null
null
null
lib/probe/supervisor.ex
atlas-forks/instruments
9df31ecf5388916fbd7a5ebb331ebac371df3e9d
[ "MIT" ]
null
null
null
lib/probe/supervisor.ex
atlas-forks/instruments
9df31ecf5388916fbd7a5ebb331ebac371df3e9d
[ "MIT" ]
null
null
null
defmodule Instruments.Probe.Supervisor do @moduledoc false use Supervisor def start_link do Supervisor.start_link(__MODULE__, [], name: __MODULE__) end def init([]) do children = [ worker(Instruments.Probe.Runner, []) ] supervise(children, strategy: :simple_one_for_one, name: __MODULE__) end def start_probe(name, type, options, probe_module) do Supervisor.start_child(__MODULE__, [name, type, options, probe_module]) end end
22.52381
75
0.714588
79869ffc840d5483bdd176a6d9ce1b8319bee020
1,113
exs
Elixir
test/ex_firebase/auth/auth_test.exs
alfietham/ex_firebase
f8f6666db003940138b8fe79e1c5be4a6e580de1
[ "MIT" ]
6
2019-03-23T10:18:13.000Z
2021-12-30T15:15:15.000Z
test/ex_firebase/auth/auth_test.exs
alfietham/ex_firebase
f8f6666db003940138b8fe79e1c5be4a6e580de1
[ "MIT" ]
null
null
null
test/ex_firebase/auth/auth_test.exs
alfietham/ex_firebase
f8f6666db003940138b8fe79e1c5be4a6e580de1
[ "MIT" ]
3
2019-05-16T01:32:20.000Z
2021-12-30T16:02:30.000Z
defmodule ExFirebase.AuthTest do use ExUnit.Case alias ExFirebase.{Auth, Error} @public_keys File.cwd!() |> Path.join("/test/fixtures/public-keys.json") |> File.read!() |> Poison.decode!() test "access_token/0 returns cached access token" do assert {:ok, _access_token} = Auth.access_token() end test "get_access_token/0 fetches new access token" do assert {:ok, %HTTPoison.Response{body: %{"access_token" => _}, status_code: 200}} = Auth.get_access_token() end test "public_keys/0 returns cached public keys" do assert @public_keys = Auth.public_keys() end test "get_public_keys/0 fetches new public keys" do assert {:ok, %HTTPoison.Response{body: @public_keys}} = Auth.get_public_keys() end test "get_public_key/1 returns a key if it exists" do {key_id, key} = Enum.at(@public_keys, 0) assert {:ok, ^key} = Auth.get_public_key(key_id) end test "get_public_key/1 returns error if key does not exist" do assert {:error, %Error{reason: :not_found}} = Auth.get_public_key("invalid") end end
30.081081
87
0.667565
7986a99f671617b9306e73364d2b726e8ae0d608
1,290
exs
Elixir
elixir/tour/mix_and_otp/kv_umbrella/apps/kv_server/test/kv_server_test.exs
supeterlau/bedev
c134875eae37d265936199fda278416e2a3c1224
[ "MIT" ]
null
null
null
elixir/tour/mix_and_otp/kv_umbrella/apps/kv_server/test/kv_server_test.exs
supeterlau/bedev
c134875eae37d265936199fda278416e2a3c1224
[ "MIT" ]
null
null
null
elixir/tour/mix_and_otp/kv_umbrella/apps/kv_server/test/kv_server_test.exs
supeterlau/bedev
c134875eae37d265936199fda278416e2a3c1224
[ "MIT" ]
null
null
null
defmodule KVServerTest do use ExUnit.Case # doctest KVServer @moduletag :capture_log setup do Application.stop(:kv) :ok = Application.start(:kv) end setup do opts = [:binary, packet: :line, active: false] {:ok, socket} = :gen_tcp.connect('localhost', 4040, opts) %{socket: socket} end test "server interaction", %{socket: socket} do assert send_and_recv(socket, "UNKNOWN shopping\r\n") == "UNKNOWN COMMAND\r\n" assert send_and_recv(socket, "GET shopping eggs\r\n") == "NOT FOUND\r\n" assert send_and_recv(socket, "CREATE shopping\r\n") == "OK\r\n" assert send_and_recv(socket, "PUT shopping eggs 3\r\n") == "OK\r\n" # GET 返回两行 assert send_and_recv(socket, "GET shopping eggs\r\n") == "3\r\n" assert send_and_recv(socket, "") == "OK\r\n" assert send_and_recv(socket, "DELETE shopping eggs\r\n") == "OK\r\n" assert send_and_recv(socket, "GET shopping eggs\r\n") == "\r\n" assert send_and_recv(socket, "") == "OK\r\n" end defp send_and_recv(socket, command) do :ok = :gen_tcp.send(socket, command) # {:ok, data} = :gen_tcp.recv(socket, 0, 1000) # tweak {:ok, data} = :gen_tcp.recv(socket, 0) data end test "greets the world" do assert KVServer.hello() == :world end end
25.8
81
0.639535
7986b756afd9e46afaa5213975bd9b43eda6ff16
360
ex
Elixir
lib/hologram/compiler/pattern_deconstructor/map_type.ex
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
40
2022-01-19T20:27:36.000Z
2022-03-31T18:17:41.000Z
lib/hologram/compiler/pattern_deconstructor/map_type.ex
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
42
2022-02-03T22:52:43.000Z
2022-03-26T20:57:32.000Z
lib/hologram/compiler/pattern_deconstructor/map_type.ex
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
3
2022-02-10T04:00:37.000Z
2022-03-08T22:07:45.000Z
alias Hologram.Compiler.IR.MapAccess alias Hologram.Compiler.IR.MapType alias Hologram.Compiler.PatternDeconstructor defimpl PatternDeconstructor, for: MapType do def deconstruct(%{data: data}, path) do Enum.reduce(data, [], fn {key, value}, acc -> acc ++ PatternDeconstructor.deconstruct(value, path ++ [%MapAccess{key: key}]) end) end end
30
84
0.733333
7986bb33a30c997aac59e2c8911a820530ad711b
470
ex
Elixir
lib/sanbase_web/admin/coinmarketcap/schedule_rescrape_price.ex
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
81
2017-11-20T01:20:22.000Z
2022-03-05T12:04:25.000Z
lib/sanbase_web/admin/coinmarketcap/schedule_rescrape_price.ex
rmoorman/sanbase2
226784ab43a24219e7332c49156b198d09a6dd85
[ "MIT" ]
359
2017-10-15T14:40:53.000Z
2022-01-25T13:34:20.000Z
lib/sanbase_web/admin/coinmarketcap/schedule_rescrape_price.ex
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
16
2017-11-19T13:57:40.000Z
2022-02-07T08:13:02.000Z
defmodule SanbaseWeb.ExAdmin.ScheduleRescrapePrice do use ExAdmin.Register register_resource Sanbase.ExternalServices.Coinmarketcap.ScheduleRescrapePrice do form srp do inputs do input(srp, :from, type: NaiveDateTime) input(srp, :to, type: NaiveDateTime) input( srp, :project, collection: from(p in Sanbase.Model.Project, order_by: p.name) |> Sanbase.Repo.all() ) end end end end
24.736842
94
0.651064
7986d86bde62b75d3c3225fb30f825b596f6a4e4
512
exs
Elixir
programming/elixir/hello-world-elixir-web-app-in-3-variants/variant-2-plug/mix.exs
NomikOS/learning
268f94605214f6861ef476ca7573e68c068ccbe5
[ "Unlicense" ]
null
null
null
programming/elixir/hello-world-elixir-web-app-in-3-variants/variant-2-plug/mix.exs
NomikOS/learning
268f94605214f6861ef476ca7573e68c068ccbe5
[ "Unlicense" ]
null
null
null
programming/elixir/hello-world-elixir-web-app-in-3-variants/variant-2-plug/mix.exs
NomikOS/learning
268f94605214f6861ef476ca7573e68c068ccbe5
[ "Unlicense" ]
null
null
null
defmodule HelloWorld.Mixfile do use Mix.Project def project do [app: :hello_world, version: "0.1.0", elixir: "~> 1.3", deps: deps()] end def application do [ mod: {HelloWorld, []}, applications: applications(Mix.env) ] end defp applications(:dev), do: applications(:all) ++ [:remix] defp applications(_), do: [:cowboy, :plug] defp deps do [ {:cowboy, "~> 1.0.0"}, {:plug, "~> 1.0"}, {:remix, "~> 0.0.1", only: :dev} ] end end
18.285714
61
0.535156
79871c89705fe49d69132bf619e5554dae892aff
56,932
ex
Elixir
lib/mix/lib/mix/tasks/release.ex
btkostner/elixir
cc2289806b3839f79a5c9ee42d138c1faa7fc0a6
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/tasks/release.ex
btkostner/elixir
cc2289806b3839f79a5c9ee42d138c1faa7fc0a6
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/tasks/release.ex
btkostner/elixir
cc2289806b3839f79a5c9ee42d138c1faa7fc0a6
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Tasks.Release do use Mix.Task @shortdoc "Assembles a self-contained release" @moduledoc """ Assembles a self-contained release for the current project: MIX_ENV=prod mix release MIX_ENV=prod mix release NAME Once a release is assembled, it can be packaged and deployed to a target, as long as the target runs on the same operating system (OS) distribution and version as the machine running the `mix release` command. A release can be configured in your `mix.exs` file under the `:releases` key inside `def project`: def project do [ releases: [ demo: [ include_executables_for: [:unix], applications: [runtime_tools: :permanent] ], ... ] ] end You can specify multiple releases where the key is the release name and the value is a keyword list with the release configuration. Releasing a certain name is done with: MIX_ENV=prod mix release demo If the given name does not exist, an error is raised. If `mix release`, without a name, is invoked and there are multiple names, an error will be raised unless you set `default_release: NAME` at the root of your project configuration. If `mix release` is invoked and there are no names, a release using the application name and default values is assembled. ## Why releases? Releases allow developers to precompile and package all of their code and the runtime into a single unit. The benefits of releases are: * Code preloading. The VM has two mechanisms for loading code: interactive and embedded. By default, it runs in the interactive mode which dynamically loads modules when they are used for the first time. The first time your application calls `Enum.map/2`, the VM will find the `Enum` module and load it. There’s a downside. When you start a new server in production, it may need to load many other modules, causing the first requests to have an unusual spike in response time. When running in Erlang/OTP earlier than 23, the system always runs in embedded mode. When using Erlang/OTP 23+, they run in interactive mode while being configured and then it swaps to embedded mode, guaranteeing your system is ready to handle requests after booting. * Configuration and customization. Releases give developers fine grained control over system configuration and the VM flags used to start the system. * Self-contained. A release does not require the source code to be included in your production artifacts. All of the code is precompiled and packaged. Releases do not even require Erlang or Elixir in your servers, as it includes the Erlang VM and its runtime by default. Furthermore, both Erlang and Elixir standard libraries are stripped to bring only the parts you are actually using. * Multiple releases. You can assemble different releases with different configuration per application or even with different applications altogether. * Management scripts. Releases come with scripts to start, restart, connect to the running system remotely, execute RPC calls, run as daemon, run as a Windows service, and more. ## Running the release Once a release is assembled, you can start it by calling `bin/RELEASE_NAME start` inside the release. In production, you would do: MIX_ENV=prod mix release _build/prod/rel/my_app/bin/my_app start `bin/my_app start` will start the system connected to the current standard input/output, where logs are also written to by default. This is the preferred way to run the system. Many tools, such as `systemd`, platforms as a service, such as Heroku, and many containers platforms, such as Docker, are capable of processing the standard input/output and redirecting the log contents elsewhere. Those tools and platforms also take care of restarting the system in case it crashes. You can also execute one-off commands, run the release as a daemon on Unix-like system, or install it as a service on Windows. We will take a look at those next. You can also list all available commands by invoking `bin/RELEASE_NAME`. ### One-off commands (eval and rpc) If you want to invoke specific modules and functions in your release, you can do so in two ways: using `eval` or `rpc`. bin/RELEASE_NAME eval "IO.puts(:hello)" bin/RELEASE_NAME rpc "IO.puts(:hello)" The `eval` command starts its own instance of the VM but without starting any of the applications in the release and without starting distribution. For example, if you need to do some prep work before running the actual system, like migrating your database, `eval` can be a good fit. Just keep in mind any application you may use during eval has to be explicitly loaded and/or started. You can start an application by calling `Application.ensure_all_started/1`. However, if for some reason you cannot start an application, maybe because it will run other services you do not want, you must at least load the application by calling `Application.load/1`. If you don't load the application, any attempt at reading its environment or configuration may fail. Note that if you start an application, it is automatically loaded before started. Another way to run commands is with `rpc`, which will connect to the system currently running and instruct it to execute the given expression. This means you need to guarantee the system was already started and be careful with the instructions you are executing. You can also use `remote` to connect a remote IEx session to the system. #### Helper module As you operate your system, you may find yourself running some piece of code as a one-off command quite often. You may consider creating a module to group these tasks: # lib/my_app/release_tasks.ex defmodule MyApp.ReleaseTasks do def eval_purge_stale_data() do # Eval commands needs to start the app before # Or Application.load(:my_app) if you can't start it Application.ensure_all_started(:my_app) # Code that purges stale data ... end def rpc_print_connected_users() do # Code that print users connected to the current running system ... end end In the example above, we prefixed the function names with the command name used to execute them, but that is entirely optional. And to run them: bin/RELEASE_NAME eval "MyApp.ReleaseTasks.eval_purge_stale_data()" bin/RELEASE_NAME rpc "MyApp.ReleaseTasks.rpc_print_connected_users()" ### Daemon mode (Unix-like) You can run the release in daemon mode with the command: bin/RELEASE_NAME daemon In daemon mode, the system is started on the background via [run_erl](http://erlang.org/doc/man/run_erl.html). You may also want to enable [heart](http://erlang.org/doc/man/heart.html) in daemon mode so it automatically restarts the system in case of crashes. See the generated `releases/RELEASE_VSN/env.sh` file. The daemon will write all of its standard output to the "tmp/log/" directory in the release root. You can watch the log file by doing `tail -f tmp/log/erlang.log.1` or similar. Once files get too large, the index suffix will be incremented. A developer can also attach to the standard input of the daemon by invoking "to_erl tmp/pipe/" from the release root. However, note that attaching to the system should be done with extreme care, since the usual commands for exiting an Elixir system, such as hitting Ctrl+C twice or Ctrl+\\, will actually shut down the daemon. Therefore, using `bin/RELEASE_NAME remote` should be preferred, even in daemon mode. You can customize the tmp directory used both for logging and for piping in daemon mode by setting the `RELEASE_TMP` environment variable. See the "Customization" section. ### Services mode (Windows) While daemons are not available on Windows, it is possible to install a released system as a service on Windows with the help of [erlsrv](http://erlang.org/doc/man/erlsrv.html). This can be done by running: bin/RELEASE_NAME install Once installed, the service must be explicitly managed via the `erlsrv` executable, which is included in the `erts-VSN/bin` directory. The service is not started automatically after installing. For example, if you have a release named `demo`, you can install the service and then start it from the release root as follows: bin/demo install erts-VSN/bin/erlsrv.exs start demo_demo The name of the service is `demo_demo` because the name is built by concatenating the node name with the release name. Since Elixir automatically uses the same name for both, the service will be referenced as `demo_demo`. The `install` command must be executed as an administrator. ### `bin/RELEASE_NAME` commands The following commands are supported by `bin/RELEASE_NAME`: start Starts the system start_iex Starts the system with IEx attached daemon Starts the system as a daemon (Unix-like only) daemon_iex Starts the system as a daemon with IEx attached (Unix-like only) install Installs this system as a Windows service (Windows only) eval "EXPR" Executes the given expression on a new, non-booted system rpc "EXPR" Executes the given expression remotely on the running system remote Connects to the running system via a remote shell restart Restarts the running system via a remote command stop Stops the running system via a remote command pid Prints the operating system PID of the running system via a remote command version Prints the release name and version to be booted ## Deployments ### Requirements A release is built on a **host**, a machine which contains Erlang, Elixir, and any other dependencies needed to compile your application. A release is then deployed to a **target**, potentially the same machine as the host, but usually separate, and often there are many targets (either multiple instances, or the release is deployed to heterogeneous environments). To deploy straight from a host to a separate target without cross-compilation, the following must be the same between the host and the target: * Target architecture (for example, x86_64 or ARM) * Target vendor + operating system (for example, Windows, Linux, or Darwin/macOS) * Target ABI (for example, musl or gnu) This is often represented in the form of target triples, for example, `x86_64-unknown-linux-gnu`, `x86_64-unknown-linux-musl`, `x86_64-apple-darwin`. So to be more precise, to deploy straight from a host to a separate target, the Erlang Runtime System (ERTS), and any native dependencies (NIFs), must be compiled for the same target triple. If you are building on a MacBook (`x86_64-apple-darwin`) and trying to deploy to a typical Ubuntu machine (`x86_64-unknown-linux-gnu`), the release will not work. Instead you should build the release on a `x86_64-unknown-linux-gnu` host. As we will see, this can be done in multiple ways, such as releasing on the target itself, or by using virtual machines or containers, usually as part of your release pipeline. In addition to matching the target triple, it is also important that the target has all of the system packages that your application will need at runtime. A common one is the need for OpenSSL when building an application that uses `:crypto` or `:ssl`, which is dynamically linked to ERTS. The other common source for native dependencies like this comes from dependencies containing NIFs (natively-implemented functions) which may expect to dynamically link to libraries they use. Of course, some operating systems and package managers can differ between versions, so if your goal is to have full compatibility between host and target, it is best to ensure the operating system and system package manager have the same versions on host and target. This may even be a requirement in some systems, especially so with package managers that try to create fully reproducible environments (Nix, Guix). Similarly, when creating a stand-alone package and release for Windows, note the Erlang Runtime System has a dependency to some Microsoft libraries (Visual C++ Redistributable Packages for Visual Studio 2013). These libraries are installed (if not present before) when Erlang is installed but it is not part of the standard Windows environment. Deploying a stand-alone release on a computer without these libraries will result in a failure when trying to run the release. One way to solve this is to download and install these Microsoft libraries the first time a release is deployed (the Erlang installer version 10.6 ships with “Microsoft Visual C++ 2013 Redistributable - 12.0.30501”). Alternatively, you can also bundle the compiled object files in the release, as long as they were compiled for the same target. If doing so, you need to update `LD_LIBRARY_PATH` environment variable with the paths containing the bundled objects on Unix-like systems or the `PATH` environment variable on Windows systems. Currently, there is no official way to cross-compile a release from one target triple to another, due to the complexities involved in the process. ### Techniques There are a couple of ways to guarantee that a release is built on a host with the same properties as the target. A simple option is to fetch the source, compile the code and assemble the release on the target itself. It would be something like this: git clone remote://path/to/my_app.git my_app_source cd my_app_source mix deps.get --only prod MIX_ENV=prod mix release _build/prod/rel/my_app/bin/my_app start If you prefer, you can also compile the release to a separate directory, so you can erase all source after the release is assembled: git clone remote://path/to/my_app.git my_app_source cd my_app_source mix deps.get --only prod MIX_ENV=prod mix release --path ../my_app_release cd ../my_app_release rm -rf ../my_app_source bin/my_app start However, this option can be expensive if you have multiple production nodes or if the release assembling process is a long one, as each node needs to individually assemble the release. You can automate this process in a couple different ways. One option is to make it part of your Continuous Integration (CI) / Continuous Deployment (CD) pipeline. When you have a CI/CD pipeline, it is common that the machines in your CI/CD pipeline run on the exact same target triple as your production servers (if they don't, they should). In this case, you can assemble the release at the end of your CI/CD pipeline by calling `MIX_ENV=prod mix release` and push the artifact to S3 or any other network storage. To perform the deployment, your production machines can fetch the deployment from the network storage and run `bin/my_app start`. Another mechanism to automate deployments is to use images, such as Amazon Machine Images, or container platforms, such as Docker. For instance, you can use Docker to run locally a system with the exact same target triple as your production servers. Inside the container, you can invoke `MIX_ENV=prod mix release` and build a complete image and/or container with the operating system, all dependencies as well as the releases. In other words, there are multiple ways systems can be deployed and releases can be automated and incorporated into all of them as long as you remember to build the system in the same target triple. Once a system is deployed, shutting down the system can be done by sending SIGINT/SIGTERM to the system, which is what most containers, platforms and tools do, or by explicitly invoking `bin/RELEASE_NAME stop`. Once the system receives the shutdown request, each application and their respective supervision trees will stop, one by one, in the opposite order that they were started. ## Customization There are a couple ways in which developers can customize the generated artifacts inside a release. ### Options The following options can be set inside your `mix.exs` on each release definition: * `:applications` - a keyword list that configures and adds new applications to the release. The key is the application name and the value is one of: * `:permanent` - the application is started and the node shuts down if the application terminates, regardless of reason * `:transient` - the application is started and the node shuts down if the application terminates abnormally * `:temporary` - the application is started and the node does not shut down if the application terminates * `:load` - the application is only loaded * `:none` - the application is part of the release but it is neither loaded nor started All applications default to `:permanent`. By default `:applications` includes the current application and all applications the current application depends on, recursively. You can include new applications or change the mode of existing ones by listing them here. The order of the applications given in `:applications` will be preserved as much as possible, with only `:kernel`, `:stdlib`, `:sasl`, and `:elixir` listed before the given application list. Releases assembled from an umbrella project require this configuration to be explicitly given. * `:strip_beams` - controls if BEAM files should have their debug information, documentation chunks, and other non-essential metadata removed. Defaults to `true`. May be set to `false` to disable stripping. Also accepts `[keep: ["Docs", "Dbgi"]]` to keep certain chunks that are usually stripped. * `:cookie` - a string representing the Erlang Distribution cookie. If this option is not set, a random cookie is written to the `releases/COOKIE` file when the first release is assembled. At runtime, we will first attempt to fetch the cookie from the `RELEASE_COOKIE` environment variable and then we'll read the `releases/COOKIE` file. If you are setting this option manually, we recommend the cookie option to be a long and randomly generated string, such as: `Base.url_encode64(:crypto.strong_rand_bytes(40))`. We also recommend to restrict the characters in the cookie to the subset returned by `Base.url_encode64/1`. * `:validate_compile_env` - by default a release will match all runtime configuration against any configuration that was marked at compile time in your application of its dependencies via the `Application.compile_env/3` function. If there is a mismatch between those, it means your system is misconfigured and unable to boot. You can disable this check by setting this option to false. * `:path` - the path the release should be installed to. Defaults to `"_build/MIX_ENV/rel/RELEASE_NAME"`. * `:version` - the release version as a string or `{:from_app, app_name}`. Defaults to the current application version. The `{:from_app, app_name}` format can be used to easily reference the application version from another application. This is particularly useful in umbrella applications. * `:quiet` - a boolean that controls if releases should write steps to the standard output. Defaults to `false`. * `:include_erts` - a boolean, string, or anonymous function of arity zero. If a boolean, it indicates whether the Erlang Runtime System (ERTS), which includes the Erlang VM, should be included in the release. The default is `true`, which is also the recommended value. If a string, it represents the path to an existing ERTS installation. If an anonymous function of arity zero, it's a function that returns any of the above (boolean or string). You may also set this option to `false` if you desire to use the ERTS version installed on the target. Note, however, that the ERTS version on the target must have **the exact version** as the ERTS version used when the release is assembled. Setting it to `false` also disables hot code upgrades. Therefore, `:include_erts` should be set to `false` with caution and only if you are assembling the release on the same server that runs it. * `:include_executables_for` - a list of atoms detailing for which Operating Systems executable files should be generated for. By default, it is set to `[:unix, :windows]`. You can customize those as follows: releases: [ demo: [ include_executables_for: [:unix] # Or [:windows] or [] ] ] * `:rel_templates_path` - the path to find template files that are copied to the release, such as "vm.args.eex", "env.sh.eex" (or "env.bat.eex"), and "overlays". Defaults to "rel" in the project root. * `:overlays` - a list of directories with extra files to be copied as is to the release. The "overlays" directory at `:rel_templates_path` is always included in this list by default (typically at "rel/overlays"). See the "Overlays" section for more information. * `:steps` - a list of steps to execute when assembling the release. See the "Steps" section for more information. Note each release definition can be given as an anonymous function. This is useful if some release attributes are expensive to compute: releases: [ demo: fn -> [version: @version <> "+" <> git_ref()] end ] Besides the options above, it is possible to customize the generated release with custom files, by tweaking the release steps or by running custom options and commands on boot. We will detail both approaches next. ### Overlays Often it is necessary to copy extra files to the release root after the release is assembled. This can be easily done by placing such files in the `rel/overlays` directory. Any file in there is copied as is to the release root. For example, if you have placed a "rel/overlays/Dockerfile" file, the "Dockerfile" will be copied as is to the release root. If you want to specify extra overlay directories, you can do so with the `:overlays` option. If you need to copy files dynamically, see the "Steps" section. ### Steps It is possible to add one or more steps before and after the release is assembled. This can be done with the `:steps` option: releases: [ demo: [ steps: [&set_configs/1, :assemble, &copy_extra_files/1] ] ] The `:steps` option must be a list and it must always include the atom `:assemble`, which does most of the release assembling. You can pass anonymous functions before and after the `:assemble` to customize your release assembling pipeline. Those anonymous functions will receive a `Mix.Release` struct and must return the same or an updated `Mix.Release` struct. It is also possible to build a tarball of the release by passing the `:tar` step anywhere after `:assemble`. If the release `:path` is not configured, the tarball is created in `_build/MIX_ENV/RELEASE_NAME-RELEASE_VSN.tar.gz` Otherwise it is created inside the configured `:path`. See `Mix.Release` for more documentation on the struct and which fields can be modified. Note that the `:steps` field itself can be modified and it is updated every time a step is called. Therefore, if you need to execute a command before and after assembling the release, you only need to declare the first steps in your pipeline and then inject the last step into the release struct. The steps field can also be used to verify if the step was set before or after assembling the release. ### vm.args and env.sh (env.bat) Developers may want to customize the VM flags and environment variables given when the release starts. This is typically done by customizing two files inside your release: `releases/RELEASE_VSN/vm.args` and `releases/RELEASE_VSN/env.sh` (or `env.bat` on Windows). However, instead of modifying those files after the release is built, the simplest way to customize those files is by running `mix release.init`. The Mix task will copy custom `rel/vm.args.eex`, `rel/env.sh.eex`, and `rel/env.bat.eex` files to your project root. You can modify those files and they will be evaluated every time you perform a new release. Those files are regular EEx templates and they have a single assign, called `@release`, with the `Mix.Release` struct. The `vm.args` file may contain any of the VM flags accepted by the [`erl` command](http://erlang.org/doc/man/erl.html). The `env.sh` and `env.bat` is used to set environment variables. In there, you can set vars such as `RELEASE_NODE`, `RELEASE_COOKIE`, and `RELEASE_TMP` to customize your node name, cookie and tmp directory respectively. Whenever `env.sh` or `env.bat` is invoked, the variables `RELEASE_ROOT`, `RELEASE_NAME`, `RELEASE_VSN`, and `RELEASE_COMMAND` have already been set, so you can rely on them. See the section on environment variables for more information. Furthermore, while `vm.args` is static, you can use `env.sh` and `env.bat` to dynamically set VM options. For example, if you want to make sure the Erlang Distribution listens only on a given port known at runtime, you can set the following: case $RELEASE_COMMAND in start*|daemon*) ELIXIR_ERL_OPTIONS="-kernel inet_dist_listen_min $BEAM_PORT inet_dist_listen_max $BEAM_PORT" export ELIXIR_ERL_OPTIONS ;; *) ;; esac Note we only set the port on start/daemon commands. If you also limit the port on other commands, such as `rpc`, then you will be unable to establish a remote connection as the port will already be in use by the node. On Windows, your `env.bat` would look like this: IF NOT %RELEASE_COMMAND:start=%==%RELEASE_COMMAND% ( set ELIXIR_ERL_OPTIONS="-kernel inet_dist_listen_min %BEAM_PORT% inet_dist_listen_max %BEAM_PORT%" ) ## Application configuration Releases provides two mechanisms for configuring OTP applications: build-time and runtime. ### Build-time configuration Whenever you invoke a `mix` command, Mix loads the configuration in `config/config.exs`, if said file exists. It is common for the `config/config.exs` file itself to import other configuration based on the current `MIX_ENV`, such as `config/dev.exs`, `config/test.exs`, and `config/prod.exs`. We say that this configuration is a build-time configuration as it is evaluated whenever you compile your code or whenever you assemble the release. In other words, if your configuration does something like: config :my_app, :secret_key, System.fetch_env!("MY_APP_SECRET_KEY") The `:secret_key` key under `:my_app` will be computed on the host machine, whenever the release is built. Setting the `MY_APP_SECRET_KEY` right before starting your release will have no effect. Luckily, releases also provide runtime configuration, which we will see next. ### Runtime configuration To enable runtime configuration in your release, all you need to do is to create a file named `config/runtime.exs`: import Config config :my_app, :secret_key, System.fetch_env!("MY_APP_SECRET_KEY") This file will be executed whenever your Mix project or your release starts. Your `config/runtime.exs` file needs to follow three important rules: * It MUST `import Config` at the top instead of the deprecated `use Mix.Config` * It MUST NOT import any other configuration file via `import_config` * It MUST NOT access `Mix` in any way, as `Mix` is a build tool and it is not available inside releases If a `config/runtime.exs` exists, it will be copied to your release and executed early in the boot process, when only Elixir and Erlang's main applications have been started. Once the configuration is loaded, the Erlang system will be restarted (within the same Operating System process) and the new configuration will take place. You can change the path to the runtime configuration file by setting `:runtime_config_path` inside each release configuration. This path is resolved at build time as the given configuration file is always copied to inside the release: releases: [ demo: [ runtime_config_path: ... ] ] Finally, in order for runtime configuration to work properly (as well as any other "Config provider" as defined next), it needs to be able to persist the newly computed configuration to disk. The computed config file will be written to "tmp" directory inside the release every time the system boots. You can configure the "tmp" directory by setting the `RELEASE_TMP` environment variable, either explicitly or inside your `releases/RELEASE_VSN/env.sh` (or `env.bat` on Windows). ### Config providers Releases also supports custom mechanisms, called config providers, to load any sort of runtime configuration to the system while it boots. For instance, if you need to access a vault or load configuration from a JSON file, it can be achieved with config providers. The runtime configuration outlined in the previous section, which is handled by the `Config.Reader` provider. See the `Config.Provider` module for more information and more examples. The following options can be set inside your releases key in your `mix.exs` to control how config providers work: * `:reboot_system_after_config` - every time your release is configured, the system is rebooted to allow the new configuration to take place. You can set this option to `false` to disable the rebooting for applications that are sensitive to boot time but, in doing so, note you won't be able to configure system applications, such as `:kernel` and `:stdlib`. Defaults to `true` if using the deprecated `config/releases.exs`, `false` otherwise. * `:prune_runtime_sys_config_after_boot` - if `:reboot_system_after_config` is set, every time your system boots, the release will write a config file to your tmp directory. These configuration files are generally small. But if you are concerned with disk space or if you have other restrictions, you can ask the system to remove said config files after boot. The downside is that you will no longer be able to restart the system internally (neither via `System.restart/0` nor `bin/RELEASE_NAME restart`). If you need a restart, you will have to terminate the Operating System process and start a new one. Defaults to `false`. * `:start_distribution_during_config` - if `:reboot_system_after_config` is set, releases only start the Erlang VM distribution features after the config files are evaluated. You can set it to `true` if you need distribution during configuration. Defaults to `false` from Erlang/OTP 22+. * `:config_providers` - a list of tuples with custom config providers. See `Config.Provider` for more information. Defaults to `[]`. ### Customization and configuration summary Generally speaking, the following files are available for customizing and configuring the running system: * `config/config.exs` (and `config/prod.exs`) - provides build-time application configuration, which are executed when the release is assembled * `config/runtime.exs` - provides runtime application configuration. It is executed every time your Mix project or your release boots and is further extensible via config providers. If you want to detect you are inside a release, you can check for release specific environment variables, such as `RELEASE_NODE` or `RELEASE_MODE` * `rel/vm.args.eex` - a template file that is copied into every release and provides static configuration of the Erlang Virtual Machine and other runtime flags * `rel/env.sh.eex` and `rel/env.bat.eex` - template files that are copied into every release and are executed on every command to set up environment variables, including specific ones to the VM, and the general environment ## Directory structure A release is organized as follows: bin/ RELEASE_NAME erts-ERTS_VSN/ lib/ APP_NAME-APP_VSN/ ebin/ include/ priv/ releases/ RELEASE_VSN/ consolidated/ elixir elixir.bat env.bat env.sh iex iex.bat runtime.exs start.boot start.script start_clean.boot start_clean.script sys.config vm.args COOKIE start_erl.data tmp/ ## Environment variables The system sets different environment variables. The following variables are set early on and can only be read by `env.sh` and `env.bat`: * `RELEASE_ROOT` - points to the root of the release. If the system includes ERTS, then it is the same as `:code.root_dir/0`. This variable is always computed and it cannot be set to a custom value * `RELEASE_COMMAND` - the command given to the release, such as `"start"`, `"remote"`, `"eval"`, and so on. This is typically accessed inside `env.sh` and `env.bat` to set different environment variables under different conditions. Note, however, that `RELEASE_COMMAND` has not been validated by the time `env.sh` and `env.bat` are called, so it may be empty or contain invalid values. This variable is always computed and it cannot be set to a custom value * `RELEASE_NAME` - the name of the release. It can be set to a custom value when invoking the release * `RELEASE_VSN` - the version of the release, otherwise the latest version is used. It can be set to a custom value when invoking the release. The custom value must be an existing release version in the `releases/` directory The following variables can be set before you invoke the release or inside `env.sh` and `env.bat`: * `RELEASE_COOKIE` - the release cookie. By default uses the value in `releases/COOKIE`. It can be set to a custom value * `RELEASE_NODE` - the release node name, in the format `name@host`. It can be set to a custom value. The name part must be made only of letters, digits, underscores, and hyphens * `RELEASE_SYS_CONFIG` - the location of the sys.config file. It can be set to a custom path and it must not include the `.config` extension * `RELEASE_VM_ARGS` - the location of the vm.args file. It can be set to a custom path * `RELEASE_TMP` - the directory in the release to write temporary files to. It can be set to a custom directory. It defaults to `$RELEASE_ROOT/tmp` * `RELEASE_MODE` - if the release should start in embedded or interactive mode. Defaults to "embedded". It applies only to start/daemon/install commands * `RELEASE_DISTRIBUTION` - how do we want to run the distribution. May be `name` (long names), `sname` (short names) or `none` (distribution is not started automatically). Defaults to `sname` which allows access only within the current system. `name` allows external connections. If `name` is used and you are not running on Erlang/OTP 22 or later, you must set `RELEASE_NODE` to `[email protected]` with an IP or a known host * `RELEASE_BOOT_SCRIPT` - the name of the boot script to use when starting the release. This script is used when running commands such as `start` and `daemon`. The boot script is expected to be located at the path `releases/RELEASE_VSN/RELEASE_BOOT_SCRIPT.boot`. Defaults to `start` * `RELEASE_BOOT_SCRIPT_CLEAN` - the name of the boot script used when starting the release clean, without your application or its dependencies. This script is used by commands such as `eval`, `rpc`, and `remote`. The boot script is expected to be located at the path `releases/RELEASE_VSN/RELEASE_BOOT_SCRIPT_CLEAN.boot`. Defaults to `start_clean` ## Umbrellas Releases are well integrated with umbrella projects, allowing you to release one or more subsets of your umbrella children. The only difference between performing a release in the umbrella project compared to a regular application is that umbrellas require you to explicitly list your release and the starting point for each release. For example, imagine this umbrella applications: my_app_umbrella/ apps/ my_app_core/ my_app_event_processing/ my_app_web/ where both `my_app_event_processing` and `my_app_web` depend on `my_app_core` but they do not depend on each other. Inside your umbrella, you can define multiple releases: releases: [ web_and_event_processing: [ applications: [ my_app_event_processing: :permanent, my_app_web: :permanent ] ], web_only: [ applications: [my_app_web: :permanent] ], event_processing_only: [ applications: [my_app_event_processing: :permanent] ] ] Note you don't need to define all applications in `:applications`, only the entry points. Also remember that the recommended mode for all applications in the system is `:permanent`. Finally, keep in mind it is not required for you to assemble the release from the umbrella root. You can also assemble the release from each child application individually. Doing it from the root, however, allows you to include two applications that do not depend on each other as part of the same release. ## Hot Code Upgrades Erlang and Elixir are sometimes known for the capability of upgrading a node that is running in production without shutting down that node. However, this feature is not supported out of the box by Elixir releases. The reason we don't provide hot code upgrades is because they are very complicated to perform in practice, as they require careful coding of your processes and applications as well as extensive testing. Given most teams can use other techniques that are language agnostic to upgrade their systems, such as Blue/Green deployments, Canary deployments, Rolling deployments, and others, hot upgrades are rarely a viable option. Let's understand why. In a hot code upgrade, you want to update a node from version A to version B. To do so, the first step is to write recipes for every application that changed between those two releases, telling exactly how the application changed between versions, those recipes are called `.appup` files. While some of the steps in building `.appup` files can be automated, not all of them can. Furthermore, each process in the application needs to be explicitly coded with hot code upgrades in mind. Let's see an example. Imagine your application has a counter process as a GenServer: defmodule Counter do use GenServer def start_link(_) do GenServer.start_link(__MODULE__, :ok, name: __MODULE__) end def bump do GenServer.call(__MODULE__, :bump) end ## Callbacks def init(:ok) do {:ok, 0} end def handle_call(:bump, counter) do {:reply, :ok, counter + 1} end end You add this process as part of your supervision tree and ship version 0.1.0 of your system. Now let's imagine that on version 0.2.0 you added two changes: instead of `bump/0`, that always increments the counter by one, you introduce `bump/1` that passes the exact value to bump the counter. You also change the state, because you want to store the maximum bump value: defmodule Counter do use GenServer def start_link(_) do GenServer.start_link(__MODULE__, :ok, name: __MODULE__) end def bump(by) do GenServer.call(__MODULE__, {:bump, by}) end ## Callbacks def init(:ok) do {:ok, {0, 0}} end def handle_call({:bump, by}, {counter, max}) do {:reply, :ok, {counter + by, max(max, by)}} end end If you were to perform a hot code upgrade in such an application, it would crash, because in the initial version the state was just a counter but in the new version the state is a tuple. Furthermore, you changed the format of the `call` message from `:bump` to `{:bump, by}` and the process may have both old and new messages temporarily mixed, so we need to handle both. The final version would be: defmodule Counter do use GenServer def start_link(_) do GenServer.start_link(__MODULE__, :ok, name: __MODULE__) end def bump(by) do GenServer.call(__MODULE__, {:bump, by}) end ## Callbacks def init(:ok) do {:ok, {0, 0}} end def handle_call(:bump, {counter, max}) do {:reply, :ok, {counter + 1, max(max, 1)}} end def handle_call({:bump, by}, {counter, max}) do {:reply, :ok, {counter + by, max(max, by)}} end def code_change(_, counter, _) do {:ok, {counter, 0}} end end Now you can proceed to list this process in the `.appup` file and hot code upgrade it. This is one of the many steps necessary to perform hot code upgrades and it must be taken into account by every process and application being upgraded in the system. The [`.appup` cookbook](http://erlang.org/doc/design_principles/appup_cookbook.html) provides a good reference and more examples. Once `.appup`s are created, the next step is to create a `.relup` file with all instructions necessary to update the release itself. Erlang documentation does provide a chapter on [Creating and Upgrading a Target System](http://erlang.org/doc/system_principles/create_target.html). [Learn You Some Erlang has a chapter on hot code upgrades](https://learnyousomeerlang.com/relups). Overall, there are many steps, complexities and assumptions made during hot code upgrades, which is ultimately why they are not provided by Elixir out of the box. However, hot code upgrades can still be achieved by teams who desire to implement those steps on top of `mix release` in their projects or as separate libraries. ## Command line options * `--force` - forces recompilation * `--no-archives-check` - does not check archive * `--no-deps-check` - does not check dependencies * `--no-elixir-version-check` - does not check Elixir version * `--no-compile` - does not compile before assembling the release * `--overwrite` - if there is an existing release version, overwrite it * `--path` - the path of the release * `--quiet` - does not write progress to the standard output * `--version` - the version of the release """ import Mix.Generator @switches [ overwrite: :boolean, force: :boolean, quiet: :boolean, path: :string, version: :string, compile: :boolean, deps_check: :boolean, archives_check: :boolean, elixir_version_check: :boolean ] @aliases [ f: :force ] @impl true def run(args) do Mix.Project.get!() Mix.Task.run("compile", args) config = Mix.Project.config() release = case OptionParser.parse!(args, strict: @switches, aliases: @aliases) do {overrides, [name]} -> Mix.Release.from_config!(String.to_atom(name), config, overrides) {overrides, []} -> Mix.Release.from_config!(nil, config, overrides) {_, _} -> Mix.raise("Expected \"mix release\" or \"mix release NAME\"") end if not File.exists?(release.version_path) or yes?(release, "Release #{release.name}-#{release.version} already exists. Overwrite?") do run_steps(release) end end defp yes?(release, message) do release.options[:overwrite] or Mix.shell().yes?(message) end defp run_steps(%{steps: [step | steps]} = release) when is_function(step) do case step.(%{release | steps: steps}) do %Mix.Release{} = release -> run_steps(release) other -> Mix.raise( "Expected step #{inspect(step)} to return a Mix.Release, got: #{inspect(other)}" ) end end defp run_steps(%{steps: [:tar | steps]} = release) do %{release | steps: steps} |> make_tar() |> run_steps() end defp run_steps(%{steps: [:assemble | steps]} = release) do %{release | steps: steps} |> assemble() |> run_steps() end defp run_steps(%{steps: []} = release) do announce(release) end defp assemble(release) do config = Mix.Project.config() message = "#{release.name}-#{release.version} on MIX_ENV=#{Mix.env()}" info(release, [:green, "* assembling ", :reset, message]) # releases/ # VERSION/ # consolidated/ # NAME.rel # start.boot # start.script # start_clean.boot # start_clean.script # sys.config # releases/ # COOKIE # start_erl.data consolidation_path = build_rel(release, config) [ # erts-VSN/ :erts, # releases/VERSION/consolidated {:consolidated, consolidation_path}, # bin/ # RELEASE_NAME # RELEASE_NAME.bat # start # start.bat # releases/ # VERSION/ # elixir # elixir.bat # iex # iex.bat {:executables, Keyword.get(release.options, :include_executables_for, [:unix, :windows])} # lib/APP_NAME-APP_VSN/ | Map.keys(release.applications) ] |> Task.async_stream(&copy(&1, release), ordered: false, timeout: :infinity) |> Stream.run() copy_overlays(release) end defp make_tar(release) do build_path = Mix.Project.build_path() dir_path = if release.path == Path.join([build_path, "rel", Atom.to_string(release.name)]) do build_path else release.path end out_path = Path.join(dir_path, "#{release.name}-#{release.version}.tar.gz") info(release, [:green, "* building ", :reset, out_path]) lib_dirs = Enum.reduce(release.applications, [], fn {name, app_config}, acc -> vsn = Keyword.fetch!(app_config, :vsn) [Path.join("lib", "#{name}-#{vsn}") | acc] end) erts_dir = case release.erts_source do nil -> [] _ -> ["erts-#{release.erts_version}"] end release_files = for basename <- File.ls!(Path.join(release.path, "releases")), not File.dir?(Path.join([release.path, "releases", basename])), do: Path.join("releases", basename) dirs = ["bin", Path.join("releases", release.version)] ++ erts_dir ++ lib_dirs ++ release_files files = dirs |> Enum.filter(&File.exists?(Path.join(release.path, &1))) |> Kernel.++(release.overlays) |> Enum.map(&{String.to_charlist(&1), String.to_charlist(Path.join(release.path, &1))}) File.rm(out_path) :ok = :erl_tar.create(String.to_charlist(out_path), files, [:dereference, :compressed]) release end # build_rel defp build_rel(release, config) do version_path = release.version_path File.rm_rf!(version_path) File.mkdir_p!(version_path) release = maybe_add_config_reader_provider(config, release, version_path) consolidation_path = if config[:consolidate_protocols] do Mix.Project.consolidation_path(config) end sys_config = if File.regular?(config[:config_path]) do config[:config_path] |> Config.Reader.read!(env: Mix.env(), target: Mix.target()) else [] end vm_args_path = Path.join(version_path, "vm.args") cookie_path = Path.join(release.path, "releases/COOKIE") start_erl_path = Path.join(release.path, "releases/start_erl.data") config_provider_path = {:system, "RELEASE_SYS_CONFIG", ".config"} with :ok <- make_boot_scripts(release, version_path, consolidation_path), :ok <- make_vm_args(release, vm_args_path), :ok <- Mix.Release.make_sys_config(release, sys_config, config_provider_path), :ok <- Mix.Release.make_cookie(release, cookie_path), :ok <- Mix.Release.make_start_erl(release, start_erl_path) do consolidation_path else {:error, message} -> File.rm_rf!(version_path) Mix.raise(message) end end defp maybe_add_config_reader_provider(config, %{options: opts} = release, version_path) do default_path = config[:config_path] |> Path.dirname() |> Path.join("runtime.exs") deprecated_path = config[:config_path] |> Path.dirname() |> Path.join("releases.exs") {path, reboot?} = cond do path = opts[:runtime_config_path] -> {path, false} File.exists?(default_path) -> if File.exists?(deprecated_path) do IO.warn( "both #{inspect(default_path)} and #{inspect(deprecated_path)} have been " <> "found, but only #{inspect(default_path)} will be used" ) end {default_path, false} File.exists?(deprecated_path) -> # TODO: Warn from Elixir v1.13 onwards {deprecated_path, true} true -> {nil, false} end cond do path -> msg = "#{path} to configure the release at runtime" Mix.shell().info([:green, "* using ", :reset, msg]) File.cp!(path, Path.join(version_path, "runtime.exs")) init = {:system, "RELEASE_ROOT", "/releases/#{release.version}/runtime.exs"} opts = [path: init, env: Mix.env(), target: Mix.target(), imports: :disabled] release = update_in(release.config_providers, &[{Config.Reader, opts} | &1]) update_in(release.options, &Keyword.put_new(&1, :reboot_system_after_config, reboot?)) release.config_providers == [] -> skipping("runtime configuration (#{default_path} not found)") release true -> release end end defp make_boot_scripts(release, version_path, consolidation_path) do prepend_paths = if consolidation_path do ["$RELEASE_LIB/../releases/#{release.version}/consolidated"] else [] end results = for {boot_name, modes} <- release.boot_scripts do sys_path = Path.join(version_path, Atom.to_string(boot_name)) with :ok <- Mix.Release.make_boot_script(release, sys_path, modes, prepend_paths) do if boot_name == :start do rel_path = Path.join(Path.dirname(sys_path), "#{release.name}.rel") File.rename!(sys_path <> ".rel", rel_path) else File.rm(sys_path <> ".rel") end :ok end end Enum.find(results, :ok, &(&1 != :ok)) end defp make_vm_args(release, path) do vm_args_template = Mix.Release.rel_templates_path(release, "vm.args.eex") if File.exists?(vm_args_template) do copy_template(vm_args_template, path, [release: release], force: true) else File.write!(path, vm_args_template(release: release)) end :ok end defp announce(release) do path = Path.relative_to_cwd(release.path) cmd = "#{path}/bin/#{release.name}" info(release, """ Release created at #{path}! # To start your system #{cmd} start Once the release is running: # To connect to it remotely #{cmd} remote # To stop it gracefully (you may also send SIGINT/SIGTERM) #{cmd} stop To list all commands: #{cmd} """) end defp info(release, message) do unless release.options[:quiet] do Mix.shell().info(message) end end defp skipping(message) do Mix.shell().info([:yellow, "* skipping ", :reset, message]) end ## Overlays defp copy_overlays(release) do target = release.path default = Mix.Release.rel_templates_path(release, "overlays") overlays = if File.dir?(default) do [default | List.wrap(release.options[:overlays])] else List.wrap(release.options[:overlays]) end relative = overlays |> Enum.flat_map(&File.cp_r!(&1, target)) |> Enum.uniq() |> List.delete(target) |> Enum.map(&Path.relative_to(&1, target)) update_in(release.overlays, &(relative ++ &1)) end ## Copy operations defp copy(:erts, release) do _ = Mix.Release.copy_erts(release) :ok end defp copy(app, release) when is_atom(app) do Mix.Release.copy_app(release, app) end defp copy({:consolidated, consolidation_path}, release) do if consolidation_path do consolidation_target = Path.join(release.version_path, "consolidated") _ = Mix.Release.copy_ebin(release, consolidation_path, consolidation_target) end :ok end defp copy({:executables, include_executables_for}, release) do elixir_bin_path = Application.app_dir(:elixir, "../../bin") bin_path = Path.join(release.path, "bin") File.mkdir_p!(bin_path) for os <- include_executables_for do {env, env_fun, clis} = cli_for(os, release) env_path = Path.join(release.version_path, env) env_template_path = Mix.Release.rel_templates_path(release, env <> ".eex") if File.exists?(env_template_path) do copy_template(env_template_path, env_path, [release: release], force: true) else File.write!(env_path, env_fun.(release)) end for {filename, contents} <- clis do target = Path.join(bin_path, filename) File.write!(target, contents) executable!(target) end for {filename, contents_fun} <- elixir_cli_for(os, release) do source = Path.join(elixir_bin_path, filename) if File.regular?(source) do target = Path.join(release.version_path, filename) File.write!(target, contents_fun.(source)) executable!(target) else skipping("#{filename} for #{os} (bin/#{filename} not found in the Elixir installation)") end end end end defp cli_for(:unix, release) do {"env.sh", &env_template(release: &1), [{"#{release.name}", cli_template(release: release)}]} end defp cli_for(:windows, release) do {"env.bat", &env_bat_template(release: &1), [{"#{release.name}.bat", cli_bat_template(release: release)}]} end defp elixir_cli_for(:unix, release) do [ {"elixir", &(&1 |> File.read!() |> String.replace(~s[ -pa "$SCRIPT_PATH"/../lib/*/ebin], "") |> replace_erts_bin(release, ~s["$SCRIPT_PATH"/../../erts-#{release.erts_version}/bin/]))}, {"iex", &File.read!/1} ] end defp elixir_cli_for(:windows, release) do [ {"elixir.bat", &(&1 |> File.read!() |> String.replace(~s[goto expand_erl_libs], ~s[goto run]) |> replace_erts_bin(release, ~s[%~dp0\\..\\..\\erts-#{release.erts_version}\\bin\\]))}, {"iex.bat", &File.read!/1} ] end defp replace_erts_bin(contents, release, new_path) do if release.erts_source do String.replace(contents, ~s[ERTS_BIN=], ~s[ERTS_BIN=#{new_path}]) else contents end end defp executable!(path), do: File.chmod!(path, 0o755) # Helper functions defp release_mode(release, env_var) do # TODO: Remove otp_release check once we require Erlang/OTP 23+ otp_gte_23? = :erlang.system_info(:otp_release) >= '23' reboot? = Keyword.get(release.options, :reboot_system_after_config, false) if otp_gte_23? and reboot? and release.config_providers != [] do "-elixir -config_provider_reboot_mode #{env_var}" else "-mode #{env_var}" end end embed_template(:vm_args, Mix.Tasks.Release.Init.vm_args_text()) embed_template(:env, Mix.Tasks.Release.Init.env_text()) embed_template(:cli, Mix.Tasks.Release.Init.cli_text()) embed_template(:env_bat, Mix.Tasks.Release.Init.env_bat_text()) embed_template(:cli_bat, Mix.Tasks.Release.Init.cli_bat_text()) end
39.31768
106
0.695865
79873108257972756bdb63159107d136100cfac4
1,919
exs
Elixir
config/dev.exs
Nagasaki45/gigalixir
8d0d96ddc2eb0d44a25651cfd28c07cc401139c8
[ "MIT" ]
2
2020-05-05T06:07:16.000Z
2020-05-09T02:12:32.000Z
config/dev.exs
Nagasaki45/gigalixir
8d0d96ddc2eb0d44a25651cfd28c07cc401139c8
[ "MIT" ]
21
2020-05-05T16:06:57.000Z
2020-07-07T17:25:46.000Z
config/dev.exs
Nagasaki45/gigalixir
8d0d96ddc2eb0d44a25651cfd28c07cc401139c8
[ "MIT" ]
null
null
null
use Mix.Config # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with webpack to recompile .js and .css sources. config :cardigan, CardiganWeb.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [ node: [ "node_modules/webpack/bin/webpack.js", "--mode", "development", "--watch-stdin", cd: Path.expand("../assets", __DIR__) ] ] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # Mix task: # # mix phx.gen.cert # # Note that this task requires Erlang/OTP 20 or later. # Run `mix help phx.gen.cert` for more information. # # The `http:` config above can be replaced with: # # https: [ # port: 4001, # cipher_suite: :strong, # keyfile: "priv/cert/selfsigned_key.pem", # certfile: "priv/cert/selfsigned.pem" # ], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Watch static and templates for browser reloading. config :cardigan, CardiganWeb.Endpoint, live_reload: [ patterns: [ ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", ~r"priv/gettext/.*(po)$", ~r"lib/cardigan_web/(live|views)/.*(ex)$", ~r"lib/cardigan_web/templates/.*(eex)$" ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Initialize plugs at runtime for faster development compilation config :phoenix, :plug_init_mode, :runtime
28.220588
68
0.684732
7987417d50116d29fe33dc48f3dad49a7614488f
1,158
ex
Elixir
debian/watch.ex
XMuli/lfxSpeed
1bc58d743df9f00e034a9f9e17528dd5a897274e
[ "MIT" ]
33
2020-11-28T09:31:51.000Z
2022-01-07T09:54:45.000Z
debian/watch.ex
XMuli/lfxSpeed
1bc58d743df9f00e034a9f9e17528dd5a897274e
[ "MIT" ]
10
2020-11-19T02:50:16.000Z
2021-12-04T06:17:15.000Z
debian/watch.ex
XMuli/lfxSpeed
1bc58d743df9f00e034a9f9e17528dd5a897274e
[ "MIT" ]
4
2020-12-12T03:10:17.000Z
2021-04-07T03:11:26.000Z
# Example watch control file for uscan # Rename this file to "watch" and then you can run the "uscan" command # to check for upstream updates and more. # See uscan(1) for format # Compulsory line, this is a version 4 file version=4 # PGP signature mangle, so foo.tar.gz has foo.tar.gz.sig #opts="pgpsigurlmangle=s%$%.sig%" # HTTP site (basic) #http://example.com/downloads.html \ # files/lfxspeed-([\d\.]+)\.tar\.gz debian uupdate # Uncomment to examine an FTP server #ftp://ftp.example.com/pub/lfxspeed-(.*)\.tar\.gz debian uupdate # SourceForge hosted projects # http://sf.net/lfxspeed/ lfxspeed-(.*)\.tar\.gz debian uupdate # GitHub hosted projects #opts="filenamemangle=s%(?:.*?)?v?(\d[\d.]*)\.tar\.gz%<project>-$1.tar.gz%" \ # https://github.com/<user>/lfxspeed/tags \ # (?:.*?/)?v?(\d[\d.]*)\.tar\.gz debian uupdate # PyPI # https://pypi.debian.net/lfxspeed/lfxspeed-(.+)\.(?:zip|tgz|tbz|txz|(?:tar\.(?:gz|bz2|xz))) # Direct Git # opts="mode=git" http://git.example.com/lfxspeed.git \ # refs/tags/v([\d\.]+) debian uupdate # Uncomment to find new files on GooglePages # http://example.googlepages.com/foo.html lfxspeed-(.*)\.tar\.gz
29.692308
92
0.670121