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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ffe36545e56f529c84aefddae8c5708b8cb90003 | 1,123 | exs | Elixir | config/config.exs | X4lldux/disc_union | e5b5a2d775a0536fa492c311bc297f71b0a5980d | [
"MIT"
] | 58 | 2016-05-14T03:56:22.000Z | 2019-04-18T14:45:27.000Z | config/config.exs | X4lldux/disc_union | e5b5a2d775a0536fa492c311bc297f71b0a5980d | [
"MIT"
] | 5 | 2016-08-30T19:47:33.000Z | 2017-02-04T22:50:40.000Z | config/config.exs | x4lldux/disc_union | e5b5a2d775a0536fa492c311bc297f71b0a5980d | [
"MIT"
] | 2 | 2017-02-03T15:39:23.000Z | 2018-11-21T15:30:59.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 :disc_union, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:disc_union, :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.225806 | 73 | 0.752449 |
ffe3672bb1e69605223ff975e6bb98eccfacab0a | 472 | ex | Elixir | lib/gexbot/github/app.ex | jakewilkins/gexbot | b92cd5bae794becaedbee9c8884e4b66942198b7 | [
"WTFPL"
] | null | null | null | lib/gexbot/github/app.ex | jakewilkins/gexbot | b92cd5bae794becaedbee9c8884e4b66942198b7 | [
"WTFPL"
] | null | null | null | lib/gexbot/github/app.ex | jakewilkins/gexbot | b92cd5bae794becaedbee9c8884e4b66942198b7 | [
"WTFPL"
] | null | null | null | defmodule Gexbot.Github.App do
alias Tentacat.Client
alias Gexbot.Github.App.Token
def client_from(%{installation_id: _id} = spec) do
Client.new(Token.installation(spec))
end
def client_from(%{user_id: _id} = spec) do
Client.new(Token.user(spec))
end
def client_from(%{oauth_code: _id} = spec) do
Client.new(Token.user(spec))
end
def client_from(%{app_id: _id, private_key: _key_path} = spec) do
Client.new(Token.jwt(spec))
end
end
| 22.47619 | 67 | 0.699153 |
ffe3682d6eea40baf83ec071054243a01cd66df8 | 2,135 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/creative_click_through_url.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/creative_click_through_url.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/creative_click_through_url.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.DFAReporting.V33.Model.CreativeClickThroughUrl do
@moduledoc """
Click-through URL
## Attributes
* `computedClickThroughUrl` (*type:* `String.t`, *default:* `nil`) - Read-only convenience field representing the actual URL that will be used for this click-through. The URL is computed as follows: - If landingPageId is specified then that landing page's URL is assigned to this field. - Otherwise, the customClickThroughUrl is assigned to this field.
* `customClickThroughUrl` (*type:* `String.t`, *default:* `nil`) - Custom click-through URL. Applicable if the landingPageId field is left unset.
* `landingPageId` (*type:* `String.t`, *default:* `nil`) - ID of the landing page for the click-through URL.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:computedClickThroughUrl => String.t(),
:customClickThroughUrl => String.t(),
:landingPageId => String.t()
}
field(:computedClickThroughUrl)
field(:customClickThroughUrl)
field(:landingPageId)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.CreativeClickThroughUrl do
def decode(value, options) do
GoogleApi.DFAReporting.V33.Model.CreativeClickThroughUrl.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.CreativeClickThroughUrl do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.283019 | 357 | 0.742389 |
ffe37f13408efaeb1e0a439f21374d5437b4f9c0 | 1,931 | ex | Elixir | lib/wobserver2/web/client_proxy.ex | aruki-delivery/wobserver | 7db6b219b405defc1e28bd86836f9a90eed235b6 | [
"MIT"
] | null | null | null | lib/wobserver2/web/client_proxy.ex | aruki-delivery/wobserver | 7db6b219b405defc1e28bd86836f9a90eed235b6 | [
"MIT"
] | null | null | null | lib/wobserver2/web/client_proxy.ex | aruki-delivery/wobserver | 7db6b219b405defc1e28bd86836f9a90eed235b6 | [
"MIT"
] | null | null | null | defmodule Wobserver2.Web.ClientProxy do
@moduledoc ~S"""
ClientProxy will proxy websocket requests from `Wobserver2.Web.ClientSocket` to a remote node.
TODO: Needs config.
"""
@behaviour :websocket_client
@doc false
@spec connect(url :: String.t(), client :: pid) ::
{:ok, pid}
| any
def connect(url, client \\ self()) do
connect =
try do
:websocket_client.start_link(url, __MODULE__, [%{client: client}])
catch
error -> error
end
case connect do
{:ok, pid} ->
Process.unlink(pid)
{:ok, pid}
error ->
error
end
end
@doc false
@spec init(state :: [any]) :: {:reconnect, map}
def init([state]) do
{:reconnect, state}
end
@doc false
@spec onconnect(any, state :: map) :: {:ok, map}
def onconnect(_websocket_request, state) do
{:ok, state}
end
@doc false
@spec ondisconnect(any, state :: map) :: {:close, any, map}
def ondisconnect(reason, state) do
send(state.client, :proxy_disconnect)
{:close, reason, state}
end
@doc false
@spec websocket_info({:proxy, data :: String.t()}, any, state :: map) ::
{:reply, {:text, String.t()}, map}
def websocket_info({:proxy, data}, _connection, state) do
{:reply, {:text, data}, state}
end
@spec websocket_info(:disconnect, any, state :: map) :: {:close, String.t(), map}
def websocket_info(:disconnect, _connection, state) do
{:close, "Disconnect", state}
end
@doc false
@spec websocket_terminate(any, any, map) :: :ok
def websocket_terminate(_reason, _conn, _state), do: :ok
@doc false
@spec websocket_handle(any, any, state :: map) :: {:ok, map}
def websocket_handle(message, conn, state)
def websocket_handle({:text, message}, _conn, state) do
send(state.client, {:proxy, message})
{:ok, state}
end
def websocket_handle(_, _conn, state), do: {:ok, state}
end
| 24.1375 | 96 | 0.618332 |
ffe38009f1e2faf5915a97653b281cdd4ebe16d9 | 397 | exs | Elixir | apps/re/priv/repo/migrations/20190221135204_create_developments.exs | ruby2elixir/emcasa-backend | 70d7f4f233555417941ffa6ada84cf8740c21dd2 | [
"MIT"
] | 4 | 2019-11-01T16:29:31.000Z | 2020-10-10T21:20:12.000Z | apps/re/priv/repo/migrations/20190221135204_create_developments.exs | caspg/backend | 34df9dc14ab8ed75de4578fefa2e087580c7e867 | [
"MIT"
] | null | null | null | apps/re/priv/repo/migrations/20190221135204_create_developments.exs | caspg/backend | 34df9dc14ab8ed75de4578fefa2e087580c7e867 | [
"MIT"
] | 5 | 2019-11-04T21:25:45.000Z | 2020-02-13T23:49:36.000Z | defmodule Re.Repo.Migrations.CreateDevelopments do
use Ecto.Migration
def up do
create table(:developments) do
add(:name, :string)
add(:title, :string)
add(:phase, :string)
add(:builder, :string)
add(:description, :text)
add(:address_id, references(:addresses))
timestamps()
end
end
def down do
drop(table(:developments))
end
end
| 18.904762 | 50 | 0.634761 |
ffe3a788a4691f823a016e2b1e3109d2e6af38b7 | 641 | ex | Elixir | lib/coderjobs/others/resume.ex | johndavedecano/CoderJobs | a185c3129f92430d8e72184f359c16f93f24c43b | [
"MIT"
] | 28 | 2017-11-20T02:01:17.000Z | 2021-05-08T16:52:58.000Z | lib/coderjobs/others/resume.ex | johndavedecano/CoderJobs | a185c3129f92430d8e72184f359c16f93f24c43b | [
"MIT"
] | 1 | 2018-12-05T06:07:36.000Z | 2018-12-09T17:33:28.000Z | lib/coderjobs/others/resume.ex | johndavedecano/CoderJobs | a185c3129f92430d8e72184f359c16f93f24c43b | [
"MIT"
] | 3 | 2017-12-21T03:29:39.000Z | 2019-08-11T02:56:08.000Z | defmodule Coderjobs.Others.Resume do
use Ecto.Schema
import Ecto.Changeset
alias Coderjobs.Others.Resume
schema "" do
field :email, :string
field :coverletter, :string
field :name, :string
field :github, :string
field :website, :string
field :resume, :string
field :mobile, :string
timestamps()
end
def changeset(%Resume{} = form, attrs \\ %{}) do
form
|> cast(attrs, [:email, :coverletter, :name, :website, :github, :resume, :mobile])
|> validate_required([:email, :resume, :name])
|> validate_format(:email, ~r/@/)
end
end
| 24.653846 | 88 | 0.591264 |
ffe3a8ff3d99f0a1482c07038e5cb813e4595757 | 342 | exs | Elixir | priv/repo/seeds.exs | Hajto/hangmanelixir | a05cc0b73e0a5d464405f63d274ae622565728ca | [
"MIT"
] | null | null | null | priv/repo/seeds.exs | Hajto/hangmanelixir | a05cc0b73e0a5d464405f63d274ae622565728ca | [
"MIT"
] | null | null | null | priv/repo/seeds.exs | Hajto/hangmanelixir | a05cc0b73e0a5d464405f63d274ae622565728ca | [
"MIT"
] | null | null | null | # Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# Hangman.Repo.insert!(%SomeModel{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
| 28.5 | 61 | 0.701754 |
ffe3b8a788743eade8e711259b3f88ab5ff13af7 | 2,442 | exs | Elixir | mix.exs | shagberg/teslamate | 1f139b29bd5c2c93b158bdef10c66f9f3556e95c | [
"MIT"
] | null | null | null | mix.exs | shagberg/teslamate | 1f139b29bd5c2c93b158bdef10c66f9f3556e95c | [
"MIT"
] | null | null | null | mix.exs | shagberg/teslamate | 1f139b29bd5c2c93b158bdef10c66f9f3556e95c | [
"MIT"
] | null | null | null | defmodule TeslaMate.MixProject do
use Mix.Project
def project do
[
app: :teslamate,
version: "1.15.1",
elixir: "~> 1.9",
elixirc_paths: elixirc_paths(Mix.env()),
compilers: [:phoenix, :gettext] ++ Mix.compilers(),
start_permanent: Mix.env() == :prod,
aliases: aliases(),
releases: releases(),
deps: deps(),
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test,
ci: :test
]
]
end
def application do
[
mod: {TeslaMate.Application, []},
extra_applications: [:logger, :runtime_tools]
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
defp deps do
[
{:phoenix, "~> 1.4"},
{:phoenix_pubsub, "~> 1.1"},
{:phoenix_ecto, "~> 4.0"},
{:ecto_sql, "~> 3.0"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.11"},
{:phoenix_live_reload, "~> 1.2", only: :dev},
{:gettext, "~> 0.11"},
{:jason, "~> 1.0"},
{:plug_cowboy, "~> 2.0"},
{:gen_state_machine, "~> 2.0"},
{:ecto_enum, "~> 1.0"},
{:phoenix_live_view, "~> 0.1"},
{:floki, "~> 0.23", only: :test},
{:tortoise, "~> 0.9"},
{:excoveralls, "~> 0.10", only: :test},
{:mojito, "~> 0.5"},
{:srtm, "~> 0.5"},
{:fuse, "~> 2.4"},
{:mock, "~> 0.3", only: :test},
{:castore, "~> 0.1"},
{:cachex, "~> 3.2"}
]
end
defp aliases do
[
setup: ["deps.get", "ecto.setup", &setup_yarn/1],
"ecto.setup": ["ecto.create", "ecto.migrate"],
"ecto.reset": ["ecto.drop", "ecto.setup"],
test: ["ecto.create --quiet", "ecto.migrate", "test --no-start"],
ci: ["format --check-formatted", "test --raise"]
]
end
defp releases() do
[
teslamate: [
include_executables_for: [:unix],
applications: [runtime_tools: :permanent]
]
]
end
defp setup_yarn(_) do
cmd("yarn", ["install"], cd: "assets")
end
defp cmd(cmd, args, opts) do
opts = Keyword.merge([into: IO.stream(:stdio, :line), stderr_to_stdout: true], opts)
{_, result} = System.cmd(cmd, args, opts)
if result != 0 do
raise "Non-zero result (#{result}) from: #{cmd} #{Enum.map_join(args, " ", &inspect/1)}"
end
end
end
| 25.705263 | 94 | 0.514742 |
ffe3c196520ee4bef2110288b2e4b9a8ca25d46c | 1,284 | exs | Elixir | apps/bank/mix.exs | patrickdet/acme_bank | b9660d995ef8eea94f921511a3936bf354d2fbbc | [
"MIT"
] | 2 | 2020-04-07T20:02:24.000Z | 2021-02-27T13:32:13.000Z | apps/bank/mix.exs | patrickdet/acme_bank | b9660d995ef8eea94f921511a3936bf354d2fbbc | [
"MIT"
] | null | null | null | apps/bank/mix.exs | patrickdet/acme_bank | b9660d995ef8eea94f921511a3936bf354d2fbbc | [
"MIT"
] | null | null | null | defmodule Bank.Mixfile do
use Mix.Project
def project do
[app: :bank,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: ">= 1.3.2",
elixirc_paths: elixirc_paths(Mix.env),
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
aliases: aliases(),
deps: deps(),
docs: [main: "Bank"]]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
[applications: [:logger, :ecto, :postgrex, :auth, :money],
mod: {Bank.Application, []}]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
defp deps do
[{:ecto, "~> 2.0"},
{:postgrex, ">= 0.0.0"},
{:scrivener_ecto, github: "drewolson/scrivener_ecto"},
{:auth, in_umbrella: true},
{:messenger, in_umbrella: true},
{:money, in_umbrella: true}]
end
defp aliases do
["ecto.setup": ["ecto.create", "ecto.migrate", "ecto.seed"],
"ecto.seed": ["run priv/repo/seeds.exs"],
"ecto.reset": ["ecto.drop", "ecto.setup"],
"test": ["ecto.create --quiet", "ecto.migrate", "test"]]
end
end
| 26.75 | 64 | 0.583333 |
ffe3c47dc4e86644427d2f1ec078c21fe64e5484 | 457 | exs | Elixir | test/elixir_cluster_demo_web/views/error_view_test.exs | isabella232/elixir_cluster | 1e81d191e50b8959200770d47fd7c0b609b658e4 | [
"MIT"
] | 18 | 2019-06-06T19:30:48.000Z | 2021-08-24T19:17:37.000Z | test/elixir_cluster_demo_web/views/error_view_test.exs | isabella232/elixir_cluster | 1e81d191e50b8959200770d47fd7c0b609b658e4 | [
"MIT"
] | 2 | 2020-03-29T21:28:56.000Z | 2020-11-19T17:13:56.000Z | test/elixir_cluster_demo_web/views/error_view_test.exs | isabella232/elixir_cluster | 1e81d191e50b8959200770d47fd7c0b609b658e4 | [
"MIT"
] | 7 | 2019-09-11T11:29:37.000Z | 2022-03-26T07:45:37.000Z | defmodule ElixirClusterDemoWeb.ErrorViewTest do
use ElixirClusterDemoWeb.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(ElixirClusterDemoWeb.ErrorView, "404.html", []) == "Not Found"
end
test "renders 500.html" do
assert render_to_string(ElixirClusterDemoWeb.ErrorView, "500.html", []) == "Internal Server Error"
end
end
| 30.466667 | 102 | 0.757112 |
ffe3d76bc0e925888bc8b22cdb1896c15dbdc9b4 | 117,548 | ex | Elixir | lib/aws/generated/iam.ex | benmmari/aws-elixir | b97477498a9e8ba0d46a09255302d88c6a1c8573 | [
"Apache-2.0"
] | null | null | null | lib/aws/generated/iam.ex | benmmari/aws-elixir | b97477498a9e8ba0d46a09255302d88c6a1c8573 | [
"Apache-2.0"
] | null | null | null | lib/aws/generated/iam.ex | benmmari/aws-elixir | b97477498a9e8ba0d46a09255302d88c6a1c8573 | [
"Apache-2.0"
] | null | null | null | # WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
# See https://github.com/aws-beam/aws-codegen for more details.
defmodule AWS.IAM do
@moduledoc """
AWS Identity and Access Management
AWS Identity and Access Management (IAM) is a web service for securely
controlling access to AWS services. With IAM, you can centrally manage
users, security credentials such as access keys, and permissions that
control which AWS resources users and applications can access. For more
information about IAM, see [AWS Identity and Access Management
(IAM)](http://aws.amazon.com/iam/) and the [AWS Identity and Access
Management User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/).
"""
@doc """
Adds a new client ID (also known as audience) to the list of client IDs
already registered for the specified IAM OpenID Connect (OIDC) provider
resource.
This operation is idempotent; it does not fail or return an error if you
add an existing client ID to the provider.
"""
def add_client_i_d_to_open_i_d_connect_provider(client, input, options \\ []) do
request(client, "AddClientIDToOpenIDConnectProvider", input, options)
end
@doc """
Adds the specified IAM role to the specified instance profile. An instance
profile can contain only one role. (The number and size of IAM resources in
an AWS account are limited. For more information, see [IAM and STS
Quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html)
in the *IAM User Guide*.) You can remove the existing role and then add a
different role to an instance profile. You must then wait for the change to
appear across all of AWS because of [eventual
consistency](https://en.wikipedia.org/wiki/Eventual_consistency). To force
the change, you must [disassociate the instance
profile](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DisassociateIamInstanceProfile.html)
and then [associate the instance
profile](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AssociateIamInstanceProfile.html),
or you can stop your instance and then restart it.
<note> The caller of this API must be granted the `PassRole` permission on
the IAM role by a permissions policy.
</note> For more information about roles, go to [Working with
Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html).
For more information about instance profiles, go to [About Instance
Profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html).
"""
def add_role_to_instance_profile(client, input, options \\ []) do
request(client, "AddRoleToInstanceProfile", input, options)
end
@doc """
Adds the specified user to the specified group.
"""
def add_user_to_group(client, input, options \\ []) do
request(client, "AddUserToGroup", input, options)
end
@doc """
Attaches the specified managed policy to the specified IAM group.
You use this API to attach a managed policy to a group. To embed an inline
policy in a group, use `PutGroupPolicy`.
For more information about policies, see [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def attach_group_policy(client, input, options \\ []) do
request(client, "AttachGroupPolicy", input, options)
end
@doc """
Attaches the specified managed policy to the specified IAM role. When you
attach a managed policy to a role, the managed policy becomes part of the
role's permission (access) policy.
<note> You cannot use a managed policy as the role's trust policy. The
role's trust policy is created at the same time as the role, using
`CreateRole`. You can update a role's trust policy using
`UpdateAssumeRolePolicy`.
</note> Use this API to attach a *managed* policy to a role. To embed an
inline policy in a role, use `PutRolePolicy`. For more information about
policies, see [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def attach_role_policy(client, input, options \\ []) do
request(client, "AttachRolePolicy", input, options)
end
@doc """
Attaches the specified managed policy to the specified user.
You use this API to attach a *managed* policy to a user. To embed an inline
policy in a user, use `PutUserPolicy`.
For more information about policies, see [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def attach_user_policy(client, input, options \\ []) do
request(client, "AttachUserPolicy", input, options)
end
@doc """
Changes the password of the IAM user who is calling this operation. The AWS
account root user password is not affected by this operation.
To change the password for a different user, see `UpdateLoginProfile`. For
more information about modifying passwords, see [Managing
Passwords](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingLogins.html)
in the *IAM User Guide*.
"""
def change_password(client, input, options \\ []) do
request(client, "ChangePassword", input, options)
end
@doc """
Creates a new AWS secret access key and corresponding AWS access key ID for
the specified user. The default status for new keys is `Active`.
If you do not specify a user name, IAM determines the user name implicitly
based on the AWS access key ID signing the request. This operation works
for access keys under the AWS account. Consequently, you can use this
operation to manage AWS account root user credentials. This is true even if
the AWS account has no associated users.
The number and size of IAM resources in an AWS account are limited. For
more information, see [IAM and STS
Quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html)
in the *IAM User Guide*.
<important> To ensure the security of your AWS account, the secret access
key is accessible only during key and user creation. You must save the key
(for example, in a text file) if you want to be able to access it again. If
a secret key is lost, you can delete the access keys for the associated
user and then create new keys.
</important>
"""
def create_access_key(client, input, options \\ []) do
request(client, "CreateAccessKey", input, options)
end
@doc """
Creates an alias for your AWS account. For information about using an AWS
account alias, see [Using an Alias for Your AWS Account
ID](https://docs.aws.amazon.com/IAM/latest/UserGuide/AccountAlias.html) in
the *IAM User Guide*.
"""
def create_account_alias(client, input, options \\ []) do
request(client, "CreateAccountAlias", input, options)
end
@doc """
Creates a new group.
The number and size of IAM resources in an AWS account are limited. For
more information, see [IAM and STS
Quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html)
in the *IAM User Guide*.
"""
def create_group(client, input, options \\ []) do
request(client, "CreateGroup", input, options)
end
@doc """
Creates a new instance profile. For information about instance profiles, go
to [About Instance
Profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html).
The number and size of IAM resources in an AWS account are limited. For
more information, see [IAM and STS
Quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html)
in the *IAM User Guide*.
"""
def create_instance_profile(client, input, options \\ []) do
request(client, "CreateInstanceProfile", input, options)
end
@doc """
Creates a password for the specified user, giving the user the ability to
access AWS services through the AWS Management Console. For more
information about managing passwords, see [Managing
Passwords](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingLogins.html)
in the *IAM User Guide*.
"""
def create_login_profile(client, input, options \\ []) do
request(client, "CreateLoginProfile", input, options)
end
@doc """
Creates an IAM entity to describe an identity provider (IdP) that supports
[OpenID Connect (OIDC)](http://openid.net/connect/).
The OIDC provider that you create with this operation can be used as a
principal in a role's trust policy. Such a policy establishes a trust
relationship between AWS and the OIDC provider.
When you create the IAM OIDC provider, you specify the following:
<ul> <li> The URL of the OIDC identity provider (IdP) to trust
</li> <li> A list of client IDs (also known as audiences) that identify the
application or applications that are allowed to authenticate using the OIDC
provider
</li> <li> A list of thumbprints of one or more server certificates that
the IdP uses
</li> </ul> You get all of this information from the OIDC IdP that you want
to use to access AWS.
<note> The trust for the OIDC provider is derived from the IAM provider
that this operation creates. Therefore, it is best to limit access to the
`CreateOpenIDConnectProvider` operation to highly privileged users.
</note>
"""
def create_open_i_d_connect_provider(client, input, options \\ []) do
request(client, "CreateOpenIDConnectProvider", input, options)
end
@doc """
Creates a new managed policy for your AWS account.
This operation creates a policy version with a version identifier of `v1`
and sets v1 as the policy's default version. For more information about
policy versions, see [Versioning for Managed
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html)
in the *IAM User Guide*.
For more information about managed policies in general, see [Managed
Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def create_policy(client, input, options \\ []) do
request(client, "CreatePolicy", input, options)
end
@doc """
Creates a new version of the specified managed policy. To update a managed
policy, you create a new policy version. A managed policy can have up to
five versions. If the policy has five versions, you must delete an existing
version using `DeletePolicyVersion` before you create a new version.
Optionally, you can set the new version as the policy's default version.
The default version is the version that is in effect for the IAM users,
groups, and roles to which the policy is attached.
For more information about managed policy versions, see [Versioning for
Managed
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html)
in the *IAM User Guide*.
"""
def create_policy_version(client, input, options \\ []) do
request(client, "CreatePolicyVersion", input, options)
end
@doc """
Creates a new role for your AWS account. For more information about roles,
go to [IAM
Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html).
The number and size of IAM resources in an AWS account are limited. For
more information, see [IAM and STS
Quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html)
in the *IAM User Guide*.
"""
def create_role(client, input, options \\ []) do
request(client, "CreateRole", input, options)
end
@doc """
Creates an IAM resource that describes an identity provider (IdP) that
supports SAML 2.0.
The SAML provider resource that you create with this operation can be used
as a principal in an IAM role's trust policy. Such a policy can enable
federated users who sign in using the SAML IdP to assume the role. You can
create an IAM role that supports Web-based single sign-on (SSO) to the AWS
Management Console or one that supports API access to AWS.
When you create the SAML provider resource, you upload a SAML metadata
document that you get from your IdP. That document includes the issuer's
name, expiration information, and keys that can be used to validate the
SAML authentication response (assertions) that the IdP sends. You must
generate the metadata document using the identity management software that
is used as your organization's IdP.
<note> This operation requires [Signature Version
4](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html).
</note> For more information, see [Enabling SAML 2.0 Federated Users to
Access the AWS Management
Console](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-saml.html)
and [About SAML 2.0-based
Federation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html)
in the *IAM User Guide*.
"""
def create_s_a_m_l_provider(client, input, options \\ []) do
request(client, "CreateSAMLProvider", input, options)
end
@doc """
Creates an IAM role that is linked to a specific AWS service. The service
controls the attached policies and when the role can be deleted. This helps
ensure that the service is not broken by an unexpectedly changed or deleted
role, which could put your AWS resources into an unknown state. Allowing
the service to control the role helps improve service stability and proper
cleanup when a service and its role are no longer needed. For more
information, see [Using Service-Linked
Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html)
in the *IAM User Guide*.
To attach a policy to this service-linked role, you must make the request
using the AWS service that depends on this role.
"""
def create_service_linked_role(client, input, options \\ []) do
request(client, "CreateServiceLinkedRole", input, options)
end
@doc """
Generates a set of credentials consisting of a user name and password that
can be used to access the service specified in the request. These
credentials are generated by IAM, and can be used only for the specified
service.
You can have a maximum of two sets of service-specific credentials for each
supported service per user.
The only supported service at this time is AWS CodeCommit.
You can reset the password to a new service-generated value by calling
`ResetServiceSpecificCredential`.
For more information about service-specific credentials, see [Using IAM
with AWS CodeCommit: Git Credentials, SSH Keys, and AWS Access
Keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_ssh-keys.html)
in the *IAM User Guide*.
"""
def create_service_specific_credential(client, input, options \\ []) do
request(client, "CreateServiceSpecificCredential", input, options)
end
@doc """
Creates a new IAM user for your AWS account.
The number and size of IAM resources in an AWS account are limited. For
more information, see [IAM and STS
Quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html)
in the *IAM User Guide*.
"""
def create_user(client, input, options \\ []) do
request(client, "CreateUser", input, options)
end
@doc """
Creates a new virtual MFA device for the AWS account. After creating the
virtual MFA, use `EnableMFADevice` to attach the MFA device to an IAM user.
For more information about creating and working with virtual MFA devices,
go to [Using a Virtual MFA
Device](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_VirtualMFA.html)
in the *IAM User Guide*.
The number and size of IAM resources in an AWS account are limited. For
more information, see [IAM and STS
Quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html)
in the *IAM User Guide*.
<important> The seed information contained in the QR code and the Base32
string should be treated like any other secret access information. In other
words, protect the seed information as you would your AWS access keys or
your passwords. After you provision your virtual device, you should ensure
that the information is destroyed following secure procedures.
</important>
"""
def create_virtual_m_f_a_device(client, input, options \\ []) do
request(client, "CreateVirtualMFADevice", input, options)
end
@doc """
Deactivates the specified MFA device and removes it from association with
the user name for which it was originally enabled.
For more information about creating and working with virtual MFA devices,
go to [Enabling a Virtual Multi-factor Authentication (MFA)
Device](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_VirtualMFA.html)
in the *IAM User Guide*.
"""
def deactivate_m_f_a_device(client, input, options \\ []) do
request(client, "DeactivateMFADevice", input, options)
end
@doc """
Deletes the access key pair associated with the specified IAM user.
If you do not specify a user name, IAM determines the user name implicitly
based on the AWS access key ID signing the request. This operation works
for access keys under the AWS account. Consequently, you can use this
operation to manage AWS account root user credentials even if the AWS
account has no associated users.
"""
def delete_access_key(client, input, options \\ []) do
request(client, "DeleteAccessKey", input, options)
end
@doc """
Deletes the specified AWS account alias. For information about using an AWS
account alias, see [Using an Alias for Your AWS Account
ID](https://docs.aws.amazon.com/IAM/latest/UserGuide/AccountAlias.html) in
the *IAM User Guide*.
"""
def delete_account_alias(client, input, options \\ []) do
request(client, "DeleteAccountAlias", input, options)
end
@doc """
Deletes the password policy for the AWS account. There are no parameters.
"""
def delete_account_password_policy(client, input, options \\ []) do
request(client, "DeleteAccountPasswordPolicy", input, options)
end
@doc """
Deletes the specified IAM group. The group must not contain any users or
have any attached policies.
"""
def delete_group(client, input, options \\ []) do
request(client, "DeleteGroup", input, options)
end
@doc """
Deletes the specified inline policy that is embedded in the specified IAM
group.
A group can also have managed policies attached to it. To detach a managed
policy from a group, use `DetachGroupPolicy`. For more information about
policies, refer to [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def delete_group_policy(client, input, options \\ []) do
request(client, "DeleteGroupPolicy", input, options)
end
@doc """
Deletes the specified instance profile. The instance profile must not have
an associated role.
<important> Make sure that you do not have any Amazon EC2 instances running
with the instance profile you are about to delete. Deleting a role or
instance profile that is associated with a running instance will break any
applications running on the instance.
</important> For more information about instance profiles, go to [About
Instance
Profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html).
"""
def delete_instance_profile(client, input, options \\ []) do
request(client, "DeleteInstanceProfile", input, options)
end
@doc """
Deletes the password for the specified IAM user, which terminates the
user's ability to access AWS services through the AWS Management Console.
<important> Deleting a user's password does not prevent a user from
accessing AWS through the command line interface or the API. To prevent all
user access, you must also either make any access keys inactive or delete
them. For more information about making keys inactive or deleting them, see
`UpdateAccessKey` and `DeleteAccessKey`.
</important>
"""
def delete_login_profile(client, input, options \\ []) do
request(client, "DeleteLoginProfile", input, options)
end
@doc """
Deletes an OpenID Connect identity provider (IdP) resource object in IAM.
Deleting an IAM OIDC provider resource does not update any roles that
reference the provider as a principal in their trust policies. Any attempt
to assume a role that references a deleted provider fails.
This operation is idempotent; it does not fail or return an error if you
call the operation for a provider that does not exist.
"""
def delete_open_i_d_connect_provider(client, input, options \\ []) do
request(client, "DeleteOpenIDConnectProvider", input, options)
end
@doc """
Deletes the specified managed policy.
Before you can delete a managed policy, you must first detach the policy
from all users, groups, and roles that it is attached to. In addition, you
must delete all the policy's versions. The following steps describe the
process for deleting a managed policy:
<ul> <li> Detach the policy from all users, groups, and roles that the
policy is attached to, using the `DetachUserPolicy`, `DetachGroupPolicy`,
or `DetachRolePolicy` API operations. To list all the users, groups, and
roles that a policy is attached to, use `ListEntitiesForPolicy`.
</li> <li> Delete all versions of the policy using `DeletePolicyVersion`.
To list the policy's versions, use `ListPolicyVersions`. You cannot use
`DeletePolicyVersion` to delete the version that is marked as the default
version. You delete the policy's default version in the next step of the
process.
</li> <li> Delete the policy (this automatically deletes the policy's
default version) using this API.
</li> </ul> For information about managed policies, see [Managed Policies
and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def delete_policy(client, input, options \\ []) do
request(client, "DeletePolicy", input, options)
end
@doc """
Deletes the specified version from the specified managed policy.
You cannot delete the default version from a policy using this API. To
delete the default version from a policy, use `DeletePolicy`. To find out
which version of a policy is marked as the default version, use
`ListPolicyVersions`.
For information about versions for managed policies, see [Versioning for
Managed
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html)
in the *IAM User Guide*.
"""
def delete_policy_version(client, input, options \\ []) do
request(client, "DeletePolicyVersion", input, options)
end
@doc """
Deletes the specified role. The role must not have any policies attached.
For more information about roles, go to [Working with
Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html).
<important> Make sure that you do not have any Amazon EC2 instances running
with the role you are about to delete. Deleting a role or instance profile
that is associated with a running instance will break any applications
running on the instance.
</important>
"""
def delete_role(client, input, options \\ []) do
request(client, "DeleteRole", input, options)
end
@doc """
Deletes the permissions boundary for the specified IAM role.
<important> Deleting the permissions boundary for a role might increase its
permissions. For example, it might allow anyone who assumes the role to
perform all the actions granted in its permissions policies.
</important>
"""
def delete_role_permissions_boundary(client, input, options \\ []) do
request(client, "DeleteRolePermissionsBoundary", input, options)
end
@doc """
Deletes the specified inline policy that is embedded in the specified IAM
role.
A role can also have managed policies attached to it. To detach a managed
policy from a role, use `DetachRolePolicy`. For more information about
policies, refer to [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def delete_role_policy(client, input, options \\ []) do
request(client, "DeleteRolePolicy", input, options)
end
@doc """
Deletes a SAML provider resource in IAM.
Deleting the provider resource from IAM does not update any roles that
reference the SAML provider resource's ARN as a principal in their trust
policies. Any attempt to assume a role that references a non-existent
provider resource ARN fails.
<note> This operation requires [Signature Version
4](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html).
</note>
"""
def delete_s_a_m_l_provider(client, input, options \\ []) do
request(client, "DeleteSAMLProvider", input, options)
end
@doc """
Deletes the specified SSH public key.
The SSH public key deleted by this operation is used only for
authenticating the associated IAM user to an AWS CodeCommit repository. For
more information about using SSH keys to authenticate to an AWS CodeCommit
repository, see [Set up AWS CodeCommit for SSH
Connections](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html)
in the *AWS CodeCommit User Guide*.
"""
def delete_s_s_h_public_key(client, input, options \\ []) do
request(client, "DeleteSSHPublicKey", input, options)
end
@doc """
Deletes the specified server certificate.
For more information about working with server certificates, see [Working
with Server
Certificates](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html)
in the *IAM User Guide*. This topic also includes a list of AWS services
that can use the server certificates that you manage with IAM.
<important> If you are using a server certificate with Elastic Load
Balancing, deleting the certificate could have implications for your
application. If Elastic Load Balancing doesn't detect the deletion of bound
certificates, it may continue to use the certificates. This could cause
Elastic Load Balancing to stop accepting traffic. We recommend that you
remove the reference to the certificate from Elastic Load Balancing before
using this command to delete the certificate. For more information, go to
[DeleteLoadBalancerListeners](https://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DeleteLoadBalancerListeners.html)
in the *Elastic Load Balancing API Reference*.
</important>
"""
def delete_server_certificate(client, input, options \\ []) do
request(client, "DeleteServerCertificate", input, options)
end
@doc """
Submits a service-linked role deletion request and returns a
`DeletionTaskId`, which you can use to check the status of the deletion.
Before you call this operation, confirm that the role has no active
sessions and that any resources used by the role in the linked service are
deleted. If you call this operation more than once for the same
service-linked role and an earlier deletion task is not complete, then the
`DeletionTaskId` of the earlier request is returned.
If you submit a deletion request for a service-linked role whose linked
service is still accessing a resource, then the deletion task fails. If it
fails, the `GetServiceLinkedRoleDeletionStatus` API operation returns the
reason for the failure, usually including the resources that must be
deleted. To delete the service-linked role, you must first remove those
resources from the linked service and then submit the deletion request
again. Resources are specific to the service that is linked to the role.
For more information about removing resources from a service, see the [AWS
documentation](http://docs.aws.amazon.com/) for your service.
For more information about service-linked roles, see [Roles Terms and
Concepts: AWS Service-Linked
Role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#iam-term-service-linked-role)
in the *IAM User Guide*.
"""
def delete_service_linked_role(client, input, options \\ []) do
request(client, "DeleteServiceLinkedRole", input, options)
end
@doc """
Deletes the specified service-specific credential.
"""
def delete_service_specific_credential(client, input, options \\ []) do
request(client, "DeleteServiceSpecificCredential", input, options)
end
@doc """
Deletes a signing certificate associated with the specified IAM user.
If you do not specify a user name, IAM determines the user name implicitly
based on the AWS access key ID signing the request. This operation works
for access keys under the AWS account. Consequently, you can use this
operation to manage AWS account root user credentials even if the AWS
account has no associated IAM users.
"""
def delete_signing_certificate(client, input, options \\ []) do
request(client, "DeleteSigningCertificate", input, options)
end
@doc """
Deletes the specified IAM user. Unlike the AWS Management Console, when you
delete a user programmatically, you must delete the items attached to the
user manually, or the deletion fails. For more information, see [Deleting
an IAM
User](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_manage.html#id_users_deleting_cli).
Before attempting to delete a user, remove the following items:
<ul> <li> Password (`DeleteLoginProfile`)
</li> <li> Access keys (`DeleteAccessKey`)
</li> <li> Signing certificate (`DeleteSigningCertificate`)
</li> <li> SSH public key (`DeleteSSHPublicKey`)
</li> <li> Git credentials (`DeleteServiceSpecificCredential`)
</li> <li> Multi-factor authentication (MFA) device (`DeactivateMFADevice`,
`DeleteVirtualMFADevice`)
</li> <li> Inline policies (`DeleteUserPolicy`)
</li> <li> Attached managed policies (`DetachUserPolicy`)
</li> <li> Group memberships (`RemoveUserFromGroup`)
</li> </ul>
"""
def delete_user(client, input, options \\ []) do
request(client, "DeleteUser", input, options)
end
@doc """
Deletes the permissions boundary for the specified IAM user.
<important> Deleting the permissions boundary for a user might increase its
permissions by allowing the user to perform all the actions granted in its
permissions policies.
</important>
"""
def delete_user_permissions_boundary(client, input, options \\ []) do
request(client, "DeleteUserPermissionsBoundary", input, options)
end
@doc """
Deletes the specified inline policy that is embedded in the specified IAM
user.
A user can also have managed policies attached to it. To detach a managed
policy from a user, use `DetachUserPolicy`. For more information about
policies, refer to [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def delete_user_policy(client, input, options \\ []) do
request(client, "DeleteUserPolicy", input, options)
end
@doc """
Deletes a virtual MFA device.
<note> You must deactivate a user's virtual MFA device before you can
delete it. For information about deactivating MFA devices, see
`DeactivateMFADevice`.
</note>
"""
def delete_virtual_m_f_a_device(client, input, options \\ []) do
request(client, "DeleteVirtualMFADevice", input, options)
end
@doc """
Removes the specified managed policy from the specified IAM group.
A group can also have inline policies embedded with it. To delete an inline
policy, use the `DeleteGroupPolicy` API. For information about policies,
see [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def detach_group_policy(client, input, options \\ []) do
request(client, "DetachGroupPolicy", input, options)
end
@doc """
Removes the specified managed policy from the specified role.
A role can also have inline policies embedded with it. To delete an inline
policy, use the `DeleteRolePolicy` API. For information about policies, see
[Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def detach_role_policy(client, input, options \\ []) do
request(client, "DetachRolePolicy", input, options)
end
@doc """
Removes the specified managed policy from the specified user.
A user can also have inline policies embedded with it. To delete an inline
policy, use the `DeleteUserPolicy` API. For information about policies, see
[Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def detach_user_policy(client, input, options \\ []) do
request(client, "DetachUserPolicy", input, options)
end
@doc """
Enables the specified MFA device and associates it with the specified IAM
user. When enabled, the MFA device is required for every subsequent login
by the IAM user associated with the device.
"""
def enable_m_f_a_device(client, input, options \\ []) do
request(client, "EnableMFADevice", input, options)
end
@doc """
Generates a credential report for the AWS account. For more information
about the credential report, see [Getting Credential
Reports](https://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html)
in the *IAM User Guide*.
"""
def generate_credential_report(client, input, options \\ []) do
request(client, "GenerateCredentialReport", input, options)
end
@doc """
Generates a report for service last accessed data for AWS Organizations.
You can generate a report for any entities (organization root,
organizational unit, or account) or policies in your organization.
To call this operation, you must be signed in using your AWS Organizations
master account credentials. You can use your long-term IAM user or root
user credentials, or temporary credentials from assuming an IAM role. SCPs
must be enabled for your organization root. You must have the required IAM
and AWS Organizations permissions. For more information, see [Refining
Permissions Using Service Last Accessed
Data](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html)
in the *IAM User Guide*.
You can generate a service last accessed data report for entities by
specifying only the entity's path. This data includes a list of services
that are allowed by any service control policies (SCPs) that apply to the
entity.
You can generate a service last accessed data report for a policy by
specifying an entity's path and an optional AWS Organizations policy ID.
This data includes a list of services that are allowed by the specified
SCP.
For each service in both report types, the data includes the most recent
account activity that the policy allows to account principals in the entity
or the entity's children. For important information about the data,
reporting period, permissions required, troubleshooting, and supported
Regions see [Reducing Permissions Using Service Last Accessed
Data](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html)
in the *IAM User Guide*.
<important> The data includes all attempts to access AWS, not just the
successful ones. This includes all attempts that were made using the AWS
Management Console, the AWS API through any of the SDKs, or any of the
command line tools. An unexpected entry in the service last accessed data
does not mean that an account has been compromised, because the request
might have been denied. Refer to your CloudTrail logs as the authoritative
source for information about all API calls and whether they were successful
or denied access. For more information, see [Logging IAM Events with
CloudTrail](https://docs.aws.amazon.com/IAM/latest/UserGuide/cloudtrail-integration.html)
in the *IAM User Guide*.
</important> This operation returns a `JobId`. Use this parameter in the `
`GetOrganizationsAccessReport` ` operation to check the status of the
report generation. To check the status of this request, use the `JobId`
parameter in the ` `GetOrganizationsAccessReport` ` operation and test the
`JobStatus` response parameter. When the job is complete, you can retrieve
the report.
To generate a service last accessed data report for entities, specify an
entity path without specifying the optional AWS Organizations policy ID.
The type of entity that you specify determines the data returned in the
report.
<ul> <li> **Root** – When you specify the organizations root as the entity,
the resulting report lists all of the services allowed by SCPs that are
attached to your root. For each service, the report includes data for all
accounts in your organization except the master account, because the master
account is not limited by SCPs.
</li> <li> **OU** – When you specify an organizational unit (OU) as the
entity, the resulting report lists all of the services allowed by SCPs that
are attached to the OU and its parents. For each service, the report
includes data for all accounts in the OU or its children. This data
excludes the master account, because the master account is not limited by
SCPs.
</li> <li> **Master account** – When you specify the master account, the
resulting report lists all AWS services, because the master account is not
limited by SCPs. For each service, the report includes data for only the
master account.
</li> <li> **Account** – When you specify another account as the entity,
the resulting report lists all of the services allowed by SCPs that are
attached to the account and its parents. For each service, the report
includes data for only the specified account.
</li> </ul> To generate a service last accessed data report for policies,
specify an entity path and the optional AWS Organizations policy ID. The
type of entity that you specify determines the data returned for each
service.
<ul> <li> **Root** – When you specify the root entity and a policy ID, the
resulting report lists all of the services that are allowed by the
specified SCP. For each service, the report includes data for all accounts
in your organization to which the SCP applies. This data excludes the
master account, because the master account is not limited by SCPs. If the
SCP is not attached to any entities in the organization, then the report
will return a list of services with no data.
</li> <li> **OU** – When you specify an OU entity and a policy ID, the
resulting report lists all of the services that are allowed by the
specified SCP. For each service, the report includes data for all accounts
in the OU or its children to which the SCP applies. This means that other
accounts outside the OU that are affected by the SCP might not be included
in the data. This data excludes the master account, because the master
account is not limited by SCPs. If the SCP is not attached to the OU or one
of its children, the report will return a list of services with no data.
</li> <li> **Master account** – When you specify the master account, the
resulting report lists all AWS services, because the master account is not
limited by SCPs. If you specify a policy ID in the CLI or API, the policy
is ignored. For each service, the report includes data for only the master
account.
</li> <li> **Account** – When you specify another account entity and a
policy ID, the resulting report lists all of the services that are allowed
by the specified SCP. For each service, the report includes data for only
the specified account. This means that other accounts in the organization
that are affected by the SCP might not be included in the data. If the SCP
is not attached to the account, the report will return a list of services
with no data.
</li> </ul> <note> Service last accessed data does not use other policy
types when determining whether a principal could access a service. These
other policy types include identity-based policies, resource-based
policies, access control lists, IAM permissions boundaries, and STS assume
role policies. It only applies SCP logic. For more about the evaluation of
policy types, see [Evaluating
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-basics)
in the *IAM User Guide*.
</note> For more information about service last accessed data, see
[Reducing Policy Scope by Viewing User
Activity](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html)
in the *IAM User Guide*.
"""
def generate_organizations_access_report(client, input, options \\ []) do
request(client, "GenerateOrganizationsAccessReport", input, options)
end
@doc """
Generates a report that includes details about when an IAM resource (user,
group, role, or policy) was last used in an attempt to access AWS services.
Recent activity usually appears within four hours. IAM reports activity for
the last 365 days, or less if your Region began supporting this feature
within the last year. For more information, see [Regions Where Data Is
Tracked](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#access-advisor_tracking-period).
<important> The service last accessed data includes all attempts to access
an AWS API, not just the successful ones. This includes all attempts that
were made using the AWS Management Console, the AWS API through any of the
SDKs, or any of the command line tools. An unexpected entry in the service
last accessed data does not mean that your account has been compromised,
because the request might have been denied. Refer to your CloudTrail logs
as the authoritative source for information about all API calls and whether
they were successful or denied access. For more information, see [Logging
IAM Events with
CloudTrail](https://docs.aws.amazon.com/IAM/latest/UserGuide/cloudtrail-integration.html)
in the *IAM User Guide*.
</important> The `GenerateServiceLastAccessedDetails` operation returns a
`JobId`. Use this parameter in the following operations to retrieve the
following details from your report:
<ul> <li> `GetServiceLastAccessedDetails` – Use this operation for users,
groups, roles, or policies to list every AWS service that the resource
could access using permissions policies. For each service, the response
includes information about the most recent access attempt.
The `JobId` returned by `GenerateServiceLastAccessedDetail` must be used by
the same role within a session, or by the same user when used to call
`GetServiceLastAccessedDetail`.
</li> <li> `GetServiceLastAccessedDetailsWithEntities` – Use this operation
for groups and policies to list information about the associated entities
(users or roles) that attempted to access a specific AWS service.
</li> </ul> To check the status of the `GenerateServiceLastAccessedDetails`
request, use the `JobId` parameter in the same operations and test the
`JobStatus` response parameter.
For additional information about the permissions policies that allow an
identity (user, group, or role) to access specific services, use the
`ListPoliciesGrantingServiceAccess` operation.
<note> Service last accessed data does not use other policy types when
determining whether a resource could access a service. These other policy
types include resource-based policies, access control lists, AWS
Organizations policies, IAM permissions boundaries, and AWS STS assume role
policies. It only applies permissions policy logic. For more about the
evaluation of policy types, see [Evaluating
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-basics)
in the *IAM User Guide*.
</note> For more information about service and action last accessed data,
see [Reducing Permissions Using Service Last Accessed
Data](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html)
in the *IAM User Guide*.
"""
def generate_service_last_accessed_details(client, input, options \\ []) do
request(client, "GenerateServiceLastAccessedDetails", input, options)
end
@doc """
Retrieves information about when the specified access key was last used.
The information includes the date and time of last use, along with the AWS
service and Region that were specified in the last request made with that
key.
"""
def get_access_key_last_used(client, input, options \\ []) do
request(client, "GetAccessKeyLastUsed", input, options)
end
@doc """
Retrieves information about all IAM users, groups, roles, and policies in
your AWS account, including their relationships to one another. Use this
API to obtain a snapshot of the configuration of IAM permissions (users,
groups, roles, and policies) in your account.
<note> Policies returned by this API are URL-encoded compliant with [RFC
3986](https://tools.ietf.org/html/rfc3986). You can use a URL decoding
method to convert the policy back to plain JSON text. For example, if you
use Java, you can use the `decode` method of the `java.net.URLDecoder`
utility class in the Java SDK. Other languages and SDKs provide similar
functionality.
</note> You can optionally filter the results using the `Filter` parameter.
You can paginate the results using the `MaxItems` and `Marker` parameters.
"""
def get_account_authorization_details(client, input, options \\ []) do
request(client, "GetAccountAuthorizationDetails", input, options)
end
@doc """
Retrieves the password policy for the AWS account. For more information
about using a password policy, go to [Managing an IAM Password
Policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingPasswordPolicies.html).
"""
def get_account_password_policy(client, input, options \\ []) do
request(client, "GetAccountPasswordPolicy", input, options)
end
@doc """
Retrieves information about IAM entity usage and IAM quotas in the AWS
account.
The number and size of IAM resources in an AWS account are limited. For
more information, see [IAM and STS
Quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html)
in the *IAM User Guide*.
"""
def get_account_summary(client, input, options \\ []) do
request(client, "GetAccountSummary", input, options)
end
@doc """
Gets a list of all of the context keys referenced in the input policies.
The policies are supplied as a list of one or more strings. To get the
context keys from policies associated with an IAM user, group, or role, use
`GetContextKeysForPrincipalPolicy`.
Context keys are variables maintained by AWS and its services that provide
details about the context of an API query request. Context keys can be
evaluated by testing against a value specified in an IAM policy. Use
`GetContextKeysForCustomPolicy` to understand what key names and values you
must supply when you call `SimulateCustomPolicy`. Note that all parameters
are shown in unencoded form here for clarity but must be URL encoded to be
included as a part of a real HTML request.
"""
def get_context_keys_for_custom_policy(client, input, options \\ []) do
request(client, "GetContextKeysForCustomPolicy", input, options)
end
@doc """
Gets a list of all of the context keys referenced in all the IAM policies
that are attached to the specified IAM entity. The entity can be an IAM
user, group, or role. If you specify a user, then the request also includes
all of the policies attached to groups that the user is a member of.
You can optionally include a list of one or more additional policies,
specified as strings. If you want to include *only* a list of policies by
string, use `GetContextKeysForCustomPolicy` instead.
**Note:** This API discloses information about the permissions granted to
other users. If you do not want users to see other user's permissions, then
consider allowing them to use `GetContextKeysForCustomPolicy` instead.
Context keys are variables maintained by AWS and its services that provide
details about the context of an API query request. Context keys can be
evaluated by testing against a value in an IAM policy. Use
`GetContextKeysForPrincipalPolicy` to understand what key names and values
you must supply when you call `SimulatePrincipalPolicy`.
"""
def get_context_keys_for_principal_policy(client, input, options \\ []) do
request(client, "GetContextKeysForPrincipalPolicy", input, options)
end
@doc """
Retrieves a credential report for the AWS account. For more information
about the credential report, see [Getting Credential
Reports](https://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html)
in the *IAM User Guide*.
"""
def get_credential_report(client, input, options \\ []) do
request(client, "GetCredentialReport", input, options)
end
@doc """
Returns a list of IAM users that are in the specified IAM group. You can
paginate the results using the `MaxItems` and `Marker` parameters.
"""
def get_group(client, input, options \\ []) do
request(client, "GetGroup", input, options)
end
@doc """
Retrieves the specified inline policy document that is embedded in the
specified IAM group.
<note> Policies returned by this API are URL-encoded compliant with [RFC
3986](https://tools.ietf.org/html/rfc3986). You can use a URL decoding
method to convert the policy back to plain JSON text. For example, if you
use Java, you can use the `decode` method of the `java.net.URLDecoder`
utility class in the Java SDK. Other languages and SDKs provide similar
functionality.
</note> An IAM group can also have managed policies attached to it. To
retrieve a managed policy document that is attached to a group, use
`GetPolicy` to determine the policy's default version, then use
`GetPolicyVersion` to retrieve the policy document.
For more information about policies, see [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def get_group_policy(client, input, options \\ []) do
request(client, "GetGroupPolicy", input, options)
end
@doc """
Retrieves information about the specified instance profile, including the
instance profile's path, GUID, ARN, and role. For more information about
instance profiles, see [About Instance
Profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html)
in the *IAM User Guide*.
"""
def get_instance_profile(client, input, options \\ []) do
request(client, "GetInstanceProfile", input, options)
end
@doc """
Retrieves the user name and password-creation date for the specified IAM
user. If the user has not been assigned a password, the operation returns a
404 (`NoSuchEntity`) error.
"""
def get_login_profile(client, input, options \\ []) do
request(client, "GetLoginProfile", input, options)
end
@doc """
Returns information about the specified OpenID Connect (OIDC) provider
resource object in IAM.
"""
def get_open_i_d_connect_provider(client, input, options \\ []) do
request(client, "GetOpenIDConnectProvider", input, options)
end
@doc """
Retrieves the service last accessed data report for AWS Organizations that
was previously generated using the ` `GenerateOrganizationsAccessReport` `
operation. This operation retrieves the status of your report job and the
report contents.
Depending on the parameters that you passed when you generated the report,
the data returned could include different information. For details, see
`GenerateOrganizationsAccessReport`.
To call this operation, you must be signed in to the master account in your
organization. SCPs must be enabled for your organization root. You must
have permissions to perform this operation. For more information, see
[Refining Permissions Using Service Last Accessed
Data](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html)
in the *IAM User Guide*.
For each service that principals in an account (root users, IAM users, or
IAM roles) could access using SCPs, the operation returns details about the
most recent access attempt. If there was no attempt, the service is listed
without details about the most recent attempt to access the service. If the
operation fails, it returns the reason that it failed.
By default, the list is sorted by service namespace.
"""
def get_organizations_access_report(client, input, options \\ []) do
request(client, "GetOrganizationsAccessReport", input, options)
end
@doc """
Retrieves information about the specified managed policy, including the
policy's default version and the total number of IAM users, groups, and
roles to which the policy is attached. To retrieve the list of the specific
users, groups, and roles that the policy is attached to, use the
`ListEntitiesForPolicy` API. This API returns metadata about the policy. To
retrieve the actual policy document for a specific version of the policy,
use `GetPolicyVersion`.
This API retrieves information about managed policies. To retrieve
information about an inline policy that is embedded with an IAM user,
group, or role, use the `GetUserPolicy`, `GetGroupPolicy`, or
`GetRolePolicy` API.
For more information about policies, see [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def get_policy(client, input, options \\ []) do
request(client, "GetPolicy", input, options)
end
@doc """
Retrieves information about the specified version of the specified managed
policy, including the policy document.
<note> Policies returned by this API are URL-encoded compliant with [RFC
3986](https://tools.ietf.org/html/rfc3986). You can use a URL decoding
method to convert the policy back to plain JSON text. For example, if you
use Java, you can use the `decode` method of the `java.net.URLDecoder`
utility class in the Java SDK. Other languages and SDKs provide similar
functionality.
</note> To list the available versions for a policy, use
`ListPolicyVersions`.
This API retrieves information about managed policies. To retrieve
information about an inline policy that is embedded in a user, group, or
role, use the `GetUserPolicy`, `GetGroupPolicy`, or `GetRolePolicy` API.
For more information about the types of policies, see [Managed Policies and
Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
For more information about managed policy versions, see [Versioning for
Managed
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html)
in the *IAM User Guide*.
"""
def get_policy_version(client, input, options \\ []) do
request(client, "GetPolicyVersion", input, options)
end
@doc """
Retrieves information about the specified role, including the role's path,
GUID, ARN, and the role's trust policy that grants permission to assume the
role. For more information about roles, see [Working with
Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html).
<note> Policies returned by this API are URL-encoded compliant with [RFC
3986](https://tools.ietf.org/html/rfc3986). You can use a URL decoding
method to convert the policy back to plain JSON text. For example, if you
use Java, you can use the `decode` method of the `java.net.URLDecoder`
utility class in the Java SDK. Other languages and SDKs provide similar
functionality.
</note>
"""
def get_role(client, input, options \\ []) do
request(client, "GetRole", input, options)
end
@doc """
Retrieves the specified inline policy document that is embedded with the
specified IAM role.
<note> Policies returned by this API are URL-encoded compliant with [RFC
3986](https://tools.ietf.org/html/rfc3986). You can use a URL decoding
method to convert the policy back to plain JSON text. For example, if you
use Java, you can use the `decode` method of the `java.net.URLDecoder`
utility class in the Java SDK. Other languages and SDKs provide similar
functionality.
</note> An IAM role can also have managed policies attached to it. To
retrieve a managed policy document that is attached to a role, use
`GetPolicy` to determine the policy's default version, then use
`GetPolicyVersion` to retrieve the policy document.
For more information about policies, see [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
For more information about roles, see [Using Roles to Delegate Permissions
and Federate
Identities](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html).
"""
def get_role_policy(client, input, options \\ []) do
request(client, "GetRolePolicy", input, options)
end
@doc """
Returns the SAML provider metadocument that was uploaded when the IAM SAML
provider resource object was created or updated.
<note> This operation requires [Signature Version
4](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html).
</note>
"""
def get_s_a_m_l_provider(client, input, options \\ []) do
request(client, "GetSAMLProvider", input, options)
end
@doc """
Retrieves the specified SSH public key, including metadata about the key.
The SSH public key retrieved by this operation is used only for
authenticating the associated IAM user to an AWS CodeCommit repository. For
more information about using SSH keys to authenticate to an AWS CodeCommit
repository, see [Set up AWS CodeCommit for SSH
Connections](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html)
in the *AWS CodeCommit User Guide*.
"""
def get_s_s_h_public_key(client, input, options \\ []) do
request(client, "GetSSHPublicKey", input, options)
end
@doc """
Retrieves information about the specified server certificate stored in IAM.
For more information about working with server certificates, see [Working
with Server
Certificates](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html)
in the *IAM User Guide*. This topic includes a list of AWS services that
can use the server certificates that you manage with IAM.
"""
def get_server_certificate(client, input, options \\ []) do
request(client, "GetServerCertificate", input, options)
end
@doc """
Retrieves a service last accessed report that was created using the
`GenerateServiceLastAccessedDetails` operation. You can use the `JobId`
parameter in `GetServiceLastAccessedDetails` to retrieve the status of your
report job. When the report is complete, you can retrieve the generated
report. The report includes a list of AWS services that the resource (user,
group, role, or managed policy) can access.
<note> Service last accessed data does not use other policy types when
determining whether a resource could access a service. These other policy
types include resource-based policies, access control lists, AWS
Organizations policies, IAM permissions boundaries, and AWS STS assume role
policies. It only applies permissions policy logic. For more about the
evaluation of policy types, see [Evaluating
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-basics)
in the *IAM User Guide*.
</note> For each service that the resource could access using permissions
policies, the operation returns details about the most recent access
attempt. If there was no attempt, the service is listed without details
about the most recent attempt to access the service. If the operation
fails, the `GetServiceLastAccessedDetails` operation returns the reason
that it failed.
The `GetServiceLastAccessedDetails` operation returns a list of services.
This list includes the number of entities that have attempted to access the
service and the date and time of the last attempt. It also returns the ARN
of the following entity, depending on the resource ARN that you used to
generate the report:
<ul> <li> **User** – Returns the user ARN that you used to generate the
report
</li> <li> **Group** – Returns the ARN of the group member (user) that last
attempted to access the service
</li> <li> **Role** – Returns the role ARN that you used to generate the
report
</li> <li> **Policy** – Returns the ARN of the user or role that last used
the policy to attempt to access the service
</li> </ul> By default, the list is sorted by service namespace.
If you specified `ACTION_LEVEL` granularity when you generated the report,
this operation returns service and action last accessed data. This includes
the most recent access attempt for each tracked action within a service.
Otherwise, this operation returns only service data.
For more information about service and action last accessed data, see
[Reducing Permissions Using Service Last Accessed
Data](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html)
in the *IAM User Guide*.
"""
def get_service_last_accessed_details(client, input, options \\ []) do
request(client, "GetServiceLastAccessedDetails", input, options)
end
@doc """
After you generate a group or policy report using the
`GenerateServiceLastAccessedDetails` operation, you can use the `JobId`
parameter in `GetServiceLastAccessedDetailsWithEntities`. This operation
retrieves the status of your report job and a list of entities that could
have used group or policy permissions to access the specified service.
<ul> <li> **Group** – For a group report, this operation returns a list of
users in the group that could have used the group’s policies in an attempt
to access the service.
</li> <li> **Policy** – For a policy report, this operation returns a list
of entities (users or roles) that could have used the policy in an attempt
to access the service.
</li> </ul> You can also use this operation for user or role reports to
retrieve details about those entities.
If the operation fails, the `GetServiceLastAccessedDetailsWithEntities`
operation returns the reason that it failed.
By default, the list of associated entities is sorted by date, with the
most recent access listed first.
"""
def get_service_last_accessed_details_with_entities(client, input, options \\ []) do
request(client, "GetServiceLastAccessedDetailsWithEntities", input, options)
end
@doc """
Retrieves the status of your service-linked role deletion. After you use
the `DeleteServiceLinkedRole` API operation to submit a service-linked role
for deletion, you can use the `DeletionTaskId` parameter in
`GetServiceLinkedRoleDeletionStatus` to check the status of the deletion.
If the deletion fails, this operation returns the reason that it failed, if
that information is returned by the service.
"""
def get_service_linked_role_deletion_status(client, input, options \\ []) do
request(client, "GetServiceLinkedRoleDeletionStatus", input, options)
end
@doc """
Retrieves information about the specified IAM user, including the user's
creation date, path, unique ID, and ARN.
If you do not specify a user name, IAM determines the user name implicitly
based on the AWS access key ID used to sign the request to this API.
"""
def get_user(client, input, options \\ []) do
request(client, "GetUser", input, options)
end
@doc """
Retrieves the specified inline policy document that is embedded in the
specified IAM user.
<note> Policies returned by this API are URL-encoded compliant with [RFC
3986](https://tools.ietf.org/html/rfc3986). You can use a URL decoding
method to convert the policy back to plain JSON text. For example, if you
use Java, you can use the `decode` method of the `java.net.URLDecoder`
utility class in the Java SDK. Other languages and SDKs provide similar
functionality.
</note> An IAM user can also have managed policies attached to it. To
retrieve a managed policy document that is attached to a user, use
`GetPolicy` to determine the policy's default version. Then use
`GetPolicyVersion` to retrieve the policy document.
For more information about policies, see [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def get_user_policy(client, input, options \\ []) do
request(client, "GetUserPolicy", input, options)
end
@doc """
Returns information about the access key IDs associated with the specified
IAM user. If there is none, the operation returns an empty list.
Although each user is limited to a small number of keys, you can still
paginate the results using the `MaxItems` and `Marker` parameters.
If the `UserName` field is not specified, the user name is determined
implicitly based on the AWS access key ID used to sign the request. This
operation works for access keys under the AWS account. Consequently, you
can use this operation to manage AWS account root user credentials even if
the AWS account has no associated users.
<note> To ensure the security of your AWS account, the secret access key is
accessible only during key and user creation.
</note>
"""
def list_access_keys(client, input, options \\ []) do
request(client, "ListAccessKeys", input, options)
end
@doc """
Lists the account alias associated with the AWS account (Note: you can have
only one). For information about using an AWS account alias, see [Using an
Alias for Your AWS Account
ID](https://docs.aws.amazon.com/IAM/latest/UserGuide/AccountAlias.html) in
the *IAM User Guide*.
"""
def list_account_aliases(client, input, options \\ []) do
request(client, "ListAccountAliases", input, options)
end
@doc """
Lists all managed policies that are attached to the specified IAM group.
An IAM group can also have inline policies embedded with it. To list the
inline policies for a group, use the `ListGroupPolicies` API. For
information about policies, see [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
You can paginate the results using the `MaxItems` and `Marker` parameters.
You can use the `PathPrefix` parameter to limit the list of policies to
only those matching the specified path prefix. If there are no policies
attached to the specified group (or none that match the specified path
prefix), the operation returns an empty list.
"""
def list_attached_group_policies(client, input, options \\ []) do
request(client, "ListAttachedGroupPolicies", input, options)
end
@doc """
Lists all managed policies that are attached to the specified IAM role.
An IAM role can also have inline policies embedded with it. To list the
inline policies for a role, use the `ListRolePolicies` API. For information
about policies, see [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
You can paginate the results using the `MaxItems` and `Marker` parameters.
You can use the `PathPrefix` parameter to limit the list of policies to
only those matching the specified path prefix. If there are no policies
attached to the specified role (or none that match the specified path
prefix), the operation returns an empty list.
"""
def list_attached_role_policies(client, input, options \\ []) do
request(client, "ListAttachedRolePolicies", input, options)
end
@doc """
Lists all managed policies that are attached to the specified IAM user.
An IAM user can also have inline policies embedded with it. To list the
inline policies for a user, use the `ListUserPolicies` API. For information
about policies, see [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
You can paginate the results using the `MaxItems` and `Marker` parameters.
You can use the `PathPrefix` parameter to limit the list of policies to
only those matching the specified path prefix. If there are no policies
attached to the specified group (or none that match the specified path
prefix), the operation returns an empty list.
"""
def list_attached_user_policies(client, input, options \\ []) do
request(client, "ListAttachedUserPolicies", input, options)
end
@doc """
Lists all IAM users, groups, and roles that the specified managed policy is
attached to.
You can use the optional `EntityFilter` parameter to limit the results to a
particular type of entity (users, groups, or roles). For example, to list
only the roles that are attached to the specified policy, set
`EntityFilter` to `Role`.
You can paginate the results using the `MaxItems` and `Marker` parameters.
"""
def list_entities_for_policy(client, input, options \\ []) do
request(client, "ListEntitiesForPolicy", input, options)
end
@doc """
Lists the names of the inline policies that are embedded in the specified
IAM group.
An IAM group can also have managed policies attached to it. To list the
managed policies that are attached to a group, use
`ListAttachedGroupPolicies`. For more information about policies, see
[Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
You can paginate the results using the `MaxItems` and `Marker` parameters.
If there are no inline policies embedded with the specified group, the
operation returns an empty list.
"""
def list_group_policies(client, input, options \\ []) do
request(client, "ListGroupPolicies", input, options)
end
@doc """
Lists the IAM groups that have the specified path prefix.
You can paginate the results using the `MaxItems` and `Marker` parameters.
"""
def list_groups(client, input, options \\ []) do
request(client, "ListGroups", input, options)
end
@doc """
Lists the IAM groups that the specified IAM user belongs to.
You can paginate the results using the `MaxItems` and `Marker` parameters.
"""
def list_groups_for_user(client, input, options \\ []) do
request(client, "ListGroupsForUser", input, options)
end
@doc """
Lists the instance profiles that have the specified path prefix. If there
are none, the operation returns an empty list. For more information about
instance profiles, go to [About Instance
Profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html).
You can paginate the results using the `MaxItems` and `Marker` parameters.
"""
def list_instance_profiles(client, input, options \\ []) do
request(client, "ListInstanceProfiles", input, options)
end
@doc """
Lists the instance profiles that have the specified associated IAM role. If
there are none, the operation returns an empty list. For more information
about instance profiles, go to [About Instance
Profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html).
You can paginate the results using the `MaxItems` and `Marker` parameters.
"""
def list_instance_profiles_for_role(client, input, options \\ []) do
request(client, "ListInstanceProfilesForRole", input, options)
end
@doc """
Lists the MFA devices for an IAM user. If the request includes a IAM user
name, then this operation lists all the MFA devices associated with the
specified user. If you do not specify a user name, IAM determines the user
name implicitly based on the AWS access key ID signing the request for this
API.
You can paginate the results using the `MaxItems` and `Marker` parameters.
"""
def list_m_f_a_devices(client, input, options \\ []) do
request(client, "ListMFADevices", input, options)
end
@doc """
Lists information about the IAM OpenID Connect (OIDC) provider resource
objects defined in the AWS account.
"""
def list_open_i_d_connect_providers(client, input, options \\ []) do
request(client, "ListOpenIDConnectProviders", input, options)
end
@doc """
Lists all the managed policies that are available in your AWS account,
including your own customer-defined managed policies and all AWS managed
policies.
You can filter the list of policies that is returned using the optional
`OnlyAttached`, `Scope`, and `PathPrefix` parameters. For example, to list
only the customer managed policies in your AWS account, set `Scope` to
`Local`. To list only AWS managed policies, set `Scope` to `AWS`.
You can paginate the results using the `MaxItems` and `Marker` parameters.
For more information about managed policies, see [Managed Policies and
Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def list_policies(client, input, options \\ []) do
request(client, "ListPolicies", input, options)
end
@doc """
Retrieves a list of policies that the IAM identity (user, group, or role)
can use to access each specified service.
<note> This operation does not use other policy types when determining
whether a resource could access a service. These other policy types include
resource-based policies, access control lists, AWS Organizations policies,
IAM permissions boundaries, and AWS STS assume role policies. It only
applies permissions policy logic. For more about the evaluation of policy
types, see [Evaluating
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-basics)
in the *IAM User Guide*.
</note> The list of policies returned by the operation depends on the ARN
of the identity that you provide.
<ul> <li> **User** – The list of policies includes the managed and inline
policies that are attached to the user directly. The list also includes any
additional managed and inline policies that are attached to the group to
which the user belongs.
</li> <li> **Group** – The list of policies includes only the managed and
inline policies that are attached to the group directly. Policies that are
attached to the group’s user are not included.
</li> <li> **Role** – The list of policies includes only the managed and
inline policies that are attached to the role.
</li> </ul> For each managed policy, this operation returns the ARN and
policy name. For each inline policy, it returns the policy name and the
entity to which it is attached. Inline policies do not have an ARN. For
more information about these policy types, see [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html)
in the *IAM User Guide*.
Policies that are attached to users and roles as permissions boundaries are
not returned. To view which managed policy is currently used to set the
permissions boundary for a user or role, use the `GetUser` or `GetRole`
operations.
"""
def list_policies_granting_service_access(client, input, options \\ []) do
request(client, "ListPoliciesGrantingServiceAccess", input, options)
end
@doc """
Lists information about the versions of the specified managed policy,
including the version that is currently set as the policy's default
version.
For more information about managed policies, see [Managed Policies and
Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def list_policy_versions(client, input, options \\ []) do
request(client, "ListPolicyVersions", input, options)
end
@doc """
Lists the names of the inline policies that are embedded in the specified
IAM role.
An IAM role can also have managed policies attached to it. To list the
managed policies that are attached to a role, use
`ListAttachedRolePolicies`. For more information about policies, see
[Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
You can paginate the results using the `MaxItems` and `Marker` parameters.
If there are no inline policies embedded with the specified role, the
operation returns an empty list.
"""
def list_role_policies(client, input, options \\ []) do
request(client, "ListRolePolicies", input, options)
end
@doc """
Lists the tags that are attached to the specified role. The returned list
of tags is sorted by tag key. For more information about tagging, see
[Tagging IAM
Identities](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)
in the *IAM User Guide*.
"""
def list_role_tags(client, input, options \\ []) do
request(client, "ListRoleTags", input, options)
end
@doc """
Lists the IAM roles that have the specified path prefix. If there are none,
the operation returns an empty list. For more information about roles, go
to [Working with
Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html).
You can paginate the results using the `MaxItems` and `Marker` parameters.
"""
def list_roles(client, input, options \\ []) do
request(client, "ListRoles", input, options)
end
@doc """
Lists the SAML provider resource objects defined in IAM in the account.
<note> This operation requires [Signature Version
4](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html).
</note>
"""
def list_s_a_m_l_providers(client, input, options \\ []) do
request(client, "ListSAMLProviders", input, options)
end
@doc """
Returns information about the SSH public keys associated with the specified
IAM user. If none exists, the operation returns an empty list.
The SSH public keys returned by this operation are used only for
authenticating the IAM user to an AWS CodeCommit repository. For more
information about using SSH keys to authenticate to an AWS CodeCommit
repository, see [Set up AWS CodeCommit for SSH
Connections](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html)
in the *AWS CodeCommit User Guide*.
Although each user is limited to a small number of keys, you can still
paginate the results using the `MaxItems` and `Marker` parameters.
"""
def list_s_s_h_public_keys(client, input, options \\ []) do
request(client, "ListSSHPublicKeys", input, options)
end
@doc """
Lists the server certificates stored in IAM that have the specified path
prefix. If none exist, the operation returns an empty list.
You can paginate the results using the `MaxItems` and `Marker` parameters.
For more information about working with server certificates, see [Working
with Server
Certificates](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html)
in the *IAM User Guide*. This topic also includes a list of AWS services
that can use the server certificates that you manage with IAM.
"""
def list_server_certificates(client, input, options \\ []) do
request(client, "ListServerCertificates", input, options)
end
@doc """
Returns information about the service-specific credentials associated with
the specified IAM user. If none exists, the operation returns an empty
list. The service-specific credentials returned by this operation are used
only for authenticating the IAM user to a specific service. For more
information about using service-specific credentials to authenticate to an
AWS service, see [Set Up service-specific
credentials](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html)
in the AWS CodeCommit User Guide.
"""
def list_service_specific_credentials(client, input, options \\ []) do
request(client, "ListServiceSpecificCredentials", input, options)
end
@doc """
Returns information about the signing certificates associated with the
specified IAM user. If none exists, the operation returns an empty list.
Although each user is limited to a small number of signing certificates,
you can still paginate the results using the `MaxItems` and `Marker`
parameters.
If the `UserName` field is not specified, the user name is determined
implicitly based on the AWS access key ID used to sign the request for this
API. This operation works for access keys under the AWS account.
Consequently, you can use this operation to manage AWS account root user
credentials even if the AWS account has no associated users.
"""
def list_signing_certificates(client, input, options \\ []) do
request(client, "ListSigningCertificates", input, options)
end
@doc """
Lists the names of the inline policies embedded in the specified IAM user.
An IAM user can also have managed policies attached to it. To list the
managed policies that are attached to a user, use
`ListAttachedUserPolicies`. For more information about policies, see
[Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
You can paginate the results using the `MaxItems` and `Marker` parameters.
If there are no inline policies embedded with the specified user, the
operation returns an empty list.
"""
def list_user_policies(client, input, options \\ []) do
request(client, "ListUserPolicies", input, options)
end
@doc """
Lists the tags that are attached to the specified user. The returned list
of tags is sorted by tag key. For more information about tagging, see
[Tagging IAM
Identities](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)
in the *IAM User Guide*.
"""
def list_user_tags(client, input, options \\ []) do
request(client, "ListUserTags", input, options)
end
@doc """
Lists the IAM users that have the specified path prefix. If no path prefix
is specified, the operation returns all users in the AWS account. If there
are none, the operation returns an empty list.
You can paginate the results using the `MaxItems` and `Marker` parameters.
"""
def list_users(client, input, options \\ []) do
request(client, "ListUsers", input, options)
end
@doc """
Lists the virtual MFA devices defined in the AWS account by assignment
status. If you do not specify an assignment status, the operation returns a
list of all virtual MFA devices. Assignment status can be `Assigned`,
`Unassigned`, or `Any`.
You can paginate the results using the `MaxItems` and `Marker` parameters.
"""
def list_virtual_m_f_a_devices(client, input, options \\ []) do
request(client, "ListVirtualMFADevices", input, options)
end
@doc """
Adds or updates an inline policy document that is embedded in the specified
IAM group.
A user can also have managed policies attached to it. To attach a managed
policy to a group, use `AttachGroupPolicy`. To create a new managed policy,
use `CreatePolicy`. For information about policies, see [Managed Policies
and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
For information about limits on the number of inline policies that you can
embed in a group, see [Limitations on IAM
Entities](https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html)
in the *IAM User Guide*.
<note> Because policy documents can be large, you should use POST rather
than GET when calling `PutGroupPolicy`. For general information about using
the Query API with IAM, go to [Making Query
Requests](https://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html)
in the *IAM User Guide*.
</note>
"""
def put_group_policy(client, input, options \\ []) do
request(client, "PutGroupPolicy", input, options)
end
@doc """
Adds or updates the policy that is specified as the IAM role's permissions
boundary. You can use an AWS managed policy or a customer managed policy to
set the boundary for a role. Use the boundary to control the maximum
permissions that the role can have. Setting a permissions boundary is an
advanced feature that can affect the permissions for the role.
You cannot set the boundary for a service-linked role.
<important> Policies used as permissions boundaries do not provide
permissions. You must also attach a permissions policy to the role. To
learn how the effective permissions for a role are evaluated, see [IAM JSON
Policy Evaluation
Logic](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html)
in the IAM User Guide.
</important>
"""
def put_role_permissions_boundary(client, input, options \\ []) do
request(client, "PutRolePermissionsBoundary", input, options)
end
@doc """
Adds or updates an inline policy document that is embedded in the specified
IAM role.
When you embed an inline policy in a role, the inline policy is used as
part of the role's access (permissions) policy. The role's trust policy is
created at the same time as the role, using `CreateRole`. You can update a
role's trust policy using `UpdateAssumeRolePolicy`. For more information
about IAM roles, go to [Using Roles to Delegate Permissions and Federate
Identities](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html).
A role can also have a managed policy attached to it. To attach a managed
policy to a role, use `AttachRolePolicy`. To create a new managed policy,
use `CreatePolicy`. For information about policies, see [Managed Policies
and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
For information about limits on the number of inline policies that you can
embed with a role, see [Limitations on IAM
Entities](https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html)
in the *IAM User Guide*.
<note> Because policy documents can be large, you should use POST rather
than GET when calling `PutRolePolicy`. For general information about using
the Query API with IAM, go to [Making Query
Requests](https://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html)
in the *IAM User Guide*.
</note>
"""
def put_role_policy(client, input, options \\ []) do
request(client, "PutRolePolicy", input, options)
end
@doc """
Adds or updates the policy that is specified as the IAM user's permissions
boundary. You can use an AWS managed policy or a customer managed policy to
set the boundary for a user. Use the boundary to control the maximum
permissions that the user can have. Setting a permissions boundary is an
advanced feature that can affect the permissions for the user.
<important> Policies that are used as permissions boundaries do not provide
permissions. You must also attach a permissions policy to the user. To
learn how the effective permissions for a user are evaluated, see [IAM JSON
Policy Evaluation
Logic](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html)
in the IAM User Guide.
</important>
"""
def put_user_permissions_boundary(client, input, options \\ []) do
request(client, "PutUserPermissionsBoundary", input, options)
end
@doc """
Adds or updates an inline policy document that is embedded in the specified
IAM user.
An IAM user can also have a managed policy attached to it. To attach a
managed policy to a user, use `AttachUserPolicy`. To create a new managed
policy, use `CreatePolicy`. For information about policies, see [Managed
Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
For information about limits on the number of inline policies that you can
embed in a user, see [Limitations on IAM
Entities](https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html)
in the *IAM User Guide*.
<note> Because policy documents can be large, you should use POST rather
than GET when calling `PutUserPolicy`. For general information about using
the Query API with IAM, go to [Making Query
Requests](https://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html)
in the *IAM User Guide*.
</note>
"""
def put_user_policy(client, input, options \\ []) do
request(client, "PutUserPolicy", input, options)
end
@doc """
Removes the specified client ID (also known as audience) from the list of
client IDs registered for the specified IAM OpenID Connect (OIDC) provider
resource object.
This operation is idempotent; it does not fail or return an error if you
try to remove a client ID that does not exist.
"""
def remove_client_i_d_from_open_i_d_connect_provider(client, input, options \\ []) do
request(client, "RemoveClientIDFromOpenIDConnectProvider", input, options)
end
@doc """
Removes the specified IAM role from the specified EC2 instance profile.
<important> Make sure that you do not have any Amazon EC2 instances running
with the role you are about to remove from the instance profile. Removing a
role from an instance profile that is associated with a running instance
might break any applications running on the instance.
</important> For more information about IAM roles, go to [Working with
Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html).
For more information about instance profiles, go to [About Instance
Profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html).
"""
def remove_role_from_instance_profile(client, input, options \\ []) do
request(client, "RemoveRoleFromInstanceProfile", input, options)
end
@doc """
Removes the specified user from the specified group.
"""
def remove_user_from_group(client, input, options \\ []) do
request(client, "RemoveUserFromGroup", input, options)
end
@doc """
Resets the password for a service-specific credential. The new password is
AWS generated and cryptographically strong. It cannot be configured by the
user. Resetting the password immediately invalidates the previous password
associated with this user.
"""
def reset_service_specific_credential(client, input, options \\ []) do
request(client, "ResetServiceSpecificCredential", input, options)
end
@doc """
Synchronizes the specified MFA device with its IAM resource object on the
AWS servers.
For more information about creating and working with virtual MFA devices,
go to [Using a Virtual MFA
Device](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_VirtualMFA.html)
in the *IAM User Guide*.
"""
def resync_m_f_a_device(client, input, options \\ []) do
request(client, "ResyncMFADevice", input, options)
end
@doc """
Sets the specified version of the specified policy as the policy's default
(operative) version.
This operation affects all users, groups, and roles that the policy is
attached to. To list the users, groups, and roles that the policy is
attached to, use the `ListEntitiesForPolicy` API.
For information about managed policies, see [Managed Policies and Inline
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html)
in the *IAM User Guide*.
"""
def set_default_policy_version(client, input, options \\ []) do
request(client, "SetDefaultPolicyVersion", input, options)
end
@doc """
Sets the specified version of the global endpoint token as the token
version used for the AWS account.
By default, AWS Security Token Service (STS) is available as a global
service, and all STS requests go to a single endpoint at
`https://sts.amazonaws.com`. AWS recommends using Regional STS endpoints to
reduce latency, build in redundancy, and increase session token
availability. For information about Regional endpoints for STS, see [AWS
Regions and
Endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#sts_region)
in the *AWS General Reference*.
If you make an STS call to the global endpoint, the resulting session
tokens might be valid in some Regions but not others. It depends on the
version that is set in this operation. Version 1 tokens are valid only in
AWS Regions that are available by default. These tokens do not work in
manually enabled Regions, such as Asia Pacific (Hong Kong). Version 2
tokens are valid in all Regions. However, version 2 tokens are longer and
might affect systems where you temporarily store tokens. For information,
see [Activating and Deactivating STS in an AWS
Region](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html)
in the *IAM User Guide*.
To view the current session token version, see the
`GlobalEndpointTokenVersion` entry in the response of the
`GetAccountSummary` operation.
"""
def set_security_token_service_preferences(client, input, options \\ []) do
request(client, "SetSecurityTokenServicePreferences", input, options)
end
@doc """
Simulate how a set of IAM policies and optionally a resource-based policy
works with a list of API operations and AWS resources to determine the
policies' effective permissions. The policies are provided as strings.
The simulation does not perform the API operations; it only checks the
authorization to determine if the simulated policies allow or deny the
operations.
If you want to simulate existing policies that are attached to an IAM user,
group, or role, use `SimulatePrincipalPolicy` instead.
Context keys are variables that are maintained by AWS and its services and
which provide details about the context of an API query request. You can
use the `Condition` element of an IAM policy to evaluate context keys. To
get the list of context keys that the policies require for correct
simulation, use `GetContextKeysForCustomPolicy`.
If the output is long, you can use `MaxItems` and `Marker` parameters to
paginate the results.
"""
def simulate_custom_policy(client, input, options \\ []) do
request(client, "SimulateCustomPolicy", input, options)
end
@doc """
Simulate how a set of IAM policies attached to an IAM entity works with a
list of API operations and AWS resources to determine the policies'
effective permissions. The entity can be an IAM user, group, or role. If
you specify a user, then the simulation also includes all of the policies
that are attached to groups that the user belongs to.
You can optionally include a list of one or more additional policies
specified as strings to include in the simulation. If you want to simulate
only policies specified as strings, use `SimulateCustomPolicy` instead.
You can also optionally include one resource-based policy to be evaluated
with each of the resources included in the simulation.
The simulation does not perform the API operations; it only checks the
authorization to determine if the simulated policies allow or deny the
operations.
**Note:** This API discloses information about the permissions granted to
other users. If you do not want users to see other user's permissions, then
consider allowing them to use `SimulateCustomPolicy` instead.
Context keys are variables maintained by AWS and its services that provide
details about the context of an API query request. You can use the
`Condition` element of an IAM policy to evaluate context keys. To get the
list of context keys that the policies require for correct simulation, use
`GetContextKeysForPrincipalPolicy`.
If the output is long, you can use the `MaxItems` and `Marker` parameters
to paginate the results.
"""
def simulate_principal_policy(client, input, options \\ []) do
request(client, "SimulatePrincipalPolicy", input, options)
end
@doc """
Adds one or more tags to an IAM role. The role can be a regular role or a
service-linked role. If a tag with the same key name already exists, then
that tag is overwritten with the new value.
A tag consists of a key name and an associated value. By assigning tags to
your resources, you can do the following:
<ul> <li> **Administrative grouping and discovery** - Attach tags to
resources to aid in organization and search. For example, you could search
for all resources with the key name *Project* and the value
*MyImportantProject*. Or search for all resources with the key name *Cost
Center* and the value *41200*.
</li> <li> **Access control** - Reference tags in IAM user-based and
resource-based policies. You can use tags to restrict access to only an IAM
user or role that has a specified tag attached. You can also restrict
access to only those resources that have a certain tag attached. For
examples of policies that show how to use tags to control access, see
[Control Access Using IAM
Tags](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html) in
the *IAM User Guide*.
</li> <li> **Cost allocation** - Use tags to help track which individuals
and teams are using which AWS resources.
</li> </ul> <note> <ul> <li> Make sure that you have no invalid tags and
that you do not exceed the allowed number of tags per role. In either case,
the entire request fails and *no* tags are added to the role.
</li> <li> AWS always interprets the tag `Value` as a single string. If you
need to store an array, you can store comma-separated values in the string.
However, you must interpret the value in your code.
</li> </ul> </note> For more information about tagging, see [Tagging IAM
Identities](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)
in the *IAM User Guide*.
"""
def tag_role(client, input, options \\ []) do
request(client, "TagRole", input, options)
end
@doc """
Adds one or more tags to an IAM user. If a tag with the same key name
already exists, then that tag is overwritten with the new value.
A tag consists of a key name and an associated value. By assigning tags to
your resources, you can do the following:
<ul> <li> **Administrative grouping and discovery** - Attach tags to
resources to aid in organization and search. For example, you could search
for all resources with the key name *Project* and the value
*MyImportantProject*. Or search for all resources with the key name *Cost
Center* and the value *41200*.
</li> <li> **Access control** - Reference tags in IAM user-based and
resource-based policies. You can use tags to restrict access to only an IAM
requesting user or to a role that has a specified tag attached. You can
also restrict access to only those resources that have a certain tag
attached. For examples of policies that show how to use tags to control
access, see [Control Access Using IAM
Tags](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html) in
the *IAM User Guide*.
</li> <li> **Cost allocation** - Use tags to help track which individuals
and teams are using which AWS resources.
</li> </ul> <note> <ul> <li> Make sure that you have no invalid tags and
that you do not exceed the allowed number of tags per role. In either case,
the entire request fails and *no* tags are added to the role.
</li> <li> AWS always interprets the tag `Value` as a single string. If you
need to store an array, you can store comma-separated values in the string.
However, you must interpret the value in your code.
</li> </ul> </note> For more information about tagging, see [Tagging IAM
Identities](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)
in the *IAM User Guide*.
"""
def tag_user(client, input, options \\ []) do
request(client, "TagUser", input, options)
end
@doc """
Removes the specified tags from the role. For more information about
tagging, see [Tagging IAM
Identities](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)
in the *IAM User Guide*.
"""
def untag_role(client, input, options \\ []) do
request(client, "UntagRole", input, options)
end
@doc """
Removes the specified tags from the user. For more information about
tagging, see [Tagging IAM
Identities](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)
in the *IAM User Guide*.
"""
def untag_user(client, input, options \\ []) do
request(client, "UntagUser", input, options)
end
@doc """
Changes the status of the specified access key from Active to Inactive, or
vice versa. This operation can be used to disable a user's key as part of a
key rotation workflow.
If the `UserName` is not specified, the user name is determined implicitly
based on the AWS access key ID used to sign the request. This operation
works for access keys under the AWS account. Consequently, you can use this
operation to manage AWS account root user credentials even if the AWS
account has no associated users.
For information about rotating keys, see [Managing Keys and
Certificates](https://docs.aws.amazon.com/IAM/latest/UserGuide/ManagingCredentials.html)
in the *IAM User Guide*.
"""
def update_access_key(client, input, options \\ []) do
request(client, "UpdateAccessKey", input, options)
end
@doc """
Updates the password policy settings for the AWS account.
<note> <ul> <li> This operation does not support partial updates. No
parameters are required, but if you do not specify a parameter, that
parameter's value reverts to its default value. See the **Request
Parameters** section for each parameter's default value. Also note that
some parameters do not allow the default parameter to be explicitly set.
Instead, to invoke the default value, do not include that parameter when
you invoke the operation.
</li> </ul> </note> For more information about using a password policy, see
[Managing an IAM Password
Policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingPasswordPolicies.html)
in the *IAM User Guide*.
"""
def update_account_password_policy(client, input, options \\ []) do
request(client, "UpdateAccountPasswordPolicy", input, options)
end
@doc """
Updates the policy that grants an IAM entity permission to assume a role.
This is typically referred to as the "role trust policy". For more
information about roles, go to [Using Roles to Delegate Permissions and
Federate
Identities](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html).
"""
def update_assume_role_policy(client, input, options \\ []) do
request(client, "UpdateAssumeRolePolicy", input, options)
end
@doc """
Updates the name and/or the path of the specified IAM group.
<important> You should understand the implications of changing a group's
path or name. For more information, see [Renaming Users and
Groups](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_WorkingWithGroupsAndUsers.html)
in the *IAM User Guide*.
</important> <note> The person making the request (the principal), must
have permission to change the role group with the old name and the new
name. For example, to change the group named `Managers` to `MGRs`, the
principal must have a policy that allows them to update both groups. If the
principal has permission to update the `Managers` group, but not the `MGRs`
group, then the update fails. For more information about permissions, see
[Access
Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html).
</note>
"""
def update_group(client, input, options \\ []) do
request(client, "UpdateGroup", input, options)
end
@doc """
Changes the password for the specified IAM user.
IAM users can change their own passwords by calling `ChangePassword`. For
more information about modifying passwords, see [Managing
Passwords](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingLogins.html)
in the *IAM User Guide*.
"""
def update_login_profile(client, input, options \\ []) do
request(client, "UpdateLoginProfile", input, options)
end
@doc """
Replaces the existing list of server certificate thumbprints associated
with an OpenID Connect (OIDC) provider resource object with a new list of
thumbprints.
The list that you pass with this operation completely replaces the existing
list of thumbprints. (The lists are not merged.)
Typically, you need to update a thumbprint only when the identity
provider's certificate changes, which occurs rarely. However, if the
provider's certificate *does* change, any attempt to assume an IAM role
that specifies the OIDC provider as a principal fails until the certificate
thumbprint is updated.
<note> Trust for the OIDC provider is derived from the provider's
certificate and is validated by the thumbprint. Therefore, it is best to
limit access to the `UpdateOpenIDConnectProviderThumbprint` operation to
highly privileged users.
</note>
"""
def update_open_i_d_connect_provider_thumbprint(client, input, options \\ []) do
request(client, "UpdateOpenIDConnectProviderThumbprint", input, options)
end
@doc """
Updates the description or maximum session duration setting of a role.
"""
def update_role(client, input, options \\ []) do
request(client, "UpdateRole", input, options)
end
@doc """
Use `UpdateRole` instead.
Modifies only the description of a role. This operation performs the same
function as the `Description` parameter in the `UpdateRole` operation.
"""
def update_role_description(client, input, options \\ []) do
request(client, "UpdateRoleDescription", input, options)
end
@doc """
Updates the metadata document for an existing SAML provider resource
object.
<note> This operation requires [Signature Version
4](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html).
</note>
"""
def update_s_a_m_l_provider(client, input, options \\ []) do
request(client, "UpdateSAMLProvider", input, options)
end
@doc """
Sets the status of an IAM user's SSH public key to active or inactive. SSH
public keys that are inactive cannot be used for authentication. This
operation can be used to disable a user's SSH public key as part of a key
rotation work flow.
The SSH public key affected by this operation is used only for
authenticating the associated IAM user to an AWS CodeCommit repository. For
more information about using SSH keys to authenticate to an AWS CodeCommit
repository, see [Set up AWS CodeCommit for SSH
Connections](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html)
in the *AWS CodeCommit User Guide*.
"""
def update_s_s_h_public_key(client, input, options \\ []) do
request(client, "UpdateSSHPublicKey", input, options)
end
@doc """
Updates the name and/or the path of the specified server certificate stored
in IAM.
For more information about working with server certificates, see [Working
with Server
Certificates](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html)
in the *IAM User Guide*. This topic also includes a list of AWS services
that can use the server certificates that you manage with IAM.
<important> You should understand the implications of changing a server
certificate's path or name. For more information, see [Renaming a Server
Certificate](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs_manage.html#RenamingServerCerts)
in the *IAM User Guide*.
</important> <note> The person making the request (the principal), must
have permission to change the server certificate with the old name and the
new name. For example, to change the certificate named `ProductionCert` to
`ProdCert`, the principal must have a policy that allows them to update
both certificates. If the principal has permission to update the
`ProductionCert` group, but not the `ProdCert` certificate, then the update
fails. For more information about permissions, see [Access
Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html)
in the *IAM User Guide*.
</note>
"""
def update_server_certificate(client, input, options \\ []) do
request(client, "UpdateServerCertificate", input, options)
end
@doc """
Sets the status of a service-specific credential to `Active` or `Inactive`.
Service-specific credentials that are inactive cannot be used for
authentication to the service. This operation can be used to disable a
user's service-specific credential as part of a credential rotation work
flow.
"""
def update_service_specific_credential(client, input, options \\ []) do
request(client, "UpdateServiceSpecificCredential", input, options)
end
@doc """
Changes the status of the specified user signing certificate from active to
disabled, or vice versa. This operation can be used to disable an IAM
user's signing certificate as part of a certificate rotation work flow.
If the `UserName` field is not specified, the user name is determined
implicitly based on the AWS access key ID used to sign the request. This
operation works for access keys under the AWS account. Consequently, you
can use this operation to manage AWS account root user credentials even if
the AWS account has no associated users.
"""
def update_signing_certificate(client, input, options \\ []) do
request(client, "UpdateSigningCertificate", input, options)
end
@doc """
Updates the name and/or the path of the specified IAM user.
<important> You should understand the implications of changing an IAM
user's path or name. For more information, see [Renaming an IAM
User](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_manage.html#id_users_renaming)
and [Renaming an IAM
Group](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage_rename.html)
in the *IAM User Guide*.
</important> <note> To change a user name, the requester must have
appropriate permissions on both the source object and the target object.
For example, to change Bob to Robert, the entity making the request must
have permission on Bob and Robert, or must have permission on all (*). For
more information about permissions, see [Permissions and
Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/PermissionsAndPolicies.html).
</note>
"""
def update_user(client, input, options \\ []) do
request(client, "UpdateUser", input, options)
end
@doc """
Uploads an SSH public key and associates it with the specified IAM user.
The SSH public key uploaded by this operation can be used only for
authenticating the associated IAM user to an AWS CodeCommit repository. For
more information about using SSH keys to authenticate to an AWS CodeCommit
repository, see [Set up AWS CodeCommit for SSH
Connections](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html)
in the *AWS CodeCommit User Guide*.
"""
def upload_s_s_h_public_key(client, input, options \\ []) do
request(client, "UploadSSHPublicKey", input, options)
end
@doc """
Uploads a server certificate entity for the AWS account. The server
certificate entity includes a public key certificate, a private key, and an
optional certificate chain, which should all be PEM-encoded.
We recommend that you use [AWS Certificate
Manager](https://docs.aws.amazon.com/acm/) to provision, manage, and deploy
your server certificates. With ACM you can request a certificate, deploy it
to AWS resources, and let ACM handle certificate renewals for you.
Certificates provided by ACM are free. For more information about using
ACM, see the [AWS Certificate Manager User
Guide](https://docs.aws.amazon.com/acm/latest/userguide/).
For more information about working with server certificates, see [Working
with Server
Certificates](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html)
in the *IAM User Guide*. This topic includes a list of AWS services that
can use the server certificates that you manage with IAM.
For information about the number of server certificates you can upload, see
[Limitations on IAM Entities and
Objects](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html)
in the *IAM User Guide*.
<note> Because the body of the public key certificate, private key, and the
certificate chain can be large, you should use POST rather than GET when
calling `UploadServerCertificate`. For information about setting up
signatures and authorization through the API, go to [Signing AWS API
Requests](https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html)
in the *AWS General Reference*. For general information about using the
Query API with IAM, go to [Calling the API by Making HTTP Query
Requests](https://docs.aws.amazon.com/IAM/latest/UserGuide/programming.html)
in the *IAM User Guide*.
</note>
"""
def upload_server_certificate(client, input, options \\ []) do
request(client, "UploadServerCertificate", input, options)
end
@doc """
Uploads an X.509 signing certificate and associates it with the specified
IAM user. Some AWS services use X.509 signing certificates to validate
requests that are signed with a corresponding private key. When you upload
the certificate, its default status is `Active`.
If the `UserName` is not specified, the IAM user name is determined
implicitly based on the AWS access key ID used to sign the request. This
operation works for access keys under the AWS account. Consequently, you
can use this operation to manage AWS account root user credentials even if
the AWS account has no associated users.
<note> Because the body of an X.509 certificate can be large, you should
use POST rather than GET when calling `UploadSigningCertificate`. For
information about setting up signatures and authorization through the API,
go to [Signing AWS API
Requests](https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html)
in the *AWS General Reference*. For general information about using the
Query API with IAM, go to [Making Query
Requests](https://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html)
in the *IAM User Guide*.
</note>
"""
def upload_signing_certificate(client, input, options \\ []) do
request(client, "UploadSigningCertificate", input, options)
end
@spec request(AWS.Client.t(), binary(), map(), list()) ::
{:ok, map() | nil, map()}
| {:error, term()}
defp request(client, action, input, options) do
client = %{client | service: "iam",
region: "us-east-1"}
host = build_host("iam", client)
url = build_url(host, client)
headers = [
{"Host", host},
{"Content-Type", "application/x-www-form-urlencoded"}
]
input = Map.merge(input, %{"Action" => action, "Version" => "2010-05-08"})
payload = encode!(client, input)
headers = AWS.Request.sign_v4(client, "POST", url, headers, payload)
post(client, url, payload, headers, options)
end
defp post(client, url, payload, headers, options) do
case AWS.Client.request(client, :post, url, payload, headers, options) do
{:ok, %{status_code: 200, body: body} = response} ->
body = if body != "", do: decode!(client, body)
{:ok, body, response}
{:ok, response} ->
{:error, {:unexpected_response, response}}
error = {:error, _reason} -> error
end
end
defp build_host(_endpoint_prefix, %{region: "local", endpoint: endpoint}) do
endpoint
end
defp build_host(_endpoint_prefix, %{region: "local"}) do
"localhost"
end
defp build_host(endpoint_prefix, %{endpoint: endpoint}) do
"#{endpoint_prefix}.#{endpoint}"
end
defp build_url(host, %{:proto => proto, :port => port}) do
"#{proto}://#{host}:#{port}/"
end
defp encode!(client, payload) do
AWS.Client.encode!(client, payload, :query)
end
defp decode!(client, payload) do
AWS.Client.decode!(client, payload, :xml)
end
end
| 43.471893 | 138 | 0.750374 |
ffe3e5b564bae90173a29538c5bcbe55b9b2e6b2 | 733 | ex | Elixir | lib/steve/job.ex | satom99/steve | 6425eff76e68605c5e882351e118e783abfe7ccc | [
"Apache-2.0"
] | null | null | null | lib/steve/job.ex | satom99/steve | 6425eff76e68605c5e882351e118e783abfe7ccc | [
"Apache-2.0"
] | null | null | null | lib/steve/job.ex | satom99/steve | 6425eff76e68605c5e882351e118e783abfe7ccc | [
"Apache-2.0"
] | null | null | null | defmodule Steve.Job do
alias Ecto.UUID
alias __MODULE__
@enforce_keys [:queue, :worker]
defstruct [
:id,
:queue,
:worker,
arguments: [],
max_retries: 5,
expiry_days: 7
]
@type t :: %Job{
queue: :term,
worker: module,
arguments: [] | list(term),
max_retries: 5 | pos_integer,
expiry_days: 7 | pos_integer
}
@doc """
Creates a `t:t/0` structure with the given params.
This function also injects additional required fields.
"""
@spec create(keyword) :: t | no_return
def create(params) do
__MODULE__
|> struct!(params)
|> Map.put_new(:id, UUID.generate())
end
end | 20.942857 | 58 | 0.547067 |
ffe3eb72eb319612801419f48757569d931238c9 | 1,925 | ex | Elixir | clients/content/lib/google_api/content/v21/model/buy_on_google_program_status.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | 1 | 2021-10-01T09:20:41.000Z | 2021-10-01T09:20:41.000Z | clients/content/lib/google_api/content/v21/model/buy_on_google_program_status.ex | kyleVsteger/elixir-google-api | 3a0dd498af066a4361b5b0fd66ffc04a57539488 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v21/model/buy_on_google_program_status.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.Content.V21.Model.BuyOnGoogleProgramStatus do
@moduledoc """
Response message for the GetProgramStatus method.
## Attributes
* `customerServicePendingEmail` (*type:* `String.t`, *default:* `nil`) - The customer service pending email.
* `customerServiceVerifiedEmail` (*type:* `String.t`, *default:* `nil`) - The customer service verified email.
* `participationStage` (*type:* `String.t`, *default:* `nil`) - The current participation stage for the program.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:customerServicePendingEmail => String.t() | nil,
:customerServiceVerifiedEmail => String.t() | nil,
:participationStage => String.t() | nil
}
field(:customerServicePendingEmail)
field(:customerServiceVerifiedEmail)
field(:participationStage)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V21.Model.BuyOnGoogleProgramStatus do
def decode(value, options) do
GoogleApi.Content.V21.Model.BuyOnGoogleProgramStatus.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V21.Model.BuyOnGoogleProgramStatus do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.320755 | 116 | 0.738701 |
ffe40f552577163e368ec9d9d75ab7a9bee35ad1 | 1,285 | exs | Elixir | config/dev.exs | piersadrian/hal | 190e3fb1cd0d187ac3ef485d1bf9e2623296ae16 | [
"MIT"
] | null | null | null | config/dev.exs | piersadrian/hal | 190e3fb1cd0d187ac3ef485d1bf9e2623296ae16 | [
"MIT"
] | null | null | null | config/dev.exs | piersadrian/hal | 190e3fb1cd0d187ac3ef485d1bf9e2623296ae16 | [
"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 :hal, HALWeb.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: []
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# command from your terminal:
#
# openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem
#
# The `http:` config above can be replaced with:
#
# https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
| 33.815789 | 170 | 0.73463 |
ffe442d4d53d47625680a2a0aab6c5046e9673cf | 2,583 | exs | Elixir | mix.exs | ArcBlock/abt-did-elixir | 7079ec20e24a35b8ff815574804c3ef05b1b8214 | [
"Apache-2.0"
] | 2 | 2019-07-18T06:09:00.000Z | 2019-08-08T09:52:59.000Z | mix.exs | ArcBlock/abt-did-elixir | 7079ec20e24a35b8ff815574804c3ef05b1b8214 | [
"Apache-2.0"
] | 1 | 2020-03-30T06:14:24.000Z | 2020-03-30T06:14:25.000Z | mix.exs | ArcBlock/abt-did-elixir | 7079ec20e24a35b8ff815574804c3ef05b1b8214 | [
"Apache-2.0"
] | null | null | null | defmodule AbtDid.MixProject do
use Mix.Project
@top File.cwd!()
@version @top |> Path.join("version") |> File.read!() |> String.trim()
@elixir_version @top |> Path.join(".elixir_version") |> File.read!() |> String.trim()
@otp_version @top |> Path.join(".otp_version") |> File.read!() |> String.trim()
def get_version, do: @version
def get_elixir_version, do: @elixir_version
def get_otp_version, do: @otp_version
def project do
[
app: :abt_did_elixir,
version: @version,
elixir: @elixir_version,
elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod,
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
],
deps: deps(),
description: description(),
package: package(),
# Docs
name: "AbtDid",
source_url: "https://github.com/arcblock/abt-did-elixir",
homepage_url: "https://github.com/arcblock/abt-did-elixir",
docs: [
main: "AbtDid",
extras: ["README.md"]
]
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(:integration), do: elixirc_paths(:test)
defp elixirc_paths(:dev), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:multibase, "~> 0.0.1"},
{:typed_struct, "~> 0.1.4"},
{:jason, "~> 1.1"},
# mcrypto
{:mcrypto, "~> 0.2"},
# dev & test
{:excoveralls, "~> 0.10", only: [:test, :integration]},
{:ex_doc, "~> 0.19.0", only: [:dev, :test], runtime: false}
]
end
defp description do
"""
Elixir implementation of [ABT DID protocol](https://github.com/ArcBlock/abt-did-spec).
"""
end
defp package do
[
files: [
"config",
"lib",
"mix.exs",
"README*",
"LICENSE",
"version",
".elixir_version",
".otp_version"
],
licenses: ["Apache 2.0"],
maintainers: [
"christinaleizhou@gmail.com",
"dingpl716@gmail.com",
"sunboshan@gmail.com",
"tyr.chen@gmail.com"
],
links: %{
"GitHub" => "https://github.com/arcblock/abt-did-elixir",
"Docs" => "https://hexdocs.pm/abt-did-elixir"
}
]
end
end
| 25.323529 | 90 | 0.562524 |
ffe453be26a413bc7cd8a947a8fc6e41ee920046 | 509 | exs | Elixir | config/test.exs | kimlindholm/drab_spike | f7573dade90d1cc3dcb54a30aa5a1c09445516fa | [
"MIT"
] | null | null | null | config/test.exs | kimlindholm/drab_spike | f7573dade90d1cc3dcb54a30aa5a1c09445516fa | [
"MIT"
] | 8 | 2019-10-31T11:27:57.000Z | 2022-02-09T23:00:28.000Z | config/test.exs | kimlindholm/drab_spike | f7573dade90d1cc3dcb54a30aa5a1c09445516fa | [
"MIT"
] | null | null | null | use Mix.Config
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :drab_spike, DrabSpikeWeb.Endpoint,
http: [port: 4001],
server: false
# Print only warnings and errors during test
config :logger, level: :warn
# Configure your database
config :drab_spike, DrabSpike.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
# password: "postgres",
database: "drab_spike_test",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
| 25.45 | 56 | 0.738703 |
ffe48558656fe256835170d5ac63e3632ffcbd97 | 2,313 | exs | Elixir | mix.exs | smeevil/ecto_translate | 72231f8ad57084512e46edb984d8a50f6618abb3 | [
"WTFPL"
] | 35 | 2016-07-02T02:33:47.000Z | 2022-01-03T23:16:57.000Z | mix.exs | smeevil/ecto_translate | 72231f8ad57084512e46edb984d8a50f6618abb3 | [
"WTFPL"
] | 17 | 2017-02-28T09:08:28.000Z | 2021-12-30T13:03:04.000Z | mix.exs | smeevil/ecto_translate | 72231f8ad57084512e46edb984d8a50f6618abb3 | [
"WTFPL"
] | 12 | 2017-02-14T15:49:05.000Z | 2022-03-01T13:51:18.000Z | defmodule EctoTranslate.Mixfile do
use Mix.Project
def project do
[
app: :ecto_translate,
description:
"EctoTranslate is a library that helps with translating Ecto data. EctoTranslate can help you with returning translated values of your Ecto data attributes. For this it uses a singe table called 'translations' which will contain polymorphic entries for all of your Ecto data stucts.",
version: "1.0.0",
elixir: "~> 1.7",
elixirc_paths: elixirc_paths(Mix.env()),
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
deps: deps(),
aliases: aliases(),
package: package(),
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
],
test_coverage: [
tool: ExCoveralls
],
dialyzer: [
plt_add_apps: [:mix, :ecto, :gettext, :eex, :ecto_sql],
ignore_warnings: ".dialyzer_ignore",
flags: [
:unknown,
:error_handling,
:race_conditions
]
]
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
def application do
[applications: applications(Mix.env())]
end
defp applications(:test), do: [:logger, :ecto_sql, :postgrex]
defp applications(_), do: [:logger]
defp deps do
[
{:credo, ">= 0.0.0", only: [:dev, :test]},
{:dialyxir, "~> 1.0.0-rc.3", only: [:dev], runtime: false},
{:earmark, ">= 0.0.0", only: :dev},
{:ecto, "~>3.0.7"},
{:ecto_sql, ">=3.0.5"},
{:ex_doc, ">= 0.0.0", only: :dev},
{:excoveralls, ">= 0.0.0 ", only: :test},
{:gettext, "~>0.16.1"},
{:postgrex, ">= 0.14.1", only: [:dev, :test]}
]
end
defp aliases do
[
"test.setup": ["ecto.create", "ecto.migrate"],
"test.reset": ["ecto.drop", "test.setup"]
]
end
defp package do
[
maintainers: ["Gerard de Brieder"],
licenses: ["WTFPL"],
files: ["lib", "mix.exs", "README*", "LICENSE*", "CHANGELOG*"],
links: %{
"GitHub" => "https://github.com/smeevil/ecto_translate",
"Docs" => "https://smeevil.github.io/ecto_translate/EctoTranslate.html"
}
]
end
end
| 28.207317 | 292 | 0.561608 |
ffe5048c9c937623ade818ee60e371610ace4b23 | 575 | exs | Elixir | mix.exs | renderedtext/sentry_grpc | 6879a067b22814984591dce62578222d596a0acd | [
"Unlicense",
"MIT"
] | null | null | null | mix.exs | renderedtext/sentry_grpc | 6879a067b22814984591dce62578222d596a0acd | [
"Unlicense",
"MIT"
] | null | null | null | mix.exs | renderedtext/sentry_grpc | 6879a067b22814984591dce62578222d596a0acd | [
"Unlicense",
"MIT"
] | null | null | null | defmodule Sentry.Grpc.Mixfile do
use Mix.Project
def project do
[
app: :sentry_grpc,
version: "0.1.0",
elixir: "~> 1.5",
start_permanent: Mix.env == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"},
]
end
end
| 19.827586 | 88 | 0.57913 |
ffe51d5ca0fba27bd6a103e1151343a46763d261 | 2,098 | ex | Elixir | clients/docs/lib/google_api/docs/v1/model/suggested_named_styles.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/docs/lib/google_api/docs/v1/model/suggested_named_styles.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/docs/lib/google_api/docs/v1/model/suggested_named_styles.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.Docs.V1.Model.SuggestedNamedStyles do
@moduledoc """
A suggested change to the NamedStyles.
## Attributes
* `namedStyles` (*type:* `GoogleApi.Docs.V1.Model.NamedStyles.t`, *default:* `nil`) - A NamedStyles that only includes the
changes made in this suggestion. This can be used along with the
named_styles_suggestion_state to
see which fields have changed and their new values.
* `namedStylesSuggestionState` (*type:* `GoogleApi.Docs.V1.Model.NamedStylesSuggestionState.t`, *default:* `nil`) - A mask that indicates which of the fields on the base NamedStyles have been changed in this suggestion.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:namedStyles => GoogleApi.Docs.V1.Model.NamedStyles.t(),
:namedStylesSuggestionState => GoogleApi.Docs.V1.Model.NamedStylesSuggestionState.t()
}
field(:namedStyles, as: GoogleApi.Docs.V1.Model.NamedStyles)
field(:namedStylesSuggestionState, as: GoogleApi.Docs.V1.Model.NamedStylesSuggestionState)
end
defimpl Poison.Decoder, for: GoogleApi.Docs.V1.Model.SuggestedNamedStyles do
def decode(value, options) do
GoogleApi.Docs.V1.Model.SuggestedNamedStyles.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Docs.V1.Model.SuggestedNamedStyles do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 39.584906 | 223 | 0.752622 |
ffe51e03f3c390b9bba1ab29f343b13cd59d4620 | 2,442 | ex | Elixir | clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_operation_group.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_operation_group.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_operation_group.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.Apigee.V1.Model.GoogleCloudApigeeV1OperationGroup do
@moduledoc """
The OperationGroup contains a list of configuration details associated with Apigee proxies or Remote services. Remote services are non-Apigee Edge proxies. eg, Istio-Envoy.
## Attributes
* `operationConfigType` (*type:* `String.t`, *default:* `nil`) - Identfies whether the configuration is for Apigee proxy or a remote service. Possible values are "proxy" and "remoteservice". If none specified, the default is "proxy". "proxy" is used when Apigee proxies are associated with the API product. "remoteservice" is used when non-Apigee proxy like Envoy is used, and is associated with the API product.
* `operationConfigs` (*type:* `list(GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1OperationConfig.t)`, *default:* `nil`) - Required. A list of OperationConfig for either Apigee proxies or other other remote services, that are associated with this API product.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:operationConfigType => String.t(),
:operationConfigs =>
list(GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1OperationConfig.t())
}
field(:operationConfigType)
field(:operationConfigs,
as: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1OperationConfig,
type: :list
)
end
defimpl Poison.Decoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1OperationGroup do
def decode(value, options) do
GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1OperationGroup.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1OperationGroup do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 44.4 | 416 | 0.760033 |
ffe5b4250e9f068dbcfd64c283b6f0b8ed6eab1f | 5,792 | ex | Elixir | apps/ewallet_api/test/support/conn_case.ex | vanmil/ewallet | 6c1aca95a83e0a9d93007670a40d8c45764a8122 | [
"Apache-2.0"
] | null | null | null | apps/ewallet_api/test/support/conn_case.ex | vanmil/ewallet | 6c1aca95a83e0a9d93007670a40d8c45764a8122 | [
"Apache-2.0"
] | null | null | null | apps/ewallet_api/test/support/conn_case.ex | vanmil/ewallet | 6c1aca95a83e0a9d93007670a40d8c45764a8122 | [
"Apache-2.0"
] | null | null | null | defmodule EWalletAPI.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 datastructures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
import EWalletDB.Factory
import Ecto.Query
alias Ecto.Adapters.SQL.Sandbox
alias EWalletDB.{Account, Repo, User}
alias EWallet.{MintGate, TransactionGate}
alias Ecto.UUID
use Phoenix.ConnTest
# Attributes required by Phoenix.ConnTest
@endpoint EWalletAPI.Endpoint
# Attributes for all calls
# The expected response version
@expected_version "1"
# The expected response version
@header_accept "application/vnd.omisego.v1+json"
# Attributes for client calls
@api_key "test_api_key"
@auth_token "test_auth_token"
@username "test_username"
@provider_user_id "test_provider_user_id"
@base_dir "api/client"
using do
quote do
# Import conveniences for testing with connections
use Phoenix.ConnTest
import EWalletAPI.ConnCase
import EWalletAPI.Router.Helpers
import EWalletDB.Factory
# Reiterate all module attributes from
@endpoint EWalletAPI.Endpoint
@expected_version unquote(@expected_version)
@header_accept unquote(@header_accept)
@api_key unquote(@api_key)
@auth_token unquote(@auth_token)
@username unquote(@username)
@provider_user_id unquote(@provider_user_id)
@base_dir unquote(@base_dir)
end
end
setup do
:ok = Sandbox.checkout(EWalletDB.Repo)
:ok = Sandbox.checkout(LocalLedgerDB.Repo)
# Insert account via `Account.insert/1` instead of the test factory to initialize wallets, etc.
{:ok, account} = :account |> params_for(parent: nil) |> Account.insert()
# Insert user via `User.insert/1` to initialize wallets, etc.
{:ok, user} =
:user
|> params_for(%{username: @username, provider_user_id: @provider_user_id})
|> User.insert()
_api_key = insert(:api_key, %{key: @api_key, owner_app: "ewallet_api"})
_auth_token =
insert(:auth_token, %{
user: user,
account: account,
token: @auth_token,
owner_app: "ewallet_api"
})
# Setup could return all the inserted credentials using ExUnit context
# by returning {:ok, context_map}. But it would make the code
# much less readable, i.e. `test "my test name", context do`,
# and access using `context[:attribute]`.
:ok
end
def stringify_keys(%NaiveDateTime{} = value) do
Date.to_iso8601(value)
end
def stringify_keys(map) when is_map(map) do
for {key, val} <- map, into: %{}, do: {convert_key(key), stringify_keys(val)}
end
def stringify_keys(value), do: value
def convert_key(key) when is_atom(key), do: Atom.to_string(key)
def convert_key(key), do: key
def get_test_user do
User.get_by_provider_user_id(@provider_user_id)
end
@doc """
Returns the last inserted record of the given schema.
"""
def get_last_inserted(schema) do
schema
|> last(:inserted_at)
|> Repo.one()
end
def set_initial_balance(%{
address: address,
token: token,
amount: amount
}) do
account = Account.get_master_account()
master_wallet = Account.get_primary_wallet(account)
mint!(token, amount * 100)
transfer!(
master_wallet.address,
address,
token,
amount * token.subunit_to_unit
)
end
def mint!(token, amount \\ 1_000_000) do
{:ok, mint, _transaction} =
MintGate.insert(%{
"idempotency_token" => UUID.generate(),
"token_id" => token.id,
"amount" => amount * token.subunit_to_unit,
"description" => "Minting #{amount} #{token.symbol}",
"metadata" => %{}
})
assert mint.confirmed == true
mint
end
def transfer!(from, to, token, amount) do
{:ok, transaction} =
TransactionGate.create(%{
"from_address" => from,
"to_address" => to,
"token_id" => token.id,
"amount" => amount,
"metadata" => %{},
"idempotency_token" => UUID.generate()
})
transaction
end
@doc """
A helper function that generates a valid public request
with given path and data, and return the parsed JSON response.
"""
def public_request(path, data \\ %{}, status \\ :ok)
when is_binary(path) and byte_size(path) > 0 do
build_conn()
|> put_req_header("accept", @header_accept)
|> post(@base_dir <> path, data)
|> json_response(status)
end
@doc """
A helper function that generates a valid client request
with given path and data, and return the parsed JSON response.
"""
def client_request(path, data \\ %{}, status \\ :ok)
when is_binary(path) and byte_size(path) > 0 do
build_conn()
|> put_req_header("accept", @header_accept)
|> put_auth_header("OMGClient", @api_key, @auth_token)
|> post(@base_dir <> path, data)
|> json_response(status)
end
@doc """
Helper functions that puts an Authorization header to the connection.
It can handle BasicAuth-like format, i.e. starts with auth type,
followed by a space, then the base64 pair of credentials.
"""
def put_auth_header(conn, type, access_key, secret_key) do
put_auth_header(conn, type, Base.encode64(access_key <> ":" <> secret_key))
end
def put_auth_header(conn, type, content) do
put_req_header(conn, "authorization", type <> " " <> content)
end
end
| 28.96 | 99 | 0.670925 |
ffe5d5ffd2a1dd4f0fb7c9d65fe6fe73845c6137 | 779 | ex | Elixir | lib/epi_contacts_web/controllers/admin_session_controller.ex | RatioPBC/epi-contacts | 6c43eea52cbfe2097f48b02e3d0c8fce3b46f1ee | [
"Apache-2.0"
] | null | null | null | lib/epi_contacts_web/controllers/admin_session_controller.ex | RatioPBC/epi-contacts | 6c43eea52cbfe2097f48b02e3d0c8fce3b46f1ee | [
"Apache-2.0"
] | 13 | 2021-06-29T04:35:41.000Z | 2022-02-09T04:25:39.000Z | lib/epi_contacts_web/controllers/admin_session_controller.ex | RatioPBC/epi-contacts | 6c43eea52cbfe2097f48b02e3d0c8fce3b46f1ee | [
"Apache-2.0"
] | null | null | null | defmodule EpiContactsWeb.AdminSessionController do
use EpiContactsWeb, :controller
alias EpiContacts.Accounts
alias EpiContactsWeb.AdminAuth
def new(conn, _params) do
render(conn, "new.html", error_message: nil)
end
def create(conn, %{"admin" => admin_params}) do
%{"email" => email, "password" => password, "verification_code" => verification_code} = admin_params
if admin = Accounts.get_admin_by_email_password_and_totp(email, password, verification_code) do
AdminAuth.log_in_admin(conn, admin, admin_params)
else
render(conn, "new.html", error_message: "Invalid email or password")
end
end
def delete(conn, _params) do
conn
|> put_flash(:info, "Logged out successfully.")
|> AdminAuth.log_out_admin()
end
end
| 28.851852 | 104 | 0.71887 |
ffe61b82b35b8729e43f3fc06659aebdff947be4 | 66 | ex | Elixir | testData/org/elixir_lang/parser_definition/matched_two_operation_parsing_test_case/CharListLine.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/matched_two_operation_parsing_test_case/CharListLine.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/matched_two_operation_parsing_test_case/CharListLine.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 145 | 2015-01-15T11:37:16.000Z | 2021-12-22T05:51:02.000Z | 'One' ++ 'Two'
'Three' -- 'Four'
'Five'..'Six'
'Seven' <> 'Eight'
| 13.2 | 18 | 0.484848 |
ffe652f326c05ee34f6eeec5ed859674f38d9074 | 98 | exs | Elixir | test/frettchen/helpers_test.exs | konstantinzolotarev/frettchen | 4aced1fb3d1571893ae09c18a31b05352c80cd9e | [
"MIT"
] | 3 | 2018-10-27T18:18:14.000Z | 2020-11-27T11:47:41.000Z | test/frettchen/helpers_test.exs | konstantinzolotarev/frettchen | 4aced1fb3d1571893ae09c18a31b05352c80cd9e | [
"MIT"
] | null | null | null | test/frettchen/helpers_test.exs | konstantinzolotarev/frettchen | 4aced1fb3d1571893ae09c18a31b05352c80cd9e | [
"MIT"
] | 3 | 2019-01-07T12:32:44.000Z | 2021-09-05T07:24:09.000Z | defmodule Frettchen.HelpersTest do
use ExUnit.Case, async: true
doctest Frettchen.Helpers
end
| 19.6 | 34 | 0.806122 |
ffe684b6ff455701117b2987c1b96410a3a4c07a | 1,259 | ex | Elixir | lib/find_my_personal_web/controllers/api/teacher_controller.ex | theguuholi/find_my_personal | 9a0c030b8f852812305ba7a44f0ab4794b9cb2c7 | [
"MIT"
] | null | null | null | lib/find_my_personal_web/controllers/api/teacher_controller.ex | theguuholi/find_my_personal | 9a0c030b8f852812305ba7a44f0ab4794b9cb2c7 | [
"MIT"
] | 9 | 2020-08-11T11:36:59.000Z | 2020-09-04T13:05:21.000Z | lib/find_my_personal_web/controllers/api/teacher_controller.ex | itorisaias/elxpro_find_my_personal | f1182650d3d15811c2ae9affa40c2751002dab40 | [
"MIT"
] | null | null | null | defmodule FindMyPersonalWeb.Api.TeacherController do
use FindMyPersonalWeb, :controller
alias FindMyPersonal.Teachers
alias FindMyPersonal.Teachers.Teacher
action_fallback FindMyPersonalWeb.FallbackController
def index(conn, _params) do
teacher = Teachers.list_teacher()
render(conn, "index.json", teacher: teacher)
end
def create(conn, %{"teacher" => teacher_params}) do
with {:ok, %Teacher{} = teacher} <- Teachers.create_teacher(teacher_params) do
conn
|> put_status(:created)
|> put_resp_header("location", Routes.teacher_path(conn, :show, teacher))
|> render("show.json", teacher: teacher)
end
end
def show(conn, %{"id" => id}) do
teacher = Teachers.get_teacher!(id)
render(conn, "show.json", teacher: teacher)
end
def update(conn, %{"id" => id, "teacher" => teacher_params}) do
teacher = Teachers.get_teacher!(id)
with {:ok, %Teacher{} = teacher} <- Teachers.update_teacher(teacher, teacher_params) do
render(conn, "show.json", teacher: teacher)
end
end
def delete(conn, %{"id" => id}) do
teacher = Teachers.get_teacher!(id)
with {:ok, %Teacher{}} <- Teachers.delete_teacher(teacher) do
send_resp(conn, :no_content, "")
end
end
end
| 28.613636 | 91 | 0.676728 |
ffe6a7a450794259bb274c60f725a30d8273b17a | 2,023 | ex | Elixir | lib/slack/bot/message_tracker.ex | zvkemp/elixir-bot-server | 0db6b6ce57ddccaac980bf659eb2d540a077de38 | [
"MIT"
] | 8 | 2016-03-15T17:15:26.000Z | 2021-12-11T11:21:53.000Z | lib/slack/bot/message_tracker.ex | zvkemp/elixir-bot-server | 0db6b6ce57ddccaac980bf659eb2d540a077de38 | [
"MIT"
] | 1 | 2017-10-15T20:13:15.000Z | 2017-10-15T20:13:15.000Z | lib/slack/bot/message_tracker.ex | zvkemp/elixir-bot-server | 0db6b6ce57ddccaac980bf659eb2d540a077de38 | [
"MIT"
] | null | null | null | defmodule Slack.Bot.MessageTracker do
@moduledoc """
Keeps a receipt of sent messages until an incoming message
arrives with the same "reply_to" id.
Sends a ping if no messages have been sent for 10 seconds (or the configured frequency value).
"""
use GenServer
alias Slack.Bot
alias Slack.Bot.MessageTracker.State, as: S
import Slack.BotRegistry
defmodule State do
defstruct messages: %{}, counter: 1, ping_ref: nil, name: nil, ping_freq: 10_000
end
@ping_ms 10_000
@spec start_link(Slack.Bot.bot_name(), integer) :: GenServer.on_start()
def start_link(name, ping_freq \\ @ping_ms) do
GenServer.start_link(__MODULE__, {name, ping_freq}, name: registry_key(name, __MODULE__))
end
@impl true
@spec init({Slack.Bot.bot_name(), integer}) :: {:ok, %S{}}
def init({name, ping_freq}) do
{:ok, %S{ping_ref: reset_ping_timer(ping_freq), name: name, ping_freq: ping_freq}}
end
@impl true
def handle_info(:ping, %S{} = s) do
GenServer.cast(registry_key(s.name, Bot), :ping)
{:noreply, %S{s | ping_ref: reset_ping_timer(s.ping_freq, s.ping_ref)}}
end
@spec reset_ping_timer(integer(), :timer.tref() | nil) :: :timer.tref()
defp reset_ping_timer(ms, ping_ref \\ nil) do
if ping_ref, do: _ = :timer.cancel(ping_ref)
{:ok, new_ping_ref} = :timer.send_after(ms, :ping)
new_ping_ref
end
@impl true
def handle_call({:push, payload}, _from, %S{} = s) do
counter = s.counter + 1
new_ping_ref =
if payload[:type] == "ping", do: s.ping_ref, else: reset_ping_timer(s.ping_freq, s.ping_ref)
{
:reply,
{:ok, counter},
%S{
s
| messages: Map.put(s.messages, counter, payload),
counter: counter,
ping_ref: new_ping_ref
}
}
end
@impl true
def handle_call({:reply, id, _payload}, _from, %S{} = s) do
{:reply, :ok, %S{s | messages: Map.delete(s.messages, id)}}
end
@impl true
def handle_call(:current, _from, state) do
{:reply, state, state}
end
end
| 27.712329 | 98 | 0.652991 |
ffe6d3e9d351ff8bef74e2d54613ca2d05af8559 | 1,878 | ex | Elixir | clients/data_fusion/lib/google_api/data_fusion/v1beta1/model/list_dns_peerings_response.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/data_fusion/lib/google_api/data_fusion/v1beta1/model/list_dns_peerings_response.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/data_fusion/lib/google_api/data_fusion/v1beta1/model/list_dns_peerings_response.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DataFusion.V1beta1.Model.ListDnsPeeringsResponse do
@moduledoc """
Response message for list DNS peerings.
## Attributes
* `dnsPeerings` (*type:* `list(GoogleApi.DataFusion.V1beta1.Model.DnsPeering.t)`, *default:* `nil`) - List of dns peering.
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no subsequent pages.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:dnsPeerings => list(GoogleApi.DataFusion.V1beta1.Model.DnsPeering.t()) | nil,
:nextPageToken => String.t() | nil
}
field(:dnsPeerings, as: GoogleApi.DataFusion.V1beta1.Model.DnsPeering, type: :list)
field(:nextPageToken)
end
defimpl Poison.Decoder, for: GoogleApi.DataFusion.V1beta1.Model.ListDnsPeeringsResponse do
def decode(value, options) do
GoogleApi.DataFusion.V1beta1.Model.ListDnsPeeringsResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DataFusion.V1beta1.Model.ListDnsPeeringsResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 37.56 | 189 | 0.742279 |
ffe6df5ca083911aa73289e405e9661121e9324a | 2,418 | exs | Elixir | config/config.exs | theafricanengineer/changelog.com | 4954d0df516c0a325667ec6c1fbbf02d68c9b953 | [
"MIT"
] | null | null | null | config/config.exs | theafricanengineer/changelog.com | 4954d0df516c0a325667ec6c1fbbf02d68c9b953 | [
"MIT"
] | null | null | null | config/config.exs | theafricanengineer/changelog.com | 4954d0df516c0a325667ec6c1fbbf02d68c9b953 | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
use Mix.Config
Code.load_file("config/docker_secret.exs")
config :changelog, ChangelogWeb.Endpoint,
url: [host: "localhost"],
static_url: [host: "localhost"],
root: Path.dirname(__DIR__),
secret_key_base: "PABstVJCyPEcRByCU8tmSZjv0UfoV+UeBlXNRigy4ba221RzqfN82qwsKvA5bJzi",
render_errors: [accepts: ~w(html json)],
pubsub: [name: Changelog.PubSub,
adapter: Phoenix.PubSub.PG2]
config :changelog,
ecto_repos: [Changelog.Repo],
buffer_token: DockerSecret.get("BUFFER_TOKEN"),
github_api_token: DockerSecret.get("GITHUB_API_TOKEN"),
cm_api_token: Base.encode64("#{DockerSecret.get("CM_API_TOKEN")}:x"),
slack_invite_api_token: DockerSecret.get("SLACK_APP_API_TOKEN"),
slack_app_api_token: DockerSecret.get("SLACK_APP_API_TOKEN")
config :changelog, Changelog.Mailer,
adapter: Bamboo.LocalAdapter
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
config :phoenix, :generators,
migration: true,
binary_id: false
config :scrivener_html,
routes_helper: ChangelogWeb.Router.Helpers,
view_style: :semantic
config :ex_aws,
access_key_id: DockerSecret.get("AWS_ACCESS_KEY_ID"),
secret_access_key: DockerSecret.get("AWS_SECRET_ACCESS_KEY")
config :ueberauth, Ueberauth,
providers: [
github: {Ueberauth.Strategy.Github, [default_scope: "user:email"]},
twitter: {Ueberauth.Strategy.Twitter, []}
]
config :ueberauth, Ueberauth.Strategy.Github.OAuth,
client_id: DockerSecret.get("GITHUB_CLIENT_ID"),
client_secret: DockerSecret.get("GITHUB_CLIENT_SECRET")
config :ueberauth, Ueberauth.Strategy.Twitter.OAuth,
consumer_key: DockerSecret.get("TWITTER_CONSUMER_KEY"),
consumer_secret: DockerSecret.get("TWITTER_CONSUMER_SECRET")
config :algolia,
application_id: DockerSecret.get("ALGOLIA_APPLICATION_ID"),
api_key: DockerSecret.get("ALGOLIA_API_KEY")
config :plug_ets_cache,
db_name: :response_cache,
ttl_check: 1,
ttl: 60
config :mime, :types, %{"application/javascript" => ["js"], "application/xml" => ["xml"]}
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"
| 33.123288 | 89 | 0.763854 |
ffe6fd16b9bfc542caa50fadd13bf6311217e451 | 1,740 | ex | Elixir | clients/firebase_app_check/lib/google_api/firebase_app_check/v1beta/model/google_firebase_appcheck_v1beta_exchange_debug_token_request.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/firebase_app_check/lib/google_api/firebase_app_check/v1beta/model/google_firebase_appcheck_v1beta_exchange_debug_token_request.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/firebase_app_check/lib/google_api/firebase_app_check/v1beta/model/google_firebase_appcheck_v1beta_exchange_debug_token_request.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.FirebaseAppCheck.V1beta.Model.GoogleFirebaseAppcheckV1betaExchangeDebugTokenRequest do
@moduledoc """
Request message for the ExchangeDebugToken method.
## Attributes
* `debugToken` (*type:* `String.t`, *default:* `nil`) - Required. A debug token secret. This string must match a debug token secret previously created using CreateDebugToken.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:debugToken => String.t() | nil
}
field(:debugToken)
end
defimpl Poison.Decoder,
for:
GoogleApi.FirebaseAppCheck.V1beta.Model.GoogleFirebaseAppcheckV1betaExchangeDebugTokenRequest do
def decode(value, options) do
GoogleApi.FirebaseAppCheck.V1beta.Model.GoogleFirebaseAppcheckV1betaExchangeDebugTokenRequest.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.FirebaseAppCheck.V1beta.Model.GoogleFirebaseAppcheckV1betaExchangeDebugTokenRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.222222 | 178 | 0.760345 |
ffe725c2e2d5b0ef1b3ef6c7d1ad15e06d847212 | 1,965 | ex | Elixir | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2beta1_intent_message_browse_carousel_card_browse_carousel_card_item_open_url_action.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2beta1_intent_message_browse_carousel_card_browse_carousel_card_item_open_url_action.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2beta1_intent_message_browse_carousel_card_browse_carousel_card_item_open_url_action.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.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenUrlAction do
@moduledoc """
Actions on Google action to open a given url.
## Attributes
* `url` (*type:* `String.t`, *default:* `nil`) - Required. URL
* `urlTypeHint` (*type:* `String.t`, *default:* `nil`) - Optional. Specifies the type of viewer that is used when opening
the URL. Defaults to opening via web browser.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:url => String.t(),
:urlTypeHint => String.t()
}
field(:url)
field(:urlTypeHint)
end
defimpl Poison.Decoder,
for:
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenUrlAction do
def decode(value, options) do
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenUrlAction.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItemOpenUrlAction do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.87931 | 137 | 0.754198 |
ffe729f756e5248ec2252ea94365ccea10d3b578 | 7,414 | ex | Elixir | lib/phoenix_inline_svg/helpers.ex | tylerhunt/phoenix_inline_svg | cbef95a7996a6c202558892d1d17b5d5d1979b26 | [
"MIT"
] | 58 | 2016-07-19T13:45:57.000Z | 2022-03-04T15:45:35.000Z | lib/phoenix_inline_svg/helpers.ex | tylerhunt/phoenix_inline_svg | cbef95a7996a6c202558892d1d17b5d5d1979b26 | [
"MIT"
] | 44 | 2016-07-20T22:27:03.000Z | 2021-05-06T22:06:28.000Z | lib/phoenix_inline_svg/helpers.ex | tylerhunt/phoenix_inline_svg | cbef95a7996a6c202558892d1d17b5d5d1979b26 | [
"MIT"
] | 33 | 2017-01-27T20:15:25.000Z | 2022-03-02T16:32:07.000Z | defmodule PhoenixInlineSvg.Helpers do
@moduledoc """
This module adds view helpers for rendering SVG files into safe HTML.
To add the helpers, add the following to the quoted `view` in your `my_app_web.ex` file.
def view do
quote do
use PhoenixInlineSvg.Helpers
end
end
This will generate functions for each of your images, effectively caching them at compile time.
You can call these functions like so
# Get an image with the default collection
svg_image("image_name")
# Get an image and insert HTML attributes to svg tag
svg_image("image_name", class: "elixir-is-awesome", id: "inline-svg")
# Get an image from a different collection
svg_image("image_name", "collection_name")
# Get an image from a different collection and insert HTML attributes to the svg tag
svg_image("image_name", "collection_name", class: "elixir-is-awesome", id: "inline-svg")
## Old Way
As an alternative this module can be imported in the quoted `view` def of the `my_app_web.ex` which will always pull the SVG files from the disk (unless you are using a caching module).
def view do
quote do
import PhoenixInlineSvg.Helpers
end
end
*Note:* If you are setting a custom directory for the SVG files and are using Exrm or Distillery, you will need to ensure that the directory you set is in the outputted `lib` directory of your application.
## Configuration
By default SVG files are loaded from: assets/static/svg/
The directory where SVG files are loaded from can be configured by setting the configuration variable:
config :phoenix_inline_svg, dir: "some/other/dir"
Where `some/other/dir` is a directory located in the Phoenix application directory.
"""
@doc """
The using macro precompiles the SVG images into functions.
## Examples
# Default collection
svg_image("image_name")
svg_image("image_name", attrs)
# Named collection
svg_image("image_name", "collection_name")
svg_image("image_name", "collection_name", attrs)
"""
defmacro __using__(_) do
PhoenixInlineSvg.Utils.config_or_default(:dir, "assets/static/svg/")
|> find_collection_sets
|> Enum.uniq()
|> Enum.map(&create_cached_svg_image(&1))
end
@doc """
Returns a safe HTML string with the contents of the SVG file using the `default_collection` configuration.
## Examples
<%= svg_image(@conn, "home") %>
<%= svg_image(YourAppWeb.Endpoint, "home") %>
Will result in the output:
```html
<svg>...</svg>
```
The main function is `svg_image/4`.
"""
def svg_image(conn_or_endpoint, name) do
svg_image(
conn_or_endpoint,
name,
PhoenixInlineSvg.Utils.config_or_default(:default_collection, "generic")
)
end
@doc """
Returns a safe HTML string with the contents of the SVG file after inserting the given HTML attributes.
## Examples
<%= svg_image(@conn, "home", class: "logo", id: "bounce-animation") %>
<%= svg_image(YourAppWeb.Endpoint, "home", class: "logo", id: "bounce-animation") %>
Will result in the output:
```html
<svg class="logo" id="bounce-animation">...</svg>
```
The main function is `svg_image/4`.
"""
def svg_image(conn_or_endpoint, name, attrs) when is_list(attrs) do
svg_image(
conn_or_endpoint,
name,
PhoenixInlineSvg.Utils.config_or_default(:default_collection, "generic"),
attrs
)
end
@doc """
Returns a safe HTML string with the contents of the SVG file for the given collection after inserting the given HTML attributes.
## Examples
<%= svg_image(@conn, "user", "fontawesome") %>
<%= svg_image(YourAppWeb.Endpoint, "user", "fontawesome") %>
Will result in the output:
```html
<svg>...</svg>
```
Find SVG file inside of "icons" folder and add class "fa fa-share" and id "bounce-animation"
<%= svg_image(@conn, "user", "icons", class: "fa fa-share", id: "bounce-animation") %>
<%= svg_image(YourAppWeb.Endpoint, "user", "icons", class: "fa fa-share", id: "bounce-animation") %>
Will result in the output:
```html
<svg class="fa fa-share" id="bounce-animation">...</svg>
```
"""
def svg_image(conn_or_endpoint, name, collection, attrs \\ []) do
"#{collection}/#{name}.svg"
|> read_svg_file(conn_or_endpoint)
|> PhoenixInlineSvg.Utils.insert_attrs(attrs)
|> PhoenixInlineSvg.Utils.safety_string()
end
defp read_svg_from_path(path) do
case File.read(path) do
{:ok, result} ->
String.trim(result)
{:error, _} ->
PhoenixInlineSvg.Utils.config_or_default(
:not_found,
"<svg viewbox='0 0 60 60'>" <>
"<text x='0' y='40' font-size='30' font-weight='bold'" <>
"font-family='monospace'>Err</text></svg>"
)
end
end
defp read_svg_file(icon_path, %Plug.Conn{} = conn) do
[
Application.app_dir(Phoenix.Controller.endpoint_module(conn).config(:otp_app)),
PhoenixInlineSvg.Utils.config_or_default(:dir, "priv/static/svg/"),
icon_path
]
|> Path.join()
|> read_svg_from_path
end
defp read_svg_file(icon_path, endpoint) do
[
Application.app_dir(endpoint.config(:otp_app)),
PhoenixInlineSvg.Utils.config_or_default(:dir, "priv/static/svg/"),
icon_path
]
|> Path.join()
|> read_svg_from_path
end
defp find_collection_sets(svgs_path) do
if File.dir?(svgs_path) do
case File.ls(svgs_path) do
{:ok, listed_files} ->
listed_files
|> Stream.filter(fn e -> File.dir?(Path.join(svgs_path, e)) end)
|> Enum.flat_map(&map_collection(&1, svgs_path))
_ ->
[]
end
else
[]
end
end
defp map_collection(collection, svgs_path) do
collection_path = Path.join(svgs_path, collection)
collection_path
|> File.ls!()
|> Stream.map(&Path.join(collection_path, &1))
|> Stream.flat_map(&to_file_path/1)
|> Enum.map(&{collection, &1})
end
defp to_file_path(path) do
if File.dir?(path) do
path
|> File.ls!()
|> Stream.map(&Path.join(path, &1))
|> Enum.flat_map(&to_file_path/1)
else
[path]
end
end
defp create_cached_svg_image({collection, name}) do
try do
filename = hd(Regex.run(~r|.*/#{collection}/(.*)\.svg$|, name, capture: :all_but_first))
svg = read_svg_from_path(name)
generic_funcs =
quote do
def svg_image(unquote(filename)) do
svg_image(unquote(filename), unquote(collection), [])
end
def svg_image(unquote(filename), opts) when is_list(opts) do
svg_image(unquote(filename), unquote(collection), opts)
end
end
explicit_funcs =
quote do
def svg_image(unquote(filename), unquote(collection)) do
svg_image(unquote(filename), unquote(collection), [])
end
def svg_image(unquote(filename), unquote(collection), opts) do
unquote(svg)
|> PhoenixInlineSvg.Utils.insert_attrs(opts)
|> PhoenixInlineSvg.Utils.safety_string()
end
end
[PhoenixInlineSvg.Utils.insert_generic_funcs(generic_funcs, collection), explicit_funcs]
rescue
ArgumentError -> nil
end
end
end
| 27.76779 | 207 | 0.644187 |
ffe7443a73c6a6ab7b3fd424650f19bb31bbe20a | 158 | ex | Elixir | gherkin/elixir/lib/gherkin/media.ex | endersstocker/cucumber | 5ad94a9ab5f87bca6ee23a6b4212705cdc58753d | [
"MIT"
] | null | null | null | gherkin/elixir/lib/gherkin/media.ex | endersstocker/cucumber | 5ad94a9ab5f87bca6ee23a6b4212705cdc58753d | [
"MIT"
] | null | null | null | gherkin/elixir/lib/gherkin/media.ex | endersstocker/cucumber | 5ad94a9ab5f87bca6ee23a6b4212705cdc58753d | [
"MIT"
] | null | null | null | defmodule Gherkin.Media do
@type t :: %__MODULE__{encoding: String.t(), type: String.t()}
@enforce_keys [:encoding, :type]
defstruct @enforce_keys
end
| 22.571429 | 64 | 0.708861 |
ffe7548a8a38306c43eb3ba642d5e492dfe3aed6 | 76 | exs | Elixir | test/views/layout_view_test.exs | bschmeck/ex_gnarl | 25d6961795f10a2d49efd1a29167a771ef9772f1 | [
"MIT"
] | null | null | null | test/views/layout_view_test.exs | bschmeck/ex_gnarl | 25d6961795f10a2d49efd1a29167a771ef9772f1 | [
"MIT"
] | 1 | 2017-04-21T17:02:56.000Z | 2017-04-21T17:02:56.000Z | test/views/layout_view_test.exs | bschmeck/ex_gnarl | 25d6961795f10a2d49efd1a29167a771ef9772f1 | [
"MIT"
] | null | null | null | defmodule ExGnarl.LayoutViewTest do
use ExGnarl.ConnCase, async: true
end
| 19 | 35 | 0.815789 |
ffe755fab1e3149e50e8bb080b9ba64f3b9f5a1c | 1,414 | exs | Elixir | lib/mix/test/mix/aliases_test.exs | mk/elixir | 2b2c66ecf7b1cc2167cae9cc3e88f950994223f1 | [
"Apache-2.0"
] | 4 | 2015-12-22T02:46:39.000Z | 2016-04-26T06:11:09.000Z | lib/mix/test/mix/aliases_test.exs | mk/elixir | 2b2c66ecf7b1cc2167cae9cc3e88f950994223f1 | [
"Apache-2.0"
] | null | null | null | lib/mix/test/mix/aliases_test.exs | mk/elixir | 2b2c66ecf7b1cc2167cae9cc3e88f950994223f1 | [
"Apache-2.0"
] | 1 | 2017-07-25T21:46:48.000Z | 2017-07-25T21:46:48.000Z | Code.require_file "../test_helper.exs", __DIR__
defmodule Mix.AliasesTest do
use MixTest.Case
defmodule Aliases do
def project do
[aliases: [h: "hello",
p: &inspect/1,
compile: "hello",
help: ["help", "hello"],
"nested.h": [&Mix.shell.info(inspect(&1)), "h foo bar"]]]
end
end
setup do
Mix.Project.push Aliases
:ok
end
test "runs string aliases" do
assert Mix.Task.run("h", []) == "Hello, World!"
assert Mix.Task.run("h", []) == :noop
assert Mix.Task.run("hello", []) == :noop
Mix.Task.reenable "h"
Mix.Task.reenable "hello"
assert Mix.Task.run("h", ["foo", "bar"]) == "Hello, foo bar!"
end
test "runs function aliases" do
assert Mix.Task.run("p", []) == "[]"
assert Mix.Task.run("p", []) == :noop
Mix.Task.reenable "p"
assert Mix.Task.run("p", ["foo", "bar"]) == "[\"foo\", \"bar\"]"
end
test "runs list aliases" do
assert Mix.Task.run("nested.h", ["baz"]) == "Hello, foo bar baz!"
assert_received {:mix_shell, :info, ["[]"]}
end
test "run alias override" do
assert Mix.Task.run("compile", []) == "Hello, World!"
assert Mix.Task.run("compile", []) == :noop
end
test "run alias override with recursion" do
assert Mix.Task.run("help", []) == "Hello, World!"
assert_received {:mix_shell, :info, ["mix test" <> _]}
end
end
| 26.185185 | 74 | 0.558699 |
ffe769724a8f6c4174e0ea4963c2424b74a18370 | 437 | ex | Elixir | lib/teslamate_web/live/car_live/index.ex | normalfaults/teslamate | 9c61150bd5614728447e21789ab6edc5169b631e | [
"MIT"
] | 1 | 2020-05-17T05:05:22.000Z | 2020-05-17T05:05:22.000Z | lib/teslamate_web/live/car_live/index.ex | normalfaults/teslamate | 9c61150bd5614728447e21789ab6edc5169b631e | [
"MIT"
] | null | null | null | lib/teslamate_web/live/car_live/index.ex | normalfaults/teslamate | 9c61150bd5614728447e21789ab6edc5169b631e | [
"MIT"
] | null | null | null | defmodule TeslaMateWeb.CarLive.Index do
use Phoenix.LiveView
alias TeslaMateWeb.CarView
alias TeslaMate.{Settings, Log}
@impl true
def mount(_session, socket) do
socket =
socket
|> assign_new(:cars, fn -> Log.list_cars() end)
|> assign_new(:settings, fn -> Settings.get_settings!() end)
{:ok, socket}
end
@impl true
def render(assigns) do
CarView.render("index.html", assigns)
end
end
| 19.863636 | 66 | 0.668192 |
ffe78220855f1076d082fa42a1013e82314b5ff8 | 850 | exs | Elixir | config/config.exs | juanpabloaj/phoenix_gitlab_monitor | 2b14a31c8d614b195d5003cd17faf9e5cfa56723 | [
"MIT"
] | 12 | 2018-11-04T03:39:34.000Z | 2020-04-29T19:30:58.000Z | config/config.exs | juanpabloaj/phoenix_gitlab_monitor | 2b14a31c8d614b195d5003cd17faf9e5cfa56723 | [
"MIT"
] | 16 | 2018-11-07T01:05:01.000Z | 2021-05-07T21:32:07.000Z | config/config.exs | juanpabloaj/phoenix_gitlab_monitor | 2b14a31c8d614b195d5003cd17faf9e5cfa56723 | [
"MIT"
] | 3 | 2019-08-27T20:29:00.000Z | 2020-05-25T20:36:12.000Z | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
use Mix.Config
# Configures the endpoint
config :monitor, MonitorWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "9lZ0CBL/MalRA1I/r0OvWXuFfNpguMrZQJ3qz6/iUKxqcMMzZKckYAz+rAcTHAIP",
render_errors: [view: MonitorWeb.ErrorView, accepts: ~w(html json)],
pubsub: [name: Monitor.PubSub,
adapter: Phoenix.PubSub.PG2]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:user_id]
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"
| 35.416667 | 86 | 0.757647 |
ffe7a1aa0e35741a40b2f7c29b14be0a231c94dc | 4,128 | ex | Elixir | lib/phoenix_and_elm_web/controllers/question_controller.ex | The-Vikings/phoenix-and-elm | c6c6bcc2415a479b81cae09cd62872873c7b7e78 | [
"MIT"
] | 1 | 2018-10-27T13:52:51.000Z | 2018-10-27T13:52:51.000Z | lib/phoenix_and_elm_web/controllers/question_controller.ex | The-Vikings/phoenix-and-elm | c6c6bcc2415a479b81cae09cd62872873c7b7e78 | [
"MIT"
] | 1 | 2018-11-01T08:12:02.000Z | 2018-11-01T09:37:56.000Z | lib/phoenix_and_elm_web/controllers/question_controller.ex | The-Vikings/phoenix-and-elm | c6c6bcc2415a479b81cae09cd62872873c7b7e78 | [
"MIT"
] | null | null | null | defmodule PhoenixAndElmWeb.QuestionController do
use PhoenixAndElmWeb, :controller
use PhoenixSwagger
alias PhoenixAndElm.Chatapp
alias PhoenixAndElm.Chatapp.Question
action_fallback PhoenixAndElmWeb.FallbackController
def index(conn, _params) do
questions = Chatapp.list_questions()
render(conn, "index.json", questions: questions)
end
def create(conn, %{"question" => question_params}) do
with {:ok, %Question{} = question} <- Chatapp.create_question(question_params) do
conn
|> put_status(:created)
|> put_resp_header("location", question_path(conn, :show, question))
|> render("show.json", question: question)
end
end
def show(conn, %{"id" => id}) do
question = Chatapp.get_question!(id)
render(conn, "show.json", question: question)
end
def update(conn, %{"id" => id, "question" => question_params}) do
question = Chatapp.get_question!(id)
with {:ok, %Question{} = question} <- Chatapp.update_question(question, question_params) do
render(conn, "show.json", question: question)
end
end
def delete(conn, %{"id" => id}) do
question = Chatapp.get_question!(id)
with {:ok, %Question{}} <- Chatapp.delete_question(question) do
send_resp(conn, :no_content, "")
end
end
def swagger_definitions do
%{
Question: swagger_schema do
title "Question"
description "A question in the application"
properties do
name :string, "Question's name", required: true
id :string, "Unique identifier", required: true
inserted_at :string, "Creation timestamp", format: :datetime
updated_at :string, "Update timestamp", format: :datetime
end
example %{
name: "CS443",
id: "123",
}
end,
Questions: swagger_schema do
title "Questions"
description "A collection of Questions"
type :array
items Schema.ref(:Question)
end,
QuestionRequest: swagger_schema do
title "QuestionRequest"
description "POST body for creating a question"
property :question, Schema.ref(:Question), "The question details"
end,
QuestionResponse: swagger_schema do
title "QuestionResponse"
description "Response schema for single question"
property :data, Schema.ref(:Question), "The question details"
end,
QuestionsResponse: swagger_schema do
title "QuestionsReponse"
description "Response schema for multiple questions"
property :data, Schema.array(:Question), "The questions details"
end,
}
end
swagger_path(:index) do
get "/api/questions"
summary "List Questions"
description "List all questions in the database"
produces "application/json"
deprecated false
response 200, "OK", Schema.ref(:QuestionResponse), example: %{
data: [ %{
id: 1, body: "How does Raft's leader election work?", inserted_at: "2017-02-08T12:34:55Z", updated_at: "2017-02-12T13:45:23Z"
}
]
}
end
swagger_path(:create) do
post "/api/questions"
summary "Create question"
description "Creates a new question"
consumes "application/json"
produces "application/json"
parameter :question, :body, Schema.ref(:QuestionRequest), "The question details", example: %{
question: %{name: "CS443"}
}
response 201, "Question created OK", Schema.ref(:QuestionResponse), example: %{
data: %{
id: 1, body: "How does Raft's leader election work?", inserted_at: "2017-02-08T12:34:55Z", updated_at: "2017-02-12T13:45:23Z"
}
}
end
swagger_path(:show) do
summary "Show Question"
description "Show a question by ID"
produces "application/json"
parameter :id, :path, :integer, "Question ID", required: true, example: 123
response 200, "OK", Schema.ref(:QuestionResponse), example: %{
data: %{
id: 123, body: "How does Raft's leader election work?", inserted_at: "2017-02-08T12:34:55Z", updated_at: "2017-02-12T13:45:23Z"
}
}
end
end
| 32.761905 | 141 | 0.647529 |
ffe7a6b27ec42d986b2261025da1714727a259b8 | 1,125 | exs | Elixir | config/config.exs | ianrumford/plymio_name | 434294b6f6fa489918a5ee007bec03b22a21212b | [
"MIT"
] | null | null | null | config/config.exs | ianrumford/plymio_name | 434294b6f6fa489918a5ee007bec03b22a21212b | [
"MIT"
] | null | null | null | config/config.exs | ianrumford/plymio_name | 434294b6f6fa489918a5ee007bec03b22a21212b | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :plymio_name, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:plymio_name, :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.290323 | 73 | 0.752889 |
ffe7ad1234031b549e31bc817642ea56ad7b1f7b | 1,734 | exs | Elixir | test/mnemonic_test.exs | imerkle/mnemonic | 8445f12693ee88a3024e83805b9427fbc0b411e7 | [
"MIT"
] | 2 | 2019-05-04T10:18:33.000Z | 2019-08-05T19:25:44.000Z | test/mnemonic_test.exs | imerkle/mnemonic | 8445f12693ee88a3024e83805b9427fbc0b411e7 | [
"MIT"
] | null | null | null | test/mnemonic_test.exs | imerkle/mnemonic | 8445f12693ee88a3024e83805b9427fbc0b411e7 | [
"MIT"
] | null | null | null | defmodule MnemonicTest do
use ExUnit.Case
# doctest Mnemonic
@vectors Fixtures.Vectors.all() |> Map.get(:english)
test "vectors example word for the library" do
@vectors |> Enum.each(fn(vector) ->
target_entropy = List.first(vector)
target_mnemonic = Enum.at(vector, 1)
target_seed = Enum.at(vector, 2)
assert Mnemonic.entropy_to_mnemonic(target_entropy) == target_mnemonic
assert Mnemonic.mnemonic_to_entropy(target_mnemonic) |> String.downcase == target_entropy
assert Mnemonic.mnemonic_to_seed(target_mnemonic, "TREZOR") == target_seed
assert Mnemonic.validate_mnemonic(target_mnemonic) == true
end)
end
test "invalid mnemonic returns false" do
assert Mnemonic.validate_mnemonic("subscribe to pewdiepie") == false
end
test "entropy_to_mnemonic works" do
entropy = "00000000000000000000000000000000"
mnemonic = Mnemonic.entropy_to_mnemonic(entropy)
assert mnemonic == "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
assert Mnemonic.mnemonic_to_entropy(mnemonic) == entropy
end
test "can create and recover mnemonic private keys" do
1..10000 |> Enum.reduce([], fn(x, acc) ->
mnemonic = Mnemonic.generate()
if Enum.member?(acc, mnemonic) do
raise "Duplicate mnemonic found #{mnemonic}"
end
private_key = Mnemonic.mnemonic_to_entropy(mnemonic)
assert Mnemonic.entropy_to_mnemonic(private_key) == mnemonic
[mnemonic | acc]
end)
end
test "generate can vary entropy length" do
l =
Mnemonic.generate(160)
|> String.split()
|> length()
assert l == 15
end
# also test that word count is 2048 bits(?)
end
| 32.716981 | 118 | 0.704152 |
ffe7c1471e29597f340c6ec35eaad78536698771 | 12,012 | ex | Elixir | installer/lib/phx_new/generator.ex | anirudh24seven/phoenix | b5580e9cd1c78e0460d2df30807f4f99bd8b3051 | [
"MIT"
] | null | null | null | installer/lib/phx_new/generator.ex | anirudh24seven/phoenix | b5580e9cd1c78e0460d2df30807f4f99bd8b3051 | [
"MIT"
] | null | null | null | installer/lib/phx_new/generator.ex | anirudh24seven/phoenix | b5580e9cd1c78e0460d2df30807f4f99bd8b3051 | [
"MIT"
] | null | null | null | defmodule Phx.New.Generator do
@moduledoc false
import Mix.Generator
alias Phx.New.{Project}
@phoenix Path.expand("../..", __DIR__)
@phoenix_version Version.parse!(Mix.Project.config()[:version])
@callback prepare_project(Project.t) :: Project.t
@callback generate(Project.t) :: Project.t
defmacro __using__(_env) do
quote do
@behaviour unquote(__MODULE__)
import Mix.Generator
import unquote(__MODULE__)
Module.register_attribute(__MODULE__, :templates, accumulate: true)
@before_compile unquote(__MODULE__)
end
end
defmacro __before_compile__(env) do
root = Path.expand("../../templates", __DIR__)
templates_ast =
for {name, mappings} <- Module.get_attribute(env.module, :templates) do
for {format, source, _, _} <- mappings, format != :keep do
path = Path.join(root, source)
quote do
@external_resource unquote(path)
def render(unquote(name), unquote(source)), do: unquote(File.read!(path))
end
end
end
quote do
unquote(templates_ast)
def template_files(name), do: Keyword.fetch!(@templates, name)
end
end
defmacro template(name, mappings) do
quote do
@templates {unquote(name), unquote(mappings)}
end
end
def copy_from(%Project{} = project, mod, name) when is_atom(name) do
mapping = mod.template_files(name)
for {format, source, project_location, target_path} <- mapping do
target = Project.join_path(project, project_location, target_path)
case format do
:keep ->
File.mkdir_p!(target)
:text ->
create_file(target, mod.render(name, source))
:config ->
contents = EEx.eval_string(mod.render(name, source), project.binding, file: source)
config_inject(Path.dirname(target), Path.basename(target), contents)
:prod_config ->
contents = EEx.eval_string(mod.render(name, source), project.binding, file: source)
prod_only_config_inject(Path.dirname(target), Path.basename(target), contents)
:eex ->
contents = EEx.eval_string(mod.render(name, source), project.binding, file: source)
create_file(target, contents)
end
end
end
def config_inject(path, file, to_inject) do
file = Path.join(path, file)
contents =
case File.read(file) do
{:ok, bin} -> bin
{:error, _} -> "import Config\n"
end
with :error <- split_with_self(contents, "use Mix.Config\n"),
:error <- split_with_self(contents, "import Config\n") do
Mix.raise ~s[Could not find "use Mix.Config" or "import Config" in #{inspect(file)}]
else
[left, middle, right] ->
write_formatted!(file, [left, middle, ?\n, to_inject, ?\n, right])
end
end
def prod_only_config_inject(path, file, to_inject) do
file = Path.join(path, file)
contents =
case File.read(file) do
{:ok, bin} -> bin
{:error, _} -> """
import Config
if config_env() == :prod do
end
"""
end
case split_with_self(contents, "if config_env() == :prod do") do
[left, middle, right] ->
write_formatted!(file, [left, middle, ?\n, to_inject, ?\n, right])
:error ->
Mix.raise ~s[Could not find "if config_env() == :prod do" in #{inspect(file)}]
end
end
defp write_formatted!(file, contents) do
formatted = contents |> IO.iodata_to_binary() |> Code.format_string!()
File.write!(file, [formatted, ?\n])
end
def inject_umbrella_config_defaults(project) do
unless File.exists?(Project.join_path(project, :project, "config/dev.exs")) do
path = Project.join_path(project, :project, "config/config.exs")
extra = Phx.New.Umbrella.render(:new, "phx_umbrella/config/extra_config.exs")
File.write(path, [File.read!(path), extra])
end
end
defp split_with_self(contents, text) do
case :binary.split(contents, text) do
[left, right] -> [left, text, right]
[_] -> :error
end
end
def in_umbrella?(app_path) do
umbrella = Path.expand(Path.join [app_path, "..", ".."])
mix_path = Path.join(umbrella, "mix.exs")
apps_path = Path.join(umbrella, "apps")
File.exists?(mix_path) && File.exists?(apps_path)
end
def put_binding(%Project{opts: opts} = project) do
db = Keyword.get(opts, :database, "postgres")
ecto = Keyword.get(opts, :ecto, true)
html = Keyword.get(opts, :html, true)
live = Keyword.get(opts, :live, false)
dashboard = Keyword.get(opts, :dashboard, true)
gettext = Keyword.get(opts, :gettext, true)
webpack = Keyword.get(opts, :webpack, true)
dev = Keyword.get(opts, :dev, false)
phoenix_path = phoenix_path(project, dev)
# We lowercase the database name because according to the
# SQL spec, they are case insensitive unless quoted, which
# means creating a database like FoO is the same as foo in
# some storages.
{adapter_app, adapter_module, adapter_config} =
get_ecto_adapter(db, String.downcase(project.app), project.app_mod)
pubsub_server = get_pubsub_server(project.app_mod)
adapter_config =
case Keyword.fetch(opts, :binary_id) do
{:ok, value} -> Keyword.put_new(adapter_config, :binary_id, value)
:error -> adapter_config
end
version = @phoenix_version
binding = [
elixir_version: elixir_version(),
app_name: project.app,
app_module: inspect(project.app_mod),
root_app_name: project.root_app,
root_app_module: inspect(project.root_mod),
lib_web_name: project.lib_web_name,
web_app_name: project.web_app,
endpoint_module: inspect(Module.concat(project.web_namespace, Endpoint)),
web_namespace: inspect(project.web_namespace),
phoenix_github_version_tag: "v#{version.major}.#{version.minor}",
phoenix_dep: phoenix_dep(phoenix_path),
phoenix_path: phoenix_path,
phoenix_webpack_path: phoenix_webpack_path(project, dev),
phoenix_html_webpack_path: phoenix_html_webpack_path(project),
phoenix_live_view_webpack_path: phoenix_live_view_webpack_path(project),
phoenix_static_path: phoenix_static_path(phoenix_path),
pubsub_server: pubsub_server,
secret_key_base: random_string(64),
signing_salt: random_string(8),
lv_signing_salt: random_string(8),
in_umbrella: project.in_umbrella?,
webpack: webpack,
ecto: ecto,
html: html,
live: live,
dashboard: dashboard,
gettext: gettext,
adapter_app: adapter_app,
adapter_module: adapter_module,
adapter_config: adapter_config,
generators: nil_if_empty(project.generators ++ adapter_generators(adapter_config)),
namespaced?: namespaced?(project),
]
%Project{project | binding: binding}
end
defp elixir_version do
System.version()
end
defp namespaced?(project) do
Macro.camelize(project.app) != inspect(project.app_mod)
end
def gen_ecto_config(%Project{project_path: project_path, binding: binding}) do
adapter_config = binding[:adapter_config]
config_inject project_path, "config/dev.exs", """
# Configure your database
config :#{binding[:app_name]}, #{binding[:app_module]}.Repo#{kw_to_config adapter_config[:dev]},
pool_size: 10
"""
config_inject project_path, "config/test.exs", """
# Configure your database
#
# The MIX_TEST_PARTITION environment variable can be used
# to provide built-in test partitioning in CI environment.
# Run `mix help test` for more information.
config :#{binding[:app_name]}, #{binding[:app_module]}.Repo#{kw_to_config adapter_config[:test]}
"""
prod_only_config_inject project_path, "config/runtime.exs", """
database_url =
System.get_env("DATABASE_URL") ||
raise \"""
environment variable DATABASE_URL is missing.
For example: ecto://USER:PASS@HOST/DATABASE
\"""
config :#{binding[:app_name]}, #{binding[:app_module]}.Repo,
# ssl: true,
url: database_url,
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10")
"""
end
defp get_pubsub_server(module) do
module
|> Module.split()
|> hd()
|> Module.concat(PubSub)
end
defp get_ecto_adapter("mssql", app, module) do
{:tds, Ecto.Adapters.Tds, db_config(app, module, "sa", "some!Password")}
end
defp get_ecto_adapter("mysql", app, module) do
{:myxql, Ecto.Adapters.MyXQL, db_config(app, module, "root", "")}
end
defp get_ecto_adapter("postgres", app, module) do
{:postgrex, Ecto.Adapters.Postgres, db_config(app, module, "postgres", "postgres")}
end
defp get_ecto_adapter(db, _app, _mod) do
Mix.raise "Unknown database #{inspect db}"
end
defp db_config(app, module, user, pass) do
[
dev: [
username: user,
password: pass,
database: "#{app}_dev",
hostname: "localhost",
show_sensitive_data_on_connection_error: true
],
test: [
username: user,
password: pass,
database: {:literal, ~s|"#{app}_test\#{System.get_env("MIX_TEST_PARTITION")}"|},
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
],
test_setup_all: "Ecto.Adapters.SQL.Sandbox.mode(#{inspect(module)}.Repo, :manual)",
test_setup: """
pid = Ecto.Adapters.SQL.Sandbox.start_owner!(#{inspect(module)}.Repo, shared: not tags[:async])
on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)\
"""
]
end
defp kw_to_config(kw) do
Enum.map(kw, fn
{k, {:literal, v}} -> ",\n #{k}: #{v}"
{k, v} -> ",\n #{k}: #{inspect v}"
end)
end
defp adapter_generators(adapter_config) do
adapter_config
|> Keyword.take([:binary_id, :migration, :sample_binary_id])
|> Enum.filter(fn {_, value} -> not is_nil(value) end)
end
defp nil_if_empty([]), do: nil
defp nil_if_empty(other), do: other
defp phoenix_path(%Project{} = project, true) do
absolute = Path.expand(project.project_path)
relative = Path.relative_to(absolute, @phoenix)
if absolute == relative do
Mix.raise "--dev projects must be generated inside Phoenix directory"
end
project
|> phoenix_path_prefix()
|> Path.join(relative)
|> Path.split()
|> Enum.map(fn _ -> ".." end)
|> Path.join()
end
defp phoenix_path(%Project{}, false) do
"deps/phoenix"
end
defp phoenix_path_prefix(%Project{in_umbrella?: true}), do: "../../../"
defp phoenix_path_prefix(%Project{in_umbrella?: false}), do: ".."
defp phoenix_webpack_path(%Project{in_umbrella?: true}, true = _dev),
do: "../../../../../"
defp phoenix_webpack_path(%Project{in_umbrella?: true}, false = _dev),
do: "../../../deps/phoenix"
defp phoenix_webpack_path(%Project{in_umbrella?: false}, true = _dev),
do: "../../../"
defp phoenix_webpack_path(%Project{in_umbrella?: false}, false = _dev),
do: "../deps/phoenix"
defp phoenix_html_webpack_path(%Project{in_umbrella?: true}),
do: "../../../deps/phoenix_html"
defp phoenix_html_webpack_path(%Project{in_umbrella?: false}),
do: "../deps/phoenix_html"
defp phoenix_live_view_webpack_path(%Project{in_umbrella?: true}),
do: "../../../deps/phoenix_live_view"
defp phoenix_live_view_webpack_path(%Project{in_umbrella?: false}),
do: "../deps/phoenix_live_view"
defp phoenix_dep("deps/phoenix"), do: ~s[{:phoenix, "~> #{@phoenix_version}"}]
# defp phoenix_dep("deps/phoenix"), do: ~s[{:phoenix, github: "phoenixframework/phoenix", override: true}]
defp phoenix_dep(path), do: ~s[{:phoenix, path: #{inspect path}, override: true}]
defp phoenix_static_path("deps/phoenix"), do: "deps/phoenix"
defp phoenix_static_path(path), do: Path.join("..", path)
defp random_string(length) do
:crypto.strong_rand_bytes(length) |> Base.encode64 |> binary_part(0, length)
end
end
| 33.553073 | 108 | 0.653014 |
ffe7cbe4d23b6139ad3cede0e9b6cd19cb93d041 | 590 | ex | Elixir | lib/mix/tasks/egg.ex | ohr486/eggman | 82eb614dab64aadaa556454b9c3c89ca9ed3c9b2 | [
"MIT"
] | 1 | 2020-01-13T20:50:40.000Z | 2020-01-13T20:50:40.000Z | lib/mix/tasks/egg.ex | ohr486/eggman | 82eb614dab64aadaa556454b9c3c89ca9ed3c9b2 | [
"MIT"
] | 25 | 2019-07-02T05:57:46.000Z | 2021-07-26T05:20:55.000Z | lib/mix/tasks/egg.ex | ohr486/eggman | 82eb614dab64aadaa556454b9c3c89ca9ed3c9b2 | [
"MIT"
] | null | null | null | defmodule Mix.Tasks.Egg do
use Mix.Task
@shortdoc "Prints Eggman help information"
@moduledoc """
Prints Eggman tasks and their information.
mix egg
"""
@doc false
def run(args) do
case args do
[] -> general()
_ -> Mix.raise "Invalid arguments, expected: mix egg"
end
end
@doc false
defp general() do
Application.ensure_all_started(:eggman)
Mix.shell.info "Eggman v#{Application.spec(:eggman, :vsn)}"
Mix.shell.info "Serverless WAF."
Mix.shell.info "\nAvailable tasks:\n"
Mix.Tasks.Help.run(["--search", "egg."])
end
end
| 20.344828 | 63 | 0.647458 |
ffe7dedb9f70f4e0b0eef6a0abb5f29009cb64e2 | 102 | exs | Elixir | config/test.exs | jfrolich/smoothie | 4b471913b8b9dc80484153cc2fda0c8944039356 | [
"MIT"
] | 45 | 2016-09-23T15:36:28.000Z | 2022-02-08T19:43:03.000Z | config/test.exs | jfrolich/smoothie | 4b471913b8b9dc80484153cc2fda0c8944039356 | [
"MIT"
] | 20 | 2016-09-27T15:51:32.000Z | 2020-09-21T02:56:59.000Z | config/test.exs | jfrolich/smoothie | 4b471913b8b9dc80484153cc2fda0c8944039356 | [
"MIT"
] | 6 | 2016-09-27T15:38:39.000Z | 2017-07-17T19:09:27.000Z | use Mix.Config
config :smoothie, modules: [Build.Mailer, Css.Mailer, Scss.Mailer, Foundation.Mailer]
| 25.5 | 85 | 0.77451 |
ffe867e35776fc01e1fcce07f7f52806ca7255f0 | 2,452 | exs | Elixir | test/crimpex_test.exs | BBC-News/crimpex | c73858882286b623dbf22027df7efd94ec029d59 | [
"MIT"
] | null | null | null | test/crimpex_test.exs | BBC-News/crimpex | c73858882286b623dbf22027df7efd94ec029d59 | [
"MIT"
] | 1 | 2019-05-21T08:11:59.000Z | 2019-05-21T08:11:59.000Z | test/crimpex_test.exs | BBC-News/crimpex | c73858882286b623dbf22027df7efd94ec029d59 | [
"MIT"
] | null | null | null | defmodule CrimpexTest do
use ExUnit.Case
describe "signature" do
test "when given a nil value it returns the correct signature" do
assert Crimpex.signature(nil) == "b14a7b8059d9c055954c92674ce60032"
end
test "when given a single string it returns the correct signature" do
assert Crimpex.signature("abc") == "c4449120506d97975c67be69719a78e2"
end
test "when given a single integer it returns the correct signature" do
assert Crimpex.signature(1) == "594170053719896a11eb08ee513813d5"
end
test "when passed an erlang binary in a list" do
assert Crimpex.signature(["a", "b", <<179>>]) == "aa31a432d46a6e85b37b442ffd44cf26"
end
end
describe "acceptance tests" do
test "verify String handling" do
assert Crimpex.signature("abc") == "c4449120506d97975c67be69719a78e2"
end
test "verify integers handling" do
assert Crimpex.signature(1) == "594170053719896a11eb08ee513813d5"
end
test "verify floats handling" do
assert Crimpex.signature(1.2) == "f1ab6592886cd4b1b66ed55e73d9ab81"
end
test "verify Array handling" do
assert Crimpex.signature([1, "a", 3]) == "cd1c43797d488d0f6c0d71537c64d30b"
end
test "verify Array sorting" do
assert Crimpex.signature([3, nil, 1, "1"]) == "518e7bb17674f6acbb296845862a152d"
end
test "verify Array sorting with capital letters" do
assert Crimpex.signature(["a", "A", "b", "B"]) == "f6692ab4bc94b35e61ec15c2d1891734"
end
test "verify nested Arrays" do
assert Crimpex.signature(["a", 1, ["b", "2"]]) == "3aaa58da4841eaeb41d3726d2c6fd875"
end
test "verify nested Arrays in another order" do
assert Crimpex.signature([["b", "2"], "a", 1]) == "3aaa58da4841eaeb41d3726d2c6fd875"
end
test "verify hash like data structures" do
assert Crimpex.signature(%{"a" => 1}) == "8cb44d69badda0f34b0bab6bb3e7fdbf"
end
test "verify nested hash" do
assert Crimpex.signature(%{"a" => %{"c" => nil, "2" => 2 }}) == "bff3538075e4007c7679a7ba0d0a5f30"
end
test "verify null values" do
assert Crimpex.signature(nil) == "b14a7b8059d9c055954c92674ce60032"
end
test "verify true boolean values" do
assert Crimpex.signature(true) == "6413cfeb7a89f7e0a8872f82b919c0d9"
end
test "verify false boolean values" do
assert Crimpex.signature(false) == "fa39253035cfe44c8638b8f5d7a3402e"
end
end
end | 33.135135 | 104 | 0.688825 |
ffe8998790299c11e8026127c858ab8f81a123d0 | 1,051 | ex | Elixir | tests/dummy/lib/dummy/endpoint.ex | autoxjs/autox-phoenix | 6446f4487e3af28955f6560973cff6add34be4d4 | [
"MIT"
] | null | null | null | tests/dummy/lib/dummy/endpoint.ex | autoxjs/autox-phoenix | 6446f4487e3af28955f6560973cff6add34be4d4 | [
"MIT"
] | 20 | 2016-04-05T06:28:58.000Z | 2016-05-12T15:45:37.000Z | tests/dummy/lib/dummy/endpoint.ex | foxnewsnetwork/autox | 66ea3f0f7ba8b3f9e910984a2ed3cdf0ef5ef29a | [
"MIT"
] | null | null | null | defmodule Dummy.Endpoint do
use Phoenix.Endpoint, otp_app: :dummy
socket "/socket", Dummy.UserSocket
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phoenix.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/", from: :dummy, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
plug Phoenix.CodeReloader
end
plug Plug.RequestId
plug Plug.Logger
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
plug Plug.MethodOverride
plug Plug.Head
plug Autox.InsecureSessionPlug,
store: :cookie,
key: "_dummy_key",
signing_salt: "tXVNJL9p",
max_age: 26_280_000 # 10 months
plug CORSPlug,
headers: CORSPlug.defaults[:headers] ++ ["_dummy_key"],
expose: ["_dummy_key"]
plug Dummy.Router
end
| 24.44186 | 65 | 0.695528 |
ffe89f12041f5992f93bbae005e9649c31086e21 | 2,341 | ex | Elixir | lib/plaid/link.ex | ethangunderson/plaid-elixir | 7c607a097bd0c23e85b72737dbbe0ec286faf96b | [
"MIT"
] | 50 | 2016-10-19T16:34:27.000Z | 2022-03-17T03:55:54.000Z | lib/plaid/link.ex | ethangunderson/plaid-elixir | 7c607a097bd0c23e85b72737dbbe0ec286faf96b | [
"MIT"
] | 47 | 2017-11-08T19:19:09.000Z | 2022-03-23T00:53:22.000Z | lib/plaid/link.ex | ethangunderson/plaid-elixir | 7c607a097bd0c23e85b72737dbbe0ec286faf96b | [
"MIT"
] | 40 | 2016-10-27T14:39:14.000Z | 2022-03-01T01:03:17.000Z | defmodule Plaid.Link do
@moduledoc """
Functions for Plaid `link` endpoint.
"""
import Plaid, only: [make_request_with_cred: 4, validate_cred: 1]
alias Plaid.Utils
@derive Jason.Encoder
defstruct link_token: nil,
expiration: nil,
# Deprecated, not returned by Plaid.
request_id: nil,
created_at: nil,
metadata: nil
@type t :: %__MODULE__{
link_token: String.t(),
expiration: String.t(),
request_id: String.t(),
created_at: String.t(),
metadata: Plaid.Link.Metadata.t()
}
@type params :: %{required(atom) => String.t()}
@type config :: %{required(atom) => String.t()}
@endpoint :link
defmodule Metadata do
@moduledoc """
Plaid Link Metadata data structure.
"""
@derive Jason.Encoder
defstruct initial_products: nil,
webhook: nil,
country_codes: nil,
language: nil,
account_filters: nil,
redirect_uri: nil,
client_name: nil
@type t :: %__MODULE__{
initial_products: [String.t()],
webhook: String.t(),
country_codes: [String.t()],
language: String.t(),
account_filters: map(),
redirect_uri: String.t(),
client_name: String.t()
}
end
@doc """
Creates a Link Token.
Parameters
```
%{
client_name: "",
language: "",
country_codes: "",
user: %{client_user_id: ""}
}
```
"""
@spec create_link_token(params, config | nil) ::
{:ok, Plaid.Link.t()} | {:error, Plaid.Error.t()}
def create_link_token(params, config \\ %{}) do
config = validate_cred(config)
endpoint = "#{@endpoint}/token/create"
make_request_with_cred(:post, endpoint, config, params)
|> Utils.handle_resp(@endpoint)
end
@doc """
Gets a Link Token's information.
Parameters
```
%{
link_token: ""
}
```
"""
@spec get_link_token(params, config | nil) ::
{:ok, Plaid.Link.t()} | {:error, Plaid.Error.t()}
def get_link_token(params, config \\ %{}) do
config = validate_cred(config)
endpoint = "#{@endpoint}/token/get"
make_request_with_cred(:post, endpoint, config, params)
|> Utils.handle_resp(@endpoint)
end
end
| 23.887755 | 67 | 0.56557 |
ffe931754cb17e0f08fda6decac6a4813fac74a7 | 481 | ex | Elixir | lib/smite.ex | luishendrix92/exrez | c9a001ff32c2081449ce190d151e7df09a0a42ee | [
"MIT"
] | null | null | null | lib/smite.ex | luishendrix92/exrez | c9a001ff32c2081449ce190d151e7df09a0a42ee | [
"MIT"
] | null | null | null | lib/smite.ex | luishendrix92/exrez | c9a001ff32c2081449ce190d151e7df09a0a42ee | [
"MIT"
] | null | null | null | defmodule Exrez.Smite do
import Exrez, only: [api_call: 2, api_call: 3]
def god_leaderboard(platform, god_id, queue_id) do
api_call(platform, "getgodleaderboard", "/#{god_id}/#{queue_id}")
end
def god_recommended_items(platform, god_id, language \\ 1) do
api_call(platform, "getgodrecommendeditems", "/#{god_id}/#{language}")
end
def motd(platform), do: api_call(platform, "getmotd")
def top_matches(platform), do: api_call(platform, "gettopmatches")
end
| 30.0625 | 74 | 0.719335 |
ffe9760dccc78c06d24fb3c933515547d6b6eeee | 811 | exs | Elixir | linq/linq_test.exs | judas-christ/love-potions | 39a43dca4c66b5e8028759c8a81d97a8c0562956 | [
"MIT"
] | null | null | null | linq/linq_test.exs | judas-christ/love-potions | 39a43dca4c66b5e8028759c8a81d97a8c0562956 | [
"MIT"
] | null | null | null | linq/linq_test.exs | judas-christ/love-potions | 39a43dca4c66b5e8028759c8a81d97a8c0562956 | [
"MIT"
] | null | null | null | ExUnit.start
Code.require_file("linq.exs", __DIR__)
defmodule LinqTest do
use ExUnit.Case
test "table name" do
assert String.contains?(Entity.all, "from entities as")
end
test "filter" do
assert String.contains?(Entity.some, "name <> \"bah\"")
end
end
defmodule Entity do
import Linq
schema table_name: "entities" do
field :name, :string
field :age, :integer
end
def all do
from fejk in Entity
end
def some do
from entity in Entity,
where: entity.age > 0 and entity.age < 30 and entity.name != "bah"
end
def map do
from entity in Entity,
select: [name: entity.name]
end
def map_some do
from entity in Entity,
where: entity.age == 40,
select: [name: entity.name]
end
end
| 18.431818 | 74 | 0.61529 |
ffe9a5e9e9e7d1eae1da5c0535498c8948eb911d | 2,244 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/encryption_info.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/encryption_info.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/encryption_info.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DFAReporting.V34.Model.EncryptionInfo do
@moduledoc """
A description of how user IDs are encrypted.
## Attributes
* `encryptionEntityId` (*type:* `String.t`, *default:* `nil`) - The encryption entity ID. This should match the encryption configuration for ad serving or Data Transfer.
* `encryptionEntityType` (*type:* `String.t`, *default:* `nil`) - The encryption entity type. This should match the encryption configuration for ad serving or Data Transfer.
* `encryptionSource` (*type:* `String.t`, *default:* `nil`) - Describes whether the encrypted cookie was received from ad serving (the %m macro) or from Data Transfer.
* `kind` (*type:* `String.t`, *default:* `dfareporting#encryptionInfo`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#encryptionInfo".
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:encryptionEntityId => String.t(),
:encryptionEntityType => String.t(),
:encryptionSource => String.t(),
:kind => String.t()
}
field(:encryptionEntityId)
field(:encryptionEntityType)
field(:encryptionSource)
field(:kind)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V34.Model.EncryptionInfo do
def decode(value, options) do
GoogleApi.DFAReporting.V34.Model.EncryptionInfo.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V34.Model.EncryptionInfo do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.071429 | 177 | 0.729501 |
ffe9b3ee25925bfbb0e0da2a4d625785846ca871 | 454 | exs | Elixir | test/sitemap/alternate_test.exs | isavita/sitemap | 0fa66869646e1bace12f2e60bb08aeaa0f713f38 | [
"MIT",
"Unlicense"
] | 3 | 2019-05-17T00:57:02.000Z | 2020-04-03T12:38:53.000Z | test/sitemap/alternate_test.exs | isavita/sitemap | 0fa66869646e1bace12f2e60bb08aeaa0f713f38 | [
"MIT",
"Unlicense"
] | 1 | 2020-02-18T14:15:48.000Z | 2020-02-18T14:15:48.000Z | test/sitemap/alternate_test.exs | isavita/sitemap | 0fa66869646e1bace12f2e60bb08aeaa0f713f38 | [
"MIT",
"Unlicense"
] | 1 | 2020-02-18T11:29:25.000Z | 2020-02-18T11:29:25.000Z | defmodule Sitemap.AlternateTest do
use ExUnit.Case
@alternates [href: "http://www.example.de/index.html", lang: "de", nofollow: true, media: "only screen and (max-width: 640px)"]
@expected "
<xhtml:link href=\"http://www.example.de/index.html\" hreflang=\"de\" media=\"only screen and (max-width: 640px)\" rel=\"alternate nofollow\"/>"
test "new/1" do
assert IO.iodata_to_binary(Sitemap.Alternate.new(@alternates)) == @expected
end
end
| 37.833333 | 146 | 0.696035 |
ffe9b4cd9d7d8fc19cafd6830e486b9489ff20c9 | 1,170 | ex | Elixir | phoenix/app/lib/phx_app_web/channels/user_socket.ex | ohr486/docker-app-template | 9365f95d1102c69dba46474d0498d8306d40ed79 | [
"MIT"
] | null | null | null | phoenix/app/lib/phx_app_web/channels/user_socket.ex | ohr486/docker-app-template | 9365f95d1102c69dba46474d0498d8306d40ed79 | [
"MIT"
] | null | null | null | phoenix/app/lib/phx_app_web/channels/user_socket.ex | ohr486/docker-app-template | 9365f95d1102c69dba46474d0498d8306d40ed79 | [
"MIT"
] | null | null | null | defmodule PhxAppWeb.UserSocket do
use Phoenix.Socket
## Channels
# channel "room:*", PhxAppWeb.RoomChannel
## Transports
transport :websocket, Phoenix.Transports.WebSocket
# transport :longpoll, Phoenix.Transports.LongPoll
# Socket params are passed from the client and can
# be used to verify and authenticate a user. After
# verification, you can put default assigns into
# the socket that will be set for all channels, ie
#
# {:ok, assign(socket, :user_id, verified_user_id)}
#
# To deny connection, return `:error`.
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
def connect(_params, socket) do
{:ok, socket}
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "user_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# PhxAppWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
def id(_socket), do: nil
end
| 30.789474 | 83 | 0.702564 |
ffe9ffd6d01429187213f45cc777dac563584357 | 7,758 | ex | Elixir | lib/ex_oauth2_provider/applications/strategies/sql_strategy.ex | loopsocial/ex_oauth2_provider | 59d177f1c7581e1d794823279067022b1598f5f2 | [
"MIT"
] | null | null | null | lib/ex_oauth2_provider/applications/strategies/sql_strategy.ex | loopsocial/ex_oauth2_provider | 59d177f1c7581e1d794823279067022b1598f5f2 | [
"MIT"
] | null | null | null | lib/ex_oauth2_provider/applications/strategies/sql_strategy.ex | loopsocial/ex_oauth2_provider | 59d177f1c7581e1d794823279067022b1598f5f2 | [
"MIT"
] | null | null | null | defmodule ExOauth2Provider.Applications.Strategy.SqlStrategy do
@moduledoc """
Standard Postgres-based application implementation strategy
"""
@behaviour ExOauth2Provider.Applications
import Ecto.Query
alias Ecto.{Changeset, Schema}
alias ExOauth2Provider.{AccessTokens, Applications.Application, Config}
@doc """
Gets a single application by uid.
Raises `Ecto.NoResultsError` if the Application does not exist.
## Examples
iex> get_application!("c341a5c7b331ef076eb4954668d54f590e0009e06b81b100191aa22c93044f3d", otp_app: :my_app)
%OauthApplication{}
iex> get_application!("75d72f326a69444a9287ea264617058dbbfe754d7071b8eef8294cbf4e7e0fdc", otp_app: :my_app)
** (Ecto.NoResultsError)
"""
@impl true
@spec get_application!(binary(), keyword()) :: Application.t() | no_return
def get_application!(uid, config \\ []) do
config
|> Config.application()
|> Config.repo(config).get_by!(uid: uid)
end
@doc """
Gets a single application for a resource owner.
Raises `Ecto.NoResultsError` if the OauthApplication does not exist for resource owner.
## Examples
iex> get_application_for!(owner, "c341a5c7b331ef076eb4954668d54f590e0009e06b81b100191aa22c93044f3d", otp_app: :my_app)
%OauthApplication{}
iex> get_application_for!(owner, "75d72f326a69444a9287ea264617058dbbfe754d7071b8eef8294cbf4e7e0fdc", otp_app: :my_app)
** (Ecto.NoResultsError)
"""
@impl true
@spec get_application_for!(Schema.t(), binary(), keyword()) :: Application.t() | no_return
def get_application_for!(resource_owner, uid, config \\ []) do
config
|> Config.application()
|> Config.repo(config).get_by!(owner_id: resource_owner.id, uid: uid)
end
@doc """
Gets a single application by uid.
## Examples
iex> get_application("c341a5c7b331ef076eb4954668d54f590e0009e06b81b100191aa22c93044f3d", otp_app: :my_app)
%OauthApplication{}
iex> get_application("75d72f326a69444a9287ea264617058dbbfe754d7071b8eef8294cbf4e7e0fdc", otp_app: :my_app)
nil
"""
@impl true
@spec get_application(binary(), keyword()) :: Application.t() | nil
def get_application(uid, config \\ []) do
config
|> Config.application()
|> Config.repo(config).get_by(uid: uid)
end
@doc """
Gets a single application by uid and secret.
## Examples
iex> load_application("c341a5c7b331ef076eb4954668d54f590e0009e06b81b100191aa22c93044f3d", "SECRET", otp_app: :my_app)
%OauthApplication{}
iex> load_application("75d72f326a69444a9287ea264617058dbbfe754d7071b8eef8294cbf4e7e0fdc", "SECRET", otp_app: :my_app)
nil
"""
@impl true
@spec load_application(
binary(),
{:client_secret, binary()} | {:code_verifier, binary()},
keyword()
) :: Application.t() | nil
def load_application(uid, secret, config \\ [])
def load_application(uid, {:client_secret, :not_required}, config) do
config
|> Config.application()
|> Config.repo(config).get_by(uid: uid)
end
def load_application(uid, {:client_secret, client_secret}, config) do
config
|> Config.application()
|> Config.repo(config).get_by(uid: uid, secret: client_secret)
end
def load_application(uid, {:code_verifier, code_verifier}, config) do
config
|> Config.application()
|> Config.repo(config).get_by(uid: uid)
|> verify_pkce(code_verifier, config)
end
def load_application(uid, :refresh_token_flow, config) do
if Config.refresh_token_without_secret?(config) do
config
|> Config.application()
|> Config.repo(config).get_by(uid: uid)
else
nil
end
end
defp verify_pkce(nil, _code_verifier, _config), do: nil
defp verify_pkce(application, code_verifier, config) do
case Config.pkce_module(config).verify(application, code_verifier) do
:ok ->
application
{:error, _message} ->
:invalid_code_verifier
end
end
@doc """
Returns all applications for a owner.
## Examples
iex> get_applications_for(resource_owner, otp_app: :my_app)
[%OauthApplication{}, ...]
"""
@impl true
@spec get_applications_for(Schema.t(), keyword()) :: [Application.t()]
def get_applications_for(resource_owner, config \\ []) do
config
|> Config.application()
|> where([a], a.owner_id == ^resource_owner.id)
|> Config.repo(config).all()
end
@doc """
Gets all authorized applications for a resource owner.
## Examples
iex> get_authorized_applications_for(owner, otp_app: :my_app)
[%OauthApplication{},...]
"""
@impl true
@spec get_authorized_applications_for(Schema.t(), keyword()) :: [Application.t()]
def get_authorized_applications_for(resource_owner, config \\ []) do
application_ids =
resource_owner
|> AccessTokens.get_authorized_tokens_for(config)
|> Enum.map(&Map.get(&1, :application_id))
config
|> Config.application()
|> where([a], a.id in ^application_ids)
|> Config.repo(config).all()
end
@doc """
Create application changeset.
## Examples
iex> change_application(application, %{}, otp_app: :my_app)
{:ok, %OauthApplication{}}
"""
@impl true
@spec change_application(Application.t(), map(), keyword()) :: Changeset.t()
def change_application(application, attrs \\ %{}, config \\ []) do
Application.changeset(application, attrs, config)
end
@doc """
Creates an application.
## Examples
iex> create_application(user, %{name: "App", redirect_uri: "http://example.com"}, otp_app: :my_app)
{:ok, %OauthApplication{}}
iex> create_application(user, %{name: ""}, otp_app: :my_app)
{:error, %Ecto.Changeset{}}
"""
@impl true
@spec create_application(Schema.t(), map(), keyword()) ::
{:ok, Application.t()} | {:error, Changeset.t()}
def create_application(owner, attrs \\ %{}, config \\ []) do
config
|> Config.application()
|> struct(owner: owner)
|> Application.changeset(attrs, config)
|> Config.repo(config).insert()
end
@doc """
Updates an application.
## Examples
iex> update_application(application, %{name: "Updated App"}, otp_app: :my_app)
{:ok, %OauthApplication{}}
iex> update_application(application, %{name: ""}, otp_app: :my_app)
{:error, %Ecto.Changeset{}}
"""
@impl true
@spec update_application(Application.t(), map(), keyword()) ::
{:ok, Application.t()} | {:error, Changeset.t()}
def update_application(application, attrs, config \\ []) do
application
|> Application.changeset(attrs, config)
|> Config.repo(config).update()
end
@doc """
Deletes an application.
## Examples
iex> delete_application(application, otp_app: :my_app)
{:ok, %OauthApplication{}}
iex> delete_application(application, otp_app: :my_app)
{:error, %Ecto.Changeset{}}
"""
@impl true
@spec delete_application(Application.t(), keyword()) ::
{:ok, Application.t()} | {:error, Changeset.t()}
def delete_application(application, config \\ []) do
Config.repo(config).delete(application)
end
@doc """
Revokes all access tokens for an application and resource owner.
## Examples
iex> revoke_all_access_tokens_for(application, resource_owner, otp_app: :my_app)
{:ok, [ok: %OauthAccessToken{}]}
"""
@impl true
@spec revoke_all_access_tokens_for(Application.t(), Schema.t(), keyword()) ::
{:ok, AccessToken.t()} | {:error, any()}
def revoke_all_access_tokens_for(application, resource_owner, config \\ []) do
AccessTokens.get_all_tokens_for(resource_owner, application, config)
|> Enum.map(&AccessTokens.revoke(&1, config))
end
end
| 28.522059 | 124 | 0.67453 |
ffea0ee014b1d21a767a4804745450c62667f828 | 2,026 | exs | Elixir | test/callbacks/handle_continue_test.exs | bnns/state_server | d62dcd7c8d261e057764c39370b6ac5a63f11aa4 | [
"MIT"
] | 8 | 2019-08-31T00:31:58.000Z | 2021-06-11T22:12:05.000Z | test/callbacks/handle_continue_test.exs | bnns/state_server | d62dcd7c8d261e057764c39370b6ac5a63f11aa4 | [
"MIT"
] | 39 | 2019-09-07T21:29:09.000Z | 2020-05-05T15:01:30.000Z | test/callbacks/handle_continue_test.exs | bnns/state_server | d62dcd7c8d261e057764c39370b6ac5a63f11aa4 | [
"MIT"
] | 2 | 2020-01-04T05:44:25.000Z | 2020-01-19T21:44:41.000Z | defmodule StateServerTest.Callbacks.HandleContinueTest do
use ExUnit.Case, async: true
defmodule Instrumented do
use StateServer, [start: [tr: :end], end: []]
def start_link(fun), do: StateServer.start_link(__MODULE__, fun)
@impl true
def init(fun), do: fun.()
@impl true
def handle_continue(:continuation, _state, fun), do: fun.()
@impl true
def handle_call(:call, _from, _state, _fun) do
{:reply, :ok, continue: :continuation}
end
end
describe "instrumenting handle_continue" do
test "works from the init function" do
test_pid = self()
internal_function = fn ->
receive do :unblock -> :ok end
send(test_pid, :initialized)
end
{:ok, pid} = Instrumented.start_link(fn ->
{:ok, internal_function, continue: :continuation}
end)
refute_receive :initialized
send(pid, :unblock)
assert_receive :initialized
end
test "works from a generic call function" do
test_pid = self()
internal_function = fn ->
receive do :unblock -> :ok end
send(test_pid, :continued)
end
{:ok, pid} = Instrumented.start_link(fn ->
{:ok, internal_function}
end)
assert :ok == GenServer.call(pid, :call)
refute_receive :continued
send(pid, :unblock)
assert_receive :continued
end
end
defmodule UnInstrumented do
use StateServer, [start: [tr: :end], end: []]
def start_link(_), do: StateServer.start_link(__MODULE__, :ok)
@impl true
def init(_), do: {:ok, :ok}
@impl true
def handle_call(:go, _, _, _) do
{:reply, :ok, continue: "foo"}
end
end
describe "tests against uninstrumented code" do
test "should throw a runtime error" do
Process.flag(:trap_exit, true)
{:ok, srv} = UnInstrumented.start_link(:ok)
StateServer.call(srv, :go)
assert_receive {:EXIT, ^srv, {%RuntimeError{message: msg}, _}}
assert msg =~ "handle_continue/3"
end
end
end
| 24.119048 | 68 | 0.62537 |
ffea2b4e389e0d8df0fa62d95e3692201cfd3109 | 299 | ex | Elixir | lib/mtg/response.ex | naps62/mtg-sdk-elixir | de2d05b5f0b15dc83ed13b558f45ed82046d0f39 | [
"MIT"
] | null | null | null | lib/mtg/response.ex | naps62/mtg-sdk-elixir | de2d05b5f0b15dc83ed13b558f45ed82046d0f39 | [
"MIT"
] | null | null | null | lib/mtg/response.ex | naps62/mtg-sdk-elixir | de2d05b5f0b15dc83ed13b558f45ed82046d0f39 | [
"MIT"
] | null | null | null | defmodule MTG.Response do
def get_key({:ok, %HTTPoison.Response{body: %{error: error}}} = b, _) do
{:error, error}
end
def get_key({:ok, %HTTPoison.Response{body: body}}, key) do
case Map.get(body, key) do
nil -> {:error, body}
result -> {:ok, result}
end
end
end
| 23 | 74 | 0.595318 |
ffea33c3a539d703bcdc8f7c81da370564d49970 | 1,640 | ex | Elixir | deps/absinthe/lib/absinthe/phase/document/validation/unique_fragment_names.ex | JoakimEskils/elixir-absinthe | d81e24ec7c7b1164e6d152101dd50422f192d7e9 | [
"MIT"
] | 3 | 2017-06-22T16:33:58.000Z | 2021-07-07T15:21:09.000Z | lib/absinthe/phase/document/validation/unique_fragment_names.ex | bruce/absinthe | 19b63d3aaa9fb75aad01ffd5e91d89e0b30d7f91 | [
"MIT"
] | null | null | null | lib/absinthe/phase/document/validation/unique_fragment_names.ex | bruce/absinthe | 19b63d3aaa9fb75aad01ffd5e91d89e0b30d7f91 | [
"MIT"
] | null | null | null | defmodule Absinthe.Phase.Document.Validation.UniqueFragmentNames do
@moduledoc false
# Validates document to ensure that all fragments have unique names.
alias Absinthe.{Blueprint, Phase}
use Absinthe.Phase
use Absinthe.Phase.Validation
@doc """
Run the validation.
"""
@spec run(Blueprint.t, Keyword.t) :: Phase.result_t
def run(input, _options \\ []) do
fragments = for fragment <- input.fragments do
process(fragment, input.fragments)
end
result = %{input | fragments: fragments}
{:ok, result}
end
@spec process(Blueprint.Document.Fragment.Named.t, [Blueprint.Document.Fragment.Named.t]) ::
Blueprint.Document.Fragment.Named.t
defp process(fragment, fragments) do
if duplicate?(fragments, fragment) do
fragment
|> flag_invalid(:duplicate_name)
|> put_error(error(fragment))
else
fragment
end
end
# Whether a duplicate fragment is present
@spec duplicate?([Blueprint.Document.Fragment.Named.t], Blueprint.Document.Fragment.Named.t) :: boolean
defp duplicate?(fragments, fragment) do
Enum.count(fragments, &(&1.name == fragment.name)) > 1
end
# Generate an error for a duplicate fragment.
@spec error(Blueprint.Document.Fragment.Named.t) :: Phase.Error.t
defp error(node) do
%Phase.Error{
phase: __MODULE__,
message: error_message(node.name),
locations: [node.source_location],
}
end
@doc """
Generate an error message for a duplicate fragment.
"""
@spec error_message(String.t) :: String.t
def error_message(name) do
~s(There can only be one fragment named "#{name}".)
end
end
| 27.333333 | 105 | 0.693293 |
ffea57f783fdadef0c1b7282f0dd989548f2802c | 2,948 | exs | Elixir | test/exscript/transformers/control_flow_test.exs | craigspaeth/exscript | c3a24790dff0eac592060ba3ae349be7c567e0a7 | [
"MIT"
] | 1 | 2017-12-15T23:55:05.000Z | 2017-12-15T23:55:05.000Z | test/exscript/transformers/control_flow_test.exs | craigspaeth/exscript | c3a24790dff0eac592060ba3ae349be7c567e0a7 | [
"MIT"
] | null | null | null | test/exscript/transformers/control_flow_test.exs | craigspaeth/exscript | c3a24790dff0eac592060ba3ae349be7c567e0a7 | [
"MIT"
] | null | null | null | defmodule ExScript.Compiler.ControlFlowTest do
use ExUnit.Case
test "compiles if expressions" do
ExScript.TestHelper.compare(
"""
a = if true, do: "hi", else: "bai"
""",
"""
let a;
a = true ? 'hi' : 'bai';
"""
)
end
test "compiles if without else expressions" do
ExScript.TestHelper.compare(
"""
a = if true, do: "hi"
""",
"""
let a;
a = true ? 'hi' : null;
"""
)
end
test "compiles if expressions with blocks" do
ExScript.TestHelper.compare(
"""
a = if true do
b = "a"
b <> "hi"
else
a = "b"
a <> "c"
end
""",
"""
let a;
a = true ? (() => {
let b;
b = 'a';
return b + 'hi';
})() : (() => {
let a;
a = 'b';
return a + 'c';
})();
"""
)
end
test "compiles cond expressions" do
ExScript.TestHelper.compare(
"""
val = cond do
1 + 1 == 2 -> "hai"
false -> "bai"
end
""",
"""
let val;
val = (() => {
if (1 + 1 === 2) {
return 'hai';
} else if (false) {
return 'bai';
}
})();
"""
)
end
test "compiles long bodied cond expressions" do
ExScript.TestHelper.compare(
"""
val = cond do
1 + 1 == 2 ->
a = "foo"
b = "bar"
a <> b
false -> "bai"
end
""",
"""
let val;
val = (() => {
if (1 + 1 === 2) {
let a, b;
a = 'foo';
b = 'bar';
return a + b;
} else if (false) {
return 'bai';
}
})();
"""
)
end
test "compiles long cond expressions" do
ExScript.TestHelper.compare(
"""
val = cond do
0 -> "a"
1 -> "b"
3 -> "c"
end
""",
"""
let val;
val = (() => {
if (0) {
return 'a';
} else if (1) {
return 'b';
} else if (3) {
return 'c';
}
})();
"""
)
end
test "compiles case expressions" do
ExScript.TestHelper.compare(
"""
val = case "a" do
"a" -> "a"
_ -> "b"
end
""",
"""
let val;
val = (() => {
if ('a' === 'a') {
return 'a';
} else if (true) {
return 'b';
}
})();
"""
)
end
test "compiles variable reassignment considering function args" do
ExScript.TestHelper.compare(
"""
fn (a) ->
c = "foo"
a = "bar" <> c
a
end
""",
"""
a => {
let c;
c = 'foo';
a = 'bar' + c;
return a;
};
"""
)
end
end
| 17.652695 | 68 | 0.340909 |
ffea8337d348579e544e565e3bba82df12e0e50e | 1,556 | ex | Elixir | test/support/data_case.ex | Dhall777/systemstats | 380426af8fc898521201311b11881cc8d2db3388 | [
"BSD-3-Clause"
] | null | null | null | test/support/data_case.ex | Dhall777/systemstats | 380426af8fc898521201311b11881cc8d2db3388 | [
"BSD-3-Clause"
] | null | null | null | test/support/data_case.ex | Dhall777/systemstats | 380426af8fc898521201311b11881cc8d2db3388 | [
"BSD-3-Clause"
] | null | null | null | defmodule Systemstats.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,
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 Systemstats.DataCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
alias Systemstats.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import Systemstats.DataCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Systemstats.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Systemstats.Repo, {:shared, self()})
end
:ok
end
@doc """
A helper that transforms changeset errors into 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} ->
Regex.replace(~r"%{(\w+)}", message, fn _, key ->
opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
end)
end)
end
end
| 27.785714 | 77 | 0.693445 |
ffea837446eed49919d01ec1903717426aed1f68 | 965 | ex | Elixir | lib/cryptopunk/utils.ex | ayrat555/cryptopunk | 9d41028739dd13b762838912f9fa1e18ac1160a8 | [
"MIT"
] | 12 | 2021-10-31T07:10:48.000Z | 2022-02-21T18:13:17.000Z | lib/cryptopunk/utils.ex | ayrat555/cryptopunk | 9d41028739dd13b762838912f9fa1e18ac1160a8 | [
"MIT"
] | null | null | null | lib/cryptopunk/utils.ex | ayrat555/cryptopunk | 9d41028739dd13b762838912f9fa1e18ac1160a8 | [
"MIT"
] | null | null | null | defmodule Cryptopunk.Utils do
@moduledoc """
Utility functions
"""
alias Cryptopunk.Key
@spec hmac_sha512(binary(), binary()) :: binary()
def hmac_sha512(key, data) do
:crypto.mac(:hmac, :sha512, key, data)
end
@spec compress_public_key(Key.t()) :: binary()
def compress_public_key(%Key{key: key, type: :public}) do
{:ok, compressed} = ExSecp256k1.public_key_compress(key)
compressed
end
@spec decompress_public_key(binary()) :: binary()
def decompress_public_key(key) do
{:ok, decompressed} = ExSecp256k1.public_key_decompress(key)
decompressed
end
@spec sha256_hash(binary()) :: binary()
def sha256_hash(binary) do
:crypto.hash(:sha256, binary)
end
@spec ripemd160_hash(binary()) :: binary()
def ripemd160_hash(binary) do
:crypto.hash(:ripemd160, binary)
end
@spec hash160(binary()) :: binary()
def hash160(binary) do
binary
|> sha256_hash()
|> ripemd160_hash()
end
end
| 21.931818 | 64 | 0.676684 |
ffea87eb0f4e6293a5c67571f8f6fbf02cd2dae7 | 909 | exs | Elixir | mix.exs | twist-vector/elixir-complex | be3b40d7ed9c8f5cb74e1877ba6250959e92e085 | [
"Apache-2.0"
] | 3 | 2015-11-22T14:21:14.000Z | 2020-01-13T21:15:00.000Z | mix.exs | twist-vector/elixir-complex | be3b40d7ed9c8f5cb74e1877ba6250959e92e085 | [
"Apache-2.0"
] | 2 | 2020-03-20T21:47:55.000Z | 2022-03-23T18:46:02.000Z | mix.exs | twist-vector/elixir-complex | be3b40d7ed9c8f5cb74e1877ba6250959e92e085 | [
"Apache-2.0"
] | 2 | 2018-09-05T21:07:53.000Z | 2022-03-21T13:10:31.000Z | defmodule Complex.Mixfile do
use Mix.Project
def project do
[app: :complex,
version: "0.3.0",
description: description(),
package: package(),
elixir: "~> 1.1",
deps: deps(),
docs: [extras: []]]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
[applications: [:logger]]
end
defp deps do
[{:ex_doc, "~> 0.22", only: :dev, runtime: false},
{:exprintf, "~> 0.1"},
{:dialyxir, "~> 0.4", only: [:dev]}]
end
defp description do
"""
Complex is a library for types and mathematical functions for complex
numbers.
"""
end
defp package do
[
maintainers: ["Tom Krauss"],
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/twist-vector/elixir-complex.git",
"Docs" => "http://hexdocs.pm/complex"}]
end
end
| 21.642857 | 79 | 0.581958 |
ffeadc5281673c4f4ee663a6e99ec1ff6d9c8413 | 6,993 | ex | Elixir | test/support/factory.ex | edgarkanye/papercups | c9652bee03cf5c3f6d7fc5742740fe13875fd40f | [
"MIT"
] | null | null | null | test/support/factory.ex | edgarkanye/papercups | c9652bee03cf5c3f6d7fc5742740fe13875fd40f | [
"MIT"
] | null | null | null | test/support/factory.ex | edgarkanye/papercups | c9652bee03cf5c3f6d7fc5742740fe13875fd40f | [
"MIT"
] | null | null | null | defmodule ChatApi.Factory do
use ExMachina.Ecto, repo: ChatApi.Repo
# Factories
def account_factory do
%ChatApi.Accounts.Account{
company_name: sequence("some company_name"),
settings: %{}
}
end
def personal_api_key_factory do
%ChatApi.ApiKeys.PersonalApiKey{
account: build(:account),
user: build(:user),
value: sequence("some value"),
label: "some label"
}
end
def browser_replay_event_factory do
%ChatApi.BrowserReplayEvents.BrowserReplayEvent{
account: build(:account),
browser_session: build(:browser_session),
event: %{"foo" => "bar"}
}
end
def browser_session_factory do
%ChatApi.BrowserSessions.BrowserSession{
finished_at: "2010-04-17T14:00:00Z",
metadata: %{},
started_at: "2010-04-17T14:00:00Z"
}
end
def canned_response_factory do
%ChatApi.CannedResponses.CannedResponse{
account: build(:account),
name: sequence("some name"),
content: sequence("some content")
}
end
def company_factory do
%ChatApi.Companies.Company{
account: build(:account),
name: "Test Inc"
}
end
def conversation_factory do
%ChatApi.Conversations.Conversation{
account: build(:account),
customer: build(:customer),
status: "open",
source: "chat"
}
end
def customer_factory do
%ChatApi.Customers.Customer{
first_seen: ~D[2020-01-01],
last_seen_at: ~U[2020-01-05 00:00:00Z],
email: sequence(:email, &"test-#{&1}@test.com"),
account: build(:account),
company: build(:company),
customer_tags: [],
tags: []
}
end
def event_subscription_factory do
%ChatApi.EventSubscriptions.EventSubscription{
account: build(:account),
verified: false,
webhook_url: "some webhook_url",
scope: "some scope"
}
end
def file_factory do
%ChatApi.Files.FileUpload{
account: build(:account),
filename: sequence("some filename"),
file_url: sequence("https://image.jpg"),
content_type: "image/png"
}
end
def github_authorization_factory do
%ChatApi.Github.GithubAuthorization{
access_token: "some access_token",
refresh_token: "some refresh_token",
token_type: "some token_type",
scope: "some scope",
github_installation_id: "some github_installation_id",
account: build(:account),
user: build(:user)
}
end
def google_authorization_factory do
%ChatApi.Google.GoogleAuthorization{
client: "some client",
refresh_token: "some long refresh token",
account: build(:account),
user: build(:user)
}
end
def mattermost_authorization_factory do
%ChatApi.Mattermost.MattermostAuthorization{
access_token: "some access_token",
account: build(:account),
user: build(:user)
}
end
def mention_factory do
%ChatApi.Mentions.Mention{
account: build(:account),
conversation: build(:conversation),
message: build(:message),
user: build(:user)
}
end
def issue_factory do
%ChatApi.Issues.Issue{
title: sequence("some title"),
body: "some body",
state: "unstarted",
account: build(:account),
creator: build(:user)
}
end
def lambda_factory do
%ChatApi.Lambdas.Lambda{
name: sequence("some name"),
description: "some description",
status: "inactive",
code: "var message = 'Hello world!';",
language: "javascript",
runtime: "nodejs14.x",
account: build(:account),
creator: build(:user)
}
end
def message_factory do
%ChatApi.Messages.Message{
account: build(:account),
conversation: build(:conversation),
customer: build(:customer),
user: build(:user),
body: "some message body",
source: "chat"
}
end
def note_factory do
account = build(:account)
%ChatApi.Notes.Note{
body: "some customer note",
customer: build(:customer),
account: account,
author: build(:user, account: account)
}
end
def slack_authorization_factory do
%ChatApi.SlackAuthorizations.SlackAuthorization{
access_token: "some access_token",
app_id: sequence(:app_id, &"some app_id #{&1}"),
authed_user_id: sequence(:authed_user_id, &"some authed_user_id #{&1}"),
bot_user_id: sequence(:bot_user_id, &"some bot_user_id #{&1}"),
channel: "#test",
channel_id: sequence(:channel_id, &"some channel_id #{&1}"),
configuration_url: "some configuration_url",
scope: "some scope",
team_id: sequence(:team_id, &"some team_id #{&1}"),
team_name: sequence(:team_name, &"some team_name #{&1}"),
token_type: "some token_type",
webhook_url: "some webhook_url",
type: "reply",
account: build(:account)
}
end
def twilio_authorization_factory do
%ChatApi.Twilio.TwilioAuthorization{
twilio_auth_token: "some auth token",
twilio_account_sid: "some account id",
from_phone_number: "some phone number",
account: build(:account),
user: build(:user)
}
end
def slack_conversation_thread_factory do
%ChatApi.SlackConversationThreads.SlackConversationThread{
account: build(:account),
conversation: build(:conversation),
slack_thread_ts: sequence("1234.56789"),
slack_channel: "#test"
}
end
def tag_factory do
%ChatApi.Tags.Tag{
account: build(:account),
name: sequence("some name")
}
end
def conversation_tag_factory do
%ChatApi.Tags.ConversationTag{
account: build(:account),
conversation: build(:conversation),
tag: build(:tag),
creator: build(:user)
}
end
def customer_tag_factory do
%ChatApi.Tags.CustomerTag{
account: build(:account),
customer: build(:customer),
tag: build(:tag)
}
end
def user_invitation_factory do
%ChatApi.UserInvitations.UserInvitation{
account: build(:account),
expires_at: DateTime.add(DateTime.utc_now(), :timer.hours(168), :millisecond)
}
end
def user_factory do
%ChatApi.Users.User{
email: sequence(:email, &"company_name-#{&1}@example.com"),
account: build(:account),
password: "supersecret123"
}
end
def user_settings_factory do
%ChatApi.Users.UserSettings{
user: build(:user),
email_alert_on_new_message: true
}
end
def user_profile_factory do
%ChatApi.Users.UserProfile{
user: build(:user),
display_name: "Test User",
full_name: "Testy McTesterson",
profile_photo_url: "https://via.placeholder.com/100x100"
}
end
def with_password_confirmation(user) do
Map.put(user, :password_confirmation, user.password)
end
def widget_settings_factory do
%ChatApi.WidgetSettings.WidgetSetting{
color: "some color",
subtitle: "some subtitle",
title: "some title"
}
end
end
| 25.064516 | 83 | 0.646218 |
ffeaeba073a1e3c2c8852fe1fd956d0938fcd320 | 1,239 | exs | Elixir | test/phoenix/controller/pipeline_test.exs | wojtekmach/phoenix | a6b3bf301c7088b8824a39a165582dc85dfdd2a4 | [
"MIT"
] | null | null | null | test/phoenix/controller/pipeline_test.exs | wojtekmach/phoenix | a6b3bf301c7088b8824a39a165582dc85dfdd2a4 | [
"MIT"
] | null | null | null | test/phoenix/controller/pipeline_test.exs | wojtekmach/phoenix | a6b3bf301c7088b8824a39a165582dc85dfdd2a4 | [
"MIT"
] | null | null | null | defmodule Phoenix.Controller.PipelineTest do
use ExUnit.Case, async: true
use ConnHelper
defmodule MyController do
use Phoenix.Controller
plug :prepend, :before1 when action in [:show, :create]
plug :prepend, :before2
plug :action
plug :prepend, :after1
plug :prepend, :after2
plug :done when not action in [:create]
defp prepend(conn, val) do
update_in conn.private.stack, &[val|&1]
end
defp done(conn, _) do
prepend(conn, :done)
end
def show(conn, _) do
prepend(conn, :action)
end
def create(conn, _) do
prepend(conn, :action)
end
end
setup do
Logger.disable(self())
end
test "invokes the plug stack" do
conn = conn(:get, "/")
|> fetch_params()
|> put_private(:stack, [])
|> MyController.call(:show)
assert conn.private.stack ==
[:done, :after2, :after1, :action, :before2, :before1]
end
test "invokes the plug stack with guards" do
conn = conn(:get, "/")
|> fetch_params()
|> put_private(:stack, [])
|> MyController.call(:create)
assert conn.private.stack ==
[:after2, :after1, :action, :before2, :before1]
end
end
| 22.944444 | 65 | 0.59322 |
ffeafdd2f3afc9bc3ba286f7717ad1972c30367b | 439 | ex | Elixir | tags_service/lib/nlw07_heat_tags/tags/count.ex | miguelriosoliveira/dowhile-mural | 3f616bf7d536f0442b41f6f8795af43ed54e61a0 | [
"MIT"
] | null | null | null | tags_service/lib/nlw07_heat_tags/tags/count.ex | miguelriosoliveira/dowhile-mural | 3f616bf7d536f0442b41f6f8795af43ed54e61a0 | [
"MIT"
] | null | null | null | tags_service/lib/nlw07_heat_tags/tags/count.ex | miguelriosoliveira/dowhile-mural | 3f616bf7d536f0442b41f6f8795af43ed54e61a0 | [
"MIT"
] | null | null | null | defmodule Nlw07HeatTags.Tags.Count do
alias Nlw07HeatTags.Messages.Get
def call do
Get.today_messages()
|> Task.async_stream(&count_words(&1.message))
|> Enum.reduce(%{}, fn elem, acc -> sum_values(elem, acc) end)
end
defp count_words(message) do
message
|> String.split()
|> Enum.frequencies()
end
defp sum_values({:ok, map1}, map2) do
Map.merge(map1, map2, fn _key, value1, value2 -> value1 + value2 end)
end
end
| 21.95 | 71 | 0.697039 |
ffeb8359e64b6a24e41e3cc5794f97d1bece9f29 | 1,000 | ex | Elixir | lib/api_phoenix_jwt_crud/application.ex | melardev/Elixir_Phoenix_Ecto_AuthJwt_Crud | 3c90eafe889b0414ed0f027d7d42bf401682f739 | [
"MIT"
] | null | null | null | lib/api_phoenix_jwt_crud/application.ex | melardev/Elixir_Phoenix_Ecto_AuthJwt_Crud | 3c90eafe889b0414ed0f027d7d42bf401682f739 | [
"MIT"
] | null | null | null | lib/api_phoenix_jwt_crud/application.ex | melardev/Elixir_Phoenix_Ecto_AuthJwt_Crud | 3c90eafe889b0414ed0f027d7d42bf401682f739 | [
"MIT"
] | null | null | null | defmodule ApiPhoenixJwtCrud.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
# List all child processes to be supervised
children = [
# Start the Ecto repository
ApiPhoenixJwtCrud.Repo,
# Start the endpoint when the application starts
ApiPhoenixJwtCrudWeb.Endpoint
# Starts a worker by calling: ApiPhoenixJwtCrud.Worker.start_link(arg)
# {ApiPhoenixJwtCrud.Worker, arg},
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: ApiPhoenixJwtCrud.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
ApiPhoenixJwtCrudWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 31.25 | 76 | 0.734 |
ffeb9a202b8a1f09149a91c146796de9f2e42b57 | 3,370 | exs | Elixir | apps/ewallet/test/ewallet/gates/activity_log_gate_test.exs | jimpeebles/ewallet | ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405 | [
"Apache-2.0"
] | null | null | null | apps/ewallet/test/ewallet/gates/activity_log_gate_test.exs | jimpeebles/ewallet | ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405 | [
"Apache-2.0"
] | null | null | null | apps/ewallet/test/ewallet/gates/activity_log_gate_test.exs | jimpeebles/ewallet | ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule EWallet.ActivityLogGateTest do
use EWallet.DBCase, async: true
import EWalletDB.Factory
alias Ecto.UUID
alias EWallet.{ActivityLogGate}
alias EWallet.Web.V1.ModuleMapper
alias EWalletDB.{User, Token}
alias ActivityLogger.ActivityLog
describe "load_originator_and_target/2" do
test "loads the originator and target structs in the list" do
user = insert(:user)
token = insert(:token)
activity_log1 =
insert(
:activity_log,
%{
originator_type: ActivityLog.get_type(User),
originator_uuid: user.uuid,
target_type: ActivityLog.get_type(Token),
target_uuid: token.uuid
}
)
activity_log2 =
insert(:activity_log, %{
originator_type: ActivityLog.get_type(User),
originator_uuid: user.uuid
# target is set to system in the factory
})
activity_logs = [activity_log1, activity_log2]
assert_raise KeyError, fn -> activity_log1.originator end
assert_raise KeyError, fn -> activity_log1.target end
assert_raise KeyError, fn -> activity_log2.originator end
assert_raise KeyError, fn -> activity_log2.target end
activity_logs = ActivityLogGate.load_originator_and_target(activity_logs, ModuleMapper)
assert Enum.at(activity_logs, 0).originator.uuid == user.uuid
assert Enum.at(activity_logs, 0).target.uuid == token.uuid
assert Enum.at(activity_logs, 1).originator.uuid == user.uuid
assert Enum.at(activity_logs, 1).target == nil
end
test "returns nil originator when the originator_uuid could not be matched" do
random_uuid = UUID.generate()
activity_log =
insert(
:activity_log,
%{
originator_type: ActivityLog.get_type(User),
originator_uuid: random_uuid
}
)
assert_raise KeyError, fn -> activity_log.originator end
activity_logs = ActivityLogGate.load_originator_and_target([activity_log], ModuleMapper)
assert Enum.at(activity_logs, 0).originator_uuid == random_uuid
assert Enum.at(activity_logs, 0).originator == nil
end
test "returns nil target when the target_uuid could not be matched" do
random_uuid = UUID.generate()
activity_log =
insert(
:activity_log,
%{
target_type: ActivityLog.get_type(Token),
target_uuid: random_uuid
}
)
assert_raise KeyError, fn -> activity_log.target end
activity_logs = ActivityLogGate.load_originator_and_target([activity_log], ModuleMapper)
assert Enum.at(activity_logs, 0).target_uuid == random_uuid
assert Enum.at(activity_logs, 0).target == nil
end
end
end
| 32.403846 | 94 | 0.681306 |
ffebfa7dc4ab1b86746daee1b4ba5d9557ccafc2 | 3,130 | ex | Elixir | lib/hexpm/emails/emails.ex | LoisSotoLopez/hexpm | 570558cea855e2928e6f573e7322d0dc63e6f21d | [
"Apache-2.0"
] | 2 | 2020-03-01T18:23:33.000Z | 2021-01-15T10:15:45.000Z | lib/hexpm/emails/emails.ex | LoisSotoLopez/hexpm | 570558cea855e2928e6f573e7322d0dc63e6f21d | [
"Apache-2.0"
] | 3 | 2020-06-30T11:24:41.000Z | 2020-08-05T15:47:34.000Z | lib/hexpm/emails/emails.ex | LoisSotoLopez/hexpm | 570558cea855e2928e6f573e7322d0dc63e6f21d | [
"Apache-2.0"
] | null | null | null | defmodule Hexpm.Emails do
use Bamboo.Phoenix, view: HexpmWeb.EmailView
import Bamboo.Email
alias Hexpm.Accounts.{Email, User}
def owner_added(package, owners, owner) do
email()
|> email_to(owners)
|> subject("Hex.pm - Owner added to package #{package.name}")
|> assign(:username, owner.username)
|> assign(:package, package.name)
|> render(:owner_add)
end
def owner_removed(package, owners, owner) do
email()
|> email_to(owners)
|> subject("Hex.pm - Owner removed from package #{package.name}")
|> assign(:username, owner.username)
|> assign(:package, package.name)
|> render(:owner_remove)
end
def verification(user, email) do
email()
|> email_to(%{email | user: user})
|> subject("Hex.pm - Email verification")
|> assign(:username, user.username)
|> assign(:email, email.email)
|> assign(:key, email.verification_key)
|> render(:verification)
end
def password_reset_request(user, reset) do
email()
|> email_to(user)
|> subject("Hex.pm - Password reset request")
|> assign(:username, user.username)
|> assign(:key, reset.key)
|> render(:password_reset_request)
end
def password_changed(user) do
email()
|> email_to(user)
|> subject("Hex.pm - Your password has changed")
|> assign(:username, user.username)
|> render(:password_changed)
end
def typosquat_candidates(candidates, threshold) do
email()
|> email_to(Application.get_env(:hexpm, :support_email))
|> subject("[TYPOSQUAT CANDIDATES]")
|> assign(:candidates, candidates)
|> assign(:threshold, threshold)
|> render(:typosquat_candidates)
end
def organization_invite(organization, user) do
email()
|> email_to(user)
|> subject("Hex.pm - You have been added to the #{organization.name} organization")
|> assign(:organization, organization.name)
|> assign(:username, user.username)
|> render(:organization_invite)
end
def package_published(user, name, version) do
email()
|> email_to(user)
|> subject("Hex.pm - Package #{name} v#{version} published")
|> assign(:version, version)
|> assign(:package, name)
|> render(:package_published)
end
defp email_to(email, to) do
to =
to
|> List.wrap()
|> Enum.flat_map(&expand_organization/1)
|> Enum.sort()
to(email, to)
end
defp expand_organization(email) when is_binary(email), do: [email]
defp expand_organization(%Email{} = email), do: [email]
defp expand_organization(%User{organization: nil} = user), do: [user]
defp expand_organization(%User{organization: %Ecto.Association.NotLoaded{}} = user), do: [user]
defp expand_organization(%User{organization: organization}) do
organization.organization_users
|> Enum.filter(&(&1.role == "admin"))
|> Enum.map(&User.email(&1.user, :primary))
end
defp email() do
new_email()
|> from(source())
|> put_layout({HexpmWeb.EmailView, :layout})
end
defp source() do
host = Application.get_env(:hexpm, :email_host) || "hex.pm"
{"Hex.pm", "noreply@#{host}"}
end
end
| 28.454545 | 97 | 0.653355 |
ffec18807fe7a0102ec1625ed1a617736d02e442 | 2,034 | ex | Elixir | clients/ad_sense/lib/google_api/ad_sense/v14/model/accounts.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/ad_sense/lib/google_api/ad_sense/v14/model/accounts.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/ad_sense/lib/google_api/ad_sense/v14/model/accounts.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.AdSense.V14.Model.Accounts do
@moduledoc """
## Attributes
* `etag` (*type:* `String.t`, *default:* `nil`) - ETag of this response for caching purposes.
* `items` (*type:* `list(GoogleApi.AdSense.V14.Model.Account.t)`, *default:* `nil`) - The accounts returned in this list response.
* `kind` (*type:* `String.t`, *default:* `adsense#accounts`) - Kind of list this is, in this case adsense#accounts.
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - Continuation token used to page through accounts. To retrieve the next page of results, set the next request's "pageToken" value to this.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:etag => String.t(),
:items => list(GoogleApi.AdSense.V14.Model.Account.t()),
:kind => String.t(),
:nextPageToken => String.t()
}
field(:etag)
field(:items, as: GoogleApi.AdSense.V14.Model.Account, type: :list)
field(:kind)
field(:nextPageToken)
end
defimpl Poison.Decoder, for: GoogleApi.AdSense.V14.Model.Accounts do
def decode(value, options) do
GoogleApi.AdSense.V14.Model.Accounts.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AdSense.V14.Model.Accounts do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.321429 | 200 | 0.70354 |
ffec409d94996869350d866ddbdd5e03c06cdda1 | 11,015 | ex | Elixir | lib/mix/lib/mix/dep.ex | jbcrail/elixir | f30ef15d9d028a6d0f74d10c2bb320d5f8501bdb | [
"Apache-2.0"
] | 1 | 2015-02-23T00:01:48.000Z | 2015-02-23T00:01:48.000Z | lib/mix/lib/mix/dep.ex | jbcrail/elixir | f30ef15d9d028a6d0f74d10c2bb320d5f8501bdb | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/dep.ex | jbcrail/elixir | f30ef15d9d028a6d0f74d10c2bb320d5f8501bdb | [
"Apache-2.0"
] | 1 | 2020-12-07T08:04:16.000Z | 2020-12-07T08:04:16.000Z | defmodule Mix.Dep do
@moduledoc false
@doc """
The Mix.Dep a struct keeps information about your project dependencies.
It contains:
* `scm` - a module representing the source code management tool (SCM)
operations
* `app` - the application name as an atom
* `requirement` - a binary or regex with the dependency's requirement
* `status` - the current status of the dependency, check
`Mix.Dep.format_status/1` for more info
* `opts` - the options given by the developer
* `deps` - dependencies of this dependency
* `top_level` - true if dependency was defined in the top-level project
* `manager` - the project management, possible values:
`:rebar` | `:mix` | `:make` | `nil`
* `from` - path to the file where the dependency was defined
* `extra` - a slot for adding extra configuration based on the manager;
the information on this field is private to the manager and should not be
relied on
A dependency is in two specific states: loaded and unloaded.
When a dependency is unloaded, it means Mix only parsed its specification
and made no attempt to actually load the dependency or validate its
status. When the dependency is loaded, it means Mix attempted to fetch,
load and validate it, the status is set in the status field.
Furthermore, in the `opts` fields, Mix keeps some internal options, which
can be accessed by SCMs:
* `:app` - the application name
* `:dest` - the destination path for the dependency
* `:lock` - the lock information retrieved from mix.lock
* `:build` - the build path for the dependency
"""
defstruct scm: nil, app: nil, requirement: nil, status: nil, opts: [],
deps: [], top_level: false, extra: [], manager: nil, from: nil
@type t :: %__MODULE__{
scm: module,
app: atom,
requirement: String.t | Regex.t,
status: atom,
opts: Keyword.t,
top_level: boolean,
manager: :rebar | :mix | :make | nil,
from: String.t,
extra: term}
@doc """
Returns all children dependencies for the current project,
as well as the defined apps in case of umbrella projects.
The children dependencies returned by this function were
not loaded yet.
## Exceptions
This function raises an exception if any of the dependencies
provided in the project are in the wrong format.
"""
defdelegate children(otps), to: Mix.Dep.Loader
@doc """
Returns loaded dependencies recursively as a `Mix.Dep` struct.
## Exceptions
This function raises an exception if any of the dependencies
provided in the project are in the wrong format.
"""
def loaded(opts) do
Mix.Dep.Converger.converge(nil, nil, opts, &{&1, &2, &3}) |> elem(0)
end
@doc """
Receives a list of dependency names and returns loaded `Mix.Dep`s.
Logs a message if the dependency could not be found.
## Exceptions
This function raises an exception if any of the dependencies
provided in the project are in the wrong format.
"""
def loaded_by_name(given, all_deps \\ nil, opts) do
all_deps = all_deps || loaded(opts)
# Ensure all apps are atoms
apps = to_app_names(given)
# We need to keep the order of deps, loaded/1 properly orders them
deps = Enum.filter(all_deps, &(&1.app in apps))
Enum.each apps, fn(app) ->
unless Enum.any?(all_deps, &(&1.app == app)) do
Mix.raise "Unknown dependency #{app} for environment #{Mix.env}"
end
end
deps
end
@doc """
Runs the given `fun` inside the given dependency project by
changing the current working directory and loading the given
project onto the project stack.
It is expected a loaded dependency as argument.
"""
def in_dependency(dep, post_config \\ [], fun)
def in_dependency(%Mix.Dep{app: app, opts: opts}, config, fun) do
# Set the app_path to be the one stored in the dependency.
# This is important because the name of application in the
# mix.exs file can be different than the actual name and we
# choose to respect the one in the mix.exs
config = Keyword.merge(Mix.Project.deps_config, config)
config = Keyword.put(config, :app_path, opts[:build])
env = opts[:env] || :prod
old_env = Mix.env
try do
Mix.env(env)
Mix.Project.in_project(app, opts[:dest], config, fun)
after
Mix.env(old_env)
end
end
@doc """
Formats the status of a dependency.
"""
def format_status(%Mix.Dep{status: {:ok, _vsn}}),
do: "ok"
def format_status(%Mix.Dep{status: {:noappfile, path}}),
do: "could not find an app file at #{Path.relative_to_cwd(path)}. " <>
"This may happen if the dependency was not yet compiled, " <>
"or you specified the wrong application name in your deps, " <>
"or the dependency indeed has no app file (then you can pass app: false as option)"
def format_status(%Mix.Dep{status: {:invalidapp, path}}),
do: "the app file at #{Path.relative_to_cwd(path)} is invalid"
def format_status(%Mix.Dep{status: {:invalidvsn, vsn}}),
do: "the app file contains an invalid version: #{inspect vsn}"
def format_status(%Mix.Dep{status: {:nomatchvsn, vsn}, requirement: req}),
do: "the dependency does not match the requirement #{inspect req}, got #{inspect vsn}"
def format_status(%Mix.Dep{status: {:lockmismatch, _}}),
do: "lock mismatch: the dependency is out of date"
def format_status(%Mix.Dep{status: :lockoutdated}),
do: "lock outdated: the lock is outdated compared to the options in your mixfile"
def format_status(%Mix.Dep{status: :nolock}),
do: "the dependency is not locked"
def format_status(%Mix.Dep{status: :compile}),
do: "the dependency build is outdated, please run `#{mix_env_var}mix deps.compile`"
def format_status(%Mix.Dep{app: app, status: {:divergedreq, other}} = dep) do
"the dependency #{app} defined\n" <>
"#{dep_status(dep)}" <>
"\n does not match the requirement specified\n" <>
"#{dep_status(other)}" <>
"\n Ensure they match or specify one of the above in your #{inspect Mix.Project.get} deps and set `override: true`"
end
def format_status(%Mix.Dep{app: app, status: {:diverged, other}} = dep) do
"different specs were given for the #{app} app:\n" <>
"#{dep_status(dep)}#{dep_status(other)}" <>
"\n Ensure they match or specify one of the above in your #{inspect Mix.Project.get} deps and set `override: true`"
end
def format_status(%Mix.Dep{app: app, status: {:overridden, other}} = dep) do
"the dependency #{app} in #{Path.relative_to_cwd(dep.from)} is overriding a child dependency:\n" <>
"#{dep_status(dep)}#{dep_status(other)}" <>
"\n Ensure they match or specify one of the above in your #{inspect Mix.Project.get} deps and set `override: true`"
end
def format_status(%Mix.Dep{status: {:unavailable, _}, scm: scm}) do
if scm.fetchable? do
"the dependency is not available, run `mix deps.get`"
else
"the dependency is not available"
end
end
def format_status(%Mix.Dep{status: {:elixirlock, _}}),
do: "the dependency is built with an out-of-date elixir version, run `#{mix_env_var}mix deps.compile`"
defp dep_status(%Mix.Dep{app: app, requirement: req, opts: opts, from: from}) do
info = {app, req, Dict.drop(opts, [:dest, :lock, :env, :build])}
"\n > In #{Path.relative_to_cwd(from)}:\n #{inspect info}\n"
end
@doc """
Checks the lock for the given dependency and update its status accordingly.
"""
def check_lock(%Mix.Dep{scm: scm, app: app, opts: opts} = dep, lock) do
if rev = lock[app] do
opts = Keyword.put(opts, :lock, rev)
end
if available?(dep) do
case scm.lock_status(opts) do
:mismatch ->
status = if rev, do: {:lockmismatch, rev}, else: :nolock
%{dep | status: status, opts: opts}
:outdated ->
# Don't include the lock in the dependency if it is outdated
%{dep | status: :lockoutdated}
:ok ->
if vsn = old_elixir_lock(dep) do
%{dep | status: {:elixirlock, vsn}, opts: opts}
else
%{dep | opts: opts}
end
end
else
%{dep | opts: opts}
end
end
@doc """
Returns true if the dependency is ok.
"""
def ok?(%Mix.Dep{status: {:ok, _}}), do: true
def ok?(%Mix.Dep{}), do: false
@doc """
Checks if a dependency is available. Available dependencies
are the ones that can be loaded.
"""
def available?(%Mix.Dep{status: {:overridden, _}}), do: false
def available?(%Mix.Dep{status: {:diverged, _}}), do: false
def available?(%Mix.Dep{status: {:divergedreq, _}}), do: false
def available?(%Mix.Dep{status: {:unavailable, _}}), do: false
def available?(%Mix.Dep{}), do: true
@doc """
Formats a dependency for printing.
"""
def format_dep(%Mix.Dep{scm: scm, app: app, status: status, opts: opts}) do
version =
case status do
{:ok, vsn} when vsn != nil -> "#{vsn} "
_ -> ""
end
"#{app} #{version}(#{scm.format(opts)})"
end
@doc """
Returns all load paths for the given dependency.
Automatically derived from source paths.
"""
def load_paths(%Mix.Dep{opts: opts} = dep) do
build_path = Path.dirname(opts[:build])
Enum.map source_paths(dep), fn path ->
Path.join [build_path, Path.basename(path), "ebin"]
end
end
@doc """
Returns all source paths.
Source paths are the directories that contains ebin files for a given
dependency. All managers, except rebar, have only one source path.
"""
def source_paths(%Mix.Dep{manager: :rebar, opts: opts, extra: extra}) do
# Add root dir and all sub dirs with ebin/ directory
sub_dirs = Enum.map(extra[:sub_dirs] || [], fn path ->
Path.join(opts[:dest], path)
end)
[opts[:dest] | sub_dirs]
|> Enum.map(&Path.wildcard(&1))
|> Enum.concat
|> Enum.filter(fn p -> p |> Path.join("ebin") |> File.dir? end)
end
def source_paths(%Mix.Dep{opts: opts}) do
[opts[:dest]]
end
@doc """
Return `true` if dependency is a mix project.
"""
def mix?(%Mix.Dep{manager: manager}) do
manager == :mix
end
@doc """
Return `true` if dependency is a rebar project.
"""
def rebar?(%Mix.Dep{manager: manager}) do
manager == :rebar
end
@doc """
Return `true` if dependency is a make project.
"""
def make?(%Mix.Dep{manager: manager}) do
manager == :make
end
## Helpers
defp mix_env_var do
if Mix.env == :dev do
""
else
"MIX_ENV=#{Mix.env} "
end
end
defp to_app_names(given) do
Enum.map given, fn(app) ->
if is_binary(app), do: String.to_atom(app), else: app
end
end
defp old_elixir_lock(%Mix.Dep{opts: opts}) do
old_vsn = Mix.Dep.Lock.elixir_vsn(opts[:build])
if old_vsn && old_vsn != System.version do
old_vsn
end
end
end
| 31.743516 | 120 | 0.643032 |
ffec6386d334031fd5fe06d5dc777bc68a47a309 | 5,418 | ex | Elixir | web/controllers/page_controller.ex | nabbisen/journey-planner | 82aa6e081504dfe3a9b2b191b40819404b9fd26b | [
"MIT"
] | null | null | null | web/controllers/page_controller.ex | nabbisen/journey-planner | 82aa6e081504dfe3a9b2b191b40819404b9fd26b | [
"MIT"
] | null | null | null | web/controllers/page_controller.ex | nabbisen/journey-planner | 82aa6e081504dfe3a9b2b191b40819404b9fd26b | [
"MIT"
] | null | null | null | defmodule JrnyPlnr.PageController do
use Phoenix.Controller
plug :action
def index(conn, _params) do
conn = delete_session(conn, :uid)
render conn, "index.html"
end
def home(conn, _params) do
uid = get_session(conn, :uid)
if uid != nil do
conn = put_session(conn, :uid, uid)
render conn, "home.html", uid: uid
else
index(conn, nil)
end
end
def login(conn, %{"uid" => uid, "passwd" => passwd}) do
usr = JrnyPlnr.Muser.authenticates(uid, passwd)
if usr != nil do
conn = put_session(conn, :uid, uid)
render conn, "home.html", uid: uid
else
render conn, "index.html", uid: uid, error: "Correct Id or password, plz."
end
end
def signin(conn, _params) do
render conn, "signin.html"
end
def signup(conn, %{"uid" => uid, "passwd" => passwd, "gvn_name" => gvn_name, "mdl_name" => mdl_name, "fml_name" => fml_name, "birth_date" => birth_date, "mail" => mail}) do
#TODO error case
if JrnyPlnr.Muser.exists(uid) == nil do
JrnyPlnr.Muser.insert(uid, passwd, gvn_name, mdl_name, fml_name, convert_string_to_date(birth_date), mail)
conn = put_session(conn, :uid, uid)
render conn, "home.html", uid: uid, gvn_name: "New comer : #{gvn_name}"
else
#TODO error msg
render conn, "signin.html", error: "Your Id already exists."
end
end
def plan(conn, _params) do
uid = get_session(conn, :uid)
if uid != nil do
conn = put_session(conn, :uid, uid)
render conn, "plan.html", uid: uid
else
index(conn, nil)
end
end
def sch(conn, _params) do
uid = get_session(conn, :uid)
if uid != nil do
plan = JrnyPlnr.Tplan.select_all(uid)
#TODO transger to ajax
sch = JrnyPlnr.Tsch.select_all(uid)
conn = put_session(conn, :uid, uid)
render conn, "sch.html", uid: uid, plan: plan, sch: sch
else
index(conn, nil)
end
end
def map(conn, _params) do
uid = get_session(conn, :uid)
if uid != nil do
sch = JrnyPlnr.Tsch.select_all(uid)
conn = put_session(conn, :uid, uid)
render conn, "map.html", uid: uid, sch: sch
else
index(conn, nil)
end
end
def calendar(conn, _params) do
uid = get_session(conn, :uid)
if uid != nil do
sch = JrnyPlnr.Tsch.select_all(uid)
conn = put_session(conn, :uid, uid)
render conn, "calendar.html", uid: uid, sch: sch
else
index(conn, nil)
end
end
def pears(conn, _params) do
uid = get_session(conn, :uid)
if uid != nil do
conn = put_session(conn, :uid, uid)
render conn, "pears.html", uid: uid
else
index(conn, nil)
end
end
def comm(conn, _params) do
uid = get_session(conn, :uid)
if uid != nil do
conn = put_session(conn, :uid, uid)
render conn, "comm.html", uid: uid
else
index(conn, nil)
end
end
def profile(conn, _params) do
uid = get_session(conn, :uid)
if uid != nil do
conn = put_session(conn, :uid, uid)
render conn, "profile.html", uid: uid
else
index(conn, nil)
end
end
def ins_sch(conn, _params) do
uid = get_session(conn, :uid)
if uid != nil do
JrnyPlnr.Tsch.insert(uid, String.to_integer(_params["plan_no"]), convert_string_to_datetime(_params["start_ts"]), convert_string_to_datetime(_params["end_ts"]), String.to_float(_params["lat"]), String.to_float(_params["lng"]), _params["place_name"], _params["detail"])
sch = JrnyPlnr.Tsch.select_all(uid)
conn = put_session(conn, :uid, uid)
render conn, "map.html", uid: uid, sch: sch
else
index(conn, nil)
end
end
def upd_sch(conn, _params) do
uid = get_session(conn, :uid)
if uid != nil do
JrnyPlnr.Tsch.update(uid, String.to_integer(_params["plan_no"]), String.to_integer(_params["sch_no"]), convert_string_to_datetime(_params["start_ts"]), convert_string_to_datetime(_params["end_ts"]), _params["place_name"], _params["detail"])
conn = put_session(conn, :uid, uid)
json conn, 201
else
index(conn, nil)
end
end
def del_sch(conn, _params) do
uid = get_session(conn, :uid)
if uid != nil do
JrnyPlnr.Tsch.delete(uid, String.to_integer(_params["plan_no"]), String.to_integer(_params["sch_no"]))
conn = put_session(conn, :uid, uid)
json conn, 201
else
index(conn, nil)
end
end
def not_found(conn, _params) do
render conn, "not_found.html"
end
def error(conn, _params) do
conn = delete_session(conn, :uid)
render conn, "error.html"
end
defp convert_string_to_date(date) do
ymd = String.split(date, "/")
#TODO condition
if Enum.count(ymd) == 3 do
%Ecto.Date{year: String.to_integer(Enum.at(ymd, 0)), month: String.to_integer(Enum.at(ymd, 1)), day: String.to_integer(Enum.at(ymd, 2))}
else
nil
end
end
defp convert_string_to_datetime(datetime) do
dt = String.split(datetime, " ")
ymd = String.split(Enum.at(dt, 0), "/")
hm = String.split(Enum.at(dt, 1), ":")
#TODO condition
if Enum.count(ymd) == 3 and Enum.count(hm) == 2 do
%Ecto.DateTime{year: String.to_integer(Enum.at(ymd, 0)), month: String.to_integer(Enum.at(ymd, 1)), day: String.to_integer(Enum.at(ymd, 2)), hour: String.to_integer(Enum.at(hm, 0)), min: String.to_integer(Enum.at(hm, 1)), sec: 0}
else
nil
end
end
end
| 28.819149 | 274 | 0.626061 |
ffec72bffb75be2b8068cea671a8d540110d48f0 | 2,639 | ex | Elixir | lib/eight.ex | mitchellhenke/AdventOfCode2020 | 8d5e89ce0d17697396344e35f76a24e4580d25dd | [
"MIT"
] | null | null | null | lib/eight.ex | mitchellhenke/AdventOfCode2020 | 8d5e89ce0d17697396344e35f76a24e4580d25dd | [
"MIT"
] | null | null | null | lib/eight.ex | mitchellhenke/AdventOfCode2020 | 8d5e89ce0d17697396344e35f76a24e4580d25dd | [
"MIT"
] | null | null | null | defmodule Adventofcode2020.Eight do
@external_resource "data/eight.txt"
@instructions File.read!("data/eight.txt")
|> String.split("\n", trim: true)
|> Enum.with_index()
|> Enum.reduce(%{}, fn {instruction, index}, acc ->
Map.put(acc, index + 1, instruction)
end)
def first do
executed_instructions = MapSet.new()
acc = 0
current_line = 1
first(acc, current_line, executed_instructions, @instructions)
end
def second do
Enum.reduce_while(@instructions, nil, fn {line, instruction}, nil ->
cond do
String.contains?(instruction, "jmp") ->
changed_instructions =
Map.put(@instructions, line, String.replace(instruction, "jmp", "nop"))
second(0, 1, MapSet.new(), changed_instructions)
|> case do
{:error, :infinite} ->
{:cont, nil}
{:success, acc} ->
{:halt, acc}
end
String.contains?(instruction, "nop") ->
changed_instructions =
Map.put(@instructions, line, String.replace(instruction, "nop", "jmp"))
second(0, 1, MapSet.new(), changed_instructions)
|> case do
{:error, :infinite} ->
{:cont, nil}
{:success, acc} ->
{:halt, acc}
end
true ->
{:cont, nil}
end
end)
end
def second(acc, line, executed_instructions, instructions) do
cond do
MapSet.member?(executed_instructions, line) ->
{:error, :infinite}
line == 623 ->
{:success, acc}
true ->
executed_instructions = MapSet.put(executed_instructions, line)
{acc, next_line} = next_instruction(acc, line, instructions)
second(acc, next_line, executed_instructions, instructions)
end
end
def first(acc, line, executed_instructions, instructions) do
if MapSet.member?(executed_instructions, line) do
acc
else
executed_instructions = MapSet.put(executed_instructions, line)
{acc, next_line} = next_instruction(acc, line, instructions)
first(acc, next_line, executed_instructions, instructions)
end
end
defp next_instruction(acc, line, instructions) do
instruction = Map.fetch!(instructions, line)
case String.split(instruction, " ") do
["nop", _] ->
{acc, line + 1}
["jmp", jmp_instruction] ->
{acc, String.to_integer(jmp_instruction) + line}
["acc", acc_instruction] ->
{String.to_integer(acc_instruction) + acc, line + 1}
end
end
end
| 27.778947 | 83 | 0.58166 |
ffec8bae8cb80f1f50bf4b9fac3b5a7b492aec49 | 982 | exs | Elixir | config/test.exs | danielhessell/wabanex | c0ad713a558a3cd52ca83bd22cd093e3c3c1b0f5 | [
"MIT"
] | null | null | null | config/test.exs | danielhessell/wabanex | c0ad713a558a3cd52ca83bd22cd093e3c3c1b0f5 | [
"MIT"
] | null | null | null | config/test.exs | danielhessell/wabanex | c0ad713a558a3cd52ca83bd22cd093e3c3c1b0f5 | [
"MIT"
] | null | null | null | import Config
# Configure your database
#
# The MIX_TEST_PARTITION environment variable can be used
# to provide built-in test partitioning in CI environment.
# Run `mix help test` for more information.
config :wabanex, Wabanex.Repo,
username: "postgres",
password: "postgres",
hostname: "localhost",
database: "wabanex_test#{System.get_env("MIX_TEST_PARTITION")}",
pool: Ecto.Adapters.SQL.Sandbox,
pool_size: 10
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :wabanex, WabanexWeb.Endpoint,
http: [ip: {127, 0, 0, 1}, port: 4002],
secret_key_base: "elypBVOR7Qen/2A8h5/EQTrxldLFe11ZTzvDUjQqQXIzBy3ywPY5fuDtIR5hu9Ok",
server: false
# In test we don't send emails.
config :wabanex, Wabanex.Mailer, adapter: Swoosh.Adapters.Test
# Print only warnings and errors during test
config :logger, level: :warn
# Initialize plugs at runtime for faster test compilation
config :phoenix, :plug_init_mode, :runtime
| 31.677419 | 86 | 0.759674 |
ffecc2ad761332805e4769ec1be38ea0753e4d32 | 1,486 | ex | Elixir | lib/passages.ex | hermanstehouwer/adventofcode2021 | 9000f0d3d96825f9ca1bb047cd7530e336022a16 | [
"CC0-1.0"
] | null | null | null | lib/passages.ex | hermanstehouwer/adventofcode2021 | 9000f0d3d96825f9ca1bb047cd7530e336022a16 | [
"CC0-1.0"
] | null | null | null | lib/passages.ex | hermanstehouwer/adventofcode2021 | 9000f0d3d96825f9ca1bb047cd7530e336022a16 | [
"CC0-1.0"
] | null | null | null | defmodule Passages do
@type graph::%{String.t() => [String.t()]}
@type path::String.t()
def input_to_graph_reducer([e1, e2], acc) do
acc
|> Map.update(e1, [e2], fn x -> x ++ [e2] end)
|> Map.update(e2, [e1], fn x -> x ++ [e1] end)
end
@spec input_to_graph([String.t()])::graph()
def input_to_graph(input) do
Enum.map(input, fn x -> String.split(x, "-", trim: true) end)
|> Enum.reduce(%{}, &input_to_graph_reducer/2)
end
defp downcase?(input), do: input == String.downcase(input)
defp get_filter(list, twice)
defp get_filter(list, false) do
{Enum.filter(list, &downcase?/1), false}
end
defp get_filter(list, true) do
{filter_a, false} = get_filter(list, false)
filter_b = filter_a -- Enum.uniq(filter_a)
if length(filter_b) > 0 do
# We already have a lowercased cave that we visited twice. So back to regular filtering
{filter_a, false}
else
{["start"], true} # We are not allowed to visit "start" twice
end
end
@spec find_all_paths(graph(), [String.t()], boolean())::[path()]
def find_all_paths(graph, partial_path, twice \\ false)
def find_all_paths(_graph, ["end"|tl], _twice) do
[Enum.join(["end"|tl], "-")]
end
def find_all_paths(graph, [hd|tl], twice) do
{filter, newtwice} = get_filter([hd|tl], twice)
graph[hd] |> Enum.filter(fn x -> !(x in filter) end)
|> Enum.map(fn x -> find_all_paths(graph, [x|[hd|tl]], newtwice) end)
|> List.flatten()
end
end
| 30.326531 | 93 | 0.625168 |
ffecdc3fe0d114d22e456f2a3aee721a23819f05 | 221 | ex | Elixir | lib/webkontist_web/controllers/page_controller.ex | lorenzosinisi/webkontist | 6af002ece0eb56b83c8d26d7f7e7ef6ca6e1562f | [
"MIT"
] | null | null | null | lib/webkontist_web/controllers/page_controller.ex | lorenzosinisi/webkontist | 6af002ece0eb56b83c8d26d7f7e7ef6ca6e1562f | [
"MIT"
] | 1 | 2021-05-10T13:24:52.000Z | 2021-05-10T13:24:52.000Z | lib/webkontist_web/controllers/page_controller.ex | lorenzosinisi/webkontist | 6af002ece0eb56b83c8d26d7f7e7ef6ca6e1562f | [
"MIT"
] | null | null | null | defmodule WebKontistWeb.PageController do
use WebKontistWeb, :controller
alias Phoenix.LiveView
def index(conn, _) do
LiveView.Controller.live_render(conn, WebKontistWeb.DashboardLive, session: %{})
end
end
| 22.1 | 84 | 0.773756 |
ffed385cd1aa72594a15d4dced0c1e84a5f85d99 | 6,771 | exs | Elixir | test/chat_api/users_test.exs | aboutphilippe/papercups | 30364cc562f41cd9d5a7ca5357b16ab8484bd5c9 | [
"MIT"
] | 1 | 2021-06-17T03:17:24.000Z | 2021-06-17T03:17:24.000Z | test/chat_api/users_test.exs | aboutphilippe/papercups | 30364cc562f41cd9d5a7ca5357b16ab8484bd5c9 | [
"MIT"
] | null | null | null | test/chat_api/users_test.exs | aboutphilippe/papercups | 30364cc562f41cd9d5a7ca5357b16ab8484bd5c9 | [
"MIT"
] | null | null | null | defmodule ChatApi.UsersTest do
use ChatApi.DataCase, async: true
require Logger
@moduledoc false
import ChatApi.Factory
alias ChatApi.Repo
alias ChatApi.Users
alias ChatApi.Users.{User, UserProfile, UserSettings}
describe "user" do
setup do
{:ok, user: insert(:user)}
end
test "delete/1 deletes user's associated data", %{user: user} do
user_profile = insert(:user_profile, user: user)
user_settings = insert(:user_settings, user: user)
conversation = insert(:conversation, assignee: user)
message = insert(:message, user: user, conversation: conversation)
google_authorization = insert(:google_authorization, user: user)
tag = insert(:tag, creator: user)
conversation_tag = insert(:conversation_tag, creator: user)
note = insert(:note, author: user)
file = insert(:file, user: user)
{:ok, _user} = Users.delete_user(user)
assert Repo.get(UserSettings, user_settings.id) == nil
assert Repo.get(UserProfile, user_profile.id) == nil
assert Repo.get(ChatApi.Messages.Message, message.id) == nil
assert Repo.get(ChatApi.Conversations.Conversation, conversation.id).assignee_id == nil
assert Repo.get(ChatApi.Google.GoogleAuthorization, google_authorization.id) == nil
assert Repo.get(ChatApi.Tags.Tag, tag.id).creator_id == nil
assert Repo.get(ChatApi.Tags.ConversationTag, conversation_tag.id).creator_id == nil
assert Repo.get(ChatApi.Notes.Note, note.id) == nil
assert Repo.get(ChatApi.Files.FileUpload, file.id) == nil
end
end
describe "user_profiles" do
@valid_attrs %{
display_name: "some display_name",
full_name: "some full_name",
profile_photo_url: "some profile_photo_url"
}
@update_attrs %{
display_name: "some updated display_name",
full_name: "some updated full_name",
profile_photo_url: "some updated profile_photo_url"
}
setup do
{:ok, user: insert(:user)}
end
test "set_admin_role/1 sets the user's role to 'admin'", %{user: user} do
assert {:ok, %User{role: "admin"}} = Users.set_admin_role(user)
end
test "set_user_role/1 sets the user's role to 'user'", %{user: user} do
assert {:ok, %User{role: "user"}} = Users.set_user_role(user)
end
test "disable_user/1 disables the user", %{user: user} do
assert {:ok, %User{disabled_at: disabled_at}} = Users.disable_user(user)
assert disabled_at != nil
end
test "archive_user/1 archives the user", %{user: user} do
assert {:ok, %User{archived_at: archived_at}} = Users.archive_user(user)
assert archived_at != nil
end
test "get_user_profile/1 returns the user_profile with given valid user id",
%{user: user} do
assert %UserProfile{user_id: id} = Users.get_user_profile(user.id)
assert id == user.id
end
test "update_user_profile/2 with valid data updates the user_profile",
%{user: user} do
assert {:ok, %UserProfile{} = user_profile} =
Users.update_user_profile(user.id, @valid_attrs)
assert user_profile.display_name == @valid_attrs.display_name
assert {:ok, %UserProfile{} = user_profile} =
Users.update_user_profile(user.id, @update_attrs)
assert user_profile.display_name == @update_attrs.display_name
end
test "get_user_profile/1 and Users.get_user_settings/1 get the profile and settings",
%{user: user} do
assert %UserProfile{} = Users.get_user_profile(user.id)
assert %UserSettings{} = Users.get_user_settings(user.id)
end
end
describe "emails" do
@company_name "Test Inc"
setup do
account = insert(:account, company_name: @company_name)
user = insert(:user, account: account)
{:ok, account: account, user: user}
end
test "Emails.format_sender_name/1 returns the company name when no profile is set",
%{account: account, user: user} do
user = Users.get_user_info(user.id)
refute user.profile
assert "Test Inc Team" = ChatApi.Emails.format_sender_name(user, account)
assert "Test Inc Team" = ChatApi.Emails.format_sender_name(user.id, account.id)
end
test "Emails.format_sender_name/1 returns the company name when no display_name or full_name are set",
%{account: account, user: user} do
assert {:ok, %UserProfile{}} =
Users.update_user_profile(user.id, %{display_name: nil, full_name: nil})
user = Users.get_user_info(user.id)
assert "Test Inc Team" = ChatApi.Emails.format_sender_name(user, account)
assert "Test Inc Team" = ChatApi.Emails.format_sender_name(user.id, account.id)
end
test "Emails.format_sender_name/1 prioritizes the display_name if both display_name and full_name are set",
%{account: account, user: user} do
assert {:ok, %UserProfile{}} =
Users.update_user_profile(user.id, %{display_name: "Alex", full_name: "Alex R"})
user = Users.get_user_info(user.id)
assert "Alex" = ChatApi.Emails.format_sender_name(user, account)
assert "Alex" = ChatApi.Emails.format_sender_name(user.id, account.id)
assert {:ok, %UserProfile{}} =
Users.update_user_profile(user.id, %{display_name: nil, full_name: "Alex R"})
user = Users.get_user_info(user.id)
assert "Alex R" = ChatApi.Emails.format_sender_name(user, account)
assert "Alex R" = ChatApi.Emails.format_sender_name(user.id, account.id)
assert {:ok, %UserProfile{}} =
Users.update_user_profile(user.id, %{display_name: "Alex", full_name: nil})
user = Users.get_user_info(user.id)
assert "Alex" = ChatApi.Emails.format_sender_name(user, account)
assert "Alex" = ChatApi.Emails.format_sender_name(user.id, account.id)
end
end
describe "user_settings" do
@valid_attrs %{email_alert_on_new_message: true}
@update_attrs %{email_alert_on_new_message: false}
setup do
{:ok, user: insert(:user)}
end
test "get_user_settings/1 returns the user_settings with given valid user id", %{user: user} do
%UserSettings{user_id: user_id} = Users.get_user_settings(user.id)
assert user_id == user.id
end
test "update_user_settings/2 with valid data updates the user_settings",
%{user: user} do
assert {:ok, %UserSettings{} = user_settings} =
Users.update_user_settings(user.id, @valid_attrs)
assert user_settings.email_alert_on_new_message == true
assert {:ok, %UserSettings{} = user_settings} =
Users.update_user_settings(user.id, @update_attrs)
assert user_settings.email_alert_on_new_message == false
end
end
end
| 35.825397 | 111 | 0.676414 |
ffed4995a0dd26cf07304889a8875b5e22ee2696 | 568 | ex | Elixir | lib/mix/tasks/publish.ex | rubencaro/bottler | f88caf6d0d7d12e88b34e8e0c9a6f372fc6c8edb | [
"MIT"
] | 37 | 2015-05-12T13:26:33.000Z | 2020-02-20T02:43:40.000Z | lib/mix/tasks/publish.ex | rubencaro/bottler | f88caf6d0d7d12e88b34e8e0c9a6f372fc6c8edb | [
"MIT"
] | 4 | 2017-10-20T10:00:00.000Z | 2018-05-13T06:32:35.000Z | lib/mix/tasks/publish.ex | rubencaro/bottler | f88caf6d0d7d12e88b34e8e0c9a6f372fc6c8edb | [
"MIT"
] | 8 | 2015-05-28T10:45:31.000Z | 2018-01-16T07:57:13.000Z | require Bottler.Helpers, as: H
alias Bottler, as: B
defmodule Mix.Tasks.Bottler.Publish do
@moduledoc """
Ship a release file to configured publish servers.
Use like `mix bottler.publish`.
`prod` environment is used by default. Use like
`MIX_ENV=other_env mix bottler.ship` to force it to `other_env`.
"""
use Mix.Task
def run(args) do
{switches, _} = H.parse_args!(args)
H.set_prod_environment
c = H.read_and_validate_config
|> H.validate_branch
|> H.inline_resolve_servers(switches)
B.publish c
end
end
| 19.586207 | 68 | 0.684859 |
ffed89a6be80f22ce15f7119379417850b87b241 | 3,276 | exs | Elixir | test/etfx_test.exs | ckampfe/etfx | 36160c740dddf4405860947590094bbf6834dbb8 | [
"BSD-3-Clause"
] | null | null | null | test/etfx_test.exs | ckampfe/etfx | 36160c740dddf4405860947590094bbf6834dbb8 | [
"BSD-3-Clause"
] | null | null | null | test/etfx_test.exs | ckampfe/etfx | 36160c740dddf4405860947590094bbf6834dbb8 | [
"BSD-3-Clause"
] | null | null | null | defmodule EtfxTest do
use ExUnit.Case
doctest Etfx
import Etfx
test "atom" do
string = <<131, 100, 0, 5, 104, 101, 108, 108, 111>>
assert {:ok, :hello} == binary_to_term(string)
end
test "atom_utf8" do
string = <<131, 118, 0, 5, 104, 101, 108, 108, 111>>
assert {:ok, :hello} == binary_to_term(string)
end
test "small_atom" do
string = <<131, 115, 5, 104, 101, 108, 108, 111>>
assert {:ok, :hello} == binary_to_term(string)
end
test "small_atom_utf8" do
string = <<131, 119, 5, 104, 101, 108, 108, 111>>
assert {:ok, :hello} == binary_to_term(string)
end
test "string" do
string = <<131, 109, 0, 0, 0, 5, 104, 101, 108, 108, 111>>
assert {:ok, "hello"} == binary_to_term(string)
string = <<131, 109, 0, 0, 0, 0>>
assert {:ok, ""} == binary_to_term(string)
end
test "map" do
empty_map = <<131, 116, 0, 0, 0, 0>>
assert {:ok, %{}} == binary_to_term(empty_map)
map = <<
131,
116,
0,
0,
0,
1,
109,
0,
0,
0,
5,
104,
101,
108,
108,
111,
109,
0,
0,
0,
5,
116,
104,
101,
114,
101
>>
assert {:ok, %{"hello" => "there"}} == binary_to_term(map)
no_key = <<131, 116, 0, 0, 0, 1>>
assert {:error, {:expected_input, 1}} == binary_to_term(no_key)
no_value = <<131, 116, 0, 0, 0, 1, 100, 0, 0>>
assert {:error, {:expected_input, 1}} == binary_to_term(no_value)
end
test "empty_list" do
string = <<131, 106>>
assert {:ok, []} == binary_to_term(string)
end
test "list" do
string = <<131, 108, 0, 0, 0, 1>>
assert {:error, {:expected_input, 1}} == binary_to_term(string)
string = <<131, 108, 0, 0, 0, 1, 109, 0, 0, 0, 5, 104, 101, 108, 108, 111, 106>>
assert {:ok, ["hello"]} == binary_to_term(string)
end
test "improper_list" do
improper_list = :erlang.term_to_binary([1 | 2])
assert {:ok, [1, 2]} == binary_to_term(improper_list)
end
test "small_integer" do
string = <<131, 97, 12>>
assert {:ok, 12} == binary_to_term(string)
end
test "integer" do
string = <<131, 98, 255, 255, 255, 244>>
assert {:ok, -12} == binary_to_term(string)
end
test "new_float" do
string = <<131, 70, 64, 64, 12, 204, 204, 204, 204, 205>>
assert {:ok, 32.1} == binary_to_term(string)
end
test "small_tuple" do
small_tuple =
<<131, 104, 5, 100, 0, 1, 49, 100, 0, 1, 50, 100, 0, 1, 51, 100, 0, 1, 52, 100, 0, 1, 53>>
assert {:ok, {:"1", :"2", :"3", :"4", :"5"}} == binary_to_term(small_tuple)
end
test "large_tuple" do
large_tuple = File.read!("fixtures/large_tuple.etf")
parsed = binary_to_term(large_tuple)
atoms =
1..256
|> Enum.map(fn n -> String.to_atom("#{n}") end)
|> List.to_tuple()
assert {:ok, atoms} == parsed
end
test "small_big" do
small_big = File.read!("fixtures/small_big.etf")
assert {:ok, 111_111_111_111_111_111_111_111_111_111_111} == binary_to_term(small_big)
end
test "large_big" do
large_big = File.read!("fixtures/large_big.etf")
expected = :erlang.binary_to_term(large_big)
assert {:ok, expected} == binary_to_term(large_big)
end
end
| 23.4 | 96 | 0.559524 |
ffed951a4a61eedea0f42a208b432c78b05ce788 | 416 | ex | Elixir | lib/queuerbackend/queue.ex | ayushpandey8439/QueuerBackend | 36195b98e02ee8af2b8ba95b9a73547887efb9ce | [
"MIT"
] | null | null | null | lib/queuerbackend/queue.ex | ayushpandey8439/QueuerBackend | 36195b98e02ee8af2b8ba95b9a73547887efb9ce | [
"MIT"
] | null | null | null | lib/queuerbackend/queue.ex | ayushpandey8439/QueuerBackend | 36195b98e02ee8af2b8ba95b9a73547887efb9ce | [
"MIT"
] | null | null | null | defmodule Queuerbackend.Queue do
use Ecto.Schema
import Ecto.Changeset
schema "queues" do
field :head, :string
field :maxLength, :integer
field :name, :string
field :queuers ,{:array, :string}
timestamps()
end
@doc false
def changeset(queue, attrs) do
queue
|> cast(attrs, [:name, :maxLength, :head, :queuers])
|> validate_required([:name, :maxLength, :head])
end
end
| 20.8 | 56 | 0.653846 |
ffedc31c8e6765a2f37f773d3e312c2899b31b4a | 2,572 | ex | Elixir | lib/fire_act.ex | arathunku/fire-act | 2577361f66463ab0741ba9db6f35850f64a0c992 | [
"MIT"
] | 2 | 2019-06-03T18:24:10.000Z | 2019-08-23T08:29:43.000Z | lib/fire_act.ex | arathunku/fire-act | 2577361f66463ab0741ba9db6f35850f64a0c992 | [
"MIT"
] | null | null | null | lib/fire_act.ex | arathunku/fire-act | 2577361f66463ab0741ba9db6f35850f64a0c992 | [
"MIT"
] | null | null | null | defmodule FireAct do
@moduledoc """
Inspired by Plug, a helper module for defining action handlers with
optional params validations via Ecto.Changeset.
Perfect for extracting logic outside the controller endpoints.
Example usage:
```
defmodule RegisterUser do
use FireAct.Handler
use FireAct.ChangesetParams, %{
age: :integer,
email: :string
}
def handle(action, permitted_params) do
MyApp.User.create_changeset(permitted_params)
|> MyApp.Repo.insert()
|> case do
{:ok, user} ->
action |> assign(:user, user)
{:error, error} ->
action |> assign(:error, error) |> fail()
end
end
def validate_params(_action, changeset) do
changeset
|> validate_email()
|> validate_required([:age, :email])
end
defp validate_email(changeset) do
if "valid@example.com" == get_field(changeset, :email) do
changeset
else
changeset
|> add_error(:email, "only valid@example.com is OK")
end
end
end
{:ok, %{assigns: %{user: user}}} = FireAct.run(RegisterUser, %{
age: 1,
email: "valid@example.com"
})
```
"""
alias FireAct.Action
@plug_init_mode Application.get_env(:fire_act, :plug_init_mode, :runtime)
def run(handlers), do: Action.new(%{}, %{}) |> do_run(List.wrap(handlers), [])
def run(%Action{} = action, handlers) do
do_run(action, List.wrap(handlers), [])
end
def run(handlers, params), do: Action.new(params, %{}) |> do_run(List.wrap(handlers), [])
def run(handlers, params, assigns),
do: Action.new(params, assigns) |> do_run(List.wrap(handlers), [])
def plug_init_mode do
@plug_init_mode
end
defp do_run(%Action{} = action, [], _), do: {:ok, action}
defp do_run(%Action{} = action, [handler | handlers], executed_handlers) do
handler.call(action, [])
|> case do
{code, %Action{} = action} when code in ~w(ok error)a -> action
action -> action
end
|> case do
%Action{failed: true} = action ->
rollback_handlers(action, executed_handlers)
%Action{failed: false} = action ->
do_run(action, handlers, [handler | executed_handlers])
end
end
defp rollback_handlers(action, []), do: {:error, action}
defp rollback_handlers(action, [handler | executed_handlers]) do
case handler.rollback(action) do
%FireAct.Action{} = action ->
rollback_handlers(action, executed_handlers)
_ ->
rollback_handlers(action, executed_handlers)
end
end
end
| 25.72 | 91 | 0.629471 |
ffedd57305fe190485501d584a714a4a0ba2db7a | 32 | ex | Elixir | lib/core/utils.ex | naramore/ivy | 171c81a23e0657088c6c5156fb181f58313c03d7 | [
"MIT"
] | null | null | null | lib/core/utils.ex | naramore/ivy | 171c81a23e0657088c6c5156fb181f58313c03d7 | [
"MIT"
] | null | null | null | lib/core/utils.ex | naramore/ivy | 171c81a23e0657088c6c5156fb181f58313c03d7 | [
"MIT"
] | null | null | null | defmodule Ivy.Core.Utils do
end
| 10.666667 | 27 | 0.8125 |
ffee157b2a99978ef8a81dd46f928c6869032b1a | 74 | exs | Elixir | test/vega_web/views/page_view_test.exs | Fudoshiki/vega | 0577024afc734933048645976705784512fbc1f4 | [
"MIT"
] | 4 | 2020-03-22T22:12:29.000Z | 2020-07-01T22:32:01.000Z | test/vega_web/views/page_view_test.exs | Fudoshiki/vega | 0577024afc734933048645976705784512fbc1f4 | [
"MIT"
] | 3 | 2021-03-10T11:53:41.000Z | 2021-10-17T11:18:54.000Z | test/vega_web/views/page_view_test.exs | Fudoshiki/vega | 0577024afc734933048645976705784512fbc1f4 | [
"MIT"
] | 3 | 2020-03-30T19:03:23.000Z | 2022-01-17T20:21:42.000Z | defmodule VegaWeb.PageViewTest do
use VegaWeb.ConnCase, async: true
end
| 18.5 | 35 | 0.810811 |
ffee2cf2c0dc1da2c292c56a305186016438e66a | 226 | ex | Elixir | apps/dtask/lib/dtask/task.ex | fehu/elixir-dtask | 93b39a1acb616cdc7b4fffb4950e82021ef5b0f6 | [
"MIT"
] | null | null | null | apps/dtask/lib/dtask/task.ex | fehu/elixir-dtask | 93b39a1acb616cdc7b4fffb4950e82021ef5b0f6 | [
"MIT"
] | null | null | null | apps/dtask/lib/dtask/task.ex | fehu/elixir-dtask | 93b39a1acb616cdc7b4fffb4950e82021ef5b0f6 | [
"MIT"
] | null | null | null | defmodule DTask.Task do
@moduledoc false
alias DTask.Task.Reporter
@type t() :: module
@type params :: term
@type outcome :: {:success, term} | {:failure, term}
@callback exec(Reporter.t, params) :: outcome
end
| 18.833333 | 54 | 0.668142 |
ffee7e50f91df89e671ce6943ba546a34b8e3475 | 908 | exs | Elixir | mix.exs | bnbfinder/ecto-ulid | 5331f1df423bd4c9378a8e85a21c6c9d3aab4777 | [
"MIT"
] | null | null | null | mix.exs | bnbfinder/ecto-ulid | 5331f1df423bd4c9378a8e85a21c6c9d3aab4777 | [
"MIT"
] | 1 | 2021-06-25T15:47:58.000Z | 2021-06-25T15:47:58.000Z | mix.exs | bnbfinder/ecto-ulid | 5331f1df423bd4c9378a8e85a21c6c9d3aab4777 | [
"MIT"
] | null | null | null | defmodule Ecto.ULID.Mixfile do
use Mix.Project
def project do
[
app: :ecto_ulid,
version: "0.2.0",
elixir: "~> 1.4",
start_permanent: Mix.env == :prod,
deps: deps(),
name: "Ecto.ULID",
description: "An Ecto.Type implementation of ULID.",
package: package(),
source_url: "https://github.com/TheRealReal/ecto-ulid",
homepage_url: "https://github.com/TheRealReal/ecto-ulid",
docs: [main: "Ecto.ULID"],
]
end
def application do
[
extra_applications: [:logger]
]
end
defp package do
[
maintainers: ["David Cuddeback"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/TheRealReal/ecto-ulid"},
]
end
defp deps do
[
{:ecto, "~>3.2"},
{:benchfella, "~> 0.3.5", only: [:dev, :test]},
{:ex_doc, "~> 0.16", only: :dev, runtime: false},
]
end
end
| 21.619048 | 71 | 0.551762 |
ffee95a549e2e5fb4c5c98c97c4e7ff4cb7c5ba3 | 1,748 | ex | Elixir | lib/sockets.ex | arijitdasgupta/exchat | 98ec1562fc1bfb60dfc0fd4231adc29a53160a61 | [
"MIT"
] | null | null | null | lib/sockets.ex | arijitdasgupta/exchat | 98ec1562fc1bfb60dfc0fd4231adc29a53160a61 | [
"MIT"
] | null | null | null | lib/sockets.ex | arijitdasgupta/exchat | 98ec1562fc1bfb60dfc0fd4231adc29a53160a61 | [
"MIT"
] | null | null | null | defmodule Sockets do
require Logger
@behaviour :cowboy_websocket_handler
@timeout 10000000
def init(_, _req, _opts) do
{:upgrade, :protocol, :cowboy_websocket}
end
def websocket_init(_type, req, _opts) do
ChatProcs.addProc(self())
ChatProcs.addMessages(self(), History.getHistory())
{:ok, req, %{}, @timeout}
end
def websocket_handle({:text, message}, req, state) do
{:ok, messageMap} = Poison.decode(message)
case messageMap do
%{"user" => user} -> # Registers user
ChatProcs.setUser(self(), user)
Mappers.createAdminMessage("#{user} joined the chat") |> broadcast()
# TODO Add initial message push
%{"sender" => sender, "message" => message} -> # Sends message to everyone
sender = case ChatProcs.getUser(self()) do
nil -> sender
user -> user
end
Mappers.createMessage(message, sender) |> broadcast()
end
{:ok, req, state}
end
def websocket_info({:broadcast, message}, req, state) do
{:reply, {:text, message}, req, state}
end
def websocket_terminate(_reason, _req, _state) do
# Decides who is leaving the chat
user = case ChatProcs.getUser(self()) do
nil -> "Somebody"
u -> u
end
Mappers.createAdminMessage("#{user} left the chat") |> broadcast()
ChatProcs.removeProc(self())
:ok
end
# TODO modify this to include recent messages
def broadcast(messageJsonEncoded) do
ChatProcs.getAllProcs()
|> Broadcast.call_broadcast(messageJsonEncoded)
end
end | 30.137931 | 86 | 0.573227 |
ffee975676c5757399eec6ad54211f0106e0f4bf | 1,340 | exs | Elixir | test/silver_vine/token/oauth2/refresh_token_test.exs | ritou/elixir-silver-vine-token | b55dde5691a9f96d32570fa329a664dd1652f1de | [
"MIT"
] | null | null | null | test/silver_vine/token/oauth2/refresh_token_test.exs | ritou/elixir-silver-vine-token | b55dde5691a9f96d32570fa329a664dd1652f1de | [
"MIT"
] | 1 | 2021-10-19T10:41:22.000Z | 2021-10-19T10:41:22.000Z | test/silver_vine/token/oauth2/refresh_token_test.exs | ritou/elixir-silver-vine-token | b55dde5691a9f96d32570fa329a664dd1652f1de | [
"MIT"
] | null | null | null | defmodule SilverVine.Token.OAuth2.RefreshTokenTest do
use ExUnit.Case
doctest SilverVine.Token.OAuth2.RefreshToken
alias SilverVine.Token.OAuth2.RefreshToken
alias KittenBlue.JWK
@authz_server "https://server.example.com"
@resource_server "https://resource.example.com"
@user_id "user_id_12345"
@client_id "client_id_12345"
@key [
"kid20200914",
"HS256",
"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ+EstJQLr/T+1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"
]
|> JWK.from_compact()
test "generate, verify" do
current = System.system_time(:second)
expiration = 60 * 60
payload = %{
"iss" => @authz_server,
"exp" => current + expiration,
"aud" => @resource_server,
"sub" => @user_id,
"client_id" => @client_id,
"iat" => current,
"auth_id" => UUID.uuid4()
}
# generate
assert {:ok, token} = RefreshToken.generate(payload, @key)
[encoded_header, _, _] = String.split(token, ".")
assert %{"alg" => "HS256", "kid" => "kid20200914", "typ" => "rt+jwt"} ==
encoded_header |> Base.url_decode64!(padding: false) |> Jason.decode!()
# verify
assert {:ok, verified_payload} = RefreshToken.verify(token, [@key])
assert verified_payload == payload |> Map.put("jti", verified_payload["jti"])
end
end
| 28.510638 | 97 | 0.640299 |
ffeea3321e64d3f15d05f2e03303320825a6010e | 7,339 | exs | Elixir | lib/mix/test/mix/tasks/app.start_test.exs | mertonium/elixir | 74e666156906974082f6b4d34dfbe6988d6465c0 | [
"Apache-2.0"
] | 1 | 2018-10-02T13:55:29.000Z | 2018-10-02T13:55:29.000Z | lib/mix/test/mix/tasks/app.start_test.exs | mertonium/elixir | 74e666156906974082f6b4d34dfbe6988d6465c0 | [
"Apache-2.0"
] | null | null | null | lib/mix/test/mix/tasks/app.start_test.exs | mertonium/elixir | 74e666156906974082f6b4d34dfbe6988d6465c0 | [
"Apache-2.0"
] | null | null | null | Code.require_file("../../test_helper.exs", __DIR__)
defmodule Mix.Tasks.App.StartTest do
use MixTest.Case
defmodule AppStartSample do
def project do
[app: :app_start_sample, version: "0.1.0"]
end
def application do
[applications: [:logger]]
end
end
defmodule WrongElixirProject do
def project do
[app: :error, version: "0.1.0", elixir: "~> 0.8.1"]
end
end
@tag apps: [:app_start_sample]
test "compiles and starts the project" do
Mix.Project.push(AppStartSample)
in_fixture("no_mixfile", fn ->
assert_raise Mix.Error, fn ->
Mix.Tasks.App.Start.run(["--no-compile"])
end
refute List.keyfind(Application.started_applications(), :logger, 0)
Application.start(:logger)
Mix.Tasks.App.Start.run(["--no-start"])
assert File.regular?("_build/dev/lib/app_start_sample/ebin/Elixir.A.beam")
assert File.regular?("_build/dev/lib/app_start_sample/ebin/app_start_sample.app")
assert :code.is_loaded(A)
refute List.keyfind(Application.started_applications(), :app_start_sample, 0)
assert List.keyfind(Application.started_applications(), :logger, 0)
purge([A])
Mix.Tasks.App.Start.run([])
refute :code.is_loaded(A)
assert List.keyfind(Application.started_applications(), :app_start_sample, 0)
assert List.keyfind(Application.started_applications(), :logger, 0)
Mix.Tasks.App.Start.run(["--preload-modules"])
assert :code.is_loaded(A)
end)
end
@tag apps: [:app_start_sample, :app_loaded_sample]
test "start checks for invalid configuration", context do
Mix.Project.push(AppStartSample)
in_tmp(context.test, fn ->
:ok = :application.load({:application, :app_loaded_sample, [vsn: '1.0.0', env: []]})
Mix.ProjectStack.configured_applications([
:app_start_sample,
:app_unknown_sample,
:app_loaded_sample
])
Mix.Tasks.Compile.run([])
Mix.Tasks.App.Start.run([])
assert_received {:mix_shell, :error,
["You have configured application :app_unknown_sample" <> _]}
refute_received {:mix_shell, :error,
["You have configured application :app_loaded_sample" <> _]}
end)
end
@tag apps: [:error]
test "validates Elixir version requirement", context do
Mix.ProjectStack.post_config(elixir: "~> ~> 0.8.1")
Mix.Project.push(WrongElixirProject)
in_tmp(context.test, fn ->
assert_raise Mix.Error, ~r"Invalid Elixir version requirement", fn ->
Mix.Tasks.App.Start.run(["--no-start"])
end
end)
end
@tag apps: [:error]
test "validates the Elixir version with requirement", context do
Mix.Project.push(WrongElixirProject)
in_tmp(context.test, fn ->
assert_raise Mix.ElixirVersionError, ~r/You're trying to run :error on Elixir/, fn ->
Mix.Tasks.App.Start.run(["--no-start"])
end
end)
end
@tag apps: [:error]
test "does not validate the Elixir version with requirement when disabled", context do
Mix.Project.push(WrongElixirProject)
in_tmp(context.test, fn ->
Mix.Tasks.App.Start.run(["--no-start", "--no-elixir-version-check"])
end)
end
test "start does nothing if app is nil" do
assert Mix.Tasks.App.Start.start([app: nil], []) == :ok
end
test "allows type to be configured" do
assert Mix.Tasks.App.Start.type([], permanent: true) == :permanent
assert Mix.Tasks.App.Start.type([], temporary: true) == :temporary
assert Mix.Tasks.App.Start.type([start_permanent: true], []) == :permanent
assert Mix.Tasks.App.Start.type([], []) == :temporary
end
defmodule ReturnSample do
def project do
[app: :return_sample, version: "0.1.0"]
end
def application do
Process.get(:application_definition)
end
end
defmodule ReturnApp do
use Application
def start(_type, return), do: return
end
@tag apps: [:return_sample]
test "start points to report on error", context do
Mix.Project.push(ReturnSample)
in_tmp(context.test, fn ->
Process.put(:application_definition, mod: {ReturnApp, {:error, :bye}})
Mix.Tasks.Compile.run([])
message =
"Could not start application return_sample: " <>
"Mix.Tasks.App.StartTest.ReturnApp.start(:normal, {:error, :bye}) " <>
"returned an error: :bye"
assert_raise Mix.Error, message, fn ->
Mix.Tasks.App.Start.start([app: :return_sample], [])
end
end)
end
@tag apps: [:return_sample]
test "start points to report on exception error", context do
Mix.Project.push(ReturnSample)
in_tmp(context.test, fn ->
mod = {ReturnApp, {:error, {:badarg, [{ReturnApp, :start, 2, []}]}}}
Process.put(:application_definition, mod: mod)
Mix.Tasks.Compile.run([])
message =
"Could not start application return_sample: " <>
"Mix.Tasks.App.StartTest.ReturnApp.start(:normal, {:error, {:badarg, [{Mix.Tasks.App.StartTest.ReturnApp, :start, 2, []}]}}) " <>
"returned an error: an exception was raised:\n" <>
" ** (ArgumentError) argument error\n" <>
" Mix.Tasks.App.StartTest.ReturnApp.start/2"
assert_raise Mix.Error, message, fn ->
Mix.Tasks.App.Start.start([app: :return_sample], [])
end
end)
end
@tag apps: [:return_sample]
test "start points to report on bad return", context do
Mix.Project.push(ReturnSample)
in_tmp(context.test, fn ->
Process.put(:application_definition, mod: {ReturnApp, :bad})
Mix.Tasks.Compile.run([])
message =
"Could not start application return_sample: " <>
"Mix.Tasks.App.StartTest.ReturnApp.start(:normal, :bad) " <>
"returned a bad value: :bad"
assert_raise Mix.Error, message, fn ->
Mix.Tasks.App.Start.start([app: :return_sample], [])
end
end)
end
defmodule ExitSample do
def project do
[app: :exit_sample, version: "0.1.0"]
end
def application do
Process.get(:application_definition)
end
end
defmodule ExitApp do
use Application
def start(_type, reason), do: exit(reason)
end
@tag apps: [:exit_sample]
test "start points to report on exit", context do
Mix.Project.push(ExitSample)
in_tmp(context.test, fn ->
Process.put(:application_definition, mod: {ExitApp, :bye})
Mix.Tasks.Compile.run([])
message =
"Could not start application exit_sample: exited in: " <>
"Mix.Tasks.App.StartTest.ExitApp.start(:normal, :bye)\n" <> " ** (EXIT) :bye"
assert_raise Mix.Error, message, fn ->
Mix.Tasks.App.Start.start([app: :exit_sample], [])
end
end)
end
@tag apps: [:exit_sample]
test "start points to report on normal exit", context do
Mix.Project.push(ExitSample)
in_tmp(context.test, fn ->
Process.put(:application_definition, mod: {ExitApp, :normal})
Mix.Tasks.Compile.run([])
message =
"Could not start application exit_sample: exited in: " <>
"Mix.Tasks.App.StartTest.ExitApp.start(:normal, :normal)\n" <> " ** (EXIT) normal"
assert_raise Mix.Error, message, fn ->
Mix.Tasks.App.Start.start([app: :exit_sample], [])
end
end)
end
end
| 29.592742 | 139 | 0.63837 |
ffeea78c0cae6dca121d9abc8e42c4dee76b0b99 | 1,200 | ex | Elixir | lib/absinthe/type/custom/decimal.ex | hoyon/absinthe | a26b37ec28438c55e89ed558f363e827c24ee631 | [
"MIT"
] | null | null | null | lib/absinthe/type/custom/decimal.ex | hoyon/absinthe | a26b37ec28438c55e89ed558f363e827c24ee631 | [
"MIT"
] | null | null | null | lib/absinthe/type/custom/decimal.ex | hoyon/absinthe | a26b37ec28438c55e89ed558f363e827c24ee631 | [
"MIT"
] | null | null | null | if Code.ensure_loaded?(Decimal) do
defmodule Absinthe.Type.Custom.Decimal do
@moduledoc false
defdelegate serialize(value), to: Decimal, as: :to_string
alias Absinthe.Blueprint.Input
@spec parse(any) :: {:ok, Decimal.t()} | {:ok, nil} | :error
def parse(%Input.String{value: value}) when is_binary(value) do
case Decimal.parse(value) do
# Decimal V2
{decimal, ""} -> {:ok, decimal}
# Decimal V1
{:ok, decimal} -> {:ok, decimal}
_ -> :error
end
end
def parse(%Input.Float{value: value}) when is_float(value) do
decimal = Decimal.from_float(value)
if Decimal.nan?(decimal), do: :error, else: {:ok, decimal}
end
def parse(%Input.Integer{value: value}) when is_integer(value) do
decimal = Decimal.new(value)
if Decimal.nan?(decimal), do: :error, else: {:ok, decimal}
end
def parse(%Input.Null{}) do
{:ok, nil}
end
def parse(_) do
:error
end
end
else
defmodule Absinthe.Type.Custom.Decimal do
@moduledoc false
@spec parse(any) :: :error
def parse(_), do: :error
@spec serialize(any) :: nil
def serialize(_), do: nil
end
end
| 24.489796 | 69 | 0.608333 |
ffeeae82cfc4e29c7f387b9a9a262c3a94d3adfc | 190 | ex | Elixir | lib/type_check/default_overrides/regex.ex | kkentzo/elixir-type_check | bec089445286e4a420d653276e7ba96dd1016876 | [
"MIT"
] | 291 | 2020-07-07T18:14:46.000Z | 2022-03-29T22:36:48.000Z | lib/type_check/default_overrides/regex.ex | kkentzo/elixir-type_check | bec089445286e4a420d653276e7ba96dd1016876 | [
"MIT"
] | 71 | 2020-07-07T11:50:37.000Z | 2022-03-23T21:20:54.000Z | lib/type_check/default_overrides/regex.ex | kkentzo/elixir-type_check | bec089445286e4a420d653276e7ba96dd1016876 | [
"MIT"
] | 12 | 2020-10-07T16:28:22.000Z | 2022-02-17T16:31:05.000Z | defmodule TypeCheck.DefaultOverrides.Regex do
use TypeCheck
@type! t() :: %Elixir.Regex{
opts: binary(),
re_pattern: term(),
re_version: term(),
source: binary()
}
end
| 19 | 45 | 0.642105 |
ffeee584092fcb2454eb74ca69d9288cc0cf2bef | 4,787 | exs | Elixir | test/phoenix_live_view/upload_external_test.exs | jonatanklosko/phoenix_live_view | 95d5c7ccd0ac66e04b15c7b6128d44b60767e682 | [
"MIT"
] | 1 | 2021-04-22T16:40:32.000Z | 2021-04-22T16:40:32.000Z | test/phoenix_live_view/upload_external_test.exs | jonatanklosko/phoenix_live_view | 95d5c7ccd0ac66e04b15c7b6128d44b60767e682 | [
"MIT"
] | null | null | null | test/phoenix_live_view/upload_external_test.exs | jonatanklosko/phoenix_live_view | 95d5c7ccd0ac66e04b15c7b6128d44b60767e682 | [
"MIT"
] | 1 | 2021-01-14T12:58:22.000Z | 2021-01-14T12:58:22.000Z | defmodule Phoenix.LiveView.UploadExternalTest do
use ExUnit.Case, async: true
@endpoint Phoenix.LiveViewTest.Endpoint
import Phoenix.LiveViewTest
alias Phoenix.LiveView
alias Phoenix.LiveViewTest.UploadLive
def inspect_html_safe(term) do
term
|> inspect()
|> Phoenix.HTML.html_escape()
|> Phoenix.HTML.safe_to_string()
end
def run(lv, func) do
GenServer.call(lv.pid, {:run, func})
end
def mount_lv(setup) when is_function(setup, 1) do
conn = Plug.Test.init_test_session(Phoenix.ConnTest.build_conn(), %{})
{:ok, lv, _} = live_isolated(conn, UploadLive, session: %{})
:ok = GenServer.call(lv.pid, {:setup, setup})
{:ok, lv}
end
setup %{allow: opts} do
external = Keyword.fetch!(opts, :external)
opts =
Keyword.put(opts, :external, fn entry, socket ->
apply(__MODULE__, external, [entry, socket])
end)
{:ok, lv} = mount_lv(fn socket -> Phoenix.LiveView.allow_upload(socket, :avatar, opts) end)
{:ok, lv: lv}
end
def preflight(%LiveView.UploadEntry{} = entry, socket) do
new_socket =
Phoenix.LiveView.update(socket, :preflights, fn preflights ->
[entry.client_name | preflights]
end)
{:ok, %{uploader: "S3"}, new_socket}
end
@tag allow: [max_entries: 2, chunk_size: 20, accept: :any, external: :preflight]
test "external upload invokes preflight per entry", %{lv: lv} do
avatar =
file_input(lv, "form", :avatar, [
%{name: "foo1.jpeg", content: String.duplicate("ok", 100)},
%{name: "foo2.jpeg", content: String.duplicate("ok", 100)}
])
assert lv
|> form("form", user: %{})
|> render_change(avatar) =~ "foo1.jpeg:0%"
assert render_upload(avatar, "foo1.jpeg", 1) =~ "foo1.jpeg:1%"
assert render(lv) =~ "preflight:#{UploadLive.inspect_html_safe("foo1.jpeg")}"
assert render(lv) =~ "preflight:#{UploadLive.inspect_html_safe("foo2.jpeg")}"
end
def bad_preflight(%LiveView.UploadEntry{} = _entry, socket), do: {:ok, %{}, socket}
@tag allow: [max_entries: 1, chunk_size: 20, accept: :any, external: :bad_preflight]
test "external preflight raises when missing required :uploader key", %{lv: lv} do
avatar =
file_input(lv, "form", :avatar, [%{name: "foo.jpeg", content: String.duplicate("ok", 100)}])
assert UploadLive.exits_with(lv, avatar, ArgumentError, fn ->
render_upload(avatar, "foo.jpeg", 1) =~ "foo.jpeg:1%"
end) =~ "external uploader metadata requires an :uploader key."
end
def error_preflight(%LiveView.UploadEntry{} = entry, socket) do
if entry.client_name == "bad.jpeg" do
{:error, %{reason: "bad name"}, socket}
else
{:ok, %{uploader: "S3"}, socket}
end
end
@tag allow: [max_entries: 2, chunk_size: 20, accept: :any, external: :error_preflight]
test "preflight with error return", %{lv: lv} do
avatar =
file_input(lv, "form", :avatar, [
%{name: "foo.jpeg", content: String.duplicate("ok", 100)},
%{name: "bad.jpeg", content: String.duplicate("ok", 100)}
])
assert {:error, [[ref, %{reason: "bad name"}]]} = render_upload(avatar, "bad.jpeg", 1)
assert {:error, [[^ref, %{reason: "bad name"}]]} = render_upload(avatar, "foo.jpeg", 1)
assert render(lv) =~ "bad name"
end
@tag allow: [max_entries: 2, chunk_size: 20, accept: :any, external: :preflight]
test "consume_uploaded_entries", %{lv: lv} do
upload_complete = "foo.jpeg:100%"
parent = self()
avatar =
file_input(lv, "form", :avatar, [%{name: "foo.jpeg", content: String.duplicate("ok", 100)}])
assert render_upload(avatar, "foo.jpeg", 100) =~ upload_complete
run(lv, fn socket ->
Phoenix.LiveView.consume_uploaded_entries(socket, :avatar, fn meta, entry ->
send(parent, {:consume, meta, entry.client_name})
end)
{:reply, :ok, socket}
end)
assert_receive {:consume, %{uploader: "S3"}, "foo.jpeg"}
refute render(lv) =~ upload_complete
end
@tag allow: [max_entries: 2, chunk_size: 20, accept: :any, external: :preflight]
test "consume_uploaded_entry", %{lv: lv} do
upload_complete = "foo.jpeg:100%"
parent = self()
avatar =
file_input(lv, "form", :avatar, [%{name: "foo.jpeg", content: String.duplicate("ok", 100)}])
assert render_upload(avatar, "foo.jpeg", 100) =~ upload_complete
run(lv, fn socket ->
{[entry], []} = Phoenix.LiveView.uploaded_entries(socket, :avatar)
Phoenix.LiveView.consume_uploaded_entry(socket, entry, fn meta ->
send(parent, {:individual_consume, meta, entry.client_name})
end)
{:reply, :ok, socket}
end)
assert_receive {:individual_consume, %{uploader: "S3"}, "foo.jpeg"}
refute render(lv) =~ upload_complete
end
end
| 33.711268 | 98 | 0.637769 |
ffef226431a7ac291cce9557f9ced27d76f4c744 | 1,135 | exs | Elixir | gol_elixir/config/config.exs | strika/gol-benchmark | 2c5e92ae0e35f2e1f0ec107109adb8fc23dc0d2a | [
"MIT"
] | null | null | null | gol_elixir/config/config.exs | strika/gol-benchmark | 2c5e92ae0e35f2e1f0ec107109adb8fc23dc0d2a | [
"MIT"
] | null | null | null | gol_elixir/config/config.exs | strika/gol-benchmark | 2c5e92ae0e35f2e1f0ec107109adb8fc23dc0d2a | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# third-party users, it should be done in your "mix.exs" file.
# You can configure your application as:
#
# config :gof_elixir, key: :value
#
# and access this configuration in your application as:
#
# Application.get_env(:gof_elixir, :key)
#
# You can also configure a third-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.612903 | 73 | 0.752423 |
ffef5aa6b357ab31c51005501b6ee186413016a8 | 397 | exs | Elixir | b1/test/b1_web/views/error_view_test.exs | lajeryl/hangman | ad90b6114ac98414b4bddf69bf88b1601b5b1799 | [
"MIT"
] | 1 | 2022-02-22T04:56:25.000Z | 2022-02-22T04:56:25.000Z | b1/test/b1_web/views/error_view_test.exs | lajeryl/hangman | ad90b6114ac98414b4bddf69bf88b1601b5b1799 | [
"MIT"
] | null | null | null | b1/test/b1_web/views/error_view_test.exs | lajeryl/hangman | ad90b6114ac98414b4bddf69bf88b1601b5b1799 | [
"MIT"
] | null | null | null | defmodule B1Web.ErrorViewTest do
use B1Web.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(B1Web.ErrorView, "404.html", []) == "Not Found"
end
test "renders 500.html" do
assert render_to_string(B1Web.ErrorView, "500.html", []) == "Internal Server Error"
end
end
| 26.466667 | 87 | 0.720403 |
ffef6a76c1b583b4f7902ee0717f43960e9089b0 | 131 | ex | Elixir | test/support/api.ex | frankdugan3/ash_phoenix | e776fbc4ec7d7c74d45d519303c4c51667a1e888 | [
"MIT"
] | null | null | null | test/support/api.ex | frankdugan3/ash_phoenix | e776fbc4ec7d7c74d45d519303c4c51667a1e888 | [
"MIT"
] | null | null | null | test/support/api.ex | frankdugan3/ash_phoenix | e776fbc4ec7d7c74d45d519303c4c51667a1e888 | [
"MIT"
] | null | null | null | defmodule AshPhoenix.Test.Api do
@moduledoc false
use Ash.Api
resources do
registry(AshPhoenix.Test.Registry)
end
end
| 14.555556 | 38 | 0.748092 |
ffef8f0227ae9b24b736076c6a08b0c220ee98d6 | 2,153 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/creative_click_through_url.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/creative_click_through_url.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/creative_click_through_url.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.DFAReporting.V34.Model.CreativeClickThroughUrl do
@moduledoc """
Click-through URL
## Attributes
* `computedClickThroughUrl` (*type:* `String.t`, *default:* `nil`) - Read-only convenience field representing the actual URL that will be used for this click-through. The URL is computed as follows: - If landingPageId is specified then that landing page's URL is assigned to this field. - Otherwise, the customClickThroughUrl is assigned to this field.
* `customClickThroughUrl` (*type:* `String.t`, *default:* `nil`) - Custom click-through URL. Applicable if the landingPageId field is left unset.
* `landingPageId` (*type:* `String.t`, *default:* `nil`) - ID of the landing page for the click-through URL.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:computedClickThroughUrl => String.t() | nil,
:customClickThroughUrl => String.t() | nil,
:landingPageId => String.t() | nil
}
field(:computedClickThroughUrl)
field(:customClickThroughUrl)
field(:landingPageId)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V34.Model.CreativeClickThroughUrl do
def decode(value, options) do
GoogleApi.DFAReporting.V34.Model.CreativeClickThroughUrl.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V34.Model.CreativeClickThroughUrl do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.622642 | 357 | 0.740362 |
ffefa1b374afadb1326df45fe6509d7f34cd3e3d | 28,931 | ex | Elixir | lib/phoenix/router.ex | ashkan18/phoenix | 01dc99d4cb3aa1cd6b6486d684aa2a8a810410ef | [
"MIT"
] | null | null | null | lib/phoenix/router.ex | ashkan18/phoenix | 01dc99d4cb3aa1cd6b6486d684aa2a8a810410ef | [
"MIT"
] | null | null | null | lib/phoenix/router.ex | ashkan18/phoenix | 01dc99d4cb3aa1cd6b6486d684aa2a8a810410ef | [
"MIT"
] | null | null | null | defmodule Phoenix.Router do
defmodule NoRouteError do
@moduledoc """
Exception raised when no route is found.
"""
defexception plug_status: 404, message: "no route found", conn: nil, router: nil
def exception(opts) do
conn = Keyword.fetch!(opts, :conn)
router = Keyword.fetch!(opts, :router)
path = "/" <> Enum.join(conn.path_info, "/")
%NoRouteError{message: "no route found for #{conn.method} #{path} (#{inspect router})",
conn: conn, router: router}
end
end
@moduledoc """
Defines a Phoenix router.
The router provides a set of macros for generating routes
that dispatch to specific controllers and actions. Those
macros are named after HTTP verbs. For example:
defmodule MyAppWeb.Router do
use Phoenix.Router
get "/pages/:page", PageController, :show
end
The `get/3` macro above accepts a request to `/pages/hello` and dispatches
it to the `PageController`'s `show` action with `%{"page" => "hello"}` in
`params`.
Phoenix's router is extremely efficient, as it relies on Elixir
pattern matching for matching routes and serving requests.
## Routing
`get/3`, `post/3`, `put/3` and other macros named after HTTP verbs are used
to create routes.
The route:
get "/pages", PageController, :index
matches a `GET` request to `/pages` and dispatches it to the `index` action in
`PageController`.
get "/pages/:page", PageController, :show
matches `/pages/hello` and dispatches to the `show` action with
`%{"path" => "hello"}` in `params`.
defmodule PageController do
def show(conn, params) do
# %{"page" => "hello"} == params
end
end
Partial and multiple segments can be matched. For example:
get "/api/v:version/pages/:id", PageController, :show
matches `/api/v1/pages/2` and puts `%{"version" => "1", "id" => "2"}` in
`params`. Only the trailing part of a segment can be captured.
Routes are matched from top to bottom. The second route here:
get "/pages/:page", PageController, :show
get "/pages/hello", PageController, :hello
will never match `/pages/hello` because `/pages/:page` matches that first.
Routes can use glob-like patterns to match trailing segments.
get "/pages/*page", PageController, :show
matches `/pages/hello/world` and puts the globbed segments in `params["page"]`.
GET /pages/hello/world
%{"page" => ["hello", "world"]} = params
Globs can match segments partially too. The difference is the whole segment
is captured along with the trailing segments.
get "/pages/he*page", PageController, :show
matches
GET /pages/hello/world
%{"page" => ["hello", "world"]} = params
GET /pages/hey/world
%{"page" => ["hey", "world"]} = params
## Helpers
Phoenix automatically generates a module `Helpers` inside your router
which contains named helpers to help developers generate and keep
their routes up to date.
Helpers are automatically generated based on the controller name.
For example, the route:
get "/pages/:page", PageController, :show
will generate the following named helper:
MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello")
"/pages/hello"
MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello", some: "query")
"/pages/hello?some=query"
MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello")
"http://example.com/pages/hello"
MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello", some: "query")
"http://example.com/pages/hello?some=query"
If the route contains glob-like patterns, parameters for those have to be given as
list:
MyAppWeb.Router.Helpers.pages_path(conn_or_endpoint, :show, ["hello", "world"])
"/pages/hello/world"
The URL generated in the named URL helpers is based on the configuration for
`:url`, `:http` and `:https`. However, if for some reason you need to manually
control the URL generation, the url helpers also allow you to pass in a `URI`
struct:
uri = %URI{scheme: "https", host: "other.example.com"}
MyAppWeb.Router.Helpers.page_url(uri, :show, "hello")
"https://other.example.com/pages/hello"
The named helper can also be customized with the `:as` option. Given
the route:
get "/pages/:page", PageController, :show, as: :special_page
the named helper will be:
MyAppWeb.Router.Helpers.special_page_path(conn, :show, "hello")
"/pages/hello"
## Scopes and Resources
It is very common in Phoenix applications to namespace all of your
routes under the application scope:
scope "/", MyAppWeb do
get "/pages/:id", PageController, :show
end
The route above will dispatch to `MyAppWeb.PageController`. This syntax
is not only convenient for developers, since we don't have to repeat
the `MyAppWeb.` prefix on all routes, but it also allows Phoenix to put
less pressure on the Elixir compiler. If instead we had written:
get "/pages/:id", MyAppWeb.PageController, :show
The Elixir compiler would infer that the router depends directly on
`MyAppWeb.PageController`, which is not true. By using scopes, Phoenix
can properly hint to the Elixir compiler the controller is not an
actual dependency of the router. This provides more efficient
compilation times.
Scopes allow us to scope on any path or even on the helper name:
scope "/api/v1", MyAppWeb, as: :api_v1 do
get "/pages/:id", PageController, :show
end
For example, the route above will match on the path `"/api/v1/pages/:id"`
and the named route will be `api_v1_page_path`, as expected from the
values given to `scope/2` option.
Phoenix also provides a `resources/4` macro that allows developers
to generate "RESTful" routes to a given resource:
defmodule MyAppWeb.Router do
use Phoenix.Router
resources "/pages", PageController, only: [:show]
resources "/users", UserController, except: [:delete]
end
Finally, Phoenix ships with a `mix phx.routes` task that nicely
formats all routes in a given router. We can use it to verify all
routes included in the router above:
$ mix phx.routes
page_path GET /pages/:id PageController.show/2
user_path GET /users UserController.index/2
user_path GET /users/:id/edit UserController.edit/2
user_path GET /users/new UserController.new/2
user_path GET /users/:id UserController.show/2
user_path POST /users UserController.create/2
user_path PATCH /users/:id UserController.update/2
PUT /users/:id UserController.update/2
One can also pass a router explicitly as an argument to the task:
$ mix phx.routes MyAppWeb.Router
Check `scope/2` and `resources/4` for more information.
## Pipelines and plugs
Once a request arrives at the Phoenix router, it performs
a series of transformations through pipelines until the
request is dispatched to a desired end-point.
Such transformations are defined via plugs, as defined
in the [Plug](http://github.com/elixir-lang/plug) specification.
Once a pipeline is defined, it can be piped through per scope.
For example:
defmodule MyAppWeb.Router do
use Phoenix.Router
pipeline :browser do
plug :fetch_session
plug :accepts, ["html"]
end
scope "/" do
pipe_through :browser
# browser related routes and resources
end
end
`Phoenix.Router` imports functions from both `Plug.Conn` and `Phoenix.Controller`
to help define plugs. In the example above, `fetch_session/2`
comes from `Plug.Conn` while `accepts/2` comes from `Phoenix.Controller`.
Note that router pipelines are only invoked after a route is found.
No plug is invoked in case no matches were found.
"""
alias Phoenix.Router.{Resource, Scope, Route, Helpers}
@http_methods [:get, :post, :put, :patch, :delete, :options, :connect, :trace, :head]
@doc false
defmacro __using__(_) do
quote do
unquote(prelude())
unquote(defs())
unquote(match_dispatch())
end
end
defp prelude() do
quote do
Module.register_attribute __MODULE__, :phoenix_routes, accumulate: true
@phoenix_forwards %{}
import Phoenix.Router
# TODO v2: No longer automatically import dependencies
import Plug.Conn
import Phoenix.Controller
# Set up initial scope
@phoenix_pipeline nil
Phoenix.Router.Scope.init(__MODULE__)
@before_compile unquote(__MODULE__)
end
end
# Because those macros are executed multiple times,
# we end-up generating a huge scope that drastically
# affects compilation. We work around it by defining
# those functions only once and calling it over and
# over again.
defp defs() do
quote unquote: false do
var!(add_resources, Phoenix.Router) = fn resource ->
path = resource.path
ctrl = resource.controller
opts = resource.route
if resource.singleton do
Enum.each resource.actions, fn
:show -> get path, ctrl, :show, opts
:new -> get path <> "/new", ctrl, :new, opts
:edit -> get path <> "/edit", ctrl, :edit, opts
:create -> post path, ctrl, :create, opts
:delete -> delete path, ctrl, :delete, opts
:update ->
patch path, ctrl, :update, opts
put path, ctrl, :update, Keyword.put(opts, :as, nil)
end
else
param = resource.param
Enum.each resource.actions, fn
:index -> get path, ctrl, :index, opts
:show -> get path <> "/:" <> param, ctrl, :show, opts
:new -> get path <> "/new", ctrl, :new, opts
:edit -> get path <> "/:" <> param <> "/edit", ctrl, :edit, opts
:create -> post path, ctrl, :create, opts
:delete -> delete path <> "/:" <> param, ctrl, :delete, opts
:update ->
patch path <> "/:" <> param, ctrl, :update, opts
put path <> "/:" <> param, ctrl, :update, Keyword.put(opts, :as, nil)
end
end
end
end
end
@doc false
def __call__(
%{private: %{phoenix_router: router, phoenix_bypass: {router, pipes}}} = conn,
{metadata, prepare, pipeline, _}
) do
conn = prepare.(conn, metadata)
case pipes do
:current -> pipeline.(conn)
_ -> Enum.reduce(pipes, conn, fn pipe, acc -> apply(router, pipe, [acc, []]) end)
end
end
def __call__(%{private: %{phoenix_bypass: :all}} = conn, {metadata, prepare, _, _}) do
prepare.(conn, metadata)
end
def __call__(conn, {metadata, prepare, pipeline, {plug, opts}}) do
conn = prepare.(conn, metadata)
start = System.monotonic_time()
metadata = %{metadata | conn: conn}
:telemetry.execute([:phoenix, :router_dispatch, :start], %{time: start}, metadata)
case pipeline.(conn) do
%Plug.Conn{halted: true} = halted_conn ->
halted_conn
%Plug.Conn{} = piped_conn ->
try do
plug.call(piped_conn, plug.init(opts))
else
conn ->
duration = System.monotonic_time() - start
metadata = %{metadata | conn: conn}
:telemetry.execute([:phoenix, :router_dispatch, :stop], %{duration: duration}, metadata)
conn
rescue
e in Plug.Conn.WrapperError ->
Plug.Conn.WrapperError.reraise(e)
catch
:error, reason ->
Plug.Conn.WrapperError.reraise(piped_conn, :error, reason, System.stacktrace())
end
end
end
defp match_dispatch() do
quote location: :keep do
@behaviour Plug
@doc """
Callback required by Plug that initializes the router
for serving web requests.
"""
def init(opts) do
opts
end
@doc """
Callback invoked by Plug on every request.
"""
def call(conn, _opts) do
%{method: method, path_info: path_info, host: host} = conn = prepare(conn)
case __match_route__(method, Enum.map(path_info, &URI.decode/1), host) do
:error -> raise NoRouteError, conn: conn, router: __MODULE__
match -> Phoenix.Router.__call__(conn, match)
end
end
defoverridable [init: 1, call: 2]
end
end
@anno (if :erlang.system_info(:otp_release) >= '19' do
[generated: true]
else
[line: -1]
end)
@doc false
defmacro __before_compile__(env) do
routes = env.module |> Module.get_attribute(:phoenix_routes) |> Enum.reverse
routes_with_exprs = Enum.map(routes, &{&1, Route.exprs(&1)})
Helpers.define(env, routes_with_exprs)
{matches, _} = Enum.map_reduce(routes_with_exprs, %{}, &build_match/2)
checks =
for {%{line: line, plug: plug, plug_opts: plug_opts}, _} <- routes_with_exprs, into: %{} do
quote line: line do
{unquote(plug).init(unquote(Macro.escape(plug_opts))), []}
end
end
# @anno is used here to avoid warnings if forwarding to root path
match_404 =
quote @anno do
def __match_route__(_method, _path_info, _host) do
:error
end
end
quote do
@doc false
def __routes__, do: unquote(Macro.escape(routes))
@doc false
def __checks__, do: unquote({:__block__, [], Map.keys(checks)})
@doc false
def __helpers__, do: __MODULE__.Helpers
defp prepare(conn) do
update_in conn.private,
&(&1
|> Map.put(:phoenix_router, __MODULE__)
|> Map.put(__MODULE__, {conn.script_name, @phoenix_forwards}))
end
unquote(matches)
unquote(match_404)
end
end
defp build_match({route, exprs}, known_pipelines) do
%{pipe_through: pipe_through} = route
%{
prepare: prepare,
dispatch: dispatch,
verb_match: verb_match,
path_params: path_params,
path: path,
host: host
} = exprs
{pipe_name, pipe_definition, known_pipelines} =
case known_pipelines do
%{^pipe_through => name} ->
{name, :ok, known_pipelines}
%{} ->
name = :"__pipe_through#{map_size(known_pipelines)}__"
{name, build_pipes(name, pipe_through), Map.put(known_pipelines, pipe_through, name)}
end
quoted =
quote line: route.line do
unquote(pipe_definition)
@doc false
def __match_route__(unquote(verb_match), unquote(path), unquote(host)) do
{unquote(build_metadata(route, path_params)),
fn var!(conn, :conn), %{path_params: var!(path_params, :conn)} -> unquote(prepare) end,
&unquote(Macro.var(pipe_name, __MODULE__))/1,
unquote(dispatch)}
end
end
{quoted, known_pipelines}
end
defp build_metadata(route, path_params) do
%{path: path, plug: plug, plug_opts: plug_opts, log: log, pipe_through: pipe_through} = route
pairs = [
conn: nil,
route: path,
plug: plug,
plug_opts: Macro.escape(plug_opts),
log: log,
path_params: path_params,
pipe_through: pipe_through
]
{:%{}, [], pairs}
end
defp build_pipes(name, []) do
quote do
defp unquote(name)(conn), do: conn
end
end
defp build_pipes(name, pipe_through) do
plugs = pipe_through |> Enum.reverse |> Enum.map(&{&1, [], true})
{conn, body} = Plug.Builder.compile(__ENV__, plugs, init_mode: Phoenix.plug_init_mode())
quote do
defp unquote(name)(unquote(conn)), do: unquote(body)
end
end
@doc """
Generates a route match based on an arbitrary HTTP method.
Useful for defining routes not included in the builtin macros.
The catch-all verb, `:*`, may also be used to match all HTTP methods.
## Options
* `:as` - configures the named helper exclusively
* `:log` - the level to log the route dispatching under,
may be set to false. Defaults to `:debug`
* `:host` - a string containing the host scope, or prefix host scope,
ie `"foo.bar.com"`, `"foo."`
* `:private` - a map of private data to merge into the connection when a route matches
* `:assigns` - a map of data to merge into the connection when a route matches
## Examples
match(:move, "/events/:id", EventController, :move)
match(:*, "/any", SomeController, :any)
"""
defmacro match(verb, path, plug, plug_opts, options \\ []) do
add_route(:match, verb, path, plug, plug_opts, options)
end
for verb <- @http_methods do
@doc """
Generates a route to handle a #{verb} request to the given path.
#{verb}("/events/:id", EventController, :action)
See `match/5` for options.
"""
defmacro unquote(verb)(path, plug, plug_opts, options \\ []) do
add_route(:match, unquote(verb), path, plug, plug_opts, options)
end
end
defp add_route(kind, verb, path, plug, plug_opts, options) do
quote do
@phoenix_routes Scope.route(
__ENV__.line,
__ENV__.module,
unquote(kind),
unquote(verb),
unquote(path),
unquote(plug),
unquote(plug_opts),
unquote(options)
)
end
end
@doc """
Defines a plug pipeline.
Pipelines are defined at the router root and can be used
from any scope.
## Examples
pipeline :api do
plug :token_authentication
plug :dispatch
end
A scope may then use this pipeline as:
scope "/" do
pipe_through :api
end
Every time `pipe_through/1` is called, the new pipelines
are appended to the ones previously given.
"""
defmacro pipeline(plug, do: block) do
block =
quote do
plug = unquote(plug)
@phoenix_pipeline []
unquote(block)
end
compiler =
quote unquote: false do
Scope.pipeline(__MODULE__, plug)
{conn, body} = Plug.Builder.compile(__ENV__, @phoenix_pipeline,
init_mode: Phoenix.plug_init_mode())
def unquote(plug)(unquote(conn), _) do
try do
unquote(body)
rescue
e in Plug.Conn.WrapperError ->
Plug.Conn.WrapperError.reraise(e)
catch
:error, reason ->
Plug.Conn.WrapperError.reraise(unquote(conn), :error, reason, System.stacktrace())
end
end
@phoenix_pipeline nil
end
quote do
try do
unquote(block)
unquote(compiler)
after
:ok
end
end
end
@doc """
Defines a plug inside a pipeline.
See `pipeline/2` for more information.
"""
defmacro plug(plug, opts \\ []) do
plug = Macro.expand(plug, %{__CALLER__ | function: {:init, 1}})
quote do
if pipeline = @phoenix_pipeline do
@phoenix_pipeline [{unquote(plug), unquote(opts), true}|pipeline]
else
raise "cannot define plug at the router level, plug must be defined inside a pipeline"
end
end
end
@doc """
Defines a pipeline to send the connection through.
See `pipeline/2` for more information.
"""
defmacro pipe_through(pipes) do
quote do
if pipeline = @phoenix_pipeline do
raise "cannot pipe_through inside a pipeline"
else
Scope.pipe_through(__MODULE__, unquote(pipes))
end
end
end
@doc """
Defines "RESTful" routes for a resource.
The given definition:
resources "/users", UserController
will include routes to the following actions:
* `GET /users` => `:index`
* `GET /users/new` => `:new`
* `POST /users` => `:create`
* `GET /users/:id` => `:show`
* `GET /users/:id/edit` => `:edit`
* `PATCH /users/:id` => `:update`
* `PUT /users/:id` => `:update`
* `DELETE /users/:id` => `:delete`
## Options
This macro accepts a set of options:
* `:only` - a list of actions to generate routes for, for example: `[:show, :edit]`
* `:except` - a list of actions to exclude generated routes from, for example: `[:delete]`
* `:param` - the name of the parameter for this resource, defaults to `"id"`
* `:name` - the prefix for this resource. This is used for the named helper
and as the prefix for the parameter in nested resources. The default value
is automatically derived from the controller name, i.e. `UserController` will
have name `"user"`
* `:as` - configures the named helper exclusively
* `:singleton` - defines routes for a singleton resource that is looked up by
the client without referencing an ID. Read below for more information
## Singleton resources
When a resource needs to be looked up without referencing an ID, because
it contains only a single entry in the given context, the `:singleton`
option can be used to generate a set of routes that are specific to
such single resource:
* `GET /user` => `:show`
* `GET /user/new` => `:new`
* `POST /user` => `:create`
* `GET /user/edit` => `:edit`
* `PATCH /user` => `:update`
* `PUT /user` => `:update`
* `DELETE /user` => `:delete`
Usage example:
resources "/account", AccountController, only: [:show], singleton: true
## Nested Resources
This macro also supports passing a nested block of route definitions.
This is helpful for nesting children resources within their parents to
generate nested routes.
The given definition:
resources "/users", UserController do
resources "/posts", PostController
end
will include the following routes:
user_post_path GET /users/:user_id/posts PostController :index
user_post_path GET /users/:user_id/posts/:id/edit PostController :edit
user_post_path GET /users/:user_id/posts/new PostController :new
user_post_path GET /users/:user_id/posts/:id PostController :show
user_post_path POST /users/:user_id/posts PostController :create
user_post_path PATCH /users/:user_id/posts/:id PostController :update
PUT /users/:user_id/posts/:id PostController :update
user_post_path DELETE /users/:user_id/posts/:id PostController :delete
"""
defmacro resources(path, controller, opts, do: nested_context) do
add_resources path, controller, opts, do: nested_context
end
@doc """
See `resources/4`.
"""
defmacro resources(path, controller, do: nested_context) do
add_resources path, controller, [], do: nested_context
end
defmacro resources(path, controller, opts) do
add_resources path, controller, opts, do: nil
end
@doc """
See `resources/4`.
"""
defmacro resources(path, controller) do
add_resources path, controller, [], do: nil
end
defp add_resources(path, controller, options, do: context) do
scope =
if context do
quote do
scope resource.member, do: unquote(context)
end
end
quote do
resource = Resource.build(unquote(path), unquote(controller), unquote(options))
var!(add_resources, Phoenix.Router).(resource)
unquote(scope)
end
end
@doc """
Defines a scope in which routes can be nested.
## Examples
scope path: "/api/v1", as: :api_v1, alias: API.V1 do
get "/pages/:id", PageController, :show
end
The generated route above will match on the path `"/api/v1/pages/:id"`
and will dispatch to `:show` action in `API.V1.PageController`. A named
helper `api_v1_page_path` will also be generated.
## Options
The supported options are:
* `:path` - a string containing the path scope
* `:as` - a string or atom containing the named helper scope
* `:alias` - an alias (atom) containing the controller scope.
When set, this value may be overridden per route by passing `alias: false`
to route definitions, such as `get`, `post`, etc.
* `:host` - a string containing the host scope, or prefix host scope,
ie `"foo.bar.com"`, `"foo."`
* `:private` - a map of private data to merge into the connection when a route matches
* `:assigns` - a map of data to merge into the connection when a route matches
* `:log` - the level to log the route dispatching under,
may be set to false. Defaults to `:debug`
"""
defmacro scope(options, do: context) do
do_scope(options, context)
end
@doc """
Define a scope with the given path.
This function is a shortcut for:
scope path: path do
...
end
## Examples
scope "/api/v1", as: :api_v1, alias: API.V1 do
get "/pages/:id", PageController, :show
end
"""
defmacro scope(path, options, do: context) do
options = quote do
path = unquote(path)
case unquote(options) do
alias when is_atom(alias) -> [path: path, alias: alias]
options when is_list(options) -> Keyword.put(options, :path, path)
end
end
do_scope(options, context)
end
@doc """
Defines a scope with the given path and alias.
This function is a shortcut for:
scope path: path, alias: alias do
...
end
## Examples
scope "/api/v1", API.V1, as: :api_v1 do
get "/pages/:id", PageController, :show
end
"""
defmacro scope(path, alias, options, do: context) do
options = quote do
unquote(options)
|> Keyword.put(:path, unquote(path))
|> Keyword.put(:alias, unquote(alias))
end
do_scope(options, context)
end
defp do_scope(options, context) do
quote do
Scope.push(__MODULE__, unquote(options))
try do
unquote(context)
after
Scope.pop(__MODULE__)
end
end
end
@doc """
Returns the full alias with the current scope's aliased prefix.
Useful for applying the same short-hand alias handling to
other values besides the second argument in route definitions.
## Examples
scope "/", MyPrefix do
get "/", ProxyPlug, controller: scoped_alias(__MODULE__, MyController)
end
"""
def scoped_alias(router_module, alias) do
Scope.expand_alias(router_module, alias)
end
@doc """
Forwards a request at the given path to a plug.
All paths that match the forwarded prefix will be sent to
the forwarded plug. This is useful for sharing a router between
applications or even breaking a big router into smaller ones.
The router pipelines will be invoked prior to forwarding the
connection.
However, we don't advise forwarding to another endpoint.
The reason is that plugs defined by your app and the forwarded
endpoint would be invoked twice, which may lead to errors.
## Examples
scope "/", MyApp do
pipe_through [:browser, :admin]
forward "/admin", SomeLib.AdminDashboard
forward "/api", ApiRouter
end
"""
defmacro forward(path, plug, plug_opts \\ [], router_opts \\ []) do
router_opts = Keyword.put(router_opts, :as, nil)
quote unquote: true, bind_quoted: [path: path, plug: plug] do
plug = Scope.register_forwards(__MODULE__, path, plug)
unquote(add_route(:forward, :*, path, plug, plug_opts, router_opts))
end
end
@doc """
Returns the compile-time route info and runtime path params for a request.
A map of metadata is returned with the following keys:
* `:log` - the configured log level. For example `:debug`
* `:path_params` - the map of runtime path params
* `:pipe_through` - the list of pipelines for the route's scope, for example `[:browser]`
* `:plug` - the plug to dipatch the route to, for example `AppWeb.PostController`
* `:plug_opts` - the options to pass when calling the plug, for example: `:index`
* `:route` - the string route pattern, such as `"/posts/:id"`
## Examples
iex> Phoenix.Router.route_info(AppWeb.Router, "GET", "/posts/123", "myhost")
%{
log: :debug,
path_params: %{"id" => "123"},
pipe_through: [:browser],
plug: AppWeb.PostController,
plug_opts: :show,
route: "/posts/:id",
}
iex> Phoenix.Router.route_info(MyRouter, "GET", "/not-exists", "myhost")
:error
"""
def route_info(router, method, path, host) do
split_path = for segment <- String.split(path, "/"), segment != "", do: segment
case router.__match_route__(method, split_path, host) do
{%{} = metadata, _prepare, _pipeline, {_plug, _opts}} -> Map.delete(metadata, :conn)
:error -> :error
end
end
end
| 30.485774 | 100 | 0.632332 |
ffefcf8e47eabbc64233e40d2198218c59c2b43b | 3,050 | exs | Elixir | test/github_reviews_test.exs | invisible-tech/bors-ng | 145663a328e98d28e2783bb2068081e03c5db099 | [
"Apache-2.0"
] | null | null | null | test/github_reviews_test.exs | invisible-tech/bors-ng | 145663a328e98d28e2783bb2068081e03c5db099 | [
"Apache-2.0"
] | 1 | 2020-07-09T20:45:37.000Z | 2020-07-09T20:45:37.000Z | test/github_reviews_test.exs | invisible-tech/bors-ng | 145663a328e98d28e2783bb2068081e03c5db099 | [
"Apache-2.0"
] | null | null | null | defmodule BorsNG.GitHub.GitHubReviewsTest do
use ExUnit.Case
doctest BorsNG.GitHub.Reviews
test "counts an empty list as zero", _ do
result = BorsNG.GitHub.Reviews.from_json!([])
assert result == %{"APPROVED" => 0, "CHANGES_REQUESTED" => 0, "approvers" => []}
end
test "counts an approval", _ do
result =
BorsNG.GitHub.Reviews.from_json!([
%{
"user" => %{"login" => "bert"},
"state" => "APPROVED"
}
])
assert result == %{"APPROVED" => 1, "CHANGES_REQUESTED" => 0, "approvers" => ["bert"]}
end
test "ignore comment-only reviews", _ do
result =
BorsNG.GitHub.Reviews.from_json!([
%{
"user" => %{"login" => "bert"},
"state" => "COMMENTED"
},
%{
"user" => %{"login" => "bert"},
"state" => "APPROVED"
},
%{
"user" => %{"login" => "bert"},
"state" => "COMMENTED"
}
])
assert result == %{"APPROVED" => 1, "CHANGES_REQUESTED" => 0, "approvers" => ["bert"]}
end
test "have dismissed reviews cancel everything else", _ do
result =
BorsNG.GitHub.Reviews.from_json!([
%{
"user" => %{"login" => "bert"},
"state" => "APPROVED"
},
%{
"user" => %{"login" => "bert"},
"state" => "DISMISSED"
}
])
assert result == %{"APPROVED" => 0, "CHANGES_REQUESTED" => 0, "approvers" => []}
end
test "counts a change request", _ do
result =
BorsNG.GitHub.Reviews.from_json!([
%{
"user" => %{"login" => "bert"},
"state" => "CHANGES_REQUESTED"
}
])
assert result == %{"APPROVED" => 0, "CHANGES_REQUESTED" => 1, "approvers" => []}
end
test "counts the last item (change request)", _ do
result =
BorsNG.GitHub.Reviews.from_json!([
%{
"user" => %{"login" => "bert"},
"state" => "APPROVED"
},
%{
"user" => %{"login" => "bert"},
"state" => "CHANGES_REQUESTED"
}
])
assert result == %{"APPROVED" => 0, "CHANGES_REQUESTED" => 1, "approvers" => []}
end
test "counts the last item (approval)", _ do
result =
BorsNG.GitHub.Reviews.from_json!([
%{
"user" => %{"login" => "bert"},
"state" => "CHANGES_REQUESTED"
},
%{
"user" => %{"login" => "bert"},
"state" => "APPROVED"
}
])
assert result == %{"APPROVED" => 1, "CHANGES_REQUESTED" => 0, "approvers" => ["bert"]}
end
test "counts separate users", _ do
result =
BorsNG.GitHub.Reviews.from_json!([
%{
"user" => %{"login" => "bert"},
"state" => "CHANGES_REQUESTED"
},
%{
"user" => %{"login" => "ernie"},
"state" => "APPROVED"
}
])
assert result == %{
"APPROVED" => 1,
"CHANGES_REQUESTED" => 1,
"approvers" => ["ernie"]
}
end
end
| 24.796748 | 90 | 0.462295 |
fff0005ae9fcdc23b3efbe46f5e56fc6071ca005 | 1,748 | ex | Elixir | lib/serum/build/pass_2/post_builder.ex | dragsubil/Serum | a465c48b388ef1e6d69ee6e8793f2869035b0520 | [
"MIT"
] | null | null | null | lib/serum/build/pass_2/post_builder.ex | dragsubil/Serum | a465c48b388ef1e6d69ee6e8793f2869035b0520 | [
"MIT"
] | null | null | null | lib/serum/build/pass_2/post_builder.ex | dragsubil/Serum | a465c48b388ef1e6d69ee6e8793f2869035b0520 | [
"MIT"
] | null | null | null | defmodule Serum.Build.Pass2.PostBuilder do
@moduledoc """
During pass 2, PostBuilder does the following:
1. Loops through the list of all blog posts. Renders the full HTML page of a
blog post for each `Serum.PostInfo` object in the list.
"""
import Serum.Util
alias Serum.Error
alias Serum.Build
alias Serum.Renderer
alias Serum.PostInfo
@type state :: Build.state
@async_opt [max_concurrency: System.schedulers_online * 10]
@doc "Starts the second pass of PostBuilder."
@spec run(Build.mode, state) :: Error.result
def run(mode, state) do
postdir = Path.join state.dest, "posts"
File.mkdir_p! postdir
msg_mkdir postdir
result = launch mode, state.site_ctx[:posts], state
Error.filter_results result, :post_builder
end
@spec launch(Build.mode, [PostInfo.t], state) :: [Error.result]
defp launch(:parallel, files, state) do
files
|> Task.async_stream(__MODULE__, :post_task, [state], @async_opt)
|> Enum.map(&(elem &1, 1))
end
defp launch(:sequential, files, state) do
files |> Enum.map(&post_task(&1, state))
end
@doc false
@spec post_task(PostInfo.t, state) :: Error.result
def post_task(info, state) do
srcpath = info.file
destpath = info.output
case render_post info, state do
{:ok, html} ->
fwrite destpath, html
msg_gen srcpath, destpath
:ok
{:error, _} = error -> error
end
end
@spec render_post(PostInfo.t, state) :: Error.result(binary)
defp render_post(info, state) do
post_ctx = [
title: info.title, date: info.date, raw_date: info.raw_date,
tags: info.tags, contents: info.html
]
Renderer.render "post", post_ctx, [page_title: info.title], state
end
end
| 26.089552 | 78 | 0.672197 |
fff00c67a0a6035e8dfed02b5467b831caffc2b2 | 1,787 | ex | Elixir | lib/instagram_clone_web/live/uploaders/avatar.ex | elixirprogrammer/InstagramClonePETAL | 5710f89de32a95b0416a960a46d081e7ad4833ab | [
"MIT"
] | 69 | 2021-04-11T21:57:26.000Z | 2022-03-30T01:09:40.000Z | lib/instagram_clone_web/live/uploaders/avatar.ex | hminy572/InstagramClonePETAL | 577cdad0e17399e47ef9d3f8e789bd07e33012b9 | [
"MIT"
] | 1 | 2021-04-16T17:38:11.000Z | 2021-04-16T17:38:11.000Z | lib/instagram_clone_web/live/uploaders/avatar.ex | hminy572/InstagramClonePETAL | 577cdad0e17399e47ef9d3f8e789bd07e33012b9 | [
"MIT"
] | 4 | 2021-04-16T10:45:18.000Z | 2021-07-23T15:08:08.000Z | defmodule InstagramClone.Uploaders.Avatar do
alias InstagramCloneWeb.Router.Helpers, as: Routes
@upload_directory_name "uploads"
@upload_directory_path "priv/static/uploads"
defp ext(entry) do
[ext | _] = MIME.extensions(entry.client_type)
ext
end
def get_avatar_url(socket, entry) do
Routes.static_path(socket, "/#{@upload_directory_name}/#{entry.uuid}.#{ext(entry)}")
end
def update(socket, old_url, entry) do
if !File.exists?(@upload_directory_path), do: File.mkdir!(@upload_directory_path)
Phoenix.LiveView.consume_uploaded_entry(socket, entry, fn %{} = meta ->
dest = Path.join(@upload_directory_path, "#{entry.uuid}.#{ext(entry)}")
dest_thumb = Path.join(@upload_directory_path, "thumb_#{entry.uuid}.#{ext(entry)}")
mogrify_thumbnail(meta.path, dest, 300)
mogrify_thumbnail(meta.path, dest_thumb, 150)
rm_file(old_url)
old_url |> get_thumb() |> rm_file()
end)
:ok
end
def get_thumb(avatar_url) when avatar_url == "/images/default-avatar.png" do
avatar_url
end
def get_thumb(avatar_url) do
file_name = String.replace_leading(avatar_url, "/uploads/", "")
["/#{@upload_directory_name}", "thumb_#{file_name}"] |> Path.join()
end
def rm_file(old_avatar_url) do
url = String.replace_leading(old_avatar_url, "/uploads/", "")
path = [@upload_directory_path, url] |> Path.join()
if File.exists?(path), do: File.rm!(path)
end
defp mogrify_thumbnail(src_path, dst_path, size) do
try do
Mogrify.open(src_path)
|> Mogrify.resize_to_limit("#{size}x#{size}")
|> Mogrify.save(path: dst_path)
rescue
File.Error -> {:error, :invalid_src_path}
error -> {:error, error}
else
_image -> {:ok, dst_path}
end
end
end
| 28.365079 | 89 | 0.672636 |
fff00d0974088cd7f8dd3aae626a23e98c17758d | 1,649 | exs | Elixir | test/new_relixir/instrumenters/plug_test.exs | nikhilbelchada/new-relixir | 6595b7ef713617e4c69ff414371c01c0e168a706 | [
"MIT"
] | 192 | 2016-03-18T23:58:14.000Z | 2022-02-04T13:41:32.000Z | test/new_relixir/instrumenters/plug_test.exs | nikhilbelchada/new-relixir | 6595b7ef713617e4c69ff414371c01c0e168a706 | [
"MIT"
] | 53 | 2016-05-06T17:57:06.000Z | 2019-01-25T21:11:52.000Z | test/new_relixir/instrumenters/plug_test.exs | nikhilbelchada/new-relixir | 6595b7ef713617e4c69ff414371c01c0e168a706 | [
"MIT"
] | 55 | 2016-04-29T09:45:36.000Z | 2020-05-27T23:35:04.000Z | defmodule NewRelixir.Instrumenters.PlugTest do
use ExUnit.Case
use Plug.Test
import TestHelpers.Assertions
alias NewRelixir.CurrentTransaction
@moduletag configured: true
defmodule FakePlugApp do
use Plug.Router
plug NewRelixir.Instrumenters.Plug
plug :match
plug :dispatch
get "/hello" do
conn = fetch_query_params(conn)
wait = conn.query_params["wait"]
if wait, do: wait |> String.to_integer |> :timer.sleep
send_resp(conn, 200, "Hello!")
end
end
setup do
start_supervised(NewRelixir.Collector)
:ok
end
setup %{configured: configured} do
previous_setting = Application.get_env(:new_relixir, :active)
Application.put_env(:new_relixir, :active, configured)
on_exit fn -> Application.put_env(:new_relixir, :active, previous_setting) end
:ok
end
test "it generates a transaction name based on request method and path" do
FakePlugApp.call(conn(:get, "/hello"), [])
assert {:ok, "hello#GET"} == CurrentTransaction.get()
assert [{"hello#GET", :total}] == get_metric_keys()
end
test "it records the elapsed time of the controller action" do
{elapsed_time, _} = :timer.tc(fn() ->
FakePlugApp.call(conn(:get, "/hello?wait=42"), [])
end)
[recorded_time] = get_metric_by_key({"hello#GET", :total})
assert_between(recorded_time, 42_000, elapsed_time)
end
@tag configured: false
test "does not record a transaction when New Relic is not configured" do
FakePlugApp.call(conn(:get, "/hello"), [])
assert {:error, :not_found} == CurrentTransaction.get()
assert [] == get_metric_keys()
end
end
| 25.369231 | 82 | 0.685264 |
fff01668418b67d6d2ba5af5583a1997043a9b9f | 4,675 | ex | Elixir | lib/plaid/accounts.ex | ethangunderson/plaid-elixir | 7c607a097bd0c23e85b72737dbbe0ec286faf96b | [
"MIT"
] | null | null | null | lib/plaid/accounts.ex | ethangunderson/plaid-elixir | 7c607a097bd0c23e85b72737dbbe0ec286faf96b | [
"MIT"
] | null | null | null | lib/plaid/accounts.ex | ethangunderson/plaid-elixir | 7c607a097bd0c23e85b72737dbbe0ec286faf96b | [
"MIT"
] | null | null | null | defmodule Plaid.Accounts do
@moduledoc """
Functions for Plaid `accounts` endpoint.
"""
import Plaid, only: [make_request_with_cred: 4, validate_cred: 1]
alias Plaid.Utils
@derive Jason.Encoder
defstruct accounts: [], item: nil, request_id: nil
@type t :: %__MODULE__{
accounts: [Plaid.Accounts.Account.t()],
item: Plaid.Item.t(),
request_id: String.t()
}
@type params :: %{required(atom) => String.t() | [String.t()] | map}
@type config :: %{required(atom) => String.t()}
@endpoint :accounts
defmodule Account do
@moduledoc """
Plaid Account data structure.
"""
@derive Jason.Encoder
defstruct account_id: nil,
balances: nil,
owners: nil,
name: nil,
mask: nil,
official_name: nil,
type: nil,
subtype: nil
@type t :: %__MODULE__{
account_id: String.t(),
balances: Plaid.Accounts.Account.Balance.t(),
owners: [Plaid.Accounts.Account.Owner.t()],
name: String.t(),
mask: String.t(),
official_name: String.t(),
type: String.t(),
subtype: String.t()
}
defmodule Balance do
@moduledoc """
Plaid Account Balance data structure.
"""
@derive Jason.Encoder
defstruct available: nil,
current: nil,
limit: nil,
iso_currency_code: nil,
unofficial_currency_code: nil
@type t :: %__MODULE__{
available: float,
current: float,
limit: float,
iso_currency_code: String.t(),
unofficial_currency_code: String.t()
}
end
defmodule Owner do
@moduledoc """
Plaid Account Owner data structure.
"""
@derive Jason.Encoder
defstruct addresses: nil,
emails: nil,
names: nil,
phone_numbers: nil
@type t :: %__MODULE__{
addresses: [Plaid.Accounts.Account.Owner.Address.t()],
emails: [Plaid.Accounts.Account.Owner.Email.t()],
names: [String.t()],
phone_numbers: [Plaid.Accounts.Account.Owner.PhoneNumber.t()]
}
defmodule Address do
@moduledoc """
Plaid Account Owner Address data structure.
"""
@derive Jason.Encoder
defstruct data: %{city: nil, region: nil, street: nil, postal_code: nil, country: nil},
primary: false
@type t :: %__MODULE__{
data: %{
city: String.t(),
region: String.t(),
street: String.t(),
postal_code: String.t(),
country: String.t()
},
primary: boolean()
}
end
defmodule Email do
@moduledoc """
Plaid Account Owner Email data structure.
"""
@derive Jason.Encoder
defstruct data: nil,
primary: false,
type: nil
@type t :: %__MODULE__{
data: String.t(),
primary: boolean(),
type: String.t()
}
end
defmodule PhoneNumber do
@moduledoc """
Plaid Account Owner PhoneNumber data structure.
"""
@derive Jason.Encoder
defstruct data: nil,
primary: false,
type: nil
@type t :: %__MODULE__{
data: String.t(),
primary: boolean(),
type: String.t()
}
end
end
end
@doc """
Gets account data associated with Item.
Parameters
```
%{access_token: "access-token"}
```
"""
@spec get(params, config | nil) :: {:ok, Plaid.Accounts.t()} | {:error, Plaid.Error.t()}
def get(params, config \\ %{}) do
config = validate_cred(config)
endpoint = "#{@endpoint}/get"
make_request_with_cred(:post, endpoint, config, params)
|> Utils.handle_resp(@endpoint)
end
@doc """
Gets balance for specifed accounts associated with Item.
Parameters
```
%{access_token: "access-token", options: %{account_ids: ["account-id"]}}
```
"""
@spec get_balance(params, config | nil) :: {:ok, Plaid.Accounts.t()} | {:error, Plaid.Error.t()}
def get_balance(params, config \\ %{}) do
config = validate_cred(config)
endpoint = "#{@endpoint}/balance/get"
make_request_with_cred(:post, endpoint, config, params)
|> Utils.handle_resp(@endpoint)
end
end
| 26.117318 | 98 | 0.519572 |
fff03a26669d3a999a268dd84bb862f8a6757050 | 14,019 | exs | Elixir | test/freshcom_web/controllers/user_controller_test.exs | freshcom/freshcom_web | fab44c9468e86b1770eef9971a97ad2b11545e9c | [
"BSD-3-Clause"
] | 9 | 2018-12-16T14:02:59.000Z | 2021-01-19T07:25:40.000Z | test/freshcom_web/controllers/user_controller_test.exs | freshcom/freshcom_web | fab44c9468e86b1770eef9971a97ad2b11545e9c | [
"BSD-3-Clause"
] | null | null | null | test/freshcom_web/controllers/user_controller_test.exs | freshcom/freshcom_web | fab44c9468e86b1770eef9971a97ad2b11545e9c | [
"BSD-3-Clause"
] | 4 | 2018-12-16T17:50:01.000Z | 2021-01-19T07:25:51.000Z | defmodule FreshcomWeb.UserControllerTest do
use FreshcomWeb.ConnCase
import FreshcomWeb.Shortcut
setup do
conn =
build_conn()
|> put_req_header("accept", "application/vnd.api+json")
|> put_req_header("content-type", "application/vnd.api+json")
%{conn: conn}
end
describe "(ListUser) GET /v1/users" do
test "given no access token", %{conn: conn} do
conn = get(conn, "/v1/users")
assert conn.status == 401
end
test "given unauthorized uat", %{conn: conn} do
%{default_account_id: account_id} = standard_user()
client = standard_app(account_id)
requester = managed_user(account_id)
uat = get_uat(account_id, requester.id, client.id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = get(conn, "/v1/users")
assert conn.status == 403
end
test "given valid uat", %{conn: conn} do
requester = standard_user()
client = standard_app(requester.default_account_id)
account_id = requester.default_account_id
managed_user(account_id)
managed_user(account_id)
uat = get_uat(account_id, requester.id, client.id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = get(conn, "/v1/users")
assert response = json_response(conn, 200)
assert length(response["data"]) == 2
assert response["meta"]["totalCount"] == 2
assert response["meta"]["allCount"] == 2
end
end
describe "(RegisterUser) POST /v1/users" do
test "given no attributes", %{conn: conn} do
conn = post(conn, "/v1/users", %{
"data" => %{
"type" => "User"
}
})
response = json_response(conn, 422)
assert length(response["errors"]) > 0
end
test "given valid attributes", %{conn: conn} do
client = system_app()
email = Faker.Internet.email()
conn = put_req_header(conn, "authorization", "Bearer #{client.prefixed_id}")
conn = post(conn, "/v1/users", %{
"data" => %{
"type" => "User",
"attributes" => %{
"name" => Faker.Name.name(),
"username" => email,
"email" => email,
"password" => "test1234",
"isTermAccepted" => true
}
}
})
assert body = json_response(conn, 201)
assert body["data"]["id"]
end
end
describe "(AddUser) POST /v1/users" do
test "given unauthorized uat", %{conn: conn} do
%{default_account_id: account_id} = standard_user()
client = standard_app(account_id)
user = managed_user(account_id)
uat = get_uat(account_id, user.id, client.id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = post(conn, "/v1/users", %{
"data" => %{
"type" => "User",
"attributes" => %{
"username" => Faker.Internet.user_name(),
"password" => "test1234",
"role" => "supportSpecialist"
}
}
})
assert json_response(conn, 403)
end
test "given no attributes", %{conn: conn} do
user = standard_user()
client = standard_app(user.default_account_id)
uat = get_uat(user.default_account_id, user.id, client.id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = post(conn, "/v1/users", %{
"data" => %{
"type" => "User"
}
})
assert json_response(conn, 422)
end
test "given valid request", %{conn: conn} do
requester = standard_user()
client = standard_app(requester.default_account_id)
uat = get_uat(requester.default_account_id, requester.id, client.id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = post(conn, "/v1/users", %{
"data" => %{
"type" => "User",
"attributes" => %{
"username" => Faker.Internet.user_name(),
"password" => "test1234",
"role" => "supportSpecialist"
}
}
})
assert response = json_response(conn, 201)
end
end
describe "(RetrieveCurrentUser) GET /v1/user" do
test "given no access token", %{conn: conn} do
conn = get(conn, "/v1/user")
assert conn.status == 401
end
test "given uat", %{conn: conn} do
requester = standard_user()
client = standard_app(requester.default_account_id)
uat = get_uat(requester.default_account_id, requester.id, client.id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = get(conn, "/v1/user")
assert response = json_response(conn, 200)
assert response["data"]["id"] == requester.id
end
end
describe "(RetrieveUser) GET /v1/users/:id" do
test "given no access token", %{conn: conn} do
conn = get(conn, "/v1/users/#{uuid4()}")
assert conn.status == 401
end
test "given unauthorized uat", %{conn: conn} do
%{default_account_id: account_id} = standard_user()
requester = managed_user(account_id)
client = standard_app(account_id)
uat = get_uat(account_id, requester.id, client.id)
user = managed_user(account_id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = get(conn, "/v1/users/#{user.id}")
assert conn.status == 403
end
test "given valid uat", %{conn: conn} do
requester = standard_user()
client = standard_app(requester.default_account_id)
uat = get_uat(requester.default_account_id, requester.id, client.id)
user = managed_user(requester.default_account_id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = get(conn, "/v1/users/#{user.id}")
assert response = json_response(conn, 200)
assert response["data"]["id"] == user.id
end
end
describe "(UpdateUser) PATCH /v1/users/:id" do
test "given no access token", %{conn: conn} do
conn = patch(conn, "/v1/users/#{uuid4()}")
assert conn.status == 401
end
test "given unauthorized uat", %{conn: conn} do
%{default_account_id: account_id} = standard_user()
requester = managed_user(account_id)
client = standard_app(account_id)
uat = get_uat(account_id, requester.id, client.id)
user = managed_user(account_id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = patch(conn, "/v1/users/#{user.id}", %{
"data" => %{
"type" => "User",
"attributes" => %{
"username" => Faker.Internet.user_name()
}
}
})
assert conn.status == 403
end
test "given valid uat", %{conn: conn} do
requester = standard_user()
account_id = requester.default_account_id
client = standard_app(account_id)
uat = get_uat(account_id, requester.id, client.id)
user = managed_user(account_id)
new_username = Faker.Internet.user_name()
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = patch(conn, "/v1/users/#{user.id}", %{
"data" => %{
"type" => "User",
"attributes" => %{
"username" => new_username
}
}
})
assert response = json_response(conn, 200)
assert response["data"]["attributes"]["username"] == new_username
end
end
describe "(ChangeDefaultAccount) PATCH /v1/user/relationships/default_account" do
test "given no access token", %{conn: conn} do
conn = patch(conn, "/v1/user/relationships/default_account")
assert conn.status == 401
end
test "given unauthorized uat", %{conn: conn} do
%{default_account_id: account_id} = standard_user()
requester = managed_user(account_id)
client = system_app()
uat = get_uat(account_id, requester.id, client.id)
account = account(requester.id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = patch(conn, "/v1/user/relationships/default_account", %{
"data" => %{
"id" => account.id,
"type" => "Account"
}
})
assert conn.status == 403
end
test "given valid uat", %{conn: conn} do
requester = standard_user()
client = system_app()
uat = get_uat(requester.default_account_id, requester.id, client.id)
account = account(requester.id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = patch(conn, "/v1/user/relationships/default_account", %{
"data" => %{
"id" => account.id,
"type" => "Account"
}
})
assert response = json_response(conn, 200)
assert response["data"]["id"] == requester.id
end
end
describe "(ChangeUserRole) PUT /v1/users/:id/role" do
test "given no access token", %{conn: conn} do
conn = put(conn, "/v1/users/#{uuid4()}/role")
assert conn.status == 401
end
test "given unauthorized uat", %{conn: conn} do
%{default_account_id: account_id} = standard_user()
requester = managed_user(account_id)
client = standard_app(account_id)
uat = get_uat(account_id, requester.id, client.id)
user = managed_user(account_id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = put(conn, "/v1/users/#{user.id}/role", %{
"data" => %{
"type" => "Role",
"attributes" => %{
"value" => "supportSpecialist"
}
}
})
assert conn.status == 403
end
test "given valid uat", %{conn: conn} do
requester = standard_user()
account_id = requester.default_account_id
client = standard_app(account_id)
uat = get_uat(account_id, requester.id, client.id)
user = managed_user(account_id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = put(conn, "/v1/users/#{user.id}/role", %{
"data" => %{
"type" => "Role",
"attributes" => %{
"value" => "supportSpecialist"
}
}
})
assert response = json_response(conn, 200)
assert response["data"]["attributes"]["role"] == "supportSpecialist"
end
end
describe "(GeneratePasswordResetToken) POST /v1/password_reset_tokens" do
test "given empty request", %{conn: conn} do
conn = post(conn, "/v1/password_reset_tokens", %{})
assert response = json_response(conn, 404)
end
test "given valid request with uat", %{conn: conn} do
requester = standard_user()
account_id = requester.default_account_id
client = standard_app(account_id)
uat = get_uat(account_id, requester.id, client.id)
user = managed_user(account_id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = post(conn, "/v1/password_reset_tokens?id=#{user.id}", %{
"data" => %{
"type" => "PasswordResetToken"
}
})
assert response = json_response(conn, 201)
assert response["data"]["id"] == user.id
end
test "given valid request without access token", %{conn: conn} do
user = standard_user()
client = system_app()
conn = put_req_header(conn, "authorization", "Bearer #{client.prefixed_id}")
conn = post(conn, "/v1/password_reset_tokens?username=#{user.username}", %{
"data" => %{
"type" => "PasswordResetToken"
}
})
assert conn.status == 204
end
end
describe "(ChangePassword) PUT /v1/password" do
test "given no access token", %{conn: conn} do
conn = put(conn, "/v1/password", %{})
assert response = json_response(conn, 404)
end
test "given unauthorized uat", %{conn: conn} do
%{default_account_id: account_id} = standard_user()
requester = managed_user(account_id)
client = standard_app(account_id)
uat = get_uat(account_id, requester.id, client.id)
user = managed_user(account_id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = put(conn, "/v1/password?id=#{user.id}", %{
"data" => %{
"type" => "Password",
"attributes" => %{
"newPassword" => "test1234"
}
}
})
assert conn.status == 403
end
test "given valid uat", %{conn: conn} do
requester = standard_user()
account_id = requester.default_account_id
client = standard_app(account_id)
uat = get_uat(account_id, requester.id, client.id)
user = managed_user(account_id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = put(conn, "/v1/password?id=#{user.id}", %{
"data" => %{
"type" => "Password",
"attributes" => %{
"newPassword" => "test1234"
}
}
})
assert response = json_response(conn, 200)
end
end
describe "(DeleteUser) DELETE /v1/users/:id" do
test "given no access token", %{conn: conn} do
conn = delete(conn, "/v1/users/#{uuid4()}")
assert conn.status == 401
end
test "given unauthorized uat", %{conn: conn} do
%{default_account_id: account_id} = standard_user()
requester = managed_user(account_id)
client = standard_app(account_id)
uat = get_uat(account_id, requester.id, client.id)
user = managed_user(account_id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = delete(conn, "/v1/users/#{user.id}")
assert conn.status == 403
end
test "given valid uat", %{conn: conn} do
requester = standard_user()
account_id = requester.default_account_id
client = standard_app(account_id)
uat = get_uat(account_id, requester.id, client.id)
user = managed_user(account_id)
conn = put_req_header(conn, "authorization", "Bearer #{uat}")
conn = delete(conn, "/v1/users/#{user.id}")
assert conn.status == 204
end
end
end
| 29.575949 | 83 | 0.591055 |
fff067777c9c4d986657d5e47595b37ba0c66276 | 1,010 | exs | Elixir | test/spaceex/articles/update_test.exs | LuizFerK/SpaceEx | ca1a4bd4881692860879b6f2c5d55bc521332c39 | [
"MIT"
] | 1 | 2021-12-13T15:50:00.000Z | 2021-12-13T15:50:00.000Z | test/spaceex/articles/update_test.exs | LuizFerK/SpaceEx | ca1a4bd4881692860879b6f2c5d55bc521332c39 | [
"MIT"
] | null | null | null | test/spaceex/articles/update_test.exs | LuizFerK/SpaceEx | ca1a4bd4881692860879b6f2c5d55bc521332c39 | [
"MIT"
] | 2 | 2022-01-09T18:12:17.000Z | 2022-01-23T22:12:51.000Z | defmodule Spaceex.Articles.UpdateTest do
use Spaceex.DataCase, async: true
import Spaceex.Factory
alias Spaceex.{Article, Error}
alias Spaceex.Articles.Update
describe "call/1" do
setup do
id = 0
insert(:article, id: id)
{:ok, id: id}
end
test "when all params are valid, updates the article", %{id: id} do
params = build(:article_params, %{"id" => id})
response = Update.call(params)
assert {:ok, %Article{id: ^id}} = response
end
test "when an invalid id is given, returns an error" do
params = build(:article_params, %{"id" => 123})
response = Update.call(params)
assert {:error, %Error{}} = response
end
test "when invalid params are given, returns an error", %{id: id} do
params =
build(:article_params, %{
"id" => id,
"featured" => "invalid_featured_type"
})
response = Update.call(params)
assert {:error, %Error{}} = response
end
end
end
| 21.956522 | 72 | 0.59604 |
fff0b86e5b6f2398a9e1adf53351cb376f44b604 | 90 | exs | Elixir | test/phx_template_web/views/layout_view_test.exs | sinorga/phx_template | 730a44df362c1e035cb8afd55d2e49d44fa60632 | [
"MIT"
] | null | null | null | test/phx_template_web/views/layout_view_test.exs | sinorga/phx_template | 730a44df362c1e035cb8afd55d2e49d44fa60632 | [
"MIT"
] | null | null | null | test/phx_template_web/views/layout_view_test.exs | sinorga/phx_template | 730a44df362c1e035cb8afd55d2e49d44fa60632 | [
"MIT"
] | null | null | null | defmodule PhxTemplateWeb.LayoutViewTest do
use PhxTemplateWeb.ConnCase, async: true
end
| 22.5 | 42 | 0.844444 |
fff0d4e5902fdbfeaedcece3d276a9fccab1dfb2 | 2,657 | ex | Elixir | apps/core/lib/core/policies/repository.ex | svilenkov/plural | ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026 | [
"Apache-2.0"
] | 1 | 2021-12-13T09:43:15.000Z | 2021-12-13T09:43:15.000Z | apps/core/lib/core/policies/repository.ex | svilenkov/plural | ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026 | [
"Apache-2.0"
] | null | null | null | apps/core/lib/core/policies/repository.ex | svilenkov/plural | ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026 | [
"Apache-2.0"
] | null | null | null | defmodule Core.Policies.Repository do
use Piazza.Policy
import Core.Policies.Utils
alias Core.Schema.{User, Installation, Repository, Integration, Artifact, DockerRepository, ApplyLock}
def can?(%User{} = user, %Integration{} = integ, policy) do
%{repository: repo} = Core.Repo.preload(integ, [:repository])
can?(user, repo, policy)
end
def can?(%User{} = user, %Artifact{} = art, policy) do
%{repository: repo} = Core.Repo.preload(art, [:repository])
can?(user, repo, policy)
end
def can?(%User{account_id: aid} = user, %Repository{} = repo, :support) do
case Core.Repo.preload(repo, [:publisher]) do
%{publisher: %{account_id: ^aid}} ->
check_rbac(user, :support, repository: repo.name)
_ -> {:error, :forbidden}
end
end
def can?(%User{account_id: aid}, %Repository{private: true} = repo, :access) do
case Core.Repo.preload(repo, [:publisher]) do
%{publisher: %{account_id: ^aid}} -> :continue
_ -> {:error, :forbidden}
end
end
def can?(%User{} = user, %DockerRepository{} = dkr, :edit) do
%{repository: repo} = Core.Repo.preload(dkr, [repository: [publisher: :account]])
can?(user, repo, :edit)
end
def can?(%User{} = user, %ApplyLock{owner_id: nil} = lock, :create) do
%{repository: repo} = Core.Repo.preload(lock, [repository: [publisher: :account]])
can?(user, repo, :edit)
end
def can?(_, %ApplyLock{}, :create), do: {:error, "lock already in use"}
def can?(%User{}, %Repository{}, :access), do: :continue
def can?(%User{account_id: aid, id: user_id}, %Repository{} = repo, :pull) do
case Core.Repo.preload(repo, [:publisher]) do
%{publisher: %{account_id: ^aid}} -> :continue
%{publisher: %{owner_id: ^user_id}} -> :continue
_ ->
if Core.Services.Repositories.get_installation(user_id, repo.id),
do: :continue, else: {:error, :forbidden}
end
end
def can?(%User{} = user, %Repository{} = repo, action) when action in [:create, :edit] do
case Core.Repo.preload(repo, [publisher: :account]) do
%{publisher: pub} -> Core.Policies.Publisher.can?(user, pub, :edit)
_ -> {:error, :forbidden}
end
end
def can?(%User{id: user_id}, %Installation{user_id: user_id}, action) when action in [:edit, :access],
do: :continue
def can?(%User{} = user, %Installation{} = inst, :create) do
%{repository: repo} = Core.Repo.preload(inst, [:repository])
check_rbac(user, :install, repository: repo.name)
end
def can?(user, %Ecto.Changeset{} = cs, action),
do: can?(user, apply_changes(cs), action)
def can?(_, _, _), do: {:error, :forbidden}
end
| 35.905405 | 104 | 0.631916 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.