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
list
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
list
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
list
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
93c708e1b6da8b079923f42f0c57cf658cc9c79d
1,395
ex
Elixir
lib/teiserver/account/reports/time_spent_report.ex
adelq/teiserver
77140896df6b4e1ec9e680d64c31ffb528158d14
[ "MIT" ]
null
null
null
lib/teiserver/account/reports/time_spent_report.ex
adelq/teiserver
77140896df6b4e1ec9e680d64c31ffb528158d14
[ "MIT" ]
null
null
null
lib/teiserver/account/reports/time_spent_report.ex
adelq/teiserver
77140896df6b4e1ec9e680d64c31ffb528158d14
[ "MIT" ]
null
null
null
defmodule Teiserver.Account.TimeSpentReport do alias Central.Helpers.DatePresets alias Teiserver.Account @spec icon() :: String.t() def icon(), do: "far fa-satellite-dish" @spec run(Plug.Conn.t(), map()) :: {list(), map()} def run(_conn, params) do params = apply_defaults(params) # Date range {start_date, end_date} = DatePresets.parse( params["date_preset"], params["start_date"], params["end_date"] ) start_date = (Timex.to_unix(start_date) / 60) |> round end_date = (Timex.to_unix(end_date) / 60) |> round data = Account.list_users( search: [ data_greater_than: {"last_login", start_date |> to_string}, data_less_than: {"last_login", end_date |> to_string}, data_equal: {"bot", "false"} ], joins: [:user_stat], order_by: {:data, "ingame_minutes", :desc}, limit: 100 ) |> Enum.sort(fn (user1, user2) -> v1 = user1.user_stat.data[params["mode"]] v2 = user2.user_stat.data[params["mode"]] v1 >= v2 end) assigns = %{ params: params, presets: DatePresets.presets() } {data, assigns} end defp apply_defaults(params) do Map.merge(%{ "date_preset" => "This month", "start_date" => "", "end_date" => "", "mode" => "player_minutes" }, Map.get(params, "report", %{})) end end
24.910714
67
0.582796
93c7112a6f5615e94b902255b646c6b23a91bf3a
1,228
exs
Elixir
config/dev.exs
avinoth/spaces
00bec5adf4568fef73b49e57808033295a837931
[ "MIT" ]
1
2016-09-13T10:40:53.000Z
2016-09-13T10:40:53.000Z
config/dev.exs
avinoth/spaces
00bec5adf4568fef73b49e57808033295a837931
[ "MIT" ]
null
null
null
config/dev.exs
avinoth/spaces
00bec5adf4568fef73b49e57808033295a837931
[ "MIT" ]
null
null
null
use Mix.Config # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with brunch.io to recompile .js and .css sources. config :spaces, Spaces.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin"]] # Watch static and templates for browser reloading. config :spaces, Spaces.Endpoint, live_reload: [ patterns: [ ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$}, ~r{priv/gettext/.*(po)$}, ~r{web/views/.*(ex)$}, ~r{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. # Do not configure such in production as keeping # and calculating stacktraces is usually expensive. config :phoenix, :stacktrace_depth, 20 # Configure your database config :spaces, Spaces.Repo, adapter: Ecto.Adapters.Postgres, username: "herenow", database: "spaces_dev", hostname: "localhost", pool_size: 10
29.238095
74
0.707655
93c71aa83b4c8c38aea25b27bd177b356e9852eb
2,285
ex
Elixir
clients/content/lib/google_api/content/v2/model/orders_return_line_item_request.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/orders_return_line_item_request.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/orders_return_line_item_request.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Content.V2.Model.OrdersReturnLineItemRequest do @moduledoc """ ## Attributes - lineItemId (String.t): The ID of the line item to return. Either lineItemId or productId is required. Defaults to: `null`. - operationId (String.t): The ID of the operation. Unique across all operations for a given order. Defaults to: `null`. - productId (String.t): The ID of the product to return. This is the REST ID used in the products service. Either lineItemId or productId is required. Defaults to: `null`. - quantity (integer()): The quantity to return. Defaults to: `null`. - reason (String.t): The reason for the return. Defaults to: `null`. - reasonText (String.t): The explanation of the reason. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :lineItemId => any(), :operationId => any(), :productId => any(), :quantity => any(), :reason => any(), :reasonText => any() } field(:lineItemId) field(:operationId) field(:productId) field(:quantity) field(:reason) field(:reasonText) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.OrdersReturnLineItemRequest do def decode(value, options) do GoogleApi.Content.V2.Model.OrdersReturnLineItemRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.OrdersReturnLineItemRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.269841
173
0.717724
93c73282bcc15ff3401b50f5926b736f5d2e8fcf
3,528
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/autoscaling_policy_scaling_schedule.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/autoscaling_policy_scaling_schedule.ex
kyleVsteger/elixir-google-api
3a0dd498af066a4361b5b0fd66ffc04a57539488
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/autoscaling_policy_scaling_schedule.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.Compute.V1.Model.AutoscalingPolicyScalingSchedule do @moduledoc """ Scaling based on user-defined schedule. The message describes a single scaling schedule. A scaling schedule changes the minimum number of VM instances an autoscaler can recommend, which can trigger scaling out. ## Attributes * `description` (*type:* `String.t`, *default:* `nil`) - A description of a scaling schedule. * `disabled` (*type:* `boolean()`, *default:* `nil`) - A boolean value that specifies whether a scaling schedule can influence autoscaler recommendations. If set to true, then a scaling schedule has no effect. This field is optional, and its value is false by default. * `durationSec` (*type:* `integer()`, *default:* `nil`) - The duration of time intervals, in seconds, for which this scaling schedule is to run. The minimum allowed value is 300. This field is required. * `minRequiredReplicas` (*type:* `integer()`, *default:* `nil`) - The minimum number of VM instances that the autoscaler will recommend in time intervals starting according to schedule. This field is required. * `schedule` (*type:* `String.t`, *default:* `nil`) - The start timestamps of time intervals when this scaling schedule is to provide a scaling signal. This field uses the extended cron format (with an optional year field). The expression can describe a single timestamp if the optional year is set, in which case the scaling schedule runs once. The schedule is interpreted with respect to time_zone. This field is required. Note: These timestamps only describe when autoscaler starts providing the scaling signal. The VMs need additional time to become serving. * `timeZone` (*type:* `String.t`, *default:* `nil`) - The time zone to use when interpreting the schedule. The value of this field must be a time zone name from the tz database: http://en.wikipedia.org/wiki/Tz_database. This field is assigned a default value of ?UTC? if left empty. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :description => String.t() | nil, :disabled => boolean() | nil, :durationSec => integer() | nil, :minRequiredReplicas => integer() | nil, :schedule => String.t() | nil, :timeZone => String.t() | nil } field(:description) field(:disabled) field(:durationSec) field(:minRequiredReplicas) field(:schedule) field(:timeZone) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.AutoscalingPolicyScalingSchedule do def decode(value, options) do GoogleApi.Compute.V1.Model.AutoscalingPolicyScalingSchedule.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.AutoscalingPolicyScalingSchedule do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
56.903226
566
0.736678
93c733aa27541d3a498aa0921d6537afbd41a2fd
467
exs
Elixir
priv/repo/migrations/20151007071706_create_rss_feed.exs
yasuhiro-okada-aktsk/sample_elixir_ecto_select
6a927e5d7f591b247920934216f226ccb0c53e6e
[ "MIT" ]
null
null
null
priv/repo/migrations/20151007071706_create_rss_feed.exs
yasuhiro-okada-aktsk/sample_elixir_ecto_select
6a927e5d7f591b247920934216f226ccb0c53e6e
[ "MIT" ]
null
null
null
priv/repo/migrations/20151007071706_create_rss_feed.exs
yasuhiro-okada-aktsk/sample_elixir_ecto_select
6a927e5d7f591b247920934216f226ccb0c53e6e
[ "MIT" ]
null
null
null
defmodule SampleElixirEctoSelect.Repo.Migrations.CreateRssFeed do use Ecto.Migration def change do create table(:rss_feeds) do add :feed_url, :string add :feed_id, :string add :title, :string add :subtitle, :string add :summary, :text add :link, :string add :author, :string add :image, :string add :updated, :datetime timestamps end create unique_index :rss_feeds, [:feed_url] end end
21.227273
65
0.64454
93c742f21750152d4433c8fe22042f5eff996b25
3,302
ex
Elixir
lib/glimesh/api/resolvers/account_resolver.ex
coredreamstudios/glimesh.tv
736f4f03aa51a7fbcaaf276ffee2af470afc2fa7
[ "MIT" ]
null
null
null
lib/glimesh/api/resolvers/account_resolver.ex
coredreamstudios/glimesh.tv
736f4f03aa51a7fbcaaf276ffee2af470afc2fa7
[ "MIT" ]
null
null
null
lib/glimesh/api/resolvers/account_resolver.ex
coredreamstudios/glimesh.tv
736f4f03aa51a7fbcaaf276ffee2af470afc2fa7
[ "MIT" ]
null
null
null
defmodule Glimesh.Api.AccountResolver do @moduledoc false import Ecto.Query alias Absinthe.Relay.Connection alias Glimesh.AccountFollows alias Glimesh.Accounts alias Glimesh.Api @error_not_found "Could not find resource" # Query Field Resolvers def resolve_email(user, _, %{context: %{access: access}}) do with :ok <- Bodyguard.permit(Api.Scopes, :email, access, user) do {:ok, user.email} end end def resolve_avatar_url(user, _, _) do {:ok, Glimesh.Api.resolve_full_url(Glimesh.Avatar.url({user.avatar, user}))} end # Users def myself(_, _, %{context: %{access: access}}) do if user = Accounts.get_user(access.user.id) do {:ok, user} else {:error, @error_not_found} end end def all_users(args, _) do Accounts.query_users() |> order_by(:id) |> Api.connection_from_query_with_count(args) end def find_user(%{id: id}, _) do if user = Accounts.get_user(id) do {:ok, user} else {:error, @error_not_found} end end def find_user(%{username: username}, _) do if user = Accounts.get_by_username(username) do {:ok, user} else {:error, @error_not_found} end end def find_user(_, _), do: {:error, @error_not_found} # Followers def all_followers(args, _) do case query_followers(args) do {:ok, :query, resp} -> Api.connection_from_query_with_count(resp, args) {:ok, :single, resp} -> Connection.from_list([resp], args) {:error, err} -> {:error, err} end end defp query_followers(%{streamer_id: streamer_id, user_id: user_id}) do streamer = Accounts.get_user(streamer_id) user = Accounts.get_user(user_id) if !is_nil(streamer) and !is_nil(user) do {:ok, :single, AccountFollows.get_following(streamer, user)} else {:error, @error_not_found} end end defp query_followers(%{streamer_id: streamer_id}) do if streamer = Accounts.get_user(streamer_id) do followers = AccountFollows.query_followers(streamer) |> order_by(:id) {:ok, :query, followers} else {:error, @error_not_found} end end defp query_followers(%{user_id: user_id}) do if user = Accounts.get_user(user_id) do following = AccountFollows.query_following(user) |> order_by(:id) {:ok, :query, following} else {:error, @error_not_found} end end defp query_followers(_) do followers = AccountFollows.query_all_follows() |> order_by(:id) {:ok, :query, followers} end def get_user_followers(args, %{source: user}) do Glimesh.AccountFollows.Follower |> where(streamer_id: ^user.id) |> order_by(:id) |> Api.connection_from_query_with_count(args) end def get_user_following(args, %{source: user}) do Glimesh.AccountFollows.Follower |> where(user_id: ^user.id) |> order_by(:id) |> Api.connection_from_query_with_count(args) end def get_live_user_following_channels(args, %{source: user}) do following_user_ids = Enum.map(Glimesh.AccountFollows.list_following(user), fn x -> x.streamer_id end) Glimesh.Streams.Channel |> where([c], c.user_id in ^following_user_ids) |> order_by(:id) |> Api.connection_from_query_with_count(args) end end
25.015152
86
0.661114
93c758785d1485f403542799d19e325f6e9289e1
297
ex
Elixir
lib/ketbin/utils/syntax.ex
ATechnoHazard/katbin
20a0b45954cf7819cd9d51c401db06be0f47666b
[ "MIT" ]
4
2020-08-05T20:05:34.000Z
2020-10-01T10:01:56.000Z
lib/ketbin/utils/syntax.ex
ATechnoHazard/katbin
20a0b45954cf7819cd9d51c401db06be0f47666b
[ "MIT" ]
1
2020-07-08T05:02:12.000Z
2020-09-25T10:05:11.000Z
lib/ketbin/utils/syntax.ex
ATechnoHazard/katbin
20a0b45954cf7819cd9d51c401db06be0f47666b
[ "MIT" ]
1
2020-08-30T12:59:49.000Z
2020-08-30T12:59:49.000Z
defmodule Ketbin.Utils.Syntax do use Rustler, otp_app: :ketbin, crate: "ketbin_utils_syntax" # When your NIF is loaded, it will override this function. def add(_a, _b), do: error() def highlight_text(_text, _lang), do: error() defp error(), do: :erlang.nif_error(:nif_not_loaded) end
27
61
0.720539
93c76edcce1245612c25e4e94fc5de507caab4d0
2,421
ex
Elixir
web/controllers/post_controller.ex
dkarter/exblog
3bc2c52dc6b8263506d5fc5e842436f64414d9c7
[ "MIT" ]
null
null
null
web/controllers/post_controller.ex
dkarter/exblog
3bc2c52dc6b8263506d5fc5e842436f64414d9c7
[ "MIT" ]
null
null
null
web/controllers/post_controller.ex
dkarter/exblog
3bc2c52dc6b8263506d5fc5e842436f64414d9c7
[ "MIT" ]
null
null
null
defmodule Exblog.PostController do use Exblog.Web, :controller alias Exblog.Post alias Exblog.Comment plug :scrub_params, "post" when action in [:create, :update] plug :scrub_params, "comment" when action in [:add_comment] def index(conn, _params) do posts = Repo.all(Post) render(conn, "index.html", posts: posts) end def new(conn, _params) do changeset = Post.changeset(%Post{}) render(conn, "new.html", changeset: changeset) end def create(conn, %{"post" => post_params}) do changeset = Post.changeset(%Post{}, post_params) case Repo.insert(changeset) do {:ok, _post} -> conn |> put_flash(:info, "Post created successfully.") |> redirect(to: post_path(conn, :index)) {:error, changeset} -> render(conn, "new.html", changeset: changeset) end end def show(conn, %{"id" => id}) do post = Repo.get!(Post, id) render(conn, "show.html", post: post) end def edit(conn, %{"id" => id}) do post = Repo.get!(Post, id) changeset = Post.changeset(post) render(conn, "edit.html", post: post, changeset: changeset) end def update(conn, %{"id" => id, "post" => post_params}) do post = Repo.get!(Post, id) changeset = Post.changeset(post, post_params) case Repo.update(changeset) do {:ok, post} -> conn |> put_flash(:info, "Post updated successfully.") |> redirect(to: post_path(conn, :show, post)) {:error, changeset} -> render(conn, "edit.html", post: post, changeset: changeset) end end def delete(conn, %{"id" => id}) do post = Repo.get!(Post, id) # Here we use delete! (with a bang) because we expect # it to always work (and if it does not, it will raise). Repo.delete!(post) conn |> put_flash(:info, "Post deleted successfully.") |> redirect(to: post_path(conn, :index)) end def add_comment(conn, %{"comment" => comment_params, "post_id" => post_id}) do changeset = Comment.changeset(%Comment{}, Map.put(comment_params, "post_id", post_id)) post = Post |> Repo.get(post_id) |> Repo.preload([:comments]) if changeset.valid? do Repo.insert(changeset) conn |> put_flash(:info, "Comment added.") |> redirect(to: post_path(conn, :show, post)) else render(conn, "show.html", post: post, changeset: changeset) end end end
27.511364
90
0.615035
93c7848633ef658d0cc79b6acd4d94cf6f2bb930
1,605
ex
Elixir
test/support/model_case.ex
JKGisMe/square_square_backend
1b5237fff2c9dab0e03082ecf5a5a28a1133935b
[ "MIT" ]
null
null
null
test/support/model_case.ex
JKGisMe/square_square_backend
1b5237fff2c9dab0e03082ecf5a5a28a1133935b
[ "MIT" ]
null
null
null
test/support/model_case.ex
JKGisMe/square_square_backend
1b5237fff2c9dab0e03082ecf5a5a28a1133935b
[ "MIT" ]
null
null
null
defmodule SquareSquareBackend.ModelCase do @moduledoc """ This module defines the test case to be used by model tests. You may define functions here to be used as helpers in your model tests. See `errors_on/2`'s definition as reference. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do alias SquareSquareBackend.Repo import Ecto.Model import Ecto.Query, only: [from: 2] import SquareSquareBackend.ModelCase end end setup tags do unless tags[:async] do Ecto.Adapters.SQL.restart_test_transaction(SquareSquareBackend.Repo, []) end :ok end @doc """ Helper for returning list of errors in model when passed certain data. ## Examples Given a User model that lists `:name` as a required field and validates `:password` to be safe, it would return: iex> errors_on(%User{}, password: "password") [password: "is unsafe", name: "is blank"] You could then write your assertion like: assert {:password, "is unsafe"} in errors_on(%User{}, password: "password") You can also create the changeset manually and retrieve the errors field directly: iex> changeset = User.changeset(%User{}, password: "password") iex> {:password, "is unsafe"} in changeset.errors true """ def errors_on(model, data) do model.__struct__.changeset(model, data).errors end end
26.75
81
0.698442
93c7c1228aafb3e0f08ab303ec5a162c461d6c01
1,188
ex
Elixir
lib/excommerce/shipments/shipment.ex
roger120981/planet
a662006551d11427c08cf6cdbacd37d377bcd9c5
[ "MIT" ]
1
2019-04-01T19:14:16.000Z
2019-04-01T19:14:16.000Z
lib/excommerce/shipments/shipment.ex
roger120981/planet
a662006551d11427c08cf6cdbacd37d377bcd9c5
[ "MIT" ]
null
null
null
lib/excommerce/shipments/shipment.ex
roger120981/planet
a662006551d11427c08cf6cdbacd37d377bcd9c5
[ "MIT" ]
1
2019-03-24T01:50:48.000Z
2019-03-24T01:50:48.000Z
defmodule Excommerce.Shipments.Shipment do use Ecto.Schema import Ecto.Changeset alias Excommerce.Shipments.{Shipment, ShippingMethod, ShipmentUnit} alias Excommerce.Adjustments.Adjustment schema "shipments" do belongs_to :shipping_method, ShippingMethod belongs_to :shipment_unit, ShipmentUnit has_one :adjustment, Adjustment timestamps() end @required_fields ~w(shipping_method_id)a @optional_fields ~w()a @doc """ Creates a changeset based on the `model` and `params`. If no params are provided, an invalid changeset is returned with no validation performed. """ def changeset(shipment, attrs \\ %{}) do shipment |> cast(attrs, @required_fields ++ @optional_fields) |> validate_required(@required_fields) end def create_changeset(shipment, attrs \\ %{}) do shipment |> cast(params_with_adjustment(shipment, attrs), @required_fields ++ @optional_fields) |> validate_required(@required_fields) |> cast_assoc(:adjustment) end defp params_with_adjustment(_shipment, attrs) do Map.put_new(attrs, "adjustment", %{"amount" => attrs["shipping_cost"], "order_id" => attrs["order_id"]}) end end
27.627907
108
0.722222
93c7cf0f2ee17ba852c4abbb73c708c52c44fbab
14,620
ex
Elixir
lib/glimesh/graphql/schema/channel_types.ex
chriscuris/glimesh.tv
e1a78aa763ea5599d045fdfa65237b94fbb28a23
[ "MIT" ]
null
null
null
lib/glimesh/graphql/schema/channel_types.ex
chriscuris/glimesh.tv
e1a78aa763ea5599d045fdfa65237b94fbb28a23
[ "MIT" ]
null
null
null
lib/glimesh/graphql/schema/channel_types.ex
chriscuris/glimesh.tv
e1a78aa763ea5599d045fdfa65237b94fbb28a23
[ "MIT" ]
null
null
null
defmodule Glimesh.Schema.ChannelTypes do @moduledoc false use Absinthe.Schema.Notation import Absinthe.Resolution.Helpers import_types(Absinthe.Plug.Types) alias Glimesh.Repo alias Glimesh.Resolvers.ChannelResolver alias Glimesh.Streams input_object :stream_metadata_input do field :ingest_server, :string, description: "Ingest Server URL" field :ingest_viewers, :integer, description: "Viewers on the ingest" field :stream_time_seconds, :integer, description: "Current Stream time in seconds" field :source_bitrate, :integer, description: "Bitrate at the source" field :source_ping, :integer, description: "Ping to the source" field :recv_packets, :integer, description: "Received stream input data packets" field :lost_packets, :integer, description: "Lost stream input data packets" field :nack_packets, :integer, description: "Negative Acknowledged stream input data packets" field :vendor_name, :string, description: "Client vendor name" field :vendor_version, :string, description: "Client vendor version" field :video_codec, :string, description: "Stream video codec" field :video_height, :integer, description: "Stream video height" field :video_width, :integer, description: "Stream video width" field :audio_codec, :string, description: "Stream audio codec" end object :streams_queries do @desc "List all channels" field :channels, list_of(:channel) do arg(:status, :channel_status) arg(:category_slug, :string) resolve(&ChannelResolver.all_channels/2) end @desc "Query individual channel" field :channel, :channel do arg(:id, :id) arg(:username, :string) arg(:hmac_key, :string) resolve(&ChannelResolver.find_channel/2) end @desc "List all categories" field :categories, list_of(:category) do resolve(&ChannelResolver.all_categories/2) end @desc "Query individual category" field :category, :category do arg(:slug, :string) resolve(&ChannelResolver.find_category/2) end @desc "List all subscribers or subscribees" field :subscriptions, list_of(:sub) do arg(:streamer_username, :string) arg(:user_username, :string) resolve(&ChannelResolver.all_subscriptions/2) end end object :streams_mutations do @desc "Start a stream" field :start_stream, type: :stream do arg(:channel_id, non_null(:id)) resolve(&ChannelResolver.start_stream/3) end @desc "End a stream" field :end_stream, type: :stream do arg(:stream_id, non_null(:id)) resolve(&ChannelResolver.end_stream/3) end @desc "Update a stream's metadata" field :log_stream_metadata, type: :stream_metadata do arg(:stream_id, non_null(:id)) arg(:metadata, non_null(:stream_metadata_input)) resolve(&ChannelResolver.log_stream_metadata/3) end @desc "Update a stream's thumbnail" field :upload_stream_thumbnail, type: :stream do arg(:stream_id, non_null(:id)) arg(:thumbnail, non_null(:upload)) resolve(&ChannelResolver.upload_stream_thumbnail/3) end end object :streams_subscriptions do field :channel, :channel do arg(:id, :id) config(fn args, _ -> case Map.get(args, :id) do nil -> {:ok, topic: [Streams.get_subscribe_topic(:channel)]} channel_id -> {:ok, topic: [Streams.get_subscribe_topic(:channel, channel_id)]} end end) end end @desc "Current channel status" enum :channel_status do value(:live, as: "live") value(:offline, as: "offline") end @desc "Categories are the containers for live streaming content." object :category do field :id, :id, description: "Unique category identifier" field :name, :string, description: "Name of the category" @desc "Tags associated with the category" field :tags, list_of(:tag), resolve: dataloader(Repo) @desc "Subcategories within the category" field :subcategories, list_of(:subcategory), resolve: dataloader(Repo) field :tag_name, :string do deprecate("Tag name is now just name") resolve(fn category, _, _ -> {:ok, category.name} end) end field :slug, :string, description: "Slug of the category" field :parent, :category do deprecate("All categories are now parents and the children are tags.") resolve(fn _, _, _ -> {:ok, nil} end) end end @desc "Subcategories are specific games, topics, or genre's that exist under a Category." object :subcategory do field :id, :id, description: "ID of subcategory" field :name, :string, description: "Name of the subcategory" field :slug, :string, description: "URL friendly name of the subcategory" field :user_created, :boolean, description: "Was the subcategory created by a user?" field :source, :string, description: "Subcategory source" field :source_id, :string, description: "Subcategory source ID" @desc "Subcategory background image URL" field :background_image_url, :string do # Resolve URL to our actual public route resolve(fn subcategory, _, _ -> {:ok, subcategory.background_image} end) end field :category, :category, resolve: dataloader(Repo), description: "Parent category" field :inserted_at, non_null(:naive_datetime), description: "Subcategory creation date" field :updated_at, non_null(:naive_datetime), description: "Subcategory updated date" end @desc "Tags are user created labels that are either global or category specific." object :tag do field :id, :id, description: "Unique tag identifier" field :name, :string, description: "Name of the tag" field :slug, :string, description: "URL friendly name of the tag" field :count_usage, :integer, description: "The number of streams started with this tag" field :category, :category, resolve: dataloader(Repo), description: "Parent category" field :inserted_at, non_null(:naive_datetime), description: "Tag creation date" field :updated_at, non_null(:naive_datetime), description: "Tag updated date" end @desc "A channel is a user's actual container for live streaming." object :channel do field :id, :id, description: "Unique channel identifier" field :status, :channel_status, description: "The current status of the channnel" field :title, :string, description: "The title of the current stream, live or offline." field :category, :category, resolve: dataloader(Repo), description: "Category the current stream is in" field :subcategory, :subcategory, resolve: dataloader(Repo), description: "Subcategory the current stream is in" field :mature_content, :boolean, description: "If the streamer has flagged this channel as only appropriate for Mature Audiences." field :language, :string, description: "The language a user can expect in the stream." field :thumbnail, :string, description: "Current stream thumbnail" @desc "Current streams unique stream key" field :stream_key, :string do resolve(fn channel, _, %{context: %{access: access}} -> case Bodyguard.permit(Glimesh.Api.Scopes, :stream_mutations, access) do :ok -> {:ok, Glimesh.Streams.get_stream_key(channel)} _ -> {:error, "Unauthorized to access streamKey field."} end end) end @desc "Hash-based Message Authentication Code for the stream" field :hmac_key, :string do resolve(fn channel, _, %{context: %{access: access}} -> case Bodyguard.permit(Glimesh.Api.Scopes, :stream_mutations, access) do :ok -> {:ok, channel.hmac_key} _ -> {:error, "Unauthorized to access hmacKey field."} end end) end field :inaccessible, :boolean, description: "Is the stream inaccessible?" field :chat_rules_md, :string, description: "Chat rules in markdown" field :chat_rules_html, :string, description: "Chat rules in html" field :show_recent_chat_messages_only, :boolean, description: "Only show recent chat messages?" field :disable_hyperlinks, :boolean, description: "Toggle for links automatically being clickable" field :block_links, :boolean, description: "Toggle for blocking anyone from posting links" field :require_confirmed_email, :boolean, description: "Toggle for requiring confirmed email before chatting" field :minimum_account_age, :integer, description: "Minimum account age length before chatting" field :stream, :stream, resolve: dataloader(Repo), description: "If the channel is live, this will be the current Stream" field :streamer, non_null(:user), resolve: dataloader(Repo), description: "User associated with the channel" field :chat_messages, list_of(:chat_message), resolve: dataloader(Repo), description: "List of chat messages sent in the channel" field :bans, list_of(:channel_ban), resolve: dataloader(Repo), description: "List of bans in the channel" field :moderators, list_of(:channel_moderator), resolve: dataloader(Repo), description: "List of moderators in the channel" field :moderation_logs, list_of(:channel_moderation_log), resolve: dataloader(Repo), description: "List of moderation events in the channel" field :user, non_null(:user), resolve: dataloader(Repo), deprecate: "Please use the streamer field" field :tags, list_of(:tag), resolve: dataloader(Repo), description: "Tags associated with the channel" field :inserted_at, non_null(:naive_datetime), description: "Channel creation date" field :updated_at, non_null(:naive_datetime), description: "Channel updated date" end @desc "A stream is a single live stream in, either current or historical." object :stream do field :id, :id, description: "Unique stream identifier" field :channel, non_null(:channel), resolve: dataloader(Repo), description: "Channel running with the stream" field :title, :string, description: "The title of the stream." field :category, non_null(:category), resolve: dataloader(Repo), description: "The category the current stream is in" field :subcategory, :subcategory, resolve: dataloader(Repo), description: "The subategory the current stream is in" field :metadata, list_of(:stream_metadata), resolve: dataloader(Repo), description: "Current stream metadata" field :started_at, non_null(:naive_datetime), description: "Datetime of when the stream was started" field :ended_at, :naive_datetime, description: "Datetime of when the stream ended, or null if still going" # field :viewers, :viewers, resolve: dataloader(Repo) # field :chatters, :chatters, resolve: dataloader(Repo) field :count_viewers, :integer, description: "Concurrent viewers during last snapshot" field :count_chatters, :integer, description: "Concurrent chatters during last snapshot" field :peak_viewers, :integer, description: "Peak concurrent viewers" field :peak_chatters, :integer, description: "Peak concurrent chatters" field :avg_viewers, :integer, description: "Average viewers during the stream" field :avg_chatters, :integer, description: "Average chatters during the stream" field :new_subscribers, :integer, description: "Total new subscribers gained during the stream" field :resub_subscribers, :integer, description: "Total resubscribers during the stream" @desc "Thumbnail URL of the stream" field :thumbnail, :string do resolve(fn stream, _, _ -> {:ok, Glimesh.StreamThumbnail.url({stream.thumbnail, stream})} end) end field :inserted_at, non_null(:naive_datetime), description: "Stream created date" field :updated_at, non_null(:naive_datetime), description: "Stream updated date" end @desc "A single instance of stream metadata." object :stream_metadata do field :id, :id, description: "Unique stream metadata identifier" field :stream, non_null(:stream), resolve: dataloader(Repo), description: "Current stream metadata references" field :ingest_server, :string, description: "Ingest Server URL" field :ingest_viewers, :string, description: "Viewers on the ingest" field :stream_time_seconds, :integer, description: "Current Stream time in seconds" field :source_bitrate, :integer, description: "Bitrate at the source" field :source_ping, :integer, description: "Ping to the source" field :recv_packets, :integer, description: "Received stream input data packets" field :lost_packets, :integer, description: "Lost stream input data packets" field :nack_packets, :integer, description: "Negative Acknowledged stream input data packets" field :vendor_name, :string, description: "Client vendor name" field :vendor_version, :string, description: "Client vendor version" field :video_codec, :string, description: "Stream video codec" field :video_height, :integer, description: "Stream video height" field :video_width, :integer, description: "Stream video width" field :audio_codec, :string, description: "Stream audio codec" field :inserted_at, non_null(:naive_datetime), description: "Stream metadata created date" field :updated_at, non_null(:naive_datetime), description: "Stream metadata updated date" end @desc "A subscription is an exchange of money for support." object :sub do field :id, :id, description: "Subscription unique identifier" field :is_active, :boolean, description: "Is the subscription currently active?" field :started_at, non_null(:datetime), description: "When the subscription started" field :ended_at, :datetime, description: "When the subscription ended" field :price, :integer, description: "Price of the subscription" field :product_name, :string, description: "Subscription product name" field :streamer, :user, resolve: dataloader(Repo), description: "The streamer receiving the support from the subscription" field :user, non_null(:user), resolve: dataloader(Repo), description: "The user giving the support with the subscription" field :inserted_at, non_null(:naive_datetime), description: "Subscription created date" field :updated_at, non_null(:naive_datetime), description: "Subscription updated date" end end
36.826196
97
0.702531
93c7d306bb82d8dde93280098c0a7079bb8ed478
1,188
ex
Elixir
test/support/conn_case.ex
Tass-Jomo/Art-for-deriq
df88debc0accab36976516a2c1cc49a98cd1dca4
[ "MIT" ]
null
null
null
test/support/conn_case.ex
Tass-Jomo/Art-for-deriq
df88debc0accab36976516a2c1cc49a98cd1dca4
[ "MIT" ]
1
2021-03-10T16:24:36.000Z
2021-03-10T16:24:36.000Z
test/support/conn_case.ex
Tass-Jomo/deriq_art
2cd1c5f0de3c11f465e4cb29c2f146836f63ea36
[ "MIT" ]
null
null
null
defmodule DeriqArtWeb.ConnCase do @moduledoc """ This module defines the test case to be used by tests that require setting up a connection. Such tests rely on `Phoenix.ConnTest` and also import other functionality to make it easier to build common data structures and query the data layer. Finally, if the test case interacts with the database, we enable the SQL sandbox, so changes done to the database are reverted at the end of every test. If you are using PostgreSQL, you can even run database tests asynchronously by setting `use DeriqArtWeb.ConnCase, async: true`, although this option is not recommendded for other databases. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest alias DeriqArtWeb.Router.Helpers, as: Routes # The default endpoint for testing @endpoint DeriqArtWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(DeriqArt.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(DeriqArt.Repo, {:shared, self()}) end {:ok, conn: Phoenix.ConnTest.build_conn()} end end
28.97561
70
0.728114
93c7e775570a3984e00a0df1bafdc4e115c4b969
58
exs
Elixir
others/elixir/command_line_args.exs
mkanenobu/trashbox
c691dbf9a07991fd42304020c8aac58e1e4b9644
[ "WTFPL" ]
2
2020-05-11T13:43:27.000Z
2020-07-31T11:57:19.000Z
others/elixir/command_line_args.exs
mkanenobu/trashbox
c691dbf9a07991fd42304020c8aac58e1e4b9644
[ "WTFPL" ]
2
2020-09-27T02:35:38.000Z
2021-03-08T08:33:02.000Z
others/elixir/command_line_args.exs
mkanenobu/trashbox
c691dbf9a07991fd42304020c8aac58e1e4b9644
[ "WTFPL" ]
1
2020-05-11T13:44:04.000Z
2020-05-11T13:44:04.000Z
IO.puts 'Arguments:' Enum.map(System.argv(), &IO.puts(&1))
29
37
0.672414
93c83be96406de3a0e2f7dd69a9d58d4fc643f89
3,017
ex
Elixir
lib/refreshable_agent.ex
statmuse/ex_microsoftbot
07196c75dc919a509d73fc15b1030481402bbd98
[ "MIT" ]
null
null
null
lib/refreshable_agent.ex
statmuse/ex_microsoftbot
07196c75dc919a509d73fc15b1030481402bbd98
[ "MIT" ]
null
null
null
lib/refreshable_agent.ex
statmuse/ex_microsoftbot
07196c75dc919a509d73fc15b1030481402bbd98
[ "MIT" ]
null
null
null
defmodule ExMicrosoftBot.RefreshableAgent do @callback get_refreshed_state(any, any) :: any @callback time_to_refresh_after_in_seconds(any) :: integer @doc false defmacro __using__(_) do quote location: :keep do require Logger @behaviour ExMicrosoftBot.RefreshableAgent use GenServer # Init def init(args) do state = args |> get_refreshed_state_and_schedule_refresh(nil) |> Map.merge(%{original_args: args}, fn _k1, _v1, v2 -> v2 end) {:ok, state} end def start_link(args \\ []) do GenServer.start_link(__MODULE__, args, name: __MODULE__) end # GenServer API def handle_call(:get_state, _from, %{state: mod_state} = state) do Logger.debug("refreshable_agent: handle_call/3 -> :get_state -> #{inspect(state)}") {:reply, mod_state, state} end # Cancel the timer, send message to self to refresh and reply with :ok def handle_call(:force_refresh, _from, %{timer_ref: timer_ref} = state) do Logger.debug("refreshable_agent: handle_call/3 -> :force_refresh") Process.cancel_timer(timer_ref) send(self(), :refresh) {:reply, :ok, state} end def handle_info(:refresh, %{state: mod_state, original_args: args} = state) do new_state = args |> get_refreshed_state_and_schedule_refresh(mod_state) |> Map.merge(state, fn _k, v1, _v2 -> v1 end) {:noreply, new_state} end def handle_info(message, state) do Logger.debug( "refreshable_agent: handle_info/2 -> #{inspect(message)} -> #{inspect(state)}" ) {:noreply, state} end # Private @spec get_state() :: any defp get_state() do GenServer.call(__MODULE__, :get_state) end @spec get_refreshed_state_and_schedule_refresh(any, any) :: Map.t() defp get_refreshed_state_and_schedule_refresh(args, old_state) do Logger.debug( "RefreshableAgent.get_refreshed_state_and_schedule_refresh/2 -> #{inspect(old_state)}" ) updated_mod_state = get_refreshed_state(args, old_state) Logger.debug( "RefreshableAgent.get_refreshed_state_and_schedule_refresh/2 -> #{ inspect(updated_mod_state) }" ) timer_ref = updated_mod_state |> time_to_refresh_after_in_seconds() # Converting to ms |> Kernel.*(1000) |> schedule_next_refresh %{state: updated_mod_state, timer_ref: timer_ref} end @spec force_refresh_state() :: :ok defp force_refresh_state() do GenServer.call(__MODULE__, :force_refresh) end defp schedule_next_refresh(refresh_time_in_seconds) do Logger.debug("RefreshableAgent.schedule_next_refresh/1 -> #{refresh_time_in_seconds}") Process.send_after(__MODULE__, :refresh, refresh_time_in_seconds) end end end end
29.009615
96
0.631422
93c84ef2f62c8aeb93848c651791ef7a773ea5e3
2,836
ex
Elixir
clients/android_management/lib/google_api/android_management/v1/model/status_reporting_settings.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
null
null
null
clients/android_management/lib/google_api/android_management/v1/model/status_reporting_settings.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
null
null
null
clients/android_management/lib/google_api/android_management/v1/model/status_reporting_settings.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.AndroidManagement.V1.Model.StatusReportingSettings do @moduledoc """ Settings controlling the behavior of status reports. ## Attributes - applicationReportsEnabled (boolean()): Whether app reports are enabled. Defaults to: `null`. - deviceSettingsEnabled (boolean()): Whether device settings reporting is enabled. Defaults to: `null`. - displayInfoEnabled (boolean()): Whether displays reporting is enabled. Defaults to: `null`. - hardwareStatusEnabled (boolean()): Whether hardware status reporting is enabled. Defaults to: `null`. - memoryInfoEnabled (boolean()): Whether memory info reporting is enabled. Defaults to: `null`. - networkInfoEnabled (boolean()): Whether network info reporting is enabled. Defaults to: `null`. - powerManagementEventsEnabled (boolean()): Whether power management event reporting is enabled. Defaults to: `null`. - softwareInfoEnabled (boolean()): Whether software info reporting is enabled. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :applicationReportsEnabled => any(), :deviceSettingsEnabled => any(), :displayInfoEnabled => any(), :hardwareStatusEnabled => any(), :memoryInfoEnabled => any(), :networkInfoEnabled => any(), :powerManagementEventsEnabled => any(), :softwareInfoEnabled => any() } field(:applicationReportsEnabled) field(:deviceSettingsEnabled) field(:displayInfoEnabled) field(:hardwareStatusEnabled) field(:memoryInfoEnabled) field(:networkInfoEnabled) field(:powerManagementEventsEnabled) field(:softwareInfoEnabled) end defimpl Poison.Decoder, for: GoogleApi.AndroidManagement.V1.Model.StatusReportingSettings do def decode(value, options) do GoogleApi.AndroidManagement.V1.Model.StatusReportingSettings.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AndroidManagement.V1.Model.StatusReportingSettings do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
41.101449
119
0.744006
93c86255a1b119042ead5a3dd10c6dd20d910fdf
1,541
ex
Elixir
lib/accent/scopes/translations_count.ex
isshindev/accent
ae4c13139b0a0dfd64ff536b94c940a4e2862150
[ "BSD-3-Clause" ]
806
2018-04-07T20:40:33.000Z
2022-03-30T01:39:57.000Z
lib/accent/scopes/translations_count.ex
isshindev/accent
ae4c13139b0a0dfd64ff536b94c940a4e2862150
[ "BSD-3-Clause" ]
194
2018-04-07T13:49:37.000Z
2022-03-30T19:58:45.000Z
lib/accent/scopes/translations_count.ex
doc-ai/accent
e337e16f3658cc0728364f952c0d9c13710ebb06
[ "BSD-3-Clause" ]
89
2018-04-09T13:55:49.000Z
2022-03-24T07:09:31.000Z
defmodule Accent.Scopes.TranslationsCount do import Ecto.Query def with_stats(query, column, options \\ []) do exclude_empty_translations = Keyword.get(options, :exclude_empty_translations, false) translations = from( t in Accent.Translation, select: %{field_id: field(t, ^column), count: count(t)}, where: [removed: false, locked: false], where: is_nil(t.version_id), group_by: field(t, ^column) ) query = query |> count_translations(translations, exclude_empty_translations) |> count_reviewed(translations) from( [translations: t, reviewed: r] in query, select_merge: %{ translations_count: coalesce(t.count, 0), reviewed_count: coalesce(r.count, 0), conflicts_count: coalesce(t.count, 0) - coalesce(r.count, 0) } ) end defp count_translations(query, translations, _exclude_empty_translations = true) do from(q in query, inner_join: translations in subquery(translations), as: :translations, on: translations.field_id == q.id) end defp count_translations(query, translations, _exclude_empty_translations = false) do from(q in query, left_join: translations in subquery(translations), as: :translations, on: translations.field_id == q.id) end defp count_reviewed(query, translations) do reviewed = from(translations, where: [conflicted: false]) from(q in query, left_join: translations in subquery(reviewed), as: :reviewed, on: translations.field_id == q.id) end end
35.022727
126
0.69111
93c86a76148f2a17143db51729a5b954ab166695
282
exs
Elixir
wasmcloud_host/test/wasmcloud_host_web/views/layout_view_test.exs
janitha09/wasmcloud-otp
858d7cbba00233eabf91d96cbcb0d6db80202444
[ "Apache-2.0" ]
84
2021-06-09T16:30:27.000Z
2022-03-27T23:41:25.000Z
wasmcloud_host/test/wasmcloud_host_web/views/layout_view_test.exs
janitha09/wasmcloud-otp
858d7cbba00233eabf91d96cbcb0d6db80202444
[ "Apache-2.0" ]
239
2021-06-07T14:00:09.000Z
2022-03-30T17:06:05.000Z
wasmcloud_host/test/wasmcloud_host_web/views/layout_view_test.exs
janitha09/wasmcloud-otp
858d7cbba00233eabf91d96cbcb0d6db80202444
[ "Apache-2.0" ]
20
2021-06-10T01:10:35.000Z
2022-03-17T15:59:57.000Z
defmodule WasmcloudHostWeb.LayoutViewTest do use WasmcloudHostWeb.ConnCase, async: true # When testing helpers, you may want to import Phoenix.HTML and # use functions such as safe_to_string() to convert the helper # result into an HTML string. # import Phoenix.HTML end
31.333333
65
0.776596
93c87579253855c5428900d670597b6385dcecd4
252
ex
Elixir
testData/org/elixir_lang/parser_definition/issue_1316/List.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
1,668
2015-01-03T05:54:27.000Z
2022-03-25T08:01:20.000Z
testData/org/elixir_lang/parser_definition/issue_1316/List.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
2,018
2015-01-01T22:43:39.000Z
2022-03-31T20:13:08.000Z
testData/org/elixir_lang/parser_definition/issue_1316/List.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
145
2015-01-15T11:37:16.000Z
2021-12-22T05:51:02.000Z
case index do -1 -> list ++ [value] _ when index < 0 -> case length(list) + index + 1 do index when index < 0 -> [value | list] index -> do_insert_at(list, index, value) end _ -> do_insert_at(list, index, value) end
18
47
0.563492
93c8b3de4f2584cb43ea4bab9447f89892f3ee2a
894
exs
Elixir
mix.exs
mwmiller/chacha20_ex
187b489ffc8bb6002dba58f674c135ad51cceb07
[ "MIT" ]
4
2016-02-26T16:32:41.000Z
2020-10-08T02:36:05.000Z
mix.exs
mwmiller/chacha20_ex
187b489ffc8bb6002dba58f674c135ad51cceb07
[ "MIT" ]
null
null
null
mix.exs
mwmiller/chacha20_ex
187b489ffc8bb6002dba58f674c135ad51cceb07
[ "MIT" ]
2
2017-11-05T11:25:36.000Z
2018-01-03T22:41:16.000Z
defmodule Chacha20.Mixfile do use Mix.Project def project do [ app: :chacha20, version: "1.0.2", elixir: "~> 1.7", name: "Chacha20", source_url: "https://github.com/mwmiller/chacha20_ex", build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, description: description(), package: package(), deps: deps() ] end def application do [] end defp deps do [ {:ex_doc, "~> 0.15", only: :dev}, ] end defp description do """ Chacha20 symmetric stream cipher """ end defp package do [ files: ["lib", "mix.exs", "README*", "LICENSE*"], maintainers: ["Matt Miller"], licenses: ["MIT"], links: %{ "GitHub" => "https://github.com/mwmiller/chacha20_ex", "RFC" => "https://tools.ietf.org/html/rfc7539" } ] end end
19.021277
62
0.538031
93c8e6101a04856ffce363951b75686b0a10aebc
11,183
ex
Elixir
clients/docs/lib/google_api/docs/v1/model/request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/docs/lib/google_api/docs/v1/model/request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/docs/lib/google_api/docs/v1/model/request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Docs.V1.Model.Request do @moduledoc """ A single update to apply to a document. ## Attributes * `createFooter` (*type:* `GoogleApi.Docs.V1.Model.CreateFooterRequest.t`, *default:* `nil`) - Creates a footer. * `createFootnote` (*type:* `GoogleApi.Docs.V1.Model.CreateFootnoteRequest.t`, *default:* `nil`) - Creates a footnote. * `createHeader` (*type:* `GoogleApi.Docs.V1.Model.CreateHeaderRequest.t`, *default:* `nil`) - Creates a header. * `createNamedRange` (*type:* `GoogleApi.Docs.V1.Model.CreateNamedRangeRequest.t`, *default:* `nil`) - Creates a named range. * `createParagraphBullets` (*type:* `GoogleApi.Docs.V1.Model.CreateParagraphBulletsRequest.t`, *default:* `nil`) - Creates bullets for paragraphs. * `deleteContentRange` (*type:* `GoogleApi.Docs.V1.Model.DeleteContentRangeRequest.t`, *default:* `nil`) - Deletes content from the document. * `deleteFooter` (*type:* `GoogleApi.Docs.V1.Model.DeleteFooterRequest.t`, *default:* `nil`) - Deletes a footer from the document. * `deleteHeader` (*type:* `GoogleApi.Docs.V1.Model.DeleteHeaderRequest.t`, *default:* `nil`) - Deletes a header from the document. * `deleteNamedRange` (*type:* `GoogleApi.Docs.V1.Model.DeleteNamedRangeRequest.t`, *default:* `nil`) - Deletes a named range. * `deleteParagraphBullets` (*type:* `GoogleApi.Docs.V1.Model.DeleteParagraphBulletsRequest.t`, *default:* `nil`) - Deletes bullets from paragraphs. * `deletePositionedObject` (*type:* `GoogleApi.Docs.V1.Model.DeletePositionedObjectRequest.t`, *default:* `nil`) - Deletes a positioned object from the document. * `deleteTableColumn` (*type:* `GoogleApi.Docs.V1.Model.DeleteTableColumnRequest.t`, *default:* `nil`) - Deletes a column from a table. * `deleteTableRow` (*type:* `GoogleApi.Docs.V1.Model.DeleteTableRowRequest.t`, *default:* `nil`) - Deletes a row from a table. * `insertInlineImage` (*type:* `GoogleApi.Docs.V1.Model.InsertInlineImageRequest.t`, *default:* `nil`) - Inserts an inline image at the specified location. * `insertPageBreak` (*type:* `GoogleApi.Docs.V1.Model.InsertPageBreakRequest.t`, *default:* `nil`) - Inserts a page break at the specified location. * `insertSectionBreak` (*type:* `GoogleApi.Docs.V1.Model.InsertSectionBreakRequest.t`, *default:* `nil`) - Inserts a section break at the specified location. * `insertTable` (*type:* `GoogleApi.Docs.V1.Model.InsertTableRequest.t`, *default:* `nil`) - Inserts a table at the specified location. * `insertTableColumn` (*type:* `GoogleApi.Docs.V1.Model.InsertTableColumnRequest.t`, *default:* `nil`) - Inserts an empty column into a table. * `insertTableRow` (*type:* `GoogleApi.Docs.V1.Model.InsertTableRowRequest.t`, *default:* `nil`) - Inserts an empty row into a table. * `insertText` (*type:* `GoogleApi.Docs.V1.Model.InsertTextRequest.t`, *default:* `nil`) - Inserts text at the specified location. * `mergeTableCells` (*type:* `GoogleApi.Docs.V1.Model.MergeTableCellsRequest.t`, *default:* `nil`) - Merges cells in a table. * `replaceAllText` (*type:* `GoogleApi.Docs.V1.Model.ReplaceAllTextRequest.t`, *default:* `nil`) - Replaces all instances of the specified text. * `replaceImage` (*type:* `GoogleApi.Docs.V1.Model.ReplaceImageRequest.t`, *default:* `nil`) - Replaces an image in the document. * `replaceNamedRangeContent` (*type:* `GoogleApi.Docs.V1.Model.ReplaceNamedRangeContentRequest.t`, *default:* `nil`) - Replaces the content in a named range. * `unmergeTableCells` (*type:* `GoogleApi.Docs.V1.Model.UnmergeTableCellsRequest.t`, *default:* `nil`) - Unmerges cells in a table. * `updateDocumentStyle` (*type:* `GoogleApi.Docs.V1.Model.UpdateDocumentStyleRequest.t`, *default:* `nil`) - Updates the style of the document. * `updateParagraphStyle` (*type:* `GoogleApi.Docs.V1.Model.UpdateParagraphStyleRequest.t`, *default:* `nil`) - Updates the paragraph style at the specified range. * `updateSectionStyle` (*type:* `GoogleApi.Docs.V1.Model.UpdateSectionStyleRequest.t`, *default:* `nil`) - Updates the section style of the specified range. * `updateTableCellStyle` (*type:* `GoogleApi.Docs.V1.Model.UpdateTableCellStyleRequest.t`, *default:* `nil`) - Updates the style of table cells. * `updateTableColumnProperties` (*type:* `GoogleApi.Docs.V1.Model.UpdateTableColumnPropertiesRequest.t`, *default:* `nil`) - Updates the properties of columns in a table. * `updateTableRowStyle` (*type:* `GoogleApi.Docs.V1.Model.UpdateTableRowStyleRequest.t`, *default:* `nil`) - Updates the row style in a table. * `updateTextStyle` (*type:* `GoogleApi.Docs.V1.Model.UpdateTextStyleRequest.t`, *default:* `nil`) - Updates the text style at the specified range. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :createFooter => GoogleApi.Docs.V1.Model.CreateFooterRequest.t(), :createFootnote => GoogleApi.Docs.V1.Model.CreateFootnoteRequest.t(), :createHeader => GoogleApi.Docs.V1.Model.CreateHeaderRequest.t(), :createNamedRange => GoogleApi.Docs.V1.Model.CreateNamedRangeRequest.t(), :createParagraphBullets => GoogleApi.Docs.V1.Model.CreateParagraphBulletsRequest.t(), :deleteContentRange => GoogleApi.Docs.V1.Model.DeleteContentRangeRequest.t(), :deleteFooter => GoogleApi.Docs.V1.Model.DeleteFooterRequest.t(), :deleteHeader => GoogleApi.Docs.V1.Model.DeleteHeaderRequest.t(), :deleteNamedRange => GoogleApi.Docs.V1.Model.DeleteNamedRangeRequest.t(), :deleteParagraphBullets => GoogleApi.Docs.V1.Model.DeleteParagraphBulletsRequest.t(), :deletePositionedObject => GoogleApi.Docs.V1.Model.DeletePositionedObjectRequest.t(), :deleteTableColumn => GoogleApi.Docs.V1.Model.DeleteTableColumnRequest.t(), :deleteTableRow => GoogleApi.Docs.V1.Model.DeleteTableRowRequest.t(), :insertInlineImage => GoogleApi.Docs.V1.Model.InsertInlineImageRequest.t(), :insertPageBreak => GoogleApi.Docs.V1.Model.InsertPageBreakRequest.t(), :insertSectionBreak => GoogleApi.Docs.V1.Model.InsertSectionBreakRequest.t(), :insertTable => GoogleApi.Docs.V1.Model.InsertTableRequest.t(), :insertTableColumn => GoogleApi.Docs.V1.Model.InsertTableColumnRequest.t(), :insertTableRow => GoogleApi.Docs.V1.Model.InsertTableRowRequest.t(), :insertText => GoogleApi.Docs.V1.Model.InsertTextRequest.t(), :mergeTableCells => GoogleApi.Docs.V1.Model.MergeTableCellsRequest.t(), :replaceAllText => GoogleApi.Docs.V1.Model.ReplaceAllTextRequest.t(), :replaceImage => GoogleApi.Docs.V1.Model.ReplaceImageRequest.t(), :replaceNamedRangeContent => GoogleApi.Docs.V1.Model.ReplaceNamedRangeContentRequest.t(), :unmergeTableCells => GoogleApi.Docs.V1.Model.UnmergeTableCellsRequest.t(), :updateDocumentStyle => GoogleApi.Docs.V1.Model.UpdateDocumentStyleRequest.t(), :updateParagraphStyle => GoogleApi.Docs.V1.Model.UpdateParagraphStyleRequest.t(), :updateSectionStyle => GoogleApi.Docs.V1.Model.UpdateSectionStyleRequest.t(), :updateTableCellStyle => GoogleApi.Docs.V1.Model.UpdateTableCellStyleRequest.t(), :updateTableColumnProperties => GoogleApi.Docs.V1.Model.UpdateTableColumnPropertiesRequest.t(), :updateTableRowStyle => GoogleApi.Docs.V1.Model.UpdateTableRowStyleRequest.t(), :updateTextStyle => GoogleApi.Docs.V1.Model.UpdateTextStyleRequest.t() } field(:createFooter, as: GoogleApi.Docs.V1.Model.CreateFooterRequest) field(:createFootnote, as: GoogleApi.Docs.V1.Model.CreateFootnoteRequest) field(:createHeader, as: GoogleApi.Docs.V1.Model.CreateHeaderRequest) field(:createNamedRange, as: GoogleApi.Docs.V1.Model.CreateNamedRangeRequest) field(:createParagraphBullets, as: GoogleApi.Docs.V1.Model.CreateParagraphBulletsRequest) field(:deleteContentRange, as: GoogleApi.Docs.V1.Model.DeleteContentRangeRequest) field(:deleteFooter, as: GoogleApi.Docs.V1.Model.DeleteFooterRequest) field(:deleteHeader, as: GoogleApi.Docs.V1.Model.DeleteHeaderRequest) field(:deleteNamedRange, as: GoogleApi.Docs.V1.Model.DeleteNamedRangeRequest) field(:deleteParagraphBullets, as: GoogleApi.Docs.V1.Model.DeleteParagraphBulletsRequest) field(:deletePositionedObject, as: GoogleApi.Docs.V1.Model.DeletePositionedObjectRequest) field(:deleteTableColumn, as: GoogleApi.Docs.V1.Model.DeleteTableColumnRequest) field(:deleteTableRow, as: GoogleApi.Docs.V1.Model.DeleteTableRowRequest) field(:insertInlineImage, as: GoogleApi.Docs.V1.Model.InsertInlineImageRequest) field(:insertPageBreak, as: GoogleApi.Docs.V1.Model.InsertPageBreakRequest) field(:insertSectionBreak, as: GoogleApi.Docs.V1.Model.InsertSectionBreakRequest) field(:insertTable, as: GoogleApi.Docs.V1.Model.InsertTableRequest) field(:insertTableColumn, as: GoogleApi.Docs.V1.Model.InsertTableColumnRequest) field(:insertTableRow, as: GoogleApi.Docs.V1.Model.InsertTableRowRequest) field(:insertText, as: GoogleApi.Docs.V1.Model.InsertTextRequest) field(:mergeTableCells, as: GoogleApi.Docs.V1.Model.MergeTableCellsRequest) field(:replaceAllText, as: GoogleApi.Docs.V1.Model.ReplaceAllTextRequest) field(:replaceImage, as: GoogleApi.Docs.V1.Model.ReplaceImageRequest) field(:replaceNamedRangeContent, as: GoogleApi.Docs.V1.Model.ReplaceNamedRangeContentRequest) field(:unmergeTableCells, as: GoogleApi.Docs.V1.Model.UnmergeTableCellsRequest) field(:updateDocumentStyle, as: GoogleApi.Docs.V1.Model.UpdateDocumentStyleRequest) field(:updateParagraphStyle, as: GoogleApi.Docs.V1.Model.UpdateParagraphStyleRequest) field(:updateSectionStyle, as: GoogleApi.Docs.V1.Model.UpdateSectionStyleRequest) field(:updateTableCellStyle, as: GoogleApi.Docs.V1.Model.UpdateTableCellStyleRequest) field(:updateTableColumnProperties, as: GoogleApi.Docs.V1.Model.UpdateTableColumnPropertiesRequest ) field(:updateTableRowStyle, as: GoogleApi.Docs.V1.Model.UpdateTableRowStyleRequest) field(:updateTextStyle, as: GoogleApi.Docs.V1.Model.UpdateTextStyleRequest) end defimpl Poison.Decoder, for: GoogleApi.Docs.V1.Model.Request do def decode(value, options) do GoogleApi.Docs.V1.Model.Request.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Docs.V1.Model.Request do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
76.59589
174
0.745954
93c8f4d16f53601723654f9e75123b1d6cf968c8
65
ex
Elixir
apps/console/lib/console/web/views/layout_view.ex
feb29/poly
e64e7a50d1683e1c29acf3d1b6973a3098f5850a
[ "MIT", "Unlicense" ]
null
null
null
apps/console/lib/console/web/views/layout_view.ex
feb29/poly
e64e7a50d1683e1c29acf3d1b6973a3098f5850a
[ "MIT", "Unlicense" ]
null
null
null
apps/console/lib/console/web/views/layout_view.ex
feb29/poly
e64e7a50d1683e1c29acf3d1b6973a3098f5850a
[ "MIT", "Unlicense" ]
null
null
null
defmodule Console.Web.LayoutView do use Console.Web, :view end
16.25
35
0.784615
93c914ccc258a972199a200cccb4f6cd84ece1dc
21,819
ex
Elixir
lib/elixir/lib/protocol.ex
davidsulc/elixir
dd4fd6ab742acd75862e34e26dbdb86e0cf6453f
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/protocol.ex
davidsulc/elixir
dd4fd6ab742acd75862e34e26dbdb86e0cf6453f
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/protocol.ex
davidsulc/elixir
dd4fd6ab742acd75862e34e26dbdb86e0cf6453f
[ "Apache-2.0" ]
null
null
null
defmodule Protocol do @moduledoc """ Functions for working with protocols. """ @doc """ Defines a new protocol function. Protocols do not allow functions to be defined directly, instead, the regular `Kernel.def/*` macros are replaced by this macro which defines the protocol functions with the appropriate callbacks. """ defmacro def(signature) defmacro def({_, _, args}) when args == [] or is_atom(args) do raise ArgumentError, "protocol functions expect at least one argument" end defmacro def({name, _, args}) when is_atom(name) and is_list(args) do arity = length(args) type_args = :lists.map(fn _ -> quote(do: term) end, :lists.seq(2, arity)) type_args = [quote(do: t) | type_args] call_args = :lists.map(fn pos -> Macro.var(String.to_atom("var" <> Integer.to_string(pos)), __MODULE__) end, :lists.seq(2, arity)) call_args = [quote(do: term) | call_args] quote do name = unquote(name) arity = unquote(arity) @functions [{name, arity} | @functions] # Generate a fake definition with the user # signature that will be used by docs Kernel.def unquote(name)(unquote_splicing(args)) # Generate the actual implementation Kernel.def unquote(name)(unquote_splicing(call_args)) do impl_for!(term).unquote(name)(unquote_splicing(call_args)) end # Convert the spec to callback if possible, # otherwise generate a dummy callback Protocol.__spec__?(__MODULE__, name, arity) || @callback unquote(name)(unquote_splicing(type_args)) :: term end end defmacro def(_) do raise ArgumentError, "invalid arguments for def inside defprotocol" end @doc """ Checks if the given module is loaded and is protocol. Returns `:ok` if so, otherwise raises `ArgumentError`. """ @spec assert_protocol!(module) :: :ok | no_return def assert_protocol!(module) do assert_protocol!(module, "") end defp assert_protocol!(module, extra) do case Code.ensure_compiled(module) do {:module, ^module} -> :ok _ -> raise ArgumentError, "#{inspect module} is not available" <> extra end try do module.__protocol__(:module) rescue UndefinedFunctionError -> raise ArgumentError, "#{inspect module} is not a protocol" <> extra end :ok end @doc """ Checks if the given module is loaded and is an implementation of the given protocol. Returns `:ok` if so, otherwise raises `ArgumentError`. """ @spec assert_impl!(module, module) :: :ok | no_return def assert_impl!(protocol, base) do assert_impl!(protocol, base, "") end defp assert_impl!(protocol, base, extra) do impl = Module.concat(protocol, base) case Code.ensure_compiled(impl) do {:module, ^impl} -> :ok _ -> raise ArgumentError, "#{inspect impl} is not available" <> extra end try do impl.__impl__(:protocol) rescue UndefinedFunctionError -> raise ArgumentError, "#{inspect impl} is not an implementation of a protocol" <> extra else ^protocol -> :ok other -> raise ArgumentError, "expected #{inspect impl} to be an implementation of #{inspect protocol}, got: #{inspect other}" <> extra end end @doc """ Derives the `protocol` for `module` with the given options. """ defmacro derive(protocol, module, options \\ []) do quote do module = unquote(module) Protocol.__derive__([{unquote(protocol), unquote(options)}], module, __ENV__) end end ## Consolidation @doc """ Extracts all protocols from the given paths. The paths can be either a charlist or a string. Internally they are worked on as charlists, so passing them as lists avoid extra conversion. Does not load any of the protocols. ## Examples # Get Elixir's ebin and retrieve all protocols iex> path = :code.lib_dir(:elixir, :ebin) iex> mods = Protocol.extract_protocols([path]) iex> Enumerable in mods true """ @spec extract_protocols([charlist | String.t]) :: [atom] def extract_protocols(paths) do extract_matching_by_attribute paths, 'Elixir.', fn module, attributes -> case attributes[:protocol] do [fallback_to_any: _] -> module _ -> nil end end end @doc """ Extracts all types implemented for the given protocol from the given paths. The paths can be either a charlist or a string. Internally they are worked on as charlists, so passing them as lists avoid extra conversion. Does not load any of the implementations. ## Examples # Get Elixir's ebin and retrieve all protocols iex> path = :code.lib_dir(:elixir, :ebin) iex> mods = Protocol.extract_impls(Enumerable, [path]) iex> List in mods true """ @spec extract_impls(module, [charlist | String.t]) :: [atom] def extract_impls(protocol, paths) when is_atom(protocol) do prefix = Atom.to_charlist(protocol) ++ '.' extract_matching_by_attribute paths, prefix, fn _mod, attributes -> case attributes[:protocol_impl] do [protocol: ^protocol, for: for] -> for _ -> nil end end end defp extract_matching_by_attribute(paths, prefix, callback) do for path <- paths, file <- list_dir(path), mod = extract_from_file(path, file, prefix, callback), do: mod end defp list_dir(path) when is_list(path) do case :file.list_dir(path) do {:ok, files} -> files _ -> [] end end defp list_dir(path), do: list_dir(to_charlist(path)) defp extract_from_file(path, file, prefix, callback) do if :lists.prefix(prefix, file) and :filename.extension(file) == '.beam' do extract_from_beam(:filename.join(path, file), callback) end end defp extract_from_beam(file, callback) do case :beam_lib.chunks(file, [:attributes]) do {:ok, {module, [attributes: attributes]}} -> callback.(module, attributes) _ -> nil end end @doc """ Returns `true` if the protocol was consolidated. """ @spec consolidated?(module) :: boolean def consolidated?(protocol) do protocol.__protocol__(:consolidated?) end @doc """ Receives a protocol and a list of implementations and consolidates the given protocol. Consolidation happens by changing the protocol `impl_for` in the abstract format to have fast lookup rules. Usually the list of implementations to use during consolidation are retrieved with the help of `extract_impls/2`. It returns the updated version of the protocol bytecode. A given bytecode or protocol implementation can be checked to be consolidated or not by analyzing the protocol attribute: Protocol.consolidated?(Enumerable) If the first element of the tuple is `true`, it means the protocol was consolidated. This function does not load the protocol at any point nor loads the new bytecode for the compiled module. However each implementation must be available and it will be loaded. """ @spec consolidate(module, [module]) :: {:ok, binary} | {:error, :not_a_protocol} | {:error, :no_beam_info} def consolidate(protocol, types) when is_atom(protocol) do with {:ok, ast_info, chunks_info} <- beam_protocol(protocol), {:ok, code} <- change_debug_info(ast_info, types), do: compile(protocol, code, chunks_info) end defp beam_protocol(protocol) do chunk_ids = [:abstract_code, :attributes, :compile_info, 'ExDc'] opts = [:allow_missing_chunks] case :beam_lib.chunks(beam_file(protocol), chunk_ids, opts) do {:ok, {^protocol, [{:abstract_code, {_raw, abstract_code}}, {:attributes, attributes}, {:compile_info, compile_info}, {'ExDc', docs}]}} -> case attributes[:protocol] do [fallback_to_any: any] -> {:ok, {protocol, any, abstract_code}, {compile_info, docs}} _ -> {:error, :not_a_protocol} end _ -> {:error, :no_beam_info} end end defp beam_file(module) when is_atom(module) do case :code.which(module) do atom when is_atom(atom) -> module file -> file end end # Change the debug information to the optimized # impl_for/1 dispatch version. defp change_debug_info({protocol, any, code}, types) do types = if any, do: types, else: List.delete(types, Any) all = [Any] ++ for {_guard, mod} <- __builtin__(), do: mod structs = types -- all case change_impl_for(code, protocol, types, structs, false, []) do {:ok, ret} -> {:ok, ret} other -> other end end defp change_impl_for([{:function, line, :__protocol__, 1, clauses} | tail], protocol, types, structs, _, acc) do abstract_types = :erl_parse.abstract(:lists.usort(types)) clauses = :lists.map(fn {:clause, l, [{:atom, _, :consolidated?}], [], [{:atom, _, _}]} -> {:clause, l, [{:atom, 0, :consolidated?}], [], [{:atom, 0, true}]} {:clause, l, [{:atom, _, :impls}], [], [{:atom, _, _}]} -> {:clause, l, [{:atom, 0, :impls}], [], [{:tuple, 0, [{:atom, 0, :consolidated}, abstract_types]}]} {:clause, _, _, _, _} = c -> c end, clauses) change_impl_for(tail, protocol, types, structs, true, [{:function, line, :__protocol__, 1, clauses} | acc]) end defp change_impl_for([{:function, line, :impl_for, 1, _} | tail], protocol, types, structs, protocol?, acc) do fallback = if Any in types, do: load_impl(protocol, Any) clauses = for {guard, mod} <- __builtin__(), mod in types, do: builtin_clause_for(mod, guard, protocol, line) clauses = [struct_clause_for(line) | clauses] ++ [fallback_clause_for(fallback, protocol, line)] change_impl_for(tail, protocol, types, structs, protocol?, [{:function, line, :impl_for, 1, clauses} | acc]) end defp change_impl_for([{:function, line, :struct_impl_for, 1, _} | tail], protocol, types, structs, protocol?, acc) do fallback = if Any in types, do: load_impl(protocol, Any) clauses = for struct <- structs, do: each_struct_clause_for(struct, protocol, line) clauses = clauses ++ [fallback_clause_for(fallback, protocol, line)] change_impl_for(tail, protocol, types, structs, protocol?, [{:function, line, :struct_impl_for, 1, clauses} | acc]) end defp change_impl_for([{:attribute, line, :spec, {{:__protocol__, 1}, funspecs}} | tail], protocol, types, structs, protocol?, acc) do new_specs = for spec <- funspecs do case spec do {:type, line, :fun, [{:type, _, :product, [{:atom, _, :consolidated?}]}, _]} -> {:type, line, :fun, [{:type, line, :product, [{:atom, 0, :consolidated?}]}, {:atom, 0, true}]} {:type, line, :fun, [{:type, _, :product, [{:atom, _, :impls}]}, _]} -> impls = for mod <- types, do: {:atom, 0, mod} {:type, line, :fun, [{:type, line, :product, [{:atom, 0, :impls}]}, {:type, 0, :tuple, [{:atom, 0, :consolidated}, {:type, 0, :list, [{:type, 0, :union, impls}]}]}]} other -> other end end change_impl_for(tail, protocol, types, structs, protocol?, [{:attribute, line, :spec, {{:__protocol__, 1}, new_specs}} | acc]) end defp change_impl_for([head | tail], protocol, info, types, protocol?, acc) do change_impl_for(tail, protocol, info, types, protocol?, [head | acc]) end defp change_impl_for([], _protocol, _info, _types, protocol?, acc) do if protocol? do {:ok, Enum.reverse(acc)} else {:error, :not_a_protocol} end end defp builtin_clause_for(mod, guard, protocol, line) do {:clause, line, [{:var, line, :x}], [[{:call, line, {:remote, line, {:atom, line, :erlang}, {:atom, line, guard}}, [{:var, line, :x}], }]], [{:atom, line, load_impl(protocol, mod)}]} end defp struct_clause_for(line) do {:clause, line, [{:map, line, [ {:map_field_exact, line, {:atom, line, :__struct__}, {:var, line, :x}} ]}], [[{:call, line, {:remote, line, {:atom, line, :erlang}, {:atom, line, :is_atom}}, [{:var, line, :x}], }]], [{:call, line, {:atom, line, :struct_impl_for}, [{:var, line, :x}]}]} end defp each_struct_clause_for(struct, protocol, line) do {:clause, line, [{:atom, line, struct}], [], [{:atom, line, load_impl(protocol, struct)}]} end defp fallback_clause_for(value, _protocol, line) do {:clause, line, [{:var, line, :_}], [], [{:atom, line, value}]} end defp load_impl(protocol, for) do Module.concat(protocol, for).__impl__(:target) end # Finally compile the module and emit its bytecode. defp compile(protocol, code, {compile_info, docs}) do opts = Keyword.take(compile_info, [:source]) opts = if Code.compiler_options[:debug_info], do: [:debug_info | opts], else: opts {:ok, ^protocol, binary, _warnings} = :compile.forms(code, [:return | opts]) {:ok, case docs do :missing_chunk -> binary _ -> :elixir_erl.add_beam_chunks(binary, [{"ExDc", docs}]) end} end ## Definition callbacks @doc false def __protocol__(name, [do: block]) do quote do defmodule unquote(name) do # We don't allow function definition inside protocols import Kernel, except: [ defmacrop: 1, defmacrop: 2, defmacro: 1, defmacro: 2, defp: 1, defp: 2, def: 1, def: 2 ] # Import the new dsl that holds the new def import Protocol, only: [def: 1] # Compile with debug info for consolidation @compile :debug_info # Set up a clear slate to store defined functions @functions [] @fallback_to_any false # Invoke the user given block _ = unquote(block) # Finalize expansion unquote(after_defprotocol()) end end end defp after_defprotocol do quote bind_quoted: [builtin: __builtin__()] do @doc false @spec impl_for(term) :: atom | nil Kernel.def impl_for(data) # Define the implementation for structs. # # It simply delegates to struct_impl_for which is then # optimized during protocol consolidation. Kernel.def impl_for(%{__struct__: struct}) when :erlang.is_atom(struct) do struct_impl_for(struct) end # Define the implementation for built-ins :lists.foreach(fn {guard, mod} -> target = Module.concat(__MODULE__, mod) Kernel.def impl_for(data) when :erlang.unquote(guard)(data) do case impl_for?(unquote(target)) do true -> unquote(target).__impl__(:target) false -> any_impl_for() end end end, builtin) # Define a catch-all impl_for/1 clause to pacify Dialyzer (since # destructuring opaque types is illegal, Dialyzer will think none of the # previous clauses matches opaque types, and without this clause, will # conclude that impl_for can't handle an opaque argument). This is a hack # since it relies on Dialyzer not being smart enough to conclude that all # opaque types will get the any_impl_for/0 implementation. Kernel.def impl_for(_) do any_impl_for() end @doc false @spec impl_for!(term) :: atom | no_return Kernel.def impl_for!(data) do impl_for(data) || raise(Protocol.UndefinedError, protocol: __MODULE__, value: data) end # Internal handler for Any if @fallback_to_any do Kernel.defp any_impl_for(), do: __MODULE__.Any.__impl__(:target) else Kernel.defp any_impl_for(), do: nil end # Internal handler for Structs Kernel.defp struct_impl_for(struct) do target = Module.concat(__MODULE__, struct) case impl_for?(target) do true -> target.__impl__(:target) false -> any_impl_for() end end # Check if compilation is available internally Kernel.defp impl_for?(target) do Code.ensure_compiled?(target) and function_exported?(target, :__impl__, 1) end # Inline any and struct implementations @compile {:inline, any_impl_for: 0, struct_impl_for: 1, impl_for?: 1} unless Kernel.Typespec.defines_type?(__MODULE__, :t, 0) do @type t :: term end # Store information as an attribute so it # can be read without loading the module. Module.register_attribute(__MODULE__, :protocol, persist: true) @protocol [fallback_to_any: !!@fallback_to_any] @doc false @spec __protocol__(:module) :: __MODULE__ @spec __protocol__(:functions) :: unquote(Protocol.__functions_spec__(@functions)) @spec __protocol__(:consolidated?) :: false @spec __protocol__(:impls) :: :not_consolidated Kernel.def __protocol__(:module), do: __MODULE__ Kernel.def __protocol__(:functions), do: unquote(:lists.sort(@functions)) Kernel.def __protocol__(:consolidated?), do: false Kernel.def __protocol__(:impls), do: :not_consolidated end end @doc false def __functions_spec__([]), do: [] def __functions_spec__([head | tail]), do: [:lists.foldl(&{:|, [], [&1, &2]}, head, tail), quote(do: ...)] @doc false def __impl__(protocol, opts) do do_defimpl(protocol, :lists.keysort(1, opts)) end defp do_defimpl(protocol, [do: block, for: for]) when is_list(for) do for f <- for, do: do_defimpl(protocol, [do: block, for: f]) end defp do_defimpl(protocol, [do: block, for: for]) do # Unquote the implementation just later # when all variables will already be injected # into the module body. impl = quote unquote: false do @doc false @spec __impl__(:for) :: unquote(for) @spec __impl__(:target) :: __MODULE__ @spec __impl__(:protocol) :: unquote(protocol) def __impl__(:for), do: unquote(for) def __impl__(:target), do: __MODULE__ def __impl__(:protocol), do: unquote(protocol) end quote do protocol = unquote(protocol) for = unquote(for) name = Module.concat(protocol, for) Protocol.assert_protocol!(protocol) Protocol.__ensure_defimpl__(protocol, for, __ENV__) defmodule name do @behaviour protocol @protocol protocol @for for unquote(block) Module.register_attribute(__MODULE__, :protocol_impl, persist: true) @protocol_impl [protocol: @protocol, for: @for] unquote(impl) end end end @doc false def __derive__(derives, for, %Macro.Env{} = env) when is_atom(for) do struct = if for == env.module do Module.get_attribute(for, :struct) || raise "struct is not defined for #{inspect for}" else for.__struct__ end :lists.foreach(fn proto when is_atom(proto) -> derive(proto, for, struct, [], env) {proto, opts} when is_atom(proto) -> derive(proto, for, struct, opts, env) end, :lists.flatten(derives)) :ok end defp derive(protocol, for, struct, opts, env) do extra = ", cannot derive #{inspect protocol} for #{inspect for}" assert_protocol!(protocol, extra) __ensure_defimpl__(protocol, for, env) assert_impl!(protocol, Any, extra) # Clean up variables from eval context env = %{env | vars: [], export_vars: nil} args = [for, struct, opts] impl = Module.concat(protocol, Any) :elixir_module.expand_callback(env.line, impl, :__deriving__, args, env, fn mod, fun, args -> if function_exported?(mod, fun, length(args)) do apply(mod, fun, args) else Module.create(Module.concat(protocol, for), quote do Module.register_attribute(__MODULE__, :protocol_impl, persist: true) @protocol_impl [protocol: unquote(protocol), for: unquote(for)] @doc false @spec __impl__(:target) :: unquote(impl) @spec __impl__(:protocol) :: unquote(protocol) @spec __impl__(:for) :: unquote(for) def __impl__(:target), do: unquote(impl) def __impl__(:protocol), do: unquote(protocol) def __impl__(:for), do: unquote(for) end, Macro.Env.location(env)) end end) end @doc false def __ensure_defimpl__(protocol, for, env) do if Protocol.consolidated?(protocol) do message = "the #{inspect protocol} protocol has already been consolidated" <> ", an implementation for #{inspect for} has no effect" :elixir_errors.warn(env.line, env.file, message) end :ok end @doc false def __spec__?(module, name, arity) do signature = {name, arity} specs = Module.get_attribute(module, :spec) found = :lists.map(fn {:spec, expr, pos} -> if Kernel.Typespec.spec_to_signature(expr) == signature do Module.store_typespec(module, :callback, {:callback, expr, pos}) true end end, specs) :lists.any(& &1 == true, found) end ## Helpers @doc false def __builtin__ do [is_tuple: Tuple, is_atom: Atom, is_list: List, is_map: Map, is_bitstring: BitString, is_integer: Integer, is_float: Float, is_function: Function, is_pid: PID, is_port: Port, is_reference: Reference] end end
31.667634
135
0.622897
93c9503a1606ee968670d42654321bfa93953f09
1,856
exs
Elixir
test/app/punches_test.exs
mzgajner/smena
6c0243ae1e8d1cef6e8a8e240f0f6b703ea638c9
[ "Unlicense" ]
null
null
null
test/app/punches_test.exs
mzgajner/smena
6c0243ae1e8d1cef6e8a8e240f0f6b703ea638c9
[ "Unlicense" ]
null
null
null
test/app/punches_test.exs
mzgajner/smena
6c0243ae1e8d1cef6e8a8e240f0f6b703ea638c9
[ "Unlicense" ]
null
null
null
defmodule Smena.PunchesTest do use Smena.DataCase alias Smena.Punches describe "punches" do alias Smena.Punches.Punch @valid_attrs %{in: true} @update_attrs %{in: false} @invalid_attrs %{in: nil} def punch_fixture(attrs \\ %{}) do {:ok, punch} = attrs |> Enum.into(@valid_attrs) |> Punches.create_punch() punch end test "list_punches/0 returns all punches" do punch = punch_fixture() assert Punches.list_punches() == [punch] end test "get_punch!/1 returns the punch with given id" do punch = punch_fixture() assert Punches.get_punch!(punch.id) == punch end test "create_punch/1 with valid data creates a punch" do assert {:ok, %Punch{} = punch} = Punches.create_punch(@valid_attrs) assert punch.in == true end test "create_punch/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Punches.create_punch(@invalid_attrs) end test "update_punch/2 with valid data updates the punch" do punch = punch_fixture() assert {:ok, %Punch{} = punch} = Punches.update_punch(punch, @update_attrs) assert punch.in == false end test "update_punch/2 with invalid data returns error changeset" do punch = punch_fixture() assert {:error, %Ecto.Changeset{}} = Punches.update_punch(punch, @invalid_attrs) assert punch == Punches.get_punch!(punch.id) end test "delete_punch/1 deletes the punch" do punch = punch_fixture() assert {:ok, %Punch{}} = Punches.delete_punch(punch) assert_raise Ecto.NoResultsError, fn -> Punches.get_punch!(punch.id) end end test "change_punch/1 returns a punch changeset" do punch = punch_fixture() assert %Ecto.Changeset{} = Punches.change_punch(punch) end end end
28.553846
86
0.655711
93c953680c186e1cc9a92958d2d3b485ab8ec89e
1,804
exs
Elixir
test/integration/strategies/threaded_nif_test.exs
wojtekmach/zigler
b2102744bff212351abfeb4f6d87e57dd1ab232c
[ "MIT" ]
null
null
null
test/integration/strategies/threaded_nif_test.exs
wojtekmach/zigler
b2102744bff212351abfeb4f6d87e57dd1ab232c
[ "MIT" ]
null
null
null
test/integration/strategies/threaded_nif_test.exs
wojtekmach/zigler
b2102744bff212351abfeb4f6d87e57dd1ab232c
[ "MIT" ]
null
null
null
defmodule ZiglerTest.Integration.Strategies.ThreadedNifTest do use ExUnit.Case, async: true use Zig @moduletag :threaded ~Z""" /// nif: threaded_forty_seven/0 threaded fn threaded_forty_seven() i32 { // sleep for 2 seconds std.time.sleep(2000000000); return 47; } """ test "threaded nifs can sleep for a while" do start = DateTime.utc_now assert 47 == threaded_forty_seven() elapsed = DateTime.utc_now |> DateTime.diff(start) assert elapsed >= 2 and elapsed < 4 verify_cleanup() end ~Z""" /// nif: threaded_void/1 threaded fn threaded_void(env: beam.env, parent: beam.pid) void { // sleep for 50 ms std.time.sleep(50000000); _ = beam.send(env, parent, beam.make_atom(env, "threaded")); } """ test "threaded nifs can have a void return and parameters" do assert :ok = threaded_void(self()) assert_receive :threaded verify_cleanup() end ~Z""" /// nif: threaded_sum/1 threaded fn threaded_sum(list: []i64) i64 { var result : i64 = 0; for (list) | val | { result += val; } return result; } """ test "threaded nifs can have an slice input" do assert 5050 == 1..100 |> Enum.to_list |> threaded_sum verify_cleanup() end ~Z""" /// nif: threaded_string/1 threaded fn threaded_string(str: []u8) usize { return str.len; } """ test "threaded nifs can have an string input" do assert 6 = threaded_string("foobar") verify_cleanup() end test "if you pass an incorrect value in you get fce" do assert_raise FunctionClauseError, fn -> threaded_string(:foobar) end verify_cleanup() end def verify_cleanup do :erlang.garbage_collect(self()) # debug message from the cleanup process assert_receive :thread_freed end end
21.73494
64
0.656319
93c956ba2a11209a3e0b172cf3c475bcaf52dbaf
1,260
ex
Elixir
lib/absinthe/language/fragment.ex
maartenvanvliet/absinthe
ebe820717200f53756e225b3dffbfefe924a94d3
[ "MIT" ]
null
null
null
lib/absinthe/language/fragment.ex
maartenvanvliet/absinthe
ebe820717200f53756e225b3dffbfefe924a94d3
[ "MIT" ]
2
2018-08-02T13:35:38.000Z
2018-08-02T13:36:42.000Z
lib/absinthe/language/fragment.ex
jlgeering/absinthe
a3dbc29640d613928398626ad75a8f03203a1720
[ "MIT" ]
null
null
null
defmodule Absinthe.Language.Fragment do @moduledoc false alias Absinthe.{Blueprint, Language} defstruct name: nil, type_condition: nil, directives: [], selection_set: nil, loc: %{start_line: nil} @type t :: %__MODULE__{ name: String.t(), type_condition: nil | Language.NamedType.t(), directives: [Language.Directive.t()], selection_set: Language.SelectionSet.t(), loc: Language.loc_t() } defimpl Blueprint.Draft do def convert(node, doc) do %Blueprint.Document.Fragment.Named{ name: node.name, type_condition: Blueprint.Draft.convert(node.type_condition, doc), selections: Blueprint.Draft.convert(node.selection_set.selections, doc), directives: Blueprint.Draft.convert(node.directives, doc), source_location: source_location(node.loc) } end defp source_location(nil) do nil end defp source_location(%{start_line: number}) do Blueprint.Document.SourceLocation.at(number) end end defimpl Absinthe.Traversal.Node do def children(node, _schema) do [node.directives, List.wrap(node.selection_set)] |> Enum.concat() end end end
26.808511
80
0.639683
93c96a1857f964f9f78044d8ec25d214f8b66cf0
6,577
ex
Elixir
lib/zig/command.ex
skunkwerks/zigler
9acd7b97dddecc87de7754e23e6f08d855b2c855
[ "MIT" ]
1
2021-02-26T00:00:34.000Z
2021-02-26T00:00:34.000Z
lib/zig/command.ex
fhunleth/zigler
037ff05087563d3255f58fb0abbaedeb12b97211
[ "MIT" ]
null
null
null
lib/zig/command.ex
fhunleth/zigler
037ff05087563d3255f58fb0abbaedeb12b97211
[ "MIT" ]
null
null
null
defmodule Zig.Command do @moduledoc """ contains all parts of the Zig library involved in calling the zig compiler toolchain, especially with regards to the `zig` command, except for assembling the build.zig file, which is performed by the `Zig.Builder` module. """ alias Zig.{Builder, Patches} require Logger ############################################################################# ## API def compile(compiler, zig_tree) do zig_executable = if compiler.module_spec.local_zig do System.find_executable("zig") else # apply patches, if applicable Patches.sync(zig_tree) Path.join(zig_tree, "zig") end opts = [cd: compiler.assembly_dir, stderr_to_stdout: true] Logger.debug("compiling nif for module #{inspect compiler.module_spec.module} in path #{compiler.assembly_dir}") Builder.build(compiler, zig_tree) case System.cmd(zig_executable, ["build"], opts) do {_, 0} -> :ok {err, _} -> alias Zig.Parser.Error Error.parse(err, compiler) end lib_dir = compiler.module_spec.otp_app |> :code.lib_dir() |> Path.join("ebin") library_filename = Zig.nif_name(compiler.module_spec) # copy the compiled library over to the lib/nif directory. File.mkdir_p!(lib_dir) compiler.assembly_dir |> Path.join("zig-cache/lib/#{library_filename}") |> File.cp!(Path.join(lib_dir, library_filename)) # link the compiled library to be unversioned. symlink_filename = Path.join(lib_dir, "#{library_filename}") unless File.exists?(symlink_filename) do lib_dir |> Path.join(library_filename) |> File.ln_s!(symlink_filename) end :ok end ############################################################################# ## download zig from online sources. @doc false def version_name(version) do "zig-#{get_os()}-#{get_arch()}-#{version}" end def get_os do case :os.type do {:unix, :linux} -> "linux" {:unix, :freebsd} -> "freebsd" {:unix, :darwin} -> Logger.warn("macos support is experimental") "macos" {_, :nt} -> windows_warn() "windows" end end @arches %{ "i386" => "i386", "i486" => "i386", "i586" => "i386", "x86_64" => "x86_64", "armv6" => "armv6kz", "armv7" => "armv7a", "aarch64" => "aarch64", "amd64" => "x86_64", "win32" => "i386", "win64" => "x86_64" } # note this is the architecture of the machine where compilation is # being done, not the target architecture of cross-compiled def get_arch do arch = :system_architecture |> :erlang.system_info() |> List.to_string() Enum.find_value(@arches, fn {prefix, zig_arch} -> if String.starts_with?(arch, prefix), do: zig_arch end) || raise arch_warn() end defp arch_warn, do: """ it seems like you are compiling from an unsupported architecture: #{ :erlang.system_info(:system_architecture) } Please leave an issue at https://github.com/ityonemo/zigler/issues """ defp windows_warn do Logger.warn(""" windows is not supported, but may work. If you find an error in the process, please leave an issue at: https://github.com/ityonemo/zigler/issues """) end @zig_dir_path Path.expand("../../zig", Path.dirname(__ENV__.file)) def fetch(version) do zig_dir = Path.join(@zig_dir_path, version_name(version)) zig_executable = Path.join(zig_dir, "zig") :global.set_lock({__MODULE__, self()}) unless File.exists?(zig_executable) do # make sure the zig directory path exists and is ready. File.mkdir_p!(@zig_dir_path) # make sure that we're in the correct operating system. extension = if match?({_, :nt}, :os.type()) do ".zip" else ".tar.xz" end archive = version_name(version) <> extension Logger.configure(level: :info) zig_download_path = Path.join(@zig_dir_path, archive) download_zig_archive(zig_download_path, version, archive) # untar the zig directory. unarchive_zig(archive) end :global.del_lock({__MODULE__, self()}) end # https://ziglang.org/download/#release-0.7.1 @checksums %{ "zig-freebsd-x86_64-0.7.1.tar.xz" => "e73c1dca35791a3183fdd5ecde0443ebbe180942efceafe651886034fb8def09", "zig-linux-aarch64-0.7.1.tar.xz" => "48ec90eba407e4587ddef7eecef25fec7e13587eb98e3b83c5f2f5fff2a5cbe7", "zig-linux-armv7a-0.7.1.tar.xz" => "5a0662e07b4c4968665e1f97558f8591f6facec45d2e0ff5715e661743107ceb", "zig-linux-i386-0.7.1.tar.xz" => "4882e052e5f83690bd0334bb4fc1702b5403cb3a3d2aa63fd7d6043d8afecba3", "zig-linux-riscv64-0.7.1.tar.xz" => "187294bfd35983348c3fe042901b42e67e7e36ab7f77a5f969d21c0051f4d21f", "zig-linux-x86_64-0.7.1.tar.xz" => "18c7b9b200600f8bcde1cd8d7f1f578cbc3676241ce36d771937ce19a8159b8d", "zig-macos-x86_64-0.7.1.tar.xz" => "845cb17562978af0cf67e3993f4e33330525eaf01ead9386df9105111e3bc519", "zig-windows-i386-0.7.1.zip" => "a1b9a7421e13153e07fd2e2c93ff29aad64d83105b8fcdafa633dbe689caf1c0", "zig-windows-x86_64-0.7.1.zip" => "4818a8a65b4672bc52c0ae7f14d014e0eb8caf10f12c0745176820384cea296a" } defp download_zig_archive(zig_download_path, version, archive) do url = "https://ziglang.org/download/#{version}/#{archive}" Logger.info("downloading zig version #{version} (#{url}) and caching in #{@zig_dir_path}.") case httpc_get(url) do {:ok, %{status: 200, body: body}} -> expected_checksum = Map.fetch!(@checksums, archive) actual_checksum = :sha256 |> :crypto.hash(body) |> Base.encode16(case: :lower) if expected_checksum != actual_checksum do raise "checksum mismatch: expected #{expected_checksum}, got #{actual_checksum}" end File.write!(zig_download_path, body) _ -> raise "failed to download the appropriate zig archive." end end defp httpc_get(url) do {:ok, _} = Application.ensure_all_started(:ssl) {:ok, _} = Application.ensure_all_started(:inets) headers = [] request = {String.to_charlist(url), headers} http_options = [timeout: 600_000] options = [body_format: :binary] case :httpc.request(:get, request, http_options, options) do {:ok, {{_, status, _}, headers, body}} -> {:ok, %{status: status, headers: headers, body: body}} other -> other end end def unarchive_zig(archive) do System.cmd("tar", ["xvf", archive], cd: @zig_dir_path) end end
31.319048
116
0.646191
93c97f1ad15206bd88be78221047b8f45d67ec89
178
ex
Elixir
lib/xqlite/driver.ex
OvermindDL1/xqlite
987f11e4ba9134239d1fe1a2cfc55f49090a72be
[ "MIT" ]
null
null
null
lib/xqlite/driver.ex
OvermindDL1/xqlite
987f11e4ba9134239d1fe1a2cfc55f49090a72be
[ "MIT" ]
null
null
null
lib/xqlite/driver.ex
OvermindDL1/xqlite
987f11e4ba9134239d1fe1a2cfc55f49090a72be
[ "MIT" ]
null
null
null
defmodule Xqlite.Driver do @callback open(Xqlite.db_name(), Xqlite.opts()) :: Xqlite.open_result() @callback close(Xqlite.conn(), Xqlite.opts()) :: Xqlite.close_result() end
35.6
73
0.724719
93c9af13b70bd9d07842fac642c49274f4b1caa2
110
ex
Elixir
lib/rdf/guards.ex
pukkamustard/rdf-ex
c459d8e7fa548fdfad82643338b68decf380a296
[ "MIT" ]
19
2020-06-05T16:55:54.000Z
2022-03-22T10:30:11.000Z
lib/rdf/guards.ex
pukkamustard/rdf-ex
c459d8e7fa548fdfad82643338b68decf380a296
[ "MIT" ]
4
2020-07-03T21:02:55.000Z
2021-11-18T07:22:06.000Z
lib/rdf/guards.ex
pukkamustard/rdf-ex
c459d8e7fa548fdfad82643338b68decf380a296
[ "MIT" ]
3
2020-07-03T13:25:36.000Z
2021-04-04T12:33:51.000Z
defmodule RDF.Guards do import RDF.Utils.Guards defguard maybe_ns_term(term) when maybe_module(term) end
18.333333
54
0.8
93c9dd4e4cf1e8e45d13a6f1ef581a9f2b60f477
35,571
ex
Elixir
clients/file/lib/google_api/file/v1/api/projects.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/file/lib/google_api/file/v1/api/projects.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/file/lib/google_api/file/v1/api/projects.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.File.V1.Api.Projects do @moduledoc """ API calls for all endpoints tagged `Projects`. """ alias GoogleApi.File.V1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Gets information about a location. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Resource name for the location. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Location{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_get(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.File.V1.Model.Location.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def file_projects_locations_get(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Location{}]) end @doc """ Lists information about the supported locations for this service. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The resource that owns the locations collection, if applicable. * `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"). * `:filter` (*type:* `String.t`) - The standard list filter. * `:includeUnrevealedLocations` (*type:* `boolean()`) - If true, the returned list will include locations which are not yet revealed. * `:pageSize` (*type:* `integer()`) - The standard list page size. * `:pageToken` (*type:* `String.t`) - The standard list page token. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.ListLocationsResponse{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.File.V1.Model.ListLocationsResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def file_projects_locations_list(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :includeUnrevealedLocations => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}/locations", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.ListLocationsResponse{}]) end @doc """ Creates an instance. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The instance's project and location, in the format projects/{project_id}/locations/{location}. In Cloud Filestore, locations map to GCP zones, for example **us-west1-b**. * `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"). * `:instanceId` (*type:* `String.t`) - Required. The name of the instance to create. The name must be unique for the specified project and location. * `:body` (*type:* `GoogleApi.File.V1.Model.Instance.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_instances_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def file_projects_locations_instances_create( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :instanceId => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+parent}/instances", %{ "parent" => URI.encode(parent, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Operation{}]) end @doc """ Deletes an instance. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The instance resource name, in the format projects/{project_id}/locations/{location}/instances/{instance_id} * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_instances_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def file_projects_locations_instances_delete( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Operation{}]) end @doc """ Gets the details of a specific instance. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The instance resource name, in the format projects/{project_id}/locations/{location}/instances/{instance_id}. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Instance{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_instances_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Instance.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def file_projects_locations_instances_get(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Instance{}]) end @doc """ Lists all instances in a project for either a specified location or for all locations. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The project and location for which to retrieve instance information, in the format projects/{project_id}/locations/{location}. In Cloud Filestore, locations map to GCP zones, for example **us-west1-b**. To retrieve instance information for all locations, use "-" for the {location} value. * `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"). * `:filter` (*type:* `String.t`) - List filter. * `:orderBy` (*type:* `String.t`) - Sort results. Supported values are "name", "name desc" or "" (unsorted). * `:pageSize` (*type:* `integer()`) - The maximum number of items to return. * `:pageToken` (*type:* `String.t`) - The next_page_token value to use if there are additional results to retrieve for this list request. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.ListInstancesResponse{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_instances_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.ListInstancesResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def file_projects_locations_instances_list( connection, parent, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :orderBy => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+parent}/instances", %{ "parent" => URI.encode(parent, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.ListInstancesResponse{}]) end @doc """ Updates the settings of a specific instance. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Output only. The resource name of the instance, in the format projects/{project}/locations/{location}/instances/{instance}. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:updateMask` (*type:* `String.t`) - Mask of fields to update. At least one path must be supplied in this field. The elements of the repeated paths field may only include these fields: * "description" * "file_shares" * "labels" * `:body` (*type:* `GoogleApi.File.V1.Model.Instance.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_instances_patch( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def file_projects_locations_instances_patch(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :updateMask => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Operation{}]) end @doc """ Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource to be cancelled. * `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.File.V1.Model.CancelOperationRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_operations_cancel( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def file_projects_locations_operations_cancel( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+name}:cancel", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Empty{}]) end @doc """ Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource to be deleted. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_operations_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def file_projects_locations_operations_delete( connection, name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Empty{}]) end @doc """ Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_operations_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def file_projects_locations_operations_get(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.Operation{}]) end @doc """ Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. To override the binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id. ## Parameters * `connection` (*type:* `GoogleApi.File.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation's parent resource. * `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"). * `:filter` (*type:* `String.t`) - The standard list filter. * `:pageSize` (*type:* `integer()`) - The standard list page size. * `:pageToken` (*type:* `String.t`) - The standard list page token. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.File.V1.Model.ListOperationsResponse{}}` on success * `{:error, info}` on failure """ @spec file_projects_locations_operations_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.File.V1.Model.ListOperationsResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def file_projects_locations_operations_list(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}/operations", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.File.V1.Model.ListOperationsResponse{}]) end end
47.051587
607
0.617722
93c9eb99d6b470990eca9f6109b5ce6d235343b3
1,790
exs
Elixir
test/concentrate/stop_time_update_test.exs
mbta/concentrate
bae6e05713ed079b7da53867a01dd007861fb656
[ "MIT" ]
19
2018-01-22T18:39:20.000Z
2022-02-22T16:15:30.000Z
test/concentrate/stop_time_update_test.exs
mbta/concentrate
bae6e05713ed079b7da53867a01dd007861fb656
[ "MIT" ]
216
2018-01-22T14:22:39.000Z
2022-03-31T10:30:31.000Z
test/concentrate/stop_time_update_test.exs
mbta/concentrate
bae6e05713ed079b7da53867a01dd007861fb656
[ "MIT" ]
5
2018-01-22T14:18:15.000Z
2021-04-26T18:34:19.000Z
defmodule Concentrate.StopTimeUpdateTest do @moduledoc false use ExUnit.Case import Concentrate.StopTimeUpdate alias Concentrate.Mergeable @stu new( trip_id: "trip", stop_sequence: 1, arrival_time: 2, departure_time: 3, status: "status", platform_id: "platform" ) describe "skip/1" do test "removes the times/status" do skipped = skip(@stu) assert time(skipped) == nil assert status(skipped) == nil end test "sets the relationship to SKIPPED" do skipped = skip(@stu) assert schedule_relationship(skipped) == :SKIPPED end end describe "Concentrate.Mergeable" do test "takes non-nil values, earliest arrival, latest departure" do first = @stu second = new( trip_id: "trip", stop_id: "stop", stop_sequence: 1, arrival_time: 1, departure_time: 4, track: "track", schedule_relationship: :SKIPPED, uncertainty: 300 ) expected = new( trip_id: "trip", stop_id: "stop", stop_sequence: 1, arrival_time: 1, departure_time: 4, status: "status", track: "track", schedule_relationship: :SKIPPED, platform_id: "platform", uncertainty: 300 ) assert Mergeable.merge(first, second) == expected assert Mergeable.merge(second, first) == expected end test "picks the 'greater' of two stop IDs" do first = new(stop_id: "stop") second = new(stop_id: "stop-01") assert %{stop_id: "stop-01"} = Mergeable.merge(first, second) assert %{stop_id: "stop-01"} = Mergeable.merge(second, first) end end end
24.861111
70
0.578212
93ca3a51f3085f31b6e135610cf0d67159ec96a5
6,433
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/network_endpoint_group.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/network_endpoint_group.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/network_endpoint_group.ex
MMore/elixir-google-api
0574ec1439d9bbfe22d63965be1681b0f45a94c9
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Compute.V1.Model.NetworkEndpointGroup do @moduledoc """ Represents a collection of network endpoints. A network endpoint group (NEG) defines how a set of endpoints should be reached, whether they are reachable, and where they are located. For more information about using NEGs, see Setting up external HTTP(S) Load Balancing with internet NEGs, Setting up zonal NEGs, or Setting up external HTTP(S) Load Balancing with serverless NEGs. ## Attributes * `annotations` (*type:* `map()`, *default:* `nil`) - Metadata defined as annotations on the network endpoint group. * `appEngine` (*type:* `GoogleApi.Compute.V1.Model.NetworkEndpointGroupAppEngine.t`, *default:* `nil`) - Only valid when networkEndpointType is "SERVERLESS". Only one of cloudRun, appEngine or cloudFunction may be set. * `cloudFunction` (*type:* `GoogleApi.Compute.V1.Model.NetworkEndpointGroupCloudFunction.t`, *default:* `nil`) - Only valid when networkEndpointType is "SERVERLESS". Only one of cloudRun, appEngine or cloudFunction may be set. * `cloudRun` (*type:* `GoogleApi.Compute.V1.Model.NetworkEndpointGroupCloudRun.t`, *default:* `nil`) - Only valid when networkEndpointType is "SERVERLESS". Only one of cloudRun, appEngine or cloudFunction may be set. * `creationTimestamp` (*type:* `String.t`, *default:* `nil`) - [Output Only] Creation timestamp in RFC3339 text format. * `defaultPort` (*type:* `integer()`, *default:* `nil`) - The default port used if the port number is not specified in the network endpoint. * `description` (*type:* `String.t`, *default:* `nil`) - An optional description of this resource. Provide this property when you create the resource. * `id` (*type:* `String.t`, *default:* `nil`) - [Output Only] The unique identifier for the resource. This identifier is defined by the server. * `kind` (*type:* `String.t`, *default:* `compute#networkEndpointGroup`) - [Output Only] Type of the resource. Always compute#networkEndpointGroup for network endpoint group. * `name` (*type:* `String.t`, *default:* `nil`) - Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. * `network` (*type:* `String.t`, *default:* `nil`) - The URL of the network to which all network endpoints in the NEG belong. Uses "default" project network if unspecified. * `networkEndpointType` (*type:* `String.t`, *default:* `nil`) - Type of network endpoints in this network endpoint group. Can be one of GCE_VM_IP, GCE_VM_IP_PORT, NON_GCP_PRIVATE_IP_PORT, INTERNET_FQDN_PORT, INTERNET_IP_PORT, SERVERLESS, PRIVATE_SERVICE_CONNECT. * `pscTargetService` (*type:* `String.t`, *default:* `nil`) - The target service url used to set up private service connection to a Google API. An example value is: "asia-northeast3-cloudkms.googleapis.com" * `region` (*type:* `String.t`, *default:* `nil`) - [Output Only] The URL of the region where the network endpoint group is located. * `selfLink` (*type:* `String.t`, *default:* `nil`) - [Output Only] Server-defined URL for the resource. * `size` (*type:* `integer()`, *default:* `nil`) - [Output only] Number of network endpoints in the network endpoint group. * `subnetwork` (*type:* `String.t`, *default:* `nil`) - Optional URL of the subnetwork to which all network endpoints in the NEG belong. * `zone` (*type:* `String.t`, *default:* `nil`) - [Output Only] The URL of the zone where the network endpoint group is located. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :annotations => map() | nil, :appEngine => GoogleApi.Compute.V1.Model.NetworkEndpointGroupAppEngine.t() | nil, :cloudFunction => GoogleApi.Compute.V1.Model.NetworkEndpointGroupCloudFunction.t() | nil, :cloudRun => GoogleApi.Compute.V1.Model.NetworkEndpointGroupCloudRun.t() | nil, :creationTimestamp => String.t() | nil, :defaultPort => integer() | nil, :description => String.t() | nil, :id => String.t() | nil, :kind => String.t() | nil, :name => String.t() | nil, :network => String.t() | nil, :networkEndpointType => String.t() | nil, :pscTargetService => String.t() | nil, :region => String.t() | nil, :selfLink => String.t() | nil, :size => integer() | nil, :subnetwork => String.t() | nil, :zone => String.t() | nil } field(:annotations, type: :map) field(:appEngine, as: GoogleApi.Compute.V1.Model.NetworkEndpointGroupAppEngine) field(:cloudFunction, as: GoogleApi.Compute.V1.Model.NetworkEndpointGroupCloudFunction) field(:cloudRun, as: GoogleApi.Compute.V1.Model.NetworkEndpointGroupCloudRun) field(:creationTimestamp) field(:defaultPort) field(:description) field(:id) field(:kind) field(:name) field(:network) field(:networkEndpointType) field(:pscTargetService) field(:region) field(:selfLink) field(:size) field(:subnetwork) field(:zone) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.NetworkEndpointGroup do def decode(value, options) do GoogleApi.Compute.V1.Model.NetworkEndpointGroup.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.NetworkEndpointGroup do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
64.979798
490
0.706047
93ca454c02cf39e70e692e75bfc37ec83f2275e7
497
ex
Elixir
apps/tai/lib/tai/events/venue_boot_error.ex
chrism2671/tai-1
847827bd23908adfad4a82c83d5295bdbc022796
[ "MIT" ]
null
null
null
apps/tai/lib/tai/events/venue_boot_error.ex
chrism2671/tai-1
847827bd23908adfad4a82c83d5295bdbc022796
[ "MIT" ]
null
null
null
apps/tai/lib/tai/events/venue_boot_error.ex
chrism2671/tai-1
847827bd23908adfad4a82c83d5295bdbc022796
[ "MIT" ]
1
2020-05-03T23:32:11.000Z
2020-05-03T23:32:11.000Z
defmodule Tai.Events.VenueBootError do alias Tai.Events.VenueBootError @type venue_id :: Tai.Venue.id() @type t :: %VenueBootError{venue: venue_id, reason: term} @enforce_keys ~w(venue reason)a defstruct ~w(venue reason)a end defimpl Tai.LogEvent, for: Tai.Events.VenueBootError do def to_data(event) do keys = event |> Map.keys() |> Enum.filter(&(&1 != :__struct__)) event |> Map.take(keys) |> Map.put(:reason, event.reason |> inspect) end end
21.608696
59
0.65996
93ca622cf5018821888da0710946fac672ef81a4
84
exs
Elixir
gcd.exs
lebm/MyElixirTests
4221012296c913179cdda278290263bfc1141454
[ "Apache-2.0" ]
null
null
null
gcd.exs
lebm/MyElixirTests
4221012296c913179cdda278290263bfc1141454
[ "Apache-2.0" ]
null
null
null
gcd.exs
lebm/MyElixirTests
4221012296c913179cdda278290263bfc1141454
[ "Apache-2.0" ]
null
null
null
defmodule Gcd do def of(x, 0), do: x def of(x, y), do: of(y, rem(x, y)) end
16.8
38
0.52381
93ca686a24152158f39fcec7df91a6a32ec648dc
556
ex
Elixir
lib/hl7/2.2/segments/om3.ex
calvinb/elixir-hl7
5e953fa11f9184857c0ec4dda8662889f35a6bec
[ "Apache-2.0" ]
null
null
null
lib/hl7/2.2/segments/om3.ex
calvinb/elixir-hl7
5e953fa11f9184857c0ec4dda8662889f35a6bec
[ "Apache-2.0" ]
null
null
null
lib/hl7/2.2/segments/om3.ex
calvinb/elixir-hl7
5e953fa11f9184857c0ec4dda8662889f35a6bec
[ "Apache-2.0" ]
null
null
null
defmodule HL7.V2_2.Segments.OM3 do @moduledoc false require Logger alias HL7.V2_2.{DataTypes} use HL7.Segment, fields: [ segment: nil, segment_type_id: nil, sequence_number_test_observation_master_file: nil, preferred_coding_system: nil, valid_coded_answers: DataTypes.Ce, normal_test_codes_for_categorical_observations: DataTypes.Ce, abnormal_test_codes_for_categorical_observations: DataTypes.Ce, critical_test_codes_for_categorical_observations: DataTypes.Ce, data_type: nil ] end
27.8
69
0.75
93ca8d92b96bd0cdb67e94c900c845919fe8127d
141
exs
Elixir
apps/services/test/services_test.exs
bitwalker/aws-dist-test
94d87e82b617da02d541f7b2744d20747d8ef21f
[ "Apache-2.0" ]
4
2019-03-13T16:38:32.000Z
2020-01-11T20:05:25.000Z
apps/services/test/services_test.exs
bitwalker/aws-dist-test
94d87e82b617da02d541f7b2744d20747d8ef21f
[ "Apache-2.0" ]
1
2019-03-14T17:41:55.000Z
2019-03-14T17:41:55.000Z
apps/services/test/services_test.exs
bitwalker/aws-dist-test
94d87e82b617da02d541f7b2744d20747d8ef21f
[ "Apache-2.0" ]
1
2019-03-14T14:53:29.000Z
2019-03-14T14:53:29.000Z
defmodule ServicesTest do use ExUnit.Case doctest Services test "greets the world" do assert Services.hello() == :world end end
15.666667
37
0.716312
93ca9a87b585f9fc157527c2dd918e641e27c254
1,622
exs
Elixir
game_of_life/test/game_of_life_test.exs
ancaciascaiu/Elixir
1867ee6dd5dda7c57e31ea04f61ef94294b21f8b
[ "MIT" ]
null
null
null
game_of_life/test/game_of_life_test.exs
ancaciascaiu/Elixir
1867ee6dd5dda7c57e31ea04f61ef94294b21f8b
[ "MIT" ]
null
null
null
game_of_life/test/game_of_life_test.exs
ancaciascaiu/Elixir
1867ee6dd5dda7c57e31ea04f61ef94294b21f8b
[ "MIT" ]
null
null
null
defmodule GameOfLifeTest do use ExUnit.Case doctest GameOfLife describe "any live cell" do test "with fewer that 2 live neighbors, it dies" do cell = %LiveCell{position: :upside_down} neighbors = [%LiveCell{}] assert %DeadCell{position: :upside_down} = GameOfLife.decide(cell, neighbors) end test "with exactly 2 live neighbors, it lives" do cell = %LiveCell{} neighbors = [%LiveCell{}, %LiveCell{}] assert %LiveCell{} = GameOfLife.decide(cell, neighbors) end test "with exactly 3 live neighbors, it lives" do cell = %LiveCell{} neighbors = [%LiveCell{}, %LiveCell{}, %LiveCell{}] assert %LiveCell{} = GameOfLife.decide(cell, neighbors) end test "with more than 3 live neighbors, it dies" do cell = %LiveCell{} neighbors = [%LiveCell{}, %LiveCell{}, %LiveCell{}, %LiveCell{}] assert %DeadCell{} = GameOfLife.decide(cell, neighbors) end end describe "any dead cell" do test "with exactly 3 live neighbors, it lives" do cell = %DeadCell{} neighbors = [%LiveCell{}, %LiveCell{}, %LiveCell{}] assert %LiveCell{} = GameOfLife.decide(cell, neighbors) end test "with less than 3 live neighbors, it dies" do cell = %DeadCell{} neighbors = [%LiveCell{}, %LiveCell{}] assert %DeadCell{} = GameOfLife.decide(cell, neighbors) end test "with more than 3 live neighbors, it dies" do cell = %DeadCell{} neighbors = [%LiveCell{}, %LiveCell{}, %LiveCell{}, %LiveCell{}] assert %DeadCell{} = GameOfLife.decide(cell, neighbors) end end end
31.803922
83
0.636252
93caaaab7e380ddca85da2cc57d0a7f6a11ec93f
1,106
ex
Elixir
lib/trifolium/endpoints/divisions.ex
daskycodes/trifolium
322f01f89948c51d974e64b049ca2ce2d0f8b45f
[ "MIT" ]
1
2021-04-19T15:09:35.000Z
2021-04-19T15:09:35.000Z
lib/trifolium/endpoints/divisions.ex
daskycodes/trifolium
322f01f89948c51d974e64b049ca2ce2d0f8b45f
[ "MIT" ]
1
2021-04-19T18:08:05.000Z
2021-04-19T18:08:05.000Z
lib/trifolium/endpoints/divisions.ex
daskycodes/trifolium
322f01f89948c51d974e64b049ca2ce2d0f8b45f
[ "MIT" ]
2
2021-04-19T15:09:39.000Z
2021-04-28T14:05:21.000Z
defmodule Trifolium.Divisions do @moduledoc """ Module to be used to interact with Trefle [Divisions](https://docs.trefle.io/reference/#tag/Divisions) related endpoints. """ alias Trifolium.Config alias Trifolium.API @endpoint_path "api/v1/divisions/" @http_client Config.http_client() @doc """ List every possible `Division`s. This endpoint IS paginated, using a optional keyword parameter. By default, the page 1 is returned. """ @spec all(page: non_neg_integer()) :: API.response() def all(opts \\ []) do @http_client.get( get_path(), [], params: API.build_query_params(opts) ) |> API.parse_response() end @doc """ Find a specific `Division` according to its `id` or `slug`. """ @spec find(non_neg_integer() | String.t()) :: API.response() def find(id) do @http_client.get( get_path("#{id}"), [], params: API.build_query_params() ) |> API.parse_response() end @spec get_path(String.t()) :: String.t() defp get_path(url \\ "") do Config.base_url() <> @endpoint_path <> url end end
25.136364
125
0.638336
93cadc89657f7bda81300b991af8b8d72fcce699
2,446
exs
Elixir
config/prod.exs
lucasmelin/Chatter
023595dab54bc86d94062a61628c344fa5d7f56d
[ "MIT" ]
null
null
null
config/prod.exs
lucasmelin/Chatter
023595dab54bc86d94062a61628c344fa5d7f56d
[ "MIT" ]
1
2020-07-16T23:18:36.000Z
2020-07-16T23:18:36.000Z
config/prod.exs
lucasmelin/Chatter
023595dab54bc86d94062a61628c344fa5d7f56d
[ "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 :chatter, ChatterWeb.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 :chatter, ChatterWeb.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 :chatter, ChatterWeb.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 :chatter, ChatterWeb.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"
33.972222
69
0.713001
93caedeedd6f305c4f683edc7d48373ee37c475c
995
exs
Elixir
mix.exs
rossjones/nifty
bb2d863a377266f96598f164e35a38628eedb42f
[ "MIT" ]
33
2015-06-11T23:54:21.000Z
2020-06-22T16:35:43.000Z
mix.exs
rossjones/nifty
bb2d863a377266f96598f164e35a38628eedb42f
[ "MIT" ]
7
2015-08-04T20:29:54.000Z
2021-11-12T19:26:25.000Z
mix.exs
rossjones/nifty
bb2d863a377266f96598f164e35a38628eedb42f
[ "MIT" ]
4
2015-08-04T20:18:55.000Z
2019-12-09T10:57:52.000Z
defmodule Nifty.Mixfile do use Mix.Project def project do [app: :nifty, version: "0.0.3", description: description, elixir: "~> 1.0", name: "Nifty", source_url: "https://github.com/rossjones/nifty", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, package: package, deps: deps] end defp package do [files: ["lib", "mix.exs", "README.md", "LICENSE"], maintainers: ["Ross Jones"], licenses: ["MIT"], links: %{ github: "https://github.com/rossjones/nifty", }] end def application do [applications: [:logger]] end def description do """ A semi-useful tool to generate boilerplate when you want to use a NIF in your project. You don't really want to use a NIF in your project, until you do. Then this might save you writing most of the boilerplate. mix nifty.gen --library hello --module MyApp.NIF """ end defp deps do [] end end
22.111111
67
0.609045
93cafaff19c985541b34813df13ded9691b5bfe2
1,885
ex
Elixir
lib/pow/config.ex
matthewford/pow
82c3359ec757a139fe38f4a745c3da176425f901
[ "MIT" ]
null
null
null
lib/pow/config.ex
matthewford/pow
82c3359ec757a139fe38f4a745c3da176425f901
[ "MIT" ]
null
null
null
lib/pow/config.ex
matthewford/pow
82c3359ec757a139fe38f4a745c3da176425f901
[ "MIT" ]
1
2020-07-13T01:11:17.000Z
2020-07-13T01:11:17.000Z
defmodule Pow.Config do @moduledoc """ Methods to parse and modify configurations. """ @type t :: Keyword.t() defmodule ConfigError do @moduledoc false defexception [:message] end @doc """ Gets the key value from the configuration. If not found, it'll fall back to environment config, and lastly to the default value which is `nil` if not specified. """ @spec get(t(), atom(), any()) :: any() def get(config, key, default \\ nil) do case Keyword.get(config, key, :not_found) do :not_found -> get_env_config(config, key, default) value -> value end end defp get_env_config(config, key, default, env_key \\ :pow) do config |> Keyword.get(:otp_app) |> case do nil -> Application.get_all_env(env_key) otp_app -> Application.get_env(otp_app, env_key, []) end |> Keyword.get(key, default) end @doc """ Puts a new key value to the configuration. """ @spec put(t(), atom(), any()) :: t() def put(config, key, value) do Keyword.put(config, key, value) end @doc """ Merges two configurations. """ @spec merge(t(), t()) :: t() def merge(l_config, r_config) do Keyword.merge(l_config, r_config) end @doc """ Raise a ConfigError exception. """ @spec raise_error(binary()) :: no_return def raise_error(message) do raise ConfigError, message: message end @doc """ Retrieves the repo module from the config, or raises an exception. """ @spec repo!(t()) :: atom() | no_return() def repo!(config) do get(config, :repo) || raise_error("No `:repo` configuration option found.") end @doc """ Retrieves the user schema module from the config, or raises an exception. """ @spec user!(t()) :: atom() | no_return() def user!(config) do get(config, :user) || raise_error("No `:user` configuration option found.") end end
24.802632
79
0.633952
93cb1af4cd0d9ed53135f10d9081f115bc245c3a
1,051
ex
Elixir
elixir/lib/elixer/application.ex
VitorFirmino/NLW-7
16d3319c6bcf2308ef6ea5fdf8257be78887a190
[ "MIT" ]
null
null
null
elixir/lib/elixer/application.ex
VitorFirmino/NLW-7
16d3319c6bcf2308ef6ea5fdf8257be78887a190
[ "MIT" ]
null
null
null
elixir/lib/elixer/application.ex
VitorFirmino/NLW-7
16d3319c6bcf2308ef6ea5fdf8257be78887a190
[ "MIT" ]
null
null
null
defmodule Elixer.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application @impl true def start(_type, _args) do children = [ # Start the Ecto repository Elixer.Repo, # Start the Telemetry supervisor ElixerWeb.Telemetry, # Start the PubSub system {Phoenix.PubSub, name: Elixer.PubSub}, # Start the Endpoint (http/https) ElixerWeb.Endpoint, # Start a worker by calling: Elixer.Worker.start_link(arg) # {Elixer.Worker, arg} Elixer.Scheduler ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Elixer.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. @impl true def config_change(changed, _new, removed) do ElixerWeb.Endpoint.config_change(changed, removed) :ok end end
27.657895
64
0.695528
93cb1e2f763dbd9bb4cd4bb7640ed91952c52a77
415
ex
Elixir
lib/new_relic/distributed_trace/context.ex
tpitale/elixir_agent
f356b588fe9d7cc3b9db00d9a251e009a20b3e0e
[ "Apache-2.0" ]
227
2018-09-05T15:33:23.000Z
2022-02-25T18:12:06.000Z
lib/new_relic/distributed_trace/context.ex
tpitale/elixir_agent
f356b588fe9d7cc3b9db00d9a251e009a20b3e0e
[ "Apache-2.0" ]
211
2018-09-05T21:42:41.000Z
2022-03-25T17:51:56.000Z
lib/new_relic/distributed_trace/context.ex
tpitale/elixir_agent
f356b588fe9d7cc3b9db00d9a251e009a20b3e0e
[ "Apache-2.0" ]
84
2018-09-05T04:26:26.000Z
2022-03-09T14:28:14.000Z
defmodule NewRelic.DistributedTrace.Context do @moduledoc false defstruct type: "App", source: nil, version: nil, account_id: nil, app_id: nil, parent_id: nil, guid: nil, span_guid: nil, trace_id: nil, trust_key: nil, priority: nil, sampled: nil, timestamp: nil end
23.055556
46
0.489157
93cb354c4c5c7dd9984784bb4dd58f5a2b40a133
3,831
ex
Elixir
lib/bot/handler.ex
ygunayer/potcu
d7b82ad9227161c93aedec03c4a1902c1d43780b
[ "MIT" ]
1
2020-05-14T18:52:05.000Z
2020-05-14T18:52:05.000Z
lib/bot/handler.ex
ygunayer/potcu
d7b82ad9227161c93aedec03c4a1902c1d43780b
[ "MIT" ]
null
null
null
lib/bot/handler.ex
ygunayer/potcu
d7b82ad9227161c93aedec03c4a1902c1d43780b
[ "MIT" ]
null
null
null
defmodule Potcu.Bot.Handler do use GenServer require Logger alias Nostrum.Api alias Nostrum.Cache alias Potcu.Bot.Registry alias Potcu.Bot.Structs.{StateData, BombStatus, VoiceStatus} alias Potcu.Bot.Voice.Structs.SessionInfo @help_text "potcu help text" ################## ## Initialization ################## def child_spec(guild_id, opts) do %{ id: "bot-handler-#{guild_id}", start: {__MODULE__, :start_link, [guild_id, opts]} } end def start_link(guild_id, opts) do GenServer.start_link(__MODULE__, guild_id, opts) end def init(guild_id) do state = %StateData{ guild_id: guild_id, bomb: %BombStatus{status: :idle}, voice: %VoiceStatus{status: :not_connected} } {:ok, state} end ################## ## Public API ################## ################## ## Private API ################## defp begin_join_voice!(state, msg, channel_id) do Nostrum.Api.update_voice_state(msg.guild_id, channel_id) voice_status = %VoiceStatus{status: :preparing, channel_id: channel_id} %StateData{state | voice: voice_status} end defp set_voice_session_id!(state, session_id) do voice_status = %VoiceStatus{state.voice | session_id: session_id} %StateData{state | voice: voice_status} |> finalize_voice_connection_attempt!() end defp set_voice_server!(state, server) do voice_status = %VoiceStatus{state.voice | server: server} %StateData{state | voice: voice_status} |> finalize_voice_connection_attempt!() end defp finalize_voice_connection_attempt!(state = %{voice: %{status: :preparing, session_id: session_id, server: server, channel_id: channel_id}}) when session_id != nil and server != nil do bot = Cache.Me.get() session = SessionInfo.from(bot.id, session_id, server) {:ok, _} = Registry.create_voice_session(session) voice_state = %VoiceStatus{ status: :connecting, channel_id: channel_id, server: server, session_id: session_id } %StateData{state | voice: voice_state} end defp finalize_voice_connection_attempt!(state), do: state ################## ## Callbacks ################## ## Cast ########## def handle_cast({:go_to_sender, msg}, state) do guild = Nostrum.Cache.GuildCache.get!(msg.guild_id) voice_state = Map.get(guild.voice_states, msg.author.id) case voice_state do nil -> Api.create_message!(msg.channel_id, "e konusmuyon ki abi nereye gelem") {:noreply, state} _ -> Api.create_message!(msg.channel_id, "geliyom abi") new_state = state |> begin_join_voice!(msg, voice_state.channel_id) {:noreply, new_state} end end # has the bot display help text def handle_cast({:help, msg}, state) do Api.create_message!(msg.channel_id, @help_text) {:noreply, state} end # updates the Discord voice state def handle_cast({:update_voice_state, %{session_id: session_id}}, state) do new_state = set_voice_session_id!(state, session_id) {:noreply, new_state} end # updates the Discord voice server information def handle_cast({:update_voice_server, voice_server}, state) do new_state = set_voice_server!(state, voice_server) {:noreply, new_state} end def handle_cast({:voice_connected, _}, state = %{voice: voice = %{status: :connecting}}) do new_voice_state = %VoiceStatus{voice | status: :connected} new_state = %StateData{state | voice: new_voice_state} Logger.debug("Voice connection is successful") {:noreply, new_state} end def handle_cast(_, state), do: {:noreply, state} ## Info ########## def handle_info(_, state) do {:noreply, state} end ## Call ########## def handle_call(_msg, _sender, state) do {:reply, :ignore, state} end end
27.364286
190
0.654398
93cb3edfa6fb06c4d82637cabbc75a571f56d5c3
3,850
ex
Elixir
clients/cloud_private_catalog_producer/lib/google_api/cloud_private_catalog_producer/v1beta1/model/google_cloud_privatecatalogproducer_v1beta1_version.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/cloud_private_catalog_producer/lib/google_api/cloud_private_catalog_producer/v1beta1/model/google_cloud_privatecatalogproducer_v1beta1_version.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/cloud_private_catalog_producer/lib/google_api/cloud_private_catalog_producer/v1beta1/model/google_cloud_privatecatalogproducer_v1beta1_version.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.CloudPrivateCatalogProducer.V1beta1.Model.GoogleCloudPrivatecatalogproducerV1beta1Version do @moduledoc """ The producer representation of a version, which is a child resource under a `Product` with asset data. ## Attributes * `asset` (*type:* `map()`, *default:* `nil`) - Output only. The asset which has been validated and is ready to be provisioned. See Version.original_asset for the schema. * `createTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The time when the version was created. * `description` (*type:* `String.t`, *default:* `nil`) - The user-supplied description of the version. Maximum of 256 characters. * `name` (*type:* `String.t`, *default:* `nil`) - Required. The resource name of the version, in the format `catalogs/{catalog_id}/products/{product_id}/versions/a-z*[a-z0-9]'. A unique identifier for the version under a product, which can't be changed after the version is created. The final segment of the name must between 1 and 63 characters in length. * `originalAsset` (*type:* `map()`, *default:* `nil`) - The user-supplied asset payload. The maximum size of the payload is 2MB. The JSON schema of the payload is defined as: ``` type: object properties: mainTemplate: type: string description: The file name of the main template and name prefix of schema file. The content of the main template should be set in the imports list. The schema file name is expected to be <mainTemplate>.schema in the imports list. required: true imports: type: array description: Import template and schema file contents. Required to have both <mainTemplate> and <mainTemplate>.schema files. required: true minItems: 2 items: type: object properties: name: type: string content: type: string ``` * `updateTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The time when the version was last updated. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :asset => map(), :createTime => DateTime.t(), :description => String.t(), :name => String.t(), :originalAsset => map(), :updateTime => DateTime.t() } field(:asset, type: :map) field(:createTime, as: DateTime) field(:description) field(:name) field(:originalAsset, type: :map) field(:updateTime, as: DateTime) end defimpl Poison.Decoder, for: GoogleApi.CloudPrivateCatalogProducer.V1beta1.Model.GoogleCloudPrivatecatalogproducerV1beta1Version do def decode(value, options) do GoogleApi.CloudPrivateCatalogProducer.V1beta1.Model.GoogleCloudPrivatecatalogproducerV1beta1Version.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.CloudPrivateCatalogProducer.V1beta1.Model.GoogleCloudPrivatecatalogproducerV1beta1Version do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.5
133
0.679221
93cb5d54d329fc9df2166506f91332432ffcc1f0
2,233
exs
Elixir
test/galapagos_nao/selection_test.exs
jeffreyksmithjr/galapgos_nao
6123d770b4019c8225d64b9a4a584b4ee0019063
[ "MIT" ]
21
2018-03-19T02:52:38.000Z
2020-07-21T06:18:54.000Z
test/galapagos_nao/selection_test.exs
jeffreyksmithjr/galapgos_nao
6123d770b4019c8225d64b9a4a584b4ee0019063
[ "MIT" ]
23
2018-02-21T23:34:41.000Z
2018-04-07T15:13:56.000Z
test/galapagos_nao/selection_test.exs
jeffreyksmithjr/galapgos_nao
6123d770b4019c8225d64b9a4a584b4ee0019063
[ "MIT" ]
1
2020-04-28T16:38:03.000Z
2020-04-28T16:38:03.000Z
defmodule GN.SelectionTest do use ExUnit.Case alias GN.Selection, as: Selection alias GN.Network, as: Network @test_agent_name :testable_selection setup do {:ok, agent} = Selection.start_link(name: @test_agent_name) {:ok, agent: agent} end test "sets cutoffs" do nets = [ %Network{ layers: [ {:dense, [24, :softrelu]}, {:activation, [:tanh]}, {:dropout, [0.25]}, {:flatten, []} ] } ] expectation = [2, 4] assert Selection.cutoffs(nets) == expectation end test "adds new elites" do Selection.put(@test_agent_name, 1, %Network{ id: "old-one", layers: [:flatten, []], test_acc: 0.01 }) Selection.put(@test_agent_name, 2, %Network{ id: "old-two", layers: [{:dense, [24, :softrelu]}, {:activation, [:tanh]}, {:dropout, [0.25]}], test_acc: 0.01 }) new_nets = [ %Network{id: "new-one", layers: [{:dense, [12]}], test_acc: 0.50}, %Network{ id: "new-two", layers: [{:dense, [48, :softrelu]}, {:activation, [:tanh]}, {:dropout, [0.25]}], test_acc: 0.60 } ] new_elites = Selection.select(@test_agent_name, new_nets) new_level_1 = Map.get(new_elites, 1).id new_level_2 = Map.get(new_elites, 2).id assert new_level_1 == "new-one" assert new_level_2 == "new-two" end test "adds externally provided models" do net = %Network{id: "external-model", layers: [:flatten, []], test_acc: 0.99} Selection.put_unevaluated(@test_agent_name, net) expectation = %{-1 => net} assert Selection.get_all(@test_agent_name) == expectation end test "gets all elites" do first_net = {1, %Network{id: "old-one", layers: [:flatten, []], test_acc: 0.01}} second_net = {2, %Network{ id: "old-two", layers: [{:dense, [24, :softrelu]}, {:activation, [:tanh]}, {:dropout, [0.25]}], test_acc: 0.01 }} elites = [first_net, second_net] for net <- elites do Selection.put(@test_agent_name, elem(net, 0), elem(net, 1)) end expectation = Enum.into(elites, %{}) assert Selection.get_all(@test_agent_name) == expectation end end
25.666667
89
0.576355
93cb5f815cce63ebb94907b5e4b38f3ed20be136
291
exs
Elixir
config/test.exs
data-twister/blog-phoenix-live-view-google-maps
13c7186219f9920962df161a093adf77f5ded69d
[ "MIT" ]
4
2020-07-31T13:48:23.000Z
2020-12-21T16:35:36.000Z
config/test.exs
data-twister/blog-phoenix-live-view-google-maps
13c7186219f9920962df161a093adf77f5ded69d
[ "MIT" ]
1
2020-08-14T15:29:28.000Z
2021-06-10T17:40:19.000Z
config/test.exs
data-twister/blog-phoenix-live-view-google-maps
13c7186219f9920962df161a093adf77f5ded69d
[ "MIT" ]
2
2020-08-13T19:11:53.000Z
2021-05-27T01:56:02.000Z
use Mix.Config # We don't run a server during test. If one is required, # you can enable the server option below. config :live_view_google_maps, LiveViewGoogleMapsWeb.Endpoint, http: [port: 4002], server: false # Print only warnings and errors during test config :logger, level: :warn
26.454545
62
0.75945
93cb64cef9c5c6ed4910d6455c72beaea4ebb9b7
887
ex
Elixir
elixir/lib/homework_web/schema.ex
TreywRoberts/web-homework
d19b17dd384341d9e6e7e3174372673584289b83
[ "MIT" ]
null
null
null
elixir/lib/homework_web/schema.ex
TreywRoberts/web-homework
d19b17dd384341d9e6e7e3174372673584289b83
[ "MIT" ]
null
null
null
elixir/lib/homework_web/schema.ex
TreywRoberts/web-homework
d19b17dd384341d9e6e7e3174372673584289b83
[ "MIT" ]
null
null
null
defmodule HomeworkWeb.Schema do @moduledoc """ Defines the graphql schema for this project. """ use Absinthe.Schema alias HomeworkWeb.Resolvers.MerchantsResolver alias HomeworkWeb.Resolvers.TransactionsResolver alias HomeworkWeb.Resolvers.UsersResolver import_types(HomeworkWeb.Schemas.Types) query do @desc "Get all Transactions" field(:transactions, list_of(:transaction)) do resolve(&TransactionsResolver.transactions/3) end @desc "Get all Users" field(:users, list_of(:user)) do resolve(&UsersResolver.users/3) end @desc "Get all Merchants" field(:merchants, list_of(:merchant)) do resolve(&MerchantsResolver.merchants/3) end end mutation do import_fields(:transaction_mutations) import_fields(:user_mutations) import_fields(:merchant_mutations) end end
25.342857
52
0.704622
93cb680a849bcada973a5a81633d32ae368cffbb
66
ex
Elixir
LPS/e3.ex
palexand/interpreters
c5ff4e644fce1e97f1823321710dd082aa79aa72
[ "BSD-3-Clause" ]
10
2015-02-05T13:24:43.000Z
2021-12-18T18:39:05.000Z
LPS/e3.ex
palexand/interpreters
c5ff4e644fce1e97f1823321710dd082aa79aa72
[ "BSD-3-Clause" ]
null
null
null
LPS/e3.ex
palexand/interpreters
c5ff4e644fce1e97f1823321710dd082aa79aa72
[ "BSD-3-Clause" ]
1
2020-12-09T10:16:44.000Z
2020-12-09T10:16:44.000Z
letL fac = \L x -> if x==0 then 1 else x * fac (x - 1) in fac 5
22
51
0.515152
93cb93afac925ca98fc4e594f3d0f6d9006074a6
999
ex
Elixir
lib/timestamp_web/live/page_live.ex
ugiete/Timestamp-Converter
04e0eca0918f7c87047bb0cb7849cf853d747f37
[ "MIT" ]
null
null
null
lib/timestamp_web/live/page_live.ex
ugiete/Timestamp-Converter
04e0eca0918f7c87047bb0cb7849cf853d747f37
[ "MIT" ]
null
null
null
lib/timestamp_web/live/page_live.ex
ugiete/Timestamp-Converter
04e0eca0918f7c87047bb0cb7849cf853d747f37
[ "MIT" ]
null
null
null
defmodule TimestampWeb.PageLive do @moduledoc false use TimestampWeb, :live_view alias Timestamp.Converter @impl true def mount(_params, _session, socket) do {:ok, assign(socket, timestamp: "", datetime: "")} end @impl true def handle_event("clear", _params, socket) do {:noreply, assign(socket, timestamp: "", datetime: "")} end @impl true def handle_event("convert", %{"timestamp" => "", "datetime" => ""}, socket) do {:noreply, assign(socket, timestamp: "", datetime: "")} end @impl true def handle_event("convert", %{"timestamp" => "", "datetime" => datetime}, socket) do %{unix: timestamp, utc: utc} = Converter.datetime_to_timestamp(datetime) {:noreply, assign(socket, timestamp: timestamp, datetime: utc)} end @impl true def handle_event("convert", %{"timestamp" => timestamp}, socket) do %{utc: utc} = timestamp |> Converter.timestamp_to_datetime() {:noreply, assign(socket, timestamp: timestamp, datetime: utc)} end end
29.382353
86
0.667668
93cb9b0a16afa3c34dbf88988f3a358c2d048718
2,320
ex
Elixir
clients/vault/lib/google_api/vault/v1/model/status.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/vault/lib/google_api/vault/v1/model/status.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/vault/lib/google_api/vault/v1/model/status.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Vault.V1.Model.Status do @moduledoc """ The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). ## Attributes * `code` (*type:* `integer()`, *default:* `nil`) - The status code, which should be an enum value of google.rpc.Code. * `details` (*type:* `list(map())`, *default:* `nil`) - A list of messages that carry the error details. There is a common set of message types for APIs to use. * `message` (*type:* `String.t`, *default:* `nil`) - A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :code => integer(), :details => list(map()), :message => String.t() } field(:code) field(:details, type: :list) field(:message) end defimpl Poison.Decoder, for: GoogleApi.Vault.V1.Model.Status do def decode(value, options) do GoogleApi.Vault.V1.Model.Status.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Vault.V1.Model.Status do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.419355
134
0.709483
93cbc5f6f6ace5673fb01f6c279ac47c1cefdfd9
1,058
ex
Elixir
lib/watcher.ex
camisetags/elixir-koans
7bb1655d0f290c0834276091efa5a28b416dd91a
[ "MIT" ]
1
2019-03-09T19:33:53.000Z
2019-03-09T19:33:53.000Z
lib/watcher.ex
camisetags/elixir-koans
7bb1655d0f290c0834276091efa5a28b416dd91a
[ "MIT" ]
null
null
null
lib/watcher.ex
camisetags/elixir-koans
7bb1655d0f290c0834276091efa5a28b416dd91a
[ "MIT" ]
null
null
null
defmodule Watcher do use GenServer def start_link() do GenServer.start_link(__MODULE__, dirs: ["lib/koans"]) end def init(args) do {:ok, watcher_pid} = FileSystem.start_link(args) FileSystem.subscribe(watcher_pid) {:ok, %{watcher_pid: watcher_pid}} end def handle_info({:file_event, watcher_pid, {path, events}}, %{watcher_pid: watcher_pid} = state) do # respond to renamed as well due to that some editors use temporary files for atomic writes (ex: TextMate) if Enum.member?(events, :modified) || Enum.member?(events, :renamed) do path |> normalize |> reload end {:noreply, state} end defp reload(file) do if Path.extname(file) == ".ex" do try do file |> Code.load_file() |> Enum.map(&elem(&1, 0)) |> Enum.find(&Runner.koan?/1) |> Runner.modules_to_run() |> Runner.run() rescue e -> Display.show_compile_error(e) end end end defp normalize(file) do String.replace_suffix(file, "___jb_tmp___", "") end end
25.190476
110
0.628544
93cbc7da39d6e60054021c36f568182cb0069a3c
4,959
ex
Elixir
lib/ex_pix.ex
LeoLeiteSC/ex_pix
85fbed588a6ab0563e038a23f11194a027ec1b9f
[ "MIT" ]
7
2021-04-18T14:54:41.000Z
2022-01-21T23:10:47.000Z
lib/ex_pix.ex
Astrocoders/ex_pix
ccf5012dfc2809f2be2c1223ab836c7a4e2fd90d
[ "MIT" ]
null
null
null
lib/ex_pix.ex
Astrocoders/ex_pix
ccf5012dfc2809f2be2c1223ab836c7a4e2fd90d
[ "MIT" ]
1
2021-09-13T18:07:19.000Z
2021-09-13T18:07:19.000Z
defmodule ExPIX do @moduledoc """ Module with basic operations. All functions in this library use the parameters in the `config.exs` file. By default, the configuration for building static QR-Codes is: ```elixir config :ex_pix, :static_code, payload_indicator: "01", start_method: "11", gui: "br.gov.bcb.pix", currency_code: "986", country_code: "BR", default_value: "0.00", category_code: "0000" ``` If you need to change any of these parameters, just define it in your own configuration file. """ alias ExPIX.Data.{ Additional, Static, StaticAccount, } alias ExPIX.Code.Builder @typedoc """ Basic information for building static code. It must be a map with the following parameters: - `:merchant_name` - Required field that represents the name of the user to be charged. - `:merchant_city` - Required field that represents the city of the user to be charged. - `:postal_code` - Non-Required field that represents the user's postal code. - `:amount` - The amount of the operation. If not provided, the code will use the default value defined in the configuration. It must be a string in the format 0.00. - `:payload_indicator` - The payload indicator of the operation. If not provided, the code will use the default value defined in the configuration. - `:initiation_method` - The initiation method of the operation. If not provided, the code will use the default value defined in the configuration. - `:category_code` - The category code of the operation. If not provided, the code will use the default value defined in the configuration. - `:currency_code` - The currency code of the operation. If not provided, the code will use the default value defined in the configuration. - `:country_code` - The country code of the operation. If not provided, the code will use the default value defined in the configuration. """ @type static_params :: %{ required(:merchant_name) => String.t, required(:merchant_city) => String.t, optional(:amount) => String.t, optional(:payload_indicator) => String.t, optional(:initiation_method) => String.t, optional(:category_code) => String.t, optional(:currency_code) => String.t, optional(:country_code) => String.t, optional(:postal_code) => String.t, } @typedoc """ Optional parameters to build the notes of the operation. The available parameters are: - `:info` - A string with the operation notes. **Important:** - The count of characters of the `info` + count of characters of the `gui` + count of characters of the `key` must not exceed the limit of 99 characters. If this limit is exceeded, an error will be returned. """ @type account_params :: %{optional(:info) => String.t} @typedoc """ Additional parameters to build the code. The available parameters are: - `:txid` - An ID to represent the operation. If not provided, the `txid` will be `***`, that represents a random string to be generated by Banco Central. **Important:** - Banco Central does not check if the provided ID is unique, so the recomendation here is use an UUID (ideally the v4). - The count of characters must not exceed the limit of 99 characters. If this limit is exceeded, an error will be returned. """ @type additional_params :: %{optional(:txid) => String.t} @doc """ Generates a static raw code. This function uses the default parameters defined in the `static_code` configuration, but if you need a special parameter, this function can receive such parameters as well. * `key` - The 'key' to be charged. It can be a CNPJ, CPF, phone number or a random binary string. It is not necessary to send the key type, but this function expects that the key is already in the format for your type (see the PIX docs for some examples). * `static_params` - Basic information to build a static code. * `account_params` - Optional parameters to build the notes of the operation. * `additional_params` - Additional parameters to build the code. ### Example: ```elixir iex> ExPIX.generate_static_code("email@email.com", %{merchant_name: "Leonardo Leite", merchant_city: "Florianopolis"}) {:ok, "00020101021126370014br.gov.bcb.pix0115email@email.com52040000530398654040.005802BR5914Leonardo Leite6013Florianopolis62070503***6304891C"} ``` """ @spec generate_static_code(String.t(), static_params, account_params, additional_params) :: {:ok, String.t()} | {:error, any} def generate_static_code(key, static_params, account_params \\ %{}, additional_params \\ %{}) do account_info = Map.merge(%StaticAccount{}, Map.merge(%{key: key}, account_params)) additional_info = Map.merge(%Additional{}, additional_params) %Static{} |> Map.merge( static_params |> Map.put(:account_information, account_info) |> Map.put(:additional, additional_info) ) |> Builder.build() end end
49.59
259
0.71224
93cc2cf270712da7d7d180e22bb124e8e57bf0ab
115
ex
Elixir
lib/remote_retro/repo.ex
octosteve/remote_retro
3385b0db3c2daab934ce12a2f7642a5f10ac5147
[ "MIT" ]
523
2017-03-15T15:21:11.000Z
2022-03-14T03:04:18.000Z
lib/remote_retro/repo.ex
octosteve/remote_retro
3385b0db3c2daab934ce12a2f7642a5f10ac5147
[ "MIT" ]
524
2017-03-16T18:31:09.000Z
2022-02-26T10:02:06.000Z
lib/remote_retro/repo.ex
octosteve/remote_retro
3385b0db3c2daab934ce12a2f7642a5f10ac5147
[ "MIT" ]
60
2017-05-01T18:02:28.000Z
2022-03-04T21:04:56.000Z
defmodule RemoteRetro.Repo do use Ecto.Repo, otp_app: :remote_retro, adapter: Ecto.Adapters.Postgres end
19.166667
35
0.747826
93cc6da4ad94f56cce172680e6bc27c6f7665920
78
exs
Elixir
test/amrita_web/views/page_view_test.exs
u3paka/Amrita
de2c566d856fd75925a4dfec58c28c2484c29d5d
[ "Apache-2.0" ]
null
null
null
test/amrita_web/views/page_view_test.exs
u3paka/Amrita
de2c566d856fd75925a4dfec58c28c2484c29d5d
[ "Apache-2.0" ]
2
2020-07-17T08:34:44.000Z
2021-03-09T08:33:47.000Z
test/amrita_web/views/page_view_test.exs
u3paka/amrita
de2c566d856fd75925a4dfec58c28c2484c29d5d
[ "Apache-2.0" ]
null
null
null
defmodule AmritaWeb.PageViewTest do use AmritaWeb.ConnCase, async: true end
19.5
37
0.820513
93cca55cbf518cbc11907cb2aa6da5264f5cbb53
3,021
ex
Elixir
clients/analytics_data/lib/google_api/analytics_data/v1beta/model/minute_range.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/analytics_data/lib/google_api/analytics_data/v1beta/model/minute_range.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/analytics_data/lib/google_api/analytics_data/v1beta/model/minute_range.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.AnalyticsData.V1beta.Model.MinuteRange do @moduledoc """ A contiguous set of minutes: startMinutesAgo, startMinutesAgo + 1, ..., endMinutesAgo. Requests are allowed up to 2 minute ranges. ## Attributes * `endMinutesAgo` (*type:* `integer()`, *default:* `nil`) - The inclusive end minute for the query as a number of minutes before now. Cannot be before `startMinutesAgo`. For example, `"endMinutesAgo": 15` specifies the report should include event data from prior to 15 minutes ago. If unspecified, `endMinutesAgo` is defaulted to 0. Standard Analytics properties can request any minute in the last 30 minutes of event data (`endMinutesAgo <= 29`), and 360 Analytics properties can request any minute in the last 60 minutes of event data (`endMinutesAgo <= 59`). * `name` (*type:* `String.t`, *default:* `nil`) - Assigns a name to this minute range. The dimension `dateRange` is valued to this name in a report response. If set, cannot begin with `date_range_` or `RESERVED_`. If not set, minute ranges are named by their zero based index in the request: `date_range_0`, `date_range_1`, etc. * `startMinutesAgo` (*type:* `integer()`, *default:* `nil`) - The inclusive start minute for the query as a number of minutes before now. For example, `"startMinutesAgo": 29` specifies the report should include event data from 29 minutes ago and after. Cannot be after `endMinutesAgo`. If unspecified, `startMinutesAgo` is defaulted to 29. Standard Analytics properties can request up to the last 30 minutes of event data (`startMinutesAgo <= 29`), and 360 Analytics properties can request up to the last 60 minutes of event data (`startMinutesAgo <= 59`). """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :endMinutesAgo => integer() | nil, :name => String.t() | nil, :startMinutesAgo => integer() | nil } field(:endMinutesAgo) field(:name) field(:startMinutesAgo) end defimpl Poison.Decoder, for: GoogleApi.AnalyticsData.V1beta.Model.MinuteRange do def decode(value, options) do GoogleApi.AnalyticsData.V1beta.Model.MinuteRange.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AnalyticsData.V1beta.Model.MinuteRange do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
57
565
0.740814
93ccb3b96c2b8c749dddb1fe000a4d99a21cabf4
7,587
ex
Elixir
lib/ex_json_schema/validator.ex
appcues/ex_json_schema
3d4abf8a17bb803ab9ec2840c89f1f2bfda16d26
[ "MIT" ]
null
null
null
lib/ex_json_schema/validator.ex
appcues/ex_json_schema
3d4abf8a17bb803ab9ec2840c89f1f2bfda16d26
[ "MIT" ]
null
null
null
lib/ex_json_schema/validator.ex
appcues/ex_json_schema
3d4abf8a17bb803ab9ec2840c89f1f2bfda16d26
[ "MIT" ]
null
null
null
defmodule ExJsonSchema.Validator do alias ExJsonSchema.Validator.Dependencies alias ExJsonSchema.Validator.Format alias ExJsonSchema.Validator.Items alias ExJsonSchema.Validator.Properties alias ExJsonSchema.Validator.Type alias ExJsonSchema.Schema alias ExJsonSchema.Schema.Root @type errors :: [{String.t, String.t}] | [] @type errors_with_list_paths :: [{String.t, [String.t | integer]}] | [] @spec validate(Root.t, ExJsonSchema.data) :: :ok | {:error, errors} def validate(root = %Root{}, data) do errors = validate(root, root.schema, data, ["#"]) |> errors_with_string_paths case Enum.empty?(errors) do true -> :ok false -> {:error, errors} end end @spec validate(ExJsonSchema.json, ExJsonSchema.data) :: :ok | {:error, errors} def validate(schema = %{}, data) do validate(Schema.resolve(schema), data) end @spec validate(Root.t, Schema.resolved, ExJsonSchema.data, [String.t | integer]) :: errors_with_list_paths def validate(root, schema, data, path \\ []) do Enum.flat_map(schema, &validate_aspect(root, schema, &1, data)) |> Enum.map fn {msg, p} -> {msg, path ++ p} end end @spec valid?(Root.t, ExJsonSchema.data) :: boolean def valid?(root = %Root{}, data), do: valid?(root, root.schema, data) @spec valid?(ExJsonSchema.json, ExJsonSchema.data) :: boolean def valid?(schema = %{}, data), do: valid?(Schema.resolve(schema), data) @spec valid?(Root.t, Schema.resolved, ExJsonSchema.data) :: boolean def valid?(root, schema, data), do: validate(root, schema, data) |> Enum.empty? defp errors_with_string_paths(errors) do Enum.map errors, fn {msg, path} -> {msg, Enum.join(path, "/")} end end defp validate_aspect(root, _, {"$ref", ref}, data) do {root, schema} = ref.(root) validate(root, schema, data) end defp validate_aspect(root, _, {"allOf", all_of}, data) do invalid_indexes = validation_result_indexes(root, all_of, data, &(!elem(&1, 0))) case Enum.empty?(invalid_indexes) do true -> [] false -> [{"Expected all of the schemata to match, " <> "but the schemata at the following indexes did not: " <> "#{Enum.join(invalid_indexes, ", ")}.", []}] end end defp validate_aspect(root, _, {"anyOf", any_of}, data) do case Enum.any?(any_of, &valid?(root, &1, data)) do true -> [] false -> [{"Expected any of the schemata to match but none did.", []}] end end defp validate_aspect(root, _, {"oneOf", one_of}, data) do valid_indexes = validation_result_indexes(root, one_of, data, &(elem(&1, 0))) case Enum.empty?(valid_indexes) do true -> [{"Expected exactly one of the schemata to match, but none of them did.", []}] false -> if Enum.count(valid_indexes) == 1 do [] else [{"Expected exactly one of the schemata to match, " <> "but the schemata at the following indexes did: " <> "#{Enum.join(valid_indexes, ", ")}.", []}] end end end defp validate_aspect(root, _, {"not", not_schema}, data) do case valid?(root, not_schema, data) do true -> [{"Expected schema not to match but it did.", []}] false -> [] end end defp validate_aspect(_, _, {"type", type}, data) do Type.validate(type, data) end defp validate_aspect(root, schema, {"properties", _}, data = %{}) do Properties.validate(root, schema, data) end defp validate_aspect(_, _, {"minProperties", min_properties}, data) when is_map(data) do case Map.size(data) >= min_properties do true -> [] false -> [{"Expected a minimum of #{min_properties} properties but got #{Map.size(data)}", []}] end end defp validate_aspect(_, _, {"maxProperties", max_properties}, data) when is_map(data) do case Map.size(data) <= max_properties do true -> [] false -> [{"Expected a maximum of #{max_properties} properties but got #{Map.size(data)}", []}] end end defp validate_aspect(_, _, {"required", required}, data) do Enum.flat_map List.wrap(required), fn property -> case Map.has_key?(data, property) do true -> [] false -> [{"Required property #{property} was not present.", []}] end end end defp validate_aspect(root, _, {"dependencies", dependencies}, data) do Dependencies.validate(root, dependencies, data) end defp validate_aspect(root, schema, {"items", _}, items) do Items.validate(root, schema, items) end defp validate_aspect(_, _, {"minItems", min_items}, items) when is_list(items) do case (count = Enum.count(items)) >= min_items do true -> [] false -> [{"Expected a minimum of #{min_items} items but got #{count}.", []}] end end defp validate_aspect(_, _, {"maxItems", max_items}, items) when is_list(items) do case (count = Enum.count(items)) <= max_items do true -> [] false -> [{"Expected a maximum of #{max_items} items but got #{count}.", []}] end end defp validate_aspect(_, _, {"uniqueItems", true}, items) when is_list(items) do case Enum.uniq(items) == items do true -> [] false -> [{"Expected items to be unique but they were not.", []}] end end defp validate_aspect(_, _, {"enum", enum}, data) do case Enum.any?(enum, &(&1 === data)) do true -> [] false -> [{"Value #{inspect(data)} is not allowed in enum.", []}] end end defp validate_aspect(_, schema, {"minimum", minimum}, data) when is_number(data) do exclusive? = schema["exclusiveMinimum"] fun = if exclusive?, do: &Kernel.>/2, else: &Kernel.>=/2 case fun.(data, minimum) do true -> [] false -> [{"Expected the value to be #{if exclusive?, do: ">", else: ">="} #{minimum}", []}] end end defp validate_aspect(_, schema, {"maximum", maximum}, data) when is_number(data) do exclusive? = schema["exclusiveMaximum"] fun = if exclusive?, do: &Kernel.</2, else: &Kernel.<=/2 case fun.(data, maximum) do true -> [] false -> [{"Expected the value to be #{if exclusive?, do: "<", else: "<="} #{maximum}", []}] end end defp validate_aspect(_, _, {"multipleOf", multiple_of}, data) when is_number(data) do factor = data / multiple_of case Float.floor(factor) == factor do true -> [] false -> [{"Expected value to be a multiple of #{multiple_of} but got #{data}.", []}] end end defp validate_aspect(_, _, {"minLength", min_length}, data) when is_binary(data) do case (length = String.length(data)) >= min_length do true -> [] false -> [{"Expected value to have a minimum length of #{min_length} but was #{length}.", []}] end end defp validate_aspect(_, _, {"maxLength", max_length}, data) when is_binary(data) do case (length = String.length(data)) <= max_length do true -> [] false -> [{"Expected value to have a maximum length of #{max_length} but was #{length}.", []}] end end defp validate_aspect(_, _, {"pattern", pattern}, data) when is_binary(data) do case pattern |> Regex.compile! |> Regex.match?(data) do true -> [] false -> [{"String #{inspect(data)} does not match pattern #{inspect(pattern)}.", []}] end end defp validate_aspect(_, _, {"format", format}, data) do Format.validate(format, data) end defp validate_aspect(_, _, _, _), do: [] defp validation_result_indexes(root, schemata, data, filter) do schemata |> Enum.map(&valid?(root, &1, data)) |> Enum.with_index |> Enum.filter(filter) |> Dict.values end end
34.486364
108
0.625016
93ccc2069607ba811a76fef2d811bc392bf622a4
1,979
exs
Elixir
mix.exs
stefkohub/darknet_to_onnx
1d378a4dd33452e7eba7a6174e4a13a210fa8cb6
[ "MIT" ]
1
2021-12-05T10:52:26.000Z
2021-12-05T10:52:26.000Z
mix.exs
stefkohub/darknet_to_onnx
1d378a4dd33452e7eba7a6174e4a13a210fa8cb6
[ "MIT" ]
3
2021-12-17T10:12:22.000Z
2022-02-28T12:17:21.000Z
mix.exs
stefkohub/darknet_to_onnx
1d378a4dd33452e7eba7a6174e4a13a210fa8cb6
[ "MIT" ]
null
null
null
defmodule DarknetToOnnx.MixProject do use Mix.Project def project do [ app: :darknet_to_onnx, version: "0.1.0", elixir: "~> 1.12", start_permanent: Mix.env() == :prod, build_embedded: Mix.env() == :prod, escript: [main_module: DarknetToOnnx.CLI], deps: deps(), ####### From ElixirCI build_path: "_build", deps_path: "deps", lockfile: "mix.lock", consolidate_protocols: Mix.env() != :test, test_coverage: [tool: ExCoveralls], preferred_cli_env: [ coveralls: :test, "coveralls.detail": :test, "coveralls.html": :test ], dialyzer: [ plt_add_apps: [:elixir, :mix], flags: [ :error_handling, :race_conditions, :underspecs ], ignore_warnings: ".dialyzer_ignore.exs" ] ############ ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger, :exla] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ # {:dep_from_hexpm, "~> 0.3.0"}, # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} # {:configparser_ex, git: "https://github.com/easco/configparser_ex", tag: "master"}, {:credo, "~> 1.6.1", only: [:dev, :test], runtime: false}, {:dialyxir, "~> 1.1", only: [:dev, :test], runtime: false}, {:excoveralls, "~> 0.14", only: [:dev, :test], runtime: false}, {:configparser_ex, git: "https://github.com/stefkohub/configparser_ex", tag: "master"}, {:axon, "~> 0.1.0-dev", github: "elixir-nx/axon"}, {:axon_onnx, github: "stefkohub/axon_onnx", tag: "master"}, {:exla, "~> 0.1.0-dev", github: "elixir-nx/nx", sparse: "exla"}, # {:torchx, "~> 0.1.0-dev", github: "elixir-nx/nx", sparse: "torchx"}, {:nx, "~> 0.1.0-dev", github: "elixir-nx/nx", sparse: "nx", override: true} ] end end
31.919355
93
0.560889
93cce167068b21bf3447df83925cf21781e5b89e
2,135
ex
Elixir
clients/people/lib/google_api/people/v1/model/relationship_interest.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/people/lib/google_api/people/v1/model/relationship_interest.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/people/lib/google_api/people/v1/model/relationship_interest.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.People.V1.Model.RelationshipInterest do @moduledoc """ A person's relationship interest . ## Attributes * `formattedValue` (*type:* `String.t`, *default:* `nil`) - Output only. The value of the relationship interest translated and formatted in the viewer's account locale or the locale specified in the Accept-Language HTTP header. * `metadata` (*type:* `GoogleApi.People.V1.Model.FieldMetadata.t`, *default:* `nil`) - Metadata about the relationship interest. * `value` (*type:* `String.t`, *default:* `nil`) - The kind of relationship the person is looking for. The value can be custom or one of these predefined values: * `friend` * `date` * `relationship` * `networking` """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :formattedValue => String.t(), :metadata => GoogleApi.People.V1.Model.FieldMetadata.t(), :value => String.t() } field(:formattedValue) field(:metadata, as: GoogleApi.People.V1.Model.FieldMetadata) field(:value) end defimpl Poison.Decoder, for: GoogleApi.People.V1.Model.RelationshipInterest do def decode(value, options) do GoogleApi.People.V1.Model.RelationshipInterest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.People.V1.Model.RelationshipInterest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35
140
0.714286
93cd5067253fdec786a342fbdc5efcef283136a6
4,239
ex
Elixir
lib/tirexs/resources.ex
williamtran29/tirex_aws
8affc13d32978db47e083bec7ae11c5546f89395
[ "Apache-2.0" ]
null
null
null
lib/tirexs/resources.ex
williamtran29/tirex_aws
8affc13d32978db47e083bec7ae11c5546f89395
[ "Apache-2.0" ]
null
null
null
lib/tirexs/resources.ex
williamtran29/tirex_aws
8affc13d32978db47e083bec7ae11c5546f89395
[ "Apache-2.0" ]
null
null
null
defmodule Tirexs.Resources do @moduledoc """ The intend is to provide an abstraction for dealing with ES resources. The interface of this module is aware about elasticsearch REST APIs conventions. Meanwhile, a `Tirexs.HTTP` provides just a general interface. """ import Tirexs.HTTP @doc "the same as `Tirexs.HTTP.ok?(Tirexs.HTTP.head(path, uri))` expression. See `Tirexs.HTTP.ok?/1` and `Tirexs.HTTP.head/2`" def exists?(path, uri), do: ok?(head(path, uri)) def exists?(url_or_path_or_uri), do: ok?(head(url_or_path_or_uri)) @doc "the same as `Tirexs.HTTP.head!(path, uri)` expression. See `Tirexs.HTTP.head!/2`" def exists!(path, uri), do: head!(path, uri) def exists!(url_or_path_or_uri), do: head!(url_or_path_or_uri) @doc """ Composes an URN from parts into request ready path as a binary string. ## Examples: iex> urn ["bear_test", "/_alias", ["2015", "2016"]] "bear_test/_alias/2015,2016" iex> urn [["bear_test", "another_bear_test"], "_refresh", { [ignore_unavailable: true] }] "bear_test,another_bear_test/_refresh?ignore_unavailable=true" iex> urn("bear_test", "bear_type", "10", "_explain?analyzer=some") "bear_test/bear_type/10/_explain?analyzer=some" Also see `Tirexs.HTTP.url/1`. """ def urn(part) when is_binary(part) do normalize(part) end def urn(parts) when is_list(parts) do Enum.map(parts, fn(part) -> normalize(part) end) |> Enum.join("/") |> String.replace("/?", "?") end def urn(a, b), do: urn([a ,b]) def urn(a, b, c), do: urn([a,b,c]) def urn(a, b, c, d), do: urn([a,b,c,d]) def urn(a, b, c, d, e), do: urn([a,b,c,d,e]) def urn(a, b, c, d, e, f), do: urn([a,b,c,d,e,f]) def urn(a, b, c, d, e, f, g), do: urn([a,b,c,d,e,f,g]) @doc false def normalize(resource) when is_binary(resource) do String.strip(resource) |> String.replace_prefix("/", "") end def normalize({ params }) do "?" <> URI.encode_query(params) end def normalize(resource) do pluralize(resource) |> normalize() end @doc false def pluralize(resource) when is_integer(resource), do: to_string(resource) def pluralize(resource) when is_binary(resource), do: resource def pluralize(resource), do: Enum.join(resource, ",") @doc """ Tries to bump resource. This one just makes a request and behaves like a proxy to one of avalable resource helper. You're able to bump any resources which are defined in `Tirexs.Resources.APIs`. Let's consider the following use case: iex> path = Tirexs.Resources.APIs._refresh(["bear_test", "duck_test"], { [force: false] }) "bear_test,duck_test/_refresh?force=false" iex> Tirexs.HTTP.post(path) { :ok, 200, ... } With bump, the same is: iex> bump._refresh(["bear_test", "duck_test"], { [force: false] }) { :ok, 200, ... } It is also available for bumping some resources with request body: iex> search = [query: [ term: [ user: "zatvobor" ] ] ] iex> bump(search)._count("bear_test", "my_type") { :ok, 200, ... } iex> payload = "{ \"index\": { \"_id\": \"2\" }}\n{ \"title\": \"My second blog post\" }\n" iex> bump(payload)._bulk("website", "blog", { [refresh: true] }) { :ok, 200, ... } Play with resources you have and see what kind of HTTP verb is used. """ def bump(), do: __t(:bump) def bump(%URI{} = uri), do: __t(:bump, [], uri) def bump(body), do: __t(:bump, body) def bump(body, %URI{} = uri), do: __t(:bump, body, uri) def bump!(), do: __t(:bump!) def bump!(%URI{} = uri), do: __t(:bump!, [], uri) def bump!(body), do: __t(:bump!, body) def bump!(body, %URI{} = uri), do: __t(:bump!, body, uri) @doc false def __c(urn, meta) when is_binary(urn) do if ctx = Process.delete(:tirexs_resources_chain) do args = case { urn, ctx[:body] } do { urn, [] } -> [ urn, ctx[:uri] ] { urn, body } -> [ urn, ctx[:uri], body ] end Kernel.apply(Tirexs.HTTP, meta[ctx[:label]], args) else urn end end @doc false defp __t(label, body \\ [], %URI{} = uri \\ Tirexs.ENV.get_uri_env()) do Process.put(:tirexs_resources_chain, [label: label, body: body, uri: uri]) Tirexs.Resources.APIs end end
33.377953
128
0.623496
93cd5fcc949a433ab202f2b22a29ce6b3380359b
2,224
ex
Elixir
lib/payments/orders.ex
DiscoveryMap/PayPal
2884bc0dde07a007d85467e4c7766f2ab4f79360
[ "MIT" ]
null
null
null
lib/payments/orders.ex
DiscoveryMap/PayPal
2884bc0dde07a007d85467e4c7766f2ab4f79360
[ "MIT" ]
null
null
null
lib/payments/orders.ex
DiscoveryMap/PayPal
2884bc0dde07a007d85467e4c7766f2ab4f79360
[ "MIT" ]
2
2020-11-03T07:06:19.000Z
2021-04-01T07:16:57.000Z
defmodule PayPal.Payments.Orders do @moduledoc """ Documentation for PayPal.Payments.Orders https://developer.paypal.com/docs/api/payments/#order """ @doc """ Show an order [docs](https://developer.paypal.com/docs/api/payments/#order_get) Possible returns: - {:ok, order} - {:error, reason} ## Examples iex> PayPal.Payments.Orders.show(order_id) {:ok, order} """ @spec show(String.t) :: {:ok, map | :not_found | :no_content } | {:error, :unauthorised | :bad_network | any} def show(order_id) do PayPal.API.get("payments/order/#{order_id}") end @doc """ Authorize an order [docs](https://developer.paypal.com/docs/api/payments/#order_authorize) Possible returns: - {:ok, refund} - {:error, refund} ## Examples iex> PayPal.Payments.Orders.authorize(order_id, %{ amount: %{ total: "1.50", currency: "USD" } }) {:ok, refund} """ @spec authorize(String.t, map) :: {:ok, map | :not_found | :no_content | nil} | {:error, :unauthorised | :bad_network | any} def authorize(payment_id, params) do PayPal.API.post("payments/orders/#{payment_id}/authorize", params) end @doc """ Capture an order [docs](https://developer.paypal.com/docs/api/payments/#order_capture) Possible returns: - {:ok, capture} - {:error, refund} ## Examples iex> PayPal.Payments.Orders.capture(order_id, %{ amount: %{ total: "1.50", currency: "USD" }, is_final_capture: true }) {:ok, capture} """ @spec capture(String.t, map) :: {:ok, map | :not_found | :no_content} | {:error, :unauthorised | :bad_network | any} def capture(order_id, params) do PayPal.API.post("payments/orders/#{order_id}/capture", params) end @doc """ Void an order [docs](https://developer.paypal.com/docs/api/payments/#order_void) Possible returns: - {:ok, order} - {:error, reason} ## Examples iex> PayPal.Payments.Orders.void(order_id) {:ok, order} """ @spec void(String.t) :: {:ok, map | :not_found | :no_content} | {:error, :unauthorised | :bad_network | any} def void(order_id) do PayPal.API.post("payments/order/#{order_id}/void", nil) end end
22.464646
126
0.625
93cda5f80f036a29028280fa02c296c2ddc0b527
1,183
ex
Elixir
lib/mongo/event_handler.ex
aenglisc/elixir-mongodb-driver
a8a72fbb8690f44ac349e0449616ac2cfbf50640
[ "Apache-2.0" ]
140
2019-04-10T09:23:53.000Z
2022-03-27T12:37:02.000Z
lib/mongo/event_handler.ex
aenglisc/elixir-mongodb-driver
a8a72fbb8690f44ac349e0449616ac2cfbf50640
[ "Apache-2.0" ]
99
2019-04-11T07:46:45.000Z
2022-03-31T07:23:28.000Z
lib/mongo/event_handler.ex
aenglisc/elixir-mongodb-driver
a8a72fbb8690f44ac349e0449616ac2cfbf50640
[ "Apache-2.0" ]
45
2019-07-15T07:06:21.000Z
2021-11-24T09:23:21.000Z
defmodule Mongo.EventHandler do @moduledoc false require Logger @all [:commands, :topology] def start(opts \\ [topics: [:commands]]) do spawn(__MODULE__, :register, [opts]) end def register(opts) do with true <- (opts[:topics] || @all) |> Enum.map(fn topic -> Registry.register(:events_registry, topic, []) end) |> Enum.all?(fn {:ok, _} -> true _other -> false end) do listen(opts) :ok end end def listen(opts) do receive do {:broadcast, :commands, %{command_name: cmd} = message} when cmd != :isMaster -> Logger.info("Received command: " <> (inspect message)) listen(opts) {:broadcast, :commands, is_master} -> case opts[:is_master] do true -> Logger.info("Received is master:" <> (inspect is_master)) _ -> [] end listen(opts) {:broadcast, topic, message} -> Logger.info("Received #{topic}: " <> (inspect message)) listen(opts) other -> Logger.info("Stopping EventHandler received unknown message:" <> inspect other) end end end
25.170213
91
0.550296
93cdc0953022194a25e8dd9e5f7e44d8c9b61c1d
666
ex
Elixir
lib/web/controllers/skill_controller.ex
NatTuck/ex_venture
7a74d33025a580f1e3e93d3755f22258eb3e9127
[ "MIT" ]
null
null
null
lib/web/controllers/skill_controller.ex
NatTuck/ex_venture
7a74d33025a580f1e3e93d3755f22258eb3e9127
[ "MIT" ]
null
null
null
lib/web/controllers/skill_controller.ex
NatTuck/ex_venture
7a74d33025a580f1e3e93d3755f22258eb3e9127
[ "MIT" ]
null
null
null
defmodule Web.SkillController do use Web, :controller alias Web.Skill plug(Web.Plug.FetchPage, [per: 10] when action in [:index]) def index(conn, _params) do %{page: page, per: per} = conn.assigns %{page: skills, pagination: pagination} = Skill.all(page: page, per: per, filter: %{enabled: true}) conn |> assign(:skills, skills) |> assign(:pagination, pagination) |> render(:index) end def show(conn, %{"id" => id}) do case Skill.get(id) do nil -> conn |> redirect(to: public_page_path(conn, :index)) skill -> conn |> assign(:skill, skill) |> render(:show) end end end
21.483871
103
0.594595
93cdebb7f6087ed5f930596870a341b3feff19e1
4,393
exs
Elixir
test/comeonin_test.exs
echenim/comeonin
1ff00b118dda3094ec2181c1d4c7bd5eabc9360d
[ "BSD-3-Clause" ]
2
2019-02-10T01:22:22.000Z
2019-02-11T20:47:28.000Z
test/comeonin_test.exs
echenim/comeonin
1ff00b118dda3094ec2181c1d4c7bd5eabc9360d
[ "BSD-3-Clause" ]
null
null
null
test/comeonin_test.exs
echenim/comeonin
1ff00b118dda3094ec2181c1d4c7bd5eabc9360d
[ "BSD-3-Clause" ]
null
null
null
defmodule ComeoninTest do use ExUnit.Case import ExUnit.CaptureIO import ComeoninTestHelper @algs [Comeonin.Argon2, Comeonin.Bcrypt, Comeonin.Pbkdf2] test "hashing and checking passwords" do wrong_list = ["aged2h$ru", "2dau$ehgr", "rg$deh2au", "2edrah$gu", "$agedhur2", ""] hash_check("hard2guess", wrong_list) end test "hashing and checking passwords with characters from the extended ascii set" do wrong_list = ["eáé åöêô ëaäo", "aäôáö eéoêë å", " aöêôée oåäëá", "åaêöéäëeoô á ", ""] hash_check("aáåä eéê ëoôö", wrong_list) end test "hashing and checking passwords with non-ascii characters" do wrong_list = [ "и Скл;лекьоток к олсомзь", "кеокок зС омлслтььлок;и", "е о оиькльлтСо;осккклзм", "" ] hash_check("Сколько лет; сколько зим", wrong_list) end test "hashing and checking passwords with mixed characters" do wrong_list = ["Я☕t☔s❤ùo", "o❤ Я☔ùrtês☕", " ùt❤o☕☔srêЯ", "ù☕os êt❤☔rЯ", ""] hash_check("Я❤três☕ où☔", wrong_list) end test "check password using check_pass, which uses the user map as input" do wrong_list = ["บดสคสััีวร", "สดรบัีสัคว", "สวดัรคบัสี", "ดรสสีวคบัั", "วรคดสัสีับ", ""] check_pass_check("สวัสดีครับ", wrong_list) end test "add hash to map and set password to nil" do wrong_list = ["êäöéaoeôáåë", "åáoêëäéôeaö", "aäáeåëéöêôo", ""] add_hash_check("aáåäeéêëoôö", wrong_list) end test "user obfuscation function always returns false" do for crypto <- @algs do assert crypto.dummy_checkpw() == false end end test "opts are passed on to the underlying function" do hash = Comeonin.Argon2.hashpwsalt("", t_cost: 2, m_cost: 12) assert String.starts_with?(hash, "$argon2i$v=19$m=4096,t=2") hash = Comeonin.Bcrypt.hashpwsalt("", log_rounds: 10) assert String.starts_with?(hash, "$2b$10$") hash = Comeonin.Pbkdf2.hashpwsalt("", rounds: 200, digest: :sha256) assert String.starts_with?(hash, "$pbkdf2-sha256$200$") end test "add_hash and check_pass" do for crypto <- @algs do assert {:ok, user} = crypto.add_hash("password") |> crypto.check_pass("password") assert {:error, "invalid password"} = crypto.add_hash("pass") |> crypto.check_pass("password") assert Map.has_key?(user, :password_hash) end end test "add_hash with a custom hash_key and check_pass" do for crypto <- @algs do assert {:ok, user} = crypto.add_hash("password", hash_key: :encrypted_password) |> crypto.check_pass("password") assert {:error, "invalid password"} = crypto.add_hash("pass", hash_key: :encrypted_password) |> crypto.check_pass("password") assert Map.has_key?(user, :encrypted_password) end end test "check_pass with custom hash_key" do for crypto <- @algs do assert {:ok, user} = crypto.add_hash("password", hash_key: :custom_hash) |> crypto.check_pass("password", hash_key: :custom_hash) assert Map.has_key?(user, :custom_hash) end end test "check_pass with invalid hash_key" do for crypto <- @algs do {:error, message} = crypto.add_hash("password", hash_key: :unconventional_name) |> crypto.check_pass("password") assert message =~ "no password hash found" end end test "check_pass with password that is not a string" do for crypto <- @algs do assert {:error, message} = crypto.add_hash("pass") |> crypto.check_pass(nil) assert message =~ "password is not a string" end end test "print stats report" do for crypto <- @algs do report = capture_io(fn -> crypto.report() end) assert report =~ "Verification OK" end end test "print stats report with options" do report = capture_io(fn -> Comeonin.Pbkdf2.report(digest: :sha256) end) assert report =~ "Digest:\t\tpbkdf2-sha256\n" assert report =~ "Digest length:\t32\n" assert report =~ "Verification OK" report = capture_io(fn -> Comeonin.Argon2.report(t_cost: 8, m_cost: 18) end) assert report =~ "Iterations:\t8\n" assert report =~ "Memory:\t\t256 MiB\n" assert report =~ "Verification OK" report = capture_io(fn -> Comeonin.Bcrypt.report(log_rounds: 10) end) assert report =~ "Hash:\t\t$2b$10$" assert report =~ "Verification OK" end end
33.030075
91
0.64967
93cdfdcc334755ce32ba8e3539184558510c50c0
2,694
exs
Elixir
exercises/simple-cipher/example.exs
darktef/elixir-exercism
bcaae351486b1405f0a01cd33b4d39555546298e
[ "MIT" ]
null
null
null
exercises/simple-cipher/example.exs
darktef/elixir-exercism
bcaae351486b1405f0a01cd33b4d39555546298e
[ "MIT" ]
null
null
null
exercises/simple-cipher/example.exs
darktef/elixir-exercism
bcaae351486b1405f0a01cd33b4d39555546298e
[ "MIT" ]
null
null
null
defmodule SimpleCipher do @alphabet "abcdefghijklmnopqrstuvwxyz" |> String.graphemes @alphabet_size @alphabet |> length for key_char <- @alphabet do shifted_alphabet = Stream.cycle(@alphabet) |> Stream.drop_while(&(&1 != key_char)) |> Enum.take(@alphabet_size) for { plain, cipher } <- Enum.zip(@alphabet, shifted_alphabet) do defp encode_char(unquote(plain), unquote(key_char)), do: unquote(cipher) defp decode_char(unquote(cipher), unquote(key_char)), do: unquote(plain) end end defp encode_char(plain, _), do: plain defp decode_char(cipher, _), do: cipher defp encode_char({plain, key}), do: encode_char(plain, key) defp decode_char({cipher, key}), do: decode_char(cipher, key) @doc """ Given a `plaintext` and `key`, encode each character of the `plaintext` by shifting it by the corresponding letter in the alphabet shifted by the number of letters represented by the `key` character, repeating the `key` if it is shorter than the `plaintext`. For example, for the letter 'd', the alphabet is rotated to become: defghijklmnopqrstuvwxyzabc You would encode the `plaintext` by taking the current letter and mapping it to the letter in the same position in this rotated alphabet. abcdefghijklmnopqrstuvwxyz defghijklmnopqrstuvwxyzabc "a" becomes "d", "t" becomes "w", etc... Each letter in the `plaintext` will be encoded with the alphabet of the `key` character in the same position. If the `key` is shorter than the `plaintext`, repeat the `key`. Example: plaintext = "testing" key = "abc" The key should repeat to become the same length as the text, becoming "abcabca". If the key is longer than the text, only use as many letters of it as are necessary. """ def encode(plaintext, key) do convert_keystream(plaintext, key, &encode_char/1) end @doc """ Given a `ciphertext` and `key`, decode each character of the `ciphertext` by finding the corresponding letter in the alphabet shifted by the number of letters represented by the `key` character, repeating the `key` if it is shorter than the `ciphertext`. The same rules for key length and shifted alphabets apply as in `encode/2`, but you will go the opposite way, so "d" becomes "a", "w" becomes "t", etc..., depending on how much you shift the alphabet. """ def decode(ciphertext, key) do convert_keystream(ciphertext, key, &decode_char/1) end defp convert_keystream(text, key, converter) do keystream = key |> String.graphemes |> Stream.cycle text |> String.graphemes |> Enum.zip(keystream) |> Enum.map_join(converter) end end
33.259259
79
0.702673
93ce06943b4d2afb130908bdf0191272a914e342
12,696
ex
Elixir
lib/ueberauth/strategy.ex
fastindian84/ueberauth
09f402672e4564930be5f5f4d746df9b1fa47bfe
[ "MIT" ]
null
null
null
lib/ueberauth/strategy.ex
fastindian84/ueberauth
09f402672e4564930be5f5f4d746df9b1fa47bfe
[ "MIT" ]
null
null
null
lib/ueberauth/strategy.ex
fastindian84/ueberauth
09f402672e4564930be5f5f4d746df9b1fa47bfe
[ "MIT" ]
null
null
null
defmodule Ueberauth.Strategy do @moduledoc """ The Strategy is the work-horse of the system. Strategies are implemented outside this library to meet your needs, the strategy provides a consistent API and behaviour. Each strategy operates through two phases. 1. `request phase` 2. `callback phase` These phases can be understood with the following psuedocode. ### Request Phase request (for the request phase - default /auth/:provider) |> relevant_strategy.handle_request!(conn) |> continue with request plug pipeline The request phase follows normal plug pipeline behaviour. The request will not continue if the strategy halted the connection. ### Callback Phase request (for a callback phase - default /auth/:provider/callback) |> relevant_strategy.handle_auth!(conn) if connection does not have ueberauth failure |> set ueberauth auth with relevant_strategy.auth |> cleanup from the strategy with relevant_strategy.handle_cleanup! |> continue with plug pipeline The callback phase is essentially a decorator and does not usually redirect or halt the request. Its result is that one of two cases will end up in your connections assigns when it reaches your controller. * On Failure - An `Ueberauth.Failure` struct is available at `:ueberauth_failure` * On Success - An `Ueberauth.Auth` struct is available at `:ueberauth_auth` ### An example The simplest example is an email/password strategy. This does not intercept the request and just decorates it with the `Ueberauth.Auth` struct. (it is always successful) defmodule Ueberauth.Strategies.Identity do use Ueberauth.Strategy alias Ueberauth.Auth.Credentials alias Ueberauth.Auth.Extra def uid(conn), do: conn.params["email"] def extra(conn), do: struct(Extra, raw_info: conn.params) def credentials(conn) do %Credentials{ other: %{ password: conn.params["password"], password_confirmation: conn.params["password_confirmation"] } } end end After the strategy has run through the `c:handle_callback!/1` function, since there are no errors added, Ueberauth will add the constructed auth struct to the connection. The Auth struct is constructed like: def auth(conn) do %Auth{ provider: strategy_name(conn), strategy: strategy(conn), uid: uid(conn), info: info(conn), extra: extra(conn), credentials: credentials(conn) } end Each component of the struct is a separate function and receives the connection object. From this Ueberauth will construct and assign the struct for processing in your own controller. ### Redirecting during the request phase Many strategies may require a redirect (looking at you OAuth). To do this, implement the `c:handle_request!/1` function. def handle_request!(conn) do callback_url = callback_url(conn) redirect!(conn, callback_url) end ### Callback phase The callback phase may not do anything other than instruct the strategy where to get the information to construct the auth struct. In that case define the functions for the components of the struct and fetch the information from the connection struct. In the case where you do need to take some other step, the `c:handle_callback!/1` function is where its at. def handle_callback!(conn) do conn |> call_external_service_and_assign_result_to_private end def uid(conn) do fetch_from_my_private_area(conn, :username) end def handle_cleanup!(conn) do remove_my_private_area(conn) end This provides a simplistic psuedocode look at what a callback + cleanup phase might look like. By setting the result of your call to the external service in the connections private assigns, you can use that to construct the auth struct in the auth component functions. Of course, as a good citizen you also cleanup the connection before the request continues. ### Cleanup phase The cleanup phase is provided for you to be a good citizen and clean up after your strategy. During the callback phase, you may need to temporarily store information in the private section of the conn struct. Once this is done, the cleanup phase exists to cleanup that temporary storage after the strategy has everything it needs. Implement the `c:handle_cleanup!/1` function and return the cleaned conn struct. ### Adding errors during callback You have two options when you're in the callback phase. Either you can let the connection go through and Ueberauth will construct the auth hash for you, or you can add errors. You should add errors before you leave your `c:handle_callback!/1` function. def handle_callback!(conn) do errors = [] if (something_bad), do: errors = [error("error_key", "Some message") | errors] if (length(errors) > 0) do set_errors!(errors) else conn end end Once you've set errors, Ueberauth will not set the auth struct in the connections assigns at `:ueberauth_auth`, instead it will set a `Ueberauth.Failure` struct at `:ueberauth_failure` with the information provided detailing the failure. """ alias Plug.Conn alias Ueberauth.Strategy.Helpers alias Ueberauth.Failure.Error alias Ueberauth.Auth alias Ueberauth.Auth.Credentials alias Ueberauth.Auth.Info alias Ueberauth.Auth.Extra @state_param_cookie_name "ueberauth.state_param" @doc """ The request phase implementation for your strategy. Setup, redirect or otherwise in here. This is an information gathering phase and should provide the end user with a way to provide the information required for your application to authenticate them. """ @callback handle_request!(Plug.Conn.t()) :: Plug.Conn.t() @doc """ The callback phase implementation for your strategy. In this function you should make any external calls you need, check for errors etc. The result of this phase is that either a failure (`Ueberauth.Failure`) will be assigned to the connections assigns at `ueberauth_failure` or an `Ueberauth.Auth` struct will be constrcted and added to the assigns at `:ueberauth_auth`. """ @callback handle_callback!(Plug.Conn.t()) :: Plug.Conn.t() @doc """ The cleanup phase implementation for your strategy. The cleanup phase runs after the callback phase and is present to provide a mechanism to cleanup any temporary data your strategy may have placed in the connection. """ @callback handle_cleanup!(Plug.Conn.t()) :: Plug.Conn.t() @doc """ Provides the uid for the user. This is one of the component functions that is used to construct the auth struct. What you return here will be in the auth struct at the `uid` key. """ @callback uid(Plug.Conn.t()) :: binary | nil @doc """ Provides the info for the user. This is one of the component functions that is used to construct the auth struct. What you return here will be in the auth struct at the `info` key. """ @callback info(Plug.Conn.t()) :: Info.t() @doc """ Provides the extra params for the user. This is one of the component functions that is used to construct the auth struct. What you return here will be in the auth struct at the `extra` key. You would include any additional information within extra that does not fit in either `info` or `credentials` """ @callback extra(Plug.Conn.t()) :: Extra.t() @doc """ Provides the credentials for the user. This is one of the component functions that is used to construct the auth struct. What you return here will be in the auth struct at the `credentials` key. """ @callback credentials(Plug.Conn.t()) :: Credentials.t() @doc """ When defining your own strategy you should use Ueberauth.Strategy. This provides default callbacks for all required callbacks to meet the Ueberauth.Strategy behaviour and imports some helper functions found in `Ueberauth.Strategy.Helpers` ### Imports * Ueberauth.Stratgey.Helpers * Plug.Conn ## Default Options When using the strategy you can pass a keyword list for default options: defmodule MyStrategy do use Ueberauth.Strategy, some: "options" # … end MyStrategy.default_options # [ some: "options" ] These options are made available to your strategy at `YourStrategy.default_options`. On a per usage level, other options can also be passed to the strategy to provide customization. ### Cross-Site Request Forgery By default strategies must implement https://tools.ietf.org/html/rfc6749#section-10.12 if you wish to disable such feature, use `:ignores_csrf_attack` option: defmodule MyStrategy do use Ueberauth.Strategy, ignores_csrf_attack: true # … end Althought we strongly recommend never disable such feature, unless you have some technical limitations that forces you to use such `:ignores_csrf_attack`. """ defmacro __using__(opts \\ []) do quote location: :keep do @behaviour Ueberauth.Strategy import Ueberauth.Strategy.Helpers import Plug.Conn, except: [request_url: 1] def default_options, do: unquote(opts) def uid(conn), do: nil def info(conn), do: %Info{} def extra(conn), do: %Extra{} def credentials(conn), do: %Credentials{} def handle_request!(conn), do: conn def handle_callback!(conn), do: conn def handle_cleanup!(conn), do: conn def auth(conn) do struct( Auth, provider: strategy_name(conn), strategy: strategy(conn), uid: uid(conn), info: info(conn), extra: extra(conn), credentials: credentials(conn) ) end defoverridable uid: 1, info: 1, extra: 1, credentials: 1, handle_request!: 1, handle_callback!: 1, handle_cleanup!: 1 end end @doc false def run_request(conn, strategy) do conn |> maybe_add_state_param() |> run_handle_request(strategy) end @doc false def run_callback(conn, strategy) do with false <- get_ignores_csrf_attack_option(conn), false <- state_param_matches?(conn) do add_state_mismatch_error(conn, strategy) else true -> run_handle_callback(conn, strategy) end end defp handle_callback_result(%{halted: true} = conn, _), do: conn defp handle_callback_result(%{assigns: %{ueberauth_failure: _}} = conn, _), do: conn defp handle_callback_result(%{assigns: %{ueberauth_auth: %{}}} = conn, _), do: conn defp handle_callback_result(conn, strategy) do auth = apply(strategy, :auth, [conn]) Plug.Conn.assign(conn, :ueberauth_auth, auth) end defp state_param_matches?(conn) do param_cookie = conn.params["state"] not is_nil(param_cookie) and param_cookie == get_state_cookie(conn) end defp add_state_mismatch_error(conn, strategy) do conn |> Helpers.set_errors!([ %Error{message_key: :csrf_attack, message: "Cross-Site Request Forgery attack"} ]) |> run_handle_cleanup(strategy) end defp run_handle_request(conn, strategy) do apply(strategy, :handle_request!, [conn]) end defp run_handle_callback(conn, strategy) do conn = remove_state_cookie(conn) strategy |> apply(:handle_callback!, [conn]) |> handle_callback_result(strategy) |> run_handle_cleanup(strategy) end defp run_handle_cleanup(conn, strategy) do apply(strategy, :handle_cleanup!, [conn]) end defp maybe_add_state_param(conn) do if get_ignores_csrf_attack_option(conn) do conn else add_state_param(conn) end end defp get_ignores_csrf_attack_option(conn) do Helpers.options(conn) |> Keyword.get(:ignores_csrf_attack, false) end defp add_state_param(conn) do state = create_state_param() conn |> Conn.put_resp_cookie(@state_param_cookie_name, state, same_site: "Lax") |> Helpers.add_state_param(state) end defp get_state_cookie(conn) do conn |> Conn.fetch_session() |> Map.get(:cookies) |> Map.get(@state_param_cookie_name) end defp remove_state_cookie(conn) do Conn.delete_resp_cookie(conn, @state_param_cookie_name) end defp create_state_param do 24 |> :crypto.strong_rand_bytes() |> Base.url_encode64() |> binary_part(0, 24) end end
30.965854
88
0.695888
93ce08509ac47dbae994b48637f415c1c8596e86
406
ex
Elixir
web/views/division_view.ex
rob05c/tox
f54847ca058ad24b909341ad65d595a4069d2471
[ "Apache-2.0" ]
2
2016-11-16T17:24:21.000Z
2019-02-15T05:38:27.000Z
web/views/division_view.ex
rob05c/tox
f54847ca058ad24b909341ad65d595a4069d2471
[ "Apache-2.0" ]
null
null
null
web/views/division_view.ex
rob05c/tox
f54847ca058ad24b909341ad65d595a4069d2471
[ "Apache-2.0" ]
null
null
null
defmodule Tox.DivisionView do use Tox.Web, :view def render("index.json", %{divisions: divisions}) do %{data: render_many(divisions, Tox.DivisionView, "division.json")} end def render("show.json", %{division: division}) do %{data: render_one(division, Tox.DivisionView, "division.json")} end def render("division.json", %{division: division}) do %{name: division.name} end end
25.375
70
0.687192
93ce3a25c5e30fbe5aa60fc7a0378b264fb326e4
1,451
ex
Elixir
lib/malan/accounts/ethnicity_enum.ex
FreedomBen/malan
ec8cd6ed3694e33371f065f018b1169956f2accf
[ "MIT" ]
3
2021-04-24T17:54:55.000Z
2021-09-10T15:40:19.000Z
lib/malan/accounts/ethnicity_enum.ex
FreedomBen/malan
ec8cd6ed3694e33371f065f018b1169956f2accf
[ "MIT" ]
57
2021-04-24T03:17:16.000Z
2022-03-27T04:50:22.000Z
lib/malan/accounts/ethnicity_enum.ex
FreedomBen/malan
ec8cd6ed3694e33371f065f018b1169956f2accf
[ "MIT" ]
null
null
null
defmodule Malan.Accounts.User.Ethnicity do def get(i) when is_integer(i), do: all_by_value()[i] def get(i) when is_binary(i), do: all_by_keyword_normalized()[normalize(i)] def to_s(nil), do: nil def to_s(i) when is_integer(i), do: get(i) def to_s(s) when is_binary(s), do: get(s) def to_i(nil), do: nil def to_i(s) when is_binary(s), do: get(s) def valid?(i) when is_nil(i), do: true def valid?(i) when is_integer(i), do: Map.has_key?(all_by_value(), i) def valid?(i) when is_binary(i) do all_by_keyword() |> Map.merge(all_by_keyword_normalized()) |> Map.has_key?(i) end def valid_values(), do: Map.keys(all_by_keyword()) def valid_values_str(), do: Enum.join(valid_values(), ", ") def normalize(g) when is_binary(g), do: String.downcase(g) def normalize_key({k, v}) when is_binary(k), do: {normalize(k), v} def normalize_value({k, v}) when is_binary(v), do: {k, normalize(v)} def equal?(f, s), do: normalize(f) == normalize(s) def all_by_value_normalized() do all_by_value() |> Enum.map(&normalize_value/1) |> Enum.into(%{}) end def all_by_keyword_normalized() do all_by_keyword() |> Enum.map(&normalize_key/1) |> Enum.into(%{}) end def all_by_value() do %{ 0 => "Hispanic or Latinx", 1 => "Not Hispanic or Latinx" } end def all_by_keyword() do %{ "Hispanic or Latinx" => 0, "Not Hispanic or Latinx" => 1 } end end
26.87037
77
0.636802
93ce989330b3b787704da2522404e21569d464d8
613
exs
Elixir
test/crypto_monitor_web/views/error_view_test.exs
obahareth/crypto-monitor
bd9e9f1e9627fad582329afe2c66e2de4c95768b
[ "MIT" ]
null
null
null
test/crypto_monitor_web/views/error_view_test.exs
obahareth/crypto-monitor
bd9e9f1e9627fad582329afe2c66e2de4c95768b
[ "MIT" ]
null
null
null
test/crypto_monitor_web/views/error_view_test.exs
obahareth/crypto-monitor
bd9e9f1e9627fad582329afe2c66e2de4c95768b
[ "MIT" ]
null
null
null
defmodule CryptoMonitorWeb.ErrorViewTest do use CryptoMonitorWeb.ConnCase, async: true # Bring render/3 and render_to_string/3 for testing custom views import Phoenix.View test "renders 404.html" do assert render_to_string(CryptoMonitorWeb.ErrorView, "404.html", []) == "Page not found" end test "render 500.html" do assert render_to_string(CryptoMonitorWeb.ErrorView, "500.html", []) == "Internal server error" end test "render any other" do assert render_to_string(CryptoMonitorWeb.ErrorView, "505.html", []) == "Internal server error" end end
27.863636
74
0.699837
93cea555b678ab35bb77cefd66b7dcac3d9ad6d3
176
ex
Elixir
lib/shiftplaner_web_web/controllers/admin_controller.ex
pfitz/shiftplaner_web
ca961b4916e76bb2c87c83c28d8f286dfaa2f2fe
[ "MIT" ]
null
null
null
lib/shiftplaner_web_web/controllers/admin_controller.ex
pfitz/shiftplaner_web
ca961b4916e76bb2c87c83c28d8f286dfaa2f2fe
[ "MIT" ]
null
null
null
lib/shiftplaner_web_web/controllers/admin_controller.ex
pfitz/shiftplaner_web
ca961b4916e76bb2c87c83c28d8f286dfaa2f2fe
[ "MIT" ]
null
null
null
defmodule ShiftplanerWebWeb.AdminController do @moduledoc false use ShiftplanerWebWeb, :controller def index(conn, _params) do render conn, "index.html" end end
16
46
0.755682
93ceafa528a2e1f433955169f23f01e6c67f670a
2,400
exs
Elixir
test/authable/config_test.exs
liberumed/authable
6db9951aa07000b358f16ffe413a13aa9aa89192
[ "Unlicense" ]
null
null
null
test/authable/config_test.exs
liberumed/authable
6db9951aa07000b358f16ffe413a13aa9aa89192
[ "Unlicense" ]
null
null
null
test/authable/config_test.exs
liberumed/authable
6db9951aa07000b358f16ffe413a13aa9aa89192
[ "Unlicense" ]
1
2021-01-12T00:55:56.000Z
2021-01-12T00:55:56.000Z
defmodule Authable.ConfigTest do use ExUnit.Case alias Authable.Config test ".repo" do assert Authable.Repo == Config.repo() end test ".scopes" do assert ~w(read write session) == Config.scopes() end test ".app_scopes" do assert "read,write,session" == Config.app_scopes() end test ".grant_types" do grant_types = %{ authorization_code: Authable.GrantType.AuthorizationCode, client_credentials: Authable.GrantType.ClientCredentials, password: Authable.GrantType.Password, refresh_token: Authable.GrantType.RefreshToken } assert grant_types == Config.grant_types() end test ".auth_strategies" do auth_strategies = %{ headers: %{ "authorization" => [ {~r/Basic ([a-zA-Z\-_\+=]+)/, Authable.Authentication.Basic}, {~r/Bearer ([a-zA-Z\-_\+=]+)/, Authable.Authentication.Bearer} ], "x-api-token" => [ {~r/([a-zA-Z\-_\+=]+)/, Authable.Authentication.Bearer} ] }, query_params: %{ "access_token" => Authable.Authentication.Bearer }, sessions: %{ "session_token" => Authable.Authentication.Session } } assert auth_strategies == Config.auth_strategies() end test ".header_auth" do headers = %{ "authorization" => [ {~r/Basic ([a-zA-Z\-_\+=]+)/, Authable.Authentication.Basic}, {~r/Bearer ([a-zA-Z\-_\+=]+)/, Authable.Authentication.Bearer} ], "x-api-token" => [ {~r/([a-zA-Z\-_\+=]+)/, Authable.Authentication.Bearer} ] } assert headers == Config.header_auth() end test ".query_params_auth" do query_params = %{ "access_token" => Authable.Authentication.Bearer } assert query_params == Config.query_params_auth() end test ".session_auth" do session_auth = %{ "session_token" => Authable.Authentication.Session } assert session_auth == Config.session_auth() end test ".expires_in" do expires_in = %{ access_token: 3600, refresh_token: 24 * 3600, authorization_code: 300, session_token: 30 * 24 * 3600 } assert expires_in == Config.expires_in() end test ".renderer" do assert Authable.Renderer.RestApi == Config.renderer() end test ".app_authorization" do assert Authable.Stub.AppAuthorization == Config.app_authorization() end end
24.242424
72
0.6175
93cebf07bcd93cf71c488a1791d659569a0e87e2
2,290
ex
Elixir
lib/quark/fixed_point.ex
toraritte/quark
acf18de05a86ba4740fdffdbb93918ce4ebfeb5f
[ "MIT" ]
null
null
null
lib/quark/fixed_point.ex
toraritte/quark
acf18de05a86ba4740fdffdbb93918ce4ebfeb5f
[ "MIT" ]
null
null
null
lib/quark/fixed_point.ex
toraritte/quark
acf18de05a86ba4740fdffdbb93918ce4ebfeb5f
[ "MIT" ]
null
null
null
defmodule Quark.FixedPoint do @moduledoc ~S""" Fixed point combinators generalize the idea of a recursive function. This can be used to great effect, simplifying many definitions. For example, here is the factorial function written in terms of `y/1`: iex> fac = fn fac -> ...> fn ...> 0 -> 0 ...> 1 -> 1 ...> n -> n * fac.(n - 1) ...> end ...> end ...> factorial = y(fac) ...> factorial.(9) 362880 The resulting function will always be curried iex> import Quark.SKI, only: [s: 3] ...> one_run = y(&s/3) ...> {_, arity} = :erlang.fun_info(one_run, :arity) ...> arity 1 """ use Quark.Partial import Quark.Curry, only: [curry: 1] defdelegate fix(), to: __MODULE__, as: :y defdelegate fix(a), to: __MODULE__, as: :y @doc ~S""" The famous Y-combinator. The resulting function will always be curried. ## Examples iex> fac = fn fac -> ...> fn ...> 0 -> 0 ...> 1 -> 1 ...> n -> n * fac.(n - 1) ...> end ...> end ...> factorial = y(fac) ...> factorial.(9) 362880 """ @spec y(fun) :: fun defpartial y(fun) do (fn x -> x.(x) end).(fn y -> curry(fun).(fn arg -> y.(y).(arg) end) end) end @doc ~S""" Alan Turing's fix-point combinator. This is the call-by-value formulation. ## Examples iex> fac = fn fac -> ...> fn ...> 0 -> 0 ...> 1 -> 1 ...> n -> n * fac.(n - 1) ...> end ...> end ...> factorial = turing(fac) ...> factorial.(9) 362880 """ @spec turing(fun) :: fun defpartial turing(fun), do: turing_inner().(turing_inner()).(fun) defpartialp turing_inner(x, y) do cx = curry(x) cy = curry(y) cy.(&(cx.(cx).(cy).(&1))) end @doc ~S""" A [normal order](https://wikipedia.org/wiki/Evaluation_strategy#Normal_order) fixed point. ## Examples iex> fac = fn fac -> ...> fn ...> 0 -> 0 ...> 1 -> 1 ...> n -> n * fac.(n - 1) ...> end ...> end ...> factorial = z(fac) ...> factorial.(9) 362880 """ @spec z(fun, any) :: fun defpartial z(g, v), do: g.(z(g)).(v) end
21.603774
79
0.480349
93ced94de08e63e4b97aebc402222d903c0d8338
2,108
ex
Elixir
clients/identity_toolkit/lib/google_api/identity_toolkit/v3/model/set_account_info_response_provider_user_info.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
null
null
null
clients/identity_toolkit/lib/google_api/identity_toolkit/v3/model/set_account_info_response_provider_user_info.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
null
null
null
clients/identity_toolkit/lib/google_api/identity_toolkit/v3/model/set_account_info_response_provider_user_info.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.IdentityToolkit.V3.Model.SetAccountInfoResponseProviderUserInfo do @moduledoc """ ## Attributes - displayName (String.t): The user&#39;s display name at the IDP. Defaults to: `null`. - federatedId (String.t): User&#39;s identifier at IDP. Defaults to: `null`. - photoUrl (String.t): The user&#39;s photo url at the IDP. Defaults to: `null`. - providerId (String.t): The IdP ID. For whitelisted IdPs it&#39;s a short domain name, e.g., google.com, aol.com, live.net and yahoo.com. For other OpenID IdPs it&#39;s the OP identifier. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :displayName => any(), :federatedId => any(), :photoUrl => any(), :providerId => any() } field(:displayName) field(:federatedId) field(:photoUrl) field(:providerId) end defimpl Poison.Decoder, for: GoogleApi.IdentityToolkit.V3.Model.SetAccountInfoResponseProviderUserInfo do def decode(value, options) do GoogleApi.IdentityToolkit.V3.Model.SetAccountInfoResponseProviderUserInfo.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.IdentityToolkit.V3.Model.SetAccountInfoResponseProviderUserInfo do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34
211
0.723909
93cf1b67ae4f797ccf1ab406a1f20afd10d99274
6,016
exs
Elixir
test/credo/code/strings_test.exs
rubysolo/credo
0aecde3001af7cf804253df923019aaaf08522d5
[ "MIT" ]
null
null
null
test/credo/code/strings_test.exs
rubysolo/credo
0aecde3001af7cf804253df923019aaaf08522d5
[ "MIT" ]
null
null
null
test/credo/code/strings_test.exs
rubysolo/credo
0aecde3001af7cf804253df923019aaaf08522d5
[ "MIT" ]
null
null
null
defmodule Credo.Code.StringsTest do use Credo.Test.Case alias Credo.Code.Strings test "it should return the source without string literals 2" do source = """ @moduledoc \"\"\" this is an example # TODO: and this is no actual comment \"\"\" x = ~s{also: # TODO: no comment here} ?" # TODO: this is the third # " "also: # TODO: no comment here as well" """ expected = """ @moduledoc \"\"\" @@EMPTY_STRING@@ \"\"\" x = ~s{ } ?" # TODO: this is the third # " " " """ |> String.replace( "@@EMPTY_STRING@@", " " ) assert expected == source |> Strings.replace_with_spaces() end test "it should return the source without string sigils 2" do source = """ should "not error for a quote in a heredoc" do errors = ~s( \"\"\" this is an example " TODO: and this is no actual comment \"\"\") |> lint assert [] == errors end """ result = source |> Strings.replace_with_spaces() assert source != result assert String.length(source) == String.length(result) refute String.contains?(result, "example") refute String.contains?(result, "TODO:") end test "it should return the source without string sigils 3" do source = ~S""" def gen_name(name) when is_binary(name), do: "#{String.replace_suffix(name, "-test", "")}_name" """ expected = ~S""" def gen_name(name) when is_binary(name), do: " " """ assert expected == Strings.replace_with_spaces(source) end test "it should return the source without string literals 3" do source = """ x = "↑ ↗ →" x = ~s|text| x = ~s"text" x = ~s'text' x = ~s(text) x = ~s[text] x = ~s{text} x = ~s<text> x = ~S|text| x = ~S"text" x = ~S'text' x = ~S(text) x = ~S[text] x = ~S{text} x = ~S<text> x = to_string('text') <> "text" ?" # <-- this is not a string """ expected = """ x = " " x = ~s| | x = ~s" " x = ~s' ' x = ~s( ) x = ~s[ ] x = ~s{ } x = ~s< > x = ~S| | x = ~S" " x = ~S' ' x = ~S( ) x = ~S[ ] x = ~S{ } x = ~S< > x = to_string('text') <> " " ?" # <-- this is not a string """ assert expected == source |> Strings.replace_with_spaces() end test "it should return the source without string sigils and replace the contents" do source = """ t = ~s({ }) """ expected = """ t = ~s(. .) """ result = source |> Strings.replace_with_spaces(".") assert expected == result end test "it should not modify commented out code" do source = """ defmodule Foo do defmodule Bar do # @doc \"\"\" # Reassign a student to a discussion group. # This will un-assign student from the current discussion group # \"\"\" # def assign_group(leader = %User{}, student = %User{}) do # cond do # leader.role == :student -> # {:error, :invalid} # # student.role != :student -> # {:error, :invalid} # # true -> # Repo.transaction(fn -> # {:ok, _} = unassign_group(student) # # %Group{} # |> Group.changeset(%{}) # |> put_assoc(:leader, leader) # |> put_assoc(:student, student) # |> Repo.insert!() # end) # end # end def baz, do: 123 end end """ expected = source assert expected == source |> Strings.replace_with_spaces(".") end test "it should NOT report expected code 2" do input = ~S""" escape_charlist('"\\' ++ r) """ assert input == Strings.replace_with_spaces(input) end test "it should replace interpolations" do input = ~S""" x = "#{~s(Hello, #{name})}" """ expected = ~S""" x = " " """ assert expected == Strings.replace_with_spaces(input) end @example_code File.read!("test/fixtures/example_code/nested_escaped_heredocs.ex") test "it should produce valid code /2" do result = Strings.replace_with_spaces(@example_code) result2 = Strings.replace_with_spaces(result) assert result == result2 assert match?({:ok, _}, Code.string_to_quoted(result)) end @tag slow: :disk_io @example_code2 File.read!("test/fixtures/example_code/large_heredoc.ex") test "it should produce valid code /3" do result = Strings.replace_with_spaces(@example_code2) result2 = Strings.replace_with_spaces(result) assert result == result2 assert match?({:ok, _}, Code.string_to_quoted(result)) end @tag slow: :disk_io test "it should produce valid code /5" do example_code = File.read!("test/fixtures/example_code/browser.ex") result = example_code |> to_source_file() |> Strings.replace_with_spaces(".", ".") result2 = result |> Strings.replace_with_spaces(".", ".") assert match?({:ok, _}, Code.string_to_quoted(result)) assert result == result2, "Strings.replace_with_spaces/2 should be idempotent" end @tag slow: :disk_io test "it should produce valid code with empty string as replacement /5" do example_code = File.read!("test/fixtures/example_code/browser.ex") result = example_code |> to_source_file() |> Strings.replace_with_spaces("", "") result2 = result |> Strings.replace_with_spaces("", "") IO.puts(result) assert match?({:ok, _}, Code.string_to_quoted(result)) assert result == result2, "Strings.replace_with_spaces/2 should be idempotent" end end
24.655738
86
0.527593
93cf532ecabc86e60e182c7c91e050fedeef719c
1,763
exs
Elixir
clients/logging/mix.exs
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/logging/mix.exs
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/logging/mix.exs
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.Logging.Mixfile do use Mix.Project @version "0.31.0" def project() do [ app: :google_api_logging, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/logging" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.4"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Cloud Logging API client library. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/logging", "Homepage" => "https://cloud.google.com/logging/docs/" } ] end end
26.313433
98
0.646625
93cf93a30f55739531156fb4269e92fd3b752947
306
ex
Elixir
lib/elixir_state_machines.ex
phasebash/elixir-finite-state-machines
ea920a6cdc320a32c9a4415ac34c062eb726f97a
[ "MIT" ]
null
null
null
lib/elixir_state_machines.ex
phasebash/elixir-finite-state-machines
ea920a6cdc320a32c9a4415ac34c062eb726f97a
[ "MIT" ]
null
null
null
lib/elixir_state_machines.ex
phasebash/elixir-finite-state-machines
ea920a6cdc320a32c9a4415ac34c062eb726f97a
[ "MIT" ]
null
null
null
defmodule ElixirStateMachines do @moduledoc """ Documentation for `ElixirStateMachines`. """ @doc """ This will at some point be interesting. ## Examples iex> ElixirStateMachines.demo() {:ok, "nothing to see here"} """ def demo do {:ok, "nothing to see here"} end end
16.105263
42
0.633987
93cfa81e2ce34cda2c9f3a1c48ea60532579128e
193
ex
Elixir
lib/doc_gen_web/controllers/about_controller.ex
the-mikedavis/doc_gen
efcc884ea65bba5748f41c5601abd00db2777ec4
[ "BSD-3-Clause" ]
null
null
null
lib/doc_gen_web/controllers/about_controller.ex
the-mikedavis/doc_gen
efcc884ea65bba5748f41c5601abd00db2777ec4
[ "BSD-3-Clause" ]
27
2018-10-29T18:34:44.000Z
2019-03-11T18:43:12.000Z
lib/doc_gen_web/controllers/about_controller.ex
the-mikedavis/doc_gen
efcc884ea65bba5748f41c5601abd00db2777ec4
[ "BSD-3-Clause" ]
null
null
null
defmodule DocGenWeb.AboutController do use DocGenWeb, :controller alias DocGen.Content.Copy def index(conn, _params) do render(conn, "index.html", copy: Copy.get(:about)) end end
19.3
54
0.73057
93cfe52ebacf6f34ba5c4951a09fea7078647359
1,927
ex
Elixir
clients/you_tube_reporting/lib/google_api/you_tube_reporting/v1/model/gdata_content_type_info.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/you_tube_reporting/lib/google_api/you_tube_reporting/v1/model/gdata_content_type_info.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/you_tube_reporting/lib/google_api/you_tube_reporting/v1/model/gdata_content_type_info.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.YouTubeReporting.V1.Model.GdataContentTypeInfo do @moduledoc """ gdata ## Attributes * `bestGuess` (*type:* `String.t`, *default:* `nil`) - gdata * `fromBytes` (*type:* `String.t`, *default:* `nil`) - gdata * `fromFileName` (*type:* `String.t`, *default:* `nil`) - gdata * `fromHeader` (*type:* `String.t`, *default:* `nil`) - gdata * `fromUrlPath` (*type:* `String.t`, *default:* `nil`) - gdata """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :bestGuess => String.t() | nil, :fromBytes => String.t() | nil, :fromFileName => String.t() | nil, :fromHeader => String.t() | nil, :fromUrlPath => String.t() | nil } field(:bestGuess) field(:fromBytes) field(:fromFileName) field(:fromHeader) field(:fromUrlPath) end defimpl Poison.Decoder, for: GoogleApi.YouTubeReporting.V1.Model.GdataContentTypeInfo do def decode(value, options) do GoogleApi.YouTubeReporting.V1.Model.GdataContentTypeInfo.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.YouTubeReporting.V1.Model.GdataContentTypeInfo do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
32.661017
88
0.689673
93cfeeda3c2192267feae4e120cd7337490d4b4a
847
exs
Elixir
samples/one_fast_fun.exs
JamesGood626/benchee
de9e99462f6e5ad03001460391a8bd82dbbba773
[ "MIT" ]
null
null
null
samples/one_fast_fun.exs
JamesGood626/benchee
de9e99462f6e5ad03001460391a8bd82dbbba773
[ "MIT" ]
null
null
null
samples/one_fast_fun.exs
JamesGood626/benchee
de9e99462f6e5ad03001460391a8bd82dbbba773
[ "MIT" ]
null
null
null
# Also way too fast and therefore not super feasible, more a test if # if benchmarking super fast functions has gotten any better. Benchee.run(%{"fast" => fn -> 1 + 1 end}, time: 1) # tobi@happy ~/github/benchee $ mix run samples/one_fast_fun.exs # Erlang/OTP 19 [erts-8.1] [source-4cc2ce3] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] # Elixir 1.3.4 # Benchmark suite executing with the following configuration: # warmup: 2.0s # time: 1.0s # parallel: 1 # Estimated total run time: 3.0s # # Benchmarking fast... # Warning: The function you are trying to benchmark is super fast, making measures more unreliable! See: https://github.com/PragTob/benchee/wiki/Benchee-Warnings#fast-execution-warning # # # Name ips average deviation median # fast 88.95 M 0.0112 μs ±14.82% 0.0110 μs
42.35
184
0.689492
93cff1efbd71b754d1570d44c478f002b8160913
9,481
exs
Elixir
lib/ex_unit/test/ex_unit/capture_io_test.exs
matiasgarciaisaia/elixir
d0a3fdbfd774e0a6972513dcb82c2683400e67a0
[ "Apache-2.0" ]
1
2015-11-24T23:39:25.000Z
2015-11-24T23:39:25.000Z
lib/ex_unit/test/ex_unit/capture_io_test.exs
lau/elixir
6cfe09c50b5f612e473725623d901080077ad6a6
[ "Apache-2.0" ]
null
null
null
lib/ex_unit/test/ex_unit/capture_io_test.exs
lau/elixir
6cfe09c50b5f612e473725623d901080077ad6a6
[ "Apache-2.0" ]
null
null
null
Code.require_file("../test_helper.exs", __DIR__) defmodule ExUnit.CaptureIOTest do use ExUnit.Case defmodule GetUntil do def until_new_line(_, :eof, _) do {:done, :eof, []} end def until_new_line(this_far, chars, stop_char) do case Enum.split_while(chars, fn c -> c != stop_char end) do {l, []} -> {:more, this_far ++ l} {l, [stop_char | rest]} -> {:done, this_far ++ l ++ [stop_char], rest} end end def get_line(device \\ Process.group_leader()) do request = {:get_until, :unicode, "", __MODULE__, :until_new_line, [?\n]} send(device, {:io_request, self(), device, request}) receive do {:io_reply, _, data} -> data end end end import ExUnit.CaptureIO doctest ExUnit.CaptureIO, import: true test "no leakage on failures" do group_leader = Process.group_leader() test = self() assert_raise ArgumentError, fn -> capture_io(fn -> send(test, {:string_io, Process.group_leader()}) raise ArgumentError end) end receive do {:string_io, pid} -> ref = Process.monitor(pid) assert_receive {:DOWN, ^ref, _, _, _} end assert Process.group_leader() == group_leader end test "with no output" do assert capture_io(fn -> nil end) == "" end test "with put chars" do assert capture_io(fn -> :io.put_chars("") end) == "" assert capture_io(fn -> :io.put_chars("a") :io.put_chars("b") end) == "ab" assert capture_io(fn -> :io.put_chars("josé") end) == "josé" assert capture_io(fn -> spawn(fn -> :io.put_chars("a") end) Process.sleep(10) end) == "a" assert capture_io(fn -> assert :io.put_chars("a") == :ok end) end test "with put chars to stderr" do assert capture_io(:stderr, fn -> :io.put_chars(:standard_error, "a") end) == "a" end test "with fwrite" do assert capture_io(fn -> :io.fwrite(<<127, 128>>) end) == <<127, 194, 128>> assert capture_io([encoding: :latin1], fn -> :io.fwrite(<<127, 128>>) end) == <<127, 128>> end test "with get chars" do assert capture_io(fn -> :io.get_chars(">", 3) end) == ">" assert capture_io([capture_prompt: false], fn -> :io.get_chars(">", 3) end) == "" capture_io(fn -> assert :io.get_chars(">", 3) == :eof end) capture_io("", fn -> assert :io.get_chars(">", 3) == :eof end) capture_io("abc\ndef", fn -> assert :io.get_chars(">", 3) == "abc" assert :io.get_chars(">", 5) == "\ndef" assert :io.get_chars(">", 7) == :eof end) capture_io("あいう", fn -> assert :io.get_chars(">", 2) == "あい" assert :io.get_chars(">", 1) == "う" assert :io.get_chars(">", 1) == :eof end) end test "with get line" do assert capture_io(fn -> :io.get_line(">") end) == ">" assert capture_io([capture_prompt: false], fn -> :io.get_line(">") end) == "" capture_io(fn -> assert :io.get_line(">") == :eof end) capture_io("", fn -> assert :io.get_line(">") == :eof end) capture_io("\n", fn -> assert :io.get_line(">") == "\n" assert :io.get_line(">") == :eof end) capture_io("a", fn -> assert :io.get_line(">") == "a" assert :io.get_line(">") == :eof end) capture_io("a\n", fn -> assert :io.get_line(">") == "a\n" assert :io.get_line(">") == :eof end) capture_io("a\nb", fn -> assert :io.get_line(">") == "a\n" assert :io.get_line(">") == "b" assert :io.get_line(">") == :eof end) capture_io("あい\nう", fn -> assert :io.get_line(">") == "あい\n" assert :io.get_line(">") == "う" assert :io.get_line(">") == :eof end) end test "with get password" do capture_io(fn -> assert :io.get_password() == :eof end) capture_io("", fn -> assert :io.get_password() == :eof end) capture_io("abc", fn -> assert :io.get_password() == "abc" assert :io.get_password() == :eof end) capture_io("abc\n", fn -> assert :io.get_password() == "abc\n" assert :io.get_password() == :eof end) capture_io("\n", fn -> assert :io.get_password() == "\n" assert :io.get_password() == :eof end) capture_io("a\nb", fn -> assert :io.get_password() == "a\n" assert :io.get_password() == "b" assert :io.get_password() == :eof end) capture_io("あい\nう", fn -> assert :io.get_password() == "あい\n" assert :io.get_password() == "う" assert :io.get_password() == :eof end) end test "with get until" do assert capture_io(fn -> :io.scan_erl_form('>') end) == ">" assert capture_io("1.\n", fn -> :io.scan_erl_form('>') end) == ">" assert capture_io("1\n.\n", fn -> :io.scan_erl_form('>') end) == ">>" assert capture_io([capture_prompt: false], fn -> :io.scan_erl_form('>') end) == "" capture_io(fn -> assert :io.scan_erl_form('>') == {:eof, 1} end) capture_io("1", fn -> assert :io.scan_erl_form('>') == {:ok, [{:integer, 1, 1}], 1} assert :io.scan_erl_form('>') == {:eof, 1} end) capture_io("1\n.", fn -> assert :io.scan_erl_form('>') == {:ok, [{:integer, 1, 1}, {:dot, 2}], 2} assert :io.scan_erl_form('>') == {:eof, 1} end) capture_io("1.\n.", fn -> assert :io.scan_erl_form('>') == {:ok, [{:integer, 1, 1}, {:dot, 1}], 2} assert :io.scan_erl_form('>') == {:ok, [dot: 1], 1} assert :io.scan_erl_form('>') == {:eof, 1} end) capture_io("\"a", fn -> assert :io.scan_erl_form('>') == {:error, {1, :erl_scan, {:string, 34, 'a'}}, 1} assert :io.scan_erl_form('>') == {:eof, 1} end) capture_io("\"a\n\"", fn -> assert :io.scan_erl_form('>') == {:ok, [{:string, 1, 'a\n'}], 2} assert :io.scan_erl_form('>') == {:eof, 1} end) capture_io(":erl. mof*,,l", fn -> assert :io.scan_erl_form('>') == {:ok, [{:":", 1}, {:atom, 1, :erl}, {:dot, 1}], 1} expected_tokens = [{:atom, 1, :mof}, {:*, 1}, {:",", 1}, {:",", 1}, {:atom, 1, :l}] assert :io.scan_erl_form('>') == {:ok, expected_tokens, 1} assert :io.scan_erl_form('>') == {:eof, 1} end) capture_io("a\nb\nc", fn -> assert GetUntil.get_line() == "a\n" assert GetUntil.get_line() == "b\n" assert GetUntil.get_line() == :eof end) end test "with setopts" do assert capture_io(fn -> assert :io.setopts({:encoding, :latin1}) == {:error, :enotsup} end) == "" end test "with getopts" do assert capture_io(fn -> assert :io.getopts() == [binary: true, encoding: :unicode] end) == "" end test "with columns" do assert capture_io(fn -> :io.columns() end) == "" capture_io(fn -> assert :io.columns() == {:error, :enotsup} end) end test "with rows" do assert capture_io(fn -> :io.rows() end) == "" capture_io(fn -> assert :io.rows() == {:error, :enotsup} end) end test "with multiple IO requests" do requests = [{:put_chars, :unicode, "a"}, {:put_chars, :unicode, "b"}] assert capture_io(fn -> send_and_receive_io({:requests, requests}) end) == "ab" capture_io(fn -> assert send_and_receive_io({:requests, requests}) == :ok end) end test "with unknown IO request" do assert capture_io(fn -> send_and_receive_io(:unknown) end) == "" capture_io(fn -> assert send_and_receive_io(:unknown) == {:error, :request} end) end test "device re-registering" do parent = self() pid = spawn(fn -> capture_io(:stderr, fn -> send(parent, :ready) Process.sleep(:infinity) end) end) assert_receive :ready # Kill the process and make sure the capture server receives the down :erlang.trace(Process.whereis(ExUnit.CaptureServer), true, [:receive, tracer: self()]) Process.exit(pid, :shutdown) assert_receive {:trace, _, :receive, {:DOWN, _, _, _, :shutdown}}, 1000 assert capture_io(:stderr, fn -> :ok end) after :erlang.trace(Process.whereis(ExUnit.CaptureServer), false, [:receive, tracer: self()]) end test "with assert inside" do try do capture_io(fn -> assert false end) rescue error in [ExUnit.AssertionError] -> assert error.message == "Expected truthy, got false" end end test "capture :stderr by two processes" do spawn(fn -> capture_io(:stderr, fn -> Process.sleep(100) end) end) Process.sleep(10) expected_message = "IO device registered at :standard_error is already captured" assert_raise RuntimeError, expected_message, fn -> capture_io(:stderr, fn -> nil end) end Process.sleep(100) end defp send_and_receive_io(req) do pid = self() send(:erlang.group_leader(), {:io_request, pid, pid, req}) receive do {:io_reply, ^pid, res} -> res end end end
24.690104
91
0.525577
93d00bed2dda079c7c638cb7a047dbe9aad83eb5
922
ex
Elixir
lib/mpdecimal.ex
SpiffInc/mpdecimal
c2e8382848c13642db7bbdf353a6f9acf959d57c
[ "MIT" ]
1
2021-04-19T13:14:02.000Z
2021-04-19T13:14:02.000Z
lib/mpdecimal.ex
SpiffInc/mpdecimal
c2e8382848c13642db7bbdf353a6f9acf959d57c
[ "MIT" ]
2
2021-05-15T16:50:09.000Z
2021-06-03T15:19:47.000Z
lib/mpdecimal.ex
SpiffInc/mpdecimal
c2e8382848c13642db7bbdf353a6f9acf959d57c
[ "MIT" ]
null
null
null
defmodule MPDecimal do alias MPDecimal.Nif @doc """ raise a decimal to a power This function performs exponentiation with fixed-decimal precision. ## Examples iex> two = Decimal.new("2.0") #Decimal<2.0> iex> four = MPDecimal.power(two, two) #Decimal<4.00> iex> MPDecimal.power(four, Decimal.new("0.5")) #Decimal<2.000000000000000000000000000> """ def power(%Decimal{} = base, %Decimal{} = exponent) do # Add the null terminator to the end of each string argument so that it # forms a valid cstring for consumption by the NIF. base = Decimal.to_string(base, :xsd) <> "\0" exponent = Decimal.to_string(exponent, :xsd) <> "\0" case Nif.power(base, exponent) do {:ok, result} -> Decimal.new(result) {:error, message} -> raise(MPDecimal.Error, message: message) end end end defmodule MPDecimal.Error do defexception [:message] end
27.117647
75
0.658351
93d0282e30bd0d63a9e5e741993a8137e9d70ec1
65
ex
Elixir
lib/bitstring_web/views/page_view.ex
the-hills/www.bitstring.xyz
fde44f0812634614bf166ef20505bdaa15a2feb4
[ "MIT" ]
1
2017-09-22T14:53:03.000Z
2017-09-22T14:53:03.000Z
lib/bitstring_web/views/page_view.ex
the-hills/www.bitstring.xyz
fde44f0812634614bf166ef20505bdaa15a2feb4
[ "MIT" ]
null
null
null
lib/bitstring_web/views/page_view.ex
the-hills/www.bitstring.xyz
fde44f0812634614bf166ef20505bdaa15a2feb4
[ "MIT" ]
null
null
null
defmodule BitstringWeb.PageView do use BitstringWeb, :view end
16.25
34
0.815385
93d0acf32566830af0b38a0bd1725d5d36e53056
3,589
ex
Elixir
lib/harald/hci/le_controller.ex
mattludwigs/harald
82e67a71d9940d8572fd217eaf29575e81533151
[ "MIT" ]
3
2020-08-07T02:09:09.000Z
2020-08-28T12:25:48.000Z
lib/harald/hci/le_controller.ex
mattludwigs/harald
82e67a71d9940d8572fd217eaf29575e81533151
[ "MIT" ]
null
null
null
lib/harald/hci/le_controller.ex
mattludwigs/harald
82e67a71d9940d8572fd217eaf29575e81533151
[ "MIT" ]
null
null
null
defmodule Harald.HCI.LEController do @moduledoc """ > The LE Controller Commands provide access and control to various capabilities of the Bluetooth > hardware, as well as methods for the Host to affect how the Link Layer manages the piconet, > and controls connections. Reference: Version 5.0, Vol 2, Part E, 7.8 """ alias Harald.HCI @ogf 0x08 @doc """ > The LE_Set_Scan_Enable command is used to start scanning. Scanning is used to discover > advertising devices nearby. > > The Filter_Duplicates parameter controls whether the Link Layer should filter out duplicate > advertising reports (Filtering_Enabled) to the Host, or if the Link Layer should generate > advertising reports for each packet received (Filtering_Disabled). See [Vol 6] Part B, Section > 4.4.3.5. > > If the scanning parameters' Own_Address_Type parameter is set to 0x01 or 0x03 and the random > address for the device has not been initialized, the Controller shall return the error code > Invalid HCI Command Parameters (0x12). > > If the LE_Scan_Enable parameter is set to 0x01 and scanning is already enabled, any change to > the Filter_Duplicates setting shall take effect. Note: Disabling scanning when it is disabled > has no effect. Reference: Version 5.0, Vol 2, Part E, 7.8.11 iex> set_enable_scan(true) <<12, 32, 2, 1, 0>> iex> set_enable_scan(false) <<12, 32, 2, 0, 0>> """ @spec set_enable_scan(HCI.opt(), HCI.opt()) :: HCI.command() def set_enable_scan(enable, filter_duplicates \\ false) do @ogf |> HCI.opcode(0x000C) |> HCI.command([enable, filter_duplicates]) end @doc """ > The LE_Set_Scan_Parameters command is used to set the scan parameters. The LE_Scan_Type > parameter controls the type of scan to perform. > > The LE_Scan_Interval and LE_Scan_Window parameters are recommendations from the Host on how > long (LE_Scan_Window) and how frequently (LE_Scan_Interval) the Controller should scan > (See [Vol 6] Part B, Section 4.5.3). The LE_Scan_Window parameter shall always be set to a > value smaller or equal to the value set for the LE_Scan_Interval parameter. If they are set to > the same value scanning should be run continuously. > > Own_Address_Type parameter indicates the type of address being used in the scan request > packets. > > The Host shall not issue this command when scanning is enabled in the Controller; if it is the > Command Disallowed error code shall be used. Reference: Version 5.0, Vol 2, Part E, 7.8.10 iex> set_scan_parameters(le_scan_type: 0x01) <<11, 32, 7, 1, 16, 0, 16, 0, 0, 0>> iex> set_scan_parameters( iex> le_scan_type: 0x01, iex> le_scan_interval: 0x0004, iex> le_scan_window: 0x0004, iex> own_address_type: 0x01, iex> scanning_filter_policy: 0x01 iex> ) <<11, 32, 7, 1, 4, 0, 4, 0, 1, 1>> """ @spec set_scan_parameters(keyword) :: HCI.command() def set_scan_parameters(new_params) do # Defaults according to the Bluetooth Core Spec v5. params = [ le_scan_type: 0x00, le_scan_interval: 0x0010, le_scan_window: 0x0010, own_address_type: 0x00, scanning_filter_policy: 0x00 ] |> Keyword.merge(new_params) opts = << params[:le_scan_type], params[:le_scan_interval]::size(16)-little, params[:le_scan_window]::size(16)-little, params[:own_address_type], params[:scanning_filter_policy] >> @ogf |> HCI.opcode(0x000B) |> HCI.command(opts) end end
36.622449
98
0.696294
93d0b3bb8840be65bee0bac3043b2ef102d89f3a
1,545
ex
Elixir
apps/artemis/lib/artemis/drivers/ibm_cloud_iam/access_token/get_access_token.ex
artemis-platform/artemis_dashboard
5ab3f5ac4c5255478bbebf76f0e43b44992e3cab
[ "MIT" ]
9
2019-08-19T19:56:34.000Z
2022-03-22T17:56:38.000Z
apps/artemis/lib/artemis/drivers/ibm_cloud_iam/access_token/get_access_token.ex
chrislaskey/artemis_teams
9930c3d9528e37b76f0525390e32b66eed7eadde
[ "MIT" ]
7
2019-07-12T21:41:01.000Z
2020-08-17T21:29:22.000Z
apps/artemis/lib/artemis/drivers/ibm_cloud_iam/access_token/get_access_token.ex
chrislaskey/artemis_teams
9930c3d9528e37b76f0525390e32b66eed7eadde
[ "MIT" ]
2
2019-07-05T22:51:47.000Z
2019-08-19T19:56:37.000Z
defmodule Artemis.Drivers.IBMCloudIAM.GetAccessToken do alias Artemis.Drivers.IBMCloudIAM require Logger def call(api_key) do with {:ok, response} <- request_access_token(api_key), {:ok, data} <- process_response(response) do {:ok, data} else {:error, error} -> {:error, error} error -> {:error, error} end end # Helpers defp request_access_token(api_key) do params = [ apikey: api_key, grant_type: "urn:ibm:params:oauth:grant-type:apikey" ] body = {:form, params} headers = [] options = [] IBMCloudIAM.Request.post("/identity/token", body, headers, options) end defp process_response(%{body: body, status_code: 200}) do data = %{ token: Map.get(body, "access_token"), meta: %{ access_token: Map.get(body, "access_token"), expiration: Map.get(body, "expiration"), expires_in: Map.get(body, "expires_in"), refresh_token: Map.get(body, "refresh_token"), scope: Map.get(body, "scope"), token_type: Map.get(body, "token_type") } } {:ok, data} end defp process_response(%{body: %{"errorCode" => code, "errorMessage" => message}} = response) do Logger.info("Error calling IBM Cloud IAM API:" <> inspect(response)) {:error, "IBM Cloud IAM API error #{code}: #{message}"} end defp process_response(response) do Logger.info("Error calling IBM Cloud IAM API:" <> inspect(response)) {:error, "Unknown error response from IBM Cloud IAM API"} end end
26.186441
97
0.628479
93d0bf39581c0aa3c66dee005845ea37a93ecfef
1,107
ex
Elixir
lib/national_voter_file.ex
nihonjinrxs/national-voter-file-api
690c40bd46e196cebb6325341f1197a862c38632
[ "MIT" ]
12
2017-03-24T02:58:38.000Z
2020-11-18T15:29:33.000Z
lib/national_voter_file.ex
nihonjinrxs/national-voter-file-api
690c40bd46e196cebb6325341f1197a862c38632
[ "MIT" ]
22
2016-12-31T17:14:33.000Z
2021-06-09T17:02:59.000Z
lib/national_voter_file.ex
nihonjinrxs/national-voter-file-api
690c40bd46e196cebb6325341f1197a862c38632
[ "MIT" ]
7
2017-02-27T15:42:55.000Z
2017-10-13T15:26:02.000Z
defmodule NationalVoterFile do use Application # See http://elixir-lang.org/docs/stable/elixir/Application.html # for more information on OTP Applications def start(_type, _args) do import Supervisor.Spec # Define workers and child supervisors to be supervised children = [ # Start the Ecto repository supervisor(NationalVoterFile.Repo, []), # Start the endpoint when the application starts supervisor(NationalVoterFile.Endpoint, []), # Start your own worker by calling: NationalVoterFile.Worker.start_link(arg1, arg2, arg3) # worker(NationalVoterFile.Worker, [arg1, arg2, arg3]), ] # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: NationalVoterFile.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do NationalVoterFile.Endpoint.config_change(changed, removed) :ok end end
34.59375
95
0.730804
93d0d0764843f5cc8642abf674d65188104f1641
1,117
exs
Elixir
config/config.exs
icehaunter/pipe_to
52f7c90368edf691cba07031e256fc50d4e1875b
[ "Apache-2.0" ]
86
2016-09-09T19:05:25.000Z
2021-09-25T05:28:43.000Z
config/config.exs
icehaunter/pipe_to
52f7c90368edf691cba07031e256fc50d4e1875b
[ "Apache-2.0" ]
5
2016-09-19T13:44:08.000Z
2020-07-01T10:57:53.000Z
config/config.exs
icehaunter/pipe_to
52f7c90368edf691cba07031e256fc50d4e1875b
[ "Apache-2.0" ]
2
2019-09-03T13:46:47.000Z
2020-03-13T11:56:56.000Z
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :pipe_to, key: :value # # And access this configuration in your application as: # # Application.get_env(:pipe_to, :key) # # Or configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs"
36.032258
73
0.751119
93d0f26de41a2454933fac103f477b942eb00baf
2,696
ex
Elixir
lib/espec/extension/datetime_extension.ex
MeneDev/espec
ec4b3d579c5192999e930224a8a2650bb1fdf0bc
[ "Apache-2.0" ]
807
2015-03-25T14:00:19.000Z
2022-03-24T08:08:15.000Z
lib/espec/extension/datetime_extension.ex
MeneDev/espec
ec4b3d579c5192999e930224a8a2650bb1fdf0bc
[ "Apache-2.0" ]
254
2015-03-27T10:12:25.000Z
2021-07-12T01:40:15.000Z
lib/espec/extension/datetime_extension.ex
MeneDev/espec
ec4b3d579c5192999e930224a8a2650bb1fdf0bc
[ "Apache-2.0" ]
85
2015-04-02T10:25:19.000Z
2021-01-30T21:30:43.000Z
defmodule DateTime.Extension do @moduledoc """ A module to extend the calendar implementation that follows to ISO8601 with methods found in Elixir 1.5.1. This is to allow ESpec to support Elixir >= 1.3.4 more easily. """ defstruct [ :year, :month, :day, :hour, :minute, :second, :time_zone, :zone_abbr, :utc_offset, :std_offset, microsecond: {0, 0}, calendar: Calendar.ISO ] @type t :: %__MODULE__{ year: Calendar.year(), month: Calendar.month(), day: Calendar.day(), calendar: Calendar.calendar(), hour: Calendar.hour(), minute: Calendar.minute(), second: Calendar.second(), microsecond: Calendar.microsecond(), time_zone: Calendar.time_zone(), zone_abbr: Calendar.zone_abbr(), utc_offset: Calendar.utc_offset(), std_offset: Calendar.std_offset() } @doc """ Converts the given `NaiveDateTime` to `DateTime`. It expects a time zone to put the NaiveDateTime in. Currently it only supports "Etc/UTC" as time zone. ## Examples iex> {:ok, datetime} = DateTime.from_naive(~N[2016-05-24 13:26:08.003], "Etc/UTC") iex> datetime #DateTime<2016-05-24 13:26:08.003Z> """ @spec from_naive(NaiveDateTime.t(), Calendar.time_zone()) :: {:ok, t} def from_naive(naive_datetime, time_zone) def from_naive( %NaiveDateTime{ calendar: calendar, hour: hour, minute: minute, second: second, microsecond: microsecond, year: year, month: month, day: day }, "Etc/UTC" ) do {:ok, %DateTime{ calendar: calendar, year: year, month: month, day: day, hour: hour, minute: minute, second: second, microsecond: microsecond, std_offset: 0, utc_offset: 0, zone_abbr: "UTC", time_zone: "Etc/UTC" }} end @doc """ Converts the given `NaiveDateTime` to `DateTime`. It expects a time zone to put the NaiveDateTime in. Currently it only supports "Etc/UTC" as time zone. ## Examples iex> DateTime.from_naive!(~N[2016-05-24 13:26:08.003], "Etc/UTC") #DateTime<2016-05-24 13:26:08.003Z> """ @spec from_naive!(NaiveDateTime.t(), Calendar.time_zone()) :: t def from_naive!(naive_datetime, time_zone) do case from_naive(naive_datetime, time_zone) do {:ok, datetime} -> datetime {:error, reason} -> raise ArgumentError, "cannot parse #{inspect(naive_datetime)} to datetime, reason: #{inspect(reason)}" end end end
25.196262
95
0.589392
93d0f69643ef66769db8ad4a03007dccd40b1f07
2,006
ex
Elixir
clients/cloud_search/lib/google_api/cloud_search/v1/model/query_interpretation.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/cloud_search/lib/google_api/cloud_search/v1/model/query_interpretation.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/cloud_search/lib/google_api/cloud_search/v1/model/query_interpretation.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.CloudSearch.V1.Model.QueryInterpretation do @moduledoc """ ## Attributes * `interpretationType` (*type:* `String.t`, *default:* `nil`) - * `interpretedQuery` (*type:* `String.t`, *default:* `nil`) - The interpretation of the query used in search. For example, queries with natural language intent like "email from john" will be interpreted as "from:john source:mail". This field will not be filled when the reason is NOT_ENOUGH_RESULTS_FOUND_FOR_USER_QUERY. * `reason` (*type:* `String.t`, *default:* `nil`) - The reason for interpretation of the query. This field will not be UNSPECIFIED if the interpretation type is not NONE. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :interpretationType => String.t(), :interpretedQuery => String.t(), :reason => String.t() } field(:interpretationType) field(:interpretedQuery) field(:reason) end defimpl Poison.Decoder, for: GoogleApi.CloudSearch.V1.Model.QueryInterpretation do def decode(value, options) do GoogleApi.CloudSearch.V1.Model.QueryInterpretation.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudSearch.V1.Model.QueryInterpretation do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.849057
324
0.7333
93d119b6da16b9f96e25dfc20435c4616707ad0e
9,770
ex
Elixir
clients/reseller/lib/google_api/reseller/v1/api/customers.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/reseller/lib/google_api/reseller/v1/api/customers.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/reseller/lib/google_api/reseller/v1/api/customers.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Reseller.V1.Api.Customers do @moduledoc """ API calls for all endpoints tagged `Customers`. """ alias GoogleApi.Reseller.V1.Connection alias GoogleApi.Gax.{Request, Response} @doc """ Get a customer account. ## Parameters - connection (GoogleApi.Reseller.V1.Connection): Connection to server - customer_id (String.t): Either the customer&#39;s primary domain name or the customer&#39;s unique identifier. If using the domain name, we do not recommend using a customerId as a key for persistent data. If the domain name for a customerId is changed, the Google system automatically updates. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. ## Returns {:ok, %GoogleApi.Reseller.V1.Model.Customer{}} on success {:error, info} on failure """ @spec reseller_customers_get(Tesla.Env.client(), String.t(), keyword()) :: {:ok, GoogleApi.Reseller.V1.Model.Customer.t()} | {:error, Tesla.Env.t()} def reseller_customers_get(connection, customer_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/customers/{customerId}", %{ "customerId" => URI.encode_www_form(customer_id) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Reseller.V1.Model.Customer{}]) end @doc """ Order a new customer&#39;s account. ## Parameters - connection (GoogleApi.Reseller.V1.Connection): Connection to server - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :customerAuthToken (String.t): The customerAuthToken query string is required when creating a resold account that transfers a direct customer&#39;s subscription or transfers another reseller customer&#39;s subscription to your reseller management. This is a hexadecimal authentication token needed to complete the subscription transfer. For more information, see the administrator help center. - :body (Customer): ## Returns {:ok, %GoogleApi.Reseller.V1.Model.Customer{}} on success {:error, info} on failure """ @spec reseller_customers_insert(Tesla.Env.client(), keyword()) :: {:ok, GoogleApi.Reseller.V1.Model.Customer.t()} | {:error, Tesla.Env.t()} def reseller_customers_insert(connection, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :customerAuthToken => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/customers") |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Reseller.V1.Model.Customer{}]) end @doc """ Update a customer account&#39;s settings. This method supports patch semantics. ## Parameters - connection (GoogleApi.Reseller.V1.Connection): Connection to server - customer_id (String.t): Either the customer&#39;s primary domain name or the customer&#39;s unique identifier. If using the domain name, we do not recommend using a customerId as a key for persistent data. If the domain name for a customerId is changed, the Google system automatically updates. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (Customer): ## Returns {:ok, %GoogleApi.Reseller.V1.Model.Customer{}} on success {:error, info} on failure """ @spec reseller_customers_patch(Tesla.Env.client(), String.t(), keyword()) :: {:ok, GoogleApi.Reseller.V1.Model.Customer.t()} | {:error, Tesla.Env.t()} def reseller_customers_patch(connection, customer_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/customers/{customerId}", %{ "customerId" => URI.encode_www_form(customer_id) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Reseller.V1.Model.Customer{}]) end @doc """ Update a customer account&#39;s settings. ## Parameters - connection (GoogleApi.Reseller.V1.Connection): Connection to server - customer_id (String.t): Either the customer&#39;s primary domain name or the customer&#39;s unique identifier. If using the domain name, we do not recommend using a customerId as a key for persistent data. If the domain name for a customerId is changed, the Google system automatically updates. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (Customer): ## Returns {:ok, %GoogleApi.Reseller.V1.Model.Customer{}} on success {:error, info} on failure """ @spec reseller_customers_update(Tesla.Env.client(), String.t(), keyword()) :: {:ok, GoogleApi.Reseller.V1.Model.Customer.t()} | {:error, Tesla.Env.t()} def reseller_customers_update(connection, customer_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/customers/{customerId}", %{ "customerId" => URI.encode_www_form(customer_id) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Reseller.V1.Model.Customer{}]) end end
44.409091
399
0.690993
93d146c17be408bc700ef122c8a3c6c168fd740d
1,168
ex
Elixir
discuss/web/channels/comments_channel.ex
darth-dodo/discuss-it
dbed7d3c844ba155b7dd3a763a83b41a54d01048
[ "MIT" ]
1
2020-07-16T11:28:44.000Z
2020-07-16T11:28:44.000Z
discuss/web/channels/comments_channel.ex
darth-dodo/discuss-it
dbed7d3c844ba155b7dd3a763a83b41a54d01048
[ "MIT" ]
1
2021-05-09T03:13:17.000Z
2021-05-09T03:13:17.000Z
discuss/web/channels/comments_channel.ex
darth-dodo/discuss-it
dbed7d3c844ba155b7dd3a763a83b41a54d01048
[ "MIT" ]
null
null
null
defmodule Discuss.CommentsChannel do use Discuss.Web, :channel alias Discuss.Topic alias Discuss.Comment # pattern matching to join the strings in elixir def join("comments:" <> topic_id, _params, socket) do topic_id = String.to_integer(topic_id) topic = Topic |> Repo.get(topic_id) |> Repo.preload(comments: [:user]) { :ok, %{ comments: topic.comments }, assign(socket, :topic, topic) } end def handle_in(name, %{"content" => content}, socket) do # name is the topic and subtopic of pubsub # message is the payload topic = socket.assigns.topic current_user_id = socket.assigns.current_user_id changeset = topic |> build_assoc(:comments, user_id: current_user_id) # Ecto. build_assoc only takes in one association and cannot be piped :| |> Comment.changeset(%{content: content}) case Repo.insert(changeset) do {:ok, comment} -> broadcast!(socket, "comments:#{topic.id}:new", %{comment: comment}) {:reply, :ok, socket} {:error, _reason} -> {:reply, {:error, %{errors: changeset}}, socket} end {:reply, :ok, socket} end end
27.162791
128
0.642123
93d15be29bff091936ac3662073d415ebf7b1d1e
299
ex
Elixir
{{cookiecutter.project_underscored}}/lib/{{cookiecutter.project_underscored}}.ex
ijcd/cookiecutter-screaming-phoenix
f34ca6704f8f8b0581e91b4f6e3e75239fb79cb1
[ "Apache-2.0" ]
null
null
null
{{cookiecutter.project_underscored}}/lib/{{cookiecutter.project_underscored}}.ex
ijcd/cookiecutter-screaming-phoenix
f34ca6704f8f8b0581e91b4f6e3e75239fb79cb1
[ "Apache-2.0" ]
null
null
null
{{cookiecutter.project_underscored}}/lib/{{cookiecutter.project_underscored}}.ex
ijcd/cookiecutter-screaming-phoenix
f34ca6704f8f8b0581e91b4f6e3e75239fb79cb1
[ "Apache-2.0" ]
null
null
null
defmodule {{cookiecutter.project_module}} do @moduledoc """ {{cookiecutter.project_module}} 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
29.9
76
0.759197
93d1695dab5e291a94da70b98aeabafd3156aa77
578
ex
Elixir
lib/shell/shell.ex
sohjiro/ex_ebook
4d5d72fbb880a7b25b1c5e217d0a9b679d0496ac
[ "MIT" ]
null
null
null
lib/shell/shell.ex
sohjiro/ex_ebook
4d5d72fbb880a7b25b1c5e217d0a9b679d0496ac
[ "MIT" ]
null
null
null
lib/shell/shell.ex
sohjiro/ex_ebook
4d5d72fbb880a7b25b1c5e217d0a9b679d0496ac
[ "MIT" ]
null
null
null
defmodule ExEbook.Shell do @moduledoc """ Module for interacting with the shell """ @type cmd :: String.t() @type path :: String.t() @type params :: [String.t()] require Logger @spec execute(cmd, params) :: {:ok, String.t()} def execute(cmd, params \\ []) do case System.cmd(cmd, params) do {data, 0} -> {:ok, data} error -> Logger.error("#{inspect(__MODULE__)} error #{inspect(error)}") {:error, :invalid_type} end end @spec current_tmp_dir :: path() def current_tmp_dir do System.tmp_dir() end end
20.642857
70
0.593426
93d17162dff08b73b1f8af447b06e6a85266251c
838
ex
Elixir
test/support/yarn_case.ex
StabbyMcDuck/elixir_ravelry
c503fc019842bb82ad58673a1b6867e3214fc7e1
[ "Apache-2.0" ]
21
2017-08-27T13:59:18.000Z
2020-10-07T03:35:22.000Z
test/support/yarn_case.ex
StabbyMcDuck/elixir_ravelry
c503fc019842bb82ad58673a1b6867e3214fc7e1
[ "Apache-2.0" ]
2
2017-09-02T15:49:47.000Z
2017-09-02T17:43:29.000Z
test/support/yarn_case.ex
StabbyMcDuck/elixir_ravelry
c503fc019842bb82ad58673a1b6867e3214fc7e1
[ "Apache-2.0" ]
7
2017-09-02T15:11:49.000Z
2019-08-20T19:00:48.000Z
defmodule ElixirRavelry.YarnCase do import ElixirRavelry.{RovingCase, MaterialForCase, WoolCase} alias ElixirRavelry.Repo alias ElixirRavelryWeb.Yarn def create_yarn(bolt_sips_conn) do Repo.Yarn.create(bolt_sips_conn, %Yarn{name: Faker.Name.name()}) end def create_connected_yarn(bolt_sips_conn) do wool = create_wool(bolt_sips_conn) roving = create_roving(bolt_sips_conn) wool_material_for_roving = create_material_for(bolt_sips_conn, %{start_node_id: wool.id, end_node_id: roving.id}) yarn = create_yarn(bolt_sips_conn) roving_material_for_yarn = create_material_for(bolt_sips_conn, %{start_node_id: roving.id, end_node_id: yarn.id}) %{roving: roving, roving_material_for_yarn: roving_material_for_yarn, yarn: yarn, wool: wool, wool_material_for_roving: wool_material_for_roving} end end
36.434783
149
0.792363
93d1ac27d7ca17167fa73baa4984076bfa788425
1,893
ex
Elixir
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_response_message_text.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_response_message_text.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_response_message_text.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2021-03-04T13:43:47.000Z
2021-03-04T13:43:47.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageText do @moduledoc """ The text response message. ## Attributes * `allowPlaybackInterruption` (*type:* `boolean()`, *default:* `nil`) - Output only. Whether the playback of this message can be interrupted by the end user's speech and the client can then starts the next Dialogflow request. * `text` (*type:* `list(String.t)`, *default:* `nil`) - Required. A collection of text responses. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :allowPlaybackInterruption => boolean(), :text => list(String.t()) } field(:allowPlaybackInterruption) field(:text, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageText do def decode(value, options) do GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageText.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageText do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.418182
229
0.743793
93d1c3ccf02e37be3ee0768d7b97ae916faa5092
1,199
exs
Elixir
scripts/n_queens.exs
rob-brown/genetic
48996c04c8ff504f37013ba0df0ef5cee2986ea9
[ "MIT" ]
null
null
null
scripts/n_queens.exs
rob-brown/genetic
48996c04c8ff504f37013ba0df0ef5cee2986ea9
[ "MIT" ]
null
null
null
scripts/n_queens.exs
rob-brown/genetic
48996c04c8ff504f37013ba0df0ef5cee2986ea9
[ "MIT" ]
null
null
null
#! /usr/bin/env elixir Mix.install([ {:genetic, path: Path.join(__DIR__, "..")} ]) defmodule NQueens do alias Genetic.{Problem, Chromosome, BasicChromosome} @behaviour Problem @impl Problem def genotype() do genes = Enum.shuffle(0..7) BasicChromosome.new(genes) end @impl Problem def fitness_module() do BasicChromosome end @impl Problem def update_fitness(c) do genes = Chromosome.genes(c) diag_clashes = for i <- 0..7, j <- 0..7 do if i != j do dx = abs(i - j) dy = genes |> Enum.at(i) |> Kernel.-(Enum.at(genes, j)) |> abs() if dx == dy do 1 else 0 end else 0 end end %BasicChromosome{c | fitness: length(Enum.uniq(genes)) - Enum.sum(diag_clashes)} end @impl Problem def terminate?(population, _generation) do population |> Enum.at(0) |> then(&(&1.fitness == 8)) # Enum.max_by(population, &fitness_function/1).fitness == 8 end end NQueens |> Genetic.run(crossover_type: &Genetic.CrossoverStrategy.order_one/3) |> Enum.at(0) |> IO.inspect(label: "Result")
19.655738
84
0.566305
93d1c3d4b3d02ccb82213b4e3af805fda8f9e532
1,984
ex
Elixir
web/controllers/html_parameter_controller.ex
rob05c/tox
f54847ca058ad24b909341ad65d595a4069d2471
[ "Apache-2.0" ]
2
2016-11-16T17:24:21.000Z
2019-02-15T05:38:27.000Z
web/controllers/html_parameter_controller.ex
rob05c/tox
f54847ca058ad24b909341ad65d595a4069d2471
[ "Apache-2.0" ]
null
null
null
web/controllers/html_parameter_controller.ex
rob05c/tox
f54847ca058ad24b909341ad65d595a4069d2471
[ "Apache-2.0" ]
null
null
null
defmodule Tox.HtmlParameterController do use Tox.Web, :controller alias Tox.Parameter def index(conn, _params) do parameters = Repo.all(Parameter) render(conn, "index.html", parameters: parameters) end def new(conn, _params) do changeset = Parameter.changeset(%Parameter{}) render(conn, "new.html", changeset: changeset) end def create(conn, %{"parameter" => parameter_params}) do changeset = Parameter.changeset(%Parameter{}, parameter_params) case Repo.insert(changeset) do {:ok, _parameter} -> conn |> put_flash(:info, "Parameter created successfully.") |> redirect(to: html_parameter_path(conn, :index)) {:error, changeset} -> render(conn, "new.html", changeset: changeset) end end def show(conn, %{"id" => id}) do parameter = Repo.get!(Parameter, id) render(conn, "show.html", parameter: parameter) end def edit(conn, %{"id" => id}) do parameter = Repo.get!(Parameter, id) changeset = Parameter.changeset(parameter) render(conn, "edit.html", parameter: parameter, changeset: changeset) end def update(conn, %{"id" => id, "parameter" => parameter_params}) do parameter = Repo.get!(Parameter, id) changeset = Parameter.changeset(parameter, parameter_params) case Repo.update(changeset) do {:ok, parameter} -> conn |> put_flash(:info, "Parameter updated successfully.") |> redirect(to: html_parameter_path(conn, :show, parameter)) {:error, changeset} -> render(conn, "edit.html", parameter: parameter, changeset: changeset) end end def delete(conn, %{"id" => id}) do parameter = Repo.get!(Parameter, id) # Here we use delete! (with a bang) because we expect # it to always work (and if it does not, it will raise). Repo.delete!(parameter) conn |> put_flash(:info, "Parameter deleted successfully.") |> redirect(to: html_parameter_path(conn, :index)) end end
30.060606
77
0.654234
93d1d1354cc2d3b9e37ad2cc77738d8d53b9a18d
4,380
ex
Elixir
lib/new_relic/transaction/reporter.ex
binaryseed/elixir_agent
25f1242c10516618d9ea3a9b18712e5bc41efad6
[ "Apache-2.0" ]
null
null
null
lib/new_relic/transaction/reporter.ex
binaryseed/elixir_agent
25f1242c10516618d9ea3a9b18712e5bc41efad6
[ "Apache-2.0" ]
null
null
null
lib/new_relic/transaction/reporter.ex
binaryseed/elixir_agent
25f1242c10516618d9ea3a9b18712e5bc41efad6
[ "Apache-2.0" ]
null
null
null
defmodule NewRelic.Transaction.Reporter do use GenServer alias NewRelic.Util.AttrStore alias NewRelic.Transaction # This GenServer collects and reports Transaction related data # - Transaction Events # - Transaction Metrics # - Span Events # - Transaction Errors # - Transaction Traces # - Custom Attributes @moduledoc false # Customer Exposed API def add_attributes(attrs) when is_list(attrs) do if tracking?(self()) do AttrStore.add( __MODULE__, self(), attrs |> NewRelic.Util.deep_flatten() |> NewRelic.Util.coerce_attributes() ) end end def incr_attributes(attrs) do if tracking?(self()) do AttrStore.incr(__MODULE__, self(), attrs) end end def set_transaction_name(custom_name) when is_binary(custom_name) do if tracking?(self()) do AttrStore.add(__MODULE__, self(), custom_name: custom_name) end end # Internal Agent API def start() do Transaction.Monitor.add(self()) AttrStore.track(__MODULE__, self()) AttrStore.add(__MODULE__, self(), pid: inspect(self()), start_time: System.system_time(), start_time_mono: System.monotonic_time() ) end def start_other_transaction(category, name) do unless tracking?(self()) do start() AttrStore.add(__MODULE__, self(), other_transaction_name: "#{category}/#{name}") end end def ignore_transaction() do if tracking?(self()) do ensure_purge(self()) AttrStore.untrack(__MODULE__, self()) AttrStore.purge(__MODULE__, self()) end end def error(pid, error) do if tracking?(pid) do AttrStore.add(__MODULE__, pid, transaction_error: {:error, error}) end end def fail(pid, %{kind: kind, reason: reason, stack: stack}) do if tracking?(pid) do if NewRelic.Config.feature?(:error_collector) do AttrStore.add(__MODULE__, pid, error: true, error_kind: kind, error_reason: inspect(reason), error_stack: inspect(stack) ) else AttrStore.add(__MODULE__, pid, error: true) end end end def add_trace_segment(segment) do if tracking?(self()) do AttrStore.add(__MODULE__, self(), trace_function_segments: {:list, segment}) end end def track_metric(metric) do if tracking?(self()) do AttrStore.add(__MODULE__, self(), transaction_metrics: {:list, metric}) end end def complete(pid, mode) do if tracking?(pid) do AttrStore.add(__MODULE__, pid, end_time_mono: System.monotonic_time()) AttrStore.untrack(__MODULE__, pid) case mode do :sync -> complete_and_purge(pid) :async -> Task.Supervisor.start_child(Transaction.TaskSupervisor, fn -> complete_and_purge(pid) end) end end end defp complete_and_purge(pid) do AttrStore.collect(__MODULE__, pid) |> Transaction.Complete.run(pid) AttrStore.purge(__MODULE__, pid) end # Internal Transaction.Monitor API # def track_spawn(original, pid, timestamp) do if tracking?(original) do AttrStore.link(__MODULE__, original, pid) AttrStore.add(__MODULE__, pid, trace_process_spawns: {:list, {pid, timestamp, original}}, trace_process_names: {:list, {pid, NewRelic.Util.process_name(pid)}} ) end end def track_exit(pid, timestamp) do if tracking?(pid) do AttrStore.add(__MODULE__, pid, trace_process_exits: {:list, {pid, timestamp}}) end end # Try really hard not to leak memory if any async reporting trickles in late def ensure_purge(pid) do Process.send_after( __MODULE__, {:ensure_purge, AttrStore.root(__MODULE__, pid)}, Application.get_env(:new_relic_agent, :ensure_purge_after, 2_000) ) end # GenServer # def start_link(_) do GenServer.start_link(__MODULE__, :ok, name: __MODULE__) end def init(:ok) do NewRelic.sample_process() AttrStore.new(__MODULE__) {:ok, %{timers: %{}}} end def handle_info({:ensure_purge, pid}, state) do AttrStore.purge(__MODULE__, pid) {:noreply, %{state | timers: Map.drop(state.timers, [pid])}} end # Helpers # def tracking?(pid), do: AttrStore.tracking?(__MODULE__, pid) def root(pid), do: AttrStore.root(__MODULE__, pid) end
24.065934
86
0.654566
93d1d9246a2690406d79ec7a75fa32f1884af8ee
266
ex
Elixir
lib/mao_web/resolvers/replies.ex
levijcl/mao
aae70589605ada84ca571a51f5ee4377091e0eb3
[ "MIT" ]
null
null
null
lib/mao_web/resolvers/replies.ex
levijcl/mao
aae70589605ada84ca571a51f5ee4377091e0eb3
[ "MIT" ]
null
null
null
lib/mao_web/resolvers/replies.ex
levijcl/mao
aae70589605ada84ca571a51f5ee4377091e0eb3
[ "MIT" ]
null
null
null
defmodule MAOWeb.Resolvers.Replies do @moduledoc false alias MAO.{Replies, Wall} def comments(%Wall.Post{} = post, _, _) do {:ok, Replies.list_comments(post)} end def create_comment(%{input: input}, _) do Replies.create_comment(input) end end
19
44
0.691729
93d1e96315fd31dfa7757fe5559a6767744ee959
3,065
ex
Elixir
lib/changelog/factory.ex
kentcdodds/changelog.com
e1c0d7ee5d47dc83dd443d623adb0f07e4acb28d
[ "MIT" ]
null
null
null
lib/changelog/factory.ex
kentcdodds/changelog.com
e1c0d7ee5d47dc83dd443d623adb0f07e4acb28d
[ "MIT" ]
null
null
null
lib/changelog/factory.ex
kentcdodds/changelog.com
e1c0d7ee5d47dc83dd443d623adb0f07e4acb28d
[ "MIT" ]
null
null
null
defmodule Changelog.Factory do use ExMachina.Ecto, repo: Changelog.Repo import Changelog.TimeView, only: [hours_from_now: 1, hours_ago: 1] def channel_factory do %Changelog.Channel{ name: sequence(:name, &"Channel #{&1}"), slug: sequence(:slug, &"channel-#{&1}") } end def episode_factory do %Changelog.Episode{ title: sequence(:title, &"Best Show Evar! #{&1}"), slug: sequence(:slug, &"best-show-evar-#{&1}"), podcast: build(:podcast) } end def episode_stat_factory do %Changelog.EpisodeStat{ date: Timex.today, episode: build(:episode), podcast: build(:podcast), downloads: 0.0, uniques: 0, demographics: %{"agents" => %{}, "countries" => %{}} } end def episode_guest_factory do %Changelog.EpisodeGuest{ episode: build(:episode), person: build(:person), position: 1 } end def episode_host_factory do %Changelog.EpisodeHost{ episode: build(:episode), person: build(:person), position: 1 } end def episode_sponsor_factory do %Changelog.EpisodeSponsor{ episode: build(:episode), sponsor: build(:sponsor), title: "Google", link_url: "https://google.com", description: "Don't be evil", position: 1 } end def live_episode_factory do %Changelog.Episode{episode_factory() | recorded_live: true} end def publishable_episode_factory do %Changelog.Episode{episode_factory() | audio_file: stub_audio_file(), summary: "An episode", published_at: hours_ago(1) } end def published_episode_factory do %Changelog.Episode{episode_factory() | audio_file: stub_audio_file(), published: true, published_at: hours_ago(1) } end def scheduled_episode_factory do %Changelog.Episode{episode_factory() | audio_file: stub_audio_file(), published: true, published_at: hours_from_now(1) } end def person_factory do %Changelog.Person{ name: sequence(:name, &"Joe Blow #{&1}"), email: sequence(:email, &"joe-#{&1}@email.com"), handle: sequence(:handle, &"joeblow-#{&1}"), admin: false } end def podcast_factory do %Changelog.Podcast{ name: sequence(:name, &"Show #{&1}"), slug: sequence(:slug, &"show-#{&1}"), status: :published } end def post_factory do %Changelog.Post{ title: sequence(:name, &"Post #{&1}"), slug: sequence(:slug, &"post-#{&1}"), author: build(:person) } end def published_post_factory do %Changelog.Post{post_factory() | published: true, published_at: hours_ago(1)} end def scheduled_post_factory do %Changelog.Post{post_factory() | published: true, published_at: hours_from_now(1)} end def sponsor_factory do %Changelog.Sponsor{ name: sequence(:name, &"Sponsor #{&1}") } end defp stub_audio_file do %{file_name: "test.mp3", updated_at: Ecto.DateTime.from_erl(:calendar.gregorian_seconds_to_datetime(63_633_830_567))} end end
24.325397
121
0.63752
93d1f24d683578b79c177a450298e90a6649bda2
1,427
ex
Elixir
apps/nerves_hub_device/test/support/data_case.ex
Gazler/nerves_hub_web
9a636a17310382819eaa6cee590e053cb47f0dcc
[ "Apache-2.0" ]
1
2019-10-13T10:56:28.000Z
2019-10-13T10:56:28.000Z
apps/nerves_hub_device/test/support/data_case.ex
Eaftos/nerves_hub_web
ac03bd044b97265bf3ba3edd8da249d300fa3668
[ "Apache-2.0" ]
null
null
null
apps/nerves_hub_device/test/support/data_case.ex
Eaftos/nerves_hub_web
ac03bd044b97265bf3ba3edd8da249d300fa3668
[ "Apache-2.0" ]
null
null
null
defmodule NervesHubDevice.DataCase do @moduledoc """ This module defines the setup for tests requiring access to the application's data layer. You may define functions here to be used as helpers in your tests. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do alias NervesHubWebCore.Repo import Ecto import Ecto.Changeset import Ecto.Query import NervesHubWebCore.DataCase end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(NervesHubWebCore.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(NervesHubWebCore.Repo, {:shared, self()}) end :ok end @doc """ A helper that transform changeset errors to a map of messages. assert {:error, changeset} = Accounts.create_user(%{password: "short"}) assert "password is too short" in errors_on(changeset).password assert %{password: ["password is too short"]} = errors_on(changeset) """ def errors_on(changeset) do Ecto.Changeset.traverse_errors(changeset, fn {message, opts} -> Enum.reduce(opts, message, fn {key, value}, acc -> String.replace(acc, "%{#{key}}", to_string(value)) end) end) end end
26.425926
78
0.689559
93d225180bda206ffe52f69311ab7785268b1946
1,274
ex
Elixir
lib/samly_howto_web/views/error_helpers.ex
chespinoza/samly_howto
511102eecfdfd516c14abd5d0280af19f5ab19a3
[ "MIT" ]
null
null
null
lib/samly_howto_web/views/error_helpers.ex
chespinoza/samly_howto
511102eecfdfd516c14abd5d0280af19f5ab19a3
[ "MIT" ]
null
null
null
lib/samly_howto_web/views/error_helpers.ex
chespinoza/samly_howto
511102eecfdfd516c14abd5d0280af19f5ab19a3
[ "MIT" ]
null
null
null
defmodule SamlyHowtoWeb.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do Enum.map(Keyword.get_values(form.errors, field), fn error -> content_tag(:span, translate_error(error), class: "help-block") end) end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # Because error messages were defined within Ecto, we must # call the Gettext module passing our Gettext backend. We # also use the "errors" domain as translations are placed # in the errors.po file. # Ecto will pass the :count keyword if the error message is # meant to be pluralized. # On your own code and templates, depending on whether you # need the message to be pluralized or not, this could be # written simply as: # # dngettext "errors", "1 file", "%{count} files", count # dgettext "errors", "is invalid" # if count = opts[:count] do Gettext.dngettext(SamlyHowtoWeb.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(SamlyHowtoWeb.Gettext, "errors", msg, opts) end end end
31.073171
79
0.673469