hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequence
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequence
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequence
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
7347684d4e1b5369255287143f9044e4916d23d0
1,524
ex
Elixir
lib/intermediate_git_web/live/user_live/form_component.ex
Baradoy/intermdiategit
3a7b7efc32e361d2347057cbe3c8997f44135522
[ "MIT" ]
null
null
null
lib/intermediate_git_web/live/user_live/form_component.ex
Baradoy/intermdiategit
3a7b7efc32e361d2347057cbe3c8997f44135522
[ "MIT" ]
null
null
null
lib/intermediate_git_web/live/user_live/form_component.ex
Baradoy/intermdiategit
3a7b7efc32e361d2347057cbe3c8997f44135522
[ "MIT" ]
null
null
null
defmodule IntermediateGitWeb.UserLive.FormComponent do use IntermediateGitWeb, :live_component alias IntermediateGit.Accounts @impl true def update(%{user: user} = assigns, socket) do changeset = Accounts.change_user(user) {:ok, socket |> assign(assigns) |> assign(:changeset, changeset)} end @impl true def handle_event("validate", %{"user" => user_params}, socket) do changeset = socket.assigns.user |> Accounts.change_user(user_params) |> Map.put(:action, :validate) {:noreply, assign(socket, :changeset, changeset)} end def handle_event("save", %{"user" => user_params}, socket) do save_user(socket, socket.assigns.action, user_params) end defp save_user(socket, :edit, user_params) do case Accounts.update_user(socket.assigns.user, user_params) do {:ok, _user} -> {:noreply, socket |> put_flash(:info, "User updated successfully") |> push_redirect(to: socket.assigns.return_to)} {:error, %Ecto.Changeset{} = changeset} -> {:noreply, assign(socket, :changeset, changeset)} end end defp save_user(socket, :new, user_params) do case Accounts.create_user(user_params) do {:ok, _user} -> {:noreply, socket |> put_flash(:info, "User created successfully") |> push_redirect(to: socket.assigns.return_to)} {:error, %Ecto.Changeset{} = changeset} -> {:noreply, assign(socket, changeset: changeset)} end end end
27.214286
67
0.644357
73477c20b615295a21d9b2c66f584b2df2589962
4,603
exs
Elixir
farmbot_os/mix.exs
adamswsk/farmbot_os
d177d3b74888c1e7bcbf8f8595818708ee97f73b
[ "MIT" ]
null
null
null
farmbot_os/mix.exs
adamswsk/farmbot_os
d177d3b74888c1e7bcbf8f8595818708ee97f73b
[ "MIT" ]
null
null
null
farmbot_os/mix.exs
adamswsk/farmbot_os
d177d3b74888c1e7bcbf8f8595818708ee97f73b
[ "MIT" ]
null
null
null
defmodule FarmbotOS.MixProject do use Mix.Project @all_targets [:rpi3, :rpi] @version Path.join([__DIR__, "..", "VERSION"]) |> File.read!() |> String.trim() @branch System.cmd("git", ~w"rev-parse --abbrev-ref HEAD") |> elem(0) |> String.trim() @commit System.cmd("git", ~w"rev-parse --verify HEAD") |> elem(0) |> String.trim() System.put_env("NERVES_FW_VCS_IDENTIFIER", @commit) System.put_env("NERVES_FW_MISC", @branch) @elixir_version Path.join([__DIR__, "..", "ELIXIR_VERSION"]) |> File.read!() |> String.trim() System.put_env("NERVES_FW_VCS_IDENTIFIER", @commit) def project do [ app: :farmbot, elixir: @elixir_version, version: @version, branch: @branch, commit: @commit, releases: [{:farmbot, release()}], elixirc_options: [warnings_as_errors: true, ignore_module_conflict: true], archives: [nerves_bootstrap: "~> 1.9"], start_permanent: Mix.env() == :prod, build_embedded: false, compilers: [:elixir_make | Mix.compilers()], aliases: [loadconfig: [&bootstrap/1]], elixirc_paths: elixirc_paths(Mix.env(), Mix.target()), deps_path: "deps/#{Mix.target()}", build_path: "_build/#{Mix.target()}", deps: deps(), test_coverage: [tool: ExCoveralls], preferred_cli_target: [run: :host, test: :host], preferred_cli_env: [ coveralls: :test, "coveralls.detail": :test, "coveralls.post": :test, "coveralls.html": :test ], source_url: "https://github.com/Farmbot/farmbot_os", homepage_url: "http://farmbot.io", docs: [ logo: "../farmbot_os/priv/static/farmbot_logo.png", extras: Path.wildcard("../docs/**/*.md") ] ] end def release do [ overwrite: true, cookie: "democookie", include_erts: &Nerves.Release.erts/0, strip_beams: false, steps: [&Nerves.Release.init/1, :assemble] ] end # Starting nerves_bootstrap adds the required aliases to Mix.Project.config() # Aliases are only added if MIX_TARGET is set. def bootstrap(args) do Application.start(:nerves_bootstrap) Mix.Task.run("loadconfig", args) end # Run "mix help compile.app" to learn about applications. def application do [ mod: {FarmbotOS, []}, extra_applications: [:logger, :runtime_tools, :eex, :rollbax] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:busybox, "~> 0.1.5", targets: @all_targets}, {:circuits_gpio, "~> 0.4.6", targets: @all_targets}, {:circuits_i2c, "~> 0.3.8", targets: @all_targets}, {:cors_plug, "~> 2.0.3", targets: @all_targets}, {:dns, "~> 2.2"}, {:elixir_make, "~> 0.6.2", runtime: false}, {:ex_doc, "~> 0.23.0", only: [:dev], targets: [:host], runtime: false}, {:excoveralls, "~> 0.13.4", only: [:test], targets: [:host]}, {:farmbot_core, path: "../farmbot_core", env: Mix.env()}, {:farmbot_ext, path: "../farmbot_ext", env: Mix.env()}, {:farmbot_system_rpi, git: "https://github.com/FarmBot/farmbot_system_rpi.git", tag: "v1.14.1-farmbot.1", runtime: false, targets: :rpi}, {:farmbot_system_rpi3, git: "https://github.com/FarmBot/farmbot_system_rpi3.git", tag: "v1.14.0-farmbot.1", runtime: false, targets: :rpi3}, {:farmbot_telemetry, path: "../farmbot_telemetry", env: Mix.env()}, {:luerl, github: "rvirding/luerl"}, {:mdns_lite, "~> 0.6.6", targets: @all_targets}, {:nerves_firmware_ssh, "~> 0.4.6", targets: @all_targets}, {:nerves_runtime, "~> 0.11.3", targets: @all_targets}, {:nerves_time, "~> 0.4.2", targets: @all_targets}, {:phoenix_html, "~> 2.14.3"}, {:nerves, "~> 1.7.4", runtime: false}, {:plug_cowboy, "~> 2.4.1"}, {:ring_logger, "~> 0.8.1"}, {:rollbax, ">= 0.0.0"}, {:shoehorn, "~> 0.7"}, {:toolshed, "~> 0.2.18", targets: @all_targets}, {:vintage_net_direct, "~> 0.9.0", targets: @all_targets}, {:vintage_net_ethernet, "~> 0.9.0", targets: @all_targets}, {:vintage_net_wifi, "~> 0.9.2", targets: @all_targets}, {:vintage_net, "~> 0.9.3", targets: @all_targets} ] end defp elixirc_paths(:test, :host) do ["./lib", "./platform/host", "./test/support"] end defp elixirc_paths(_, :host) do ["./lib", "./platform/host"] end defp elixirc_paths(_env, _target) do ["./lib", "./platform/target"] end end
33.355072
80
0.579839
7347bb56c36a0db2ea89f41fca379061bb91ac07
4,144
ex
Elixir
clients/spanner/lib/google_api/spanner/v1/model/binding.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/spanner/lib/google_api/spanner/v1/model/binding.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/spanner/lib/google_api/spanner/v1/model/binding.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.Spanner.V1.Model.Binding do @moduledoc """ Associates `members` with a `role`. ## Attributes * `condition` (*type:* `GoogleApi.Spanner.V1.Model.Expr.t`, *default:* `nil`) - The condition that is associated with this binding. NOTE: An unsatisfied condition will not allow user access via current binding. Different bindings, including their conditions, are examined independently. * `members` (*type:* `list(String.t)`, *default:* `nil`) - Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific Google account. For example, `[email protected]` . * `serviceAccount:{emailid}`: An email address that represents a service account. For example, `[email protected]`. * `group:{emailid}`: An email address that represents a Google group. For example, `[email protected]`. * `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that has been recently deleted. For example, `[email protected]?uid=123456789012345678901`. If the user is recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. * `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a service account that has been recently deleted. For example, `[email protected]?uid=123456789012345678901`. If the service account is undeleted, this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a Google group that has been recently deleted. For example, `[email protected]?uid=123456789012345678901`. If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role in the binding. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that domain. For example, `google.com` or `example.com`. * `role` (*type:* `String.t`, *default:* `nil`) - Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :condition => GoogleApi.Spanner.V1.Model.Expr.t(), :members => list(String.t()), :role => String.t() } field(:condition, as: GoogleApi.Spanner.V1.Model.Expr) field(:members, type: :list) field(:role) end defimpl Poison.Decoder, for: GoogleApi.Spanner.V1.Model.Binding do def decode(value, options) do GoogleApi.Spanner.V1.Model.Binding.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Spanner.V1.Model.Binding do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
41.44
136
0.698842
7347c24884e3ac11a99210d0acb5ee312f554ff9
20,964
exs
Elixir
test/live_sup/core/datasources/wordpress_datasource_test.exs
livesup-dev/livesup
eaf9ffc78d3043bd9e3408f0f4df26ed16eb8446
[ "Apache-2.0", "MIT" ]
null
null
null
test/live_sup/core/datasources/wordpress_datasource_test.exs
livesup-dev/livesup
eaf9ffc78d3043bd9e3408f0f4df26ed16eb8446
[ "Apache-2.0", "MIT" ]
3
2022-02-23T15:51:48.000Z
2022-03-14T22:52:43.000Z
test/live_sup/core/datasources/wordpress_datasource_test.exs
livesup-dev/livesup
eaf9ffc78d3043bd9e3408f0f4df26ed16eb8446
[ "Apache-2.0", "MIT" ]
null
null
null
defmodule LiveSup.Test.Core.Datasources.WordpressDatasourceTest do use LiveSup.DataCase, async: true alias LiveSup.Core.Datasources.WordpressDatasource describe "managing wordpress datasource" do @describetag :datasource @describetag :wordpress_datasource @site_health_parsed_response %{ "wp-active-theme" => %{ "health-label" => "Active Theme", "health-name" => "wp-active-theme", "name" => %{"label" => "Name", "value" => "LIvesup (sup)"}, "version" => %{"label" => "Version", "value" => "1.0.0"} }, "wp-constants" => %{ "WP_CACHE" => %{"label" => "WP_CACHE", "value" => "Disabled"}, "WP_DEBUG" => %{"label" => "WP_DEBUG", "value" => "Disabled"}, "WP_MAX_MEMORY_LIMIT" => %{"label" => "WP_MAX_MEMORY_LIMIT", "value" => "256M"}, "WP_MEMORY_LIMIT" => %{"label" => "WP_MEMORY_LIMIT", "value" => "256M"}, "health-label" => "WordPress Constants", "health-name" => "wp-constants" }, "wp-core" => %{ "blog_public" => %{ "label" => "Is this site discouraging search engines?", "value" => "No" }, "health-label" => "WordPress", "health-name" => "wp-core", "https_status" => %{"label" => "Is this site using HTTPS?", "value" => "Yes"}, "version" => %{"label" => "Version", "value" => "5.8.2"} }, "wp-database" => %{ "database_name" => %{"label" => "Database name", "value" => "db4044012362"}, "database_prefix" => %{"label" => "Table prefix", "value" => "wp_hfco0vt0up_"}, "health-label" => "Database", "health-name" => "wp-database", "server_version" => %{ "label" => "Server version", "value" => "5.6.32-1+deb.sury.org~precise+0.1" } }, "wp-filesystem" => %{ "health-label" => "Filesystem Permissions", "health-name" => "wp-filesystem", "plugins" => %{"label" => "The plugins directory", "value" => "Writable"}, "themes" => %{"label" => "The themes directory", "value" => "Writable"}, "uploads" => %{"label" => "The uploads directory", "value" => "Writable"}, "wordpress" => %{"label" => "The main WordPress directory", "value" => "Writable"}, "wp-content" => %{"label" => "The wp-content directory", "value" => "Writable"} }, "wp-media" => %{ "health-label" => "Media Handling", "health-name" => "wp-media", "max_effective_size" => %{"label" => "Max effective file size", "value" => "300 MB"}, "max_file_uploads" => %{"label" => "Max number of files allowed", "value" => "20"}, "post_max_size" => %{"label" => "Max size of post data allowed", "value" => "300M"}, "upload_max_filesize" => %{"label" => "Max size of an uploaded file", "value" => "300M"} }, "wp-mu-plugins" => %{ "health-label" => "Must Use Plugins", "health-name" => "wp-mu-plugins", "health-total-count" => 1, "plugins" => %{ "dinkum-terminus-mwu" => %{ "label" => "dinkum-terminus-mwu", "value" => "Version 0.0.4 by SiteMavens.com" } } }, "wp-paths-sizes" => %{ "database_size" => %{"label" => "Database size", "value" => "Loading…"}, "health-label" => "Directories and Sizes", "health-name" => "wp-paths-sizes", "total_size" => %{"label" => "Total installation size", "value" => "Loading…"} }, "wp-plugins-active" => %{ "health-label" => "Active Plugins", "health-name" => "wp-plugins-active", "health-total-count" => 11, "plugins" => %{ "contactform7" => %{ "label" => "Contact Form 7", "value" => "Version 5.5.2 by Takayuki Miyoshi | Auto-updates disabled" }, "contactformdb" => %{ "label" => "Contact Form DB", "value" => "Version 2.10.32 by Michael Simpson | Auto-updates disabled" }, "defenderpro" => %{ "label" => "Defender Pro", "value" => "Version 2.6.4 by WPMU DEV | Auto-updates disabled" }, "googleanalyticsforwordpressbymonsterinsights" => %{ "label" => "Google Analytics for WordPress by MonsterInsights", "value" => "Version 8.2.0 by MonsterInsights | Auto-updates disabled" }, "livesup" => %{ "label" => "LiveSup", "value" => "Version 1.0.0 by LiveSup | Auto-updates disabled" }, "nativephpsessionsforwordpress" => %{ "label" => "Native PHP Sessions for WordPress", "value" => "Version 1.2.4 by Pantheon | Auto-updates disabled" }, "sliderrevolution" => %{ "label" => "Slider Revolution", "value" => "Version 5.4.1 by ThemePunch | Auto-updates disabled" }, "wordpressimporter" => %{ "label" => "WordPress Importer", "value" => "Version 0.7 by wordpressdotorg | Auto-updates disabled" }, "wpbakeryvisualcomposer" => %{ "label" => "WPBakery Visual Composer", "value" => "Version 5.1.1 by Michael M - WPBakery.com | Auto-updates disabled" }, "wpmudevdashboard" => %{ "label" => "WPMU DEV Dashboard", "value" => "Version 4.11.6 by WPMU DEV | Auto-updates enabled" }, "yoastseo" => %{ "label" => "Yoast SEO", "value" => "Version 17.6 by Team Yoast | Auto-updates disabled" } } }, "wp-plugins-inactive" => %{ "health-label" => "Inactive Plugins", "health-name" => "wp-plugins-inactive", "health-total-count" => 2, "plugins" => %{ "contactform7extensionformailchimp" => %{ "label" => "Contact Form 7 Extension For Mailchimp", "value" => "Version 0.5.52 by Renzo Johnson | Auto-updates disabled" }, "envatowordpresstoolkitdeprecated" => %{ "label" => "Envato WordPress Toolkit (Deprecated)", "value" => "Version 1.8.0 by Envato | Auto-updates disabled" } } }, "wp-server" => %{ "health-label" => "Server", "health-name" => "wp-server", "max_input_variables" => %{"label" => "PHP max input variables", "value" => "4000"}, "memory_limit" => %{"label" => "PHP memory limit", "value" => "256M"}, "php_version" => %{ "label" => "PHP version", "value" => "7.4.18 (Supports 64bit values)" }, "pretty_permalinks" => %{ "label" => "Are pretty permalinks supported?", "value" => "Yes" }, "time_limit" => %{"label" => "PHP time limit", "value" => "30"} }, "wp-themes-inactive" => %{ "health-label" => "Inactive Themes", "health-name" => "wp-themes-inactive", "health-total-count" => 4, "themes" => %{ "twentyfifteen" => %{ "label" => "Twenty Fifteen (twentyfifteen)", "value" => "Version 3.0 by the WordPress team | Auto-updates disabled" }, "twentynineteen" => %{ "label" => "Twenty Nineteen (twentynineteen)", "value" => "Version 2.1 by the WordPress team | Auto-updates disabled" }, "twentyseventeen" => %{ "label" => "Twenty Seventeen (twentyseventeen)", "value" => "Version 2.8 by the WordPress team | Auto-updates disabled" }, "twentysixteen" => %{ "label" => "Twenty Sixteen (twentysixteen)", "value" => "Version 2.5 by the WordPress team | Auto-updates disabled" } } } } setup do bypass = Bypass.open() {:ok, bypass: bypass} end test "Get site health", %{bypass: bypass} do Bypass.expect_once(bypass, "GET", "/wp-json/wp-site-live-sup/v1/site-health", fn conn -> Plug.Conn.resp(conn, 200, site_health_response()) end) {:ok, data} = WordpressDatasource.site_health(%{ user: "xxx", application_password: "xxx", url: endpoint_url(bypass.port) }) assert @site_health_parsed_response = data end test "Get directory sizes", %{bypass: bypass} do Bypass.expect_once(bypass, "GET", "/wp-json/wp-site-health/v1/directory-sizes", fn conn -> Plug.Conn.resp(conn, 200, response()) end) {:ok, data} = WordpressDatasource.directory_sizes(%{ user: "xxx", application_password: "xxx", url: endpoint_url(bypass.port) }) assert [ {"database_size", %{ "debug" => "21.78 MB (22839296 bytes)", "raw" => 22_839_296, "size" => "21.78 MB" }}, {"plugins_size", %{ "debug" => "86.00 MB (90176646 bytes)", "raw" => 90_176_646, "size" => "86.00 MB" }}, {"themes_size", %{ "debug" => "25.53 MB (26774299 bytes)", "raw" => 26_774_299, "size" => "25.53 MB" }}, {"total_size", %{ "debug" => "715.89 MB (750669086 bytes)", "raw" => 750_669_086, "size" => "715.89 MB" }}, {"uploads_size", %{ "debug" => "532.32 MB (558177513 bytes)", "raw" => 558_177_513, "size" => "532.32 MB" }}, {"wordpress_size", %{ "debug" => "50.26 MB (52701332 bytes)", "raw" => 52_701_332, "size" => "50.26 MB" }} ] = data end test "Failing to get directory sizes", %{bypass: bypass} do Bypass.expect_once(bypass, "GET", "/wp-json/wp-site-health/v1/directory-sizes", fn conn -> Plug.Conn.resp(conn, 401, error_response()) end) data = WordpressDatasource.directory_sizes(%{ user: "xxx", application_password: "xxx", url: endpoint_url(bypass.port) }) assert {:error, "401: Sorry, you are not allowed to do that."} = data end def site_health_response() do """ { "wp-core": { "health-name": "wp-core", "health-label": "WordPress", "version": { "label": "Version", "value": "5.8.2" }, "https_status": { "label": "Is this site using HTTPS?", "value": "Yes" }, "blog_public": { "label": "Is this site discouraging search engines?", "value": "No" } }, "wp-paths-sizes": { "health-name": "wp-paths-sizes", "health-label": "Directories and Sizes", "database_size": { "label": "Database size", "value": "Loading…" }, "total_size": { "label": "Total installation size", "value": "Loading…" } }, "wp-active-theme": { "health-name": "wp-active-theme", "health-label": "Active Theme", "name": { "label": "Name", "value": "LIvesup (sup)" }, "version": { "label": "Version", "value": "1.0.0" } }, "wp-themes-inactive": { "health-name": "wp-themes-inactive", "health-label": "Inactive Themes", "health-total-count": 4, "themes": { "twentyfifteen": { "label": "Twenty Fifteen (twentyfifteen)", "value": "Version 3.0 by the WordPress team | Auto-updates disabled" }, "twentynineteen": { "label": "Twenty Nineteen (twentynineteen)", "value": "Version 2.1 by the WordPress team | Auto-updates disabled" }, "twentyseventeen": { "label": "Twenty Seventeen (twentyseventeen)", "value": "Version 2.8 by the WordPress team | Auto-updates disabled" }, "twentysixteen": { "label": "Twenty Sixteen (twentysixteen)", "value": "Version 2.5 by the WordPress team | Auto-updates disabled" } } }, "wp-mu-plugins": { "health-name": "wp-mu-plugins", "health-label": "Must Use Plugins", "health-total-count": 1, "plugins": { "dinkum-terminus-mwu": { "label": "dinkum-terminus-mwu", "value": "Version 0.0.4 by SiteMavens.com" } } }, "wp-plugins-active": { "health-name": "wp-plugins-active", "health-label": "Active Plugins", "health-total-count": 11, "plugins": { "contactform7": { "label": "Contact Form 7", "value": "Version 5.5.2 by Takayuki Miyoshi | Auto-updates disabled" }, "contactformdb": { "label": "Contact Form DB", "value": "Version 2.10.32 by Michael Simpson | Auto-updates disabled" }, "defenderpro": { "label": "Defender Pro", "value": "Version 2.6.4 by WPMU DEV | Auto-updates disabled" }, "googleanalyticsforwordpressbymonsterinsights": { "label": "Google Analytics for WordPress by MonsterInsights", "value": "Version 8.2.0 by MonsterInsights | Auto-updates disabled" }, "livesup": { "label": "LiveSup", "value": "Version 1.0.0 by LiveSup | Auto-updates disabled" }, "nativephpsessionsforwordpress": { "label": "Native PHP Sessions for WordPress", "value": "Version 1.2.4 by Pantheon | Auto-updates disabled" }, "sliderrevolution": { "label": "Slider Revolution", "value": "Version 5.4.1 by ThemePunch | Auto-updates disabled" }, "wordpressimporter": { "label": "WordPress Importer", "value": "Version 0.7 by wordpressdotorg | Auto-updates disabled" }, "wpbakeryvisualcomposer": { "label": "WPBakery Visual Composer", "value": "Version 5.1.1 by Michael M - WPBakery.com | Auto-updates disabled" }, "wpmudevdashboard": { "label": "WPMU DEV Dashboard", "value": "Version 4.11.6 by WPMU DEV | Auto-updates enabled" }, "yoastseo": { "label": "Yoast SEO", "value": "Version 17.6 by Team Yoast | Auto-updates disabled" } } }, "wp-plugins-inactive": { "health-name": "wp-plugins-inactive", "health-label": "Inactive Plugins", "health-total-count": 2, "plugins": { "contactform7extensionformailchimp": { "label": "Contact Form 7 Extension For Mailchimp", "value": "Version 0.5.52 by Renzo Johnson | Auto-updates disabled" }, "envatowordpresstoolkitdeprecated": { "label": "Envato WordPress Toolkit (Deprecated)", "value": "Version 1.8.0 by Envato | Auto-updates disabled" } } }, "wp-media": { "health-name": "wp-media", "health-label": "Media Handling", "post_max_size": { "label": "Max size of post data allowed", "value": "300M" }, "upload_max_filesize": { "label": "Max size of an uploaded file", "value": "300M" }, "max_effective_size": { "label": "Max effective file size", "value": "300 MB" }, "max_file_uploads": { "label": "Max number of files allowed", "value": "20" } }, "wp-server": { "health-name": "wp-server", "health-label": "Server", "php_version": { "label": "PHP version", "value": "7.4.18 (Supports 64bit values)" }, "max_input_variables": { "label": "PHP max input variables", "value": "4000" }, "time_limit": { "label": "PHP time limit", "value": "30" }, "memory_limit": { "label": "PHP memory limit", "value": "256M" }, "pretty_permalinks": { "label": "Are pretty permalinks supported?", "value": "Yes" } }, "wp-database": { "health-name": "wp-database", "health-label": "Database", "server_version": { "label": "Server version", "value": "5.6.32-1+deb.sury.org~precise+0.1" }, "database_name": { "label": "Database name", "value": "db4044012362" }, "database_prefix": { "label": "Table prefix", "value": "wp_hfco0vt0up_" } }, "wp-constants": { "health-name": "wp-constants", "health-label": "WordPress Constants", "WP_MEMORY_LIMIT": { "label": "WP_MEMORY_LIMIT", "value": "256M" }, "WP_MAX_MEMORY_LIMIT": { "label": "WP_MAX_MEMORY_LIMIT", "value": "256M" }, "WP_DEBUG": { "label": "WP_DEBUG", "value": "Disabled" }, "WP_CACHE": { "label": "WP_CACHE", "value": "Disabled" } }, "wp-filesystem": { "health-name": "wp-filesystem", "health-label": "Filesystem Permissions", "wordpress": { "label": "The main WordPress directory", "value": "Writable" }, "wp-content": { "label": "The wp-content directory", "value": "Writable" }, "uploads": { "label": "The uploads directory", "value": "Writable" }, "plugins": { "label": "The plugins directory", "value": "Writable" }, "themes": { "label": "The themes directory", "value": "Writable" } } } """ end def response() do """ { "raw": 0, "wordpress_size": { "size": "50.26 MB", "debug": "50.26 MB (52701332 bytes)", "raw": 52701332 }, "themes_size": { "size": "25.53 MB", "debug": "25.53 MB (26774299 bytes)", "raw": 26774299 }, "plugins_size": { "size": "86.00 MB", "debug": "86.00 MB (90176646 bytes)", "raw": 90176646 }, "uploads_size": { "size": "532.32 MB", "debug": "532.32 MB (558177513 bytes)", "raw": 558177513 }, "database_size": { "size": "21.78 MB", "debug": "21.78 MB (22839296 bytes)", "raw": 22839296 }, "total_size": { "size": "715.89 MB", "debug": "715.89 MB (750669086 bytes)", "raw": 750669086 } } """ end def error_response() do """ { "code": "rest_forbidden", "message": "Sorry, you are not allowed to do that.", "data": { "status": 401 } } """ end defp endpoint_url(port), do: "http://localhost:#{port}" end end
36.395833
96
0.450296
7347c31f136c2b217b1b390f68f377a331750da9
1,605
ex
Elixir
clients/docs/lib/google_api/docs/v1/model/delete_named_range_request.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/docs/lib/google_api/docs/v1/model/delete_named_range_request.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/docs/lib/google_api/docs/v1/model/delete_named_range_request.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Docs.V1.Model.DeleteNamedRangeRequest do @moduledoc """ Deletes a NamedRange. ## Attributes * `name` (*type:* `String.t`, *default:* `nil`) - The name of the range(s) to delete. All named ranges with the given name will be deleted. * `namedRangeId` (*type:* `String.t`, *default:* `nil`) - The ID of the named range to delete. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :name => String.t(), :namedRangeId => String.t() } field(:name) field(:namedRangeId) end defimpl Poison.Decoder, for: GoogleApi.Docs.V1.Model.DeleteNamedRangeRequest do def decode(value, options) do GoogleApi.Docs.V1.Model.DeleteNamedRangeRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Docs.V1.Model.DeleteNamedRangeRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
32.1
143
0.722118
7347dcce2ee98c8f20ad4f8d18f90ee32bbaa740
4,778
ex
Elixir
apps/admin_app/lib/admin_app/order/order.ex
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
456
2018-09-20T02:40:59.000Z
2022-03-07T08:53:48.000Z
apps/admin_app/lib/admin_app/order/order.ex
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
273
2018-09-19T06:43:43.000Z
2021-08-07T12:58:26.000Z
apps/admin_app/lib/admin_app/order/order.ex
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
122
2018-09-26T16:32:46.000Z
2022-03-13T11:44:19.000Z
defmodule AdminApp.OrderContext do @moduledoc """ Module for the order related helper functions """ import Ecto.Query alias AdminAppWeb.Helpers alias BeepBop.Context alias Snitch.Domain.Order.DefaultMachine alias Snitch.Data.Schema.{Order, Package} alias Snitch.Data.Model.Order, as: OrderModel alias Snitch.Core.Tools.MultiTenancy.Repo alias Snitch.Domain.Order, as: OrderDomain alias SnitchPayments.PaymentMethodCode alias Snitch.Data.Model.Payment alias AdminApp.Order.SearchContext alias Snitch.Pagination def get_order(%{"number" => number}) do case OrderModel.get(%{number: number}) do {:ok, order} -> order = Repo.preload(order, [ [line_items: :product], [packages: [:items, :shipping_method]], [payments: :payment_method], :user ]) {:ok, order} {:error, msg} -> {:error, msg} end end def get_order(%{"id" => id}) do {:ok, order} = id |> String.to_integer() |> OrderModel.get() case OrderModel.get(String.to_integer(id)) do {:ok, order} -> order = Repo.preload(order, [ [line_items: :product], [packages: [:items, :shipping_method]], [payments: :payment_method], :user ]) {:ok, order} {:error, msg} -> {:error, msg} end end def get_total(order) do OrderDomain.total_amount(order) end def order_list("pending", sort_param, page) do rummage = get_rummage(sort_param) query = query_confirmed_orders(rummage) orders = load_orders(query) orders_query = from(order in orders, left_join: package in Package, on: order.id == package.order_id, where: package.state == ^:processing ) Pagination.page(orders_query, page) end def order_list("unshipped", sort_param, page) do rummage = get_rummage(sort_param) query = query_confirmed_orders(rummage) orders = load_orders(query) orders_query = from(order in orders, left_join: package in Package, on: order.id == package.order_id, where: package.state == ^:ready ) Pagination.page(orders_query, page) end def order_list("shipped", sort_param, page) do rummage = get_rummage(sort_param) query = query_confirmed_orders(rummage) orders = load_orders(query) orders_query = from(order in orders, left_join: package in Package, on: order.id == package.order_id, where: package.state == ^:shipped or package.state == ^:delivered ) Pagination.page(orders_query, page) end def update_cod_payment(order, state) do order = Repo.preload(order, :payments) cod_payment = Enum.find(order.payments, fn payment -> payment.payment_type == PaymentMethodCode.cash_on_delivery() end) Payment.update(cod_payment, %{state: state}) end def state_transition(_state = "complete", order) do order |> Context.new() |> DefaultMachine.complete_order() |> transition_response() end defp transition_response(%Context{errors: nil}) do {:ok, "Order moved to Completed"} end defp transition_response(%Context{errors: errors}) do errors = Enum.reduce(errors, "", fn {:error, message}, acc -> acc <> " " <> message end) {:error, errors} end defp initial_date_range do %{ start_date: 30 |> Helpers.date_days_before() |> Date.from_iso8601() |> elem(1) |> SearchContext.format_date(), end_date: SearchContext.format_date(Date.utc_today()) } end def order_list("complete", sort_param, page) do rummage = get_rummage(sort_param) {queryable, _rummage} = Order.rummage(rummage) query = from(p in queryable, where: p.state == "complete" and p.updated_at >= ^initial_date_range.start_date and p.updated_at <= ^initial_date_range.end_date ) query |> load_orders() |> Pagination.page(page) end defp query_confirmed_orders(rummage) do {queryable, _rummage} = Order.rummage(rummage) query = from(p in queryable, where: p.state == "confirmed" and p.updated_at >= ^initial_date_range.start_date and p.updated_at <= ^initial_date_range.end_date, select: p ) end defp get_rummage(sort_param) do case sort_param do nil -> %{} _ -> sort_order = String.to_atom(sort_param) %{ sort: %{field: :inserted_at, order: sort_order} } end end defp load_orders(query) do preload(query, [:user, [packages: :items], [line_items: :product]]) end end
24.502564
87
0.620134
7347e63ec6244cc9d947c2c51cb13c36dd2ef3a6
1,740
exs
Elixir
apps/ello_feeds/test/controllers/editorial_controller_test.exs
ello/apex
4acb096b3ce172ff4ef9a51e5d068d533007b920
[ "MIT" ]
16
2017-06-21T21:31:20.000Z
2021-05-09T03:23:26.000Z
apps/ello_feeds/test/controllers/editorial_controller_test.exs
ello/apex
4acb096b3ce172ff4ef9a51e5d068d533007b920
[ "MIT" ]
25
2017-06-07T12:18:28.000Z
2018-06-08T13:27:43.000Z
apps/ello_feeds/test/controllers/editorial_controller_test.exs
ello/apex
4acb096b3ce172ff4ef9a51e5d068d533007b920
[ "MIT" ]
3
2018-06-14T15:34:07.000Z
2022-02-28T21:06:13.000Z
defmodule Ello.Feeds.EditorialControllerTest do use Ello.Feeds.ConnCase import SweetXml setup %{conn: conn} do Factory.insert(:post_editorial, published_position: 1) Factory.insert(:external_editorial, published_position: 2) Factory.insert(:category_editorial, published_position: 3) Factory.insert(:curated_posts_editorial, published_position: 4) Factory.insert(:internal_editorial, published_position: 5) Factory.insert(:following_editorial, published_position: 6) Ecto.Adapters.SQL.Sandbox.mode(Repo, {:shared, self()}) {:ok, conn: conn} end test "GET /feeds/editorials - as rss", %{conn: conn} do assert %{status: 200, resp_body: body} = get(conn, "/feeds/editorials") assert xpath(body, ~x"/rss/channel/title/text()"s) == "Ello" assert xpath(body, ~x"/rss/channel/description/text()"s) assert xpath(body, ~x"/rss/channel/link/text()"s) assert xpath(body, ~x"/rss/channel/image/link/text()"s) == "https://ello.co" assert xpath(body, ~x"/rss/channel/item[1]/title/text()"s) == "Internal Editorial" assert xpath(body, ~x"/rss/channel/item[1]/description/text()"s) assert xpath(body, ~x"/rss/channel/item[1]/link/text()"s) == "https://ello.co/discover/recent" assert xpath(body, ~x"/rss/channel/item[2]/title/text()"s) == "External Editorial" assert xpath(body, ~x"/rss/channel/item[2]/description/text()"s) assert xpath(body, ~x"/rss/channel/item[2]/link/text()"s) =~ "https://ello.co/wtf" assert xpath(body, ~x"/rss/channel/item[3]/title/text()"s) == "Post Editorial" assert xpath(body, ~x"/rss/channel/item[3]/description/text()"s) assert xpath(body, ~x"/rss/channel/item[3]/link/text()"s) =~ ~r"https://ello.co/.*/post/.*" end end
49.714286
98
0.686207
7347ebe77c1d140df47aba6b05344b44a5b5b798
1,256
exs
Elixir
mix.exs
nTraum/lapin
02450640e5b1e0b0f2e76af38d41dee170166b18
[ "MIT" ]
21
2017-10-23T21:18:57.000Z
2022-02-09T11:58:33.000Z
mix.exs
nTraum/lapin
02450640e5b1e0b0f2e76af38d41dee170166b18
[ "MIT" ]
37
2017-10-23T22:29:43.000Z
2022-02-22T00:15:52.000Z
mix.exs
nTraum/lapin
02450640e5b1e0b0f2e76af38d41dee170166b18
[ "MIT" ]
13
2017-10-17T15:15:35.000Z
2022-03-08T14:02:36.000Z
defmodule Lapin.Mixfile do use Mix.Project def project do [ app: :lapin, version: "1.0.4", elixir: "~> 1.9", description: "Elixir RabbitMQ Client", source_url: "https://github.com/lucacorti/lapin", package: package(), docs: docs(), start_permanent: Mix.env() == :prod, deps: deps(), dialyzer: [ plt_add_apps: [:ex_unit, :amqp_client], plt_add_deps: :apps_direct, ignore_warnings: ".dialyzer.ignore-warnings" ] ] 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 [ {:amqp, "~> 1.0 or ~> 2.0 or ~> 3.0"}, {:connection, "~> 1.0"}, {:ex_doc, ">= 0.0.0", only: [:dev]}, {:earmark, ">= 0.0.0", only: [:dev]}, {:credo, ">= 0.0.0", only: [:dev]}, {:dialyxir, ">= 0.0.0", only: [:dev]} ] end defp package do [ maintainers: ["Luca Corti"], licenses: ["MIT"], links: %{GitHub: "https://github.com/lucacorti/lapin"} ] end defp docs do [ main: "main", extras: [ "docs/main.md" ] ] end end
21.288136
60
0.521497
73483840e6072984dc974f85e9c1f859d97cf401
1,906
ex
Elixir
clients/chrome_policy/lib/google_api/chrome_policy/v1/model/google_chrome_policy_v1_policy_schema_field_known_value_description.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/chrome_policy/lib/google_api/chrome_policy/v1/model/google_chrome_policy_v1_policy_schema_field_known_value_description.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/chrome_policy/lib/google_api/chrome_policy/v1/model/google_chrome_policy_v1_policy_schema_field_known_value_description.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.ChromePolicy.V1.Model.GoogleChromePolicyV1PolicySchemaFieldKnownValueDescription do @moduledoc """ Provides detailed information about a known value that is allowed for a particular field in a PolicySchema. ## Attributes * `description` (*type:* `String.t`, *default:* `nil`) - Output only. Additional description for this value. * `value` (*type:* `String.t`, *default:* `nil`) - Output only. The string represenstation of the value that can be set for the field. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :description => String.t() | nil, :value => String.t() | nil } field(:description) field(:value) end defimpl Poison.Decoder, for: GoogleApi.ChromePolicy.V1.Model.GoogleChromePolicyV1PolicySchemaFieldKnownValueDescription do def decode(value, options) do GoogleApi.ChromePolicy.V1.Model.GoogleChromePolicyV1PolicySchemaFieldKnownValueDescription.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.ChromePolicy.V1.Model.GoogleChromePolicyV1PolicySchemaFieldKnownValueDescription do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.654545
138
0.746065
734876d9f619c4658da01c56b1de42a3da4705b6
553
exs
Elixir
test/test_helper.exs
seantanly/money_sql
4511d05c55a9e953c2652ff777f17053d0cdce47
[ "Apache-2.0" ]
null
null
null
test/test_helper.exs
seantanly/money_sql
4511d05c55a9e953c2652ff777f17053d0cdce47
[ "Apache-2.0" ]
null
null
null
test/test_helper.exs
seantanly/money_sql
4511d05c55a9e953c2652ff777f17053d0cdce47
[ "Apache-2.0" ]
null
null
null
ExUnit.start() {:ok, _pid} = Money.SQL.Repo.start_link() :ok = Ecto.Adapters.SQL.Sandbox.mode(Money.SQL.Repo, :manual) defmodule Money.SQL.RepoCase do use ExUnit.CaseTemplate using do quote do alias Money.SQL.Repo import Ecto import Ecto.Query import Money.SQL.RepoCase # and any other stuff end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Money.SQL.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(Money.SQL.Repo, {:shared, self()}) end :ok end end
18.433333
71
0.658228
734884ad8d5a319a181da1ab706c759cd41cd546
2,049
ex
Elixir
lib/ggity/scale/y_continuous.ex
kianmeng/ggity
75f0097464eae4086f8c70e4bea995d60571eba9
[ "MIT" ]
null
null
null
lib/ggity/scale/y_continuous.ex
kianmeng/ggity
75f0097464eae4086f8c70e4bea995d60571eba9
[ "MIT" ]
null
null
null
lib/ggity/scale/y_continuous.ex
kianmeng/ggity
75f0097464eae4086f8c70e4bea995d60571eba9
[ "MIT" ]
null
null
null
defmodule GGity.Scale.Y.Continuous do @moduledoc false alias GGity.Scale.Y @base_axis_intervals [0.1, 0.2, 0.25, 0.4, 0.5, 0.75, 1.0, 2.0, 2.5, 4.0, 5.0, 7.5, 10] @type t() :: %__MODULE__{} @type mapping() :: map() defstruct width: 200, breaks: 5, labels: :waivers, tick_values: nil, inverse: nil, transform: nil @spec new(keyword()) :: Y.Continuous.t() def new(options \\ []), do: struct(Y.Continuous, options) @spec train(Y.Continuous.t(), {number(), number()}) :: Y.Continuous.t() def train(scale, {min, max}) do range = max - min struct(scale, transformations(range, min, max, scale)) end defp transformations(0, min, _max, %Y.Continuous{} = scale) do [ tick_values: min, inverse: fn _value -> min end, transform: fn _value -> scale.width / 2 end ] end defp transformations(range, min, max, %Y.Continuous{} = scale) do raw_interval_size = range / (scale.breaks - 1) order_of_magnitude = :math.ceil(:math.log10(raw_interval_size) - 1) power_of_ten = :math.pow(10, order_of_magnitude) adjusted_interval_size = axis_interval_lookup(raw_interval_size / power_of_ten) * power_of_ten adjusted_min = adjusted_interval_size * Float.floor(min / adjusted_interval_size) adjusted_max = adjusted_interval_size * Float.ceil(max / adjusted_interval_size) adjusted_interval_count = round(1.0001 * (adjusted_max - adjusted_min) / adjusted_interval_size) tick_values = Enum.map( 1..(adjusted_interval_count + 1), &(adjusted_min + (&1 - 1) * adjusted_interval_size) ) [ tick_values: tick_values, inverse: fn value -> floor((value - adjusted_min) / (adjusted_max - adjusted_min) * scale.width) end, transform: fn value -> floor((value - adjusted_min) / (adjusted_max - adjusted_min) * scale.width) end ] end defp axis_interval_lookup(value) do Enum.find(@base_axis_intervals, &(&1 >= value)) end end
30.58209
98
0.637872
7348a5b151e23b71c65743fee28e22a5bcd41b6f
11,354
ex
Elixir
lib/phoenix_live_view/utils.ex
caironoleto/phoenix_live_view
e102da323feceab588a1a090e7d0b766c9e099b8
[ "MIT" ]
1
2020-07-26T12:20:43.000Z
2020-07-26T12:20:43.000Z
lib/phoenix_live_view/utils.ex
mcrumm/phoenix_live_view
ff2313f42444c27e7652ebc5e4ee94ffa619bf85
[ "MIT" ]
null
null
null
lib/phoenix_live_view/utils.ex
mcrumm/phoenix_live_view
ff2313f42444c27e7652ebc5e4ee94ffa619bf85
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveView.Utils do # Shared helpers used mostly by Channel and Diff, # but also Static, and LiveViewTest. @moduledoc false alias Phoenix.LiveView.Rendered alias Phoenix.LiveView.Socket # All available mount options @mount_opts [:temporary_assigns, :layout] @max_flash_age :timer.seconds(60) @doc """ Assigns a value if it changed change. """ def assign(%Socket{} = socket, key, value) do case socket do %{assigns: %{^key => ^value}} -> socket %{} -> force_assign(socket, key, value) end end @doc """ Forces an assign. """ def force_assign(%Socket{assigns: assigns, changed: changed} = socket, key, val) do current_val = Map.get(assigns, key) # If the current value is a map, we store it in changed so # we can perform nested change tracking. Also note the use # of put_new is important. We want to keep the original value # from assigns and not any intermediate ones that may appear. new_changed = Map.put_new(changed, key, if(is_map(current_val), do: current_val, else: true)) new_assigns = Map.put(assigns, key, val) %{socket | assigns: new_assigns, changed: new_changed} end @doc """ Clears the changes from the socket assigns. """ def clear_changed(%Socket{private: private, assigns: assigns} = socket) do temporary = Map.get(private, :temporary_assigns, %{}) %Socket{socket | changed: %{}, assigns: Map.merge(assigns, temporary)} end @doc """ Checks if the socket changed. """ def changed?(%Socket{changed: changed}), do: changed != %{} @doc """ Checks if the given assign changed. """ def changed?(%Socket{changed: %{} = changed}, assign), do: Map.has_key?(changed, assign) def changed?(%Socket{}, _), do: false @doc """ Configures the socket for use. """ def configure_socket(%{id: nil, assigns: assigns, view: view} = socket, private, action, flash) do %{ socket | id: random_id(), private: private, assigns: configure_assigns(assigns, view, action, flash) } end def configure_socket(%{assigns: assigns, view: view} = socket, private, action, flash) do %{socket | private: private, assigns: configure_assigns(assigns, view, action, flash)} end defp configure_assigns(assigns, view, action, flash) do Map.merge(assigns, %{live_module: view, live_action: action, flash: flash}) end @doc """ Returns a random ID with valid DOM tokens """ def random_id do "phx-" |> Kernel.<>(random_encoded_bytes()) |> String.replace(["/", "+"], "-") end @doc """ Prunes any data no longer needed after mount. """ def post_mount_prune(%Socket{} = socket) do socket |> clear_changed() |> drop_private([:connect_params, :assign_new]) end @doc """ Renders the view with socket into a rendered struct. """ def to_rendered(socket, view) do inner_content = render_assigns(socket) |> view.render() |> check_rendered!(view) case layout(socket, view) do {layout_mod, layout_template} -> socket = assign(socket, :inner_content, inner_content) layout_template |> layout_mod.render(render_assigns(socket)) |> check_rendered!(layout_mod) false -> inner_content end end defp check_rendered!(%Rendered{} = rendered, _view), do: rendered defp check_rendered!(other, view) do raise RuntimeError, """ expected #{inspect(view)} to return a %Phoenix.LiveView.Rendered{} struct Ensure your render function uses ~L, or your eex template uses the .leex extension. Got: #{inspect(other)} """ end @doc """ Returns the socket's flash messages. """ def get_flash(%Socket{assigns: assigns}), do: assigns.flash def get_flash(%{} = flash, key), do: flash[key] @doc """ Puts a new flash with the socket's flash messages. """ def replace_flash(%Socket{} = socket, %{} = new_flash) do assign(socket, :flash, new_flash) end @doc """ Clears the flash. """ def clear_flash(%Socket{} = socket), do: assign(socket, :flash, %{}) @doc """ Clears the key from the flash. """ def clear_flash(%Socket{} = socket, key) do key = flash_key(key) new_flash = Map.delete(socket.assigns.flash, key) assign(socket, :flash, new_flash) end @doc """ Puts a flash message in the socket. """ def put_flash(%Socket{assigns: assigns} = socket, kind, msg) do kind = flash_key(kind) new_flash = Map.put(assigns.flash, kind, msg) assign(socket, :flash, new_flash) end defp flash_key(binary) when is_binary(binary), do: binary defp flash_key(atom) when is_atom(atom), do: Atom.to_string(atom) @doc """ Returns the configured signing salt for the endpoint. """ def salt!(endpoint) when is_atom(endpoint) do endpoint.config(:live_view)[:signing_salt] || raise ArgumentError, """ no signing salt found for #{inspect(endpoint)}. Add the following LiveView configuration to your config/config.exs: config :my_app, MyAppWeb.Endpoint, ..., live_view: [signing_salt: "#{random_encoded_bytes()}"] """ end @doc """ Returns the internal or external matched LiveView route info for the given uri """ def live_link_info!(%{router: nil}, view, _uri) do raise ArgumentError, "cannot invoke handle_params/3 on #{inspect(view)} " <> "because it is not mounted nor accessed through the router live/3 macro" end def live_link_info!(%{router: router, endpoint: endpoint}, view, uri) do %URI{host: host, path: path, query: query} = parsed_uri = URI.parse(uri) query_params = if query, do: Plug.Conn.Query.decode(query), else: %{} decoded_path = URI.decode(path || "") split_path = for segment <- String.split(decoded_path, "/"), segment != "", do: segment route_path = strip_segments(endpoint.script_name(), split_path) || split_path case Phoenix.Router.route_info(router, "GET", route_path, host) do %{plug: Phoenix.LiveView.Plug, phoenix_live_view: {^view, action}, path_params: path_params} -> {:internal, Map.merge(query_params, path_params), action, parsed_uri} %{} -> :external :error -> raise ArgumentError, "cannot invoke handle_params nor live_redirect/live_link to #{inspect(uri)} " <> "because it isn't defined in #{inspect(router)}" end end defp strip_segments([head | tail1], [head | tail2]), do: strip_segments(tail1, tail2) defp strip_segments([], tail2), do: tail2 defp strip_segments(_, _), do: nil @doc """ Raises error message for bad live patch on mount. """ def raise_bad_mount_and_live_patch!() do raise RuntimeError, """ attempted to live patch while mounting. a LiveView cannot be mounted while issuing a live patch to the client. \ Use push_redirect/2 or redirect/2 instead if you wish to mount and redirect. """ end @doc """ Calls the optional `mount/N` callback, otherwise returns the socket as is. """ def maybe_call_mount!(socket, view, args) do arity = length(args) if function_exported?(view, :mount, arity) do case apply(view, :mount, args) do {:ok, %Socket{} = socket, opts} when is_list(opts) -> validate_mount_redirect!(socket.redirected) Enum.reduce(opts, socket, fn {key, val}, acc -> mount_opt(acc, key, val, arity) end) {:ok, %Socket{} = socket} -> validate_mount_redirect!(socket.redirected) socket other -> raise ArgumentError, """ invalid result returned from #{inspect(view)}.mount/#{length(args)}. Expected {:ok, socket} | {:ok, socket, opts}, got: #{inspect(other)} """ end else socket end end defp validate_mount_redirect!({:live, {_, _}, _}), do: raise_bad_mount_and_live_patch!() defp validate_mount_redirect!(_), do: :ok @doc """ Calls the optional `update/2` callback, otherwise update the socket directly. """ def maybe_call_update!(socket, component, assigns) do if function_exported?(component, :update, 2) do socket = case component.update(assigns, socket) do {:ok, %Socket{} = socket} -> socket other -> raise ArgumentError, """ invalid result returned from #{inspect(component)}.update/2. Expected {:ok, socket}, got: #{inspect(other)} """ end if socket.redirected do raise "cannot redirect socket on update/2" end socket else Enum.reduce(assigns, socket, fn {k, v}, acc -> assign(acc, k, v) end) end end @doc """ Signs the socket's flash into a token if it has been set. """ def sign_flash(endpoint_mod, %{} = flash) do Phoenix.Token.sign(endpoint_mod, flash_salt(endpoint_mod), flash) end @doc """ Verifies the socket's flash token. """ def verify_flash(endpoint_mod, flash_token) do salt = flash_salt(endpoint_mod) case Phoenix.Token.verify(endpoint_mod, salt, flash_token, max_age: @max_flash_age) do {:ok, flash} -> flash {:error, _reason} -> %{} end end defp random_encoded_bytes do binary = << System.system_time(:nanosecond)::64, :erlang.phash2({node(), self()})::16, :erlang.unique_integer()::16 >> Base.url_encode64(binary) end defp mount_opt(%Socket{} = socket, key, val, _arity) when key in @mount_opts do do_mount_opt(socket, key, val) end defp mount_opt(%Socket{view: view}, key, val, arity) do raise ArgumentError, """ invalid option returned from #{inspect(view)}.mount/#{arity}. Expected keys to be one of #{inspect(@mount_opts)} got: #{inspect(key)}: #{inspect(val)} """ end defp do_mount_opt(socket, :layout, {mod, template}) when is_atom(mod) and is_binary(template) do %Socket{socket | private: Map.put(socket.private, :phoenix_live_layout, {mod, template})} end defp do_mount_opt(socket, :layout, false) do %Socket{socket | private: Map.put(socket.private, :phoenix_live_layout, false)} end defp do_mount_opt(_socket, :layout, bad_layout) do raise ArgumentError, "the :layout mount option expects a tuple of the form {MyLayoutView, \"my_template.html\"}, " <> "got: #{inspect(bad_layout)}" end defp do_mount_opt(socket, :temporary_assigns, temp_assigns) do unless Keyword.keyword?(temp_assigns) do raise "the :temporary_assigns mount option must be keyword list" end temp_assigns = Map.new(temp_assigns) %Socket{ socket | assigns: Map.merge(temp_assigns, socket.assigns), private: Map.put(socket.private, :temporary_assigns, temp_assigns) } end defp drop_private(%Socket{private: private} = socket, keys) do %Socket{socket | private: Map.drop(private, keys)} end defp render_assigns(socket) do Map.put(socket.assigns, :socket, %Socket{socket | assigns: %Socket.AssignsNotInSocket{}}) end defp layout(socket, view) do case socket.private do %{phoenix_live_layout: layout} -> layout %{} -> view.__live__()[:layout] || false end end defp flash_salt(endpoint_mod) when is_atom(endpoint_mod) do "flash:" <> salt!(endpoint_mod) end end
29.722513
106
0.648582
7348c60bf2aebe2ccb008b4d364d75395bb9b91d
1,694
exs
Elixir
hippo-backend/priv/repo/seeds.exs
yvc74/Hippo
4a1784c67bdbe073dafaf9aea66660d5b3c7ed5e
[ "MIT" ]
1
2020-09-20T14:16:03.000Z
2020-09-20T14:16:03.000Z
hippo-backend/priv/repo/seeds.exs
yvc74/Hippo
4a1784c67bdbe073dafaf9aea66660d5b3c7ed5e
[ "MIT" ]
null
null
null
hippo-backend/priv/repo/seeds.exs
yvc74/Hippo
4a1784c67bdbe073dafaf9aea66660d5b3c7ed5e
[ "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: # # Hippo.Repo.insert!(%Hippo.SomeSchema{}) # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong. alias Hippo.{ Lanes.Lane, Projects.Project, Cards.Card } alias Hippo.Repo require Ecto.Query defmodule Truncater do def truncate(tables) when is_list(tables) do tables |> Enum.map(&Atom.to_string/1) |> Enum.flat_map(&to_queries/1) |> Enum.each(&Repo.query/1) end defp to_queries(table_name) do [ "TRUNCATE TABLE #{table_name} CASCADE", "ALTER SEQUENCE #{table_name}_id_seq RESTART WITH 1" ] end end Truncater.truncate([:projects, :lanes, :cards]) # very bare bones helper module to setup some fake projects and data defmodule ProjectSeeder do def project() do %Project{ title: "Project - #{rand_id()}", description: "Some Description goes here - #{rand_id()}", lanes: Enum.map(0..5, fn _idx -> lane() end) } end def lane() do %Lane{ title: "Lane Title #{rand_id()}", description: "A lane description #{rand_id()}", cards: Enum.map(0..5, fn _idx -> card() end) } end def card() do %Card{ title: "Card title #{rand_id()}", description: "some card description #{rand_id()}" } end defp rand_id() do :crypto.strong_rand_bytes(6) |> Base.encode16() end end # make 25 projects to test with make_project = fn _idx -> ProjectSeeder.project() |> Hippo.Repo.insert() end Enum.each(0..25, make_project)
22
68
0.649941
7348df3a360c3ed543bb566379337c0e2d414648
1,216
exs
Elixir
mix.exs
kelostrada/ex_assert_eventually
569992b5be39c3c91b806b2acd5fc5571aa4ca17
[ "Apache-2.0" ]
null
null
null
mix.exs
kelostrada/ex_assert_eventually
569992b5be39c3c91b806b2acd5fc5571aa4ca17
[ "Apache-2.0" ]
null
null
null
mix.exs
kelostrada/ex_assert_eventually
569992b5be39c3c91b806b2acd5fc5571aa4ca17
[ "Apache-2.0" ]
null
null
null
defmodule ExAssertEventually.MixProject do use Mix.Project def project do [ app: :assert_eventually, version: "1.0.0", elixir: "~> 1.8", start_permanent: Mix.env() == :prod, deps: deps(), elixirc_paths: elixirc_paths(Mix.env()), package: package(), description: description(), name: "AssertEventually", source_url: source_url() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end defp package() do [ name: "assert_eventually", files: ~w(lib .formatter.exs mix.exs README* LICENSE*), licenses: ["Apache-2.0"], links: %{"GitHub" => source_url()} ] end defp source_url(), do: "https://github.com/rslota/ex_assert_eventually" defp description() do "A few sentences (a paragraph) describing the project." end # Run "mix help deps" to learn about dependencies. defp deps do [ {:ex_doc, ">= 0.0.0", runtime: false, optional: true} ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/utils"] defp elixirc_paths(_), do: ["lib"] end
23.384615
73
0.619243
7348e5c314bdd1f08be3146e571192d8516bb906
2,421
ex
Elixir
lib/phoenix_container_example_web/telemetry.ex
wwaldner-amtelco/phoenix_container_example
aeee424b40f444fe6bbfeab4d57b78d201397701
[ "Apache-2.0" ]
null
null
null
lib/phoenix_container_example_web/telemetry.ex
wwaldner-amtelco/phoenix_container_example
aeee424b40f444fe6bbfeab4d57b78d201397701
[ "Apache-2.0" ]
null
null
null
lib/phoenix_container_example_web/telemetry.ex
wwaldner-amtelco/phoenix_container_example
aeee424b40f444fe6bbfeab4d57b78d201397701
[ "Apache-2.0" ]
null
null
null
defmodule PhoenixContainerExampleWeb.Telemetry do @moduledoc false use Supervisor import Telemetry.Metrics def start_link(arg) do Supervisor.start_link(__MODULE__, arg, name: __MODULE__) end @impl true def init(_arg) do children = [ # Telemetry poller will execute the given period measurements # every 10_000ms. Learn more here: https://hexdocs.pm/telemetry_metrics {:telemetry_poller, measurements: periodic_measurements(), period: 10_000} # Add reporters as children of your supervision tree. # {Telemetry.Metrics.ConsoleReporter, metrics: metrics()} ] Supervisor.init(children, strategy: :one_for_one) end def metrics do [ # Phoenix Metrics summary("phoenix.endpoint.stop.duration", unit: {:native, :millisecond} ), summary("phoenix.router_dispatch.stop.duration", tags: [:route], unit: {:native, :millisecond} ), # Database Metrics summary("phoenix_container_example.repo.query.total_time", unit: {:native, :millisecond}, description: "The sum of the other measurements" ), summary("phoenix_container_example.repo.query.decode_time", unit: {:native, :millisecond}, description: "The time spent decoding the data received from the database" ), summary("phoenix_container_example.repo.query.query_time", unit: {:native, :millisecond}, description: "The time spent executing the query" ), summary("phoenix_container_example.repo.query.queue_time", unit: {:native, :millisecond}, description: "The time spent waiting for a database connection" ), summary("phoenix_container_example.repo.query.idle_time", unit: {:native, :millisecond}, description: "The time the connection spent waiting before being checked out for the query" ), # VM Metrics summary("vm.memory.total", unit: {:byte, :kilobyte}), summary("vm.total_run_queue_lengths.total"), summary("vm.total_run_queue_lengths.cpu"), summary("vm.total_run_queue_lengths.io") ] end defp periodic_measurements do [ # A module, function and arguments to be invoked periodically. # This function must call :telemetry.execute/3 and a metric must be added above. # {PhoenixContainerExampleWeb, :count_users, []} ] end end
32.716216
88
0.67121
7348e745ee383750b83038c55ff1baaa69649cf1
795
ex
Elixir
design/data_model_playground/lib/data_model_playground/schema/thread.ex
CircleCI-Public/firestorm
9ca2c46a2b2377370347ad94d6003eeb77be38d6
[ "MIT" ]
10
2017-06-28T08:06:52.000Z
2022-03-19T17:49:21.000Z
design/data_model_playground/lib/data_model_playground/schema/thread.ex
CircleCI-Public/firestorm
9ca2c46a2b2377370347ad94d6003eeb77be38d6
[ "MIT" ]
null
null
null
design/data_model_playground/lib/data_model_playground/schema/thread.ex
CircleCI-Public/firestorm
9ca2c46a2b2377370347ad94d6003eeb77be38d6
[ "MIT" ]
2
2017-10-21T12:01:02.000Z
2021-01-29T10:26:22.000Z
defmodule DataModelPlayground.Thread do use Ecto.Schema import Ecto.Changeset alias DataModelPlayground.{Repo, Category, Post, User} schema "threads" do import Ecto.Query belongs_to :category, Category has_many :posts, Post field :title, :string timestamps end @required_fields ~w(category_id title)a @optional_fields ~w()a def changeset(record, params \\ :empty) do record |> cast(params, @required_fields ++ @optional_fields) |> validate_required(@required_fields) end def user(thread) do thread = thread |> Repo.preload(posts: [:user]) case thread.posts do [] -> {:error, "No first post"} [first_post|_] -> {:ok, first_post.user} end end def user(_) do {:error, "No first post!"} end end
20.921053
57
0.655346
7348ff498730361e319c7c61cb7f122f0a11945e
2,540
exs
Elixir
integration_test/pg/test_helper.exs
dgvncsz0f/ecto
bae06fe650328cc1060c09fe889a2de9a10edb1b
[ "Apache-2.0" ]
null
null
null
integration_test/pg/test_helper.exs
dgvncsz0f/ecto
bae06fe650328cc1060c09fe889a2de9a10edb1b
[ "Apache-2.0" ]
null
null
null
integration_test/pg/test_helper.exs
dgvncsz0f/ecto
bae06fe650328cc1060c09fe889a2de9a10edb1b
[ "Apache-2.0" ]
1
2018-09-21T16:05:29.000Z
2018-09-21T16:05:29.000Z
Logger.configure(level: :info) ExUnit.start # Configure Ecto for support and tests Application.put_env(:ecto, :lock_for_update, "FOR UPDATE") Application.put_env(:ecto, :primary_key_type, :id) # Configure PG connection Application.put_env(:ecto, :pg_test_url, "ecto://" <> (System.get_env("PG_URL") || "postgres:postgres@localhost") ) # Load support files Code.require_file "../support/repo.exs", __DIR__ Code.require_file "../support/schemas.exs", __DIR__ Code.require_file "../support/migration.exs", __DIR__ pool = case System.get_env("ECTO_POOL") || "poolboy" do "poolboy" -> DBConnection.Poolboy "sbroker" -> DBConnection.Sojourn end # Pool repo for async, safe tests alias Ecto.Integration.TestRepo Application.put_env(:ecto, TestRepo, url: Application.get_env(:ecto, :pg_test_url) <> "/ecto_test", pool: Ecto.Adapters.SQL.Sandbox, ownership_pool: pool) defmodule Ecto.Integration.TestRepo do use Ecto.Integration.Repo, otp_app: :ecto, adapter: Ecto.Adapters.Postgres end # Pool repo for non-async tests alias Ecto.Integration.PoolRepo Application.put_env(:ecto, PoolRepo, pool: pool, url: Application.get_env(:ecto, :pg_test_url) <> "/ecto_test", pool_size: 10, max_restarts: 20, max_seconds: 10) defmodule Ecto.Integration.PoolRepo do use Ecto.Integration.Repo, otp_app: :ecto, adapter: Ecto.Adapters.Postgres def create_prefix(prefix) do "create schema #{prefix}" end def drop_prefix(prefix) do "drop schema #{prefix}" end end defmodule Ecto.Integration.Case do use ExUnit.CaseTemplate setup do :ok = Ecto.Adapters.SQL.Sandbox.checkout(TestRepo) end end {:ok, _} = Ecto.Adapters.Postgres.ensure_all_started(TestRepo.config(), :temporary) # Load up the repository, start it, and run migrations _ = Ecto.Adapters.Postgres.storage_down(TestRepo.config) :ok = Ecto.Adapters.Postgres.storage_up(TestRepo.config) {:ok, _pid} = TestRepo.start_link {:ok, _pid} = PoolRepo.start_link %{rows: [[version]]} = TestRepo.query!("SHOW server_version", []) version = case String.split(version, ".") do [x, y] -> "#{x}.#{y}.0" _other -> version end if Version.match?(version, "~> 9.5") do ExUnit.configure(exclude: [:without_conflict_target]) else Application.put_env(:ecto, :postgres_map_type, "json") ExUnit.configure(exclude: [:upsert, :upsert_all, :array_type, :aggregate_filters]) end :ok = Ecto.Migrator.up(TestRepo, 0, Ecto.Integration.Migration, log: false) Ecto.Adapters.SQL.Sandbox.mode(TestRepo, :manual) Process.flag(:trap_exit, true)
27.311828
84
0.73189
73490007a2d560794cee4a1c9d32bb05a89be97d
4,362
ex
Elixir
lib/crawly.ex
m4hi2/crawly
b9e1bfffcc97e978023924e7aad53fc8a223aebf
[ "Apache-2.0" ]
486
2019-05-30T09:19:59.000Z
2021-04-28T07:51:31.000Z
lib/crawly.ex
m4hi2/crawly
b9e1bfffcc97e978023924e7aad53fc8a223aebf
[ "Apache-2.0" ]
131
2019-06-29T12:43:24.000Z
2021-04-24T19:40:07.000Z
lib/crawly.ex
m4hi2/crawly
b9e1bfffcc97e978023924e7aad53fc8a223aebf
[ "Apache-2.0" ]
52
2019-06-24T10:13:41.000Z
2021-03-28T07:36:42.000Z
defmodule Crawly do @moduledoc """ Crawly is a fast high-level web crawling & scraping framework for Elixir. """ @doc """ Fetches a given url. This function is mainly used for the spiders development when you need to get individual pages and parse them. The fetched URL is being converted to a request, and the request is piped through the middlewares specified in a config (with the exception of `Crawly.Middlewares.DomainFilter`, `Crawly.Middlewares.RobotsTxt`) Provide a spider with the `:with` option to fetch a given webpage using that spider. ### Fetching with a spider To fetch a response from a url with a spider, define your spider, and pass the module name to the `:with` option. iex> Crawly.fetch("https://www.example.com", with: MySpider) {%HTTPoison.Response{...}, %{...}, [...], %{...}} Using the `:with` option will return a 4 item tuple: 1. The HTTPoison response 2. The result returned from the `parse_item/1` callback 3. The list of items that have been processed by the declared item pipelines. 4. The pipeline state, included for debugging purposes. """ @type with_opt :: {:with, nil | module()} @type request_opt :: {:request_options, list(Crawly.Request.option())} @type headers_opt :: {:headers, list(Crawly.Request.header())} @type parsed_item_result :: Crawly.ParsedItem.t() @type parsed_items :: list(any()) @type pipeline_state :: %{optional(atom()) => any()} @type spider :: module() @spec fetch(url, opts) :: HTTPoison.Response.t() | {HTTPoison.Response.t(), parsed_item_result, parsed_items, pipeline_state} when url: binary(), opts: [ with_opt | request_opt | headers_opt ] def fetch(url, opts \\ []) do opts = Enum.into(opts, %{with: nil, request_options: [], headers: []}) request0 = Crawly.Request.new(url, opts[:headers], opts[:request_options]) |> Map.put( :middlewares, Crawly.Utils.get_settings(:middlewares, opts[:with], []) ) ignored_middlewares = [ Crawly.Middlewares.DomainFilter, Crawly.Middlewares.RobotsTxt ] new_middlewares = request0.middlewares -- ignored_middlewares request0 = Map.put( request0, :middlewares, new_middlewares ) {%{} = request, _} = Crawly.Utils.pipe(request0.middlewares, request0, %{}) {:ok, {response, _}} = Crawly.Worker.get_response({request, opts[:with]}) case opts[:with] do nil -> # no spider provided, return response as is response _ -> # spider provided, send response through parse_item callback, pipe through the pipelines with {:ok, {parsed_result, _, _}} <- Crawly.Worker.parse_item({response, opts[:with]}), pipelines <- Crawly.Utils.get_settings( :pipelines, opts[:with] ), items <- Map.get(parsed_result, :items, []), {pipeline_result, pipeline_state} <- Enum.reduce(items, {[], %{}}, fn item, {acc, state} -> {piped, state} = Crawly.Utils.pipe(pipelines, item, state) if piped == false do # dropped {acc, state} else {[piped | acc], state} end end) do {response, parsed_result, pipeline_result, pipeline_state} end end end @doc """ Parses a given response with a given spider. Allows to quickly see the outcome of the given :parse_item implementation. """ @spec parse(response, spider) :: {:ok, result} when response: Crawly.Response.t(), spider: atom(), result: Crawly.ParsedItem.t() def parse(response, spider) do case Kernel.function_exported?(spider, :parse_item, 1) do false -> {:error, :spider_not_found} true -> spider.parse_item(response) end end @doc """ Returns a list of known modules which implements Crawly.Spider behaviour. Should not be used for spider management. Use functions defined in `Crawly.Engine` for that. """ @spec list_spiders() :: [module()] def list_spiders(), do: Crawly.Utils.list_spiders() end
33.045455
115
0.607519
73490d92ed868f1069556bd6d7e5d653f3ab7ccb
1,552
ex
Elixir
lib/retrospectivex_web/views/error_helpers.ex
dreamingechoes/retrospectivex
cad0df6cfde5376121d841f4a8b36861b6ec5d45
[ "MIT" ]
5
2018-06-27T17:51:51.000Z
2020-10-05T09:59:04.000Z
lib/retrospectivex_web/views/error_helpers.ex
dreamingechoes/retrospectivex
cad0df6cfde5376121d841f4a8b36861b6ec5d45
[ "MIT" ]
1
2018-10-08T11:33:12.000Z
2018-10-08T11:33:12.000Z
lib/retrospectivex_web/views/error_helpers.ex
dreamingechoes/retrospectivex
cad0df6cfde5376121d841f4a8b36861b6ec5d45
[ "MIT" ]
2
2018-10-08T11:31:55.000Z
2020-10-05T09:59:05.000Z
defmodule RetrospectivexWeb.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do Enum.map(Keyword.get_values(form.errors, field), fn error -> content_tag(:span, translate_error(error), class: "help-block") end) end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # When using gettext, we typically pass the strings we want # to translate as a static argument: # # # Translate "is invalid" in the "errors" domain # dgettext "errors", "is invalid" # # # Translate the number of files with plural rules # dngettext "errors", "1 file", "%{count} files", count # # Because the error messages we show in our forms and APIs # are defined inside Ecto, we need to translate them dynamically. # This requires us to call the Gettext module passing our gettext # backend as first argument. # # Note we use the "errors" domain, which means translations # should be written to the errors.po file. The :count option is # set by Ecto and indicates we should also apply plural rules. if count = opts[:count] do Gettext.dngettext( RetrospectivexWeb.Gettext, "errors", msg, msg, count, opts ) else Gettext.dgettext(RetrospectivexWeb.Gettext, "errors", msg, opts) end end end
29.846154
70
0.651418
73492f1c4bdb384b9d51d1df3aad44afec807f5e
1,690
ex
Elixir
lib/stripe_app_web/controllers/coherence/redirects.ex
hotpyn/stripe_demo
2a0ac3ab34a616ffcd6d7e979c25517b5f1636b5
[ "MIT" ]
null
null
null
lib/stripe_app_web/controllers/coherence/redirects.ex
hotpyn/stripe_demo
2a0ac3ab34a616ffcd6d7e979c25517b5f1636b5
[ "MIT" ]
null
null
null
lib/stripe_app_web/controllers/coherence/redirects.ex
hotpyn/stripe_demo
2a0ac3ab34a616ffcd6d7e979c25517b5f1636b5
[ "MIT" ]
null
null
null
defmodule Coherence.Redirects do @moduledoc """ Define controller action redirection functions. This module contains default redirect functions for each of the controller actions that perform redirects. By using this Module you get the following functions: * session_create/2 * session_delete/2 * password_create/2 * password_update/2, * unlock_create_not_locked/2 * unlock_create_invalid/2 * unlock_create/2 * unlock_edit_not_locked/2 * unlock_edit/2 * unlock_edit_invalid/2 * registration_create/2 * invitation_create/2 * confirmation_create/2 * confirmation_edit_invalid/2 * confirmation_edit_expired/2 * confirmation_edit/2 * confirmation_edit_error/2 You can override any of the functions to customize the redirect path. Each function is passed the `conn` and `params` arguments from the controller. ## Examples import StripeAppWeb.Router.Helpers # override the log out action back to the log in page def session_delete(conn, _), do: redirect(conn, to: session_path(conn, :new)) # redirect the user to the login page after registering def registration_create(conn, _), do: redirect(conn, to: session_path(conn, :new)) # disable the user_return_to feature on login def session_create(conn, _), do: redirect(conn, to: landing_path(conn, :index)) """ use Redirects # Uncomment the import below if adding overrides # import StripeAppWeb.Router.Helpers # Add function overrides below # Example usage # Uncomment the following line to return the user to the login form after logging out # def session_delete(conn, _), do: redirect(conn, to: session_path(conn, :new)) end
30.727273
88
0.742012
734936eec36c9d169a4f90fe4350fb83426ff129
1,663
exs
Elixir
misc/fb_api.exs
feihong/elixir-examples
dda6128f729199dad21220925df3bae241911fbd
[ "Apache-2.0" ]
null
null
null
misc/fb_api.exs
feihong/elixir-examples
dda6128f729199dad21220925df3bae241911fbd
[ "Apache-2.0" ]
null
null
null
misc/fb_api.exs
feihong/elixir-examples
dda6128f729199dad21220925df3bae241911fbd
[ "Apache-2.0" ]
null
null
null
defmodule Fetch do @keywords Application.fetch_env!(:misc, :keywords) @access_token Application.fetch_env!(:misc, Facebook)[:access_token] def fetch_all() do pages = Application.fetch_env!(:misc, Facebook)[:pages] # Fetch all events and sort. events = pages |> Enum.map(fn name -> fetch(name) end) |> List.flatten |> Enum.map(&enhance/1) |> Enum.sort_by(&sort_mapper/1) end defp fetch(name) do cache_name = "facebook__#{name}" url = "https://graph.facebook.com/v2.9/#{name}/events/" params = %{access_token: @access_token, since: DateTime.utc_now |> DateTime.to_iso8601} Download.fetch(cache_name, url, params)["data"] end defp enhance(evt) do text = evt["name"] <> " " <> evt["description"] |> String.downcase matched_keywords = for keyword <- @keywords, String.contains?(text, keyword) do keyword end evt |> Map.put("url", "https://facebook.com/events/#{evt["id"]}") |> Map.put("matched_keywords", matched_keywords) |> Map.put("start_dt", Timex.parse!(evt["start_time"], "{ISO:Extended}")) end defp sort_mapper(evt) do # Make sure that events that match keywords are always in front # regardless of start time. num = if length(evt["matched_keywords"]) > 0, do: 0, else: 1 {num, evt["start_time"]} end end events = Fetch.fetch_all() match_count = events |> Enum.count(fn evt -> length(evt["matched_keywords"]) > 0 end) template = "report.slime" |> File.read! Slime.render(template, events: events, match_count: match_count) |> (fn output -> File.write("report.html", output) end).()
29.696429
79
0.639206
734943dfae9e74780d54e313554c88c9becb8bef
1,130
ex
Elixir
web/controllers/paste_controller.ex
redvers/pastenix
53f10765769b6695cf2a73cd007869d18dd183b4
[ "MIT" ]
6
2015-02-25T06:13:45.000Z
2016-04-11T13:06:13.000Z
web/controllers/paste_controller.ex
redvers/pastenix
53f10765769b6695cf2a73cd007869d18dd183b4
[ "MIT" ]
null
null
null
web/controllers/paste_controller.ex
redvers/pastenix
53f10765769b6695cf2a73cd007869d18dd183b4
[ "MIT" ]
null
null
null
defmodule Pastenix.Controller.Paste do use Phoenix.Controller plug :action def index(conn, _params) do lastpastes = Pastenix.Paste.fetchPublicMeta(10) render conn, "index.html", %{lastpastes: lastpastes} end def create(conn, %{"pastetext" => content, "title" => title, "permissions" => perms}) do uuid = Pastenix.Paste.create(%PasteDB.Paste{date: Timex.Date.now(:secs), content: content, title: title, public: is_public?(perms)}) redirect conn, to: "/paste/" <> uuid end def fetch(conn, %{"id" => id}) do lastpastes = Pastenix.Paste.fetchPublicMeta(10) pasterecord = Pastenix.Paste.fetch(id) render conn, "show.html", %{paste: pasterecord, lastpastes: lastpastes} end def edit(conn, %{"id" => id, "pastetext" => content, "title" => title, "permissions" => perms}) do uuid = Pastenix.Paste.edit(%PasteDB.Paste{id: id, date: Timex.Date.now(:secs), content: content, title: title, public: is_public?(perms)}) redirect conn, to: "/paste/" <> uuid end defp is_public?("public") do true end defp is_public?("private") do false end end
28.974359
142
0.656637
73496bb4281597541e36660fcc9758cee286bfe4
1,056
exs
Elixir
apps/omg_watcher_info/test/test_helper.exs
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
apps/omg_watcher_info/test/test_helper.exs
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
apps/omg_watcher_info/test/test_helper.exs
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
# Copyright 2019-2020 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ExUnit.configure(exclude: [integration: true, property: true, wrappers: true]) ExUnitFixtures.start() ExUnit.start() {:ok, _} = Application.ensure_all_started(:httpoison) {:ok, _} = Application.ensure_all_started(:fake_server) {:ok, _} = Application.ensure_all_started(:briefly) {:ok, _} = Application.ensure_all_started(:erlexec) {:ok, _} = Application.ensure_all_started(:ex_machina) Mix.Task.run("ecto.create", ~w(--quiet)) Mix.Task.run("ecto.migrate", ~w(--quiet))
39.111111
78
0.751894
73496d7b529eb5e318b36c4c12f26b08f5ffa549
6,256
ex
Elixir
api/lib/worker/index_adapter.ex
lucas-angermann/idai-field-web
788c9c9505b6fd12d591345b23053e934f1022d1
[ "Apache-2.0" ]
null
null
null
api/lib/worker/index_adapter.ex
lucas-angermann/idai-field-web
788c9c9505b6fd12d591345b23053e934f1022d1
[ "Apache-2.0" ]
null
null
null
api/lib/worker/index_adapter.ex
lucas-angermann/idai-field-web
788c9c9505b6fd12d591345b23053e934f1022d1
[ "Apache-2.0" ]
null
null
null
defmodule Api.Worker.IndexAdapter do require Logger alias Api.Core.Config defguard is_ok(status_code) when status_code >= 200 and status_code < 300 defguard is_error(status_code) when status_code >= 400 @doc """ Indexes a single document """ def process(project, index), do: fn change -> process(change, project, index) end def process(nil, _, _), do: nil def process(change = %{deleted: true}, project, index) do # TODO: mark documents as deleted instead of removing them from index case HTTPoison.delete(get_doc_url(change.id, index)) do # Deleted documents possibly never existed in the index, so ignore 404s {:ok, %HTTPoison.Response{status_code: 404, body: _}} -> nil result -> handle_result(result, change, project) end end def process(change, project, index) do HTTPoison.put( get_doc_url(change.id, index), Poison.encode!(change.doc), [{"Content-Type", "application/json"}] ) |> handle_result(change, project) end @doc """ Creates a new index with new name for a given project, where the project is given by an index alias. Returns a concrete index name for a project, as given by an index alias, which can be written to. """ def create_new_index_and_set_alias(project) do alias = "#{Config.get(:elasticsearch_index_prefix)}_#{project}" {new_index, old_index} = get_new_index_name(alias) add_index(new_index) {new_index, old_index} end def remove_stale_index_alias(project) do alias = "#{Config.get(:elasticsearch_index_prefix)}_#{project}" {new_index, _old_index} = get_new_index_name(alias) # TODO handle failure with {:ok, %HTTPoison.Response{body: body}} <- HTTPoison.delete("#{Config.get(:elasticsearch_url)}/#{new_index}"), body <- Poison.decode! body do case body do %{ "acknowledged" => true } -> IO.puts "done" # TODO return message to caller? _ -> nil end else _err -> nil end end def add_alias_and_remove_old_index(project, new_index, old_index) do alias = "#{Config.get(:elasticsearch_index_prefix)}_#{project}" when_alias_exists(alias, fn -> remove_alias(old_index, alias) end) add_alias(new_index, alias) if old_index != nil, do: when_index_exists(old_index, fn -> remove_index(old_index) end) end def update_mapping_template() do with {:ok, body} <- File.read("resources/elasticsearch-mapping.json"), {:ok, _} <- HTTPoison.put(get_template_url(), body, [{"Content-Type", "application/json"}]) do Logger.info "Successfully updated index mapping template" else err -> Logger.error "Updating index mapping failed: #{inspect err}" end end defp get_doc_url(id, index), do: "#{Config.get(:elasticsearch_url)}/#{index}/_doc/#{id}" defp get_template_url() do "#{Config.get(:elasticsearch_url)}/" <> "_template/" <> "#{Config.get(:elasticsearch_index_prefix)}" end defp handle_result({:ok, %HTTPoison.Response{status_code: status_code, body: body}}, _, _) when is_ok(status_code) do Poison.decode!(body) end defp handle_result({:ok, %HTTPoison.Response{status_code: status_code, body: body}}, change, project) when is_error(status_code) do result = Poison.decode!(body) Logger.error "Updating index failed! status_code: #{status_code} project: #{project} id: #{change.id} result: #{inspect result}" nil end defp handle_result({:error, %HTTPoison.Error{reason: reason}}, change, project) do Logger.error "Updating index failed! project: #{project} id: #{change.id} reason: #{inspect reason}" nil end defp when_index_exists(index, f) do with {:ok, %HTTPoison.Response{body: body}} <- HTTPoison.get("#{Config.get(:elasticsearch_url)}/#{index}") do body = Poison.decode! body if Map.has_key?(body, "error"), do: nil, else: f.() else _err -> nil end end defp when_alias_exists(alias, f) do with {:ok, %HTTPoison.Response{body: body}} <- HTTPoison.get("#{Config.get(:elasticsearch_url)}/#{alias}/_alias") do body = Poison.decode! body if Map.has_key?(body, "error"), do: nil, else: f.() else _err -> nil end end defp add_index(index) do with {:ok, _} <- HTTPoison.put("#{Config.get(:elasticsearch_url)}/#{index}") do Logger.info "Successfully created index #{index}" else err -> Logger.error "Creating index failed: #{inspect err}" end end defp remove_index(index) do with {:ok, _} <-HTTPoison.delete("#{Config.get(:elasticsearch_url)}/#{index}") do Logger.info "Successfully removed index #{index}" else err -> Logger.error "Creating alias failed: #{inspect err}" end end defp add_alias(index, alias) do with {:ok, %HTTPoison.Response{body: _body}} <- HTTPoison.post("#{Config.get(:elasticsearch_url)}/_aliases", Poison.encode!(%{ actions: %{ add: %{ index: index, alias: alias } }}), [{"Content-Type", "application/json"}]) do Logger.info "Successfully created alias #{alias} for index #{index}" else err -> Logger.error "Creating alias failed: #{inspect err}" end end defp remove_alias(index, alias) do with {:ok, _} <- HTTPoison.post("#{Config.get(:elasticsearch_url)}/_aliases", Poison.encode!(%{ actions: %{ remove: %{ index: index, alias: alias } }}), [{"Content-Type", "application/json"}]) do Logger.info "Successfully removed alias #{alias} from index #{index}" else err -> Logger.error "Removing alias failed: #{inspect err}" end end defp get_new_index_name(alias) do with {:ok, %HTTPoison.Response{body: body}} <- HTTPoison.get("#{Config.get(:elasticsearch_url)}/#{alias}/_alias") do body = Poison.decode! body if Map.has_key?(body, "error") do {alias <> "__a__", nil} else if String.ends_with?(List.first(Map.keys(body)), "__a__") do {alias <> "__b__", alias <> "__a__"} else {alias <> "__a__", alias <> "__b__"} end end else _err -> nil end end end
32.414508
118
0.640825
734975e2bfe66e89a0ea40e45437eceac1b748f4
791
ex
Elixir
lib/robocar/application.ex
adampointer/robocar-elixir
42ae904325f6165174275c4650f6ed6a7c7b5410
[ "MIT" ]
null
null
null
lib/robocar/application.ex
adampointer/robocar-elixir
42ae904325f6165174275c4650f6ed6a7c7b5410
[ "MIT" ]
null
null
null
lib/robocar/application.ex
adampointer/robocar-elixir
42ae904325f6165174275c4650f6ed6a7c7b5410
[ "MIT" ]
null
null
null
defmodule RoboCar.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do children = [ RoboCarWeb.Telemetry, {Phoenix.PubSub, name: RoboCar.PubSub}, RoboCarWeb.Endpoint, RoboCar.Drive, RoboCar.Sonar ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: RoboCar.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 RoboCarWeb.Endpoint.config_change(changed, removed) :ok end end
26.366667
61
0.714286
7349a2671d9dfd958ca54ff4ed10a29c40477d63
212
ex
Elixir
sample_app/lib/my_app_web/meta.ex
smanolloff/phoenix_params
90ce2f08b04db11a267ddadbf72bb645ceac275f
[ "MIT" ]
15
2018-09-05T13:36:40.000Z
2021-03-18T15:00:12.000Z
sample_app/lib/my_app_web/meta.ex
smanolloff/phoenix_params
90ce2f08b04db11a267ddadbf72bb645ceac275f
[ "MIT" ]
null
null
null
sample_app/lib/my_app_web/meta.ex
smanolloff/phoenix_params
90ce2f08b04db11a267ddadbf72bb645ceac275f
[ "MIT" ]
1
2018-11-15T09:33:53.000Z
2018-11-15T09:33:53.000Z
defmodule PhoenixParams.Meta do defstruct error_view: nil, key_type: nil, typedefs: nil, paramdefs: nil, global_validators: nil, param_names: nil end
23.555556
35
0.570755
7349b46840cc2f9da8da0a08ad8c47248bd7e176
1,975
exs
Elixir
test/controllers/page_controller_test.exs
okbreathe/quasar
58449a190aefde36aa83e5b1f3116f458ced7c09
[ "Apache-2.0" ]
11
2017-07-10T10:13:42.000Z
2021-12-19T16:46:20.000Z
test/controllers/page_controller_test.exs
okbreathe/quasar
58449a190aefde36aa83e5b1f3116f458ced7c09
[ "Apache-2.0" ]
null
null
null
test/controllers/page_controller_test.exs
okbreathe/quasar
58449a190aefde36aa83e5b1f3116f458ced7c09
[ "Apache-2.0" ]
3
2017-07-18T20:03:34.000Z
2019-07-28T13:32:49.000Z
defmodule Quasar.PageControllerTest do use Quasar.ConnCase alias Quasar.Page @valid_attrs %{} @invalid_attrs %{} setup %{conn: conn} do {:ok, conn: put_req_header(conn, "accept", "application/json")} end test "lists all entries on index", %{conn: conn} do conn = get conn, page_path(conn, :index) assert json_response(conn, 200)["data"] == [] end test "shows chosen resource", %{conn: conn} do page = Repo.insert! %Page{} conn = get conn, page_path(conn, :show, page) assert json_response(conn, 200)["data"] == %{"id" => page.id} end test "renders page not found when id is nonexistent", %{conn: conn} do assert_error_sent 404, fn -> get conn, page_path(conn, :show, -1) end end test "creates and renders resource when data is valid", %{conn: conn} do conn = post conn, page_path(conn, :create), page: @valid_attrs assert json_response(conn, 201)["data"]["id"] assert Repo.get_by(Page, @valid_attrs) end test "does not create resource and renders errors when data is invalid", %{conn: conn} do conn = post conn, page_path(conn, :create), page: @invalid_attrs assert json_response(conn, 422)["errors"] != %{} end test "updates and renders chosen resource when data is valid", %{conn: conn} do page = Repo.insert! %Page{} conn = put conn, page_path(conn, :update, page), page: @valid_attrs assert json_response(conn, 200)["data"]["id"] assert Repo.get_by(Page, @valid_attrs) end test "does not update chosen resource and renders errors when data is invalid", %{conn: conn} do page = Repo.insert! %Page{} conn = put conn, page_path(conn, :update, page), page: @invalid_attrs assert json_response(conn, 422)["errors"] != %{} end test "deletes chosen resource", %{conn: conn} do page = Repo.insert! %Page{} conn = delete conn, page_path(conn, :delete, page) assert response(conn, 204) refute Repo.get(Page, page.id) end end
32.916667
98
0.662785
7349cc1e405649f9029ab1ee6d3ff112322f59fd
291
exs
Elixir
priv/repo/migrations/20210331021358_create_orders_items_table.exs
cassiofariasmachado/rockelivery
3d88d4d8af1cdc3f2988edc69162d848009babbd
[ "MIT" ]
1
2021-09-27T06:15:08.000Z
2021-09-27T06:15:08.000Z
priv/repo/migrations/20210331021358_create_orders_items_table.exs
cassiofariasmachado/rockelivery
3d88d4d8af1cdc3f2988edc69162d848009babbd
[ "MIT" ]
null
null
null
priv/repo/migrations/20210331021358_create_orders_items_table.exs
cassiofariasmachado/rockelivery
3d88d4d8af1cdc3f2988edc69162d848009babbd
[ "MIT" ]
1
2021-12-21T12:47:59.000Z
2021-12-21T12:47:59.000Z
defmodule Rockelivery.Repo.Migrations.CreateOrdersItemsTable do use Ecto.Migration def change do create table(:orders_items, primary_key: false) do add :item_id, references(:items, type: :binary_id) add :order_id, references(:orders, type: :binary_id) end end end
26.454545
63
0.731959
7349f07c9e2c711d795341a7de982665f75c7d0d
1,084
exs
Elixir
mix.exs
LostKobrakai/inch_ex
714bb76ede1c1b529c3269d02e96c31188e69758
[ "MIT" ]
null
null
null
mix.exs
LostKobrakai/inch_ex
714bb76ede1c1b529c3269d02e96c31188e69758
[ "MIT" ]
null
null
null
mix.exs
LostKobrakai/inch_ex
714bb76ede1c1b529c3269d02e96c31188e69758
[ "MIT" ]
null
null
null
defmodule InchEx.Mixfile do use Mix.Project def project do [ app: :inch_ex, version: "2.0.0-rc1", elixir: "~> 1.7.0-dev", description: "Provides a Mix task that gives you hints where to improve your inline docs", source_url: "https://github.com/rrrene/inch_ex", package: [ maintainers: ["René Föhring"], licenses: ["MIT"], links: %{ "GitHub" => "https://github.com/rrrene/inch_ex" } ], deps: deps() ] end # Configuration for the OTP application # # Type `mix help compile.app` for more information def application do [mod: {InchEx.Application, []}, applications: [:bunt, :logger, :inets]] end # Dependencies can be Hex packages: # # {:mydep, "~> 0.3.0"} # # Or git/path repositories: # # {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"} # # Type `mix help deps` for more examples and options defp deps do [ {:jason, "~> 1.0"}, {:bunt, "~> 0.2"}, {:credo, "~> 0.10", only: :dev} ] end end
23.565217
96
0.559963
734a3664ffe457d97724d62f60be8f25ffef783a
1,293
ex
Elixir
kousa/lib/broth/message/user/get_following.ex
samyadel/dogehouse
c9daffbfe81a7488093b07f3f9a274a062dde801
[ "MIT" ]
2
2021-05-01T16:57:50.000Z
2021-07-07T22:01:14.000Z
kousa/lib/broth/message/user/get_following.ex
32Bites/dogehouse
ac70ced30a7f967979715a98a47ea2ac92f3344d
[ "MIT" ]
null
null
null
kousa/lib/broth/message/user/get_following.ex
32Bites/dogehouse
ac70ced30a7f967979715a98a47ea2ac92f3344d
[ "MIT" ]
null
null
null
defmodule Broth.Message.User.GetFollowing do use Broth.Message.Call @primary_key false embedded_schema do field(:username, :string) field(:cursor, :integer, default: 0) field(:limit, :integer, default: 100) end def changeset(initializer \\ %__MODULE__{}, data) do initializer |> cast(data, [:cursor, :limit, :username]) |> validate_number(:limit, greater_than: 0, message: "too low") end defmodule Reply do use Broth.Message.Push @derive {Jason.Encoder, only: [:following, :nextCursor]} @primary_key false embedded_schema do embeds_many(:following, Beef.Schemas.User) field(:nextCursor, :integer) field(:initial, :boolean) end end def execute(changeset, state) do alias Beef.Follows with {:ok, request} <- apply_action(changeset, :validate) do {users, next_cursor} = if is_nil(request.username) do Follows.get_my_following(state.user_id, request.cursor) else Kousa.Follow.get_follow_list_by_username( state.user_id, request.username, true, request.cursor ) end {:reply, %Reply{following: users, nextCursor: next_cursor, initial: request.cursor == 0}, state} end end end
25.352941
95
0.639598
734a41d93fea615fd1a6021f606db9cf0b38af30
1,989
ex
Elixir
apps/artemis_web/lib/artemis_web/live/summary_data_centers_map_live.ex
artemis-platform/artemis_dashboard
5ab3f5ac4c5255478bbebf76f0e43b44992e3cab
[ "MIT" ]
9
2019-08-19T19:56:34.000Z
2022-03-22T17:56:38.000Z
apps/artemis_web/lib/artemis_web/live/summary_data_centers_map_live.ex
chrislaskey/atlas_dashboard
9009ef5aac8fefba126fa7d3e3b82d1b610ee6fe
[ "MIT" ]
7
2019-07-12T21:41:01.000Z
2020-08-17T21:29:22.000Z
apps/artemis_web/lib/artemis_web/live/summary_data_centers_map_live.ex
chrislaskey/atlas_dashboard
9009ef5aac8fefba126fa7d3e3b82d1b610ee6fe
[ "MIT" ]
2
2019-04-10T13:34:15.000Z
2019-05-17T02:42:24.000Z
defmodule ArtemisWeb.SummaryDataCentersMapLive do use ArtemisWeb.LiveView # LiveView Callbacks @impl true def mount(_params, session, socket) do broadcast_topic = Artemis.CacheEvent.get_broadcast_topic() assigns = socket |> assign(:data, []) |> assign(:id, session["id"]) |> assign(:status, :loading) |> assign(:user, session["user"]) socket = update_data(assigns, :loaded) :ok = ArtemisPubSub.subscribe(broadcast_topic) {:ok, socket} end @impl true def render(assigns) do Phoenix.View.render(ArtemisWeb.LayoutView, "summary_data_centers_map_data.html", assigns) end # GenServer Callbacks @impl true def handle_info({:update_data, status}, socket) do socket = update_data(socket, status) {:noreply, socket} end def handle_info(%{event: "cache:reset", payload: payload}, socket) do update_if_match(socket, payload) {:noreply, socket} end def handle_info(_, socket), do: {:noreply, socket} # Helpers defp update_if_match(socket, payload) do if module_match?(socket, payload) do Process.send(self(), {:update_data, :updated}, []) end end defp module_match?(_socket, %{module: module}) do module == Artemis.ListDataCenters end defp update_data(socket, status) do data = get_data(socket) socket |> assign(:data, data) |> assign(:status, status) end defp get_data(socket) do params = %{ paginate: false } params |> Artemis.ListDataCenters.call_with_cache(socket.assigns.user) |> Map.get(:data) |> Enum.map(fn record -> %{} |> Map.put(:title, record.name) |> Map.put(:latitude, record.latitude && String.to_float(record.latitude)) |> Map.put(:longitude, record.longitude && String.to_float(record.longitude)) |> Map.put(:url, ArtemisWeb.Router.Helpers.data_center_path(socket, :show, record.id)) |> Map.put(:color, Enum.random(["#e14eca"])) end) end end
23.678571
93
0.657114
734a72579ea411e3d38286890b0e4329fa0a288c
4,961
exs
Elixir
test/langs/brainfuck/brainfuck_test.exs
Arvid-L/Esolix
b600b10c82433d737af046775582f5232a7e27f5
[ "MIT" ]
null
null
null
test/langs/brainfuck/brainfuck_test.exs
Arvid-L/Esolix
b600b10c82433d737af046775582f5232a7e27f5
[ "MIT" ]
null
null
null
test/langs/brainfuck/brainfuck_test.exs
Arvid-L/Esolix
b600b10c82433d737af046775582f5232a7e27f5
[ "MIT" ]
null
null
null
defmodule Esolix.Langs.BrainfuckTest do use ExUnit.Case, async: true import ExUnit.CaptureIO alias Esolix.Langs.Brainfuck describe "eval/3" do test "Example code should print \"Hello World!\"" do assert Brainfuck.eval("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.") == "Hello World!\n" end test "should mirror input" do assert Brainfuck.eval(",.,.,.,.,.,.", input: "hello!") == "hello!" end # https://esolangs.org/wiki/Brainfuck#Examples and scroll to Cell Size test "should calculate cell byte size correctly for 1 byte" do assert Brainfuck.eval(""" Calculate the value 256 and test if it's zero If the interpreter errors on overflow this is where it'll happen ++++++++[>++++++++<-]>[<++++>-] +<[>-< Not zero so multiply by 256 again to get 65536 [>++++<-]>[<++++++++>-]<[>++++++++<-] +>[> # Print "32" ++++++++++[>+++++<-]>+.-.[-]< <[-]<->] <[>> # Print "16" +++++++[>+++++++<-]>.+++++.[-]< <<-]] >[> # Print "8" ++++++++[>+++++++<-]>.[-]< <-]< # Print " bit cells\n" +++++++++++[>+++>+++++++++>+++++++++>+<<<<-]>-.>-.+++++++.+++++++++++.<. >>.++.+++++++..<-.>>- Clean up used cells. [[-]<] """) == "8 bit cells\n" end test "should calculate cell byte size correctly for 2 bytes" do assert Brainfuck.eval( """ Calculate the value 256 and test if it's zero If the interpreter errors on overflow this is where it'll happen ++++++++[>++++++++<-]>[<++++>-] +<[>-< Not zero so multiply by 256 again to get 65536 [>++++<-]>[<++++++++>-]<[>++++++++<-] +>[> # Print "32" ++++++++++[>+++++<-]>+.-.[-]< <[-]<->] <[>> # Print "16" +++++++[>+++++++<-]>.+++++.[-]< <<-]] >[> # Print "8" ++++++++[>+++++++<-]>.[-]< <-]< # Print " bit cells\n" +++++++++++[>+++>+++++++++>+++++++++>+<<<<-]>-.>-.+++++++.+++++++++++.<. >>.++.+++++++..<-.>>- Clean up used cells. [[-]<] """, tape_params: [cell_byte_size: 2] ) == "16 bit cells\n" end test "should calculate cell byte size correctly for 4 bytes" do assert Brainfuck.eval( """ Calculate the value 256 and test if it's zero If the interpreter errors on overflow this is where it'll happen ++++++++[>++++++++<-]>[<++++>-] +<[>-< Not zero so multiply by 256 again to get 65536 [>++++<-]>[<++++++++>-]<[>++++++++<-] +>[> # Print "32" ++++++++++[>+++++<-]>+.-.[-]< <[-]<->] <[>> # Print "16" +++++++[>+++++++<-]>.+++++.[-]< <<-]] >[> # Print "8" ++++++++[>+++++++<-]>.[-]< <-]< # Print " bit cells\n" +++++++++++[>+++>+++++++++>+++++++++>+<<<<-]>-.>-.+++++++.+++++++++++.<. >>.++.+++++++..<-.>>- Clean up used cells. [[-]<] """, tape_params: [cell_byte_size: 4] ) == "32 bit cells\n" end end describe "eval_file/3" do test "should throw error on wrong file extension" do assert_raise Esolix.Langs.Brainfuck.WrongFileExtensionError, fn -> Brainfuck.eval_file("not_a_brainfuck_file.png") end end test "hello_world.bf should print \"Hello World!\"" do assert Brainfuck.eval_file("test/langs/brainfuck/hello_world.bf") == "Hello World!\n" end test "byte_size.bf should calculate correct byte size" do assert Brainfuck.eval_file("test/langs/brainfuck/byte_size.bf", tape_params: [cell_byte_size: 1] ) == "8 bit cells\n" assert Brainfuck.eval_file("test/langs/brainfuck/byte_size.bf", tape_params: [cell_byte_size: 2] ) == "16 bit cells\n" assert Brainfuck.eval_file("test/langs/brainfuck/byte_size.bf", tape_params: [cell_byte_size: 4] ) == "32 bit cells\n" end end end
38.757813
157
0.350333
734a889e50c6d418a4bbb46e25e645e4c94aeb2c
86
exs
Elixir
test/lv_template_web/views/page_view_test.exs
ustrajunior/lv_template
633c85d8c5810a130bbf24077845dda49e82ca3f
[ "MIT" ]
null
null
null
test/lv_template_web/views/page_view_test.exs
ustrajunior/lv_template
633c85d8c5810a130bbf24077845dda49e82ca3f
[ "MIT" ]
null
null
null
test/lv_template_web/views/page_view_test.exs
ustrajunior/lv_template
633c85d8c5810a130bbf24077845dda49e82ca3f
[ "MIT" ]
null
null
null
defmodule LvTemplateWeb.PageViewTest do use LvTemplateWeb.ConnCase, async: true end
21.5
41
0.837209
734ada13af95f6392480d41825f778dad06afd09
23,087
ex
Elixir
apps/language_server/lib/language_server/server.ex
hauleth/elixir-ls
5bf39b8ac617074ed019ace26fa7fad25bbbd1ce
[ "Apache-2.0" ]
null
null
null
apps/language_server/lib/language_server/server.ex
hauleth/elixir-ls
5bf39b8ac617074ed019ace26fa7fad25bbbd1ce
[ "Apache-2.0" ]
null
null
null
apps/language_server/lib/language_server/server.ex
hauleth/elixir-ls
5bf39b8ac617074ed019ace26fa7fad25bbbd1ce
[ "Apache-2.0" ]
null
null
null
defmodule ElixirLS.LanguageServer.Server do @moduledoc """ Language Server Protocol server This server tracks open files, attempts to rebuild the project when a file changes, and handles requests from the IDE (for things like autocompletion, hover, etc.) Notifications from the IDE are handled synchronously, whereas requests can be handled sychronously or asynchronously. When possible, handling the request asynchronously has several advantages. The asynchronous request handling cannot modify the server state. That way, if the process handling the request crashes, we can report that error to the client and continue knowing that the state is uncorrupted. Also, asynchronous requests can be cancelled by the client if they're taking too long or the user no longer cares about the result. """ use GenServer alias ElixirLS.LanguageServer.{SourceFile, Build, Protocol, JsonRpc, Dialyzer} alias ElixirLS.LanguageServer.Providers.{ Completion, Hover, Definition, References, Formatting, SignatureHelp, DocumentSymbols, WorkspaceSymbols, OnTypeFormatting, CodeLens, ExecuteCommand } use Protocol defstruct [ :build_ref, :dialyzer_sup, :client_capabilities, :root_uri, :project_dir, :settings, build_diagnostics: [], dialyzer_diagnostics: [], needs_build?: false, load_all_modules?: false, build_running?: false, analysis_ready?: false, received_shutdown?: false, requests: %{}, # Tracks source files that are currently open in the editor source_files: %{}, awaiting_contracts: [] ] ## Client API def start_link(name \\ nil) do GenServer.start_link(__MODULE__, :ok, name: name) end def receive_packet(server \\ __MODULE__, packet) do GenServer.cast(server, {:receive_packet, packet}) end def build_finished(server \\ __MODULE__, result) do GenServer.cast(server, {:build_finished, result}) end def dialyzer_finished(server \\ __MODULE__, diagnostics, build_ref) do GenServer.cast(server, {:dialyzer_finished, diagnostics, build_ref}) end def rebuild(server \\ __MODULE__) do GenServer.cast(server, :rebuild) end def suggest_contracts(server \\ __MODULE__, uri) do GenServer.call(server, {:suggest_contracts, uri}, :infinity) end ## Server Callbacks @impl GenServer def init(:ok) do {:ok, %__MODULE__{}} end @impl GenServer def handle_call({:request_finished, id, result}, _from, state) do case result do {:error, type, msg} -> JsonRpc.respond_with_error(id, type, msg) {:ok, result} -> JsonRpc.respond(id, result) end state = %{state | requests: Map.delete(state.requests, id)} {:reply, :ok, state} end @impl GenServer def handle_call({:suggest_contracts, uri}, from, state) do case state do %{analysis_ready?: true, source_files: %{^uri => %{dirty?: false}}} -> {:reply, Dialyzer.suggest_contracts([SourceFile.path_from_uri(uri)]), state} _ -> {:noreply, %{state | awaiting_contracts: [{from, uri} | state.awaiting_contracts]}} end end @impl GenServer def handle_cast({:build_finished, {status, diagnostics}}, state) when status in [:ok, :noop, :error] and is_list(diagnostics) do {:noreply, handle_build_result(status, diagnostics, state)} end @impl GenServer def handle_cast({:dialyzer_finished, diagnostics, build_ref}, state) do {:noreply, handle_dialyzer_result(diagnostics, build_ref, state)} end @impl GenServer def handle_cast({:receive_packet, request(id, _, _) = packet}, state) do {:noreply, handle_request_packet(id, packet, state)} end def handle_cast({:receive_packet, request(id, method)}, state) do {:noreply, handle_request_packet(id, request(id, method, nil), state)} end @impl GenServer def handle_cast({:receive_packet, notification(_) = packet}, state) do {:noreply, handle_notification(packet, state)} end @impl GenServer def handle_cast(:rebuild, state) do {:noreply, trigger_build(state)} end @impl GenServer def handle_info(:send_file_watchers, state) do JsonRpc.register_capability_request("workspace/didChangeWatchedFiles", %{ "watchers" => [ %{"globPattern" => "**/*.ex"}, %{"globPattern" => "**/*.exs"}, %{"globPattern" => "**/*.eex"}, %{"globPattern" => "**/*.leex"} ] }) {:noreply, state} end @impl GenServer def handle_info(:default_config, state) do state = case state do %{settings: nil} -> JsonRpc.show_message( :info, "Did not receive workspace/didChangeConfiguration notification after 5 seconds. " <> "Using default settings." ) set_settings(state, %{}) _ -> state end {:noreply, state} end @impl GenServer def handle_info({:DOWN, ref, _, _pid, reason}, %{build_ref: ref, build_running?: true} = state) do state = %{state | build_running?: false} state = case reason do :normal -> state _ -> handle_build_result(:error, [Build.exception_to_diagnostic(reason)], state) end state = if state.needs_build?, do: trigger_build(state), else: state {:noreply, state} end @impl GenServer def handle_info({:DOWN, _ref, :process, pid, reason}, %{requests: requests} = state) do state = case Enum.find(requests, &match?({_, ^pid}, &1)) do {id, _} -> error_msg = Exception.format_exit(reason) JsonRpc.respond_with_error(id, :server_error, error_msg) %{state | requests: Map.delete(requests, id)} nil -> state end {:noreply, state} end ## Helpers defp handle_notification(notification("initialized"), state) do state end defp handle_notification(notification("$/setTraceNotification"), state) do # noop state end defp handle_notification(cancel_request(id), %{requests: requests} = state) do case requests do %{^id => pid} -> Process.exit(pid, :cancelled) JsonRpc.respond_with_error(id, :request_cancelled, "Request cancelled") %{state | requests: Map.delete(requests, id)} _ -> state end end # We don't start performing builds until we receive settings from the client in case they've set # the `projectDir` or `mixEnv` settings. If the settings don't match the format expected, leave # settings unchanged or set default settings if this is the first request. defp handle_notification(did_change_configuration(changed_settings), state) do prev_settings = state.settings || %{} new_settings = case changed_settings do %{"elixirLS" => changed_settings} when is_map(changed_settings) -> Map.merge(prev_settings, changed_settings) _ -> prev_settings end set_settings(state, new_settings) end defp handle_notification(notification("exit"), state) do code = if state.received_shutdown?, do: 0, else: 1 System.halt(code) state end defp handle_notification(did_open(uri, _language_id, version, text), state) do source_file = %SourceFile{text: text, version: version} Build.publish_file_diagnostics( uri, state.build_diagnostics ++ state.dialyzer_diagnostics, source_file ) put_in(state.source_files[uri], source_file) end defp handle_notification(did_close(uri), state) do awaiting_contracts = Enum.reject(state.awaiting_contracts, fn {from, ^uri} -> GenServer.reply(from, []) _ -> false end) %{ state | source_files: Map.delete(state.source_files, uri), awaiting_contracts: awaiting_contracts } end defp handle_notification(did_change(uri, version, content_changes), state) do update_in(state.source_files[uri], fn nil -> # The source file was not marked as open either due to a bug in the # client or a restart of the server. So just ignore the message and do # not update the state IO.warn( "Received textDocument/didChange for file that is not open. Received uri: #{ inspect(uri) }" ) nil source_file -> source_file = %{source_file | version: version, dirty?: true} SourceFile.apply_content_changes(source_file, content_changes) end) end defp handle_notification(did_save(uri), state) do WorkspaceSymbols.notify_uris_modified([uri]) state = update_in(state.source_files[uri], &%{&1 | dirty?: false}) trigger_build(state) end defp handle_notification(did_change_watched_files(changes), state) do needs_build = Enum.any?(changes, fn %{"uri" => uri, "type" => type} -> Path.extname(uri) in [".ex", ".exs", ".erl", ".yrl", ".xrl", ".eex", ".leex"] and (type in [1, 3] or not Map.has_key?(state.source_files, uri)) end) changes |> Enum.map(& &1["uri"]) |> Enum.uniq() |> WorkspaceSymbols.notify_uris_modified() if needs_build, do: trigger_build(state), else: state end defp handle_notification(notification(_, _) = packet, state) do IO.warn("Received unmatched notification: #{inspect(packet)}") state end defp handle_request_packet(id, packet, state) do case handle_request(packet, state) do {:ok, result, state} -> JsonRpc.respond(id, result) state {:error, type, msg, state} -> JsonRpc.respond_with_error(id, type, msg) state {:async, fun, state} -> {pid, _ref} = handle_request_async(id, fun) %{state | requests: Map.put(state.requests, id, pid)} end end defp handle_request(initialize_req(_id, root_uri, client_capabilities), state) do show_version_warnings() state = case root_uri do "file://" <> _ -> root_path = SourceFile.path_from_uri(root_uri) File.cd!(root_path) %{state | root_uri: root_uri} nil -> state end state = %{state | client_capabilities: client_capabilities} # If we don't receive workspace/didChangeConfiguration for 5 seconds, use default settings Process.send_after(self(), :default_config, 5000) # Explicitly request file watchers from the client if supported supports_dynamic = get_in(client_capabilities, [ "textDocument", "codeAction", "dynamicRegistration" ]) if supports_dynamic do Process.send_after(self(), :send_file_watchers, 100) end {:ok, %{"capabilities" => server_capabilities()}, state} end defp handle_request(request(_id, "shutdown", _params), state) do {:ok, nil, %{state | received_shutdown?: true}} end defp handle_request(definition_req(_id, uri, line, character), state) do fun = fn -> Definition.definition(uri, state.source_files[uri].text, line, character) end {:async, fun, state} end defp handle_request(references_req(_id, uri, line, character, include_declaration), state) do fun = fn -> {:ok, References.references( state.source_files[uri].text, uri, line, character, include_declaration )} end {:async, fun, state} end defp handle_request(hover_req(_id, uri, line, character), state) do fun = fn -> Hover.hover(state.source_files[uri].text, line, character) end {:async, fun, state} end defp handle_request(document_symbol_req(_id, uri), state) do fun = fn -> hierarchical? = get_in(state.client_capabilities, [ "textDocument", "documentSymbol", "hierarchicalDocumentSymbolSupport" ]) || false source_file = state.source_files[uri] if source_file do DocumentSymbols.symbols(uri, source_file.text, hierarchical?) else {:ok, []} end end {:async, fun, state} end defp handle_request(workspace_symbol_req(_id, query), state) do fun = fn -> state.source_files WorkspaceSymbols.symbols(query) end {:async, fun, state} end defp handle_request(completion_req(_id, uri, line, character), state) do snippets_supported = !!get_in(state.client_capabilities, [ "textDocument", "completion", "completionItem", "snippetSupport" ]) # deprecated as of Language Server Protocol Specification - 3.15 deprecated_supported = !!get_in(state.client_capabilities, [ "textDocument", "completion", "completionItem", "deprecatedSupport" ]) tags_supported = case get_in(state.client_capabilities, [ "textDocument", "completion", "completionItem", "tagSupport" ]) do nil -> [] %{"valueSet" => value_set} -> value_set end fun = fn -> Completion.completion(state.source_files[uri].text, line, character, snippets_supported: snippets_supported, deprecated_supported: deprecated_supported, tags_supported: tags_supported ) end {:async, fun, state} end defp handle_request(formatting_req(_id, uri, _options), state) do case state.source_files[uri] do nil -> {:error, :server_error, "Missing source file", state} source_file -> fun = fn -> Formatting.format(source_file, uri, state.project_dir) end {:async, fun, state} end end defp handle_request(signature_help_req(_id, uri, line, character), state) do fun = fn -> SignatureHelp.signature(state.source_files[uri], line, character) end {:async, fun, state} end defp handle_request(on_type_formatting_req(_id, uri, line, character, ch, options), state) do fun = fn -> OnTypeFormatting.format(state.source_files[uri], line, character, ch, options) end {:async, fun, state} end defp handle_request(code_lens_req(_id, uri), state) do if dialyzer_enabled?(state) and state.settings["suggestSpecs"] != false do {:async, fn -> CodeLens.code_lens(uri, state.source_files[uri].text) end, state} else {:ok, nil, state} end end defp handle_request(execute_command_req(_id, command, args), state) do {:async, fn -> ExecuteCommand.execute(command, args, state.source_files) end, state} end defp handle_request(macro_expansion(_id, whole_buffer, selected_macro, macro_line), state) do x = ElixirSense.expand_full(whole_buffer, selected_macro, macro_line) {:ok, x, state} end defp handle_request(request(_, _) = req, state) do handle_invalid_request(req, state) end defp handle_request(request(_, _, _) = req, state) do handle_invalid_request(req, state) end defp handle_invalid_request(req, state) do IO.inspect(req, label: "Unmatched request") {:error, :invalid_request, nil, state} end defp handle_request_async(id, func) do parent = self() spawn_monitor(fn -> result = func.() GenServer.call(parent, {:request_finished, id, result}, :infinity) end) end defp server_capabilities do %{ "macroExpansion" => true, "textDocumentSync" => %{ "change" => 2, "openClose" => true, "save" => %{"includeText" => true} }, "hoverProvider" => true, "completionProvider" => %{"triggerCharacters" => Completion.trigger_characters()}, "definitionProvider" => true, "referencesProvider" => References.supported?(), "documentFormattingProvider" => Formatting.supported?(), "signatureHelpProvider" => %{"triggerCharacters" => ["("]}, "documentSymbolProvider" => true, "workspaceSymbolProvider" => true, "documentOnTypeFormattingProvider" => %{"firstTriggerCharacter" => "\n"}, "codeLensProvider" => %{"resolveProvider" => false}, "executeCommandProvider" => %{"commands" => ["spec"]}, "workspace" => %{ "workspaceFolders" => %{"supported" => true, "changeNotifications" => true} } } end # Build defp trigger_build(state) do if build_enabled?(state) and not state.build_running? do fetch_deps? = Map.get(state.settings || %{}, "fetchDeps", true) {_pid, build_ref} = Build.build(self(), state.project_dir, fetch_deps?: fetch_deps?, load_all_modules?: state.load_all_modules? ) %__MODULE__{ state | build_ref: build_ref, needs_build?: false, build_running?: true, analysis_ready?: false, load_all_modules?: false } else %__MODULE__{state | needs_build?: true, analysis_ready?: false} end end defp dialyze(state) do warn_opts = (state.settings["dialyzerWarnOpts"] || []) |> Enum.map(&String.to_atom/1) if dialyzer_enabled?(state), do: Dialyzer.analyze(state.build_ref, warn_opts, dialyzer_default_format(state)) state end defp dialyzer_default_format(state) do state.settings["dialyzerFormat"] || "dialyxir_long" end defp handle_build_result(status, diagnostics, state) do old_diagnostics = state.build_diagnostics ++ state.dialyzer_diagnostics state = put_in(state.build_diagnostics, diagnostics) state = cond do state.needs_build? -> state status == :error or not dialyzer_enabled?(state) -> put_in(state.dialyzer_diagnostics, []) true -> dialyze(state) end publish_diagnostics( state.build_diagnostics ++ state.dialyzer_diagnostics, old_diagnostics, state.source_files ) state end defp handle_dialyzer_result(diagnostics, build_ref, state) do old_diagnostics = state.build_diagnostics ++ state.dialyzer_diagnostics state = put_in(state.dialyzer_diagnostics, diagnostics) publish_diagnostics( state.build_diagnostics ++ state.dialyzer_diagnostics, old_diagnostics, state.source_files ) # If these results were triggered by the most recent build and files are not dirty, then we know # we're up to date and can release spec suggestions to the code lens provider if build_ref == state.build_ref do JsonRpc.log_message(:info, "Dialyzer analysis is up to date") {dirty, not_dirty} = state.awaiting_contracts |> Enum.filter(fn {_, uri} -> state.source_files[uri] != nil end) |> Enum.split_with(fn {_, uri} -> state.source_files[uri].dirty? end) contracts = not_dirty |> Enum.uniq() |> Enum.map(fn {_from, uri} -> SourceFile.path_from_uri(uri) end) |> Dialyzer.suggest_contracts() for {from, uri} <- not_dirty do contracts = Enum.filter(contracts, fn {file, _, _, _, _} -> SourceFile.path_from_uri(uri) == file end) GenServer.reply(from, contracts) end WorkspaceSymbols.notify_build_complete() %{state | analysis_ready?: true, awaiting_contracts: dirty} else state end end defp build_enabled?(state) do is_binary(state.project_dir) end defp dialyzer_enabled?(state) do Dialyzer.check_support() == :ok and build_enabled?(state) and state.dialyzer_sup != nil end defp publish_diagnostics(new_diagnostics, old_diagnostics, source_files) do files = Enum.uniq(Enum.map(new_diagnostics, & &1.file) ++ Enum.map(old_diagnostics, & &1.file)) for file <- files, uri = SourceFile.path_to_uri(file), do: Build.publish_file_diagnostics(uri, new_diagnostics, Map.get(source_files, uri)) end defp show_version_warnings do unless Version.match?(System.version(), ">= 1.7.0") do JsonRpc.show_message( :warning, "Elixir versions below 1.7 are not supported. (Currently v#{System.version()})" ) end otp_release = String.to_integer(System.otp_release()) if otp_release < 20 do JsonRpc.show_message( :info, "Erlang OTP releases below 20 are not supported (Currently OTP #{otp_release})" ) end case Dialyzer.check_support() do :ok -> :ok {:error, msg} -> JsonRpc.show_message(:info, msg) end :ok end defp set_settings(state, settings) do enable_dialyzer = Dialyzer.check_support() == :ok && Map.get(settings, "dialyzerEnabled", true) mix_env = Map.get(settings, "mixEnv", "test") project_dir = Map.get(settings, "projectDir") state = state |> set_mix_env(mix_env) |> set_project_dir(project_dir) |> set_dialyzer_enabled(enable_dialyzer) state = create_gitignore(state) trigger_build(%{state | settings: settings}) end defp set_dialyzer_enabled(state, enable_dialyzer) do cond do enable_dialyzer and state.dialyzer_sup == nil and is_binary(state.project_dir) -> {:ok, pid} = Dialyzer.Supervisor.start_link(state.project_dir) %{state | dialyzer_sup: pid} not enable_dialyzer and state.dialyzer_sup != nil -> Process.exit(state.dialyzer_sup, :normal) %{state | dialyzer_sup: nil, analysis_ready?: false} true -> state end end defp set_mix_env(state, env) do prev_env = state.settings["mixEnv"] if is_nil(prev_env) or env == prev_env do Mix.env(String.to_atom(env)) else JsonRpc.show_message(:warning, "You must restart ElixirLS after changing Mix env") end state end defp set_project_dir(%{project_dir: prev_project_dir, root_uri: root_uri} = state, project_dir) when is_binary(root_uri) do root_dir = SourceFile.path_from_uri(root_uri) project_dir = if is_binary(project_dir) do Path.absname(Path.join(root_dir, project_dir)) else root_dir end cond do not File.dir?(project_dir) -> JsonRpc.show_message(:error, "Project directory #{project_dir} does not exist") state is_nil(prev_project_dir) -> File.cd!(project_dir) Map.merge(state, %{project_dir: project_dir, load_all_modules?: true}) prev_project_dir != project_dir -> JsonRpc.show_message( :warning, "You must restart ElixirLS after changing the project directory" ) state true -> state end end defp set_project_dir(state, _) do state end defp create_gitignore(%{project_dir: project_dir} = state) do with gitignore_path <- Path.join([project_dir, ".elixir_ls", ".gitignore"]), false <- File.exists?(gitignore_path), :ok <- gitignore_path |> Path.dirname() |> File.mkdir_p(), :ok <- File.write(gitignore_path, "*", [:write]) do state else true -> state {:error, err} -> JsonRpc.log_message( :warning, "Cannot create .elixir_ls/.gitignore, cause: #{Atom.to_string(err)}" ) state end end end
28.052248
100
0.646035
734b1b03b523636ae991df28e277c8f75fccf557
538
ex
Elixir
lib/events_tools/venues/hall.ex
Apps-Team/conferencetools
ce2e16a3e4a521dc4682e736a209e6dd380c050d
[ "Apache-2.0" ]
null
null
null
lib/events_tools/venues/hall.ex
Apps-Team/conferencetools
ce2e16a3e4a521dc4682e736a209e6dd380c050d
[ "Apache-2.0" ]
6
2017-10-05T20:16:34.000Z
2017-10-05T20:36:11.000Z
lib/events_tools/venues/hall.ex
apps-team/events-tools
ce2e16a3e4a521dc4682e736a209e6dd380c050d
[ "Apache-2.0" ]
null
null
null
defmodule EventsTools.Venues.Hall do use Ecto.Schema import Ecto.Changeset alias EventsTools.Venues.Hall schema "halls" do field :name, :string belongs_to :building, EventsTools.Venues.Building # this was added has_many :hall_room_plans, EventsTools.Venues.Hall_Room_Plan # this was added has_many :rooms, EventsTools.Venues.Room # this was added timestamps() end @doc false def changeset(%Hall{} = hall, attrs) do hall |> cast(attrs, [:name]) |> validate_required([:name]) end end
22.416667
82
0.700743
734b2ed7f995dfce71f042ad5953d274b780bf44
1,422
exs
Elixir
mix.exs
keichan34/webpay
49c8f5df78016632d90e7cdbfc63f34d46c26b1c
[ "MIT" ]
1
2016-05-15T14:09:18.000Z
2016-05-15T14:09:18.000Z
mix.exs
keichan34/webpay
49c8f5df78016632d90e7cdbfc63f34d46c26b1c
[ "MIT" ]
null
null
null
mix.exs
keichan34/webpay
49c8f5df78016632d90e7cdbfc63f34d46c26b1c
[ "MIT" ]
null
null
null
defmodule Webpay.Mixfile do use Mix.Project def project do [ app: :webpay, version: "0.0.1", elixir: "~> 1.2", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, elixirc_paths: elixirc_paths(Mix.env), source_url: "https://github.com/keichan34/webpay", docs: [ extras: ["README.md"] ], package: package, description: description, deps: deps ] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do [ applications: [ :logger, :poison, :httpoison, :crypto ], mod: {Webpay, []} ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] defp deps do [ {:httpoison, "~> 0.8.1"}, {:poison, "~> 2.1"}, {:exvcr, "~> 0.7", only: :test} ] end defp package do [ files: ["lib", "mix.exs", "README.md", "LICENSE.txt"], maintainers: ["Keitaroh Kobayashi"], licenses: ["MIT"], links: %{ "GitHub" => "https://github.com/keichan34/webpay", "Docs" => "http://hexdocs.pm/webpay/readme.html" } ] end defp description do """ An interface to the WebPay payment processor for Elixir. """ end end
21.223881
60
0.548523
734b348e3ac022b63a87c7fc91cc72b6f8b14e50
206
exs
Elixir
test/iex_line_bot_web/controllers/page_controller_test.exs
pastleo/iex_line_bot
73d02b45adc05bc7331fa5f88859861d04a2e71f
[ "MIT" ]
1
2019-06-24T23:55:26.000Z
2019-06-24T23:55:26.000Z
test/iex_line_bot_web/controllers/page_controller_test.exs
pastleo/iex_line_bot
73d02b45adc05bc7331fa5f88859861d04a2e71f
[ "MIT" ]
null
null
null
test/iex_line_bot_web/controllers/page_controller_test.exs
pastleo/iex_line_bot
73d02b45adc05bc7331fa5f88859861d04a2e71f
[ "MIT" ]
null
null
null
defmodule IexLineBotWeb.PageControllerTest do use IexLineBotWeb.ConnCase test "GET /", %{conn: conn} do conn = get(conn, "/") assert html_response(conn, 200) =~ "Welcome to Phoenix!" end end
22.888889
60
0.68932
734b4724e6c80e595422986f1e2569cd1e715134
3,377
exs
Elixir
test/trento/application/integration/discovery/discovery_test.exs
trento-project/web
3260b30c781bffbbb0e5205cd650966c4026b9ac
[ "Apache-2.0" ]
1
2022-03-22T16:59:34.000Z
2022-03-22T16:59:34.000Z
test/trento/application/integration/discovery/discovery_test.exs
trento-project/web
3260b30c781bffbbb0e5205cd650966c4026b9ac
[ "Apache-2.0" ]
24
2022-03-22T16:45:25.000Z
2022-03-31T13:00:02.000Z
test/trento/application/integration/discovery/discovery_test.exs
trento-project/web
3260b30c781bffbbb0e5205cd650966c4026b9ac
[ "Apache-2.0" ]
1
2022-03-30T14:16:16.000Z
2022-03-30T14:16:16.000Z
defmodule Trento.Integration.DiscoveryTest do use ExUnit.Case use Trento.DataCase import Trento.Factory alias Trento.Integration.Discovery alias Trento.Integration.Discovery.{ DiscardedDiscoveryEvent, DiscoveryEvent } test "should retrieve the current set of discovery events" do agent_id_1 = Faker.UUID.v4() agent_id_2 = Faker.UUID.v4() agent_id_3 = Faker.UUID.v4() for index <- 0..9 do insert( :discovery_event, agent_id: agent_id_1, discovery_type: "discovery_type", payload: %{"key" => index} ) insert( :discovery_event, agent_id: agent_id_2, discovery_type: "discovery_type", payload: %{"key" => index} ) insert( :discovery_event, agent_id: agent_id_3, discovery_type: "discovery_type", payload: %{"key" => index} ) end discovery_events = Discovery.get_current_discovery_events() [ %DiscoveryEvent{agent_id: ^agent_id_1, payload: %{"key" => 9}}, %DiscoveryEvent{agent_id: ^agent_id_2, payload: %{"key" => 9}}, %DiscoveryEvent{agent_id: ^agent_id_3, payload: %{"key" => 9}} ] = discovery_events end test "should retrieve the discarded discovery events" do insert( :discarded_discovery_event, payload: %{"key" => 1}, inserted_at: Timex.shift(DateTime.utc_now(), seconds: 1) ) insert( :discarded_discovery_event, payload: %{"key" => 2}, inserted_at: Timex.shift(DateTime.utc_now(), seconds: 2) ) insert( :discarded_discovery_event, payload: %{"key" => 3}, reason: "invalid value", inserted_at: Timex.shift(DateTime.utc_now(), seconds: 3) ) insert( :discarded_discovery_event, payload: %{"key" => 4}, inserted_at: Timex.shift(DateTime.utc_now(), seconds: 4) ) discarded_events = Discovery.get_discarded_discovery_events(2) [ %DiscardedDiscoveryEvent{payload: %{"key" => 4}}, %DiscardedDiscoveryEvent{payload: %{"key" => 3}, reason: "invalid value"} ] = discarded_events end test "should delete events older than the specified days" do for _ <- 0..9 do insert( :discovery_event, agent_id: Faker.UUID.v4(), discovery_type: "discovery_type", payload: %{}, inserted_at: Timex.shift(DateTime.utc_now(), days: -11) ) end assert 10 == Discovery.prune_events(10) assert 0 == DiscoveryEvent |> Trento.Repo.all() |> length() end test "should delete discarded events older than the specified days" do for _ <- 0..9 do insert( :discarded_discovery_event, payload: %{}, inserted_at: Timex.shift(DateTime.utc_now(), days: -11) ) end assert 10 == Discovery.prune_discarded_discovery_events(10) assert 0 == DiscardedDiscoveryEvent |> Trento.Repo.all() |> length() end @tag capture_log: true test "should discard discovery events with invalid payload" do event = %{ "agent_id" => "invalid_uuid", "discovery_type" => "host_discovery", "payload" => %{"key" => "value"} } {:error, _} = Discovery.handle(event) discarded_events = DiscardedDiscoveryEvent |> Trento.Repo.all() [ %DiscardedDiscoveryEvent{payload: ^event} ] = discarded_events end end
25.976923
79
0.624815
734b4e6c2224f1aee6077132bee7a96d9a399a05
2,806
ex
Elixir
lib/ecto_job/worker.ex
mbuhot/ecto_job
0d02d33e354df66a1f27a030edd6c37a8a96d1ef
[ "MIT" ]
268
2017-08-15T12:55:41.000Z
2022-03-20T22:42:18.000Z
lib/ecto_job/worker.ex
mbuhot/ecto_job
0d02d33e354df66a1f27a030edd6c37a8a96d1ef
[ "MIT" ]
52
2018-01-15T20:47:54.000Z
2021-12-24T06:13:55.000Z
lib/ecto_job/worker.ex
mbuhot/ecto_job
0d02d33e354df66a1f27a030edd6c37a8a96d1ef
[ "MIT" ]
38
2018-01-08T12:26:19.000Z
2021-06-01T12:41:09.000Z
defmodule EctoJob.Worker do @moduledoc """ Worker module responsible for executing a single Job. """ alias EctoJob.{Config, JobQueue} require Logger @type repo :: module @doc """ Equivalent to `start_link(config, job, DateTime.utc_now())`. """ @spec start_link(Config.t(), EctoJob.JobQueue.job()) :: {:ok, pid} def start_link(config, job), do: start_link(config, job, DateTime.utc_now()) @doc """ Start a worker process given a repo module and a job struct. This may fail if the job reservation has expired, in which case the job will be reactivated by the producer. """ @spec start_link(Config.t(), EctoJob.JobQueue.job(), DateTime.t()) :: {:ok, pid} def start_link(config, job, now) do Task.start_link(fn -> do_work(config, job, now) end) end @doc false @spec do_work(Config.t(), EctoJob.JobQueue.job(), DateTime.t()) :: :ok | {:error, any()} def do_work(config = %Config{repo: repo, execution_timeout: exec_timeout}, job, now) do with {:ok, in_progress_job} <- JobQueue.update_job_in_progress(repo, job, now, exec_timeout), :ok <- run_job(config, in_progress_job) do log_duration(config, in_progress_job, now) notify_completed(repo, in_progress_job) else {:error, reason} -> {:error, reason} end end @spec run_job(Config.t(), EctoJob.JobQueue.job()) :: :ok defp run_job(%Config{repo: repo, retry_timeout: timeout}, job = %queue{}) do job_failed = fn -> _ = JobQueue.job_failed(repo, job, DateTime.utc_now(), timeout) :ok end try do case queue.perform(JobQueue.initial_multi(job), job.params) do {:ok, _value} -> :ok {:error, _value} -> job_failed.() {:error, _failed_operation, _failed_value, _changes_so_far} -> job_failed.() end rescue e -> # An exception occurred, make an attempt to put the job into the RETRY state # before propagating the exception stacktrace = System.stacktrace() job_failed.() reraise(e, stacktrace) end end @spec log_duration(Config.t(), EctoJob.JobQueue.job(), DateTime.t()) :: :ok defp log_duration( %Config{log: true, log_level: log_level}, _job = %queue{id: id}, start = %DateTime{} ) do duration = DateTime.diff(DateTime.utc_now(), start, :microsecond) Logger.log(log_level, fn -> "#{queue}[#{id}] done: #{duration} µs" end) end defp log_duration(_config, _job, _start), do: :ok @spec notify_completed(repo, EctoJob.JobQueue.job()) :: :ok defp notify_completed(_repo, _job = %{notify: nil}), do: :ok defp notify_completed(repo, _job = %queue{notify: payload}) do topic = queue.__schema__(:source) <> ".completed" repo.query("SELECT pg_notify($1, $2)", [topic, payload]) :ok end end
33.807229
97
0.64861
734b5c97f2ce8499048026b744e237a89a8228f0
1,056
exs
Elixir
mix.exs
cas27/ex_taxjar
507d474dbd7e72a21b2e14194b39170b535913bc
[ "MIT" ]
6
2018-04-13T17:50:57.000Z
2019-09-08T01:25:56.000Z
mix.exs
cas27/ex_taxjar
507d474dbd7e72a21b2e14194b39170b535913bc
[ "MIT" ]
null
null
null
mix.exs
cas27/ex_taxjar
507d474dbd7e72a21b2e14194b39170b535913bc
[ "MIT" ]
1
2021-06-24T20:11:16.000Z
2021-06-24T20:11:16.000Z
defmodule ExTaxjar.MixProject do use Mix.Project def project do [ app: :ex_taxjar, version: "0.5.0", elixir: "~> 1.6", name: "ExTaxjar", description: description(), package: package(), start_permanent: Mix.env() == :prod, preferred_cli_env: [ vcr: :test, "vcr.delete": :test, "vcr.check": :test, "vcr.show": :test ], 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 [ {:httpoison, "~> 1.1"}, {:exjsx, "~> 4.0"}, {:ex_doc, ">= 0.0.0", only: :dev}, {:exvcr, "~> 0.10", only: :test} ] end defp description do "A client library for use with v2 of the TaxJar API" end defp package do [ maintainers: ["Cory Schmitt"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/cas27/ex_taxjar"} ] end end
20.307692
64
0.536932
734b5d02cf31ee826cdf097f9a8043a9b5437e2e
167,481
ex
Elixir
lib/elixir/lib/kernel.ex
dwellmind/elixir
0a248debe36ffc4a2e3626b3c5a8498e0cfb753c
[ "Apache-2.0" ]
4
2019-03-04T10:05:55.000Z
2019-03-06T17:30:59.000Z
lib/elixir/lib/kernel.ex
dwellmind/elixir
0a248debe36ffc4a2e3626b3c5a8498e0cfb753c
[ "Apache-2.0" ]
5
2015-02-07T14:46:40.000Z
2020-09-20T16:43:42.000Z
lib/elixir/lib/kernel.ex
dwellmind/elixir
0a248debe36ffc4a2e3626b3c5a8498e0cfb753c
[ "Apache-2.0" ]
2
2018-04-03T08:57:41.000Z
2019-03-04T08:20:04.000Z
# Use elixir_bootstrap module to be able to bootstrap Kernel. # The bootstrap module provides simpler implementations of the # functions removed, simple enough to bootstrap. import Kernel, except: [@: 1, defmodule: 2, def: 1, def: 2, defp: 2, defmacro: 1, defmacro: 2, defmacrop: 2] import :elixir_bootstrap defmodule Kernel do @moduledoc """ `Kernel` is Elixir's default environment. It mainly consists of: * basic language primitives, such as arithmetic operators, spawning of processes, data type handling, and others * macros for control-flow and defining new functionality (modules, functions, and the like) * guard checks for augmenting pattern matching You can invoke `Kernel` functions and macros anywhere in Elixir code without the use of the `Kernel.` prefix since they have all been automatically imported. For example, in IEx, you can call: iex> is_number(13) true If you don't want to import a function or macro from `Kernel`, use the `:except` option and then list the function/macro by arity: import Kernel, except: [if: 2, unless: 2] See `Kernel.SpecialForms.import/2` for more information on importing. Elixir also has special forms that are always imported and cannot be skipped. These are described in `Kernel.SpecialForms`. ## The standard library `Kernel` provides the basic capabilities the Elixir standard library is built on top of. It is recommended to explore the standard library for advanced functionality. Here are the main groups of modules in the standard library (this list is not a complete reference, see the documentation sidebar for all entries). ### Built-in types The following modules handle Elixir built-in data types: * `Atom` - literal constants with a name (`true`, `false`, and `nil` are atoms) * `Float` - numbers with floating point precision * `Function` - a reference to code chunk, created with the `fn/1` special form * `Integer` - whole numbers (not fractions) * `List` - collections of a variable number of elements (linked lists) * `Map` - collections of key-value pairs * `Process` - light-weight threads of execution * `Port` - mechanisms to interact with the external world * `Tuple` - collections of a fixed number of elements There are two data types without an accompanying module: * Bitstring - a sequence of bits, created with `Kernel.SpecialForms.<<>>/1`. When the number of bits is divisible by 8, they are called binaries and can be manipulated with Erlang's `:binary` module * Reference - a unique value in the runtime system, created with `make_ref/0` ### Data types Elixir also provides other data types that are built on top of the types listed above. Some of them are: * `Date` - `year-month-day` structs in a given calendar * `DateTime` - date and time with time zone in a given calendar * `Exception` - data raised from errors and unexpected scenarios * `MapSet` - unordered collections of unique elements * `NaiveDateTime` - date and time without time zone in a given calendar * `Keyword` - lists of two-element tuples, often representing optional values * `Range` - inclusive ranges between two integers * `Regex` - regular expressions * `String` - UTF-8 encoded binaries representing characters * `Time` - `hour:minute:second` structs in a given calendar * `URI` - representation of URIs that identify resources * `Version` - representation of versions and requirements ### System modules Modules that interface with the underlying system, such as: * `IO` - handles input and output * `File` - interacts with the underlying file system * `Path` - manipulates file system paths * `System` - reads and writes system information ### Protocols Protocols add polymorphic dispatch to Elixir. They are contracts implementable by data types. See `Protocol` for more information on protocols. Elixir provides the following protocols in the standard library: * `Collectable` - collects data into a data type * `Enumerable` - handles collections in Elixir. The `Enum` module provides eager functions for working with collections, the `Stream` module provides lazy functions * `Inspect` - converts data types into their programming language representation * `List.Chars` - converts data types to their outside world representation as charlists (non-programming based) * `String.Chars` - converts data types to their outside world representation as strings (non-programming based) ### Process-based and application-centric functionality The following modules build on top of processes to provide concurrency, fault-tolerance, and more. * `Agent` - a process that encapsulates mutable state * `Application` - functions for starting, stopping and configuring applications * `GenServer` - a generic client-server API * `Registry` - a key-value process-based storage * `Supervisor` - a process that is responsible for starting, supervising and shutting down other processes * `Task` - a process that performs computations * `Task.Supervisor` - a supervisor for managing tasks exclusively ### Supporting documents Elixir documentation also includes supporting documents under the "Pages" section. Those are: * [Compatibility and deprecations](compatibility-and-deprecations.md) - lists compatibility between every Elixir version and Erlang/OTP, release schema; lists all deprecated functions, when they were deprecated and alternatives * [Library guidelines](library-guidelines.md) - general guidelines, anti-patterns, and rules for those writing libraries * [Naming conventions](naming-conventions.md) - naming conventions for Elixir code * [Operators](operators.md) - lists all Elixir operators and their precedences * [Patterns and guards](patterns-and-guards.md) - an introduction to patterns, guards, and extensions * [Syntax reference](syntax-reference.md) - the language syntax reference * [Typespecs](typespecs.md)- types and function specifications, including list of types * [Unicode syntax](unicode-syntax.md) - outlines Elixir support for Unicode * [Writing documentation](writing-documentation.md) - guidelines for writing documentation in Elixir ## Guards This module includes the built-in guards used by Elixir developers. They are a predefined set of functions and macros that augment pattern matching, typically invoked after the `when` operator. For example: def drive(%User{age: age}) when age >= 16 do ... end The clause above will only be invoked if the user's age is more than or equal to 16. Guards also support joining multiple conditions with `and` and `or`. The whole guard is true if all guard expressions will evaluate to `true`. A more complete introduction to guards is available in the [Patterns and guards](patterns-and-guards.md) page. ## Structural comparison The comparison functions in this module perform structural comparison. This means structures are compared based on their representation and not on their semantic value. This is specially important for functions that are meant to provide ordering, such as `>/2`, `</2`, `>=/2`, `<=/2`, `min/2`, and `max/2`. For example: ~D[2017-03-31] > ~D[2017-04-01] will return `true` because structural comparison compares the `:day` field before `:month` or `:year`. Therefore, when comparing structs, you often use the `compare/2` function made available by the structs modules themselves: iex> Date.compare(~D[2017-03-31], ~D[2017-04-01]) :lt Alternatively, you can use the functions in the `Enum` module to sort or compute a maximum/minimum: iex> Enum.sort([~D[2017-03-31], ~D[2017-04-01]], Date) [~D[2017-03-31], ~D[2017-04-01]] iex> Enum.max([~D[2017-03-31], ~D[2017-04-01]], Date) ~D[2017-04-01] ## Truthy and falsy values Besides the booleans `true` and `false`, Elixir has the concept of a "truthy" or "falsy" value. * a value is truthy when it is neither `false` nor `nil` * a value is falsy when it is either `false` or `nil` Elixir has functions, like `and/2`, that *only* work with booleans, but also functions that work with these truthy/falsy values, like `&&/2` and `!/1`. ### Examples We can check the truthiness of a value by using the `!/1` function twice. Truthy values: iex> !!true true iex> !!5 true iex> !![1,2] true iex> !!"foo" true Falsy values (of which there are exactly two): iex> !!false false iex> !!nil false ## Inlining Some of the functions described in this module are inlined by the Elixir compiler into their Erlang counterparts in the [`:erlang`](`:erlang`) module. Those functions are called BIFs (built-in internal functions) in Erlang-land and they exhibit interesting properties, as some of them are allowed in guards and others are used for compiler optimizations. Most of the inlined functions can be seen in effect when capturing the function: iex> &Kernel.is_atom/1 &:erlang.is_atom/1 Those functions will be explicitly marked in their docs as "inlined by the compiler". """ # We need this check only for bootstrap purposes. # Once Kernel is loaded and we recompile, it is a no-op. @compile {:inline, bootstrapped?: 1} case :code.ensure_loaded(Kernel) do {:module, _} -> defp bootstrapped?(_), do: true {:error, _} -> defp bootstrapped?(module), do: :code.ensure_loaded(module) == {:module, module} end ## Delegations to Erlang with inlining (macros) @doc """ Returns an integer or float which is the arithmetical absolute value of `number`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> abs(-3.33) 3.33 iex> abs(-3) 3 """ @doc guard: true @spec abs(number) :: number def abs(number) do :erlang.abs(number) end @doc """ Invokes the given anonymous function `fun` with the list of arguments `args`. If the number of arguments is known at compile time, prefer `fun.(arg_1, arg_2, ..., arg_n)` as it is clearer than `apply(fun, [arg_1, arg_2, ..., arg_n])`. Inlined by the compiler. ## Examples iex> apply(fn x -> x * 2 end, [2]) 4 """ @spec apply(fun, [any]) :: any def apply(fun, args) do :erlang.apply(fun, args) end @doc """ Invokes the given function from `module` with the list of arguments `args`. `apply/3` is used to invoke functions where the module, function name or arguments are defined dynamically at runtime. For this reason, you can't invoke macros using `apply/3`, only functions. If the number of arguments and the function name are known at compile time, prefer `module.function(arg_1, arg_2, ..., arg_n)` as it is clearer than `apply(module, :function, [arg_1, arg_2, ..., arg_n])`. `apply/3` cannot be used to call private functions. Inlined by the compiler. ## Examples iex> apply(Enum, :reverse, [[1, 2, 3]]) [3, 2, 1] """ @spec apply(module, function_name :: atom, [any]) :: any def apply(module, function_name, args) do :erlang.apply(module, function_name, args) end @doc """ Extracts the part of the binary starting at `start` with length `length`. Binaries are zero-indexed. If `start` or `length` reference in any way outside the binary, an `ArgumentError` exception is raised. Allowed in guard tests. Inlined by the compiler. ## Examples iex> binary_part("foo", 1, 2) "oo" A negative `length` can be used to extract bytes that come *before* the byte at `start`: iex> binary_part("Hello", 5, -3) "llo" An `ArgumentError` is raised when the length is outside of the binary: binary_part("Hello", 0, 10) ** (ArgumentError) argument error """ @doc guard: true @spec binary_part(binary, non_neg_integer, integer) :: binary def binary_part(binary, start, length) do :erlang.binary_part(binary, start, length) end @doc """ Returns an integer which is the size in bits of `bitstring`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> bit_size(<<433::16, 3::3>>) 19 iex> bit_size(<<1, 2, 3>>) 24 """ @doc guard: true @spec bit_size(bitstring) :: non_neg_integer def bit_size(bitstring) do :erlang.bit_size(bitstring) end @doc """ Returns the number of bytes needed to contain `bitstring`. That is, if the number of bits in `bitstring` is not divisible by 8, the resulting number of bytes will be rounded up (by excess). This operation happens in constant time. Allowed in guard tests. Inlined by the compiler. ## Examples iex> byte_size(<<433::16, 3::3>>) 3 iex> byte_size(<<1, 2, 3>>) 3 """ @doc guard: true @spec byte_size(bitstring) :: non_neg_integer def byte_size(bitstring) do :erlang.byte_size(bitstring) end @doc """ Returns the smallest integer greater than or equal to `number`. If you want to perform ceil operation on other decimal places, use `Float.ceil/2` instead. Allowed in guard tests. Inlined by the compiler. """ @doc since: "1.8.0", guard: true @spec ceil(number) :: integer def ceil(number) do :erlang.ceil(number) end @doc """ Performs an integer division. Raises an `ArithmeticError` exception if one of the arguments is not an integer, or when the `divisor` is `0`. `div/2` performs *truncated* integer division. This means that the result is always rounded towards zero. If you want to perform floored integer division (rounding towards negative infinity), use `Integer.floor_div/2` instead. Allowed in guard tests. Inlined by the compiler. ## Examples div(5, 2) #=> 2 div(6, -4) #=> -1 div(-99, 2) #=> -49 div(100, 0) ** (ArithmeticError) bad argument in arithmetic expression """ @doc guard: true @spec div(integer, neg_integer | pos_integer) :: integer def div(dividend, divisor) do :erlang.div(dividend, divisor) end @doc """ Stops the execution of the calling process with the given reason. Since evaluating this function causes the process to terminate, it has no return value. Inlined by the compiler. ## Examples When a process reaches its end, by default it exits with reason `:normal`. You can also call `exit/1` explicitly if you want to terminate a process but not signal any failure: exit(:normal) In case something goes wrong, you can also use `exit/1` with a different reason: exit(:seems_bad) If the exit reason is not `:normal`, all the processes linked to the process that exited will crash (unless they are trapping exits). ## OTP exits Exits are used by the OTP to determine if a process exited abnormally or not. The following exits are considered "normal": * `exit(:normal)` * `exit(:shutdown)` * `exit({:shutdown, term})` Exiting with any other reason is considered abnormal and treated as a crash. This means the default supervisor behaviour kicks in, error reports are emitted, and so forth. This behaviour is relied on in many different places. For example, `ExUnit` uses `exit(:shutdown)` when exiting the test process to signal linked processes, supervision trees and so on to politely shut down too. ## CLI exits Building on top of the exit signals mentioned above, if the process started by the command line exits with any of the three reasons above, its exit is considered normal and the Operating System process will exit with status 0. It is, however, possible to customize the operating system exit signal by invoking: exit({:shutdown, integer}) This will cause the operating system process to exit with the status given by `integer` while signaling all linked Erlang processes to politely shut down. Any other exit reason will cause the operating system process to exit with status `1` and linked Erlang processes to crash. """ @spec exit(term) :: no_return def exit(reason) do :erlang.exit(reason) end @doc """ Returns the largest integer smaller than or equal to `number`. If you want to perform floor operation on other decimal places, use `Float.floor/2` instead. Allowed in guard tests. Inlined by the compiler. """ @doc since: "1.8.0", guard: true @spec floor(number) :: integer def floor(number) do :erlang.floor(number) end @doc """ Returns the head of a list. Raises `ArgumentError` if the list is empty. It works with improper lists. Allowed in guard tests. Inlined by the compiler. ## Examples hd([1, 2, 3, 4]) #=> 1 hd([1 | 2]) #=> 1 Giving it an empty list raises: hd([]) #=> ** (ArgumentError) argument error """ @doc guard: true @spec hd(nonempty_maybe_improper_list(elem, any)) :: elem when elem: term def hd(list) do :erlang.hd(list) end @doc """ Returns `true` if `term` is an atom; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> is_atom(false) true iex> is_atom(:name) true iex> is_atom(AnAtom) true iex> is_atom("true") false """ @doc guard: true @spec is_atom(term) :: boolean def is_atom(term) do :erlang.is_atom(term) end @doc """ Returns `true` if `term` is a binary; otherwise returns `false`. A binary always contains a complete number of bytes. Allowed in guard tests. Inlined by the compiler. ## Examples iex> is_binary("foo") true iex> is_binary(<<1::3>>) false """ @doc guard: true @spec is_binary(term) :: boolean def is_binary(term) do :erlang.is_binary(term) end @doc """ Returns `true` if `term` is a bitstring (including a binary); otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> is_bitstring("foo") true iex> is_bitstring(<<1::3>>) true """ @doc guard: true @spec is_bitstring(term) :: boolean def is_bitstring(term) do :erlang.is_bitstring(term) end @doc """ Returns `true` if `term` is either the atom `true` or the atom `false` (i.e., a boolean); otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> is_boolean(false) true iex> is_boolean(true) true iex> is_boolean(:test) false """ @doc guard: true @spec is_boolean(term) :: boolean def is_boolean(term) do :erlang.is_boolean(term) end @doc """ Returns `true` if `term` is a floating-point number; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_float(term) :: boolean def is_float(term) do :erlang.is_float(term) end @doc """ Returns `true` if `term` is a function; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> is_function(fn x -> x + x end) true iex> is_function("not a function") false """ @doc guard: true @spec is_function(term) :: boolean def is_function(term) do :erlang.is_function(term) end @doc """ Returns `true` if `term` is a function that can be applied with `arity` number of arguments; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> is_function(fn x -> x * 2 end, 1) true iex> is_function(fn x -> x * 2 end, 2) false """ @doc guard: true @spec is_function(term, non_neg_integer) :: boolean def is_function(term, arity) do :erlang.is_function(term, arity) end @doc """ Returns `true` if `term` is an integer; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_integer(term) :: boolean def is_integer(term) do :erlang.is_integer(term) end @doc """ Returns `true` if `term` is a list with zero or more elements; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_list(term) :: boolean def is_list(term) do :erlang.is_list(term) end @doc """ Returns `true` if `term` is either an integer or a floating-point number; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_number(term) :: boolean def is_number(term) do :erlang.is_number(term) end @doc """ Returns `true` if `term` is a PID (process identifier); otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_pid(term) :: boolean def is_pid(term) do :erlang.is_pid(term) end @doc """ Returns `true` if `term` is a port identifier; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_port(term) :: boolean def is_port(term) do :erlang.is_port(term) end @doc """ Returns `true` if `term` is a reference; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_reference(term) :: boolean def is_reference(term) do :erlang.is_reference(term) end @doc """ Returns `true` if `term` is a tuple; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_tuple(term) :: boolean def is_tuple(term) do :erlang.is_tuple(term) end @doc """ Returns `true` if `term` is a map; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_map(term) :: boolean def is_map(term) do :erlang.is_map(term) end @doc """ Returns `true` if `key` is a key in `map`; otherwise returns `false`. It raises `BadMapError` if the first element is not a map. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true, since: "1.10.0" @spec is_map_key(map, term) :: boolean def is_map_key(map, key) do :erlang.is_map_key(key, map) end @doc """ Returns the length of `list`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> length([1, 2, 3, 4, 5, 6, 7, 8, 9]) 9 """ @doc guard: true @spec length(list) :: non_neg_integer def length(list) do :erlang.length(list) end @doc """ Returns an almost unique reference. The returned reference will re-occur after approximately 2^82 calls; therefore it is unique enough for practical purposes. Inlined by the compiler. ## Examples make_ref() #=> #Reference<0.0.0.135> """ @spec make_ref() :: reference def make_ref() do :erlang.make_ref() end @doc """ Returns the size of a map. The size of a map is the number of key-value pairs that the map contains. This operation happens in constant time. Allowed in guard tests. Inlined by the compiler. ## Examples iex> map_size(%{a: "foo", b: "bar"}) 2 """ @doc guard: true @spec map_size(map) :: non_neg_integer def map_size(map) do :erlang.map_size(map) end @doc """ Returns the biggest of the two given terms according to their structural comparison. If the terms compare equal, the first one is returned. This performs a structural comparison where all Elixir terms can be compared with each other. See the ["Structural comparison" section](#module-structural-comparison) section for more information. Inlined by the compiler. ## Examples iex> max(1, 2) 2 iex> max(:a, :b) :b """ @spec max(first, second) :: first | second when first: term, second: term def max(first, second) do :erlang.max(first, second) end @doc """ Returns the smallest of the two given terms according to their structural comparison. If the terms compare equal, the first one is returned. This performs a structural comparison where all Elixir terms can be compared with each other. See the ["Structural comparison" section](#module-structural-comparison) section for more information. Inlined by the compiler. ## Examples iex> min(1, 2) 1 iex> min("foo", "bar") "bar" """ @spec min(first, second) :: first | second when first: term, second: term def min(first, second) do :erlang.min(first, second) end @doc """ Returns an atom representing the name of the local node. If the node is not alive, `:nonode@nohost` is returned instead. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec node() :: node def node do :erlang.node() end @doc """ Returns the node where the given argument is located. The argument can be a PID, a reference, or a port. If the local node is not alive, `:nonode@nohost` is returned. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec node(pid | reference | port) :: node def node(arg) do :erlang.node(arg) end @doc """ Computes the remainder of an integer division. `rem/2` uses truncated division, which means that the result will always have the sign of the `dividend`. Raises an `ArithmeticError` exception if one of the arguments is not an integer, or when the `divisor` is `0`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> rem(5, 2) 1 iex> rem(6, -4) 2 """ @doc guard: true @spec rem(integer, neg_integer | pos_integer) :: integer def rem(dividend, divisor) do :erlang.rem(dividend, divisor) end @doc """ Rounds a number to the nearest integer. If the number is equidistant to the two nearest integers, rounds away from zero. Allowed in guard tests. Inlined by the compiler. ## Examples iex> round(5.6) 6 iex> round(5.2) 5 iex> round(-9.9) -10 iex> round(-9) -9 iex> round(2.5) 3 iex> round(-2.5) -3 """ @doc guard: true @spec round(number) :: integer def round(number) do :erlang.round(number) end @doc """ Sends a message to the given `dest` and returns the message. `dest` may be a remote or local PID, a local port, a locally registered name, or a tuple in the form of `{registered_name, node}` for a registered name at another node. Inlined by the compiler. ## Examples iex> send(self(), :hello) :hello """ @spec send(dest :: Process.dest(), message) :: message when message: any def send(dest, message) do :erlang.send(dest, message) end @doc """ Returns the PID (process identifier) of the calling process. Allowed in guard clauses. Inlined by the compiler. """ @doc guard: true @spec self() :: pid def self() do :erlang.self() end @doc """ Spawns the given function and returns its PID. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. The anonymous function receives 0 arguments, and may return any value. Inlined by the compiler. ## Examples current = self() child = spawn(fn -> send(current, {self(), 1 + 2}) end) receive do {^child, 3} -> IO.puts("Received 3 back") end """ @spec spawn((() -> any)) :: pid def spawn(fun) do :erlang.spawn(fun) end @doc """ Spawns the given function `fun` from the given `module` passing it the given `args` and returns its PID. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. Inlined by the compiler. ## Examples spawn(SomeModule, :function, [1, 2, 3]) """ @spec spawn(module, atom, list) :: pid def spawn(module, fun, args) do :erlang.spawn(module, fun, args) end @doc """ Spawns the given function, links it to the current process, and returns its PID. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. For more information on linking, check `Process.link/1`. The anonymous function receives 0 arguments, and may return any value. Inlined by the compiler. ## Examples current = self() child = spawn_link(fn -> send(current, {self(), 1 + 2}) end) receive do {^child, 3} -> IO.puts("Received 3 back") end """ @spec spawn_link((() -> any)) :: pid def spawn_link(fun) do :erlang.spawn_link(fun) end @doc """ Spawns the given function `fun` from the given `module` passing it the given `args`, links it to the current process, and returns its PID. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. For more information on linking, check `Process.link/1`. Inlined by the compiler. ## Examples spawn_link(SomeModule, :function, [1, 2, 3]) """ @spec spawn_link(module, atom, list) :: pid def spawn_link(module, fun, args) do :erlang.spawn_link(module, fun, args) end @doc """ Spawns the given function, monitors it and returns its PID and monitoring reference. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. The anonymous function receives 0 arguments, and may return any value. Inlined by the compiler. ## Examples current = self() spawn_monitor(fn -> send(current, {self(), 1 + 2}) end) """ @spec spawn_monitor((() -> any)) :: {pid, reference} def spawn_monitor(fun) do :erlang.spawn_monitor(fun) end @doc """ Spawns the given module and function passing the given args, monitors it and returns its PID and monitoring reference. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. Inlined by the compiler. ## Examples spawn_monitor(SomeModule, :function, [1, 2, 3]) """ @spec spawn_monitor(module, atom, list) :: {pid, reference} def spawn_monitor(module, fun, args) do :erlang.spawn_monitor(module, fun, args) end @doc """ Pipes `value` to the given `fun` and returns the `value` itself. Useful for running synchronous side effects in a pipeline. ## Examples iex> tap(1, fn x -> x + 1 end) 1 Most commonly, this is used in pipelines. For example, let's suppose you want to inspect part of a data structure. You could write: %{a: 1} |> Map.update!(:a, & &1 + 2) |> tap(&IO.inspect(&1.a)) |> Map.update!(:a, & &1 * 2) """ @doc since: "1.12.0" defmacro tap(value, fun) do quote bind_quoted: [fun: fun, value: value] do _ = fun.(value) value end end @doc """ A non-local return from a function. Check `Kernel.SpecialForms.try/1` for more information. Inlined by the compiler. """ @spec throw(term) :: no_return def throw(term) do :erlang.throw(term) end @doc """ Returns the tail of a list. Raises `ArgumentError` if the list is empty. It works with improper lists. Allowed in guard tests. Inlined by the compiler. ## Examples tl([1, 2, 3, :go]) #=> [2, 3, :go] tl([:one]) #=> [] tl([:a, :b | :c]) #=> [:b | :c] tl([:a | %{b: 1}]) #=> %{b: 1} Giving it an empty list raises: tl([]) #=> ** (ArgumentError) argument error """ @doc guard: true @spec tl(nonempty_maybe_improper_list(elem, tail)) :: maybe_improper_list(elem, tail) | tail when elem: term, tail: term def tl(list) do :erlang.tl(list) end @doc """ Returns the integer part of `number`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> trunc(5.4) 5 iex> trunc(-5.99) -5 iex> trunc(-5) -5 """ @doc guard: true @spec trunc(number) :: integer def trunc(number) do :erlang.trunc(number) end @doc """ Returns the size of a tuple. This operation happens in constant time. Allowed in guard tests. Inlined by the compiler. ## Examples iex> tuple_size({:a, :b, :c}) 3 """ @doc guard: true @spec tuple_size(tuple) :: non_neg_integer def tuple_size(tuple) do :erlang.tuple_size(tuple) end @doc """ Arithmetic addition operator. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 + 2 3 """ @doc guard: true @spec integer + integer :: integer @spec float + float :: float @spec integer + float :: float @spec float + integer :: float def left + right do :erlang.+(left, right) end @doc """ Arithmetic subtraction operator. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 - 2 -1 """ @doc guard: true @spec integer - integer :: integer @spec float - float :: float @spec integer - float :: float @spec float - integer :: float def left - right do :erlang.-(left, right) end @doc """ Arithmetic positive unary operator. Allowed in guard tests. Inlined by the compiler. ## Examples iex> +1 1 """ @doc guard: true @spec +integer :: integer @spec +float :: float def +value do :erlang.+(value) end @doc """ Arithmetic negative unary operator. Allowed in guard tests. Inlined by the compiler. ## Examples iex> -2 -2 """ @doc guard: true @spec -0 :: 0 @spec -pos_integer :: neg_integer @spec -neg_integer :: pos_integer @spec -float :: float def -value do :erlang.-(value) end @doc """ Arithmetic multiplication operator. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 * 2 2 """ @doc guard: true @spec integer * integer :: integer @spec float * float :: float @spec integer * float :: float @spec float * integer :: float def left * right do :erlang.*(left, right) end @doc """ Arithmetic division operator. The result is always a float. Use `div/2` and `rem/2` if you want an integer division or the remainder. Raises `ArithmeticError` if `right` is 0 or 0.0. Allowed in guard tests. Inlined by the compiler. ## Examples 1 / 2 #=> 0.5 -3.0 / 2.0 #=> -1.5 5 / 1 #=> 5.0 7 / 0 ** (ArithmeticError) bad argument in arithmetic expression """ @doc guard: true @spec number / number :: float def left / right do :erlang./(left, right) end @doc """ List concatenation operator. Concatenates a proper list and a term, returning a list. The complexity of `a ++ b` is proportional to `length(a)`, so avoid repeatedly appending to lists of arbitrary length, for example, `list ++ [element]`. Instead, consider prepending via `[element | rest]` and then reversing. If the `right` operand is not a proper list, it returns an improper list. If the `left` operand is not a proper list, it raises `ArgumentError`. Inlined by the compiler. ## Examples iex> [1] ++ [2, 3] [1, 2, 3] iex> 'foo' ++ 'bar' 'foobar' # returns an improper list iex> [1] ++ 2 [1 | 2] # returns a proper list iex> [1] ++ [2] [1, 2] # improper list on the right will return an improper list iex> [1] ++ [2 | 3] [1, 2 | 3] """ @spec list ++ term :: maybe_improper_list def left ++ right do :erlang.++(left, right) end @doc """ List subtraction operator. Removes the first occurrence of an element on the left list for each element on the right. This function is optimized so the complexity of `a -- b` is proportional to `length(a) * log(length(b))`. See also the [Erlang efficiency guide](https://www.erlang.org/doc/efficiency_guide/retired_myths.html). Inlined by the compiler. ## Examples iex> [1, 2, 3] -- [1, 2] [3] iex> [1, 2, 3, 2, 1] -- [1, 2, 2] [3, 1] The `--/2` operator is right associative, meaning: iex> [1, 2, 3] -- [2] -- [3] [1, 3] As it is equivalent to: iex> [1, 2, 3] -- ([2] -- [3]) [1, 3] """ @spec list -- list :: list def left -- right do :erlang.--(left, right) end @doc """ Strictly boolean "not" operator. `value` must be a boolean; if it's not, an `ArgumentError` exception is raised. Allowed in guard tests. Inlined by the compiler. ## Examples iex> not false true """ @doc guard: true @spec not true :: false @spec not false :: true def not value do :erlang.not(value) end @doc """ Less-than operator. Returns `true` if `left` is less than `right`. This performs a structural comparison where all Elixir terms can be compared with each other. See the ["Structural comparison" section](#module-structural-comparison) section for more information. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 < 2 true """ @doc guard: true @spec term < term :: boolean def left < right do :erlang.<(left, right) end @doc """ Greater-than operator. Returns `true` if `left` is more than `right`. This performs a structural comparison where all Elixir terms can be compared with each other. See the ["Structural comparison" section](#module-structural-comparison) section for more information. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 > 2 false """ @doc guard: true @spec term > term :: boolean def left > right do :erlang.>(left, right) end @doc """ Less-than or equal to operator. Returns `true` if `left` is less than or equal to `right`. This performs a structural comparison where all Elixir terms can be compared with each other. See the ["Structural comparison" section](#module-structural-comparison) section for more information. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 <= 2 true """ @doc guard: true @spec term <= term :: boolean def left <= right do :erlang."=<"(left, right) end @doc """ Greater-than or equal to operator. Returns `true` if `left` is more than or equal to `right`. This performs a structural comparison where all Elixir terms can be compared with each other. See the ["Structural comparison" section](#module-structural-comparison) section for more information. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 >= 2 false """ @doc guard: true @spec term >= term :: boolean def left >= right do :erlang.>=(left, right) end @doc """ Equal to operator. Returns `true` if the two terms are equal. This operator considers 1 and 1.0 to be equal. For stricter semantics, use `===/2` instead. All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 == 2 false iex> 1 == 1.0 true """ @doc guard: true @spec term == term :: boolean def left == right do :erlang.==(left, right) end @doc """ Not equal to operator. Returns `true` if the two terms are not equal. This operator considers 1 and 1.0 to be equal. For match comparison, use `!==/2` instead. All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 != 2 true iex> 1 != 1.0 false """ @doc guard: true @spec term != term :: boolean def left != right do :erlang."/="(left, right) end @doc """ Strictly equal to operator. Returns `true` if the two terms are exactly equal. The terms are only considered to be exactly equal if they have the same value and are of the same type. For example, `1 == 1.0` returns `true`, but since they are of different types, `1 === 1.0` returns `false`. All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 === 2 false iex> 1 === 1.0 false """ @doc guard: true @spec term === term :: boolean def left === right do :erlang."=:="(left, right) end @doc """ Strictly not equal to operator. Returns `true` if the two terms are not exactly equal. See `===/2` for a definition of what is considered "exactly equal". All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 !== 2 true iex> 1 !== 1.0 true """ @doc guard: true @spec term !== term :: boolean def left !== right do :erlang."=/="(left, right) end @doc """ Gets the element at the zero-based `index` in `tuple`. It raises `ArgumentError` when index is negative or it is out of range of the tuple elements. Allowed in guard tests. Inlined by the compiler. ## Examples tuple = {:foo, :bar, 3} elem(tuple, 1) #=> :bar elem({}, 0) ** (ArgumentError) argument error elem({:foo, :bar}, 2) ** (ArgumentError) argument error """ @doc guard: true @spec elem(tuple, non_neg_integer) :: term def elem(tuple, index) do :erlang.element(index + 1, tuple) end @doc """ Puts `value` at the given zero-based `index` in `tuple`. Inlined by the compiler. ## Examples iex> tuple = {:foo, :bar, 3} iex> put_elem(tuple, 0, :baz) {:baz, :bar, 3} """ @spec put_elem(tuple, non_neg_integer, term) :: tuple def put_elem(tuple, index, value) do :erlang.setelement(index + 1, tuple, value) end ## Implemented in Elixir defp optimize_boolean({:case, meta, args}) do {:case, [{:optimize_boolean, true} | meta], args} end @doc """ Strictly boolean "or" operator. If `left` is `true`, returns `true`; otherwise returns `right`. Requires only the `left` operand to be a boolean since it short-circuits. If the `left` operand is not a boolean, a `BadBooleanError` exception is raised. Allowed in guard tests. ## Examples iex> true or false true iex> false or 42 42 iex> 42 or false ** (BadBooleanError) expected a boolean on left-side of "or", got: 42 """ @doc guard: true defmacro left or right do case __CALLER__.context do nil -> build_boolean_check(:or, left, true, right) :match -> invalid_match!(:or) :guard -> quote(do: :erlang.orelse(unquote(left), unquote(right))) end end @doc """ Strictly boolean "and" operator. If `left` is `false`, returns `false`; otherwise returns `right`. Requires only the `left` operand to be a boolean since it short-circuits. If the `left` operand is not a boolean, a `BadBooleanError` exception is raised. Allowed in guard tests. ## Examples iex> true and false false iex> true and "yay!" "yay!" iex> "yay!" and true ** (BadBooleanError) expected a boolean on left-side of "and", got: "yay!" """ @doc guard: true defmacro left and right do case __CALLER__.context do nil -> build_boolean_check(:and, left, right, false) :match -> invalid_match!(:and) :guard -> quote(do: :erlang.andalso(unquote(left), unquote(right))) end end defp build_boolean_check(operator, check, true_clause, false_clause) do optimize_boolean( quote do case unquote(check) do false -> unquote(false_clause) true -> unquote(true_clause) other -> :erlang.error({:badbool, unquote(operator), other}) end end ) end @doc """ Boolean "not" operator. Receives any value (not just booleans) and returns `true` if `value` is `false` or `nil`; returns `false` otherwise. Not allowed in guard clauses. ## Examples iex> !Enum.empty?([]) false iex> !List.first([]) true """ defmacro !value defmacro !{:!, _, [value]} do assert_no_match_or_guard_scope(__CALLER__.context, "!") optimize_boolean( quote do case unquote(value) do x when :"Elixir.Kernel".in(x, [false, nil]) -> false _ -> true end end ) end defmacro !value do assert_no_match_or_guard_scope(__CALLER__.context, "!") optimize_boolean( quote do case unquote(value) do x when :"Elixir.Kernel".in(x, [false, nil]) -> true _ -> false end end ) end @doc """ Binary concatenation operator. Concatenates two binaries. Raises an `ArgumentError` if one of the sides aren't binaries. ## Examples iex> "foo" <> "bar" "foobar" The `<>/2` operator can also be used in pattern matching (and guard clauses) as long as the left argument is a literal binary: iex> "foo" <> x = "foobar" iex> x "bar" `x <> "bar" = "foobar"` would result in an `ArgumentError` exception. """ defmacro left <> right do concats = extract_concatenations({:<>, [], [left, right]}, __CALLER__) quote(do: <<unquote_splicing(concats)>>) end # Extracts concatenations in order to optimize many # concatenations into one single clause. defp extract_concatenations({:<>, _, [left, right]}, caller) do [wrap_concatenation(left, :left, caller) | extract_concatenations(right, caller)] end defp extract_concatenations(other, caller) do [wrap_concatenation(other, :right, caller)] end defp wrap_concatenation(binary, _side, _caller) when is_binary(binary) do binary end defp wrap_concatenation(literal, _side, _caller) when is_list(literal) or is_atom(literal) or is_integer(literal) or is_float(literal) do :erlang.error( ArgumentError.exception( "expected binary argument in <> operator but got: #{Macro.to_string(literal)}" ) ) end defp wrap_concatenation(other, side, caller) do expanded = expand_concat_argument(other, side, caller) {:"::", [], [expanded, {:binary, [], nil}]} end defp expand_concat_argument(arg, :left, %{context: :match} = caller) do expanded_arg = case bootstrapped?(Macro) do true -> Macro.expand(arg, caller) false -> arg end case expanded_arg do {var, _, nil} when is_atom(var) -> invalid_concat_left_argument_error(Atom.to_string(var)) {:^, _, [{var, _, nil}]} when is_atom(var) -> invalid_concat_left_argument_error("^#{Atom.to_string(var)}") _ -> expanded_arg end end defp expand_concat_argument(arg, _, _) do arg end defp invalid_concat_left_argument_error(arg) do :erlang.error( ArgumentError.exception( "the left argument of <> operator inside a match should always be a literal " <> "binary because its size can't be verified. Got: #{arg}" ) ) end @doc """ Raises an exception. If `message` is a string, it raises a `RuntimeError` exception with it. If `message` is an atom, it just calls `raise/2` with the atom as the first argument and `[]` as the second one. If `message` is an exception struct, it is raised as is. If `message` is anything else, `raise` will fail with an `ArgumentError` exception. ## Examples iex> raise "oops" ** (RuntimeError) oops try do 1 + :foo rescue x in [ArithmeticError] -> IO.puts("that was expected") raise x end """ defmacro raise(message) do # Try to figure out the type at compilation time # to avoid dead code and make Dialyzer happy. message = case not is_binary(message) and bootstrapped?(Macro) do true -> Macro.expand(message, __CALLER__) false -> message end erlang_error = case :erlang.system_info(:otp_release) >= '24' do true -> fn x -> quote do :erlang.error(unquote(x), :none, error_info: %{module: Exception}) end end false -> fn x -> quote do :erlang.error(unquote(x)) end end end case message do message when is_binary(message) -> erlang_error.(quote do: RuntimeError.exception(unquote(message))) {:<<>>, _, _} = message -> erlang_error.(quote do: RuntimeError.exception(unquote(message))) alias when is_atom(alias) -> erlang_error.(quote do: unquote(alias).exception([])) _ -> erlang_error.(quote do: Kernel.Utils.raise(unquote(message))) end end @doc """ Raises an exception. Calls the `exception/1` function on the given argument (which has to be a module name like `ArgumentError` or `RuntimeError`) passing `attributes` in order to retrieve the exception struct. Any module that contains a call to the `defexception/1` macro automatically implements the `c:Exception.exception/1` callback expected by `raise/2`. For more information, see `defexception/1`. ## Examples iex> raise(ArgumentError, "Sample") ** (ArgumentError) Sample """ defmacro raise(exception, attributes) do quote do :erlang.error(unquote(exception).exception(unquote(attributes))) end end @doc """ Raises an exception preserving a previous stacktrace. Works like `raise/1` but does not generate a new stacktrace. Note that `__STACKTRACE__` can be used inside catch/rescue to retrieve the current stacktrace. ## Examples try do raise "oops" rescue exception -> reraise exception, __STACKTRACE__ end """ defmacro reraise(message, stacktrace) do # Try to figure out the type at compilation time # to avoid dead code and make Dialyzer happy. case Macro.expand(message, __CALLER__) do message when is_binary(message) -> quote do :erlang.error( :erlang.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace)) ) end {:<<>>, _, _} = message -> quote do :erlang.error( :erlang.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace)) ) end alias when is_atom(alias) -> quote do :erlang.error(:erlang.raise(:error, unquote(alias).exception([]), unquote(stacktrace))) end message -> quote do :erlang.error( :erlang.raise(:error, Kernel.Utils.raise(unquote(message)), unquote(stacktrace)) ) end end end @doc """ Raises an exception preserving a previous stacktrace. `reraise/3` works like `reraise/2`, except it passes arguments to the `exception/1` function as explained in `raise/2`. ## Examples try do raise "oops" rescue exception -> reraise WrapperError, [exception: exception], __STACKTRACE__ end """ defmacro reraise(exception, attributes, stacktrace) do quote do :erlang.raise( :error, unquote(exception).exception(unquote(attributes)), unquote(stacktrace) ) end end @doc """ Text-based match operator. Matches the term on the `left` against the regular expression or string on the `right`. If `right` is a regular expression, returns `true` if `left` matches right. If `right` is a string, returns `true` if `left` contains `right`. ## Examples iex> "abcd" =~ ~r/c(d)/ true iex> "abcd" =~ ~r/e/ false iex> "abcd" =~ ~r// true iex> "abcd" =~ "bc" true iex> "abcd" =~ "ad" false iex> "abcd" =~ "abcd" true iex> "abcd" =~ "" true For more information about regular expressions, please check the `Regex` module. """ @spec String.t() =~ (String.t() | Regex.t()) :: boolean def left =~ "" when is_binary(left), do: true def left =~ right when is_binary(left) and is_binary(right) do :binary.match(left, right) != :nomatch end def left =~ right when is_binary(left) do Regex.match?(right, left) end @doc ~S""" Inspects the given argument according to the `Inspect` protocol. The second argument is a keyword list with options to control inspection. ## Options `inspect/2` accepts a list of options that are internally translated to an `Inspect.Opts` struct. Check the docs for `Inspect.Opts` to see the supported options. ## Examples iex> inspect(:foo) ":foo" iex> inspect([1, 2, 3, 4, 5], limit: 3) "[1, 2, 3, ...]" iex> inspect([1, 2, 3], pretty: true, width: 0) "[1,\n 2,\n 3]" iex> inspect("olá" <> <<0>>) "<<111, 108, 195, 161, 0>>" iex> inspect("olá" <> <<0>>, binaries: :as_strings) "\"olá\\0\"" iex> inspect("olá", binaries: :as_binaries) "<<111, 108, 195, 161>>" iex> inspect('bar') "'bar'" iex> inspect([0 | 'bar']) "[0, 98, 97, 114]" iex> inspect(100, base: :octal) "0o144" iex> inspect(100, base: :hex) "0x64" Note that the `Inspect` protocol does not necessarily return a valid representation of an Elixir term. In such cases, the inspected result must start with `#`. For example, inspecting a function will return: inspect(fn a, b -> a + b end) #=> #Function<...> The `Inspect` protocol can be derived to hide certain fields from structs, so they don't show up in logs, inspects and similar. See the "Deriving" section of the documentation of the `Inspect` protocol for more information. """ @spec inspect(Inspect.t(), keyword) :: String.t() def inspect(term, opts \\ []) when is_list(opts) do opts = Inspect.Opts.new(opts) limit = case opts.pretty do true -> opts.width false -> :infinity end doc = Inspect.Algebra.group(Inspect.Algebra.to_doc(term, opts)) IO.iodata_to_binary(Inspect.Algebra.format(doc, limit)) end @doc """ Creates and updates a struct. The `struct` argument may be an atom (which defines `defstruct`) or a `struct` itself. The second argument is any `Enumerable` that emits two-element tuples (key-value pairs) during enumeration. Keys in the `Enumerable` that don't exist in the struct are automatically discarded. Note that keys must be atoms, as only atoms are allowed when defining a struct. If keys in the `Enumerable` are duplicated, the last entry will be taken (same behaviour as `Map.new/1`). This function is useful for dynamically creating and updating structs, as well as for converting maps to structs; in the latter case, just inserting the appropriate `:__struct__` field into the map may not be enough and `struct/2` should be used instead. ## Examples defmodule User do defstruct name: "john" end struct(User) #=> %User{name: "john"} opts = [name: "meg"] user = struct(User, opts) #=> %User{name: "meg"} struct(user, unknown: "value") #=> %User{name: "meg"} struct(User, %{name: "meg"}) #=> %User{name: "meg"} # String keys are ignored struct(User, %{"name" => "meg"}) #=> %User{name: "john"} """ @spec struct(module | struct, Enum.t()) :: struct def struct(struct, fields \\ []) do struct(struct, fields, fn {:__struct__, _val}, acc -> acc {key, val}, acc -> case acc do %{^key => _} -> %{acc | key => val} _ -> acc end end) end @doc """ Similar to `struct/2` but checks for key validity. The function `struct!/2` emulates the compile time behaviour of structs. This means that: * when building a struct, as in `struct!(SomeStruct, key: :value)`, it is equivalent to `%SomeStruct{key: :value}` and therefore this function will check if every given key-value belongs to the struct. If the struct is enforcing any key via `@enforce_keys`, those will be enforced as well; * when updating a struct, as in `struct!(%SomeStruct{}, key: :value)`, it is equivalent to `%SomeStruct{struct | key: :value}` and therefore this function will check if every given key-value belongs to the struct. However, updating structs does not enforce keys, as keys are enforced only when building; """ @spec struct!(module | struct, Enum.t()) :: struct def struct!(struct, fields \\ []) def struct!(struct, fields) when is_atom(struct) do validate_struct!(struct.__struct__(fields), struct, 1) end def struct!(struct, fields) when is_map(struct) do struct(struct, fields, fn {:__struct__, _}, acc -> acc {key, val}, acc -> Map.replace!(acc, key, val) end) end defp struct(struct, [], _fun) when is_atom(struct) do validate_struct!(struct.__struct__(), struct, 0) end defp struct(struct, fields, fun) when is_atom(struct) do struct(validate_struct!(struct.__struct__(), struct, 0), fields, fun) end defp struct(%_{} = struct, [], _fun) do struct end defp struct(%_{} = struct, fields, fun) do Enum.reduce(fields, struct, fun) end defp validate_struct!(%{__struct__: module} = struct, module, _arity) do struct end defp validate_struct!(%{__struct__: struct_name}, module, arity) when is_atom(struct_name) do error_message = "expected struct name returned by #{inspect(module)}.__struct__/#{arity} to be " <> "#{inspect(module)}, got: #{inspect(struct_name)}" :erlang.error(ArgumentError.exception(error_message)) end defp validate_struct!(expr, module, arity) do error_message = "expected #{inspect(module)}.__struct__/#{arity} to return a map with a :__struct__ " <> "key that holds the name of the struct (atom), got: #{inspect(expr)}" :erlang.error(ArgumentError.exception(error_message)) end @doc """ Returns true if `term` is a struct; otherwise returns `false`. Allowed in guard tests. ## Examples iex> is_struct(URI.parse("/")) true iex> is_struct(%{}) false """ @doc since: "1.10.0", guard: true defmacro is_struct(term) do case __CALLER__.context do nil -> quote do case unquote(term) do %_{} -> true _ -> false end end :match -> invalid_match!(:is_struct) :guard -> quote do is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and is_atom(:erlang.map_get(:__struct__, unquote(term))) end end end @doc """ Returns true if `term` is a struct of `name`; otherwise returns `false`. Allowed in guard tests. ## Examples iex> is_struct(URI.parse("/"), URI) true iex> is_struct(URI.parse("/"), Macro.Env) false """ @doc since: "1.11.0", guard: true defmacro is_struct(term, name) do case __CALLER__.context do nil -> quote generated: true do case unquote(name) do name when is_atom(name) -> case unquote(term) do %{__struct__: ^name} -> true _ -> false end _ -> raise ArgumentError end end :match -> invalid_match!(:is_struct) :guard -> quote do is_map(unquote(term)) and (is_atom(unquote(name)) or :fail) and :erlang.is_map_key(:__struct__, unquote(term)) and :erlang.map_get(:__struct__, unquote(term)) == unquote(name) end end end @doc """ Returns true if `term` is an exception; otherwise returns `false`. Allowed in guard tests. ## Examples iex> is_exception(%RuntimeError{}) true iex> is_exception(%{}) false """ @doc since: "1.11.0", guard: true defmacro is_exception(term) do case __CALLER__.context do nil -> quote do case unquote(term) do %_{__exception__: true} -> true _ -> false end end :match -> invalid_match!(:is_exception) :guard -> quote do is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and is_atom(:erlang.map_get(:__struct__, unquote(term))) and :erlang.is_map_key(:__exception__, unquote(term)) and :erlang.map_get(:__exception__, unquote(term)) == true end end end @doc """ Returns true if `term` is an exception of `name`; otherwise returns `false`. Allowed in guard tests. ## Examples iex> is_exception(%RuntimeError{}, RuntimeError) true iex> is_exception(%RuntimeError{}, Macro.Env) false """ @doc since: "1.11.0", guard: true defmacro is_exception(term, name) do case __CALLER__.context do nil -> quote do case unquote(name) do name when is_atom(name) -> case unquote(term) do %{__struct__: ^name, __exception__: true} -> true _ -> false end _ -> raise ArgumentError end end :match -> invalid_match!(:is_exception) :guard -> quote do is_map(unquote(term)) and (is_atom(unquote(name)) or :fail) and :erlang.is_map_key(:__struct__, unquote(term)) and :erlang.map_get(:__struct__, unquote(term)) == unquote(name) and :erlang.is_map_key(:__exception__, unquote(term)) and :erlang.map_get(:__exception__, unquote(term)) == true end end end @doc """ Pipes `value` into the given `fun`. In other words, it invokes `fun` with `value` as argument. This is most commonly used in pipelines, allowing you to pipe a value to a function outside of its first argument. ### Examples iex> 1 |> then(fn x -> x * 2 end) 2 iex> 1 |> then(fn x -> Enum.drop(["a", "b", "c"], x) end) ["b", "c"] """ @doc since: "1.12.0" defmacro then(value, fun) do quote do unquote(fun).(unquote(value)) end end @doc """ Gets a value from a nested structure. Uses the `Access` module to traverse the structures according to the given `keys`, unless the `key` is a function, which is detailed in a later section. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> get_in(users, ["john", :age]) 27 `get_in/2` can also use the accessors in the `Access` module to traverse more complex data structures. For example, here we use `Access.all/0` to traverse a list: iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}] iex> get_in(users, [Access.all(), :age]) [27, 23] In case any of the components returns `nil`, `nil` will be returned and `get_in/2` won't traverse any futher: iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> get_in(users, ["unknown", :age]) nil iex> users = nil iex> get_in(users, [Access.all(), :age]) nil The main feature of `get_in/2` is precisely that it aborts traversal when a `nil` value is found. Unless you need nil-safety, you are likely better off by writing "regular" Elixir code: iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> users["john"][:age] 27 iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}] iex> Enum.map(users, fn user -> user[:age] end) [27, 23] Alternatively, if you need to access complex data-structures, you can use pattern matching: case users do %{"john" => %{age: age}} -> age _ -> default_value end ## Functions as keys If a key given to `get_in/2` is a function, the function will be invoked passing three arguments: * the operation (`:get`) * the data to be accessed * a function to be invoked next This means `get_in/2` can be extended to provide custom lookups. That's precisely how the `Access.all/0` key in the previous section behaves. For example, we can manually implement such traversal as follows: iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}] iex> all = fn :get, data, next -> Enum.map(data, next) end iex> get_in(users, [all, :age]) [27, 23] The `Access` module ships with many convenience accessor functions. See `Access.all/0`, `Access.key/2`, and others as examples. ## Working with structs By default, structs do not implement the `Access` behaviour required by this function. Therefore, you can't do this: get_in(some_struct, [:some_key, :nested_key]) The good news is that structs have predefined shape. Therefore, you can write instead: some_struct.some_key.nested_key If, by any chance, `some_key` can return nil, you can always fallback to pattern matching to provide nested struct handling: case some_struct do %{some_key: %{nested_key: value}} -> value %{} -> nil end """ @spec get_in(Access.t(), nonempty_list(term)) :: term def get_in(data, keys) def get_in(nil, [_ | _]), do: nil def get_in(data, [h]) when is_function(h), do: h.(:get, data, & &1) def get_in(data, [h | t]) when is_function(h), do: h.(:get, data, &get_in(&1, t)) def get_in(data, [h]), do: Access.get(data, h) def get_in(data, [h | t]), do: get_in(Access.get(data, h), t) @doc """ Puts a value in a nested structure. Uses the `Access` module to traverse the structures according to the given `keys`, unless the `key` is a function. If the key is a function, it will be invoked as specified in `get_and_update_in/3`. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> put_in(users, ["john", :age], 28) %{"john" => %{age: 28}, "meg" => %{age: 23}} If any of the intermediate values are nil, it will raise: iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> put_in(users, ["jane", :age], "oops") ** (ArgumentError) could not put/update key :age on a nil value """ @spec put_in(Access.t(), nonempty_list(term), term) :: Access.t() def put_in(data, [_ | _] = keys, value) do elem(get_and_update_in(data, keys, fn _ -> {nil, value} end), 1) end @doc """ Updates a key in a nested structure. Uses the `Access` module to traverse the structures according to the given `keys`, unless the `key` is a function. If the key is a function, it will be invoked as specified in `get_and_update_in/3`. `data` is a nested structure (that is, a map, keyword list, or struct that implements the `Access` behaviour). The `fun` argument receives the value of `key` (or `nil` if `key` is not present) and the result replaces the value in the structure. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> update_in(users, ["john", :age], &(&1 + 1)) %{"john" => %{age: 28}, "meg" => %{age: 23}} Note the current value given to the anonymous function may be `nil`. If any of the intermediate values are nil, it will raise: iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> update_in(users, ["jane", :age], & &1 + 1) ** (ArgumentError) could not put/update key :age on a nil value """ @spec update_in(Access.t(), nonempty_list(term), (term -> term)) :: Access.t() def update_in(data, [_ | _] = keys, fun) when is_function(fun) do elem(get_and_update_in(data, keys, fn x -> {nil, fun.(x)} end), 1) end @doc """ Gets a value and updates a nested structure. `data` is a nested structure (that is, a map, keyword list, or struct that implements the `Access` behaviour). The `fun` argument receives the value of `key` (or `nil` if `key` is not present) and must return one of the following values: * a two-element tuple `{current_value, new_value}`. In this case, `current_value` is the retrieved value which can possibly be operated on before being returned. `new_value` is the new value to be stored under `key`. * `:pop`, which implies that the current value under `key` should be removed from the structure and returned. This function uses the `Access` module to traverse the structures according to the given `keys`, unless the `key` is a function, which is detailed in a later section. ## Examples This function is useful when there is a need to retrieve the current value (or something calculated in function of the current value) and update it at the same time. For example, it could be used to read the current age of a user while increasing it by one in one pass: iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> get_and_update_in(users, ["john", :age], &{&1, &1 + 1}) {27, %{"john" => %{age: 28}, "meg" => %{age: 23}}} Note the current value given to the anonymous function may be `nil`. If any of the intermediate values are nil, it will raise: iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> get_and_update_in(users, ["jane", :age], &{&1, &1 + 1}) ** (ArgumentError) could not put/update key :age on a nil value ## Functions as keys If a key is a function, the function will be invoked passing three arguments: * the operation (`:get_and_update`) * the data to be accessed * a function to be invoked next This means `get_and_update_in/3` can be extended to provide custom lookups. The downside is that functions cannot be stored as keys in the accessed data structures. When one of the keys is a function, the function is invoked. In the example below, we use a function to get and increment all ages inside a list: iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}] iex> all = fn :get_and_update, data, next -> ...> data |> Enum.map(next) |> Enum.unzip() ...> end iex> get_and_update_in(users, [all, :age], &{&1, &1 + 1}) {[27, 23], [%{name: "john", age: 28}, %{name: "meg", age: 24}]} If the previous value before invoking the function is `nil`, the function *will* receive `nil` as a value and must handle it accordingly (be it by failing or providing a sane default). The `Access` module ships with many convenience accessor functions, like the `all` anonymous function defined above. See `Access.all/0`, `Access.key/2`, and others as examples. """ @spec get_and_update_in( structure, keys, (term | nil -> {current_value, new_value} | :pop) ) :: {current_value, new_structure :: structure} when structure: Access.t(), keys: nonempty_list(any), current_value: Access.value(), new_value: Access.value() def get_and_update_in(data, keys, fun) def get_and_update_in(data, [head], fun) when is_function(head, 3), do: head.(:get_and_update, data, fun) def get_and_update_in(data, [head | tail], fun) when is_function(head, 3), do: head.(:get_and_update, data, &get_and_update_in(&1, tail, fun)) def get_and_update_in(data, [head], fun) when is_function(fun, 1), do: Access.get_and_update(data, head, fun) def get_and_update_in(data, [head | tail], fun) when is_function(fun, 1), do: Access.get_and_update(data, head, &get_and_update_in(&1, tail, fun)) @doc """ Pops a key from the given nested structure. Uses the `Access` protocol to traverse the structures according to the given `keys`, unless the `key` is a function. If the key is a function, it will be invoked as specified in `get_and_update_in/3`. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> pop_in(users, ["john", :age]) {27, %{"john" => %{}, "meg" => %{age: 23}}} In case any entry returns `nil`, its key will be removed and the deletion will be considered a success. iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> pop_in(users, ["jane", :age]) {nil, %{"john" => %{age: 27}, "meg" => %{age: 23}}} """ @spec pop_in(data, nonempty_list(Access.get_and_update_fun(term, data) | term)) :: {term, data} when data: Access.container() def pop_in(data, keys) def pop_in(nil, [key | _]) do raise ArgumentError, "could not pop key #{inspect(key)} on a nil value" end def pop_in(data, [_ | _] = keys) do pop_in_data(data, keys) end defp pop_in_data(nil, [_ | _]), do: :pop defp pop_in_data(data, [fun]) when is_function(fun), do: fun.(:get_and_update, data, fn _ -> :pop end) defp pop_in_data(data, [fun | tail]) when is_function(fun), do: fun.(:get_and_update, data, &pop_in_data(&1, tail)) defp pop_in_data(data, [key]), do: Access.pop(data, key) defp pop_in_data(data, [key | tail]), do: Access.get_and_update(data, key, &pop_in_data(&1, tail)) @doc """ Puts a value in a nested structure via the given `path`. This is similar to `put_in/3`, except the path is extracted via a macro rather than passing a list. For example: put_in(opts[:foo][:bar], :baz) Is equivalent to: put_in(opts, [:foo, :bar], :baz) This also works with nested structs and the `struct.path.to.value` way to specify paths: put_in(struct.foo.bar, :baz) Note that in order for this macro to work, the complete path must always be visible by this macro. For more information about the supported path expressions, please check `get_and_update_in/2` docs. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> put_in(users["john"][:age], 28) %{"john" => %{age: 28}, "meg" => %{age: 23}} iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> put_in(users["john"].age, 28) %{"john" => %{age: 28}, "meg" => %{age: 23}} """ defmacro put_in(path, value) do case unnest(path, [], true, "put_in/2") do {[h | t], true} -> nest_update_in(h, t, quote(do: fn _ -> unquote(value) end)) {[h | t], false} -> expr = nest_get_and_update_in(h, t, quote(do: fn _ -> {nil, unquote(value)} end)) quote(do: :erlang.element(2, unquote(expr))) end end @doc """ Pops a key from the nested structure via the given `path`. This is similar to `pop_in/2`, except the path is extracted via a macro rather than passing a list. For example: pop_in(opts[:foo][:bar]) Is equivalent to: pop_in(opts, [:foo, :bar]) Note that in order for this macro to work, the complete path must always be visible by this macro. For more information about the supported path expressions, please check `get_and_update_in/2` docs. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> pop_in(users["john"][:age]) {27, %{"john" => %{}, "meg" => %{age: 23}}} iex> users = %{john: %{age: 27}, meg: %{age: 23}} iex> pop_in(users.john[:age]) {27, %{john: %{}, meg: %{age: 23}}} In case any entry returns `nil`, its key will be removed and the deletion will be considered a success. """ defmacro pop_in(path) do {[h | t], _} = unnest(path, [], true, "pop_in/1") nest_pop_in(:map, h, t) end @doc """ Updates a nested structure via the given `path`. This is similar to `update_in/3`, except the path is extracted via a macro rather than passing a list. For example: update_in(opts[:foo][:bar], &(&1 + 1)) Is equivalent to: update_in(opts, [:foo, :bar], &(&1 + 1)) This also works with nested structs and the `struct.path.to.value` way to specify paths: update_in(struct.foo.bar, &(&1 + 1)) Note that in order for this macro to work, the complete path must always be visible by this macro. For more information about the supported path expressions, please check `get_and_update_in/2` docs. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> update_in(users["john"][:age], &(&1 + 1)) %{"john" => %{age: 28}, "meg" => %{age: 23}} iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> update_in(users["john"].age, &(&1 + 1)) %{"john" => %{age: 28}, "meg" => %{age: 23}} """ defmacro update_in(path, fun) do case unnest(path, [], true, "update_in/2") do {[h | t], true} -> nest_update_in(h, t, fun) {[h | t], false} -> expr = nest_get_and_update_in(h, t, quote(do: fn x -> {nil, unquote(fun).(x)} end)) quote(do: :erlang.element(2, unquote(expr))) end end @doc """ Gets a value and updates a nested data structure via the given `path`. This is similar to `get_and_update_in/3`, except the path is extracted via a macro rather than passing a list. For example: get_and_update_in(opts[:foo][:bar], &{&1, &1 + 1}) Is equivalent to: get_and_update_in(opts, [:foo, :bar], &{&1, &1 + 1}) This also works with nested structs and the `struct.path.to.value` way to specify paths: get_and_update_in(struct.foo.bar, &{&1, &1 + 1}) Note that in order for this macro to work, the complete path must always be visible by this macro. See the "Paths" section below. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> get_and_update_in(users["john"].age, &{&1, &1 + 1}) {27, %{"john" => %{age: 28}, "meg" => %{age: 23}}} ## Paths A path may start with a variable, local or remote call, and must be followed by one or more: * `foo[bar]` - accesses the key `bar` in `foo`; in case `foo` is nil, `nil` is returned * `foo.bar` - accesses a map/struct field; in case the field is not present, an error is raised Here are some valid paths: users["john"][:age] users["john"].age User.all()["john"].age all_users()["john"].age Here are some invalid ones: # Does a remote call after the initial value users["john"].do_something(arg1, arg2) # Does not access any key or field users """ defmacro get_and_update_in(path, fun) do {[h | t], _} = unnest(path, [], true, "get_and_update_in/2") nest_get_and_update_in(h, t, fun) end defp nest_update_in([], fun), do: fun defp nest_update_in(list, fun) do quote do fn x -> unquote(nest_update_in(quote(do: x), list, fun)) end end end defp nest_update_in(h, [{:map, key} | t], fun) do quote do Map.update!(unquote(h), unquote(key), unquote(nest_update_in(t, fun))) end end defp nest_get_and_update_in([], fun), do: fun defp nest_get_and_update_in(list, fun) do quote do fn x -> unquote(nest_get_and_update_in(quote(do: x), list, fun)) end end end defp nest_get_and_update_in(h, [{:access, key} | t], fun) do quote do Access.get_and_update(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun))) end end defp nest_get_and_update_in(h, [{:map, key} | t], fun) do quote do Map.get_and_update!(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun))) end end defp nest_pop_in(kind, list) do quote do fn x -> unquote(nest_pop_in(kind, quote(do: x), list)) end end end defp nest_pop_in(:map, h, [{:access, key}]) do quote do case unquote(h) do nil -> {nil, nil} h -> Access.pop(h, unquote(key)) end end end defp nest_pop_in(_, _, [{:map, key}]) do raise ArgumentError, "cannot use pop_in when the last segment is a map/struct field. " <> "This would effectively remove the field #{inspect(key)} from the map/struct" end defp nest_pop_in(_, h, [{:map, key} | t]) do quote do Map.get_and_update!(unquote(h), unquote(key), unquote(nest_pop_in(:map, t))) end end defp nest_pop_in(_, h, [{:access, key}]) do quote do case unquote(h) do nil -> :pop h -> Access.pop(h, unquote(key)) end end end defp nest_pop_in(_, h, [{:access, key} | t]) do quote do Access.get_and_update(unquote(h), unquote(key), unquote(nest_pop_in(:access, t))) end end defp unnest({{:., _, [Access, :get]}, _, [expr, key]}, acc, _all_map?, kind) do unnest(expr, [{:access, key} | acc], false, kind) end defp unnest({{:., _, [expr, key]}, _, []}, acc, all_map?, kind) when is_tuple(expr) and :erlang.element(1, expr) != :__aliases__ and :erlang.element(1, expr) != :__MODULE__ do unnest(expr, [{:map, key} | acc], all_map?, kind) end defp unnest(other, [], _all_map?, kind) do raise ArgumentError, "expected expression given to #{kind} to access at least one element, " <> "got: #{Macro.to_string(other)}" end defp unnest(other, acc, all_map?, kind) do case proper_start?(other) do true -> {[other | acc], all_map?} false -> raise ArgumentError, "expression given to #{kind} must start with a variable, local or remote call " <> "and be followed by an element access, got: #{Macro.to_string(other)}" end end defp proper_start?({{:., _, [expr, _]}, _, _args}) when is_atom(expr) when :erlang.element(1, expr) == :__aliases__ when :erlang.element(1, expr) == :__MODULE__, do: true defp proper_start?({atom, _, _args}) when is_atom(atom), do: true defp proper_start?(other), do: not is_tuple(other) @doc """ Converts the argument to a string according to the `String.Chars` protocol. This is the function invoked when there is string interpolation. ## Examples iex> to_string(:foo) "foo" """ defmacro to_string(term) do quote(do: :"Elixir.String.Chars".to_string(unquote(term))) end @doc """ Converts the given term to a charlist according to the `List.Chars` protocol. ## Examples iex> to_charlist(:foo) 'foo' """ defmacro to_charlist(term) do quote(do: List.Chars.to_charlist(unquote(term))) end @doc """ Returns `true` if `term` is `nil`, `false` otherwise. Allowed in guard clauses. ## Examples iex> is_nil(1) false iex> is_nil(nil) true """ @doc guard: true defmacro is_nil(term) do quote(do: unquote(term) == nil) end @doc """ A convenience macro that checks if the right side (an expression) matches the left side (a pattern). ## Examples iex> match?(1, 1) true iex> match?({1, _}, {1, 2}) true iex> map = %{a: 1, b: 2} iex> match?(%{a: _}, map) true iex> a = 1 iex> match?(^a, 1) true `match?/2` is very useful when filtering or finding a value in an enumerable: iex> list = [a: 1, b: 2, a: 3] iex> Enum.filter(list, &match?({:a, _}, &1)) [a: 1, a: 3] Guard clauses can also be given to the match: iex> list = [a: 1, b: 2, a: 3] iex> Enum.filter(list, &match?({:a, x} when x < 2, &1)) [a: 1] However, variables assigned in the match will not be available outside of the function call (unlike regular pattern matching with the `=` operator): iex> match?(_x, 1) true iex> binding() [] Furthermore, remember the pin operator matches _values_, not _patterns_: match?(%{x: 1}, %{x: 1, y: 2}) #=> true attrs = %{x: 1} match?(^attrs, %{x: 1, y: 2}) #=> false The pin operator will check if the values are equal, using `===/2`, while patterns have their own rules when matching maps, lists, and so forth. Such behaviour is not specific to `match?/2`. The following code also throws an exception: attrs = %{x: 1} ^attrs = %{x: 1, y: 2} #=> (MatchError) no match of right hand side value: %{x: 1, y: 2} """ defmacro match?(pattern, expr) do success = quote do unquote(pattern) -> true end failure = quote generated: true do _ -> false end {:case, [], [expr, [do: success ++ failure]]} end @doc """ Module attribute unary operator. Reads and writes attributes in the current module. The canonical example for attributes is annotating that a module implements an OTP behaviour, such as `GenServer`: defmodule MyServer do @behaviour GenServer # ... callbacks ... end By default Elixir supports all the module attributes supported by Erlang, but custom attributes can be used as well: defmodule MyServer do @my_data 13 IO.inspect(@my_data) #=> 13 end Unlike Erlang, such attributes are not stored in the module by default since it is common in Elixir to use custom attributes to store temporary data that will be available at compile-time. Custom attributes may be configured to behave closer to Erlang by using `Module.register_attribute/3`. > **Important:** Libraries and frameworks should consider prefixing any > module attributes that are private by underscore, such as `@_my_data` > so code completion tools do not show them on suggestions and prompts. Finally, note that attributes can also be read inside functions: defmodule MyServer do @my_data 11 def first_data, do: @my_data @my_data 13 def second_data, do: @my_data end MyServer.first_data() #=> 11 MyServer.second_data() #=> 13 It is important to note that reading an attribute takes a snapshot of its current value. In other words, the value is read at compilation time and not at runtime. Check the `Module` module for other functions to manipulate module attributes. ## Attention! Multiple references of the same attribute As mentioned above, every time you read a module attribute, a snapshot of its current value is taken. Therefore, if you are storing large values inside module attributes (for example, embedding external files in module attributes), you should avoid referencing the same attribute multiple times. For example, don't do this: @files %{ example1: File.read!("lib/example1.data"), example2: File.read!("lib/example2.data") } def example1, do: @files[:example1] def example2, do: @files[:example2] In the above, each reference to `@files` may end-up with a complete and individual copy of the whole `@files` module attribute. Instead, reference the module attribute once in a private function: @files %{ example1: File.read!("lib/example1.data"), example2: File.read!("lib/example2.data") } defp files(), do: @files def example1, do: files()[:example1] def example2, do: files()[:example2] ## Attention! Compile-time dependencies Keep in mind references to other modules, even in module attributes, generate compile-time dependencies to said modules. For example, take this common pattern: @values [:foo, :bar, :baz] def handle_arg(arg) when arg in @values do ... end While the above is fine, imagine if instead you have actual module names in the module attribute, like this: @values [Foo, Bar, Baz] def handle_arg(arg) when arg in @values do ... end The code above will define a compile-time dependency on the modules `Foo`, `Bar`, and `Baz`, in a way that, if any of them change, the current module will have to recompile. In such cases, it may be preferred to avoid the module attribute altogether: def handle_arg(arg) when arg in [Foo, Bar, Baz] do ... end """ defmacro @expr defmacro @{:__aliases__, _meta, _args} do raise ArgumentError, "module attributes set via @ cannot start with an uppercase letter" end defmacro @{name, meta, args} do assert_module_scope(__CALLER__, :@, 1) function? = __CALLER__.function != nil cond do # Check for Macro as it is compiled later than Kernel not bootstrapped?(Macro) -> nil not function? and __CALLER__.context == :match -> raise ArgumentError, """ invalid write attribute syntax. If you want to define an attribute, don't do this: @foo = :value Instead, do this: @foo :value """ # Typespecs attributes are currently special cased by the compiler is_list(args) and typespec?(name) -> case bootstrapped?(Kernel.Typespec) do false -> :ok true -> pos = :elixir_locals.cache_env(__CALLER__) %{line: line, file: file, module: module} = __CALLER__ quote do Kernel.Typespec.deftypespec( unquote(name), unquote(Macro.escape(hd(args), unquote: true)), unquote(line), unquote(file), unquote(module), unquote(pos) ) end end true -> do_at(args, meta, name, function?, __CALLER__) end end # @attribute(value) defp do_at([arg], meta, name, function?, env) do line = case :lists.keymember(:context, 1, meta) do true -> nil false -> env.line end cond do function? -> raise ArgumentError, "cannot set attribute @#{name} inside function/macro" name == :behavior -> warn_message = "@behavior attribute is not supported, please use @behaviour instead" IO.warn(warn_message, Macro.Env.stacktrace(env)) :lists.member(name, [:moduledoc, :typedoc, :doc]) -> arg = {env.line, arg} quote do Module.__put_attribute__(__MODULE__, unquote(name), unquote(arg), unquote(line)) end true -> arg = expand_attribute(name, arg, env) quote do Module.__put_attribute__(__MODULE__, unquote(name), unquote(arg), unquote(line)) end end end # @attribute() defp do_at([], meta, name, function?, env) do IO.warn( "the @#{name}() notation (with parenthesis) is deprecated, please use @#{name} (without parenthesis) instead", Macro.Env.stacktrace(env) ) do_at(nil, meta, name, function?, env) end # @attribute defp do_at(args, _meta, name, function?, env) when is_atom(args) do line = env.line doc_attr? = :lists.member(name, [:moduledoc, :typedoc, :doc]) case function? do true -> value = case Module.__get_attribute__(env.module, name, line) do {_, doc} when doc_attr? -> doc other -> other end try do :elixir_quote.escape(value, :none, false) rescue ex in [ArgumentError] -> raise ArgumentError, "cannot inject attribute @#{name} into function/macro because " <> Exception.message(ex) end false when doc_attr? -> quote do case Module.__get_attribute__(__MODULE__, unquote(name), unquote(line)) do {_, doc} -> doc other -> other end end false -> quote do Module.__get_attribute__(__MODULE__, unquote(name), unquote(line)) end end end # Error cases defp do_at([{call, meta, ctx_or_args}, [{:do, _} | _] = kw], _meta, name, _function?, _env) do args = case is_atom(ctx_or_args) do true -> [] false -> ctx_or_args end code = "\n@#{name} (#{Macro.to_string({call, meta, args ++ [kw]})})" raise ArgumentError, """ expected 0 or 1 argument for @#{name}, got 2. It seems you are trying to use the do-syntax with @module attributes \ but the do-block is binding to the attribute name. You probably want \ to wrap the argument value in parentheses, like this: #{String.replace(code, "\n", "\n ")} """ end defp do_at(args, _meta, name, _function?, _env) do raise ArgumentError, "expected 0 or 1 argument for @#{name}, got: #{length(args)}" end defp expand_attribute(:compile, arg, env) do Macro.prewalk(arg, fn # {:no_warn_undefined, alias} {elem, {:__aliases__, _, _} = alias} -> {elem, Macro.expand(alias, %{env | function: {:__info__, 1}})} # {alias, fun, arity} {:{}, meta, [{:__aliases__, _, _} = alias, fun, arity]} -> {:{}, meta, [Macro.expand(alias, %{env | function: {:__info__, 1}}), fun, arity]} node -> node end) end defp expand_attribute(_, arg, _), do: arg defp typespec?(:type), do: true defp typespec?(:typep), do: true defp typespec?(:opaque), do: true defp typespec?(:spec), do: true defp typespec?(:callback), do: true defp typespec?(:macrocallback), do: true defp typespec?(_), do: false @doc """ Returns the binding for the given context as a keyword list. In the returned result, keys are variable names and values are the corresponding variable values. If the given `context` is `nil` (by default it is), the binding for the current context is returned. ## Examples iex> x = 1 iex> binding() [x: 1] iex> x = 2 iex> binding() [x: 2] iex> binding(:foo) [] iex> var!(x, :foo) = 1 1 iex> binding(:foo) [x: 1] """ defmacro binding(context \\ nil) do in_match? = Macro.Env.in_match?(__CALLER__) bindings = for {v, c} <- Macro.Env.vars(__CALLER__), c == context do {v, wrap_binding(in_match?, {v, [generated: true], c})} end :lists.sort(bindings) end defp wrap_binding(true, var) do quote(do: ^unquote(var)) end defp wrap_binding(_, var) do var end @doc """ Provides an `if/2` macro. This macro expects the first argument to be a condition and the second argument to be a keyword list. ## One-liner examples if(foo, do: bar) In the example above, `bar` will be returned if `foo` evaluates to a truthy value (neither `false` nor `nil`). Otherwise, `nil` will be returned. An `else` option can be given to specify the opposite: if(foo, do: bar, else: baz) ## Blocks examples It's also possible to pass a block to the `if/2` macro. The first example above would be translated to: if foo do bar end Note that `do`-`end` become delimiters. The second example would translate to: if foo do bar else baz end In order to compare more than two clauses, the `cond/1` macro has to be used. """ defmacro if(condition, clauses) do build_if(condition, clauses) end defp build_if(condition, do: do_clause) do build_if(condition, do: do_clause, else: nil) end defp build_if(condition, do: do_clause, else: else_clause) do optimize_boolean( quote do case unquote(condition) do x when :"Elixir.Kernel".in(x, [false, nil]) -> unquote(else_clause) _ -> unquote(do_clause) end end ) end defp build_if(_condition, _arguments) do raise ArgumentError, "invalid or duplicate keys for if, only \"do\" and an optional \"else\" are permitted" end @doc """ Provides an `unless` macro. This macro evaluates and returns the `do` block passed in as the second argument if `condition` evaluates to a falsy value (`false` or `nil`). Otherwise, it returns the value of the `else` block if present or `nil` if not. See also `if/2`. ## Examples iex> unless(Enum.empty?([]), do: "Hello") nil iex> unless(Enum.empty?([1, 2, 3]), do: "Hello") "Hello" iex> unless Enum.sum([2, 2]) == 5 do ...> "Math still works" ...> else ...> "Math is broken" ...> end "Math still works" """ defmacro unless(condition, clauses) do build_unless(condition, clauses) end defp build_unless(condition, do: do_clause) do build_unless(condition, do: do_clause, else: nil) end defp build_unless(condition, do: do_clause, else: else_clause) do quote do if(unquote(condition), do: unquote(else_clause), else: unquote(do_clause)) end end defp build_unless(_condition, _arguments) do raise ArgumentError, "invalid or duplicate keys for unless, " <> "only \"do\" and an optional \"else\" are permitted" end @doc """ Destructures two lists, assigning each term in the right one to the matching term in the left one. Unlike pattern matching via `=`, if the sizes of the left and right lists don't match, destructuring simply stops instead of raising an error. ## Examples iex> destructure([x, y, z], [1, 2, 3, 4, 5]) iex> {x, y, z} {1, 2, 3} In the example above, even though the right list has more entries than the left one, destructuring works fine. If the right list is smaller, the remaining elements are simply set to `nil`: iex> destructure([x, y, z], [1]) iex> {x, y, z} {1, nil, nil} The left-hand side supports any expression you would use on the left-hand side of a match: x = 1 destructure([^x, y, z], [1, 2, 3]) The example above will only work if `x` matches the first value in the right list. Otherwise, it will raise a `MatchError` (like the `=` operator would do). """ defmacro destructure(left, right) when is_list(left) do quote do unquote(left) = Kernel.Utils.destructure(unquote(right), unquote(length(left))) end end @doc """ Creates a range from `first` to `last`. If first is less than last, the range will be increasing from first to last. If first is equal to last, the range will contain one element, which is the number itself. If first is more than last, the range will be decreasing from first to last, albeit this behaviour is deprecated. Instead prefer to explicitly list the step with `first..last//-1`. See the `Range` module for more information. ## Examples iex> 0 in 1..3 false iex> 2 in 1..3 true iex> Enum.to_list(1..3) [1, 2, 3] """ defmacro first..last do case bootstrapped?(Macro) do true -> first = Macro.expand(first, __CALLER__) last = Macro.expand(last, __CALLER__) validate_range!(first, last) range(__CALLER__.context, first, last) false -> range(__CALLER__.context, first, last) end end defp range(_context, first, last) when is_integer(first) and is_integer(last) do # TODO: Deprecate inferring a range with a step of -1 on Elixir v1.17 step = if first <= last, do: 1, else: -1 {:%{}, [], [__struct__: Elixir.Range, first: first, last: last, step: step]} end defp range(nil, first, last) do quote(do: Elixir.Range.new(unquote(first), unquote(last))) end defp range(:guard, first, last) do # TODO: Deprecate me inside guard when sides are not integers on Elixir v1.17 {:%{}, [], [__struct__: Elixir.Range, first: first, last: last, step: nil]} end defp range(:match, first, last) do # TODO: Deprecate me inside match in all occasions (including literals) on Elixir v1.17 {:%{}, [], [__struct__: Elixir.Range, first: first, last: last]} end @doc """ Creates a range from `first` to `last` with `step`. See the `Range` module for more information. ## Examples iex> 0 in 1..3//1 false iex> 2 in 1..3//1 true iex> 2 in 1..3//2 false iex> Enum.to_list(1..3//1) [1, 2, 3] iex> Enum.to_list(1..3//2) [1, 3] iex> Enum.to_list(3..1//-1) [3, 2, 1] iex> Enum.to_list(1..0//1) [] """ @doc since: "1.12.0" defmacro first..last//step do case bootstrapped?(Macro) do true -> first = Macro.expand(first, __CALLER__) last = Macro.expand(last, __CALLER__) step = Macro.expand(step, __CALLER__) validate_range!(first, last) validate_step!(step) range(__CALLER__.context, first, last, step) false -> range(__CALLER__.context, first, last, step) end end defp range(context, first, last, step) when is_integer(first) and is_integer(last) and is_integer(step) when context != nil do {:%{}, [], [__struct__: Elixir.Range, first: first, last: last, step: step]} end defp range(nil, first, last, step) do quote(do: Elixir.Range.new(unquote(first), unquote(last), unquote(step))) end defp validate_range!(first, last) when is_float(first) or is_float(last) or is_atom(first) or is_atom(last) or is_binary(first) or is_binary(last) or is_list(first) or is_list(last) do raise ArgumentError, "ranges (first..last//step) expect both sides to be integers, " <> "got: #{Macro.to_string({:.., [], [first, last]})}" end defp validate_range!(_, _), do: :ok defp validate_step!(step) when is_float(step) or is_atom(step) or is_binary(step) or is_list(step) or step == 0 do raise ArgumentError, "ranges (first..last//step) expect the step to be a non-zero integer, " <> "got: #{Macro.to_string(step)}" end defp validate_step!(_), do: :ok @doc """ Boolean "and" operator. Provides a short-circuit operator that evaluates and returns the second expression only if the first one evaluates to a truthy value (neither `false` nor `nil`). Returns the first expression otherwise. Not allowed in guard clauses. ## Examples iex> Enum.empty?([]) && Enum.empty?([]) true iex> List.first([]) && true nil iex> Enum.empty?([]) && List.first([1]) 1 iex> false && throw(:bad) false Note that, unlike `and/2`, this operator accepts any expression as the first argument, not only booleans. """ defmacro left && right do assert_no_match_or_guard_scope(__CALLER__.context, "&&") quote do case unquote(left) do x when :"Elixir.Kernel".in(x, [false, nil]) -> x _ -> unquote(right) end end end @doc """ Boolean "or" operator. Provides a short-circuit operator that evaluates and returns the second expression only if the first one does not evaluate to a truthy value (that is, it is either `nil` or `false`). Returns the first expression otherwise. Not allowed in guard clauses. ## Examples iex> Enum.empty?([1]) || Enum.empty?([1]) false iex> List.first([]) || true true iex> Enum.empty?([1]) || 1 1 iex> Enum.empty?([]) || throw(:bad) true Note that, unlike `or/2`, this operator accepts any expression as the first argument, not only booleans. """ defmacro left || right do assert_no_match_or_guard_scope(__CALLER__.context, "||") quote do case unquote(left) do x when :"Elixir.Kernel".in(x, [false, nil]) -> unquote(right) x -> x end end end @doc """ Pipe operator. This operator introduces the expression on the left-hand side as the first argument to the function call on the right-hand side. ## Examples iex> [1, [2], 3] |> List.flatten() [1, 2, 3] The example above is the same as calling `List.flatten([1, [2], 3])`. The `|>` operator is mostly useful when there is a desire to execute a series of operations resembling a pipeline: iex> [1, [2], 3] |> List.flatten() |> Enum.map(fn x -> x * 2 end) [2, 4, 6] In the example above, the list `[1, [2], 3]` is passed as the first argument to the `List.flatten/1` function, then the flattened list is passed as the first argument to the `Enum.map/2` function which doubles each element of the list. In other words, the expression above simply translates to: Enum.map(List.flatten([1, [2], 3]), fn x -> x * 2 end) ## Pitfalls There are two common pitfalls when using the pipe operator. The first one is related to operator precedence. For example, the following expression: String.graphemes "Hello" |> Enum.reverse Translates to: String.graphemes("Hello" |> Enum.reverse()) which results in an error as the `Enumerable` protocol is not defined for binaries. Adding explicit parentheses resolves the ambiguity: String.graphemes("Hello") |> Enum.reverse() Or, even better: "Hello" |> String.graphemes() |> Enum.reverse() The second limitation is that Elixir always pipes to a function call. Therefore, to pipe into an anonymous function, you need to invoke it: some_fun = &Regex.replace(~r/l/, &1, "L") "Hello" |> some_fun.() Alternatively, you can use `then/2` for the same effect: some_fun = &Regex.replace(~r/l/, &1, "L") "Hello" |> then(some_fun) `then/2` is most commonly used when you want to pipe to a function but the value is expected outside of the first argument, such as above. By replacing `some_fun` by its value, we get: "Hello" |> then(&Regex.replace(~r/l/,&1, "L")) """ defmacro left |> right do [{h, _} | t] = Macro.unpipe({:|>, [], [left, right]}) fun = fn {x, pos}, acc -> Macro.pipe(acc, x, pos) end :lists.foldl(fun, h, t) end @doc """ Returns `true` if `module` is loaded and contains a public `function` with the given `arity`, otherwise `false`. Note that this function does not load the module in case it is not loaded. Check `Code.ensure_loaded/1` for more information. Inlined by the compiler. ## Examples iex> function_exported?(Enum, :map, 2) true iex> function_exported?(Enum, :map, 10) false iex> function_exported?(List, :to_string, 1) true """ @spec function_exported?(module, atom, arity) :: boolean def function_exported?(module, function, arity) do :erlang.function_exported(module, function, arity) end @doc """ Returns `true` if `module` is loaded and contains a public `macro` with the given `arity`, otherwise `false`. Note that this function does not load the module in case it is not loaded. Check `Code.ensure_loaded/1` for more information. If `module` is an Erlang module (as opposed to an Elixir module), this function always returns `false`. ## Examples iex> macro_exported?(Kernel, :use, 2) true iex> macro_exported?(:erlang, :abs, 1) false """ @spec macro_exported?(module, atom, arity) :: boolean def macro_exported?(module, macro, arity) when is_atom(module) and is_atom(macro) and is_integer(arity) and (arity >= 0 and arity <= 255) do function_exported?(module, :__info__, 1) and :lists.member({macro, arity}, module.__info__(:macros)) end @doc """ Power operator. It expects two numbers are input. If the left-hand side is an integer and the right-hand side is more than or equal to 0, then the result is integer. Otherwise it returns a float. ## Examples iex> 2 ** 2 4 iex> 2 ** -4 0.0625 iex> 2.0 ** 2 4.0 iex> 2 ** 2.0 4.0 """ @doc since: "1.13.0" @spec integer ** non_neg_integer :: integer @spec integer ** neg_integer :: float @spec float ** float :: float def base ** exponent when is_integer(base) and is_integer(exponent) and exponent >= 0 do integer_pow(base, 1, exponent) end def base ** exponent when is_number(base) and is_number(exponent) do :math.pow(base, exponent) end # https://en.wikipedia.org/wiki/Exponentiation_by_squaring defp integer_pow(_, _, 0), do: 1 defp integer_pow(b, a, 1), do: b * a defp integer_pow(b, a, e) when :erlang.band(e, 1) == 0, do: integer_pow(b * b, a, :erlang.bsr(e, 1)) defp integer_pow(b, a, e), do: integer_pow(b * b, a * b, :erlang.bsr(e, 1)) @doc """ Membership operator. Checks if the element on the left-hand side is a member of the collection on the right-hand side. ## Examples iex> x = 1 iex> x in [1, 2, 3] true This operator (which is a macro) simply translates to a call to `Enum.member?/2`. The example above would translate to: Enum.member?([1, 2, 3], x) Elixir also supports `left not in right`, which evaluates to `not(left in right)`: iex> x = 1 iex> x not in [1, 2, 3] false ## Guards The `in/2` operator (as well as `not in`) can be used in guard clauses as long as the right-hand side is a range or a list. In such cases, Elixir will expand the operator to a valid guard expression. For example: when x in [1, 2, 3] translates to: when x === 1 or x === 2 or x === 3 However, this construct will be inneficient for large lists. In such cases, it is best to stop using guards and use a more appropriate data structure, such as `MapSet`. ### AST considerations `left not in right` is parsed by the compiler into the AST: {:not, _, [{:in, _, [left, right]}]} This is the same AST as `not(left in right)`. Additionally, `Macro.to_string/2` and `Code.format_string!/2` will translate all occurrences of this AST to `left not in right`. """ @doc guard: true defmacro left in right do in_body? = __CALLER__.context == nil expand = case bootstrapped?(Macro) do true -> &Macro.expand(&1, __CALLER__) false -> & &1 end case expand.(right) do [] when not in_body? -> false [] -> quote do _ = unquote(left) false end [head | tail] = list -> # We only expand lists in the body if they are relatively # short and it is made only of literal expressions. case not in_body? or small_literal_list?(right) do true -> in_var(in_body?, left, &in_list(&1, head, tail, expand, list, in_body?)) false -> quote(do: :lists.member(unquote(left), unquote(right))) end {:%{}, _meta, [__struct__: Elixir.Range, first: first, last: last, step: step]} -> in_var(in_body?, left, &in_range(&1, expand.(first), expand.(last), expand.(step))) right when in_body? -> quote(do: Elixir.Enum.member?(unquote(right), unquote(left))) %{__struct__: Elixir.Range, first: _, last: _, step: _} -> raise ArgumentError, "non-literal range in guard should be escaped with Macro.escape/2" right -> raise_on_invalid_args_in_2(right) end end defp raise_on_invalid_args_in_2(right) do raise ArgumentError, << "invalid right argument for operator \"in\", it expects a compile-time proper list ", "or compile-time range on the right side when used in guard expressions, got: ", Macro.to_string(right)::binary >> end defp in_var(false, ast, fun), do: fun.(ast) defp in_var(true, {atom, _, context} = var, fun) when is_atom(atom) and is_atom(context), do: fun.(var) defp in_var(true, ast, fun) do quote do var = unquote(ast) unquote(fun.(quote(do: var))) end end defp small_literal_list?(list) when is_list(list) and length(list) <= 32 do :lists.all(fn x -> is_binary(x) or is_atom(x) or is_number(x) end, list) end defp small_literal_list?(_list), do: false defp in_range(left, first, last, nil) do # TODO: nil steps are only supported due to x..y in guards. Remove me on Elixir 2.0. quote do :erlang.is_integer(unquote(left)) and :erlang.is_integer(unquote(first)) and :erlang.is_integer(unquote(last)) and ((:erlang."=<"(unquote(first), unquote(last)) and unquote(increasing_compare(left, first, last))) or (:erlang.<(unquote(last), unquote(first)) and unquote(decreasing_compare(left, first, last)))) end end defp in_range(left, first, last, step) when is_integer(step) do in_range_literal(left, first, last, step) end defp in_range(left, first, last, step) do quoted = quote do :erlang.is_integer(unquote(left)) and :erlang.is_integer(unquote(first)) and :erlang.is_integer(unquote(last)) and ((:erlang.>(unquote(step), 0) and unquote(increasing_compare(left, first, last))) or (:erlang.<(unquote(step), 0) and unquote(decreasing_compare(left, first, last)))) end in_range_step(quoted, left, first, step) end defp in_range_literal(left, first, first, _step) when is_integer(first) do quote do: :erlang."=:="(unquote(left), unquote(first)) end defp in_range_literal(left, first, last, step) when step > 0 do quoted = quote do :erlang.andalso( :erlang.is_integer(unquote(left)), unquote(increasing_compare(left, first, last)) ) end in_range_step(quoted, left, first, step) end defp in_range_literal(left, first, last, step) when step < 0 do quoted = quote do :erlang.andalso( :erlang.is_integer(unquote(left)), unquote(decreasing_compare(left, first, last)) ) end in_range_step(quoted, left, first, step) end defp in_range_step(quoted, _left, _first, step) when step == 1 or step == -1 do quoted end defp in_range_step(quoted, left, first, step) do quote do :erlang.andalso( unquote(quoted), :erlang."=:="(:erlang.rem(unquote(left) - unquote(first), unquote(step)), 0) ) end end defp in_list(left, head, tail, expand, right, in_body?) do [head | tail] = :lists.map(&comp(left, &1, expand, right, in_body?), [head | tail]) :lists.foldl(&quote(do: :erlang.orelse(unquote(&2), unquote(&1))), head, tail) end defp comp(left, {:|, _, [head, tail]}, expand, right, in_body?) do case expand.(tail) do [] -> quote(do: :erlang."=:="(unquote(left), unquote(head))) [tail_head | tail] -> quote do :erlang.orelse( :erlang."=:="(unquote(left), unquote(head)), unquote(in_list(left, tail_head, tail, expand, right, in_body?)) ) end tail when in_body? -> quote do :erlang.orelse( :erlang."=:="(unquote(left), unquote(head)), :lists.member(unquote(left), unquote(tail)) ) end _ -> raise_on_invalid_args_in_2(right) end end defp comp(left, right, _expand, _right, _in_body?) do quote(do: :erlang."=:="(unquote(left), unquote(right))) end defp increasing_compare(var, first, last) do quote do :erlang.andalso( :erlang.>=(unquote(var), unquote(first)), :erlang."=<"(unquote(var), unquote(last)) ) end end defp decreasing_compare(var, first, last) do quote do :erlang.andalso( :erlang."=<"(unquote(var), unquote(first)), :erlang.>=(unquote(var), unquote(last)) ) end end @doc """ Marks that the given variable should not be hygienized. This macro expects a variable and it is typically invoked inside `Kernel.SpecialForms.quote/2` to mark that a variable should not be hygienized. See `Kernel.SpecialForms.quote/2` for more information. ## Examples iex> Kernel.var!(example) = 1 1 iex> Kernel.var!(example) 1 """ defmacro var!(var, context \\ nil) defmacro var!({name, meta, atom}, context) when is_atom(name) and is_atom(atom) do # Remove counter and force them to be vars meta = :lists.keydelete(:counter, 1, meta) meta = :lists.keystore(:if_undefined, 1, meta, {:if_undefined, :raise}) case Macro.expand(context, __CALLER__) do context when is_atom(context) -> {name, meta, context} other -> raise ArgumentError, "expected var! context to expand to an atom, got: #{Macro.to_string(other)}" end end defmacro var!(other, _context) do raise ArgumentError, "expected a variable to be given to var!, got: #{Macro.to_string(other)}" end @doc """ When used inside quoting, marks that the given alias should not be hygienized. This means the alias will be expanded when the macro is expanded. Check `Kernel.SpecialForms.quote/2` for more information. """ defmacro alias!(alias) when is_atom(alias) do alias end defmacro alias!({:__aliases__, meta, args}) do # Simply remove the alias metadata from the node # so it does not affect expansion. {:__aliases__, :lists.keydelete(:alias, 1, meta), args} end ## Definitions implemented in Elixir @doc ~S""" Defines a module given by name with the given contents. This macro defines a module with the given `alias` as its name and with the given contents. It returns a tuple with four elements: * `:module` * the module name * the binary contents of the module * the result of evaluating the contents block ## Examples defmodule Number do def one, do: 1 def two, do: 2 end #=> {:module, Number, <<70, 79, 82, ...>>, {:two, 0}} Number.one() #=> 1 Number.two() #=> 2 ## Nesting Nesting a module inside another module affects the name of the nested module: defmodule Foo do defmodule Bar do end end In the example above, two modules - `Foo` and `Foo.Bar` - are created. When nesting, Elixir automatically creates an alias to the inner module, allowing the second module `Foo.Bar` to be accessed as `Bar` in the same lexical scope where it's defined (the `Foo` module). This only happens if the nested module is defined via an alias. If the `Foo.Bar` module is moved somewhere else, the references to `Bar` in the `Foo` module need to be updated to the fully-qualified name (`Foo.Bar`) or an alias has to be explicitly set in the `Foo` module with the help of `Kernel.SpecialForms.alias/2`. defmodule Foo.Bar do # code end defmodule Foo do alias Foo.Bar # code here can refer to "Foo.Bar" as just "Bar" end ## Dynamic names Elixir module names can be dynamically generated. This is very useful when working with macros. For instance, one could write: defmodule String.to_atom("Foo#{1}") do # contents ... end Elixir will accept any module name as long as the expression passed as the first argument to `defmodule/2` evaluates to an atom. Note that, when a dynamic name is used, Elixir won't nest the name under the current module nor automatically set up an alias. ## Reserved module names If you attempt to define a module that already exists, you will get a warning saying that a module has been redefined. There are some modules that Elixir does not currently implement but it may be implement in the future. Those modules are reserved and defining them will result in a compilation error: defmodule Any do # code end ** (CompileError) iex:1: module Any is reserved and cannot be defined Elixir reserves the following module names: `Elixir`, `Any`, `BitString`, `PID`, and `Reference`. """ defmacro defmodule(alias, do_block) defmacro defmodule(alias, do: block) do env = __CALLER__ expanded = expand_module_alias(alias, env) {expanded, with_alias} = case is_atom(expanded) do true -> # Expand the module considering the current environment/nesting {full, old, new} = alias_defmodule(alias, expanded, env) meta = [defined: full, context: env.module] ++ alias_meta(alias) {full, {:alias, meta, [old, [as: new, warn: false]]}} false -> {expanded, nil} end # We do this so that the block is not tail-call optimized and stacktraces # are not messed up. Basically, we just insert something between the return # value of the block and what is returned by defmodule. Using just ":ok" or # similar doesn't work because it's likely optimized away by the compiler. block = quote do result = unquote(block) :elixir_utils.noop() result end escaped = case env do %{function: nil, lexical_tracker: pid} when is_pid(pid) -> integer = Kernel.LexicalTracker.write_cache(pid, block) quote(do: Kernel.LexicalTracker.read_cache(unquote(pid), unquote(integer))) %{} -> :elixir_quote.escape(block, :none, false) end module_vars = :lists.map(&module_var/1, :maps.keys(env.versioned_vars)) quote do unquote(with_alias) :elixir_module.compile(unquote(expanded), unquote(escaped), unquote(module_vars), __ENV__) end end defp alias_meta({:__aliases__, meta, _}), do: meta defp alias_meta(_), do: [] # We don't want to trace :alias_reference since we are defining the alias defp expand_module_alias({:__aliases__, _, _} = original, env) do case :elixir_aliases.expand_or_concat(original, env) do receiver when is_atom(receiver) -> receiver aliases -> aliases = :lists.map(&Macro.expand(&1, env), aliases) case :lists.all(&is_atom/1, aliases) do true -> :elixir_aliases.concat(aliases) false -> original end end end defp expand_module_alias(other, env), do: Macro.expand(other, env) # defmodule Elixir.Alias defp alias_defmodule({:__aliases__, _, [:"Elixir", _ | _]}, module, _env), do: {module, module, nil} # defmodule Alias in root defp alias_defmodule({:__aliases__, _, _}, module, %{module: nil}), do: {module, module, nil} # defmodule Alias nested defp alias_defmodule({:__aliases__, _, [h | t]}, _module, env) when is_atom(h) do module = :elixir_aliases.concat([env.module, h]) alias = String.to_atom("Elixir." <> Atom.to_string(h)) case t do [] -> {module, module, alias} _ -> {String.to_atom(Enum.join([module | t], ".")), module, alias} end end # defmodule _ defp alias_defmodule(_raw, module, _env) do {module, module, nil} end defp module_var({name, kind}) when is_atom(kind), do: {name, [generated: true], kind} defp module_var({name, kind}), do: {name, [counter: kind, generated: true], nil} @doc ~S""" Defines a public function with the given name and body. ## Examples defmodule Foo do def bar, do: :baz end Foo.bar() #=> :baz A function that expects arguments can be defined as follows: defmodule Foo do def sum(a, b) do a + b end end In the example above, a `sum/2` function is defined; this function receives two arguments and returns their sum. ## Default arguments `\\` is used to specify a default value for a parameter of a function. For example: defmodule MyMath do def multiply_by(number, factor \\ 2) do number * factor end end MyMath.multiply_by(4, 3) #=> 12 MyMath.multiply_by(4) #=> 8 The compiler translates this into multiple functions with different arities, here `MyMath.multiply_by/1` and `MyMath.multiply_by/2`, that represent cases when arguments for parameters with default values are passed or not passed. When defining a function with default arguments as well as multiple explicitly declared clauses, you must write a function head that declares the defaults. For example: defmodule MyString do def join(string1, string2 \\ nil, separator \\ " ") def join(string1, nil, _separator) do string1 end def join(string1, string2, separator) do string1 <> separator <> string2 end end Note that `\\` can't be used with anonymous functions because they can only have a sole arity. ### Keyword lists with default arguments Functions containing many arguments can benefit from using `Keyword` lists to group and pass attributes as a single value. defmodule MyConfiguration do @default_opts [storage: "local"] def configure(resource, opts \\ []) do opts = Keyword.merge(@default_opts, opts) storage = opts[:storage] # ... end end The difference between using `Map` and `Keyword` to store many arguments is `Keyword`'s keys: * must be atoms * can be given more than once * ordered, as specified by the developer ## Function and variable names Function and variable names have the following syntax: A _lowercase ASCII letter_ or an _underscore_, followed by any number of _lowercase or uppercase ASCII letters_, _numbers_, or _underscores_. Optionally they can end in either an _exclamation mark_ or a _question mark_. For variables, any identifier starting with an underscore should indicate an unused variable. For example: def foo(bar) do [] end #=> warning: variable bar is unused def foo(_bar) do [] end #=> no warning def foo(_bar) do _bar end #=> warning: the underscored variable "_bar" is used after being set ## `rescue`/`catch`/`after`/`else` Function bodies support `rescue`, `catch`, `after`, and `else` as `Kernel.SpecialForms.try/1` does (known as "implicit try"). For example, the following two functions are equivalent: def convert(number) do try do String.to_integer(number) rescue e in ArgumentError -> {:error, e.message} end end def convert(number) do String.to_integer(number) rescue e in ArgumentError -> {:error, e.message} end """ defmacro def(call, expr \\ nil) do define(:def, call, expr, __CALLER__) end @doc """ Defines a private function with the given name and body. Private functions are only accessible from within the module in which they are defined. Trying to access a private function from outside the module it's defined in results in an `UndefinedFunctionError` exception. Check `def/2` for more information. ## Examples defmodule Foo do def bar do sum(1, 2) end defp sum(a, b), do: a + b end Foo.bar() #=> 3 Foo.sum(1, 2) ** (UndefinedFunctionError) undefined function Foo.sum/2 """ defmacro defp(call, expr \\ nil) do define(:defp, call, expr, __CALLER__) end @doc """ Defines a public macro with the given name and body. Macros must be defined before its usage. Check `def/2` for rules on naming and default arguments. ## Examples defmodule MyLogic do defmacro unless(expr, opts) do quote do if !unquote(expr), unquote(opts) end end end require MyLogic MyLogic.unless false do IO.puts("It works") end """ defmacro defmacro(call, expr \\ nil) do define(:defmacro, call, expr, __CALLER__) end @doc """ Defines a private macro with the given name and body. Private macros are only accessible from the same module in which they are defined. Private macros must be defined before its usage. Check `defmacro/2` for more information, and check `def/2` for rules on naming and default arguments. """ defmacro defmacrop(call, expr \\ nil) do define(:defmacrop, call, expr, __CALLER__) end defp define(kind, call, expr, env) do module = assert_module_scope(env, kind, 2) assert_no_function_scope(env, kind, 2) unquoted_call = :elixir_quote.has_unquotes(call) unquoted_expr = :elixir_quote.has_unquotes(expr) escaped_call = :elixir_quote.escape(call, :none, true) escaped_expr = case unquoted_expr do true -> :elixir_quote.escape(expr, :none, true) false -> key = :erlang.unique_integer() :elixir_module.write_cache(module, key, expr) quote(do: :elixir_module.read_cache(unquote(module), unquote(key))) end # Do not check clauses if any expression was unquoted check_clauses = not (unquoted_expr or unquoted_call) pos = :elixir_locals.cache_env(env) quote do :elixir_def.store_definition( unquote(kind), unquote(check_clauses), unquote(escaped_call), unquote(escaped_expr), unquote(pos) ) end end @doc """ Defines a struct. A struct is a tagged map that allows developers to provide default values for keys, tags to be used in polymorphic dispatches and compile time assertions. For more information about structs, please check `Kernel.SpecialForms.%/2`. It is only possible to define a struct per module, as the struct it tied to the module itself. Calling `defstruct/1` also defines a `__struct__/0` function that returns the struct itself. ## Examples defmodule User do defstruct name: nil, age: nil end Struct fields are evaluated at compile-time, which allows them to be dynamic. In the example below, `10 + 11` is evaluated at compile-time and the age field is stored with value `21`: defmodule User do defstruct name: nil, age: 10 + 11 end The `fields` argument is usually a keyword list with field names as atom keys and default values as corresponding values. `defstruct/1` also supports a list of atoms as its argument: in that case, the atoms in the list will be used as the struct's field names and they will all default to `nil`. defmodule Post do defstruct [:title, :content, :author] end ## Deriving Although structs are maps, by default structs do not implement any of the protocols implemented for maps. For example, attempting to use a protocol with the `User` struct leads to an error: john = %User{name: "John"} MyProtocol.call(john) ** (Protocol.UndefinedError) protocol MyProtocol not implemented for %User{...} `defstruct/1`, however, allows protocol implementations to be *derived*. This can be done by defining a `@derive` attribute as a list before invoking `defstruct/1`: defmodule User do @derive [MyProtocol] defstruct name: nil, age: 10 + 11 end MyProtocol.call(john) # it works! For each protocol in the `@derive` list, Elixir will assert the protocol has been implemented for `Any`. If the `Any` implementation defines a `__deriving__/3` callback, the callback will be invoked and it should define the implementation module. Otherwise an implementation that simply points to the `Any` implementation is automatically derived. For more information on the `__deriving__/3` callback, see `Protocol.derive/3`. ## Enforcing keys When building a struct, Elixir will automatically guarantee all keys belongs to the struct: %User{name: "john", unknown: :key} ** (KeyError) key :unknown not found in: %User{age: 21, name: nil} Elixir also allows developers to enforce certain keys must always be given when building the struct: defmodule User do @enforce_keys [:name] defstruct name: nil, age: 10 + 11 end Now trying to build a struct without the name key will fail: %User{age: 21} ** (ArgumentError) the following keys must also be given when building struct User: [:name] Keep in mind `@enforce_keys` is a simple compile-time guarantee to aid developers when building structs. It is not enforced on updates and it does not provide any sort of value-validation. ## Types It is recommended to define types for structs. By convention such type is called `t`. To define a struct inside a type, the struct literal syntax is used: defmodule User do defstruct name: "John", age: 25 @type t :: %__MODULE__{name: String.t(), age: non_neg_integer} end It is recommended to only use the struct syntax when defining the struct's type. When referring to another struct it's better to use `User.t` instead of `%User{}`. The types of the struct fields that are not included in `%User{}` default to `term()` (see `t:term/0`). Structs whose internal structure is private to the local module (pattern matching them or directly accessing their fields should not be allowed) should use the `@opaque` attribute. Structs whose internal structure is public should use `@type`. """ defmacro defstruct(fields) do builder = case bootstrapped?(Enum) do true -> quote do case @enforce_keys do [] -> def __struct__(kv) do Enum.reduce(kv, @__struct__, fn {key, val}, map -> Map.replace!(map, key, val) end) end _ -> def __struct__(kv) do {map, keys} = Enum.reduce(kv, {@__struct__, @enforce_keys}, fn {key, val}, {map, keys} -> {Map.replace!(map, key, val), List.delete(keys, key)} end) case keys do [] -> map _ -> raise ArgumentError, "the following keys must also be given when building " <> "struct #{inspect(__MODULE__)}: #{inspect(keys)}" end end end end false -> quote do _ = @enforce_keys def __struct__(kv) do :lists.foldl(fn {key, val}, acc -> Map.replace!(acc, key, val) end, @__struct__, kv) end end end quote do if Module.has_attribute?(__MODULE__, :__struct__) do raise ArgumentError, "defstruct has already been called for " <> "#{Kernel.inspect(__MODULE__)}, defstruct can only be called once per module" end {struct, keys, derive} = Kernel.Utils.defstruct(__MODULE__, unquote(fields)) @__struct__ struct @enforce_keys keys case derive do [] -> :ok _ -> Protocol.__derive__(derive, __MODULE__, __ENV__) end def __struct__() do @__struct__ end unquote(builder) Kernel.Utils.announce_struct(__MODULE__) struct end end @doc ~S""" Defines an exception. Exceptions are structs backed by a module that implements the `Exception` behaviour. The `Exception` behaviour requires two functions to be implemented: * [`exception/1`](`c:Exception.exception/1`) - receives the arguments given to `raise/2` and returns the exception struct. The default implementation accepts either a set of keyword arguments that is merged into the struct or a string to be used as the exception's message. * [`message/1`](`c:Exception.message/1`) - receives the exception struct and must return its message. Most commonly exceptions have a message field which by default is accessed by this function. However, if an exception does not have a message field, this function must be explicitly implemented. Since exceptions are structs, the API supported by `defstruct/1` is also available in `defexception/1`. ## Raising exceptions The most common way to raise an exception is via `raise/2`: defmodule MyAppError do defexception [:message] end value = [:hello] raise MyAppError, message: "did not get what was expected, got: #{inspect(value)}" In many cases it is more convenient to pass the expected value to `raise/2` and generate the message in the `c:Exception.exception/1` callback: defmodule MyAppError do defexception [:message] @impl true def exception(value) do msg = "did not get what was expected, got: #{inspect(value)}" %MyAppError{message: msg} end end raise MyAppError, value The example above shows the preferred strategy for customizing exception messages. """ defmacro defexception(fields) do quote bind_quoted: [fields: fields] do @behaviour Exception struct = defstruct([__exception__: true] ++ fields) if Map.has_key?(struct, :message) do @impl true def message(exception) do exception.message end defoverridable message: 1 @impl true def exception(msg) when Kernel.is_binary(msg) do exception(message: msg) end end # Calls to Kernel functions must be fully-qualified to ensure # reproducible builds; otherwise, this macro will generate ASTs # with different metadata (:import, :context) depending on if # it is the bootstrapped version or not. # TODO: Change the implementation on v2.0 to simply call Kernel.struct!/2 @impl true def exception(args) when Kernel.is_list(args) do struct = __struct__() {valid, invalid} = Enum.split_with(args, fn {k, _} -> Map.has_key?(struct, k) end) case invalid do [] -> :ok _ -> IO.warn( "the following fields are unknown when raising " <> "#{Kernel.inspect(__MODULE__)}: #{Kernel.inspect(invalid)}. " <> "Please make sure to only give known fields when raising " <> "or redefine #{Kernel.inspect(__MODULE__)}.exception/1 to " <> "discard unknown fields. Future Elixir versions will raise on " <> "unknown fields given to raise/2" ) end Kernel.struct!(struct, valid) end defoverridable exception: 1 end end @doc """ Defines a protocol. See the `Protocol` module for more information. """ defmacro defprotocol(name, do_block) defmacro defprotocol(name, do: block) do Protocol.__protocol__(name, do: block) end @doc """ Defines an implementation for the given protocol. See the `Protocol` module for more information. """ defmacro defimpl(name, opts, do_block \\ []) do merged = Keyword.merge(opts, do_block) merged = Keyword.put_new(merged, :for, __CALLER__.module) if Keyword.fetch!(merged, :for) == nil do raise ArgumentError, "defimpl/3 expects a :for option when declared outside a module" end Protocol.__impl__(name, merged) end @doc """ Makes the given definitions in the current module overridable. If the user defines a new function or macro with the same name and arity, then the overridable ones are discarded. Otherwise, the original definitions are used. It is possible for the overridden definition to have a different visibility than the original: a public function can be overridden by a private function and vice-versa. Macros cannot be overridden as functions and vice-versa. ## Example defmodule DefaultMod do defmacro __using__(_opts) do quote do def test(x, y) do x + y end defoverridable test: 2 end end end defmodule InheritMod do use DefaultMod def test(x, y) do x * y + super(x, y) end end As seen as in the example above, `super` can be used to call the default implementation. If `@behaviour` has been defined, `defoverridable` can also be called with a module as an argument. All implemented callbacks from the behaviour above the call to `defoverridable` will be marked as overridable. ## Example defmodule Behaviour do @callback foo :: any end defmodule DefaultMod do defmacro __using__(_opts) do quote do @behaviour Behaviour def foo do "Override me" end defoverridable Behaviour end end end defmodule InheritMod do use DefaultMod def foo do "Overridden" end end """ defmacro defoverridable(keywords_or_behaviour) do quote do Module.make_overridable(__MODULE__, unquote(keywords_or_behaviour)) end end @doc """ Generates a macro suitable for use in guard expressions. It raises at compile time if the definition uses expressions that aren't allowed in guards, and otherwise creates a macro that can be used both inside or outside guards. Note the convention in Elixir is to name functions/macros allowed in guards with the `is_` prefix, such as `is_list/1`. If, however, the function/macro returns a boolean and is not allowed in guards, it should have no prefix and end with a question mark, such as `Keyword.keyword?/1`. ## Example defmodule Integer.Guards do defguard is_even(value) when is_integer(value) and rem(value, 2) == 0 end defmodule Collatz do @moduledoc "Tools for working with the Collatz sequence." import Integer.Guards @doc "Determines the number of steps `n` takes to reach `1`." # If this function never converges, please let me know what `n` you used. def converge(n) when n > 0, do: step(n, 0) defp step(1, step_count) do step_count end defp step(n, step_count) when is_even(n) do step(div(n, 2), step_count + 1) end defp step(n, step_count) do step(3 * n + 1, step_count + 1) end end """ @doc since: "1.6.0" @spec defguard(Macro.t()) :: Macro.t() defmacro defguard(guard) do define_guard(:defmacro, guard, __CALLER__) end @doc """ Generates a private macro suitable for use in guard expressions. It raises at compile time if the definition uses expressions that aren't allowed in guards, and otherwise creates a private macro that can be used both inside or outside guards in the current module. Similar to `defmacrop/2`, `defguardp/1` must be defined before its use in the current module. """ @doc since: "1.6.0" @spec defguardp(Macro.t()) :: Macro.t() defmacro defguardp(guard) do define_guard(:defmacrop, guard, __CALLER__) end defp define_guard(kind, guard, env) do case :elixir_utils.extract_guards(guard) do {call, [_, _ | _]} -> raise ArgumentError, "invalid syntax in defguard #{Macro.to_string(call)}, " <> "only a single when clause is allowed" {call, impls} -> case Macro.decompose_call(call) do {_name, args} -> validate_variable_only_args!(call, args) macro_definition = case impls do [] -> define(kind, call, nil, env) [guard] -> quoted = quote do require Kernel.Utils Kernel.Utils.defguard(unquote(args), unquote(guard)) end define(kind, call, [do: quoted], env) end quote do @doc guard: true unquote(macro_definition) end _invalid_definition -> raise ArgumentError, "invalid syntax in defguard #{Macro.to_string(call)}" end end end defp validate_variable_only_args!(call, args) do Enum.each(args, fn {ref, _meta, context} when is_atom(ref) and is_atom(context) -> :ok {:\\, _m1, [{ref, _m2, context}, _default]} when is_atom(ref) and is_atom(context) -> :ok _match -> raise ArgumentError, "invalid syntax in defguard #{Macro.to_string(call)}" end) end @doc """ Uses the given module in the current context. When calling: use MyModule, some: :options Elixir will invoke `MyModule.__using__/1` passing the second argument of `use` as its argument. Since `__using__/1` is typically a macro, all the usual macro rules apply, and its return value should be quoted code that is then inserted where `use/2` is called. > Note: `use MyModule` works as a code injection point in the caller. > Given the caller of `use MyModule` has little control over how the > code is injected, `use/2` should be used with care. If you can, > avoid use in favor of `import/2` or `alias/2` whenever possible. ## Examples For example, to write test cases using the `ExUnit` framework provided with Elixir, a developer should `use` the `ExUnit.Case` module: defmodule AssertionTest do use ExUnit.Case, async: true test "always pass" do assert true end end In this example, Elixir will call the `__using__/1` macro in the `ExUnit.Case` module with the keyword list `[async: true]` as its argument. In other words, `use/2` translates to: defmodule AssertionTest do require ExUnit.Case ExUnit.Case.__using__(async: true) test "always pass" do assert true end end where `ExUnit.Case` defines the `__using__/1` macro: defmodule ExUnit.Case do defmacro __using__(opts) do # do something with opts quote do # return some code to inject in the caller end end end ## Best practices `__using__/1` is typically used when there is a need to set some state (via module attributes) or callbacks (like `@before_compile`, see the documentation for `Module` for more information) into the caller. `__using__/1` may also be used to alias, require, or import functionality from different modules: defmodule MyModule do defmacro __using__(_opts) do quote do import MyModule.Foo import MyModule.Bar import MyModule.Baz alias MyModule.Repo end end end However, do not provide `__using__/1` if all it does is to import, alias or require the module itself. For example, avoid this: defmodule MyModule do defmacro __using__(_opts) do quote do import MyModule end end end In such cases, developers should instead import or alias the module directly, so that they can customize those as they wish, without the indirection behind `use/2`. Finally, developers should also avoid defining functions inside the `__using__/1` callback, unless those functions are the default implementation of a previously defined `@callback` or are functions meant to be overridden (see `defoverridable/1`). Even in these cases, defining functions should be seen as a "last resort". """ defmacro use(module, opts \\ []) do calls = Enum.map(expand_aliases(module, __CALLER__), fn expanded when is_atom(expanded) -> quote do require unquote(expanded) unquote(expanded).__using__(unquote(opts)) end _otherwise -> raise ArgumentError, "invalid arguments for use, " <> "expected a compile time atom or alias, got: #{Macro.to_string(module)}" end) quote(do: (unquote_splicing(calls))) end defp expand_aliases({{:., _, [base, :{}]}, _, refs}, env) do base = Macro.expand(base, env) Enum.map(refs, fn {:__aliases__, _, ref} -> Module.concat([base | ref]) ref when is_atom(ref) -> Module.concat(base, ref) other -> other end) end defp expand_aliases(module, env) do [Macro.expand(module, env)] end @doc """ Defines a function that delegates to another module. Functions defined with `defdelegate/2` are public and can be invoked from outside the module they're defined in, as if they were defined using `def/2`. Therefore, `defdelegate/2` is about extending the current module's public API. If what you want is to invoke a function defined in another module without using its full module name, then use `alias/2` to shorten the module name or use `import/2` to be able to invoke the function without the module name altogether. Delegation only works with functions; delegating macros is not supported. Check `def/2` for rules on naming and default arguments. ## Options * `:to` - the module to dispatch to. * `:as` - the function to call on the target given in `:to`. This parameter is optional and defaults to the name being delegated (`funs`). ## Examples defmodule MyList do defdelegate reverse(list), to: Enum defdelegate other_reverse(list), to: Enum, as: :reverse end MyList.reverse([1, 2, 3]) #=> [3, 2, 1] MyList.other_reverse([1, 2, 3]) #=> [3, 2, 1] """ defmacro defdelegate(funs, opts) do funs = Macro.escape(funs, unquote: true) # don't add compile-time dependency on :to opts = with true <- is_list(opts), {:ok, target} <- Keyword.fetch(opts, :to), {:__aliases__, _, _} <- target do target = Macro.expand(target, %{__CALLER__ | function: {:__info__, 1}}) Keyword.replace!(opts, :to, target) else _ -> opts end quote bind_quoted: [funs: funs, opts: opts] do target = Keyword.get(opts, :to) || raise ArgumentError, "expected to: to be given as argument" if is_list(funs) do IO.warn( "passing a list to Kernel.defdelegate/2 is deprecated, please define each delegate separately", Macro.Env.stacktrace(__ENV__) ) end if Keyword.has_key?(opts, :append_first) do IO.warn( "Kernel.defdelegate/2 :append_first option is deprecated", Macro.Env.stacktrace(__ENV__) ) end for fun <- List.wrap(funs) do {name, args, as, as_args} = Kernel.Utils.defdelegate(fun, opts) @doc delegate_to: {target, as, :erlang.length(as_args)} # Build the call AST by hand so it doesn't get a # context and it warns on things like missing @impl def unquote({name, [line: __ENV__.line], args}) do unquote(target).unquote(as)(unquote_splicing(as_args)) end end end end ## Sigils @doc ~S""" Handles the sigil `~S` for strings. It returns a string without interpolations and without escape characters, except for the escaping of the closing sigil character itself. ## Examples iex> ~S(foo) "foo" iex> ~S(f#{o}o) "f\#{o}o" iex> ~S(\o/) "\\o/" However, if you want to re-use the sigil character itself on the string, you need to escape it: iex> ~S((\)) "()" """ defmacro sigil_S(term, modifiers) defmacro sigil_S({:<<>>, _, [binary]}, []) when is_binary(binary), do: binary @doc ~S""" Handles the sigil `~s` for strings. It returns a string as if it was a double quoted string, unescaping characters and replacing interpolations. ## Examples iex> ~s(foo) "foo" iex> ~s(f#{:o}o) "foo" iex> ~s(f\#{:o}o) "f\#{:o}o" """ defmacro sigil_s(term, modifiers) defmacro sigil_s({:<<>>, _, [piece]}, []) when is_binary(piece) do :elixir_interpolation.unescape_string(piece) end defmacro sigil_s({:<<>>, line, pieces}, []) do {:<<>>, line, unescape_tokens(pieces)} end @doc ~S""" Handles the sigil `~C` for charlists. It returns a charlist without interpolations and without escape characters, except for the escaping of the closing sigil character itself. ## Examples iex> ~C(foo) 'foo' iex> ~C(f#{o}o) 'f\#{o}o' """ defmacro sigil_C(term, modifiers) defmacro sigil_C({:<<>>, _meta, [string]}, []) when is_binary(string) do String.to_charlist(string) end @doc ~S""" Handles the sigil `~c` for charlists. It returns a charlist as if it was a single quoted string, unescaping characters and replacing interpolations. ## Examples iex> ~c(foo) 'foo' iex> ~c(f#{:o}o) 'foo' iex> ~c(f\#{:o}o) 'f\#{:o}o' """ defmacro sigil_c(term, modifiers) # We can skip the runtime conversion if we are # creating a binary made solely of series of chars. defmacro sigil_c({:<<>>, _meta, [string]}, []) when is_binary(string) do String.to_charlist(:elixir_interpolation.unescape_string(string)) end defmacro sigil_c({:<<>>, _meta, pieces}, []) do quote(do: List.to_charlist(unquote(unescape_list_tokens(pieces)))) end @doc ~S""" Handles the sigil `~r` for regular expressions. It returns a regular expression pattern, unescaping characters and replacing interpolations. More information on regular expressions can be found in the `Regex` module. ## Examples iex> Regex.match?(~r/foo/, "foo") true iex> Regex.match?(~r/a#{:b}c/, "abc") true While the `~r` sigil allows parens and brackets to be used as delimiters, it is preferred to use `"` or `/` to avoid escaping conflicts with reserved regex characters. """ defmacro sigil_r(term, modifiers) defmacro sigil_r({:<<>>, _meta, [string]}, options) when is_binary(string) do binary = :elixir_interpolation.unescape_string(string, &Regex.unescape_map/1) regex = Regex.compile!(binary, :binary.list_to_bin(options)) Macro.escape(regex) end defmacro sigil_r({:<<>>, meta, pieces}, options) do binary = {:<<>>, meta, unescape_tokens(pieces, &Regex.unescape_map/1)} quote(do: Regex.compile!(unquote(binary), unquote(:binary.list_to_bin(options)))) end @doc ~S""" Handles the sigil `~R` for regular expressions. It returns a regular expression pattern without interpolations and without escape characters. Note it still supports escape of Regex tokens (such as escaping `+` or `?`) and it also requires you to escape the closing sigil character itself if it appears on the Regex. More information on regexes can be found in the `Regex` module. ## Examples iex> Regex.match?(~R(f#{1,3}o), "f#o") true """ defmacro sigil_R(term, modifiers) defmacro sigil_R({:<<>>, _meta, [string]}, options) when is_binary(string) do regex = Regex.compile!(string, :binary.list_to_bin(options)) Macro.escape(regex) end @doc ~S""" Handles the sigil `~D` for dates. By default, this sigil uses the built-in `Calendar.ISO`, which requires dates to be written in the ISO8601 format: ~D[yyyy-mm-dd] such as: ~D[2015-01-13] If you are using alternative calendars, any representation can be used as long as you follow the representation by a single space and the calendar name: ~D[SOME-REPRESENTATION My.Alternative.Calendar] The lower case `~d` variant does not exist as interpolation and escape characters are not useful for date sigils. More information on dates can be found in the `Date` module. ## Examples iex> ~D[2015-01-13] ~D[2015-01-13] """ defmacro sigil_D(date_string, modifiers) defmacro sigil_D({:<<>>, _, [string]}, []) do {{:ok, {year, month, day}}, calendar} = parse_with_calendar!(string, :parse_date, "Date") to_calendar_struct(Date, calendar: calendar, year: year, month: month, day: day) end @doc ~S""" Handles the sigil `~T` for times. By default, this sigil uses the built-in `Calendar.ISO`, which requires times to be written in the ISO8601 format: ~T[hh:mm:ss] ~T[hh:mm:ss.ssssss] such as: ~T[13:00:07] ~T[13:00:07.123] If you are using alternative calendars, any representation can be used as long as you follow the representation by a single space and the calendar name: ~T[SOME-REPRESENTATION My.Alternative.Calendar] The lower case `~t` variant does not exist as interpolation and escape characters are not useful for time sigils. More information on times can be found in the `Time` module. ## Examples iex> ~T[13:00:07] ~T[13:00:07] iex> ~T[13:00:07.001] ~T[13:00:07.001] """ defmacro sigil_T(time_string, modifiers) defmacro sigil_T({:<<>>, _, [string]}, []) do {{:ok, {hour, minute, second, microsecond}}, calendar} = parse_with_calendar!(string, :parse_time, "Time") to_calendar_struct(Time, calendar: calendar, hour: hour, minute: minute, second: second, microsecond: microsecond ) end @doc ~S""" Handles the sigil `~N` for naive date times. By default, this sigil uses the built-in `Calendar.ISO`, which requires naive date times to be written in the ISO8601 format: ~N[yyyy-mm-dd hh:mm:ss] ~N[yyyy-mm-dd hh:mm:ss.ssssss] ~N[yyyy-mm-ddThh:mm:ss.ssssss] such as: ~N[2015-01-13 13:00:07] ~N[2015-01-13T13:00:07.123] If you are using alternative calendars, any representation can be used as long as you follow the representation by a single space and the calendar name: ~N[SOME-REPRESENTATION My.Alternative.Calendar] The lower case `~n` variant does not exist as interpolation and escape characters are not useful for date time sigils. More information on naive date times can be found in the `NaiveDateTime` module. ## Examples iex> ~N[2015-01-13 13:00:07] ~N[2015-01-13 13:00:07] iex> ~N[2015-01-13T13:00:07.001] ~N[2015-01-13 13:00:07.001] """ defmacro sigil_N(naive_datetime_string, modifiers) defmacro sigil_N({:<<>>, _, [string]}, []) do {{:ok, {year, month, day, hour, minute, second, microsecond}}, calendar} = parse_with_calendar!(string, :parse_naive_datetime, "NaiveDateTime") to_calendar_struct(NaiveDateTime, calendar: calendar, year: year, month: month, day: day, hour: hour, minute: minute, second: second, microsecond: microsecond ) end @doc ~S""" Handles the sigil `~U` to create a UTC `DateTime`. By default, this sigil uses the built-in `Calendar.ISO`, which requires UTC date times to be written in the ISO8601 format: ~U[yyyy-mm-dd hh:mm:ssZ] ~U[yyyy-mm-dd hh:mm:ss.ssssssZ] ~U[yyyy-mm-ddThh:mm:ss.ssssss+00:00] such as: ~U[2015-01-13 13:00:07Z] ~U[2015-01-13T13:00:07.123+00:00] If you are using alternative calendars, any representation can be used as long as you follow the representation by a single space and the calendar name: ~U[SOME-REPRESENTATION My.Alternative.Calendar] The given `datetime_string` must include "Z" or "00:00" offset which marks it as UTC, otherwise an error is raised. The lower case `~u` variant does not exist as interpolation and escape characters are not useful for date time sigils. More information on date times can be found in the `DateTime` module. ## Examples iex> ~U[2015-01-13 13:00:07Z] ~U[2015-01-13 13:00:07Z] iex> ~U[2015-01-13T13:00:07.001+00:00] ~U[2015-01-13 13:00:07.001Z] """ @doc since: "1.9.0" defmacro sigil_U(datetime_string, modifiers) defmacro sigil_U({:<<>>, _, [string]}, []) do {{:ok, {year, month, day, hour, minute, second, microsecond}, offset}, calendar} = parse_with_calendar!(string, :parse_utc_datetime, "UTC DateTime") if offset != 0 do raise ArgumentError, "cannot parse #{inspect(string)} as UTC DateTime for #{inspect(calendar)}, reason: :non_utc_offset" end to_calendar_struct(DateTime, calendar: calendar, year: year, month: month, day: day, hour: hour, minute: minute, second: second, microsecond: microsecond, time_zone: "Etc/UTC", zone_abbr: "UTC", utc_offset: 0, std_offset: 0 ) end defp parse_with_calendar!(string, fun, context) do {calendar, string} = extract_calendar(string) result = apply(calendar, fun, [string]) {maybe_raise!(result, calendar, context, string), calendar} end defp extract_calendar(string) do case :binary.split(string, " ", [:global]) do [_] -> {Calendar.ISO, string} parts -> maybe_atomize_calendar(List.last(parts), string) end end defp maybe_atomize_calendar(<<alias, _::binary>> = last_part, string) when alias >= ?A and alias <= ?Z do string = binary_part(string, 0, byte_size(string) - byte_size(last_part) - 1) {String.to_atom("Elixir." <> last_part), string} end defp maybe_atomize_calendar(_last_part, string) do {Calendar.ISO, string} end defp maybe_raise!({:error, reason}, calendar, type, string) do raise ArgumentError, "cannot parse #{inspect(string)} as #{type} for #{inspect(calendar)}, " <> "reason: #{inspect(reason)}" end defp maybe_raise!(other, _calendar, _type, _string), do: other defp to_calendar_struct(type, fields) do quote do %{unquote_splicing([__struct__: type] ++ fields)} end end @doc ~S""" Handles the sigil `~w` for list of words. It returns a list of "words" split by whitespace. Character unescaping and interpolation happens for each word. ## Modifiers * `s`: words in the list are strings (default) * `a`: words in the list are atoms * `c`: words in the list are charlists ## Examples iex> ~w(foo #{:bar} baz) ["foo", "bar", "baz"] iex> ~w(foo #{" bar baz "}) ["foo", "bar", "baz"] iex> ~w(--source test/enum_test.exs) ["--source", "test/enum_test.exs"] iex> ~w(foo bar baz)a [:foo, :bar, :baz] iex> ~w(foo bar baz)c ['foo', 'bar', 'baz'] """ defmacro sigil_w(term, modifiers) defmacro sigil_w({:<<>>, _meta, [string]}, modifiers) when is_binary(string) do split_words(:elixir_interpolation.unescape_string(string), modifiers, __CALLER__) end defmacro sigil_w({:<<>>, meta, pieces}, modifiers) do binary = {:<<>>, meta, unescape_tokens(pieces)} split_words(binary, modifiers, __CALLER__) end @doc ~S""" Handles the sigil `~W` for list of words. It returns a list of "words" split by whitespace without interpolations and without escape characters, except for the escaping of the closing sigil character itself. ## Modifiers * `s`: words in the list are strings (default) * `a`: words in the list are atoms * `c`: words in the list are charlists ## Examples iex> ~W(foo #{bar} baz) ["foo", "\#{bar}", "baz"] """ defmacro sigil_W(term, modifiers) defmacro sigil_W({:<<>>, _meta, [string]}, modifiers) when is_binary(string) do split_words(string, modifiers, __CALLER__) end defp split_words(string, [], caller) do split_words(string, [?s], caller) end defp split_words(string, [mod], caller) when mod == ?s or mod == ?a or mod == ?c do case is_binary(string) do true -> parts = String.split(string) parts_with_trailing_comma = :lists.filter(&(byte_size(&1) > 1 and :binary.last(&1) == ?,), parts) if parts_with_trailing_comma != [] do stacktrace = Macro.Env.stacktrace(caller) IO.warn( "the sigils ~w/~W do not allow trailing commas at the end of each word. " <> "If the comma is necessary, define a regular list with [...], otherwise remove the comma.", stacktrace ) end case mod do ?s -> parts ?a -> :lists.map(&String.to_atom/1, parts) ?c -> :lists.map(&String.to_charlist/1, parts) end false -> parts = quote(do: String.split(unquote(string))) case mod do ?s -> parts ?a -> quote(do: :lists.map(&String.to_atom/1, unquote(parts))) ?c -> quote(do: :lists.map(&String.to_charlist/1, unquote(parts))) end end end defp split_words(_string, _mods, _caller) do raise ArgumentError, "modifier must be one of: s, a, c" end ## Shared functions defp assert_module_scope(env, fun, arity) do case env.module do nil -> raise ArgumentError, "cannot invoke #{fun}/#{arity} outside module" mod -> mod end end defp assert_no_function_scope(env, fun, arity) do case env.function do nil -> :ok _ -> raise ArgumentError, "cannot invoke #{fun}/#{arity} inside function/macro" end end defp assert_no_match_or_guard_scope(context, exp) do case context do :match -> invalid_match!(exp) :guard -> raise ArgumentError, "invalid expression in guard, #{exp} is not allowed in guards. " <> "To learn more about guards, visit: https://hexdocs.pm/elixir/patterns-and-guards.html" _ -> :ok end end defp invalid_match!(exp) do raise ArgumentError, "invalid expression in match, #{exp} is not allowed in patterns " <> "such as function clauses, case clauses or on the left side of the = operator" end # Helper to handle the :ok | :error tuple returned from :elixir_interpolation.unescape_tokens # We need to do this for bootstrapping purposes, actual code can use Macro.unescape_string. defp unescape_tokens(tokens) do :lists.map( fn token -> case is_binary(token) do true -> :elixir_interpolation.unescape_string(token) false -> token end end, tokens ) end defp unescape_tokens(tokens, unescape_map) do :lists.map( fn token -> case is_binary(token) do true -> :elixir_interpolation.unescape_string(token, unescape_map) false -> token end end, tokens ) end defp unescape_list_tokens(tokens) do escape = fn {:"::", _, [expr, _]} -> expr binary when is_binary(binary) -> :elixir_interpolation.unescape_string(binary) end :lists.map(escape, tokens) end @doc false defmacro to_char_list(arg) do IO.warn( "Kernel.to_char_list/1 is deprecated, use Kernel.to_charlist/1 instead", Macro.Env.stacktrace(__CALLER__) ) quote(do: Kernel.to_charlist(unquote(arg))) end end
27.065449
116
0.633069
734b77169a02b77f1cc580e3d8a4770beddb1347
1,147
exs
Elixir
config/config.exs
danielgrieve/plug_media_type_router
30144c4977af8f0718b22e0fa463a18447eb47a0
[ "MIT" ]
1
2019-04-13T10:01:07.000Z
2019-04-13T10:01:07.000Z
config/config.exs
danielgrieve/plug_media_type_router
30144c4977af8f0718b22e0fa463a18447eb47a0
[ "MIT" ]
null
null
null
config/config.exs
danielgrieve/plug_media_type_router
30144c4977af8f0718b22e0fa463a18447eb47a0
[ "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 :plug_media_type_router, key: :value # # And access this configuration in your application as: # # Application.get_env(:plug_media_type_router, :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"
37
73
0.757629
734b7f5488bd2d9c0d7839e5eea67ad8308af0ad
1,650
ex
Elixir
lib/ed_explorer/web/web.ex
lee-dohm/ed-explorer
879a883a8143531bc657fa74e55f72ed36b3547e
[ "MIT" ]
1
2020-01-26T18:07:51.000Z
2020-01-26T18:07:51.000Z
lib/ed_explorer/web/web.ex
lee-dohm/ed-explorer
879a883a8143531bc657fa74e55f72ed36b3547e
[ "MIT" ]
null
null
null
lib/ed_explorer/web/web.ex
lee-dohm/ed-explorer
879a883a8143531bc657fa74e55f72ed36b3547e
[ "MIT" ]
null
null
null
defmodule EdExplorer.Web do @moduledoc """ A module that keeps using definitions for controllers, views and so on. This can be used in your application as: use EdExplorer.Web, :controller use EdExplorer.Web, :view The definitions below will be executed for every view, controller, etc, so keep them short and clean, focused on imports, uses and aliases. Do NOT define functions inside the quoted expressions below. """ def controller do quote do use Phoenix.Controller, namespace: EdExplorer.Web import Plug.Conn import EdExplorer.Web.Router.Helpers import EdExplorer.Web.Gettext end end def view do quote do use Phoenix.View, root: "lib/ed_explorer/web/templates", namespace: EdExplorer.Web # Import convenience functions from controllers import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1] # Use all HTML functionality (forms, tags, etc) use Phoenix.HTML import EdExplorer.Web.Router.Helpers import EdExplorer.Web.ErrorHelpers import EdExplorer.Web.Gettext import EdExplorer.Web.AvatarHelpers import EdExplorer.Web.OcticonHelpers end end def router do quote do use Phoenix.Router import Plug.Conn import Phoenix.Controller end end def channel do quote do use Phoenix.Channel import EdExplorer.Web.Gettext end end @doc """ When used, dispatch to the appropriate controller/view/etc. """ defmacro __using__(which) when is_atom(which) do apply(__MODULE__, which, []) end end
23.571429
88
0.686061
734b8254224741830818b96618bcbafa68110400
27,285
ex
Elixir
deps/socket/lib/socket/web.ex
mahcinek/concurrency
55fcee4e5be6be3505dc4512ae8b091844e6a14f
[ "MIT" ]
1
2017-05-19T09:32:08.000Z
2017-05-19T09:32:08.000Z
deps/socket/lib/socket/web.ex
mahcinek/concurrency
55fcee4e5be6be3505dc4512ae8b091844e6a14f
[ "MIT" ]
null
null
null
deps/socket/lib/socket/web.ex
mahcinek/concurrency
55fcee4e5be6be3505dc4512ae8b091844e6a14f
[ "MIT" ]
null
null
null
# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE # Version 2, December 2004 # # DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE # TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION # # 0. You just DO WHAT THE FUCK YOU WANT TO. defmodule Socket.Web do @moduledoc ~S""" This module implements RFC 6455 WebSockets. ## Client example socket = Socket.Web.connect! "echo.websocket.org" socket |> Socket.Web.send! { :text, "test" } socket |> Socket.Web.recv! # => {:text, "test"} ## Server example server = Socket.Web.listen! 80 client = server |> Socket.Web.accept! # here you can verify if you want to accept the request or not, call # `Socket.Web.close!` if you don't want to accept it, or else call # `Socket.Web.accept!` client |> Socket.Web.accept! # echo the first message client |> Socket.Web.send!(client |> Socket.Web.recv!) """ use Bitwise import Kernel, except: [length: 1, send: 2] alias __MODULE__, as: W @type error :: Socket.TCP.error | Socket.SSL.error @type packet :: { :text, String.t } | { :binary, binary } | { :fragmented, :text | :binary | :continuation | :end, binary } | :close | { :close, atom, binary } | { :ping, binary } | { :pong, binary } @compile { :inline, opcode: 1, close_code: 1, key: 1, length: 1, forge: 2 } Enum.each [ text: 0x1, binary: 0x2, close: 0x8, ping: 0x9, pong: 0xA ], fn { name, code } -> defp opcode(unquote(name)), do: unquote(code) defp opcode(unquote(code)), do: unquote(name) end Enum.each [ normal: 1000, going_away: 1001, protocol_error: 1002, unsupported_data: 1003, reserved: 1004, no_status_received: 1005, abnormal: 1006, invalid_payload: 1007, policy_violation: 1008, message_too_big: 1009, mandatory_extension: 1010, internal_error: 1011, handshake: 1015 ], fn { name, code } -> defp close_code(unquote(name)), do: unquote(code) defp close_code(unquote(code)), do: unquote(name) end defmacrop known?(n) do quote do unquote(n) in [0x1, 0x2, 0x8, 0x9, 0xA] end end defmacrop data?(n) do quote do unquote(n) in 0x1 .. 0x7 or unquote(n) in [:text, :binary] end end defmacrop control?(n) do quote do unquote(n) in 0x8 .. 0xF or unquote(n) in [:close, :ping, :pong] end end defstruct [:socket, :version, :path, :origin, :protocols, :extensions, :key, :mask, { :headers, %{} }] @type t :: %Socket.Web{ socket: term, version: 13, path: String.t, origin: String.t, protocols: [String.t], extensions: [String.t], key: String.t, mask: boolean } @spec headers(%{String.t => String.t}, Socket.t, Keyword.t) :: %{String.t => String.t} defp headers(acc, socket, options) do case socket |> Socket.Stream.recv!(options) do { :http_header, _, name, _, value } when name |> is_atom -> acc |> Map.put(Atom.to_string(name) |> String.downcase, value) |> headers(socket, options) { :http_header, _, name, _, value } when name |> is_binary -> acc |> Map.put(String.downcase(name), value) |> headers(socket, options) :http_eoh -> acc end end @spec key(String.t) :: String.t defp key(value) do :crypto.hash(:sha, value <> "258EAFA5-E914-47DA-95CA-C5AB0DC85B11") |> :base64.encode end @doc """ Connects to the given address or { address, port } tuple. """ @spec connect({ Socket.Address.t, :inet.port_number }) :: { :ok, t } | { :error, error } def connect({ address, port }) do connect(address, port, []) end def connect(address) do connect(address, []) end @doc """ Connect to the given address or { address, port } tuple with the given options or address and port. """ @spec connect({ Socket.Address.t, :inet.port_number } | Socket.Address.t, Keyword.t | :inet.port_number) :: { :ok, t } | { :error, error } def connect({ address, port }, options) do connect(address, port, options) end def connect(address, options) when options |> is_list do connect(address, if(options[:secure], do: 443, else: 80), options) end def connect(address, port) when port |> is_integer do connect(address, port, []) end @doc """ Connect to the given address, port and options. ## Options `:path` sets the path to give the server, `/` by default `:origin` sets the Origin header, this is optional `:handshake` is the key used for the handshake, this is optional You can also pass TCP or SSL options, depending if you're using secure websockets or not. """ @spec connect(Socket.Address.t, :inet.port_number, Keyword.t) :: { :ok, t } | { :error, error } def connect(address, port, options) do try do { :ok, connect!(address, port, options) } rescue e in [MatchError] -> case e.term do { :http_response, _, http_code, http_message } -> { :error, { http_code, http_message } } _ -> { :error, "malformed handshake" } end e in [RuntimeError] -> { :error, e.message } e in [Socket.Error] -> { :error, e.message } e in [Socket.TCP.Error, Socket.SSL.Error] -> { :error, e.code } end end @doc """ Connects to the given address or { address, port } tuple, raising if an error occurs. """ @spec connect!({ Socket.Address.t, :inet.port_number }) :: t | no_return def connect!({ address, port }) do connect!(address, port, []) end def connect!(address) do connect!(address, []) end @doc """ Connect to the given address or { address, port } tuple with the given options or address and port, raising if an error occurs. """ @spec connect!({ Socket.Address.t, :inet.port_number } | Socket.Address.t, Keyword.t | :inet.port_number) :: t | no_return def connect!({ address, port }, options) do connect!(address, port, options) end def connect!(address, options) when options |> is_list do connect!(address, if(options[:secure], do: 443, else: 80), options) end def connect!(address, port) when port |> is_integer do connect!(address, port, []) end @doc """ Connect to the given address, port and options, raising if an error occurs. ## Options `:path` sets the path to give the server, `/` by default `:origin` sets the Origin header, this is optional `:handshake` is the key used for the handshake, this is optional `:headers` are additional headers that will be sent You can also pass TCP or SSL options, depending if you're using secure websockets or not. """ @spec connect!(Socket.Address.t, :inet.port_number, Keyword.t) :: t | no_return def connect!(address, port, options) do { local, global } = arguments(options) mod = if local[:secure] do Socket.SSL else Socket.TCP end path = local[:path] || "/" origin = local[:origin] protocols = local[:protocol] extensions = local[:extensions] handshake = :base64.encode(local[:handshake] || "fork the dongles") headers = Enum.map(local[:headers] || %{}, fn({ k, v }) -> ["#{k}: #{v}", "\r\n"] end) client = mod.connect!(address, port, global) client |> Socket.packet!(:raw) client |> Socket.Stream.send!([ "GET #{path} HTTP/1.1", "\r\n", headers, "Host: #{address}:#{port}", "\r\n", if(origin, do: ["Origin: #{origin}", "\r\n"], else: []), "Upgrade: websocket", "\r\n", "Connection: Upgrade", "\r\n", "Sec-WebSocket-Key: #{handshake}", "\r\n", if(protocols, do: ["Sec-WebSocket-Protocol: #{Enum.join protocols, ", "}", "\r\n"], else: []), if(extensions, do: ["Sec-WebSocket-Extensions: #{Enum.join extensions, ", "}", "\r\n"], else: []), "Sec-WebSocket-Version: 13", "\r\n", "\r\n"]) client |> Socket.packet(:http_bin) { :http_response, _, 101, _ } = client |> Socket.Stream.recv!(global) headers = headers(%{}, client, local) if String.downcase(headers["upgrade"] || "") != "websocket" or String.downcase(headers["connection"] || "") != "upgrade" do client |> Socket.close raise RuntimeError, message: "malformed upgrade response" end if headers["sec-websocket-version"] && headers["sec-websocket-version"] != "13" do client |> Socket.close raise RuntimeError, message: "unsupported version" end if !headers["sec-websocket-accept"] or headers["sec-websocket-accept"] != key(handshake) do client |> Socket.close raise RuntimeError, message: "wrong key response" end client |> Socket.packet!(:raw) %W{socket: client, version: 13, path: path, origin: origin, key: handshake, mask: true} end @doc """ Listens on the default port (80). """ @spec listen :: { :ok, t } | { :error, error } def listen do listen([]) end @doc """ Listens on the given port or with the given options. """ @spec listen(:inet.port_number | Keyword.t) :: { :ok, t } | { :error, error } def listen(port) when port |> is_integer do listen(port, []) end def listen(options) do if options[:secure] do listen(443, options) else listen(80, options) end end @doc """ Listens on the given port with the given options. ## Options `:secure` when true it will use SSL sockets You can also pass TCP or SSL options, depending if you're using secure websockets or not. """ @spec listen(:inet.port_number, Keyword.t) :: { :ok, t } | { :error, error } def listen(port, options) do { local, global } = arguments(options) mod = if local[:secure] do Socket.SSL else Socket.TCP end case mod.listen(port, global) do { :ok, socket } -> { :ok, %W{socket: socket} } error -> error end end @doc """ Listens on the default port (80), raising if an error occurs. """ @spec listen! :: t | no_return def listen! do listen!([]) end @doc """ Listens on the given port or with the given options, raising if an error occurs. """ @spec listen!(:inet.port_number | Keyword.t) :: t | no_return def listen!(port) when port |> is_integer do listen!(port, []) end def listen!(options) do if options[:secure] do listen!(443, options) else listen!(80, options) end end @doc """ Listens on the given port with the given options, raising if an error occurs. ## Options `:secure` when true it will use SSL sockets You can also pass TCP or SSL options, depending if you're using secure websockets or not. """ @spec listen!(:inet.port_number, Keyword.t) :: t | no_return def listen!(port, options) do { local, global } = arguments(options) mod = if local[:secure] do Socket.SSL else Socket.TCP end %W{socket: mod.listen!(port, global)} end @doc """ If you're calling this on a listening socket, it accepts a new client connection. If you're calling this on a client socket, it finalizes the acception handshake, this separation is done because then you can verify the client can connect based on Origin header, path and other things. """ @spec accept(t, Keyword.t) :: { :ok, t } | { :error, error } def accept(%W{key: nil} = self, options \\ []) do try do { :ok, accept!(self, options) } rescue MatchError -> { :error, "malformed handshake" } e in [RuntimeError] -> { :error, e.message } e in [Socket.Error] -> { :error, e.code } end end @doc """ If you're calling this on a listening socket, it accepts a new client connection. If you're calling this on a client socket, it finalizes the acception handshake, this separation is done because then you can verify the client can connect based on Origin header, path and other things. In case of error, it raises. """ @spec accept!(t, Keyword.t) :: t | no_return def accept!(socket, options \\ []) def accept!(%W{socket: socket, key: nil}, options) do { local, global } = arguments(options) client = socket |> Socket.accept!(global) client |> Socket.packet!(:http_bin) path = case client |> Socket.Stream.recv!(global) do { :http_request, :GET, { :abs_path, path }, _ } -> path end headers = headers(%{}, client, local) if headers["upgrade"] != "websocket" and headers["connection"] != "Upgrade" do client |> Socket.close raise RuntimeError, message: "malformed upgrade request" end unless headers["sec-websocket-key"] do client |> Socket.close raise RuntimeError, message: "missing key" end protocols = if p = headers["sec-websocket-protocol"] do String.split(p, ~r/\s*,\s*/) end extensions = if e = headers["sec-websocket-extensions"] do String.split(e, ~r/\s*,\s*/) end client |> Socket.packet!(:raw) %W{socket: client, origin: headers["origin"], path: path, version: 13, key: headers["sec-websocket-key"], protocols: protocols, extensions: extensions, headers: headers} end def accept!(%W{socket: socket, key: key}, options) do { local, _ } = arguments(options) extensions = local[:extensions] protocol = local[:protocol] socket |> Socket.packet!(:raw) socket |> Socket.Stream.send!([ "HTTP/1.1 101 Switching Protocols", "\r\n", "Upgrade: websocket", "\r\n", "Connection: Upgrade", "\r\n", "Sec-WebSocket-Accept: #{key(key)}", "\r\n", "Sec-WebSocket-Version: 13", "\r\n", if(extensions, do: ["Sec-WebSocket-Extensions: ", Enum.join(extensions, ", "), "\r\n"], else: []), if(protocol, do: ["Sec-WebSocket-Protocol: ", protocol, "\r\n"], else: []), "\r\n" ]) end @doc """ Extract websocket specific options from the rest. """ @spec arguments(Keyword.t) :: { Keyword.t, Keyword.t } def arguments(options) do options = Enum.group_by(options, fn { :secure, _ } -> true { :path, _ } -> true { :origin, _ } -> true { :protocol, _ } -> true { :extensions, _ } -> true { :handshake, _ } -> true { :headers, _ } -> true _ -> false end) { Map.get(options, true, []), Map.get(options, false, []) } end @doc """ Return the local address and port. """ @spec local(t) :: { :ok, { :inet.ip_address, :inet.port_number } } | { :error, error } def local(%W{socket: socket}) do socket |> Socket.local end @doc """ Return the local address and port, raising if an error occurs. """ @spec local!(t) :: { :inet.ip_address, :inet.port_number } | no_return def local!(%W{socket: socket}) do socket |> Socket.local! end @doc """ Return the remote address and port. """ @spec remote(t) :: { :ok, { :inet.ip_address, :inet.port_number } } | { :error, error } def remote(%W{socket: socket}) do socket |> Socket.remote end @doc """ Return the remote address and port, raising if an error occurs. """ @spec remote!(t) :: { :inet.ip_address, :inet.port_number } | no_return def remote!(%W{socket: socket}) do socket |> Socket.remote! end @spec mask(binary) :: { integer, binary } defp mask(data) do case :crypto.strong_rand_bytes(4) do << key :: 32 >> -> { key, unmask(key, data) } end end @spec mask(integer, binary) :: { integer, binary } defp mask(key, data) do { key, unmask(key, data) } end @spec unmask(integer, binary) :: binary defp unmask(key, data) do unmask(key, data, <<>>) end # we have to XOR the key with the data iterating over the key when there's # more data, this means we can optimize and do it 4 bytes at a time and then # fallback to the smaller sizes defp unmask(key, << data :: 32, rest :: binary >>, acc) do unmask(key, rest, << acc :: binary, data ^^^ key :: 32 >>) end defp unmask(key, << data :: 24 >>, acc) do << key :: 24, _ :: 8 >> = << key :: 32 >> unmask(key, <<>>, << acc :: binary, data ^^^ key :: 24 >>) end defp unmask(key, << data :: 16 >>, acc) do << key :: 16, _ :: 16 >> = << key :: 32 >> unmask(key, <<>>, << acc :: binary, data ^^^ key :: 16 >>) end defp unmask(key, << data :: 8 >>, acc) do << key :: 8, _ :: 24 >> = << key :: 32 >> unmask(key, <<>>, << acc :: binary, data ^^^ key :: 8 >>) end defp unmask(_, <<>>, acc) do acc end @spec recv(t, boolean, non_neg_integer, Keyword.t) :: { :ok, binary } | { :error, error } defp recv(%W{socket: socket, version: 13}, mask, length, options) do length = cond do length == 127 -> case socket |> Socket.Stream.recv(8, options) do { :ok, << length :: 64 >> } -> length { :error, _ } = error -> error end length == 126 -> case socket |> Socket.Stream.recv(2, options) do { :ok, << length :: 16 >> } -> length { :error, _ } = error -> error end length <= 125 -> length end case length do { :error, _ } = error -> error length -> if mask do case socket |> Socket.Stream.recv(4, options) do { :ok, << key :: 32 >> } -> if length > 0 do case socket |> Socket.Stream.recv(length, options) do { :ok, data } -> { :ok, unmask(key, data) } { :error, _ } = error -> error end else { :ok, "" } end { :error, _ } = error -> error end else if length > 0 do case socket |> Socket.Stream.recv(length, options) do { :ok, data } -> { :ok, data } { :error, _ } = error -> error end else { :ok, "" } end end end end defmacrop on_success(result, options) do quote do case recv(var!(self), var!(mask) == 1, var!(length), unquote(options)) do { :ok, var!(data) } -> { :ok, unquote(result) } { :error, _ } = error -> error end end end @doc """ Receive a packet from the websocket. """ @spec recv(t, Keyword.t) :: { :ok, packet } | { :error, error } def recv(self, options \\ []) def recv(%W{socket: socket, version: 13} = self, options) do case socket |> Socket.Stream.recv(2, options) do # a non fragmented message packet { :ok, << 1 :: 1, 0 :: 3, opcode :: 4, mask :: 1, length :: 7 >> } when known?(opcode) and data?(opcode) -> case on_success({ opcode(opcode), data }, options) do { :ok, { :text, data } } = result -> if String.valid?(data) do result else { :error, :invalid_payload } end { :ok, { :binary, _ } } = result -> result end # beginning of a fragmented packet { :ok, << 0 :: 1, 0 :: 3, opcode :: 4, mask :: 1, length :: 7 >> } when known?(opcode) and not control?(opcode) -> { :fragmented, opcode(opcode), data } |> on_success(options) # a fragmented continuation { :ok, << 0 :: 1, 0 :: 3, 0 :: 4, mask :: 1, length :: 7 >> } -> { :fragmented, :continuation, data } |> on_success(options) # final fragmented packet { :ok, << 1 :: 1, 0 :: 3, 0 :: 4, mask :: 1, length :: 7 >> } -> { :fragmented, :end, data } |> on_success(options) # control packet { :ok, << 1 :: 1, 0 :: 3, opcode :: 4, mask :: 1, length :: 7 >> } when known?(opcode) and control?(opcode) -> case opcode(opcode) do :ping -> { :ping, data } :pong -> { :pong, data } :close -> case data do <<>> -> :close << code :: 16, rest :: binary >> -> { :close, close_code(code), rest } end end |> on_success(options) { :ok, nil } -> # 1006 is reserved for connection closed with no close frame # https://tools.ietf.org/html/rfc6455#section-7.4.1 { :ok, { :close, close_code(1006), nil } } { :ok, _ } -> { :error, :protocol_error } { :error, _ } = error -> error end end @doc """ Receive a packet from the websocket, raising if an error occurs. """ @spec recv!(t, Keyword.t) :: packet | no_return def recv!(self, options \\ []) do case recv(self, options) do { :ok, packet } -> packet { :error, :protocol_error } -> raise RuntimeError, message: "protocol error" { :error, code } -> raise Socket.Error, reason: code end end @spec length(binary) :: binary defp length(data) when byte_size(data) <= 125 do << byte_size(data) :: 7 >> end defp length(data) when byte_size(data) <= 65536 do << 126 :: 7, byte_size(data) :: 16 >> end defp length(data) when byte_size(data) <= 18446744073709551616 do << 127 :: 7, byte_size(data) :: 64 >> end @spec forge(nil | true | integer, binary) :: binary defp forge(nil, data) do << 0 :: 1, length(data) :: bitstring, data :: bitstring >> end defp forge(true, data) do { key, data } = mask(data) << 1 :: 1, length(data) :: bitstring, key :: 32, data :: bitstring >> end defp forge(key, data) do { key, data } = mask(key, data) << 1 :: 1, length(data) :: bitstring, key :: 32, data :: bitstring >> end @doc """ Send a packet to the websocket. """ @spec send(t, packet) :: :ok | { :error, error } @spec send(t, packet, Keyword.t) :: :ok | { :error, error } def send(self, packet, options \\ []) def send(%W{socket: socket, version: 13, mask: mask}, { opcode, data }, options) when opcode != :close do mask = if Keyword.has_key?(options, :mask), do: options[:mask], else: mask socket |> Socket.Stream.send( << 1 :: 1, 0 :: 3, opcode(opcode) :: 4, forge(mask, data) :: binary >>) end def send(%W{socket: socket, version: 13, mask: mask}, { :fragmented, :end, data }, options) do mask = if Keyword.has_key?(options, :mask), do: options[:mask], else: mask socket |> Socket.Stream.send( << 1 :: 1, 0 :: 3, 0 :: 4, forge(mask, data) :: binary >>) end def send(%W{socket: socket, version: 13, mask: mask}, { :fragmented, :continuation, data }, options) do mask = if Keyword.has_key?(options, :mask), do: options[:mask], else: mask socket |> Socket.Stream.send( << 0 :: 1, 0 :: 3, 0 :: 4, forge(mask, data) :: binary >>) end def send(%W{socket: socket, version: 13, mask: mask}, { :fragmented, opcode, data }, options) do mask = if Keyword.has_key?(options, :mask), do: options[:mask], else: mask socket |> Socket.Stream.send( << 0 :: 1, 0 :: 3, opcode(opcode) :: 4, forge(mask, data) :: binary >>) end @doc """ Send a packet to the websocket, raising if an error occurs. """ @spec send!(t, packet) :: :ok | no_return @spec send!(t, packet, Keyword.t) :: :ok | no_return def send!(self, packet, options \\ []) do case send(self, packet, options) do :ok -> :ok { :error, code } -> raise Socket.Error, reason: code end end @doc """ Send a ping request with the optional cookie. """ @spec ping(t) :: :ok | { :error, error } @spec ping(t, binary) :: :ok | { :error, error } def ping(self, cookie \\ :crypto.strong_rand_bytes(32)) do case send(self, { :ping, cookie }) do :ok -> cookie { :error, _ } = error -> error end end @doc """ Send a ping request with the optional cookie, raising if an error occurs. """ @spec ping!(t) :: :ok | no_return @spec ping!(t, binary) :: :ok | no_return def ping!(self, cookie \\ :crypto.strong_rand_bytes(32)) do send!(self, { :ping, cookie }) cookie end @doc """ Send a pong with the given (and received) ping cookie. """ @spec pong(t, binary) :: :ok | { :error, error } def pong(self, cookie) do send(self, { :pong, cookie }) end @doc """ Send a pong with the given (and received) ping cookie, raising if an error occurs. """ @spec pong!(t, binary) :: :ok | no_return def pong!(self, cookie) do send!(self, { :pong, cookie }) end @doc """ Close the socket when a close request has been received. """ @spec close(t) :: :ok | { :error, error } def close(%W{socket: socket, version: 13}) do socket |> Socket.Stream.send( << 1 :: 1, 0 :: 3, opcode(:close) :: 4, forge(nil, <<>>) :: binary >>) end @doc """ Close the socket sending a close request, unless `:wait` is set to `false` it blocks until the close response has been received, and then closes the underlying socket. If :reason? is set to true and the response contains a closing reason and custom data the function returns it as a tuple. """ @spec close(t, atom, Keyword.t) :: :ok | {:ok, atom, binary} | { :error, error } def close(%W{socket: socket, version: 13, mask: mask} = self, reason, options \\ []) do { reason, data } = if is_tuple(reason), do: reason, else: { reason, <<>> } mask = if Keyword.has_key?(options, :mask), do: options[:mask], else: mask socket |> Socket.Stream.send( << 1 :: 1, 0 :: 3, opcode(:close) :: 4, forge(mask, << close_code(reason) :: 16, data :: binary >>) :: binary >>) unless options[:wait] == false do do_close(self, recv(self, options), Keyword.get(options, :reason?, false), options) end end defp do_close(self, { :ok, :close }, _, _) do abort(self) end defp do_close(self, { :ok, { :close, _, _ } }, false, _) do abort(self) end defp do_close(self, { :ok, { :close, reason, data } }, true, _) do abort(self) {:ok, reason, data} end defp do_close(self, { :ok, { :error, _ } }, _, _) do abort(self) end defp do_close(self, _, reason?, options) do do_close(self, recv(self, options), reason?, options) end @doc """ Close the underlying socket, only use when you mean it, normal closure procedure should be preferred. """ @spec abort(t) :: :ok | { :error, error } def abort(%W{socket: socket}) do Socket.Stream.close(socket) end end
28.570681
140
0.558659
734b89ccd8784c143b8b059858b38e3d5de93d92
8,650
ex
Elixir
deps/phoenix_ecto/lib/phoenix_ecto/html.ex
hallebadkapp/rumbl-ms
ae2ef9975658115f8c4d5c49c28d8bde00a74b83
[ "MIT" ]
null
null
null
deps/phoenix_ecto/lib/phoenix_ecto/html.ex
hallebadkapp/rumbl-ms
ae2ef9975658115f8c4d5c49c28d8bde00a74b83
[ "MIT" ]
null
null
null
deps/phoenix_ecto/lib/phoenix_ecto/html.ex
hallebadkapp/rumbl-ms
ae2ef9975658115f8c4d5c49c28d8bde00a74b83
[ "MIT" ]
null
null
null
if Code.ensure_loaded?(Phoenix.HTML) do defimpl Phoenix.HTML.FormData, for: Ecto.Changeset do def to_form(changeset, opts) do %{params: params, data: data} = changeset {name, opts} = Keyword.pop(opts, :as) name = to_string(name || form_for_name(data)) %Phoenix.HTML.Form{ source: changeset, impl: __MODULE__, id: name, name: name, errors: form_for_errors(changeset), data: data, params: params || %{}, hidden: form_for_hidden(data), options: Keyword.put_new(opts, :method, form_for_method(data)) } end def to_form(%{action: parent_action} = source, form, field, opts) do if Keyword.has_key?(opts, :default) do raise ArgumentError, ":default is not supported on inputs_for with changesets. " <> "The default value must be set in the changeset data" end {prepend, opts} = Keyword.pop(opts, :prepend, []) {append, opts} = Keyword.pop(opts, :append, []) {name, opts} = Keyword.pop(opts, :as) {id, opts} = Keyword.pop(opts, :id) id = to_string(id || form.id <> "_#{field}") name = to_string(name || form.name <> "[#{field}]") case find_inputs_for_type!(source, field) do {:one, cast, module} -> changesets = case Map.fetch(source.changes, field) do {:ok, nil} -> [] {:ok, map} when not is_nil(map) -> [validate_map!(map, field)] _ -> [validate_map!(assoc_from_data(source.data, field), field) || module.__struct__] end for changeset <- skip_replaced(changesets) do %{data: data, params: params} = changeset = to_changeset(changeset, parent_action, module, cast) %Phoenix.HTML.Form{ source: changeset, impl: __MODULE__, id: id, name: name, errors: form_for_errors(changeset), data: data, params: params || %{}, hidden: form_for_hidden(data), options: opts } end {:many, cast, module} -> changesets = validate_list!(Map.get(source.changes, field), field) || validate_list!(assoc_from_data(source.data, field), field) || [] changesets = if form.params[Atom.to_string(field)] do changesets else prepend ++ changesets ++ append end changesets = skip_replaced(changesets) for {changeset, index} <- Enum.with_index(changesets) do %{data: data, params: params} = changeset = to_changeset(changeset, parent_action, module, cast) index_string = Integer.to_string(index) %Phoenix.HTML.Form{ source: changeset, impl: __MODULE__, id: id <> "_" <> index_string, name: name <> "[" <> index_string <> "]", index: index, errors: form_for_errors(changeset), data: data, params: params || %{}, hidden: form_for_hidden(data), options: opts } end end end def input_type(changeset, field) do type = Map.get(changeset.types, field, :string) type = if Ecto.Type.primitive?(type), do: type, else: type.type case type do :integer -> :number_input :float -> :number_input :decimal -> :number_input :boolean -> :checkbox :date -> :date_select :time -> :time_select :datetime -> :datetime_select _ -> :text_input end end def input_validations(changeset, field) do [required: field in changeset.required] ++ for({key, validation} <- changeset.validations, key == field, attr <- validation_to_attrs(validation, field, changeset), do: attr) end defp assoc_from_data(data, field) do assoc_from_data(data, Map.fetch!(data, field), field) end defp assoc_from_data(%{__meta__: %{state: :built}}, %Ecto.Association.NotLoaded{}, _field) do nil end defp assoc_from_data(%{__struct__: struct}, %Ecto.Association.NotLoaded{}, field) do raise ArgumentError, "using inputs_for for association `#{field}` " <> "from `#{inspect struct}` but it was not loaded. Please preload your " <> "associations before using them in inputs_for" end defp assoc_from_data(_data, value, _field) do value end defp skip_replaced(changesets) do Enum.reject(changesets, fn %Ecto.Changeset{action: :replace} -> true _ -> false end) end defp validation_to_attrs({:length, opts}, _field, _changeset) do max = if val = Keyword.get(opts, :max) do [maxlength: val] else [] end min = if val = Keyword.get(opts, :min) do [minlength: val] else [] end max ++ min end defp validation_to_attrs({:number, opts}, field, changeset) do type = Map.get(changeset.types, field, :integer) step_for(type) ++ min_for(type, opts) ++ max_for(type, opts) end defp validation_to_attrs(_validation, _field, _changeset) do [] end defp step_for(:integer), do: [step: 1] defp step_for(_other), do: [step: "any"] defp max_for(type, opts) do cond do max = type == :integer && Keyword.get(opts, :less_than) -> [max: max - 1] max = Keyword.get(opts, :less_than_or_equal_to) -> [max: max] true -> [] end end defp min_for(type, opts) do cond do min = type == :integer && Keyword.get(opts, :greater_than) -> [min: min + 1] min = Keyword.get(opts, :greater_than_or_equal_to) -> [min: min] true -> [] end end defp find_inputs_for_type!(changeset, field) do case Map.fetch(changeset.types, field) do {:ok, {tag, %{cardinality: cardinality, on_cast: cast, related: module}}} when tag in [:embed, :assoc] -> {cardinality, cast, module} _ -> raise ArgumentError, "could not generate inputs for #{inspect field} from #{inspect changeset.data.__struct__}. " <> "Check the field exists and it is one of embeds_one, embeds_many, has_one, " <> "has_many, belongs_to or many_to_many" end end defp to_changeset(%Ecto.Changeset{} = changeset, parent_action, _module, _cast), do: apply_action(changeset, parent_action) defp to_changeset(%{} = data, parent_action, _module, cast) when is_function(cast, 2), do: apply_action(cast.(data, %{}), parent_action) defp to_changeset(%{} = data, parent_action, _module, nil), do: apply_action(Ecto.Changeset.change(data), parent_action) # If the parent changeset had no action, we need to remove the action # from children changeset so we ignore all errors accordingly. defp apply_action(changeset, nil), do: %{changeset | action: nil} defp apply_action(changeset, _action), do: changeset defp validate_list!(value, _what) when is_list(value) or is_nil(value), do: value defp validate_list!(value, what) do raise ArgumentError, "expected #{what} to be a list, got: #{inspect value}" end defp validate_map!(value, _what) when is_map(value) or is_nil(value), do: value defp validate_map!(value, what) do raise ArgumentError, "expected #{what} to be a map/struct, got: #{inspect value}" end defp form_for_errors(%{action: nil}), do: [] defp form_for_errors(%{errors: errors}), do: errors defp form_for_hidden(%{__struct__: _} = data) do # Since they are primary keys, we should ignore nil values. for {k, v} <- Ecto.primary_key(data), v != nil, do: {k, v} end defp form_for_hidden(_), do: [] defp form_for_name(%{__struct__: module}) do module |> Module.split() |> List.last() |> Macro.underscore() end defp form_for_name(_) do raise ArgumentError, "non-struct data in changeset requires the :as option to be given" end defp form_for_method(%{__meta__: %{state: :loaded}}), do: "put" defp form_for_method(_), do: "post" end defimpl Phoenix.HTML.Safe, for: [Decimal, Ecto.Time, Ecto.Date, Ecto.DateTime] do def to_iodata(t) do @for.to_string(t) end end end
33.269231
113
0.578844
734b8a8b8ad60465d7205e598569ab0a42057a8f
1,381
ex
Elixir
lib/phx_chirp_web/router.ex
dannyh79/15m_phx_twitter
b8639c12e8f01eb46dab4f82600854e13fa1ecdc
[ "MIT" ]
null
null
null
lib/phx_chirp_web/router.ex
dannyh79/15m_phx_twitter
b8639c12e8f01eb46dab4f82600854e13fa1ecdc
[ "MIT" ]
10
2020-05-19T14:13:34.000Z
2021-06-13T13:16:43.000Z
lib/phx_chirp_web/router.ex
dannyh79/15m_phx_twitter
b8639c12e8f01eb46dab4f82600854e13fa1ecdc
[ "MIT" ]
1
2020-05-19T13:37:01.000Z
2020-05-19T13:37:01.000Z
defmodule PhxChirpWeb.Router do use PhxChirpWeb, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_live_flash plug :put_root_layout, {PhxChirpWeb.LayoutView, :root} plug :protect_from_forgery plug :put_secure_browser_headers end pipeline :api do plug :accepts, ["json"] end scope "/", PhxChirpWeb do pipe_through :browser live "/", PostLive.Index, :index live "/posts", PostLive.Index, :index live "/posts/new", PostLive.Index, :new live "/posts/:id/edit", PostLive.Index, :edit live "/posts/:id", PostLive.Show, :show live "/posts/:id/show/edit", PostLive.Show, :edit end # Other scopes may use custom stacks. # scope "/api", PhxChirpWeb do # pipe_through :api # end # Enables LiveDashboard only for development # # If you want to use the LiveDashboard in production, you should put # it behind authentication and allow only admins to access it. # If your application does not have an admins-only section yet, # you can use Plug.BasicAuth to set up some basic authentication # as long as you are also using SSL (which you should anyway). if Mix.env() in [:dev, :test] do import Phoenix.LiveDashboard.Router scope "/" do pipe_through :browser live_dashboard "/dashboard", metrics: PhxChirpWeb.Telemetry end end end
27.078431
70
0.690804
734b93fed4222babfd9d985c04dcf4e08da9a228
2,236
ex
Elixir
clients/content/lib/google_api/content/v2/model/shipping_settings.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/shipping_settings.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/content/lib/google_api/content/v2/model/shipping_settings.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Content.V2.Model.ShippingSettings do @moduledoc """ The merchant account's shipping settings. All methods except getsupportedcarriers and getsupportedholidays require the admin role. ## Attributes * `accountId` (*type:* `String.t`, *default:* `nil`) - The ID of the account to which these account shipping settings belong. Ignored upon update, always present in get request responses. * `postalCodeGroups` (*type:* `list(GoogleApi.Content.V2.Model.PostalCodeGroup.t)`, *default:* `nil`) - A list of postal code groups that can be referred to in `services`. Optional. * `services` (*type:* `list(GoogleApi.Content.V2.Model.Service.t)`, *default:* `nil`) - The target account's list of services. Optional. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :accountId => String.t(), :postalCodeGroups => list(GoogleApi.Content.V2.Model.PostalCodeGroup.t()), :services => list(GoogleApi.Content.V2.Model.Service.t()) } field(:accountId) field(:postalCodeGroups, as: GoogleApi.Content.V2.Model.PostalCodeGroup, type: :list) field(:services, as: GoogleApi.Content.V2.Model.Service, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.ShippingSettings do def decode(value, options) do GoogleApi.Content.V2.Model.ShippingSettings.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.ShippingSettings do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
42.188679
191
0.737478
734b9fd397771468e2a6c57a3603876acf9661fe
454
exs
Elixir
deps/poolboy/package.exs
mafei198/game_server
df4a2975fe53f0dc768e1a9b5a4e6e955263f90d
[ "MIT" ]
24
2015-01-25T16:31:03.000Z
2020-03-15T12:16:26.000Z
package.exs
soundrop/poolboy
5223d6489538150025abb43569b934a54580b22e
[ "Apache-2.0", "Unlicense" ]
1
2015-07-02T07:42:42.000Z
2015-07-10T16:36:26.000Z
package.exs
soundrop/poolboy
5223d6489538150025abb43569b934a54580b22e
[ "Apache-2.0", "Unlicense" ]
10
2015-01-25T16:32:09.000Z
2021-06-23T06:24:40.000Z
version = String.strip(File.read!("VERSION")) Expm.Package.new( name: "poolboy", description: "A hunky Erlang worker pool factory", homepage: "http://devintorr.es/poolboy", version: version, keywords: %w(Erlang library pool pools pooler), maintainers: [[name: "Devin Torres", email: "[email protected]"], [name: "Andrew Thompson", email: "[email protected]"]], repositories: [[github: "devinus/poolboy", tag: version]] )
34.923077
72
0.676211
734c11c64537714b3e858ef83e6e6129909333e7
775
ex
Elixir
test/support/channel_case.ex
s6o/elmverse
3e5c732a09f5e7f456286487e84d711672239529
[ "MIT" ]
null
null
null
test/support/channel_case.ex
s6o/elmverse
3e5c732a09f5e7f456286487e84d711672239529
[ "MIT" ]
3
2021-03-09T01:27:03.000Z
2022-02-10T17:08:49.000Z
test/support/channel_case.ex
s6o/elmverse
3e5c732a09f5e7f456286487e84d711672239529
[ "MIT" ]
null
null
null
defmodule ElmverseWeb.ChannelCase do @moduledoc """ This module defines the test case to be used by channel tests. Such tests rely on `Phoenix.ChannelTest` and also import other functionality to make it easier to build common data structures and query the data layer. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with channels use Phoenix.ChannelTest # The default endpoint for testing @endpoint ElmverseWeb.Endpoint end end setup _tags do :ok end end
24.21875
59
0.727742
734c367e6cd7f8745a6ebeade6184a9f1b543fa0
767
exs
Elixir
cli_client/krcli/test/board_test.exs
t6n/Komorebi
70b0b864af3d25dda9bf42482cf3648e3d0c2e7e
[ "MIT" ]
2
2016-07-12T09:30:41.000Z
2017-01-15T10:25:02.000Z
cli_client/krcli/test/board_test.exs
t6n/Komorebi
70b0b864af3d25dda9bf42482cf3648e3d0c2e7e
[ "MIT" ]
35
2016-07-11T09:55:36.000Z
2018-08-30T07:57:28.000Z
cli_client/krcli/test/board_test.exs
t6n/Komorebi
70b0b864af3d25dda9bf42482cf3648e3d0c2e7e
[ "MIT" ]
4
2016-06-30T06:59:51.000Z
2018-04-26T08:29:46.000Z
defmodule BoardTest do use ExUnit.Case, async: true doctest Krcli.Board test "Should create board from json" do json = File.read("test_data/board_test.json") assert {:ok, board} = Krcli.Board.parse(json) assert board.name == "The ultimate board" assert length(board.columns) == 3 assert board.id == 5 end test "should find all boards by name" do match_test = (fn(x) -> x.name == "bcd" end) not_match_test = (fn({:error, message}) -> message == "could not find Board" end) boards = [%Krcli.Board{name: "abc"}, %Krcli.Board{name: "bcd"}] assert Krcli.Board.by_name("bcd", {:ok, boards}) |> Util.unwrap |> match_test.() assert Krcli.Board.by_name("def", {:ok, boards}) |> not_match_test.() end end
31.958333
73
0.636245
734c3bee8a0043b1208770a40f91d5a0af9b5958
1,930
exs
Elixir
mix.exs
underhilllabs/big_snips
7f1b59d2be45fe6a488d8e3ce7842e7cc867d676
[ "MIT" ]
3
2016-12-20T17:16:39.000Z
2017-02-22T11:06:56.000Z
mix.exs
underhilllabs/big_snips
7f1b59d2be45fe6a488d8e3ce7842e7cc867d676
[ "MIT" ]
1
2017-05-31T16:32:41.000Z
2017-05-31T16:32:41.000Z
mix.exs
underhilllabs/big_snips
7f1b59d2be45fe6a488d8e3ce7842e7cc867d676
[ "MIT" ]
null
null
null
defmodule BigSnips.Mixfile do use Mix.Project def project do [app: :big_snips, version: "0.0.1", elixir: "~> 1.2", elixirc_paths: elixirc_paths(Mix.env), compilers: [:phoenix, :gettext] ++ Mix.compilers, build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, aliases: aliases(), deps: deps()] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [mod: {BigSnips, []}, applications: [:phoenix, :phoenix_pubsub, :phoenix_html, :cowboy, :logger, :gettext, :earmark, :scrivener, :scrivener_ecto, :scrivener_html, :comeonin, :phoenix_ecto, :mariaex]] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "web", "test/support"] defp elixirc_paths(_), do: ["lib", "web"] # Specifies your project dependencies. # # Type `mix help deps` for examples and options. defp deps do [{:phoenix, "~> 1.2.1"}, {:phoenix_pubsub, "~> 1.0"}, {:phoenix_ecto, "~> 3.0"}, {:mariaex, ">= 0.0.0"}, {:phoenix_html, "~> 2.6"}, {:phoenix_live_reload, "~> 1.0", only: :dev}, {:gettext, "~> 0.11"}, {:guardian, "~> 0.13.0"}, {:earmark, "~> 1.0.0"}, {:distillery, "~> 2.0"}, {:comeonin, "~> 2.6"}, {:scrivener, "~> 2.0"}, {:scrivener_html, "~> 1.1"}, {:scrivener_ecto, "~> 1.0"}, {:cowboy, "~> 1.0"}] end # Aliases are shortcuts or tasks specific to the current project. # For example, to create, migrate and run the seeds file at once: # # $ mix ecto.setup # # See the documentation for `Mix` for more info on aliases. defp aliases do ["ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], "test": ["ecto.create --quiet", "ecto.migrate", "test"]] end end
31.129032
102
0.586528
734c5da3c1f9e334b253dda0c4d05a834170ab5b
8,813
ex
Elixir
lib/ecto/query/builder/join.ex
zachahn/ecto
8119ad877f7caa837912647a014f4a63a951dba0
[ "Apache-2.0" ]
null
null
null
lib/ecto/query/builder/join.ex
zachahn/ecto
8119ad877f7caa837912647a014f4a63a951dba0
[ "Apache-2.0" ]
null
null
null
lib/ecto/query/builder/join.ex
zachahn/ecto
8119ad877f7caa837912647a014f4a63a951dba0
[ "Apache-2.0" ]
null
null
null
import Kernel, except: [apply: 2] defmodule Ecto.Query.Builder.Join do @moduledoc false alias Ecto.Query.Builder alias Ecto.Query.{JoinExpr, QueryExpr} @doc """ Escapes a join expression (not including the `on` expression). It returns a tuple containing the binds, the on expression (if available) and the association expression. ## Examples iex> escape(quote(do: x in "foo"), [], __ENV__) {:x, {"foo", nil}, nil, %{}} iex> escape(quote(do: "foo"), [], __ENV__) {:_, {"foo", nil}, nil, %{}} iex> escape(quote(do: x in Sample), [], __ENV__) {:x, {nil, {:__aliases__, [alias: false], [:Sample]}}, nil, %{}} iex> escape(quote(do: x in {"foo", Sample}), [], __ENV__) {:x, {"foo", {:__aliases__, [alias: false], [:Sample]}}, nil, %{}} iex> escape(quote(do: x in {"foo", :sample}), [], __ENV__) {:x, {"foo", :sample}, nil, %{}} iex> escape(quote(do: c in assoc(p, :comments)), [p: 0], __ENV__) {:c, nil, {0, :comments}, %{}} iex> escape(quote(do: x in fragment("foo")), [], __ENV__) {:x, {:{}, [], [:fragment, [], [raw: "foo"]]}, nil, %{}} """ @spec escape(Macro.t, Keyword.t, Macro.Env.t) :: {[atom], Macro.t | nil, Macro.t | nil, %{}} def escape({:in, _, [{var, _, context}, expr]}, vars, env) when is_atom(var) and is_atom(context) do {_, expr, assoc, params} = escape(expr, vars, env) {var, expr, assoc, params} end def escape({:subquery, _, [expr]}, _vars, _env) do {:_, quote(do: Ecto.Query.subquery(unquote(expr))), nil, %{}} end def escape({:subquery, _, [expr, opts]}, _vars, _env) do {:_, quote(do: Ecto.Query.subquery(unquote(expr), unquote(opts))), nil, %{}} end def escape({:fragment, _, [_ | _]} = expr, vars, env) do {expr, {params, :acc}} = Builder.escape(expr, :any, {%{}, :acc}, vars, env) {:_, expr, nil, params} end def escape({:unsafe_fragment, _, [_ | _]} = expr, vars, env) do {expr, {params, :acc}} = Builder.escape(expr, :any, {%{}, :acc}, vars, env) {:_, expr, nil, params} end def escape({:__aliases__, _, _} = module, _vars, _env) do {:_, {nil, module}, nil, %{}} end def escape(string, _vars, _env) when is_binary(string) do {:_, {string, nil}, nil, %{}} end def escape({string, {:__aliases__, _, _} = module}, _vars, _env) when is_binary(string) do {:_, {string, module}, nil, %{}} end def escape({string, atom}, _vars, _env) when is_binary(string) and is_atom(atom) do {:_, {string, atom}, nil, %{}} end def escape({:assoc, _, [{var, _, context}, field]}, vars, _env) when is_atom(var) and is_atom(context) do ensure_field!(field) var = Builder.find_var!(var, vars) field = Builder.quoted_field!(field) {:_, nil, {var, field}, %{}} end def escape({:^, _, [expr]}, _vars, _env) do {:_, quote(do: Ecto.Query.Builder.Join.join!(unquote(expr))), nil, %{}} end def escape(join, vars, env) do case Macro.expand(join, env) do ^join -> Builder.error! "malformed join `#{Macro.to_string(join)}` in query expression" join -> escape(join, vars, env) end end @doc """ Called at runtime to check dynamic joins. """ def join!(expr) when is_atom(expr), do: {nil, expr} def join!(expr) when is_binary(expr), do: {expr, nil} def join!({source, module}) when is_binary(source) and is_atom(module), do: {source, module} def join!(expr), do: Ecto.Queryable.to_query(expr) @doc """ Builds a quoted expression. The quoted expression should evaluate to a query at runtime. If possible, it does all calculations at compile time to avoid runtime work. """ @spec build(Macro.t, atom, [Macro.t], Macro.t, Macro.t, Macro.t, atom, Macro.Env.t) :: {Macro.t, Keyword.t, non_neg_integer | nil} def build(query, qual, binding, expr, count_bind, on, as, env) do if not is_atom(as) do Builder.error! "`as` must be a compile time atom, got: `#{Macro.to_string(as)}`" end {query, binding} = Builder.escape_binding(query, binding, env) {join_bind, join_source, join_assoc, join_params} = escape(expr, binding, env) join_params = Builder.escape_params(join_params) qual = validate_qual(qual) validate_bind(join_bind, binding) {count_bind, query} = if join_bind != :_ and !count_bind do # If count_bind is not available, # we need to compute the amount of binds at runtime query = quote do query = Ecto.Queryable.to_query(unquote(query)) join_count = Builder.count_binds(query) query end {quote(do: join_count), query} else {count_bind, query} end binding = binding ++ [{join_bind, count_bind}] next_bind = if is_integer(count_bind) do count_bind + 1 else quote(do: unquote(count_bind) + 1) end query = build_on(on || true, as, query, binding, count_bind, qual, join_source, join_assoc, join_params, env) {query, binding, next_bind} end def build_on({:^, _, [var]}, as, query, _binding, count_bind, join_qual, join_source, join_assoc, join_params, env) do quote do query = unquote(query) Ecto.Query.Builder.Join.join!(query, unquote(var), unquote(as), unquote(count_bind), unquote(join_qual), unquote(join_source), unquote(join_assoc), unquote(join_params), unquote(env.file), unquote(env.line)) end end def build_on(on, as, query, binding, count_bind, join_qual, join_source, join_assoc, join_params, env) do {on_expr, on_params} = Ecto.Query.Builder.Filter.escape(:on, on, count_bind, binding, env) on_params = Builder.escape_params(on_params) join = quote do %JoinExpr{qual: unquote(join_qual), source: unquote(join_source), assoc: unquote(join_assoc), as: unquote(as), file: unquote(env.file), line: unquote(env.line), params: unquote(join_params), on: %QueryExpr{expr: unquote(on_expr), params: unquote(on_params), line: unquote(env.line), file: unquote(env.file)}} end Builder.apply_query(query, __MODULE__, [join, as, count_bind], env) end @doc """ Applies the join expression to the query. """ def apply(%Ecto.Query{joins: joins, aliases: aliases} = query, expr, as, count_bind) do aliases = apply_aliases(aliases, as, count_bind) %{query | joins: joins ++ [expr], aliases: aliases} end def apply(query, expr, as, count_bind) do apply(Ecto.Queryable.to_query(query), expr, as, count_bind) end def apply_aliases(aliases, nil, _), do: aliases def apply_aliases(aliases = %{}, name, join_count) when is_atom(name) and is_integer(join_count) do if Map.has_key?(aliases, name) do Builder.error! "alias `#{inspect name}` already exists" else Map.put(aliases, name, join_count) end end def apply_aliases(aliases, name, join_count) do quote do Ecto.Query.Builder.Join.apply_aliases(unquote(Macro.escape(aliases)), unquote(name), unquote(join_count)) end end @doc """ Called at runtime to build a join. """ def join!(query, expr, as, count_bind, join_qual, join_source, join_assoc, join_params, file, line) do {on_expr, on_params, on_file, on_line} = Ecto.Query.Builder.Filter.filter!(:on, query, expr, count_bind, file, line) join = %JoinExpr{qual: join_qual, source: join_source, assoc: join_assoc, as: as, file: file, line: line, params: join_params, on: %QueryExpr{expr: on_expr, params: on_params, line: on_line, file: on_file}} apply(query, join, as, count_bind) end defp validate_qual(qual) when is_atom(qual) do qual!(qual) end defp validate_qual(qual) do quote(do: Ecto.Query.Builder.Join.qual!(unquote(qual))) end defp validate_bind(bind, all) do if bind != :_ and bind in all do Builder.error! "variable `#{bind}` is already defined in query" end end @qualifiers [:inner, :inner_lateral, :left, :left_lateral, :right, :full, :cross] @doc """ Called at runtime to check dynamic qualifier. """ def qual!(qual) when qual in @qualifiers, do: qual def qual!(qual) do raise ArgumentError, "invalid join qualifier `#{inspect qual}`, accepted qualifiers are: " <> Enum.map_join(@qualifiers, ", ", &"`#{inspect &1}`") end defp ensure_field!({var, _, _}) when var != :^ do Builder.error! "you passed the variable `#{var}` to `assoc/2`. Did you mean to pass the atom `:#{var}?`" end defp ensure_field!(_), do: true end
33.766284
111
0.611823
734c7b3dd524bc01d34b55f0faf3edf4aeca7cc2
902
ex
Elixir
lib/zoho/accounts.ex
wyattbenno777/Zoho-elixir
6be80727fc2dd0f6b4f185e4047ca61e27e20b5e
[ "MIT" ]
null
null
null
lib/zoho/accounts.ex
wyattbenno777/Zoho-elixir
6be80727fc2dd0f6b4f185e4047ca61e27e20b5e
[ "MIT" ]
null
null
null
lib/zoho/accounts.ex
wyattbenno777/Zoho-elixir
6be80727fc2dd0f6b4f185e4047ca61e27e20b5e
[ "MIT" ]
null
null
null
defmodule Zoho.Accounts do @loc "Accounts" @resource Zoho.Account use Zoho.Resource #get example map for Accounts post def get_example do example = %{"Account Name": "Zillum", "Website": "www.zillum.com", "Employees": "200", "Ownership": "Private", "Industry": "[email protected]", "Fax": "99999", "Annual Revenue": "2000000"} example end #clean up strange data format def get_clean do data = Zoho.Accounts.get top = data.response["result"]["Accounts"]["row"] if is_list top do data2 = top data3 = Enum.map(data2, fn(y) -> Enum.map(y["FL"], fn(x) -> %{x["val"] => x["content"]} end) end) Enum.map(data3, fn(y) -> Enum.reduce(y, %{}, fn (map, acc) -> Map.merge(acc, map) end) end) else data2 = top["FL"] Enum.map(data2, fn(x) -> %{x["val"] => x["content"]} end) end end end
23.128205
104
0.570953
734cd8466d73892d3c3b88c4573ee7d524ddb2d9
468
exs
Elixir
test/livebook_test.exs
kianmeng/livebook
8fe8d27d3d46b64d22126d1b97157330b87e611c
[ "Apache-2.0" ]
1,846
2021-04-13T14:46:36.000Z
2021-07-14T20:37:40.000Z
test/livebook_test.exs
kianmeng/livebook
8fe8d27d3d46b64d22126d1b97157330b87e611c
[ "Apache-2.0" ]
411
2021-07-15T07:41:54.000Z
2022-03-31T21:34:22.000Z
test/livebook_test.exs
kianmeng/livebook
8fe8d27d3d46b64d22126d1b97157330b87e611c
[ "Apache-2.0" ]
130
2021-04-13T15:43:55.000Z
2021-07-12T16:57:46.000Z
defmodule LivebookTest do use ExUnit.Case, async: true test "live_markdown_to_elixir/1" do markdown = """ # Lists ## Introduction Let's generate a list of numbers: ```elixir Enum.to_list(1..10) ``` """ assert Livebook.live_markdown_to_elixir(markdown) == """ # Title: Lists # ── Introduction ── # Let's generate a list of numbers: Enum.to_list(1..10) """ end end
16.714286
60
0.553419
734cee7fd4e6a717c6eef358e7722c54abb75844
1,468
ex
Elixir
lib/db_connection/query.ex
lukebakken/db_connection
aa53f2d9c78aa6b5f6a9c0615459e97ec89f0c32
[ "Apache-2.0" ]
227
2016-06-16T13:56:02.000Z
2022-03-09T23:03:58.000Z
lib/db_connection/query.ex
lukebakken/db_connection
aa53f2d9c78aa6b5f6a9c0615459e97ec89f0c32
[ "Apache-2.0" ]
198
2016-06-20T08:08:15.000Z
2022-03-06T17:54:37.000Z
deps/db_connection/lib/db_connection/query.ex
adrianomota/blog
ef3b2d2ed54f038368ead8234d76c18983caa75b
[ "MIT" ]
110
2016-06-20T03:50:39.000Z
2022-03-03T20:53:01.000Z
defprotocol DBConnection.Query do @moduledoc """ The `DBConnection.Query` protocol is responsible for preparing and encoding queries. All `DBConnection.Query` functions are executed in the caller process which means it's safe to, for example, raise exceptions or do blocking calls as they won't affect the connection process. """ @doc """ Parse a query. This function is called to parse a query term before it is prepared using a connection callback module. See `DBConnection.prepare/3`. """ @spec parse(any, Keyword.t()) :: any def parse(query, opts) @doc """ Describe a query. This function is called to describe a query after it is prepared using a connection callback module. See `DBConnection.prepare/3`. """ @spec describe(any, Keyword.t()) :: any def describe(query, opts) @doc """ Encode parameters using a query. This function is called to encode a query before it is executed using a connection callback module. If this function raises `DBConnection.EncodeError`, then the query is prepared once again. See `DBConnection.execute/3`. """ @spec encode(any, any, Keyword.t()) :: any def encode(query, params, opts) @doc """ Decode a result using a query. This function is called to decode a result after it is returned by a connection callback module. See `DBConnection.execute/3`. """ @spec decode(any, any, Keyword.t()) :: any def decode(query, result, opts) end
25.310345
77
0.707766
734cfba63045aa4221c0944e086b2f26497ce21d
423
ex
Elixir
lib/hound/helpers.ex
knewter/hound
49ca7d71f7fb0d9a9de14afa86ca1a1fe5ae1278
[ "MIT" ]
1
2015-07-08T04:32:02.000Z
2015-07-08T04:32:02.000Z
lib/hound/helpers.ex
knewter/hound
49ca7d71f7fb0d9a9de14afa86ca1a1fe5ae1278
[ "MIT" ]
null
null
null
lib/hound/helpers.ex
knewter/hound
49ca7d71f7fb0d9a9de14afa86ca1a1fe5ae1278
[ "MIT" ]
null
null
null
defmodule Hound.Helpers do @moduledoc false defmacro __using__([]) do {:ok, driver} = Hound.get_driver_info quote do use unquote(driver[:type]) import unquote(__MODULE__) import Hound end end defmacro hound_session do quote do setup do Hound.start_session :ok end teardown do Hound.end_session :ok end end end end
14.586207
41
0.593381
734d04e37fb8580efe85053e60dd69d18fd630f5
2,222
ex
Elixir
web/controllers/attraction_controller.ex
nelsonblaha/yonder
6ab708d742e967dec63146b27b30e570ae21911f
[ "CC0-1.0" ]
null
null
null
web/controllers/attraction_controller.ex
nelsonblaha/yonder
6ab708d742e967dec63146b27b30e570ae21911f
[ "CC0-1.0" ]
null
null
null
web/controllers/attraction_controller.ex
nelsonblaha/yonder
6ab708d742e967dec63146b27b30e570ae21911f
[ "CC0-1.0" ]
null
null
null
defmodule Yonder.AttractionController do use Yonder.Web, :controller alias Yonder.Attraction plug :scrub_params, "attraction" when action in [:create, :update] def index(conn, _params) do attractions = Repo.all(Attraction) render(conn, "index.html", attractions: attractions) end def map(conn, _params) do attractions = Repo.all(Attraction) render(conn, "mapindex.html", attractions: attractions) end def new(conn, _params) do changeset = Attraction.changeset(%Attraction{}) render(conn, "new.html", changeset: changeset) end def create(conn, %{"attraction" => attraction_params}) do changeset = Attraction.changeset(%Attraction{}, attraction_params) case Repo.insert(changeset) do {:ok, _attraction} -> conn |> put_flash(:info, "Attraction created successfully.") |> redirect(to: attraction_path(conn, :index)) {:error, changeset} -> render(conn, "new.html", changeset: changeset) end end def show(conn, %{"id" => id}) do attraction = Repo.get!(Attraction, id) render(conn, "show.html", attraction: attraction) end def edit(conn, %{"id" => id}) do attraction = Repo.get!(Attraction, id) changeset = Attraction.changeset(attraction) render(conn, "edit.html", attraction: attraction, changeset: changeset) end def update(conn, %{"id" => id, "attraction" => attraction_params}) do attraction = Repo.get!(Attraction, id) changeset = Attraction.changeset(attraction, attraction_params) case Repo.update(changeset) do {:ok, attraction} -> conn |> put_flash(:info, "Attraction updated successfully.") |> redirect(to: attraction_path(conn, :show, attraction)) {:error, changeset} -> render(conn, "edit.html", attraction: attraction, changeset: changeset) end end def delete(conn, %{"id" => id}) do attraction = Repo.get!(Attraction, id) # Here we use delete! (with a bang) because we expect # it to always work (and if it does not, it will raise). Repo.delete!(attraction) conn |> put_flash(:info, "Attraction deleted successfully.") |> redirect(to: attraction_path(conn, :index)) end end
30.438356
79
0.664266
734d147adbecd02e85c6c8390d8a8f504d220c7f
11,779
exs
Elixir
apps/admin_api/test/admin_api/v1/controllers/provider_auth/transaction_request_controller_test.exs
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
null
null
null
apps/admin_api/test/admin_api/v1/controllers/provider_auth/transaction_request_controller_test.exs
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
null
null
null
apps/admin_api/test/admin_api/v1/controllers/provider_auth/transaction_request_controller_test.exs
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
null
null
null
defmodule AdminAPI.V1.ProviderAuth.TransactionRequestControllerTest do use AdminAPI.ConnCase, async: true alias EWalletDB.{Repo, TransactionRequest, User, Account, AccountUser} alias EWallet.Web.{Date, V1.TokenSerializer, V1.UserSerializer} describe "/transaction_request.all" do setup do user = get_test_user() account = Account.get_master_account() {:ok, _} = AccountUser.link(account.uuid, user.uuid) tr_1 = insert(:transaction_request, user_uuid: user.uuid, status: "valid") tr_2 = insert(:transaction_request, account_uuid: account.uuid, status: "valid") tr_3 = insert(:transaction_request, account_uuid: account.uuid, status: "expired") %{ user: user, tr_1: tr_1, tr_2: tr_2, tr_3: tr_3 } end test "returns all the transaction_requests", meta do response = provider_request("/transaction_request.all", %{ "sort_by" => "created", "sort_dir" => "asc" }) transfers = [ meta.tr_1, meta.tr_2, meta.tr_3 ] assert length(response["data"]["data"]) == length(transfers) # All transfers made during setup should exist in the response assert Enum.all?(transfers, fn transfer -> Enum.any?(response["data"]["data"], fn data -> transfer.id == data["id"] end) end) end test "returns all the transaction_requests for a specific status", meta do response = provider_request("/transaction_request.all", %{ "sort_by" => "created_at", "sort_dir" => "asc", "search_terms" => %{ "status" => "valid" } }) assert response["data"]["data"] |> length() == 2 assert Enum.map(response["data"]["data"], fn t -> t["id"] end) == [ meta.tr_1.id, meta.tr_2.id ] end test "returns all transaction_requests filtered", meta do response = provider_request("/transaction_request.all", %{ "sort_by" => "created_at", "sort_dir" => "asc", "search_term" => "valid" }) assert response["data"]["data"] |> length() == 2 assert Enum.map(response["data"]["data"], fn t -> t["id"] end) == [ meta.tr_1.id, meta.tr_2.id ] end test "returns all transaction_requests sorted and paginated", meta do response = provider_request("/transaction_request.all", %{ "sort_by" => "created_at", "sort_dir" => "asc", "per_page" => 2, "page" => 1 }) assert response["data"]["data"] |> length() == 2 transaction_1 = Enum.at(response["data"]["data"], 0) transaction_2 = Enum.at(response["data"]["data"], 1) assert transaction_2["created_at"] > transaction_1["created_at"] assert Enum.map(response["data"]["data"], fn t -> t["id"] end) == [ meta.tr_1.id, meta.tr_2.id ] end end describe "/transaction_request.create" do test "creates a transaction request with all the params" do account = Account.get_master_account() user = get_test_user() token = insert(:token) wallet = User.get_primary_wallet(user) {:ok, _} = AccountUser.link(account.uuid, user.uuid) response = provider_request("/transaction_request.create", %{ type: "send", token_id: token.id, correlation_id: "123", amount: 1_000, address: wallet.address }) request = TransactionRequest |> Repo.all() |> Enum.at(0) assert response == %{ "success" => true, "version" => "1", "data" => %{ "object" => "transaction_request", "amount" => 1_000, "address" => wallet.address, "correlation_id" => "123", "id" => request.id, "formatted_id" => request.id, "socket_topic" => "transaction_request:#{request.id}", "token_id" => token.id, "token" => token |> TokenSerializer.serialize() |> stringify_keys(), "type" => "send", "status" => "valid", "user_id" => user.id, "user" => user |> UserSerializer.serialize() |> stringify_keys(), "account_id" => nil, "account" => nil, "exchange_account" => nil, "exchange_account_id" => nil, "exchange_wallet" => nil, "exchange_wallet_address" => nil, "allow_amount_override" => true, "require_confirmation" => false, "consumption_lifetime" => nil, "encrypted_metadata" => %{}, "expiration_date" => nil, "expiration_reason" => nil, "expired_at" => nil, "max_consumptions" => nil, "current_consumptions_count" => 0, "max_consumptions_per_user" => nil, "metadata" => %{}, "created_at" => Date.to_iso8601(request.inserted_at), "updated_at" => Date.to_iso8601(request.updated_at) } } end test "creates a transaction request with the minimum params" do account = Account.get_master_account() user = get_test_user() token = insert(:token) wallet = User.get_primary_wallet(user) {:ok, _} = AccountUser.link(account.uuid, user.uuid) response = provider_request("/transaction_request.create", %{ type: "send", token_id: token.id, correlation_id: nil, amount: nil, address: wallet.address }) request = TransactionRequest |> Repo.all() |> Enum.at(0) assert response == %{ "success" => true, "version" => "1", "data" => %{ "object" => "transaction_request", "amount" => nil, "address" => wallet.address, "correlation_id" => nil, "id" => request.id, "formatted_id" => request.id, "socket_topic" => "transaction_request:#{request.id}", "token_id" => token.id, "token" => token |> TokenSerializer.serialize() |> stringify_keys(), "type" => "send", "status" => "valid", "user_id" => user.id, "user" => user |> UserSerializer.serialize() |> stringify_keys(), "account_id" => nil, "account" => nil, "exchange_account" => nil, "exchange_account_id" => nil, "exchange_wallet" => nil, "exchange_wallet_address" => nil, "allow_amount_override" => true, "require_confirmation" => false, "consumption_lifetime" => nil, "metadata" => %{}, "encrypted_metadata" => %{}, "expiration_date" => nil, "expiration_reason" => nil, "expired_at" => nil, "max_consumptions" => nil, "current_consumptions_count" => 0, "max_consumptions_per_user" => nil, "created_at" => Date.to_iso8601(request.inserted_at), "updated_at" => Date.to_iso8601(request.updated_at) } } end test "receives an error when the type is invalid" do account = Account.get_master_account() user = get_test_user() token = insert(:token) wallet = User.get_primary_wallet(user) {:ok, _} = AccountUser.link(account.uuid, user.uuid) response = provider_request("/transaction_request.create", %{ type: "fake", token_id: token.id, correlation_id: nil, amount: nil, address: wallet.address }) assert response == %{ "success" => false, "version" => "1", "data" => %{ "code" => "client:invalid_parameter", "description" => "Invalid parameter provided `type` is invalid.", "messages" => %{"type" => ["inclusion"]}, "object" => "error" } } end test "receives an error when the address is invalid" do token = insert(:token) response = provider_request("/transaction_request.create", %{ type: "send", token_id: token.id, correlation_id: nil, amount: nil, address: "fake-0000-0000-0000" }) assert response["success"] == false assert response["data"]["code"] == "wallet:wallet_not_found" end test "receives an error when the address does not belong to the user" do account = Account.get_master_account() token = insert(:token) wallet = insert(:wallet) response = provider_request("/transaction_request.create", %{ type: "send", token_id: token.id, correlation_id: nil, amount: nil, account_id: account.id, address: wallet.address }) assert response == %{ "success" => false, "version" => "1", "data" => %{ "code" => "account:account_wallet_mismatch", "description" => "The provided wallet does not belong to the given account", "messages" => nil, "object" => "error" } } end test "receives an error when the token ID is not found" do account = Account.get_master_account() user = get_test_user() wallet = User.get_primary_wallet(user) {:ok, _} = AccountUser.link(account.uuid, user.uuid) response = provider_request("/transaction_request.create", %{ type: "send", token_id: "123", correlation_id: nil, amount: nil, address: wallet.address }) assert response == %{ "success" => false, "version" => "1", "data" => %{ "code" => "token:id_not_found", "description" => "There is no token corresponding to the provided id", "messages" => nil, "object" => "error" } } end end describe "/transaction_request.get" do test "returns the transaction request" do transaction_request = insert(:transaction_request) response = provider_request("/transaction_request.get", %{ formatted_id: transaction_request.id }) assert response["success"] == true assert response["data"]["id"] == transaction_request.id end test "returns an error when the request ID is not found" do response = provider_request("/transaction_request.get", %{ formatted_id: "123" }) assert response == %{ "success" => false, "version" => "1", "data" => %{ "code" => "unauthorized", "description" => "You are not allowed to perform the requested operation", "messages" => nil, "object" => "error" } } end end end
33.087079
93
0.504712
734d2b347a8b9e73afc39404318a0f457e6f0a0e
1,214
ex
Elixir
lib/wasabi_ex/helper.ex
goodhamgupta/wasabi_ex
77e5e955aaf6be8cd1e1357cf681c6dc58afc258
[ "Apache-2.0" ]
null
null
null
lib/wasabi_ex/helper.ex
goodhamgupta/wasabi_ex
77e5e955aaf6be8cd1e1357cf681c6dc58afc258
[ "Apache-2.0" ]
null
null
null
lib/wasabi_ex/helper.ex
goodhamgupta/wasabi_ex
77e5e955aaf6be8cd1e1357cf681c6dc58afc258
[ "Apache-2.0" ]
null
null
null
defmodule WasabiEx.Helper do alias WasabiEx.{Request, Response, Errors} def make_request(token, url, params, :get) do headers = get_headers(token) with {:ok, response} <- Request.get(url, params, headers), {:ok, body} <- Response.parse(response) do {:ok, body} else {:error, error} -> raise Errors.ApiError, Kernel.inspect(error) end end def make_request(token, url, params, :post) do headers = get_headers(token) with {:ok, response} <- Request.post(url, params, headers), {:ok, body} <- Response.parse(response) do {:ok, body} else {:error, error} -> raise Errors.ApiError, Kernel.inspect(error) end end def make_request(token, url, params, :delete) do headers = get_headers(token) with {:ok, response} <- Request.delete(url, params, headers), {:ok, body} <- Response.parse(response) do {:ok, body} else {:error, error} -> raise Errors.ApiError, Kernel.inspect(error) end end defp get_headers(token) do [ Authorization: "Basic #{token}", Accept: "Application/json; Charset=utf-8", "Content-Type": "application/json" ] end end
25.291667
65
0.612026
734d32d992996c8ff5e252374f4976efb6c3ecf2
1,839
ex
Elixir
lib/radixir/gateway/request/get_transaction_status.ex
radixir/radixir
703034330e857bc084b78dd927ec611c3ea54349
[ "Apache-2.0" ]
16
2022-01-05T20:41:55.000Z
2022-03-25T09:06:43.000Z
lib/radixir/gateway/request/get_transaction_status.ex
radixir/radixir
703034330e857bc084b78dd927ec611c3ea54349
[ "Apache-2.0" ]
null
null
null
lib/radixir/gateway/request/get_transaction_status.ex
radixir/radixir
703034330e857bc084b78dd927ec611c3ea54349
[ "Apache-2.0" ]
1
2022-02-10T21:55:26.000Z
2022-02-10T21:55:26.000Z
defmodule Radixir.Gateway.Request.GetTransactionStatus do @moduledoc false # @moduledoc """ # Methods to create each map in `GetTransactionStatus` request body. # """ alias Radixir.StitchPlan @type stitch_plans :: list(keyword) @type params :: keyword @doc """ Generates stitch plan for `network_identifier` map in `GetTransactionStatus` request body. ## Parameters - `stitch_plans`: On-going stitch plans that will be stitched into a map. - `params`: Keyword list that contains: - `network` (optional, string): If `network` is not in `params` it will default to what is returned from `Radixir.Config.network()`. """ @spec network_identifier(stitch_plans, params) :: stitch_plans defdelegate network_identifier(stitch_plans, params \\ []), to: StitchPlan @doc """ Generates stitch plan for `transaction_identifier` map in `GetTransactionStatus` request body. ## Parameters - `stitch_plans`: On-going stitch plans that will be stitched into a map. - `params`: Keyword list that contains: - `hash` (required, string): Transaction Identifer hash. """ @spec transaction_identifier(stitch_plans, params) :: stitch_plans defdelegate transaction_identifier(stitch_plans, params), to: StitchPlan @doc """ Generates stitch plan for `at_state_identifier` map in `GetTransactionStatus` request body. ## Parameters - `stitch_plans`: On-going stitch plans that will be stitched into a map. - `params`: Keyword list that contains: - `version` (optional, integer): Version. - `timestamp` (optional, string): Timestamp. - `epoch` (optional, integer): Epoch. - `round` (optional, integer): Round. """ @spec at_state_identifier(stitch_plans, params) :: stitch_plans defdelegate at_state_identifier(stitch_plans, params), to: StitchPlan end
39.12766
138
0.716694
734d89f02230c26c1ad6e0e30a5a8f6a88be150b
1,511
exs
Elixir
mix.exs
crertel/statisaur
4c70aba7c04be2ad06432124ac5dc76094170ff1
[ "Unlicense" ]
3
2020-08-19T10:19:42.000Z
2021-01-28T08:19:09.000Z
mix.exs
crertel/statisaur
4c70aba7c04be2ad06432124ac5dc76094170ff1
[ "Unlicense" ]
null
null
null
mix.exs
crertel/statisaur
4c70aba7c04be2ad06432124ac5dc76094170ff1
[ "Unlicense" ]
null
null
null
defmodule Statisaur.Mixfile do use Mix.Project def project do [ app: :statisaur, version: "0.0.1", elixir: "~> 1.0", elixirc_paths: elixirc_paths(Mix.env()), build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, package: package(), docs: &docs/0, deps: deps(), test_coverage: [tool: ExCoveralls], description: description() ] end defp elixirc_paths(:test), do: ["lib", "test/helpers"] defp elixirc_paths(_), do: ["lib"] # Configuration for the OTP application # # Type `mix help compile.app` for more information def application() do [] end defp package() do [ contributors: ["Neeraj Tandon", "Chris Ertel"], licenses: ["Public Domain (unlicense)"], links: %{"GitHub" => "https://github.com/hawthornehaus/statisaur"} ] end defp description() do """ Statisaur is a simple library for doing univariate and descriptive statistics. It also does various tests, regressions, and models. """ end defp deps() do [ {:earmark, "~> 1.3.1", only: [:dev, :docs]}, {:ex_doc, "~> 0.19.3", only: [:dev, :docs]}, {:excoveralls, "~> 0.10.0", only: [:test, :dev]}, {:inch_ex, "~> 2.0.0", only: :docs}, {:dialyxir, "~> 1.0.0-rc.6", only: [:dev], runtime: false} ] end defp docs() do {ref, 0} = System.cmd("git", ["rev-parse", "--verify", "--quiet", "HEAD"]) [source_ref: ref, main: "overview"] end end
24.770492
82
0.572469
734d90bf6d0f2c98b79823098bb1bdee3c15b9ac
2,616
ex
Elixir
lib/elixir/lib/behaviour.ex
mk/elixir
2b2c66ecf7b1cc2167cae9cc3e88f950994223f1
[ "Apache-2.0" ]
4
2015-12-22T02:46:39.000Z
2016-04-26T06:11:09.000Z
lib/elixir/lib/behaviour.ex
mk/elixir
2b2c66ecf7b1cc2167cae9cc3e88f950994223f1
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/behaviour.ex
mk/elixir
2b2c66ecf7b1cc2167cae9cc3e88f950994223f1
[ "Apache-2.0" ]
null
null
null
defmodule Behaviour do @moduledoc """ This module has been deprecated. Instead of `defcallback`, one can simply use `@callback`. Instead of `defmacrocallback`, one can simply use `@macrocallback`. Instead of `__behaviour__(:callbacks)`, one can simply use `behaviour_info(:callbacks)`. """ # TODO: Deprecate by 1.4 # TODO: Remove by 2.0 @doc """ Defines a function callback according to the given type specification. """ defmacro defcallback(spec) do do_defcallback(:def, split_spec(spec, quote(do: term))) end @doc """ Defines a macro callback according to the given type specification. """ defmacro defmacrocallback(spec) do do_defcallback(:defmacro, split_spec(spec, quote(do: Macro.t))) end defp split_spec({:when, _, [{:::, _, [spec, return]}, guard]}, _default) do {spec, return, guard} end defp split_spec({:when, _, [spec, guard]}, default) do {spec, default, guard} end defp split_spec({:::, _, [spec, return]}, _default) do {spec, return, []} end defp split_spec(spec, default) do {spec, default, []} end defp do_defcallback(kind, {spec, return, guards}) do case Macro.decompose_call(spec) do {name, args} -> do_callback(kind, name, args, return, guards) _ -> raise ArgumentError, "invalid syntax in #{kind}callback #{Macro.to_string(spec)}" end end defp do_callback(kind, name, args, return, guards) do :lists.foreach fn {:::, _, [left, right]} -> ensure_not_default(left) ensure_not_default(right) left other -> ensure_not_default(other) other end, args spec = quote do unquote(name)(unquote_splicing(args)) :: unquote(return) when unquote(guards) end case kind do :def -> quote(do: @callback unquote(spec)) :defmacro -> quote(do: @macrocallback unquote(spec)) end end defp ensure_not_default({:\\, _, [_, _]}) do raise ArgumentError, "default arguments \\\\ not supported in defcallback/defmacrocallback" end defp ensure_not_default(_), do: :ok @doc false defmacro __using__(_) do quote do @doc false def __behaviour__(:callbacks) do __MODULE__.behaviour_info(:callbacks) end def __behaviour__(:docs) do for {tuple, line, kind, docs} <- Code.get_docs(__MODULE__, :callback_docs) do case kind do :callback -> {tuple, line, :def, docs} :macrocallback -> {tuple, line, :defmacro, docs} end end end import unquote(__MODULE__) end end end
25.90099
95
0.633028
734d92d656c994cbd36221794f79a01e1fe77a9f
572
exs
Elixir
tab_player/mix.exs
alpdenizz/ElixirPlayground
58b5a16c489058e0067e4811042d96fe6a5f8d59
[ "MIT" ]
null
null
null
tab_player/mix.exs
alpdenizz/ElixirPlayground
58b5a16c489058e0067e4811042d96fe6a5f8d59
[ "MIT" ]
null
null
null
tab_player/mix.exs
alpdenizz/ElixirPlayground
58b5a16c489058e0067e4811042d96fe6a5f8d59
[ "MIT" ]
null
null
null
defmodule TabPlayer.Mixfile do use Mix.Project def project do [ app: :tab_player, 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.724138
88
0.578671
734da78a7e7a3f4b24bf36d724b26e2caa139ec9
2,556
ex
Elixir
lib/retrospectivex/accounts/managers/administrator.ex
dreamingechoes/retrospectivex
cad0df6cfde5376121d841f4a8b36861b6ec5d45
[ "MIT" ]
5
2018-06-27T17:51:51.000Z
2020-10-05T09:59:04.000Z
lib/retrospectivex/accounts/managers/administrator.ex
dreamingechoes/retrospectivex
cad0df6cfde5376121d841f4a8b36861b6ec5d45
[ "MIT" ]
1
2018-10-08T11:33:12.000Z
2018-10-08T11:33:12.000Z
lib/retrospectivex/accounts/managers/administrator.ex
dreamingechoes/retrospectivex
cad0df6cfde5376121d841f4a8b36861b6ec5d45
[ "MIT" ]
2
2018-10-08T11:31:55.000Z
2020-10-05T09:59:05.000Z
defmodule Retrospectivex.Accounts.Managers.Administrator do import Ecto.Query, warn: false alias Retrospectivex.Accounts.Queries.Administrator, as: Query alias Retrospectivex.Accounts.Schemas.Administrator alias Retrospectivex.Repo @doc """ Returns the list of administrators. ## Examples iex> list_administrators() [%Administrator{}, ...] """ def list_administrators do Repo.all(Administrator) end @doc """ Gets a single administrator. Raises `Ecto.NoResultsError` if the Administrator does not exist. ## Examples iex> get_administrator!(123) %Administrator{} iex> get_administrator!(456) ** (Ecto.NoResultsError) """ def get_administrator!(id), do: Repo.get!(Administrator, id) @doc """ Gets a single administrator by email. Returns nil if the Administrator does not exist. ## Examples iex> get_administrator_by_email("[email protected]") %Administrator{} iex> get_administrator_by_email("[email protected]") nil """ def get_administrator_by_email(email) do email |> Query.by_email() |> Repo.one() end @doc """ Creates a administrator. ## Examples iex> create_administrator(%{field: value}) {:ok, %Administrator{}} iex> create_administrator(%{field: bad_value}) {:error, %Ecto.Changeset{}} """ def create_administrator(attrs \\ %{}) do %Administrator{} |> Administrator.changeset(attrs) |> Repo.insert() end @doc """ Updates a administrator. ## Examples iex> update_administrator(administrator, %{field: new_value}) {:ok, %Administrator{}} iex> update_administrator(administrator, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ def update_administrator(%Administrator{} = administrator, attrs) do administrator |> Administrator.changeset(attrs) |> Repo.update() end @doc """ Deletes a Administrator. ## Examples iex> delete_administrator(administrator) {:ok, %Administrator{}} iex> delete_administrator(administrator) {:error, %Ecto.Changeset{}} """ def delete_administrator(%Administrator{} = administrator) do Repo.delete(administrator) end @doc """ Returns an `%Ecto.Changeset{}` for tracking administrator changes. ## Examples iex> change_administrator(administrator) %Ecto.Changeset{source: %Administrator{}} """ def change_administrator(%Administrator{} = administrator) do Administrator.changeset(administrator, %{}) end end
20.95082
70
0.669405
734db7f56c87b84c8b724d1a95a30b86b2bb296a
128
exs
Elixir
test/test_helper.exs
joshillian/faker
eeede9d7c35c543dcf6abe72dc476e755c80415b
[ "MIT" ]
540
2015-01-05T16:31:49.000Z
2019-09-25T00:40:27.000Z
test/test_helper.exs
echenim/faker
15172b7d9c2b7711173a5faf3e45bfc4e45d6a97
[ "MIT" ]
172
2015-01-06T03:55:17.000Z
2019-10-03T12:58:02.000Z
test/test_helper.exs
echenim/faker
15172b7d9c2b7711173a5faf3e45bfc4e45d6a97
[ "MIT" ]
163
2015-01-05T21:24:54.000Z
2019-10-03T07:59:42.000Z
:ets.new(:seed_registry, [:named_table, :public]) Application.put_env(:faker, :random_module, Faker.Random.Test) ExUnit.start()
32
62
0.765625
734dc1976828460dd5e0d34e651180930fddfc6a
14,173
exs
Elixir
test/core/async_job/queue_test.exs
ikeyasu/antikythera
544fdd22e46b1f34177053d87d9e2a9708c74113
[ "Apache-2.0" ]
null
null
null
test/core/async_job/queue_test.exs
ikeyasu/antikythera
544fdd22e46b1f34177053d87d9e2a9708c74113
[ "Apache-2.0" ]
null
null
null
test/core/async_job/queue_test.exs
ikeyasu/antikythera
544fdd22e46b1f34177053d87d9e2a9708c74113
[ "Apache-2.0" ]
null
null
null
# Copyright(c) 2015-2018 ACCESS CO., LTD. All rights reserved. defmodule AntikytheraCore.AsyncJob.QueueTest do use Croma.TestCase alias Antikythera.{Time, Cron} alias Antikythera.Test.{GenServerHelper, AsyncJobHelper} alias AntikytheraCore.ExecutorPool alias AntikytheraCore.ExecutorPool.Setting, as: EPoolSetting alias AntikytheraCore.ExecutorPool.RegisteredName, as: RegName alias AntikytheraCore.ExecutorPool.AsyncJobBroker, as: Broker alias AntikytheraCore.AsyncJob alias AntikytheraCore.AsyncJob.RateLimit defmodule TestJob do use Antikythera.AsyncJob @impl true def run(_payload, _metadata, _context) do :ok end end @epool_id {:gear, :testgear} @queue_name RegName.async_job_queue_unsafe(@epool_id) @setting %EPoolSetting{n_pools_a: 2, pool_size_a: 1, pool_size_j: 1, ws_max_connections: 10} @payload %{foo: "bar"} @job_id "foobar" defp register_job(opts) do case AsyncJob.register(:testgear, TestJob, @payload, @epool_id, opts) do {:ok, _} -> :ok error -> error end end defp waiting_brokers() do {:ok, %Queue{brokers_waiting: bs}} = RaftFleet.query(@queue_name, :all) bs end setup do AsyncJobHelper.reset_rate_limit_status(@epool_id) ExecutorPool.start_executor_pool(@epool_id, @setting) ExecutorPoolHelper.wait_until_async_job_queue_added(@epool_id) {_, broker_pid, _, _} = Supervisor.which_children(RegName.supervisor(@epool_id)) |> Enum.find(&match?({Broker, _, :worker, _}, &1)) Broker.deactivate(broker_pid) # don't run jobs throughout this test case _ = :sys.get_state(broker_pid) # wait until deactivate message gets processed on_exit(fn -> ExecutorPoolHelper.kill_and_wait(@epool_id) end) end test "register and fetch job" do # fetch => register; receives a notification assert waiting_brokers() == [] assert Queue.fetch_job(@queue_name) == nil assert waiting_brokers() == [self()] assert Queue.fetch_job(@queue_name) == nil assert waiting_brokers() == [self()] assert register_job([]) == :ok assert GenServerHelper.receive_cast_message() == :job_registered assert waiting_brokers() == [] {_job_key, job1} = Queue.fetch_job(@queue_name) assert job1.payload == @payload assert waiting_brokers() == [] # fetch => register with start time; no notification assert Queue.fetch_job(@queue_name) == nil assert waiting_brokers() == [self()] start_time = Time.shift_milliseconds(Time.now(), 10) assert register_job([schedule: {:once, start_time}]) == :ok refute_received(_) :timer.sleep(10) {_job_key, job2} = Queue.fetch_job(@queue_name) assert job2.payload == @payload assert waiting_brokers() == [] # register => fetch; no notification assert register_job([]) == :ok {_job_key, job3} = Queue.fetch_job(@queue_name) assert job3.payload == @payload assert waiting_brokers() == [] refute_received(_) end test "register should validate options" do [ id: "", id: "ID with invalid chars", id: String.duplicate("a", 33), schedule: {:unexpected_tuple, "foo"}, schedule: {:once, Time.shift_milliseconds(Time.now(), -10)}, schedule: {:once, Time.shift_days(Time.now(), 51)}, attempts: 0, attempts: 11, max_duration: 0, max_duration: 1_800_001, retry_interval: {-1, 2.0}, retry_interval: {300_001, 2.0}, retry_interval: {10_000, 0.9}, retry_interval: {10_000, 5.1}, ] |> Enum.each(fn option_pair -> {:error, {:invalid_value, _}} = register_job([option_pair]) end) [ id: String.duplicate("a", 32), schedule: {:once, Time.shift_seconds(Time.now(), 1)}, schedule: {:once, Time.shift_days(Time.now(), 49)}, schedule: {:cron, Cron.parse!("* * * * *")}, attempts: 1, attempts: 10, max_duration: 1, max_duration: 1_800_000, retry_interval: {0, 2.0}, retry_interval: {300_000, 2.0}, retry_interval: {10_000, 1.0}, retry_interval: {10_000, 5.0}, ] |> Enum.each(fn option_pair -> AsyncJobHelper.reset_rate_limit_status(@epool_id) assert register_job([option_pair]) == :ok end) end test "register should reject to add job with existing ID" do assert register_job([id: "foobar"]) == :ok assert register_job([id: "foobar"]) == {:error, :existing_id} end test "register should reject to add more than 1000 jobs" do Enum.each(1..Queue.max_jobs(), fn _ -> AsyncJobHelper.reset_rate_limit_status(@epool_id) assert register_job([]) == :ok end) assert register_job([]) == {:error, :full} end test "register should reject to use executor pool which is unavailable to the gear" do [ {:gear, :unknown_gear}, ] |> Enum.each(fn epool_id -> assert AsyncJob.register(:testgear, TestJob, @payload, epool_id, []) == {:error, {:invalid_executor_pool, epool_id}} end) end test "register => remove_locked" do assert register_job([]) == :ok {job_key, _job} = Queue.fetch_job(@queue_name) assert Queue.remove_locked_job(@queue_name, job_key) == :ok assert Queue.fetch_job(@queue_name) == nil end test "register => unlock_for_retry: should decrement remaining_attempts" do assert register_job([retry_interval: {0, 1.0}]) == :ok {{t1, ref} = job_key, job1} = Queue.fetch_job(@queue_name) assert Queue.unlock_job_for_retry(@queue_name, job_key) == :ok {{t2, ^ref}, job2} = Queue.fetch_job(@queue_name) assert t1 <= t2 assert job2.remaining_attempts == job1.remaining_attempts - 1 assert Map.delete(job2, :remaining_attempts) == Map.delete(job1, :remaining_attempts) assert Queue.fetch_job(@queue_name) == nil end test "cancel nonexisting job" do assert Queue.cancel(@queue_name, @job_id) == {:error, :not_found} end test "cancel waiting job" do second_after = Time.now() |> Time.shift_seconds(1) assert register_job([id: @job_id, schedule: {:once, second_after}]) == :ok {:ok, status1} = Queue.status(@queue_name, @job_id) assert status1.state == :waiting assert Queue.cancel(@queue_name, @job_id) == :ok assert Queue.cancel(@queue_name, @job_id) == {:error, :not_found} end test "cancel runnable job" do assert Queue.fetch_job(@queue_name) == nil assert register_job([id: @job_id]) == :ok assert Queue.start_jobs_and_get_metrics(Process.whereis(@queue_name)) assert_receive({:"$gen_cast", :job_registered}) {:ok, status2} = Queue.status(@queue_name, @job_id) assert status2.state == :runnable assert Queue.cancel(@queue_name, @job_id) == :ok assert Queue.cancel(@queue_name, @job_id) == {:error, :not_found} end test "cancel running job" do assert register_job([id: @job_id]) == :ok {_key, _job} = Queue.fetch_job(@queue_name) {:ok, status3} = Queue.status(@queue_name, @job_id) assert status3.state == :running assert Queue.cancel(@queue_name, @job_id) == :ok assert Queue.cancel(@queue_name, @job_id) == {:error, :not_found} end test "consecutive registrations/cancels should be rejected by rate limit" do n = div(RateLimit.max_tokens(), RateLimit.tokens_per_command()) Enum.each(1..n, fn i -> assert register_job([id: @job_id <> "#{i}"]) == :ok end) {:error, {:rate_limit_reached, _}} = register_job([id: @job_id <> "0"]) AsyncJobHelper.reset_rate_limit_status(@epool_id) assert register_job([id: @job_id <> "0"]) == :ok AsyncJobHelper.reset_rate_limit_status(@epool_id) Enum.each(1..n, fn i -> assert Queue.cancel(@queue_name, @job_id <> "#{i}") == :ok end) {:error, {:rate_limit_reached, _}} = Queue.cancel(@queue_name, @job_id <> "0") end test "consecutive fetchings of status should sleep-and-retry on hitting rate limit" do t1 = System.system_time(:milliseconds) Enum.each(1..RateLimit.max_tokens(), fn _ -> assert Queue.status(@queue_name, @job_id) == {:error, :not_found} end) t2 = System.system_time(:milliseconds) assert t2 - t1 < 100 assert Queue.status(@queue_name, @job_id) == {:error, :not_found} t3 = System.system_time(:milliseconds) assert t3 - t2 > RateLimit.milliseconds_per_token() - 100 end test "consecutive listings should sleep-and-retry on hitting rate limit" do t1 = System.system_time(:milliseconds) Enum.each(1..RateLimit.max_tokens(), fn _ -> assert Queue.list(@queue_name) == [] end) t2 = System.system_time(:milliseconds) assert t2 - t1 < 100 assert Queue.list(@queue_name) == [] t3 = System.system_time(:milliseconds) assert t3 - t2 > RateLimit.milliseconds_per_token() - 100 end end defmodule AntikytheraCore.AsyncJob.QueueCommandTest do use ExUnit.Case alias Croma.Result, as: R alias Antikythera.{Time, Cron} alias Antikythera.AsyncJob.{Id, MaxDuration} alias AntikytheraCore.AsyncJob alias AntikytheraCore.AsyncJob.Queue @now_millis System.system_time(:milliseconds) @now Time.from_epoch_milliseconds(@now_millis) @cron Cron.parse!("* * * * *") @job_id Id.generate() @job_key {@now_millis, @job_id} @job AsyncJob.make_job(:testgear, Testgear.DummyModule, %{}, {:once, @now }, []) |> R.get!() @job_cron AsyncJob.make_job(:testgear, Testgear.DummyModule, %{}, {:cron, @cron}, []) |> R.get!() defp make_queue_with_started_job(job) do q0 = Queue.new() {_, q1} = Queue.command(q0, {{:add, @job_key, job}, @now_millis - 1_000}) assert_job_waiting(q1) {{@job_key, ^job}, q2} = Queue.command(q1, {{:fetch, self()}, @now_millis}) assert_job_running(q2) q2 end defp index_has_id?(index) do :gb_sets.to_list(index) |> Enum.any?(fn {_time, id} -> id == @job_id end) end defp assert_job_waiting(q) do assert Map.has_key?(q.jobs, @job_id) assert index_has_id?(q.index_waiting) refute index_has_id?(q.index_runnable) refute index_has_id?(q.index_running) end defp assert_job_runnable(q) do assert Map.has_key?(q.jobs, @job_id) refute index_has_id?(q.index_waiting) assert index_has_id?(q.index_runnable) refute index_has_id?(q.index_running) end defp assert_job_running(q) do assert Map.has_key?(q.jobs, @job_id) refute index_has_id?(q.index_waiting) refute index_has_id?(q.index_runnable) assert index_has_id?(q.index_running) end defp assert_job_removed(q) do refute Map.has_key?(q.jobs, @job_id) refute index_has_id?(q.index_waiting) refute index_has_id?(q.index_runnable) refute index_has_id?(q.index_running) end test "command/2 success or failure_abandon (once) => remove" do q0 = make_queue_with_started_job(@job) {:ok, q1} = Queue.command(q0, {{:remove_locked, @job_key}, @now_millis}) assert_job_removed(q1) end test "command/2 success or failure_abandon (cron) => requeue" do q0 = make_queue_with_started_job(@job_cron) {:ok, q1} = Queue.command(q0, {{:remove_locked, @job_key}, @now_millis}) assert_job_waiting(q1) {_, next_time, :waiting} = q1.jobs[@job_id] assert next_time == @now_millis - rem(@now_millis, 60_000) + 60_000 end test "command/2 failure_retry (once and cron)" do [ make_queue_with_started_job(@job), make_queue_with_started_job(@job_cron), ] |> Enum.each(fn q1 -> {:ok, q2} = Queue.command(q1, {{:unlock_for_retry, @job_key}, @now_millis}) assert_job_waiting(q2) {j, _, :waiting} = q2.jobs[@job_id] assert j.remaining_attempts == @job.remaining_attempts - 1 end) end test "command/2 retry by running too long (once and cron)" do [ make_queue_with_started_job(@job), make_queue_with_started_job(@job_cron), ] |> Enum.each(fn q1 -> {_, q2} = Queue.command(q1, {:get_metrics, @now_millis + MaxDuration.max()}) assert_job_runnable(q2) {j, _, :runnable} = q2.jobs[@job_id] assert j.remaining_attempts == @job.remaining_attempts - 1 end) end test "command/2 abandon by running too long (once) => remove" do j = %AsyncJob{@job | remaining_attempts: 1} q0 = make_queue_with_started_job(j) assert q0.abandoned_jobs == [] {_, q1} = Queue.command(q0, {:get_metrics, @now_millis + MaxDuration.max()}) assert q1.abandoned_jobs == [{@job_id, j}] assert_job_removed(q1) end test "command/2 abandon by running too long (cron) => requeue" do j = %AsyncJob{@job_cron | remaining_attempts: 1} q0 = make_queue_with_started_job(j) assert q0.abandoned_jobs == [] current_time = @now_millis + MaxDuration.max() {_, q1} = Queue.command(q0, {:get_metrics, current_time}) assert q1.abandoned_jobs == [{@job_id, j}] assert_job_waiting(q1) {j2, next_time, :waiting} = q1.jobs[@job_id] assert j2.remaining_attempts == 3 assert next_time == current_time - rem(current_time, 60_000) + 60_000 end test "command/2 move waiting jobs that have become runnable" do q0 = Queue.new() {_, q1} = Queue.command(q0, {{:add, @job_key, @job}, @now_millis - 1_000}) assert_job_waiting(q1) {_, q2} = Queue.command(q1, {:get_metrics, @now_millis + 1_000}) assert_job_runnable(q2) end test "command/2 add/remove broker" do q0 = Queue.new() assert q0.brokers_waiting == [] {nil, q1} = Queue.command(q0, {{:fetch, self()}, @now_millis}) assert q1.brokers_waiting == [self()] {nil, q2} = Queue.command(q1, {{:fetch, self()}, @now_millis}) assert q2.brokers_waiting == [self()] {:ok, q3} = Queue.command(q2, {{:remove_broker_from_waiting_list, self()}, @now_millis}) assert q3.brokers_waiting == [] {:ok, q4} = Queue.command(q3, {{:remove_broker_from_waiting_list, self()}, @now_millis}) assert q4.brokers_waiting == [] end end
37.494709
122
0.653073
734dda4208e076c94898af6073b492dd0c31c884
905
exs
Elixir
test/ecto/poison_test.exs
jeregrine/ecto
98b2dd4bf7b39738ab9a5ae3fa7e48e43a4af39b
[ "Apache-2.0" ]
null
null
null
test/ecto/poison_test.exs
jeregrine/ecto
98b2dd4bf7b39738ab9a5ae3fa7e48e43a4af39b
[ "Apache-2.0" ]
null
null
null
test/ecto/poison_test.exs
jeregrine/ecto
98b2dd4bf7b39738ab9a5ae3fa7e48e43a4af39b
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.PoisonTest do use ExUnit.Case, async: true defmodule User do use Ecto.Schema embedded_schema do has_many :comments, Ecto.Comment end end test "encodes datetimes" do time = %Ecto.Time{hour: 1, min: 2, sec: 3} assert Poison.encode!(time) == ~s("01:02:03") date = %Ecto.Date{year: 2010, month: 4, day: 17} assert Poison.encode!(date) == ~s("2010-04-17") dt = %Ecto.DateTime{year: 2010, month: 4, day: 17, hour: 0, min: 0, sec: 0} assert Poison.encode!(dt) == ~s("2010-04-17T00:00:00") end test "encodes decimal" do decimal = Decimal.new("1.0") assert Poison.encode!(decimal) == ~s("1.0") end test "fails on association not loaded" do assert_raise RuntimeError, ~r/cannot encode association :comments from Ecto.PoisonTest.User to JSON/, fn -> Poison.encode!(%User{}.comments) end end end
25.857143
97
0.629834
734df4a447108cf3e946905ac7e5560929e0b964
585
exs
Elixir
config/config.exs
antonioparisi/yatapp-elixir
5d426dda3ec8b9222a7197951da32d6f90d75d83
[ "MIT" ]
null
null
null
config/config.exs
antonioparisi/yatapp-elixir
5d426dda3ec8b9222a7197951da32d6f90d75d83
[ "MIT" ]
null
null
null
config/config.exs
antonioparisi/yatapp-elixir
5d426dda3ec8b9222a7197951da32d6f90d75d83
[ "MIT" ]
null
null
null
use Mix.Config config :yatapp, api_key: System.get_env("YATA_API_KEY"), project_id: System.get_env("YATA_PROJECT_ID"), default_locale: "en", locales: ~w(en), otp_app: :yatapp, json_parser: Jason, store: Yatapp.Store.ETS, pluralizer: Yatapp.Pluralization.Base, download_on_start: true, save_to_path: "priv/locales/", translations_format: "json", translation_file_parser: Jason, root: false, strip_empty: false, enable_websocket: false, var_prefix: "%{", var_suffix: "}", fallback: false, http: %{ timeout: 50_000, recv_timeout: 50_000 }
22.5
48
0.700855
734dfc8dc381f33ac458f0e7a4af4ba75cc36872
1,325
ex
Elixir
implementations/elixir/ockam/ockam/lib/ockam/workers/call.ex
psinghal20/ockam
55c2787eb2392c919156c6dded9f31a5249541e1
[ "Apache-2.0" ]
null
null
null
implementations/elixir/ockam/ockam/lib/ockam/workers/call.ex
psinghal20/ockam
55c2787eb2392c919156c6dded9f31a5249541e1
[ "Apache-2.0" ]
null
null
null
implementations/elixir/ockam/ockam/lib/ockam/workers/call.ex
psinghal20/ockam
55c2787eb2392c919156c6dded9f31a5249541e1
[ "Apache-2.0" ]
null
null
null
defmodule Ockam.Workers.Call do @moduledoc """ One-off worker to perform a synchronous call to an Ockam worker using the routing protocol. """ use Ockam.Worker alias Ockam.Message require Logger def call(call, options \\ [], timeout \\ 10_000) do {:ok, address} = __MODULE__.create(Keyword.put(options, :call, call)) GenServer.call(Ockam.Node.whereis(address), :fetch, timeout) end @impl true def setup(options, state) do call = Keyword.fetch!(options, :call) send_call(call, state) {:ok, state} end def send_call(call, state) do Ockam.Router.route(%{ payload: Message.payload(call), onward_route: Message.onward_route(call), return_route: [state.address] }) end @impl true def handle_message(message, state) do Map.put(state, :message, message) case Map.get(state, :wait) do nil -> {:ok, state} waiter -> GenServer.reply(waiter, message) ## Terminate here {:stop, :shutdown, state} end end @impl true def handle_call(:fetch, from, state) do case Map.get(state, :message) do nil -> {:noreply, Map.put(state, :wait, from)} message -> GenServer.reply(from, message) ## Terminate here {:stop, :shutdown, state} end end end
21.721311
73
0.623396
734e02c39d167659692f7e85bf0740854af16f61
372
exs
Elixir
test/lib/types/json_test.exs
ramkrishna70/opencov
7a3415f8eebb797ad1f7b6c832daa4f04d70af8d
[ "MIT" ]
189
2018-09-25T09:02:41.000Z
2022-03-09T13:52:06.000Z
test/lib/types/json_test.exs
ramkrishna70/opencov
7a3415f8eebb797ad1f7b6c832daa4f04d70af8d
[ "MIT" ]
29
2018-09-26T05:51:18.000Z
2021-11-05T08:55:03.000Z
test/lib/types/json_test.exs
ramkrishna70/opencov
7a3415f8eebb797ad1f7b6c832daa4f04d70af8d
[ "MIT" ]
32
2018-10-21T12:28:11.000Z
2022-03-28T02:20:19.000Z
defmodule Opencov.Types.JSONText do use ExUnit.Case import Opencov.Types.JSON @json String.trim(""" {"foo":"bar"} """) test "load" do assert load(@json) == {:ok, %{"foo" => "bar"}} assert {:error, _} = load("invalid_json") end test "dump" do assert dump(%{"foo" => "bar"}) == {:ok, @json} assert dump("foo") == {:ok, "foo"} end end
18.6
50
0.551075
734e0eb585d250d450d12c10a7ed44ab0997c353
1,901
ex
Elixir
clients/translate/lib/google_api/translate/v3/model/list_glossaries_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/translate/lib/google_api/translate/v3/model/list_glossaries_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/translate/lib/google_api/translate/v3/model/list_glossaries_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Translate.V3.Model.ListGlossariesResponse do @moduledoc """ Response message for ListGlossaries. ## Attributes * `glossaries` (*type:* `list(GoogleApi.Translate.V3.Model.Glossary.t)`, *default:* `nil`) - The list of glossaries for a project. * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - A token to retrieve a page of results. Pass this value in the [ListGlossariesRequest.page_token] field in the subsequent call to `ListGlossaries` method to retrieve the next page of results. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :glossaries => list(GoogleApi.Translate.V3.Model.Glossary.t()) | nil, :nextPageToken => String.t() | nil } field(:glossaries, as: GoogleApi.Translate.V3.Model.Glossary, type: :list) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.Translate.V3.Model.ListGlossariesResponse do def decode(value, options) do GoogleApi.Translate.V3.Model.ListGlossariesResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Translate.V3.Model.ListGlossariesResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.02
253
0.741189
734e20e2425097a3a0f255b245be8880a17d0872
2,457
exs
Elixir
test/battle_box/user_test.exs
GrantJamesPowell/battle_box
301091955b68cd4672f6513d645eca4e3c4e17d0
[ "Apache-2.0" ]
2
2020-10-17T05:48:49.000Z
2020-11-11T02:34:15.000Z
test/battle_box/user_test.exs
FlyingDutchmanGames/battle_box
301091955b68cd4672f6513d645eca4e3c4e17d0
[ "Apache-2.0" ]
3
2020-05-18T05:52:21.000Z
2020-06-09T07:24:14.000Z
test/battle_box/user_test.exs
FlyingDutchmanGames/battle_box
301091955b68cd4672f6513d645eca4e3c4e17d0
[ "Apache-2.0" ]
null
null
null
defmodule BattleBox.UserTest do use BattleBox.DataCase alias BattleBox.{User, Repo} setup do %{ user_from_github: %{ "id" => 1, "html_url" => "test.com", "login" => "GrantJamesPowell", "name" => "Grant Powell", "avatar_url" => "test-avatar.com", "access_token" => "1234" } } end test "names are case insensitive" do {:ok, _user} = create_user(username: "GrantJamesPowell") assert %User{username: "GrantJamesPowell"} = Repo.get_by(User, username: "GrantJamesPowell") assert %User{username: "GrantJamesPowell"} = Repo.get_by(User, username: "grantjamespowell") assert %User{username: "GrantJamesPowell"} = Repo.get_by(User, username: "GRANTJAMESPOWELL") end describe "upsert_from_github" do test "if there is nothing in the db it succeeds", context do assert {:ok, user} = User.upsert_from_github(context.user_from_github) assert not is_nil(user.id) end test "it will upsert the row if its called twice", context do assert {:ok, _} = User.upsert_from_github(context.user_from_github) user = Repo.get_by(User, github_id: context.user_from_github["id"]) assert user.username == "GrantJamesPowell" assert {:ok, user2} = User.upsert_from_github(%{context.user_from_github | "login" => "pass"}) assert user2.id == user.id assert user2.username == "pass" end end describe "anon_human_user/0" do test "If the anon user doesn't exist, this function will create it" do assert Repo.all(User) == [] %User{username: "Anonymous", id: id} = User.anon_human_user() assert [%{username: "Anonymous", id: ^id}] = Repo.all(User) end test "you can make multiple calls to `anon_human_user`" do assert %User{username: "Anonymous", id: id} = User.anon_human_user() assert %User{username: "Anonymous", id: ^id} = User.anon_human_user() end end describe "system_user/0" do test "If the system user doesn't exist, this function will create it" do assert Repo.all(User) == [] %User{username: "Botskrieg", id: id} = User.system_user() assert [%{username: "Botskrieg", id: ^id}] = Repo.all(User) end test "you can make multiple calls to `system_user`" do assert %User{username: "Botskrieg", id: id} = User.system_user() assert %User{username: "Botskrieg", id: ^id} = User.system_user() end end end
34.605634
96
0.646724
734e69bd06c4b8ac47b5429a293f833175c35d6d
550
exs
Elixir
priv/repo/migrations/20220219224136_create_voters.exs
manojsamanta/election
e4eca4f2813011954d08eb04d057f84a9f6bda90
[ "MIT" ]
null
null
null
priv/repo/migrations/20220219224136_create_voters.exs
manojsamanta/election
e4eca4f2813011954d08eb04d057f84a9f6bda90
[ "MIT" ]
null
null
null
priv/repo/migrations/20220219224136_create_voters.exs
manojsamanta/election
e4eca4f2813011954d08eb04d057f84a9f6bda90
[ "MIT" ]
null
null
null
defmodule Election.Repo.Migrations.CreateVoters do use Ecto.Migration def change do create table(:voters) do add :first, :string add :middle, :string add :last, :string add :street, :string add :city, :string add :county, :string add :precinct, :string add :v_2014, :boolean, default: false, null: false add :v_2016, :boolean, default: false, null: false add :v_2018, :boolean, default: false, null: false add :v_2020, :boolean, default: false, null: false end end end
27.5
56
0.636364
734e932cfbb4aeaac36c77232b66344dedca4bf2
2,891
ex
Elixir
lib/formatter.ex
cowile/scribe
75334daf0f1fd24ba92bceef67b4cb6e1e2c4f37
[ "MIT" ]
253
2016-08-13T21:47:42.000Z
2022-01-18T06:53:28.000Z
lib/formatter.ex
cowile/scribe
75334daf0f1fd24ba92bceef67b4cb6e1e2c4f37
[ "MIT" ]
15
2017-02-18T18:00:15.000Z
2022-01-30T15:48:08.000Z
lib/formatter.ex
cowile/scribe
75334daf0f1fd24ba92bceef67b4cb6e1e2c4f37
[ "MIT" ]
11
2016-12-23T08:21:36.000Z
2021-12-31T21:03:26.000Z
defmodule Scribe.Formatter.Index do @moduledoc false defstruct row: 0, row_max: 0, col: 0, col_max: 0 end defmodule Scribe.Formatter.Line do @moduledoc false defstruct data: [], widths: [], style: nil, opts: [], index: nil alias Scribe.Formatter.{Index, Line} def format(%Line{index: %Index{row: 0}} = line) do top(line) <> data(line) <> bottom(line) end def format(%Line{} = line) do data(line) <> bottom(line) end def data(%Line{} = line) do %Line{ data: row, widths: widths, style: style, opts: opts, index: index } = line border = style.border_at(index.row, 0, index.row_max, index.col_max) left_edge = border.left_edge line = Enum.reduce(0..(index.col_max - 1), "", fn x, acc -> b = style.border_at(index.row, x, index.row_max, index.col_max) width = Enum.at(widths, x) value = Enum.at(row, x) cell_value = case opts[:colorize] do false -> value |> cell(width) _ -> value |> cell(width) |> colorize(style.color(value)) end acc <> cell_value <> b.right_edge end) left_edge <> line <> "\n" end def cell(x, width) do len = min(String.length(" #{inspect(x)} "), width) padding = String.duplicate(" ", width - len) truncate(" #{inspect(x)}#{padding}", width - 2) <> " " end def cell_value(x, padding, max_width) when padding >= 0 do truncate(" #{inspect(x)}#{String.duplicate(" ", padding)} ", max_width) end defp truncate(elem, width) do String.slice(elem, 0..width) end def colorize(string, color) do "#{color}#{string}#{IO.ANSI.reset()}" end def top(%Line{widths: widths, style: style, index: index, opts: opts}) do border = style.border_at(index.row, 0, index.row_max, index.col_max) top_left = border.top_left_corner line = Enum.reduce(0..(index.col_max - 1), "", fn x, acc -> b = style.border_at(index.row, x, index.row_max, index.col_max) width = Enum.at(widths, x) acc <> String.duplicate(b.top_edge, width) <> b.top_right_corner end) color_prefix = if Keyword.get(opts, :colorize, true) do style.default_color() else "" end color_prefix <> top_left <> add_newline(line) end def bottom(%Line{widths: widths, style: style, index: index}) do border = style.border_at(index.row, 0, index.row_max, index.col_max) bottom_left = border.bottom_left_corner line = Enum.reduce(0..(index.col_max - 1), "", fn x, acc -> b = style.border_at(index.row, x, index.row_max, index.col_max) width = Enum.at(widths, x) acc <> String.duplicate(b.bottom_edge, width) <> b.bottom_right_corner end) bottom_left <> add_newline(line) end def add_newline(""), do: "" def add_newline(line), do: line <> "\n" end
26.768519
78
0.603597
734e9d278fc05fd5084028b0d1d629963a6bd7c2
14,155
exs
Elixir
test/phoenix/controller/controller_test.exs
manukall/phoenix
5ce19ebb63b1b31e37da5fe6465edb6c4850772e
[ "MIT" ]
1
2019-06-11T20:22:21.000Z
2019-06-11T20:22:21.000Z
test/phoenix/controller/controller_test.exs
DavidAlphaFox/phoenix
560131ab3b48c6b6cf864a3d20b7667e40990237
[ "MIT" ]
null
null
null
test/phoenix/controller/controller_test.exs
DavidAlphaFox/phoenix
560131ab3b48c6b6cf864a3d20b7667e40990237
[ "MIT" ]
null
null
null
defmodule Phoenix.Controller.ControllerTest do use ExUnit.Case, async: true use RouterHelper import Phoenix.Controller alias Plug.Conn setup do Logger.disable(self) :ok end defp get_resp_content_type(conn) do [header] = get_resp_header(conn, "content-type") header |> String.split(";") |> Enum.fetch!(0) end test "action_name/1" do conn = put_private(%Conn{}, :phoenix_action, :show) assert action_name(conn) == :show end test "controller_module/1" do conn = put_private(%Conn{}, :phoenix_controller, Hello) assert controller_module(conn) == Hello end test "router_module/1" do conn = put_private(%Conn{}, :phoenix_router, Hello) assert router_module(conn) == Hello end test "endpoint_module/1" do conn = put_private(%Conn{}, :phoenix_endpoint, Hello) assert endpoint_module(conn) == Hello end test "view_template/1" do conn = put_private(%Conn{}, :phoenix_template, "hello.html") assert view_template(conn) == "hello.html" assert view_template(%Conn{}) == nil end test "put_layout_formats/2 and layout_formats/1" do conn = conn(:get, "/") assert layout_formats(conn) == ~w(html) conn = put_layout_formats conn, ~w(json xml) assert layout_formats(conn) == ~w(json xml) assert_raise Plug.Conn.AlreadySentError, fn -> put_layout_formats sent_conn, ~w(json) end end test "put_layout/2 and layout/1" do conn = conn(:get, "/") assert layout(conn) == false conn = put_layout conn, {AppView, "app.html"} assert layout(conn) == {AppView, "app.html"} conn = put_layout conn, "print.html" assert layout(conn) == {AppView, "print.html"} conn = put_layout conn, :print assert layout(conn) == {AppView, :print} conn = put_layout conn, false assert layout(conn) == false assert_raise RuntimeError, fn -> put_layout conn, "print" end assert_raise Plug.Conn.AlreadySentError, fn -> put_layout sent_conn, {AppView, :print} end end test "put_new_layout/2" do conn = put_new_layout(conn(:get, "/"), false) assert layout(conn) == false conn = put_new_layout(conn, {AppView, "app.html"}) assert layout(conn) == false conn = put_new_layout(conn(:get, "/"), {AppView, "app.html"}) assert layout(conn) == {AppView, "app.html"} conn = put_new_layout(conn, false) assert layout(conn) == {AppView, "app.html"} assert_raise Plug.Conn.AlreadySentError, fn -> put_new_layout sent_conn, {AppView, "app.html"} end end test "put_view/2 and put_new_view/2" do conn = put_new_view(conn(:get, "/"), Hello) assert view_module(conn) == Hello conn = put_new_view(conn, World) assert view_module(conn) == Hello conn = put_view(conn, World) assert view_module(conn) == World assert_raise Plug.Conn.AlreadySentError, fn -> put_new_view sent_conn, Hello end assert_raise Plug.Conn.AlreadySentError, fn -> put_view sent_conn, Hello end end test "json/2" do conn = json(conn(:get, "/"), %{foo: :bar}) assert conn.resp_body == "{\"foo\":\"bar\"}" assert get_resp_content_type(conn) == "application/json" refute conn.halted end test "json/2 allows status injection on connection" do conn = conn(:get, "/") |> put_status(400) conn = json(conn, %{foo: :bar}) assert conn.resp_body == "{\"foo\":\"bar\"}" assert conn.status == 400 end test "json/2 allows content-type injection on connection" do conn = conn(:get, "/") |> put_resp_content_type("application/vnd.api+json") conn = json(conn, %{foo: :bar}) assert conn.resp_body == "{\"foo\":\"bar\"}" assert Conn.get_resp_header(conn, "content-type") == ["application/vnd.api+json; charset=utf-8"] end test "allow_jsonp/2 returns json when no callback param is present" do conn = conn(:get, "/") |> fetch_query_params |> allow_jsonp |> json(%{foo: "bar"}) assert conn.resp_body == "{\"foo\":\"bar\"}" assert get_resp_content_type(conn) == "application/json" refute conn.halted end test "allow_jsonp/2 returns json when callback name is left empty" do conn = conn(:get, "/?callback=") |> fetch_query_params |> allow_jsonp |> json(%{foo: "bar"}) assert conn.resp_body == "{\"foo\":\"bar\"}" assert get_resp_content_type(conn) == "application/json" refute conn.halted end test "allow_jsonp/2 returns javascript when callback param is present" do conn = conn(:get, "/?callback=cb") |> fetch_query_params |> allow_jsonp |> json(%{foo: "bar"}) assert conn.resp_body == "/**/ typeof cb === 'function' && cb({\"foo\":\"bar\"});" assert get_resp_content_type(conn) == "application/javascript" refute conn.halted end test "allow_jsonp/2 allows to override the callback param" do conn = conn(:get, "/?cb=cb") |> fetch_query_params |> allow_jsonp(callback: "cb") |> json(%{foo: "bar"}) assert conn.resp_body == "/**/ typeof cb === 'function' && cb({\"foo\":\"bar\"});" assert get_resp_content_type(conn) == "application/javascript" refute conn.halted end test "allow_jsonp/2 raises ArgumentError when callback contains invalid characters" do conn = conn(:get, "/?cb=_c*b!()[0]") |> fetch_query_params() assert_raise ArgumentError, "the JSONP callback name contains invalid characters", fn -> allow_jsonp(conn, callback: "cb") end end test "allow_jsonp/2 escapes invalid javascript characters" do conn = conn(:get, "/?cb=cb") |> fetch_query_params |> allow_jsonp(callback: "cb") |> json(%{foo: <<0x2028::utf8, 0x2029::utf8>>}) assert conn.resp_body == "/**/ typeof cb === 'function' && cb({\"foo\":\"\\u2028\\u2029\"});" assert get_resp_content_type(conn) == "application/javascript" refute conn.halted end test "text/2" do conn = text(conn(:get, "/"), "foobar") assert conn.resp_body == "foobar" assert get_resp_content_type(conn) == "text/plain" refute conn.halted conn = text(conn(:get, "/"), :foobar) assert conn.resp_body == "foobar" assert get_resp_content_type(conn) == "text/plain" refute conn.halted end test "text/2 allows status injection on connection" do conn = conn(:get, "/") |> put_status(400) conn = text(conn, :foobar) assert conn.resp_body == "foobar" assert conn.status == 400 end test "html/2" do conn = html(conn(:get, "/"), "foobar") assert conn.resp_body == "foobar" assert get_resp_content_type(conn) == "text/html" refute conn.halted end test "html/2 allows status injection on connection" do conn = conn(:get, "/") |> put_status(400) conn = html(conn, "foobar") assert conn.resp_body == "foobar" assert conn.status == 400 end test "redirect/2 with :to" do conn = redirect(conn(:get, "/"), to: "/foobar") assert conn.resp_body =~ "/foobar" assert get_resp_content_type(conn) == "text/html" assert get_resp_header(conn, "location") == ["/foobar"] refute conn.halted conn = redirect(conn(:get, "/"), to: "/<foobar>") assert conn.resp_body =~ "/&lt;foobar&gt;" assert_raise ArgumentError, ~r/the :to option in redirect expects a path/, fn -> redirect(conn(:get, "/"), to: "http://example.com") end assert_raise ArgumentError, ~r/the :to option in redirect expects a path/, fn -> redirect(conn(:get, "/"), to: "//example.com") end end test "redirect/2 with :external" do conn = redirect(conn(:get, "/"), external: "http://example.com") assert conn.resp_body =~ "http://example.com" assert get_resp_header(conn, "location") == ["http://example.com"] refute conn.halted end test "redirect/2 with put_status/2 uses previously set status or defaults to 302" do conn = conn(:get, "/") |> redirect(to: "/") assert conn.status == 302 conn = conn(:get, "/") |> put_status(301) |> redirect(to: "/") assert conn.status == 301 end defp with_accept(header) do conn(:get, "/", []) |> put_req_header("accept", header) end test "accepts/2 uses params[\"_format\"] when available" do conn = accepts conn(:get, "/", _format: "json"), ~w(json) assert get_format(conn) == "json" assert conn.params["_format"] == "json" conn = accepts conn(:get, "/", _format: "json"), ~w(html) assert conn.status == 406 assert conn.halted end test "accepts/2 uses first accepts on empty or catch-all header" do conn = accepts conn(:get, "/", []), ~w(json) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("*/*"), ~w(json) assert get_format(conn) == "json" assert conn.params["_format"] == nil end test "accepts/2 on non-empty */*" do # Fallbacks to HTML due to browsers behavior conn = accepts with_accept("application/json, */*"), ~w(html json) assert get_format(conn) == "html" assert conn.params["_format"] == nil conn = accepts with_accept("*/*, application/json"), ~w(html json) assert get_format(conn) == "html" assert conn.params["_format"] == nil # No HTML is treated normally conn = accepts with_accept("*/*, text/plain, application/json"), ~w(json text) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("text/plain, application/json, */*"), ~w(json text) assert get_format(conn) == "text" assert conn.params["_format"] == nil end test "accepts/2 ignores invalid media types" do conn = accepts with_accept("foo/bar, bar baz, application/json"), ~w(html json) assert get_format(conn) == "json" assert conn.params["_format"] == nil end test "accepts/2 considers q params" do conn = accepts with_accept("text/html; q=0.7, application/json"), ~w(html json) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("application/json, text/html; q=0.7"), ~w(html json) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("application/json; q=1.0, text/html; q=0.7"), ~w(html json) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("application/json; q=0.8, text/html; q=0.7"), ~w(html json) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("text/html; q=0.7, application/json; q=0.8"), ~w(html json) assert get_format(conn) == "json" assert conn.params["_format"] == nil conn = accepts with_accept("text/html; q=0.7, application/json; q=0.8"), ~w(xml) assert conn.halted assert conn.status == 406 end test "scrub_params/2 raises Phoenix.MissingParamError for missing key" do assert_raise(Phoenix.MissingParamError, ~r"expected key \"foo\" to be present in params", fn -> conn(:get, "/") |> fetch_query_params |> scrub_params("foo") end) assert_raise(Phoenix.MissingParamError, ~r"expected key \"foo\" to be present in params", fn -> conn(:get, "/?foo=") |> fetch_query_params |> scrub_params("foo") end) end test "scrub_params/2 keeps populated keys intact" do conn = conn(:get, "/?foo=bar") |> fetch_query_params |> scrub_params("foo") assert conn.params["foo"] == "bar" end test "scrub_params/2 nils out all empty values for the passed in key if it is a list" do conn = conn(:get, "/?foo[]=&foo[]=++&foo[]=bar") |> fetch_query_params |> scrub_params("foo") assert conn.params["foo"] == [nil, nil, "bar"] end test "scrub_params/2 nils out all empty keys in value for the passed in key if it is a map" do conn = conn(:get, "/?foo[bar]=++&foo[baz]=&foo[bat]=ok") |> fetch_query_params |> scrub_params("foo") assert conn.params["foo"] == %{"bar" => nil, "baz" => nil, "bat" => "ok"} end test "scrub_params/2 nils out all empty keys in value for the passed in key if it is a nested map" do conn = conn(:get, "/?foo[bar][baz]=") |> fetch_query_params |> scrub_params("foo") assert conn.params["foo"] == %{"bar" => %{"baz" => nil}} end test "scrub_params/2 ignores the keys that don't match the passed in key" do conn = conn(:get, "/?foo=bar&baz=") |> fetch_query_params |> scrub_params("foo") assert conn.params["baz"] == "" end test "scrub_params/2 keeps structs intact" do conn = conn(:get, "/", %{"foo" => %{"bar" => %Plug.Upload{}}}) |> fetch_query_params |> scrub_params("foo") assert conn.params["foo"]["bar"] == %Plug.Upload{} end test "protect_from_forgery/2 doesn't blow up" do conn(:get, "/") |> with_session |> protect_from_forgery([]) assert is_binary get_csrf_token assert is_binary delete_csrf_token end test "put_secure_browser_headers/2" do conn = conn(:get, "/") |> put_secure_browser_headers() assert get_resp_header(conn, "x-frame-options") == ["SAMEORIGIN"] assert get_resp_header(conn, "x-xss-protection") == ["1; mode=block"] assert get_resp_header(conn, "x-content-type-options") == ["nosniff"] end test "__view__ returns the view module based on controller module" do assert Phoenix.Controller.__view__(MyApp.UserController) == MyApp.UserView assert Phoenix.Controller.__view__(MyApp.Admin.UserController) == MyApp.Admin.UserView end test "__layout__ returns the layout modoule based on controller module" do assert Phoenix.Controller.__layout__(UserController, []) == LayoutView assert Phoenix.Controller.__layout__(MyApp.UserController, []) == MyApp.LayoutView assert Phoenix.Controller.__layout__(MyApp.Admin.UserController, []) == MyApp.LayoutView assert Phoenix.Controller.__layout__(MyApp.Admin.UserController, namespace: MyApp.Admin) == MyApp.Admin.LayoutView end defp sent_conn do conn(:get, "/") |> send_resp(:ok, "") end end
32.995338
103
0.639774
734ea473ced978ff556c4bd1ff22815e6a186aef
272
ex
Elixir
lib/ecto_crdt_types/types/state/gmap.ex
ExpressApp/ecto_crdt_types
cf18557cf888b3d50a44640997507cff6caf2b93
[ "MIT" ]
8
2018-09-20T13:05:16.000Z
2021-09-22T08:40:40.000Z
lib/ecto_crdt_types/types/state/gmap.ex
ExpressApp/ecto_crdt_types
cf18557cf888b3d50a44640997507cff6caf2b93
[ "MIT" ]
null
null
null
lib/ecto_crdt_types/types/state/gmap.ex
ExpressApp/ecto_crdt_types
cf18557cf888b3d50a44640997507cff6caf2b93
[ "MIT" ]
null
null
null
defmodule EctoCrdtTypes.Types.State.GMap do @moduledoc """ GMap CRDT: grow only map. Modeled as a dictionary where keys can be anything and the values are join-semilattices. """ @crdt_type :state_gmap @crdt_value_type :map use EctoCrdtTypes.Types.CRDT end
24.727273
60
0.75
734ee661d62020643ea87fc6fb1fe8a94f7109a7
69,987
exs
Elixir
test/ecto/changeset_test.exs
esl-ktec/ecto
93173a223a8bb61bce652c17484535f13c3c10bb
[ "Apache-2.0" ]
null
null
null
test/ecto/changeset_test.exs
esl-ktec/ecto
93173a223a8bb61bce652c17484535f13c3c10bb
[ "Apache-2.0" ]
null
null
null
test/ecto/changeset_test.exs
esl-ktec/ecto
93173a223a8bb61bce652c17484535f13c3c10bb
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.ChangesetTest do use ExUnit.Case, async: true import Ecto.Changeset defmodule SocialSource do use Ecto.Schema @primary_key false embedded_schema do field :origin field :url end def changeset(schema \\ %SocialSource{}, params) do cast(schema, params, ~w(origin url)a) end end defmodule Category do use Ecto.Schema schema "categories" do field :name, :string has_many :posts, Ecto.ChangesetTest.Post end end defmodule Comment do use Ecto.Schema schema "comments" do belongs_to :post, Ecto.ChangesetTest.Post end end defmodule Post do use Ecto.Schema schema "posts" do field :token, :integer, primary_key: true field :title, :string, default: "" field :body field :uuid, :binary_id field :color, :binary field :decimal, :decimal field :upvotes, :integer, default: 0 field :topics, {:array, :string} field :virtual, :string, virtual: true field :published_at, :naive_datetime field :source, :map field :permalink, :string, source: :url belongs_to :category, Ecto.ChangesetTest.Category, source: :cat_id has_many :comments, Ecto.ChangesetTest.Comment, on_replace: :delete has_one :comment, Ecto.ChangesetTest.Comment end end defmodule NoSchemaPost do defstruct [:title, :upvotes] end defp changeset(schema \\ %Post{}, params) do cast(schema, params, ~w(id token title body upvotes decimal color topics virtual)a) end defmodule CustomError do use Ecto.Type def type, do: :any def cast(_), do: {:error, message: "custom error message", reason: :foobar} def load(_), do: :error def dump(_), do: :error end defmodule CustomErrorWithType do use Ecto.Type def type, do: :any def cast(_), do: {:error, message: "custom error message", reason: :foobar, type: :some_type} def load(_), do: :error def dump(_), do: :error end defmodule CustomErrorWithoutMessage do use Ecto.Type def type, do: :any def cast(_), do: {:error, reason: :foobar} def load(_), do: :error def dump(_), do: :error end defmodule CustomErrorTest do use Ecto.Schema schema "custom_error" do field :custom_error, CustomError field :custom_error_without_message, CustomErrorWithoutMessage field :custom_error_with_type, CustomErrorWithType field :array_custom_error, {:array, CustomError} field :map_custom_error, {:map, CustomError} end end ## cast/4 test "cast/4: with valid string keys" do params = %{"title" => "hello", "body" => "world"} struct = %Post{} changeset = cast(struct, params, ~w(title body)a) assert changeset.params == params assert changeset.data == struct assert changeset.changes == %{title: "hello", body: "world"} assert changeset.errors == [] assert validations(changeset) == [] assert changeset.required == [] assert changeset.valid? end test "cast/4: with valid atom keys" do params = %{title: "hello", body: "world"} struct = %Post{} changeset = cast(struct, params, ~w(title body)a) assert changeset.params == %{"title" => "hello", "body" => "world"} assert changeset.data == struct assert changeset.changes == %{title: "hello", body: "world"} assert changeset.errors == [] assert validations(changeset) == [] assert changeset.required == [] assert changeset.valid? end test "cast/4: with empty values" do params = %{"title" => "", "body" => nil} struct = %Post{title: "foo", body: "bar"} changeset = cast(struct, params, ~w(title body)a) assert changeset.changes == %{title: "", body: nil} end test "cast/4: with custom empty values" do params = %{"title" => "empty", "body" => nil} struct = %Post{title: "foo", body: "bar"} changeset = cast(struct, params, ~w(title body)a, empty_values: ["empty"]) assert changeset.changes == %{title: "", body: nil} assert changeset.empty_values == [""] end test "cast/4: with matching empty values" do params = %{"title" => "", "body" => nil} struct = %Post{title: "", body: nil} changeset = cast(struct, params, ~w(title body)a) assert changeset.changes == %{} end test "cast/4: with data and types" do data = {%{title: "hello"}, %{title: :string, upvotes: :integer}} params = %{"title" => "world", "upvotes" => "0"} changeset = cast(data, params, ~w(title upvotes)a) assert changeset.params == params assert changeset.data == %{title: "hello"} assert changeset.changes == %{title: "world", upvotes: 0} assert changeset.errors == [] assert changeset.valid? assert apply_changes(changeset) == %{title: "world", upvotes: 0} end test "cast/4: with data struct and types" do data = {%NoSchemaPost{title: "hello"}, %{title: :string, upvotes: :integer}} params = %{"title" => "world", "upvotes" => "0"} changeset = cast(data, params, ~w(title upvotes)a) assert changeset.params == params assert changeset.data == %NoSchemaPost{title: "hello"} assert changeset.changes == %{title: "world", upvotes: 0} assert changeset.errors == [] assert changeset.valid? assert apply_changes(changeset) == %NoSchemaPost{title: "world", upvotes: 0} end test "cast/4: with dynamic embed" do data = { %{ title: "hello" }, %{ title: :string, source: { :embed, %Ecto.Embedded{ cardinality: :one, field: :source, on_cast: &SocialSource.changeset(&1, &2), on_replace: :raise, owner: nil, related: SocialSource, unique: true } } } } params = %{"title" => "world", "source" => %{"origin" => "facebook", "url" => "http://example.com/social"}} changeset = data |> cast(params, ~w(title)a) |> cast_embed(:source, required: true) assert changeset.params == params assert changeset.data == %{title: "hello"} assert %{title: "world", source: %Ecto.Changeset{}} = changeset.changes assert changeset.errors == [] assert changeset.valid? assert apply_changes(changeset) == %{title: "world", source: %Ecto.ChangesetTest.SocialSource{origin: "facebook", url: "http://example.com/social"}} end test "cast/4: with changeset" do base_changeset = cast(%Post{title: "valid"}, %{}, ~w(title)a) |> validate_required(:title) |> validate_length(:title, min: 3) |> unique_constraint(:title) # No changes changeset = cast(base_changeset, %{}, ~w()) assert changeset.valid? assert changeset.changes == %{} assert changeset.required == [:title] assert length(validations(changeset)) == 1 assert length(constraints(changeset)) == 1 # Value changes changeset = cast(changeset, %{body: "new body"}, ~w(body)a) assert changeset.valid? assert changeset.changes == %{body: "new body"} assert changeset.required == [:title] assert length(validations(changeset)) == 1 assert length(constraints(changeset)) == 1 # Nil changes changeset = cast(changeset, %{body: nil}, ~w(body)a) assert changeset.valid? assert changeset.changes == %{body: nil} assert changeset.required == [:title] assert length(validations(changeset)) == 1 assert length(constraints(changeset)) == 1 end test "cast/4: struct with :invalid parameters" do changeset = cast(%Post{}, :invalid, ~w(title body)a) assert changeset.data == %Post{} assert changeset.params == nil assert changeset.changes == %{} assert changeset.errors == [] assert validations(changeset) == [] refute changeset.valid? end test "cast/4: changeset with :invalid parameters" do changeset = cast(%Post{}, %{"title" => "sample"}, ~w(title)a) changeset = cast(changeset, :invalid, ~w(body)a) assert changeset.data == %Post{} assert changeset.params == %{"title" => "sample"} assert changeset.changes == %{title: "sample"} assert changeset.errors == [] assert validations(changeset) == [] refute changeset.valid? end test "cast/4: field is marked as invalid" do params = %{"body" => :world} struct = %Post{} changeset = cast(struct, params, ~w(body)a) assert changeset.changes == %{} assert changeset.errors == [body: {"is invalid", [type: :string, validation: :cast]}] refute changeset.valid? end test "cast/4: field has a custom invalid error message" do params = %{"custom_error" => :error} struct = %CustomErrorTest{} changeset = cast(struct, params, ~w(custom_error)a) assert changeset.errors == [custom_error: {"custom error message", [type: Ecto.ChangesetTest.CustomError, validation: :cast, reason: :foobar]}] refute changeset.valid? end test "cast/4: ignores the :type parameter in custom errors" do params = %{"custom_error_with_type" => :error} struct = %CustomErrorTest{} changeset = cast(struct, params, ~w(custom_error_with_type)a) assert changeset.errors == [custom_error_with_type: {"custom error message", [type: Ecto.ChangesetTest.CustomErrorWithType, validation: :cast, reason: :foobar]}] refute changeset.valid? end test "cast/4: field has a custom invalid error message without message" do params = %{"custom_error_without_message" => :error} struct = %CustomErrorTest{} changeset = cast(struct, params, ~w(custom_error_without_message)a) assert changeset.errors == [custom_error_without_message: {"is invalid", [type: Ecto.ChangesetTest.CustomErrorWithoutMessage, validation: :cast, reason: :foobar]}] refute changeset.valid? end test "cast/4: field has a custom invalid error message on an array field" do params = %{"array_custom_error" => [:error]} struct = %CustomErrorTest{} changeset = cast(struct, params, ~w(array_custom_error)a) assert changeset.errors == [array_custom_error: {"is invalid", [type: {:array, Ecto.ChangesetTest.CustomError}, validation: :cast]}] refute changeset.valid? end test "cast/4: field has a custom invalid error message on a map field" do params = %{"map_custom_error" => %{foo: :error}} struct = %CustomErrorTest{} changeset = cast(struct, params, ~w(map_custom_error)a) assert changeset.errors == [map_custom_error: {"is invalid", [type: {:map, Ecto.ChangesetTest.CustomError}, validation: :cast]}] refute changeset.valid? end test "cast/4: fails on invalid field" do assert_raise ArgumentError, ~r"unknown field `:unknown`", fn -> cast(%Post{}, %{}, ~w(unknown)a) end end test "cast/4: fails on bad arguments" do assert_raise Ecto.CastError, ~r"expected params to be a :map, got:", fn -> cast(%Post{}, %Post{}, ~w(unknown)a) end assert_raise Ecto.CastError, ~r"expected params to be a :map, got:", fn -> cast(%Post{}, "foo", ~w(unknown)a) end assert_raise Ecto.CastError, ~r"mixed keys", fn -> cast(%Post{}, %{"title" => "foo", title: "foo"}, ~w()) end assert_raise FunctionClauseError, fn -> cast(%Post{}, %{}, %{}) end assert_raise FunctionClauseError, fn -> cast(%Post{}, %{"title" => "foo"}, nil) end end test "cast/4: protects against atom injection" do assert_raise ArgumentError, fn -> cast(%Post{}, %{}, ~w(surely_never_saw_this_atom_before)a) end end test "cast/4: required field (via validate_required/2) of wrong type is marked as invalid" do params = %{"body" => :world} struct = %Post{} changeset = cast(struct, params, [:body]) |> validate_required([:body]) assert changeset.changes == %{} assert changeset.errors == [body: {"is invalid", [type: :string, validation: :cast]}] refute changeset.valid? end test "cast/4: does not validate types in data" do params = %{} struct = %Post{title: 100, decimal: "string"} changeset = cast(struct, params, ~w(title decimal)a) assert changeset.params == %{} assert changeset.data == struct assert changeset.changes == %{} assert changeset.errors == [] assert validations(changeset) == [] assert changeset.required == [] assert changeset.valid? end test "cast/4: semantic comparison" do changeset = cast(%Post{decimal: Decimal.new(1)}, %{decimal: "1.0"}, ~w(decimal)a) assert changeset.changes == %{} changeset = cast(%Post{decimal: Decimal.new(1)}, %{decimal: "1.1"}, ~w(decimal)a) assert changeset.changes == %{decimal: Decimal.new("1.1")} changeset = cast(%Post{decimal: nil}, %{decimal: nil}, ~w(decimal)a) assert changeset.changes == %{} {data, types} = {%{x: [Decimal.new(1)]}, %{x: {:array, :decimal}}} changeset = cast({data, types}, %{x: [Decimal.new("1.0")]}, ~w(x)a) assert changeset.changes == %{} changeset = cast({data, types}, %{x: [Decimal.new("1.1")]}, ~w(x)a) assert changeset.changes == %{x: [Decimal.new("1.1")]} changeset = cast({%{x: [nil]}, types}, %{x: [nil]}, ~w(x)a) assert changeset.changes == %{} {data, types} = {%{x: %{decimal: nil}}, %{x: {:map, :decimal}}} changeset = cast({data, types}, data, ~w(x)a) assert changeset.changes == %{} end ## Changeset functions test "merge/2: merges changes" do cs1 = cast(%Post{}, %{title: "foo"}, ~w(title)a) cs2 = cast(%Post{}, %{body: "bar"}, ~w(body)a) assert merge(cs1, cs2).changes == %{body: "bar", title: "foo"} cs1 = cast(%Post{}, %{title: "foo"}, ~w(title)a) cs2 = cast(%Post{}, %{title: "bar"}, ~w(title)a) changeset = merge(cs1, cs2) assert changeset.valid? assert changeset.params == %{"title" => "bar"} assert changeset.changes == %{title: "bar"} end test "merge/2: merges errors" do cs1 = cast(%Post{}, %{}, ~w(title)a) |> validate_required(:title) cs2 = cast(%Post{}, %{}, ~w(title body)a) |> validate_required([:title, :body]) changeset = merge(cs1, cs2) refute changeset.valid? assert changeset.errors == [title: {"can't be blank", [validation: :required]}, body: {"can't be blank", [validation: :required]}] end test "merge/2: merges validations" do cs1 = cast(%Post{}, %{title: "Title"}, ~w(title)a) |> validate_length(:title, min: 1, max: 10) cs2 = cast(%Post{}, %{body: "Body"}, ~w(body)a) |> validate_format(:body, ~r/B/) changeset = merge(cs1, cs2) assert changeset.valid? assert length(validations(changeset)) == 2 assert Enum.find(validations(changeset), &match?({:body, {:format, _}}, &1)) assert Enum.find(validations(changeset), &match?({:title, {:length, _}}, &1)) end test "merge/2: repo opts" do cs1 = %Post{} |> change() |> Map.put(:repo_opts, [a: 1, b: 2]) cs2 = %Post{} |> change() |> Map.put(:repo_opts, [b: 3, c: 4]) changeset = merge(cs1, cs2) assert changeset.repo_opts == [a: 1, b: 3, c: 4] end test "merge/2: merges constraints" do cs1 = cast(%Post{}, %{title: "Title"}, ~w(title)a) |> unique_constraint(:title) cs2 = cast(%Post{}, %{body: "Body"}, ~w(body)a) |> unique_constraint(:body) changeset = merge(cs1, cs2) assert changeset.valid? assert length(constraints(changeset)) == 2 end test "merge/2: merges parameters" do empty = cast(%Post{}, %{}, ~w(title)a) cs1 = cast(%Post{}, %{body: "foo"}, ~w(body)a) cs2 = cast(%Post{}, %{body: "bar"}, ~w(body)a) assert merge(cs1, cs2).params == %{"body" => "bar"} assert merge(cs1, empty).params == %{"body" => "foo"} assert merge(empty, cs2).params == %{"body" => "bar"} assert merge(empty, empty).params == %{} end test "merge/2: gives required fields precedence over optional ones" do cs1 = cast(%Post{}, %{}, ~w(title)a) |> validate_required(:title) cs2 = cast(%Post{}, %{}, ~w(title)a) changeset = merge(cs1, cs2) assert changeset.required == [:title] end test "merge/2: doesn't duplicate required or optional fields" do cs1 = cast(%Post{}, %{}, ~w(title body)a) |> validate_required([:title, :body]) cs2 = cast(%Post{}, %{}, ~w(body title)a) |> validate_required([:body, :title]) changeset = merge(cs1, cs2) assert Enum.sort(changeset.required) == [:body, :title] end test "merge/2: merges the :repo field when either one is nil" do changeset = merge(%Ecto.Changeset{repo: :foo}, %Ecto.Changeset{repo: nil}) assert changeset.repo == :foo changeset = merge(%Ecto.Changeset{repo: nil}, %Ecto.Changeset{repo: :bar}) assert changeset.repo == :bar end test "merge/2: merges the :action field when either one is nil" do changeset = merge(%Ecto.Changeset{action: :insert}, %Ecto.Changeset{repo: nil}) assert changeset.action == :insert changeset = merge(%Ecto.Changeset{action: nil}, %Ecto.Changeset{action: :update}) assert changeset.action == :update end test "merge/2: fails when the :data, :repo or :action field are not equal" do cs1 = cast(%Post{title: "foo"}, %{}, ~w(title)a) cs2 = cast(%Post{title: "bar"}, %{}, ~w(title)a) assert_raise ArgumentError, "different :data when merging changesets", fn -> merge(cs1, cs2) end assert_raise ArgumentError, "different repos (`:foo` and `:bar`) when merging changesets", fn -> merge(%Ecto.Changeset{repo: :foo}, %Ecto.Changeset{repo: :bar}) end assert_raise ArgumentError, "different actions (`:insert` and `:update`) when merging changesets", fn -> merge(%Ecto.Changeset{action: :insert}, %Ecto.Changeset{action: :update}) end end test "change/2 with a struct" do changeset = change(%Post{}) assert changeset.valid? assert changeset.data == %Post{} assert changeset.changes == %{} changeset = change(%Post{body: "bar"}, body: "bar") assert changeset.valid? assert changeset.data == %Post{body: "bar"} assert changeset.changes == %{} changeset = change(%Post{body: "bar"}, %{body: "bar", title: "foo"}) assert changeset.valid? assert changeset.data == %Post{body: "bar"} assert changeset.changes == %{title: "foo"} changeset = change(%Post{}, body: "bar") assert changeset.valid? assert changeset.data == %Post{} assert changeset.changes == %{body: "bar"} changeset = change(%Post{}, %{body: "bar"}) assert changeset.valid? assert changeset.data == %Post{} assert changeset.changes == %{body: "bar"} end test "change/2 with data and types" do datatypes = {%{title: "hello"}, %{title: :string}} changeset = change(datatypes) assert changeset.valid? assert changeset.data == %{title: "hello"} assert changeset.changes == %{} changeset = change(datatypes, title: "world") assert changeset.valid? assert changeset.data == %{title: "hello"} assert changeset.changes == %{title: "world"} assert apply_changes(changeset) == %{title: "world"} changeset = change(datatypes, title: "hello") assert changeset.valid? assert changeset.data == %{title: "hello"} assert changeset.changes == %{} assert apply_changes(changeset) == %{title: "hello"} end test "change/2 with a changeset" do base_changeset = cast(%Post{upvotes: 5}, %{title: "title"}, ~w(title)a) assert change(base_changeset) == base_changeset changeset = change(base_changeset, %{body: "body"}) assert changeset.changes == %{title: "title", body: "body"} changeset = change(base_changeset, %{title: "new title"}) assert changeset.changes == %{title: "new title"} changeset = change(base_changeset, title: "new title") assert changeset.changes == %{title: "new title"} changeset = change(base_changeset, body: nil) assert changeset.changes == %{title: "title"} changeset = change(base_changeset, %{upvotes: nil}) assert changeset.changes == %{title: "title", upvotes: nil} changeset = change(base_changeset, %{upvotes: 5}) assert changeset.changes == %{title: "title"} changeset = change(base_changeset, %{upvotes: 10}) assert changeset.changes == %{title: "title", upvotes: 10} changeset = change(base_changeset, %{title: "new title", upvotes: 5}) assert changeset.changes == %{title: "new title"} end test "change/2 semantic comparison" do post = %Post{decimal: Decimal.new("1.0")} changeset = change(post, decimal: Decimal.new(1)) assert changeset.changes == %{} end test "change/2 with unknown field" do post = %Post{} assert_raise ArgumentError, ~r"unknown field `:unknown`", fn -> change(post, unknown: Decimal.new(1)) end end test "change/2 with non-atom field" do post = %Post{} assert_raise ArgumentError, ~r"must be atoms, got: `\"bad\"`", fn -> change(post, %{"bad" => 42}) end end test "fetch_field/2" do changeset = changeset(%Post{body: "bar"}, %{"title" => "foo"}) assert fetch_field(changeset, :title) == {:changes, "foo"} assert fetch_field(changeset, :body) == {:data, "bar"} assert fetch_field(changeset, :other) == :error end test "fetch_field!/2" do changeset = changeset(%Post{body: "bar"}, %{"title" => "foo"}) assert fetch_field!(changeset, :title) == "foo" assert fetch_field!(changeset, :body) == "bar" assert_raise KeyError, ~r/key :other not found in/, fn -> fetch_field!(changeset, :other) end end test "get_field/3" do changeset = changeset(%Post{body: "bar"}, %{"title" => "foo"}) assert get_field(changeset, :title) == "foo" assert get_field(changeset, :body) == "bar" assert get_field(changeset, :body, "other") == "bar" assert get_field(changeset, :other) == nil assert get_field(changeset, :other, "other") == "other" end test "get_field/3 with associations" do post = %Post{comments: [%Comment{}]} changeset = change(post) |> put_assoc(:comments, []) assert get_field(changeset, :comments) == [] end test "fetch_change/2" do changeset = changeset(%{"title" => "foo", "body" => nil, "upvotes" => nil}) assert fetch_change(changeset, :title) == {:ok, "foo"} assert fetch_change(changeset, :body) == :error assert fetch_change(changeset, :upvotes) == {:ok, nil} end test "fetch_change!/2" do changeset = changeset(%{"title" => "foo", "body" => nil, "upvotes" => nil}) assert fetch_change!(changeset, :title) == "foo" assert_raise KeyError, "key :body not found in: %{title: \"foo\", upvotes: nil}", fn -> fetch_change!(changeset, :body) end assert fetch_change!(changeset, :upvotes) == nil end test "get_change/3" do changeset = changeset(%{"title" => "foo", "body" => nil, "upvotes" => nil}) assert get_change(changeset, :title) == "foo" assert get_change(changeset, :body) == nil assert get_change(changeset, :body, "other") == "other" assert get_change(changeset, :upvotes) == nil assert get_change(changeset, :upvotes, "other") == nil end test "update_change/3" do changeset = changeset(%{"title" => "foo"}) |> update_change(:title, & &1 <> "bar") assert changeset.changes.title == "foobar" changeset = changeset(%{"upvotes" => nil}) |> update_change(:upvotes, & &1 || 10) assert changeset.changes.upvotes == 10 changeset = changeset(%{}) |> update_change(:title, & &1 || "bar") assert changeset.changes == %{} changeset = changeset(%Post{title: "mytitle"}, %{title: "MyTitle"}) |> update_change(:title, &String.downcase/1) assert changeset.changes == %{} end test "put_change/3 and delete_change/2" do base_changeset = change(%Post{upvotes: 5}) changeset = put_change(base_changeset, :title, "foo") assert changeset.changes.title == "foo" changeset = delete_change(changeset, :title) assert changeset.changes == %{} changeset = put_change(base_changeset, :title, "bar") assert changeset.changes.title == "bar" changeset = put_change(base_changeset, :body, nil) assert changeset.changes == %{} changeset = put_change(base_changeset, :upvotes, 5) assert changeset.changes == %{} changeset = put_change(changeset, :upvotes, 10) assert changeset.changes.upvotes == 10 changeset = put_change(base_changeset, :upvotes, nil) assert changeset.changes.upvotes == nil end test "force_change/3" do changeset = change(%Post{upvotes: 5}) changeset = force_change(changeset, :title, "foo") assert changeset.changes.title == "foo" changeset = force_change(changeset, :title, "bar") assert changeset.changes.title == "bar" changeset = force_change(changeset, :upvotes, 5) assert changeset.changes.upvotes == 5 end test "apply_changes/1" do post = %Post{} assert post.title == "" changeset = changeset(post, %{"title" => "foo"}) changed_post = apply_changes(changeset) assert changed_post.__struct__ == post.__struct__ assert changed_post.title == "foo" end describe "apply_action/2" do test "valid changeset" do post = %Post{} assert post.title == "" changeset = changeset(post, %{"title" => "foo"}) assert changeset.valid? assert {:ok, changed_post} = apply_action(changeset, :update) assert changed_post.__struct__ == post.__struct__ assert changed_post.title == "foo" end test "invalid changeset" do changeset = %Post{} |> changeset(%{"title" => "foo"}) |> validate_length(:title, min: 10) refute changeset.valid? changeset_new_action = %Ecto.Changeset{changeset | action: :update} assert {:error, ^changeset_new_action} = apply_action(changeset, :update) end test "invalid action" do assert_raise ArgumentError, ~r/expected action to be an atom/, fn -> %Post{} |> changeset(%{}) |> apply_action("invalid_action") end end end describe "apply_action!/2" do test "valid changeset" do changeset = changeset(%Post{}, %{"title" => "foo"}) post = apply_action!(changeset, :update) assert post.title == "foo" end test "invalid changeset" do changeset = %Post{} |> changeset(%{"title" => "foo"}) |> validate_length(:title, min: 10) assert_raise Ecto.InvalidChangesetError, fn -> apply_action!(changeset, :update) end end end ## Validations test "add_error/3" do changeset = changeset(%{}) |> add_error(:foo, "bar") assert changeset.errors == [foo: {"bar", []}] changeset = changeset(%{}) |> add_error(:foo, "bar", additional: "information") assert changeset.errors == [foo: {"bar", [additional: "information"]}] end test "validate_change/3" do # When valid changeset = changeset(%{"title" => "hello"}) |> validate_change(:title, fn :title, "hello" -> [] end) assert changeset.valid? assert changeset.errors == [] # When invalid with binary changeset = changeset(%{"title" => "hello"}) |> validate_change(:title, fn :title, "hello" -> [title: "oops"] end) refute changeset.valid? assert changeset.errors == [title: {"oops", []}] # When invalid with tuple changeset = changeset(%{"title" => "hello"}) |> validate_change(:title, fn :title, "hello" -> [title: {"oops", type: "bar"}] end) refute changeset.valid? assert changeset.errors == [title: {"oops", type: "bar"}] # When missing changeset = changeset(%{}) |> validate_change(:title, fn :title, "hello" -> [title: "oops"] end) assert changeset.valid? assert changeset.errors == [] # When nil changeset = changeset(%{"title" => nil}) |> validate_change(:title, fn :title, "hello" -> [title: "oops"] end) assert changeset.valid? assert changeset.errors == [] # When virtual changeset = changeset(%{"virtual" => "hello"}) |> validate_change(:virtual, fn :virtual, "hello" -> [] end) assert changeset.valid? assert changeset.errors == [] # When unknown field assert_raise ArgumentError, ~r/unknown field :bad in/, fn -> changeset(%{"title" => "hello"}) |> validate_change(:bad, fn _, _ -> [] end) end end test "validate_change/4" do changeset = changeset(%{"title" => "hello"}) |> validate_change(:title, :oops, fn :title, "hello" -> [title: "oops"] end) refute changeset.valid? assert changeset.errors == [title: {"oops", []}] assert validations(changeset) == [title: :oops] changeset = changeset(%{}) |> validate_change(:title, :oops, fn :title, "hello" -> [title: "oops"] end) assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [title: :oops] end test "validate_required/2" do # When valid changeset = changeset(%{"title" => "hello", "body" => "something"}) |> validate_required(:title) assert changeset.valid? assert changeset.errors == [] # When missing changeset = changeset(%{}) |> validate_required(:title) refute changeset.valid? assert changeset.required == [:title] assert changeset.errors == [title: {"can't be blank", [validation: :required]}] # When nil changeset = changeset(%{title: nil, body: "\n"}) |> validate_required([:title, :body], message: "is blank") refute changeset.valid? assert changeset.required == [:title, :body] assert changeset.changes == %{} assert changeset.errors == [title: {"is blank", [validation: :required]}, body: {"is blank", [validation: :required]}] # When :trim option is false changeset = changeset(%{title: " "}) |> validate_required(:title, trim: false) assert changeset.valid? assert changeset.errors == [] changeset = changeset(%{color: <<12, 12, 12>>}) |> validate_required(:color, trim: false) assert changeset.valid? assert changeset.errors == [] # When unknown field assert_raise ArgumentError, ~r/unknown field :bad in/, fn -> changeset(%{"title" => "hello", "body" => "something"}) |> validate_required(:bad) end # When field is not an atom assert_raise ArgumentError, ~r/expects field names to be atoms, got: `"title"`/, fn -> changeset(%{"title" => "hello"}) |> validate_required("title") end # When field is nil assert_raise FunctionClauseError, fn -> changeset(%{"title" => "hello"}) |> validate_required(nil) end end test "validate_format/3" do changeset = changeset(%{"title" => "foo@bar"}) |> validate_format(:title, ~r/@/) assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [title: {:format, ~r/@/}] changeset = changeset(%{"title" => "foobar"}) |> validate_format(:title, ~r/@/) refute changeset.valid? assert changeset.errors == [title: {"has invalid format", [validation: :format]}] assert validations(changeset) == [title: {:format, ~r/@/}] changeset = changeset(%{"title" => "foobar"}) |> validate_format(:title, ~r/@/, message: "yada") assert changeset.errors == [title: {"yada", [validation: :format]}] end test "validate_inclusion/3" do changeset = changeset(%{"title" => "hello"}) |> validate_inclusion(:title, ~w(hello)) assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [title: {:inclusion, ~w(hello)}] changeset = changeset(%{"title" => "hello"}) |> validate_inclusion(:title, ~w(world)) refute changeset.valid? assert changeset.errors == [title: {"is invalid", [validation: :inclusion, enum: ~w(world)]}] assert validations(changeset) == [title: {:inclusion, ~w(world)}] changeset = changeset(%{"title" => "hello"}) |> validate_inclusion(:title, ~w(world), message: "yada") assert changeset.errors == [title: {"yada", [validation: :inclusion, enum: ~w(world)]}] end test "validate_subset/3" do changeset = changeset(%{"topics" => ["cat", "dog"]}) |> validate_subset(:topics, ~w(cat dog)) assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [topics: {:subset, ~w(cat dog)}] changeset = changeset(%{"topics" => ["cat", "laptop"]}) |> validate_subset(:topics, ~w(cat dog)) refute changeset.valid? assert changeset.errors == [topics: {"has an invalid entry", [validation: :subset, enum: ~w(cat dog)]}] assert validations(changeset) == [topics: {:subset, ~w(cat dog)}] changeset = changeset(%{"topics" => ["laptop"]}) |> validate_subset(:topics, ~w(cat dog), message: "yada") assert changeset.errors == [topics: {"yada", [validation: :subset, enum: ~w(cat dog)]}] end test "validate_exclusion/3" do changeset = changeset(%{"title" => "world"}) |> validate_exclusion(:title, ~w(hello)) assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [title: {:exclusion, ~w(hello)}] changeset = changeset(%{"title" => "world"}) |> validate_exclusion(:title, ~w(world)) refute changeset.valid? assert changeset.errors == [title: {"is reserved", [validation: :exclusion, enum: ~w(world)]}] assert validations(changeset) == [title: {:exclusion, ~w(world)}] changeset = changeset(%{"title" => "world"}) |> validate_exclusion(:title, ~w(world), message: "yada") assert changeset.errors == [title: {"yada", [validation: :exclusion, enum: ~w(world)]}] end test "validate_length/3 with string" do changeset = changeset(%{"title" => "world"}) |> validate_length(:title, min: 3, max: 7) assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [title: {:length, [min: 3, max: 7]}] changeset = changeset(%{"title" => "world"}) |> validate_length(:title, min: 5, max: 5) assert changeset.valid? changeset = changeset(%{"title" => "world"}) |> validate_length(:title, is: 5) assert changeset.valid? changeset = changeset(%{"title" => "world"}) |> validate_length(:title, min: 6) refute changeset.valid? assert changeset.errors == [title: {"should be at least %{count} character(s)", count: 6, validation: :length, kind: :min, type: :string}] changeset = changeset(%{"title" => "world"}) |> validate_length(:title, max: 4) refute changeset.valid? assert changeset.errors == [title: {"should be at most %{count} character(s)", count: 4, validation: :length, kind: :max, type: :string}] changeset = changeset(%{"title" => "world"}) |> validate_length(:title, is: 10) refute changeset.valid? assert changeset.errors == [title: {"should be %{count} character(s)", count: 10, validation: :length, kind: :is, type: :string}] changeset = changeset(%{"title" => "world"}) |> validate_length(:title, is: 10, message: "yada") assert changeset.errors == [title: {"yada", count: 10, validation: :length, kind: :is, type: :string}] changeset = changeset(%{"title" => "\u0065\u0301"}) |> validate_length(:title, max: 1) assert changeset.valid? changeset = changeset(%{"title" => "\u0065\u0301"}) |> validate_length(:title, max: 1, count: :codepoints) refute changeset.valid? assert changeset.errors == [title: {"should be at most %{count} character(s)", count: 1, validation: :length, kind: :max, type: :string}] end test "validate_length/3 with binary" do changeset = changeset(%{"body" => <<0, 1, 2, 3>>}) |> validate_length(:body, count: :bytes, min: 3, max: 7) assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [body: {:length, [count: :bytes, min: 3, max: 7]}] changeset = changeset(%{"body" => <<0, 1, 2, 3, 4>>}) |> validate_length(:body, count: :bytes, min: 5, max: 5) assert changeset.valid? changeset = changeset(%{"body" => <<0, 1, 2, 3, 4>>}) |> validate_length(:body, count: :bytes, is: 5) assert changeset.valid? changeset = changeset(%{"body" => <<0, 1, 2, 3, 4>>}) |> validate_length(:body, count: :bytes, min: 6) refute changeset.valid? assert changeset.errors == [ body: {"should be at least %{count} byte(s)", count: 6, validation: :length, kind: :min, type: :binary} ] changeset = changeset(%{"body" => <<0, 1, 2, 3, 4>>}) |> validate_length(:body, count: :bytes, max: 4) refute changeset.valid? assert changeset.errors == [ body: {"should be at most %{count} byte(s)", count: 4, validation: :length, kind: :max, type: :binary} ] changeset = changeset(%{"body" => <<0, 1, 2, 3, 4>>}) |> validate_length(:body, count: :bytes, is: 10) refute changeset.valid? assert changeset.errors == [ body: {"should be %{count} byte(s)", count: 10, validation: :length, kind: :is, type: :binary} ] changeset = changeset(%{"body" => <<0, 1, 2, 3, 4>>}) |> validate_length(:body, count: :bytes, is: 10, message: "yada") assert changeset.errors == [body: {"yada", count: 10, validation: :length, kind: :is, type: :binary}] end test "validate_length/3 with list" do changeset = changeset(%{"topics" => ["Politics", "Security", "Economy", "Elections"]}) |> validate_length(:topics, min: 3, max: 7) assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [topics: {:length, [min: 3, max: 7]}] changeset = changeset(%{"topics" => ["Politics", "Security"]}) |> validate_length(:topics, min: 2, max: 2) assert changeset.valid? changeset = changeset(%{"topics" => ["Politics", "Security", "Economy"]}) |> validate_length(:topics, is: 3) assert changeset.valid? changeset = changeset(%{"topics" => ["Politics", "Security"]}) |> validate_length(:topics, min: 6, foo: true) refute changeset.valid? assert changeset.errors == [topics: {"should have at least %{count} item(s)", count: 6, validation: :length, kind: :min, type: :list}] changeset = changeset(%{"topics" => ["Politics", "Security", "Economy"]}) |> validate_length(:topics, max: 2) refute changeset.valid? assert changeset.errors == [topics: {"should have at most %{count} item(s)", count: 2, validation: :length, kind: :max, type: :list}] changeset = changeset(%{"topics" => ["Politics", "Security"]}) |> validate_length(:topics, is: 10) refute changeset.valid? assert changeset.errors == [topics: {"should have %{count} item(s)", count: 10, validation: :length, kind: :is, type: :list}] changeset = changeset(%{"topics" => ["Politics", "Security"]}) |> validate_length(:topics, is: 10, message: "yada") assert changeset.errors == [topics: {"yada", count: 10, validation: :length, kind: :is, type: :list}] end test "validate_length/3 with associations" do post = %Post{comments: [%Comment{id: 1}]} changeset = change(post) |> put_assoc(:comments, []) |> validate_length(:comments, min: 1) assert changeset.errors == [comments: {"should have at least %{count} item(s)", count: 1, validation: :length, kind: :min, type: :list}] changeset = change(post) |> put_assoc(:comments, [%Comment{id: 2}, %Comment{id: 3}]) |> validate_length(:comments, max: 2) assert changeset.valid? end test "validate_number/3" do changeset = changeset(%{"upvotes" => 3}) |> validate_number(:upvotes, greater_than: 0) assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [upvotes: {:number, [greater_than: 0]}] # Single error changeset = changeset(%{"upvotes" => -1}) |> validate_number(:upvotes, greater_than: 0) refute changeset.valid? assert changeset.errors == [upvotes: {"must be greater than %{number}", validation: :number, kind: :greater_than, number: 0}] assert validations(changeset) == [upvotes: {:number, [greater_than: 0]}] # Non equality error changeset = changeset(%{"upvotes" => 1}) |> validate_number(:upvotes, not_equal_to: 1) refute changeset.valid? assert changeset.errors == [upvotes: {"must be not equal to %{number}", validation: :number, kind: :not_equal_to, number: 1}] assert validations(changeset) == [upvotes: {:number, [not_equal_to: 1]}] # Multiple validations changeset = changeset(%{"upvotes" => 3}) |> validate_number(:upvotes, greater_than: 0, less_than: 100) assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [upvotes: {:number, [greater_than: 0, less_than: 100]}] # Multiple validations with multiple errors changeset = changeset(%{"upvotes" => 3}) |> validate_number(:upvotes, greater_than: 100, less_than: 0) refute changeset.valid? assert changeset.errors == [upvotes: {"must be greater than %{number}", validation: :number, kind: :greater_than, number: 100}] # Multiple validations with custom message errors changeset = changeset(%{"upvotes" => 3}) |> validate_number(:upvotes, greater_than: 100, less_than: 0, message: "yada") assert changeset.errors == [upvotes: {"yada", validation: :number, kind: :greater_than, number: 100}] end test "validate_number/3 with decimal" do changeset = changeset(%{"decimal" => Decimal.new(1)}) |> validate_number(:decimal, greater_than: Decimal.new(-3)) assert changeset.valid? changeset = changeset(%{"decimal" => Decimal.new(-3)}) |> validate_number(:decimal, less_than: Decimal.new(1)) assert changeset.valid? changeset = changeset(%{"decimal" => Decimal.new(-1)}) |> validate_number(:decimal, equal_to: Decimal.new(-1)) assert changeset.valid? changeset = changeset(%{"decimal" => Decimal.new(0)}) |> validate_number(:decimal, not_equal_to: Decimal.new(-1)) assert changeset.valid? changeset = changeset(%{"decimal" => Decimal.new(-3)}) |> validate_number(:decimal, less_than_or_equal_to: Decimal.new(-1)) assert changeset.valid? changeset = changeset(%{"decimal" => Decimal.new(-3)}) |> validate_number(:decimal, less_than_or_equal_to: Decimal.new(-3)) assert changeset.valid? changeset = changeset(%{"decimal" => Decimal.new(-1)}) |> validate_number(:decimal, greater_than_or_equal_to: Decimal.new("-1.5")) assert changeset.valid? changeset = changeset(%{"decimal" => Decimal.new("1.5")}) |> validate_number(:decimal, greater_than_or_equal_to: Decimal.new("1.5")) assert changeset.valid? changeset = changeset(%{"decimal" => Decimal.new("4.9")}) |> validate_number(:decimal, greater_than_or_equal_to: 4.9) assert changeset.valid? changeset = changeset(%{"decimal" => Decimal.new(5)}) |> validate_number(:decimal, less_than: 4) refute changeset.valid? end test "validate_number/3 with bad options" do assert_raise ArgumentError, ~r"unknown option :min given to validate_number/3", fn -> validate_number(changeset(%{"upvotes" => 1}), :upvotes, min: Decimal.new("1.5")) end end test "validate_confirmation/3" do changeset = changeset(%{"title" => "title", "title_confirmation" => "title"}) |> validate_confirmation(:title) assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [{:title, {:confirmation, []}}] changeset = changeset(%{"title" => "title"}) |> validate_confirmation(:title) assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [{:title, {:confirmation, []}}] changeset = changeset(%{"title" => "title"}) |> validate_confirmation(:title, required: false) assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [{:title, {:confirmation, [required: false]}}] changeset = changeset(%{"title" => "title"}) |> validate_confirmation(:title, required: true) refute changeset.valid? assert changeset.errors == [title_confirmation: {"can't be blank", [validation: :required]}] assert validations(changeset) == [{:title, {:confirmation, [required: true]}}] changeset = changeset(%{"title" => "title", "title_confirmation" => nil}) |> validate_confirmation(:title) refute changeset.valid? assert changeset.errors == [title_confirmation: {"does not match confirmation", [validation: :confirmation]}] assert validations(changeset) == [{:title, {:confirmation, []}}] changeset = changeset(%{"title" => "title", "title_confirmation" => "not title"}) |> validate_confirmation(:title) refute changeset.valid? assert changeset.errors == [title_confirmation: {"does not match confirmation", [validation: :confirmation]}] assert validations(changeset) == [{:title, {:confirmation, []}}] changeset = changeset(%{"title" => "title", "title_confirmation" => "not title"}) |> validate_confirmation(:title, message: "doesn't match field below") refute changeset.valid? assert changeset.errors == [title_confirmation: {"doesn't match field below", [validation: :confirmation]}] assert validations(changeset) == [{:title, {:confirmation, [message: "doesn't match field below"]}}] # Skip when no parameter changeset = changeset(%{"title" => "title"}) |> validate_confirmation(:title, message: "password doesn't match") assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [{:title, {:confirmation, [message: "password doesn't match"]}}] # With casting changeset = changeset(%{"upvotes" => "1", "upvotes_confirmation" => "1"}) |> validate_confirmation(:upvotes) assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [{:upvotes, {:confirmation, []}}] # With blank change changeset = changeset(%{"password" => "", "password_confirmation" => "password"}) |> validate_confirmation(:password) refute changeset.valid? assert changeset.errors == [password_confirmation: {"does not match confirmation", [validation: :confirmation]}] # With missing change changeset = changeset(%{"password_confirmation" => "password"}) |> validate_confirmation(:password) refute changeset.valid? assert changeset.errors == [password_confirmation: {"does not match confirmation", [validation: :confirmation]}] # invalid params changeset = changeset(:invalid) |> validate_confirmation(:password) refute changeset.valid? assert changeset.errors == [] assert validations(changeset) == [] end test "validate_acceptance/3" do # accepted changeset = changeset(%{"terms_of_service" => "true"}) |> validate_acceptance(:terms_of_service) assert changeset.valid? assert changeset.errors == [] assert validations(changeset) == [terms_of_service: {:acceptance, []}] # not accepted changeset = changeset(%{"terms_of_service" => "false"}) |> validate_acceptance(:terms_of_service) refute changeset.valid? assert changeset.errors == [terms_of_service: {"must be accepted", [validation: :acceptance]}] assert validations(changeset) == [terms_of_service: {:acceptance, []}] changeset = changeset(%{"terms_of_service" => "other"}) |> validate_acceptance(:terms_of_service) refute changeset.valid? assert changeset.errors == [terms_of_service: {"must be accepted", [validation: :acceptance]}] assert validations(changeset) == [terms_of_service: {:acceptance, []}] # empty params changeset = changeset(%{}) |> validate_acceptance(:terms_of_service) refute changeset.valid? assert changeset.errors == [terms_of_service: {"must be accepted", [validation: :acceptance]}] assert validations(changeset) == [terms_of_service: {:acceptance, []}] # invalid params changeset = changeset(:invalid) |> validate_acceptance(:terms_of_service) refute changeset.valid? assert changeset.errors == [] assert validations(changeset) == [terms_of_service: {:acceptance, []}] # custom message changeset = changeset(%{}) |> validate_acceptance(:terms_of_service, message: "must be abided") refute changeset.valid? assert changeset.errors == [terms_of_service: {"must be abided", [validation: :acceptance]}] assert validations(changeset) == [terms_of_service: {:acceptance, [message: "must be abided"]}] end alias Ecto.TestRepo describe "unsafe_validate_unique/4" do setup do dup_result = {1, [true]} no_dup_result = {0, []} base_changeset = changeset(%Post{}, %{"title" => "Hello World", "body" => "hi"}) [dup_result: dup_result, no_dup_result: no_dup_result, base_changeset: base_changeset] end defmodule MockRepo do @moduledoc """ Allows tests to verify or refute that a query was run. """ def one(query, opts \\ []) do send(self(), [__MODULE__, function: :one, query: query, opts: opts]) end end test "validates the uniqueness of a single field", context do Process.put(:test_repo_all_results, context.dup_result) changeset = unsafe_validate_unique(context.base_changeset, :title, TestRepo) assert changeset.errors == [title: {"has already been taken", validation: :unsafe_unique, fields: [:title]}] Process.put(:test_repo_all_results, context.no_dup_result) changeset = unsafe_validate_unique(context.base_changeset, :title, TestRepo) assert changeset.valid? end test "validates the uniqueness of a combination of fields", context do Process.put(:test_repo_all_results, context.dup_result) changeset = unsafe_validate_unique(context.base_changeset, [:title, :body], TestRepo) assert changeset.errors == [ title: {"has already been taken", validation: :unsafe_unique, fields: [:title, :body]} ] Process.put(:test_repo_all_results, context.no_dup_result) changeset = unsafe_validate_unique(context.base_changeset, [:title, :body], TestRepo) assert changeset.valid? end test "does not validate uniqueness if there is any prior error on a field", context do Process.put(:test_repo_all_results, context.dup_result) changeset = context.base_changeset |> validate_length(:title, max: 3) |> unsafe_validate_unique(:title, TestRepo) refute changeset.valid? assert changeset.errors == [title: {"should be at most %{count} character(s)", [count: 3, validation: :length, kind: :max, type: :string]}] end test "does not validate uniqueness if there is any prior error on a combination of fields", context do Process.put(:test_repo_all_results, context.dup_result) changeset = context.base_changeset |> validate_length(:title, max: 3) |> unsafe_validate_unique([:title, :body], TestRepo) refute changeset.valid? assert changeset.errors == [title: {"should be at most %{count} character(s)", [count: 3, validation: :length, kind: :max, type: :string]}] end test "allows setting a custom error message", context do Process.put(:test_repo_all_results, context.dup_result) changeset = unsafe_validate_unique(context.base_changeset, [:title], TestRepo, message: "is taken") assert changeset.errors == [title: {"is taken", validation: :unsafe_unique, fields: [:title]}] end test "allows setting a custom error key", context do Process.put(:test_repo_all_results, context.dup_result) changeset = unsafe_validate_unique(context.base_changeset, [:title], TestRepo, message: "is taken", error_key: :foo) assert changeset.errors == [foo: {"is taken", validation: :unsafe_unique, fields: [:title]}] end test "accepts a prefix option" do body_change = changeset(%Post{title: "Hello World", body: "hi"}, %{body: "ho"}) unsafe_validate_unique(body_change, :body, MockRepo, prefix: "my_prefix") assert_receive [MockRepo, function: :one, query: %Ecto.Query{prefix: "my_prefix"}, opts: []] end test "accepts repo options" do body_change = changeset(%Post{title: "Hello World", body: "hi"}, %{body: "ho"}) unsafe_validate_unique(body_change, :body, MockRepo, repo_opts: [tenant_id: 1]) assert_receive [MockRepo, function: :one, query: %Ecto.Query{}, opts: [tenant_id: 1]] end test "only queries the db when necessary" do body_change = changeset(%Post{title: "Hello World", body: "hi"}, %{body: "ho"}) unsafe_validate_unique(body_change, :body, MockRepo) assert_receive [MockRepo, function: :one, query: %Ecto.Query{}, opts: []] unsafe_validate_unique(body_change, [:body, :title], MockRepo) assert_receive [MockRepo, function: :one, query: %Ecto.Query{}, opts: []] unsafe_validate_unique(body_change, :title, MockRepo) # no overlap between changed fields and those required to be unique refute_receive [MockRepo, function: :one, query: %Ecto.Query{}, opts: []] end end ## Locks defp prepared_changes(changeset) do Enum.reduce(changeset.prepare, changeset, & &1.(&2)).changes end test "optimistic_lock/3 with changeset with default incremeter" do changeset = changeset(%{}) |> optimistic_lock(:upvotes) assert changeset.filters == %{upvotes: 0} assert changeset.changes == %{} assert prepared_changes(changeset) == %{upvotes: 1} changeset = changeset(%Post{upvotes: 2}, %{upvotes: 1}) |> optimistic_lock(:upvotes) assert changeset.filters == %{upvotes: 1} assert changeset.changes == %{upvotes: 1} assert prepared_changes(changeset) == %{upvotes: 2} # Assert default increment will rollover to 1 when the current one is equal or greater than 2_147_483_647 changeset = changeset(%Post{upvotes: 2_147_483_647}, %{}) |> optimistic_lock(:upvotes) assert changeset.filters == %{upvotes: 2_147_483_647} assert changeset.changes == %{} assert prepared_changes(changeset) == %{upvotes: 1} changeset = changeset(%Post{upvotes: 3_147_483_647}, %{}) |> optimistic_lock(:upvotes) assert changeset.filters == %{upvotes: 3_147_483_647} assert changeset.changes == %{} assert prepared_changes(changeset) == %{upvotes: 1} changeset = changeset(%Post{upvotes: 2_147_483_647}, %{upvotes: 2_147_483_648}) |> optimistic_lock(:upvotes) assert changeset.filters == %{upvotes: 2_147_483_648} assert changeset.changes == %{upvotes: 2_147_483_648} assert prepared_changes(changeset) == %{upvotes: 1} end test "optimistic_lock/3 with struct" do changeset = %Post{} |> optimistic_lock(:upvotes) assert changeset.filters == %{upvotes: 0} assert changeset.changes == %{} assert prepared_changes(changeset) == %{upvotes: 1} end test "optimistic_lock/3 with custom incrementer" do changeset = %Post{} |> optimistic_lock(:upvotes, &(&1 - 1)) assert changeset.filters == %{upvotes: 0} assert changeset.changes == %{} assert prepared_changes(changeset) == %{upvotes: -1} end ## Constraints test "check_constraint/3" do changeset = change(%Post{}) |> check_constraint(:title, name: :title_must_be_short) assert constraints(changeset) == [%{type: :check, field: :title, constraint: "title_must_be_short", match: :exact, error_message: "is invalid", error_type: :check}] changeset = change(%Post{}) |> check_constraint(:title, name: :title_must_be_short, message: "cannot be more than 15 characters") assert constraints(changeset) == [%{type: :check, field: :title, constraint: "title_must_be_short", match: :exact, error_message: "cannot be more than 15 characters", error_type: :check}] assert_raise ArgumentError, ~r/invalid match type: :invalid/, fn -> change(%Post{}) |> check_constraint(:title, name: :whatever, match: :invalid, message: "match is invalid") end assert_raise ArgumentError, ~r/supply the name/, fn -> check_constraint(:title, message: "cannot be more than 15 characters") end end test "unique_constraint/3" do changeset = change(%Post{}) |> unique_constraint(:title) assert constraints(changeset) == [%{type: :unique, field: :title, constraint: "posts_title_index", match: :exact, error_message: "has already been taken", error_type: :unique}] changeset = change(%Post{}) |> unique_constraint(:title, name: :whatever, message: "is taken") assert constraints(changeset) == [%{type: :unique, field: :title, constraint: "whatever", match: :exact, error_message: "is taken", error_type: :unique}] changeset = change(%Post{}) |> unique_constraint(:title, name: :whatever, match: :suffix, message: "is taken") assert constraints(changeset) == [%{type: :unique, field: :title, constraint: "whatever", match: :suffix, error_message: "is taken", error_type: :unique}] changeset = change(%Post{}) |> unique_constraint(:title, name: :whatever, match: :prefix, message: "is taken") assert constraints(changeset) == [%{type: :unique, field: :title, constraint: "whatever", match: :prefix, error_message: "is taken", error_type: :unique}] assert_raise ArgumentError, ~r/invalid match type: :invalid/, fn -> change(%Post{}) |> unique_constraint(:title, name: :whatever, match: :invalid, message: "is taken") end end test "unique_constraint/3 on field with :source" do changeset = change(%Post{}) |> unique_constraint(:permalink) assert constraints(changeset) == [%{type: :unique, field: :permalink, constraint: "posts_url_index", match: :exact, error_message: "has already been taken", error_type: :unique}] changeset = change(%Post{}) |> unique_constraint(:permalink, name: :whatever, message: "is taken") assert constraints(changeset) == [%{type: :unique, field: :permalink, constraint: "whatever", match: :exact, error_message: "is taken", error_type: :unique}] changeset = change(%Post{}) |> unique_constraint(:permalink, name: :whatever, match: :suffix, message: "is taken") assert constraints(changeset) == [%{type: :unique, field: :permalink, constraint: "whatever", match: :suffix, error_message: "is taken", error_type: :unique}] assert_raise ArgumentError, ~r/invalid match type: :invalid/, fn -> change(%Post{}) |> unique_constraint(:permalink, name: :whatever, match: :invalid, message: "is taken") end end test "unique_constraint/3 with multiple fields" do changeset = change(%Post{}) |> unique_constraint([:permalink, :color]) assert constraints(changeset) == [%{type: :unique, field: :permalink, constraint: "posts_url_color_index", match: :exact, error_message: "has already been taken", error_type: :unique}] end test "foreign_key_constraint/3" do changeset = change(%Comment{}) |> foreign_key_constraint(:post_id) assert constraints(changeset) == [%{type: :foreign_key, field: :post_id, constraint: "comments_post_id_fkey", match: :exact, error_message: "does not exist", error_type: :foreign}] changeset = change(%Comment{}) |> foreign_key_constraint(:post_id, name: :whatever, message: "is not available") assert constraints(changeset) == [%{type: :foreign_key, field: :post_id, constraint: "whatever", match: :exact, error_message: "is not available", error_type: :foreign}] end test "foreign_key_constraint/3 on field with :source" do changeset = change(%Post{}) |> foreign_key_constraint(:permalink) assert constraints(changeset) == [%{type: :foreign_key, field: :permalink, constraint: "posts_url_fkey", match: :exact, error_message: "does not exist", error_type: :foreign}] changeset = change(%Post{}) |> foreign_key_constraint(:permalink, name: :whatever, message: "is not available") assert constraints(changeset) == [%{type: :foreign_key, field: :permalink, constraint: "whatever", match: :exact, error_message: "is not available", error_type: :foreign}] end test "assoc_constraint/3" do changeset = change(%Comment{}) |> assoc_constraint(:post) assert constraints(changeset) == [%{type: :foreign_key, field: :post, constraint: "comments_post_id_fkey", match: :exact, error_message: "does not exist", error_type: :assoc}] changeset = change(%Comment{}) |> assoc_constraint(:post, name: :whatever, message: "is not available") assert constraints(changeset) == [%{type: :foreign_key, field: :post, constraint: "whatever", match: :exact, error_message: "is not available", error_type: :assoc}] end test "assoc_constraint/3 on field with :source" do changeset = change(%Post{}) |> assoc_constraint(:category) assert constraints(changeset) == [%{type: :foreign_key, field: :category, constraint: "posts_category_id_fkey", match: :exact, error_message: "does not exist", error_type: :assoc}] changeset = change(%Post{}) |> assoc_constraint(:category, name: :whatever, message: "is not available") assert constraints(changeset) == [%{type: :foreign_key, field: :category, constraint: "whatever", match: :exact, error_message: "is not available", error_type: :assoc}] end test "assoc_constraint/3 with errors" do message = ~r"cannot add constraint to changeset because association `unknown` does not exist. Did you mean one of `category`, `comment`, `comments`?" assert_raise ArgumentError, message, fn -> change(%Post{}) |> assoc_constraint(:unknown) end message = ~r"assoc_constraint can only be added to belongs to associations" assert_raise ArgumentError, message, fn -> change(%Post{}) |> assoc_constraint(:comments) end end test "no_assoc_constraint/3 with has_many" do changeset = change(%Post{}) |> no_assoc_constraint(:comments) assert constraints(changeset) == [%{type: :foreign_key, field: :comments, constraint: "comments_post_id_fkey", match: :exact, error_message: "are still associated with this entry", error_type: :no_assoc}] changeset = change(%Post{}) |> no_assoc_constraint(:comments, name: :whatever, message: "exists") assert constraints(changeset) == [%{type: :foreign_key, field: :comments, constraint: "whatever", match: :exact, error_message: "exists", error_type: :no_assoc}] end test "no_assoc_constraint/3 with has_one" do changeset = change(%Post{}) |> no_assoc_constraint(:comment) assert constraints(changeset) == [%{type: :foreign_key, field: :comment, constraint: "comments_post_id_fkey", match: :exact, error_message: "is still associated with this entry", error_type: :no_assoc}] changeset = change(%Post{}) |> no_assoc_constraint(:comment, name: :whatever, message: "exists") assert constraints(changeset) == [%{type: :foreign_key, field: :comment, constraint: "whatever", match: :exact, error_message: "exists", error_type: :no_assoc}] end test "no_assoc_constraint/3 with errors" do message = ~r"cannot add constraint to changeset because association `unknown` does not exist" assert_raise ArgumentError, message, fn -> change(%Post{}) |> no_assoc_constraint(:unknown) end message = ~r"no_assoc_constraint can only be added to has one/many associations" assert_raise ArgumentError, message, fn -> change(%Comment{}) |> no_assoc_constraint(:post) end end test "exclusion_constraint/3" do changeset = change(%Post{}) |> exclusion_constraint(:title) assert constraints(changeset) == [%{type: :exclusion, field: :title, constraint: "posts_title_exclusion", match: :exact, error_message: "violates an exclusion constraint", error_type: :exclusion}] changeset = change(%Post{}) |> exclusion_constraint(:title, name: :whatever, message: "is invalid") assert constraints(changeset) == [%{type: :exclusion, field: :title, constraint: "whatever", match: :exact, error_message: "is invalid", error_type: :exclusion}] assert_raise ArgumentError, ~r/invalid match type: :invalid/, fn -> change(%Post{}) |> exclusion_constraint(:title, name: :whatever, match: :invalid, message: "match is invalid") end end ## traverse_errors test "traverses changeset errors" do changeset = changeset(%{"title" => "title", "body" => "hi", "upvotes" => :bad}) |> validate_length(:body, min: 3) |> validate_format(:body, ~r/888/) |> add_error(:title, "is taken", name: "your title") errors = traverse_errors(changeset, fn {"is invalid", [type: type, validation: :cast]} -> "expected to be #{inspect(type)}" {"is taken", keys} -> String.upcase("#{keys[:name]} is taken") {msg, keys} -> msg |> String.replace("%{count}", to_string(keys[:count])) |> String.upcase() end) assert errors == %{ body: ["HAS INVALID FORMAT", "SHOULD BE AT LEAST 3 CHARACTER(S)"], title: ["YOUR TITLE IS TAKEN"], upvotes: ["expected to be :integer"], } end test "traverses changeset errors with field" do changeset = changeset(%{"title" => "title", "body" => "hi", "upvotes" => :bad}) |> validate_length(:body, min: 3) |> validate_format(:body, ~r/888/) |> validate_inclusion(:body, ["hola", "bonjour", "hallo"]) |> add_error(:title, "is taken", name: "your title") errors = traverse_errors(changeset, fn %Ecto.Changeset{}, field, {_, [type: type, validation: :cast]} -> "expected #{field} to be #{inspect(type)}" %Ecto.Changeset{}, field, {_, [name: "your title"]} -> "value in #{field} is taken" |> String.upcase() %Ecto.Changeset{}, field, {_, [count: 3, validation: :length, kind: :min, type: :string] = keys} -> "should be at least #{keys[:count]} character(s) in field #{field}" |> String.upcase() %Ecto.Changeset{validations: validations}, field, {_, [validation: :format]} -> validation = Keyword.get_values(validations, field) "field #{field} should match format #{inspect validation[:format]}" %Ecto.Changeset{validations: validations}, field, {_, [validation: :inclusion, enum: _]} -> validation = Keyword.get_values(validations, field) values = Enum.join(validation[:inclusion], ", ") "#{field} value should be in #{values}" end) assert errors == %{ body: ["body value should be in hola, bonjour, hallo", "field body should match format ~r/888/", "SHOULD BE AT LEAST 3 CHARACTER(S) IN FIELD BODY"], title: ["VALUE IN TITLE IS TAKEN"], upvotes: ["expected upvotes to be :integer"], } end ## inspect defmodule RedactedSchema do use Ecto.Schema schema "redacted_schema" do field :password, :string, redact: true field :username, :string field :display_name, :string, redact: false field :virtual_pass, :string, redact: true, virtual: true end end describe "inspect" do test "reveals relevant data" do assert inspect(%Ecto.Changeset{}) == "#Ecto.Changeset<action: nil, changes: %{}, errors: [], data: nil, valid?: false>" assert inspect(changeset(%{"title" => "title", "body" => "hi"})) == "#Ecto.Changeset<action: nil, changes: %{body: \"hi\", title: \"title\"}, " <> "errors: [], data: #Ecto.ChangesetTest.Post<>, valid?: true>" data = {%NoSchemaPost{title: "hello"}, %{title: :string, upvotes: :integer}} params = %{"title" => "world", "upvotes" => "0"} assert inspect(cast(data, params, ~w(title upvotes)a)) == "#Ecto.Changeset<action: nil, changes: %{title: \"world\", upvotes: 0}, " <> "errors: [], data: #Ecto.ChangesetTest.NoSchemaPost<>, valid?: true>" end test "redacts fields marked redact: true" do changeset = Ecto.Changeset.cast(%RedactedSchema{}, %{password: "hunter2"}, [:password]) refute inspect(changeset) =~ "hunter2" assert inspect(changeset) =~ "**redacted**" end test "redacts virtual fields marked redact: true" do changeset = Ecto.Changeset.cast(%RedactedSchema{}, %{virtual_pass: "hunter2"}, [:virtual_pass]) refute inspect(changeset) =~ "hunter2" assert inspect(changeset) =~ "**redacted**" end test "doesn't redact fields without redacted (defaults to false)" do changeset = Ecto.Changeset.cast(%RedactedSchema{}, %{username: "hunter2"}, [:username]) assert inspect(changeset) =~ "hunter2" refute inspect(changeset) =~ "**redacted**" end test "doesn't redact fields marked redact: false" do changeset = Ecto.Changeset.cast(%RedactedSchema{}, %{display_name: "hunter2"}, [:display_name]) assert inspect(changeset) =~ "hunter2" refute inspect(changeset) =~ "**redacted**" end end end
38.349041
167
0.634646
734eecb649f13e98b6b927eb4220b79aa3cd4eb3
619
exs
Elixir
test/slackerton_chat/middlewares/mute_test.exs
matthewoden/slackerton
0604122884cf08087432f2e32d80eca42a878c37
[ "MIT" ]
1
2022-02-19T17:49:37.000Z
2022-02-19T17:49:37.000Z
test/slackerton_chat/middlewares/mute_test.exs
matthewoden/slackerton
0604122884cf08087432f2e32d80eca42a878c37
[ "MIT" ]
4
2018-07-14T16:30:17.000Z
2022-02-10T16:23:23.000Z
test/slackerton_chat/middlewares/mute_test.exs
matthewoden/slackerton
0604122884cf08087432f2e32d80eca42a878c37
[ "MIT" ]
null
null
null
defmodule SlackertonChat.Middleware.MutedTest do use ExUnit.Case alias SlackertonChat.Middleware.Muted test "it does not set muted on private if the user is muted" do msg = %{user: %{ id: "test", team: "team" }, private: %{} } state = %{ opts: [team: "test"]} assert Muted.call(msg, state) == { :next, msg, state} end test "it does not set muted on private if the user is muted" do msg = %{user: %{ id: "test", team: "team" }, private: %{} } state = %{ opts: [team: "test"]} {:halt, msg, state} = Muted.call(msg, state) assert %{ private: %{ "muted" => true } } = msg end end
32.578947
65
0.605816
734f1a45299cab4800661de8dc6aa4f351a19064
1,059
ex
Elixir
lib/os/configurator/fake_network_layer.ex
bahanni/custom_rpi4
ddefa85d30bacaae40151a63a9a0ebbf4ad30ed5
[ "MIT" ]
843
2016-10-05T23:46:05.000Z
2022-03-14T04:31:55.000Z
lib/os/configurator/fake_network_layer.ex
bahanni/custom_rpi4
ddefa85d30bacaae40151a63a9a0ebbf4ad30ed5
[ "MIT" ]
455
2016-10-15T08:49:16.000Z
2022-03-15T12:23:04.000Z
lib/os/configurator/fake_network_layer.ex
bahanni/custom_rpi4
ddefa85d30bacaae40151a63a9a0ebbf4ad30ed5
[ "MIT" ]
261
2016-10-10T04:37:06.000Z
2022-03-13T21:07:38.000Z
defmodule FarmbotOS.Configurator.FakeNetworkLayer do @moduledoc """ stub Configurator network layer """ @behaviour FarmbotOS.Configurator.NetworkLayer @impl FarmbotOS.Configurator.NetworkLayer def list_interfaces() do [ {"eth0", %{mac_address: "not real lol"}}, {"wlan0", %{mac_address: "even more not real"}} ] end @impl FarmbotOS.Configurator.NetworkLayer def scan(_ifname) do [ %{ ssid: "test psk", bssid: "de:ad:be:ef", level: 100, security: "WPA-PSK" }, %{ ssid: "test eap", bssid: "ca:fe:fo:od", level: 25, security: "WPA-EAP" }, %{ ssid: "test none", bssid: "ba:ad:fo:od", level: 50, security: "NONE" }, %{ ssid: "test none gray", bssid: "ba:df:oo:d1", level: 10, security: "NONE" }, %{ ssid: "test unknown yellow", bssid: "ba:df:oo:d2", level: 75, security: "UNKNOWN" } ] end end
20.365385
53
0.510859
734f5e4b95f38bd7dec5ac6c00ab4799708975b8
2,733
exs
Elixir
mix.exs
gissandrogama/blog
fedd7fbf908b11d651debdac2a040128a50ecd2f
[ "MIT" ]
null
null
null
mix.exs
gissandrogama/blog
fedd7fbf908b11d651debdac2a040128a50ecd2f
[ "MIT" ]
17
2021-04-22T00:58:05.000Z
2021-09-26T04:03:12.000Z
mix.exs
gissandrogama/blog
fedd7fbf908b11d651debdac2a040128a50ecd2f
[ "MIT" ]
null
null
null
defmodule Blog.MixProject do use Mix.Project @github_url "github.com:gissandrogama/blog.git" def project do [ app: :blog, version: "0.1.0", elixir: "~> 1.11", description: "projects to learn fundamentals in elixir and settings important", source_url: @github_url, homepage_url: @github_url, files: ~w(mix.exs lib LICENSE.md README.md CHANGELOG.md), package: [ maintainers: ["Gissandro Gama"], licenses: ["MIT"], links: %{ "GitHub" => @github_url } ], docs: [ main: "readme", extras: ["README.md", "CHANGELOG.md"] ], elixirc_paths: elixirc_paths(Mix.env()), compilers: [:phoenix, :gettext] ++ Mix.compilers(), start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps(), test_coverage: [tool: ExCoveralls], preferred_cli_env: [ coveralls: :test, "coveralls.detail": :test, "coveralls.post": :test, "coveralls.json": :test, "coveralls.html": :test ] ] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [ mod: {Blog.Application, []}, extra_applications: [:logger, :runtime_tools] ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Specifies your project dependencies. # # Type `mix help deps` for examples and options. defp deps do [ {:phoenix, "~> 1.5.4"}, {:phoenix_ecto, "~> 4.1"}, {:ecto_sql, "~> 3.4"}, {:postgrex, ">= 0.0.0"}, {:phoenix_html, "~> 2.11"}, {:phoenix_live_reload, "~> 1.2", only: :dev}, {:phoenix_live_dashboard, "~> 0.2"}, {:telemetry_metrics, "~> 0.4"}, {:telemetry_poller, "~> 0.4"}, {:gettext, "~> 0.11"}, {:jason, "~> 1.0"}, {:plug_cowboy, "~> 2.0"}, {:credo, "~> 1.5", only: [:dev, :test], runtime: false}, {:sobelow, "~> 0.8", only: :dev}, {:excoveralls, "~> 0.10", only: :test}, {:ueberauth_google, "~> 0.10"} ] end # Aliases are shortcuts or tasks specific to the current project. # For example, to install project dependencies and perform other setup tasks, run: # # $ mix setup # # See the documentation for `Mix` for more info on aliases. defp aliases do [ setup: ["deps.get", "ecto.setup", "cmd npm install --prefix assets"], "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], test: ["ecto.reset --quiet", "test"] ] end end
28.768421
85
0.564215
734f799f895b23080f9277473051ef0186fdeafe
82
exs
Elixir
test/ambrosia_web/views/page_view_test.exs
emeric-martineau/ambrosia
74c55d35cf66537d7c8a33ef6057e89d44abd347
[ "MIT" ]
2
2020-05-25T05:28:31.000Z
2020-05-25T08:10:43.000Z
test/ambrosia_web/views/page_view_test.exs
emeric-martineau/ambrosia
74c55d35cf66537d7c8a33ef6057e89d44abd347
[ "MIT" ]
9
2020-05-25T16:39:15.000Z
2020-11-11T16:51:37.000Z
test/ambrosia_web/views/page_view_test.exs
emeric-martineau/ambrosia
74c55d35cf66537d7c8a33ef6057e89d44abd347
[ "MIT" ]
null
null
null
defmodule AmbrosiaWeb.PageViewTest do use AmbrosiaWeb.ConnCase, async: true end
20.5
39
0.829268
734f7f4ed81798482d9df7ad2886d74b72b739aa
2,387
ex
Elixir
lib/pomaid/file_interface.ex
KTSCode/pomaid
9bb97f5cbffe7188dbcc19c86e2abc8c8237f485
[ "MIT" ]
1
2020-06-22T21:10:49.000Z
2020-06-22T21:10:49.000Z
lib/pomaid/file_interface.ex
KTSCode/pomaid
9bb97f5cbffe7188dbcc19c86e2abc8c8237f485
[ "MIT" ]
null
null
null
lib/pomaid/file_interface.ex
KTSCode/pomaid
9bb97f5cbffe7188dbcc19c86e2abc8c8237f485
[ "MIT" ]
null
null
null
defmodule Pomaid.FileInterface do @moduledoc """ File Interface: provides functions for reading and writing to files, specifically at todo.txt file and a done.txt file ! Warning ! many of the functions in this mondule contain side effects """ @doc "This function is pretty gross, try to think of a cleaner way to write it" def select_todo_file(path \\ "") do {:ok, files} = case path do "" -> File.ls() _ -> File.ls(String.trim(path)) end updated_path = case path do "" -> "" _ -> path <> "/" end cond do Enum.member?(files, "README.md") -> {:ok, updated_path <> "README.md"} Enum.member?(files, "todo.txt") -> {:ok, updated_path <> "todo.txt"} true -> {:error, "No todo.txt or README.md in path"} end end def read_todo_file(path) do case File.read(path) do {:error, e} -> {:error, e} {:ok, contents} -> cond do String.contains?(path, "README.md") -> {:ok, parse_readme(contents)} true -> {:ok, parse_todo_txt(contents)} end end end def read_done_file(path) do case File.read(path) do {:error, e} -> {:error, e} {:ok, contents} -> {:ok, contents} # cond do # String.contains?(path, "README.md") -> {:ok, parse_readme(contents)} # true -> {:ok, parse_todo_txt(contents)} # end end end @doc ~S""" Takes a raw todo.txt file and splits it by lines, trimming whitespace and removing blank lines ## Examples iex> Pomaid.FileInterface.parse_todo_txt("one\n two\n\n") ["one", "two"] """ def parse_todo_txt(raw_file_contents) do raw_file_contents |> String.split("\n") |> Enum.map(&String.trim/1) |> Enum.filter(&(&1 != "")) end @doc ~S""" Takes a raw README.md file and extract the TODO from it ## Examples iex> Pomaid.FileInterface.parse_readme("# README\n one\n two\n\n - [ ] task1\n - [ ] task 2\n\n") ["task1", "task 2"] """ def parse_readme(raw_file_contents) do raw_file_contents |> String.split("\n") |> Enum.map(&String.trim/1) |> Enum.filter(&(&1 != "")) |> Enum.filter(&String.starts_with?(&1, ["- [ ]", "-[ ]"])) |> Enum.map(&(String.split(&1, "] ") |> List.last())) end end
25.393617
109
0.55509
734fea0de4e0809f479b489164a0913fba9b00a4
2,141
ex
Elixir
clients/ad_exchange_seller/lib/google_api/ad_exchange_seller/v20/model/custom_channels.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/ad_exchange_seller/lib/google_api/ad_exchange_seller/v20/model/custom_channels.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/ad_exchange_seller/lib/google_api/ad_exchange_seller/v20/model/custom_channels.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.AdExchangeSeller.V20.Model.CustomChannels do @moduledoc """ ## Attributes - etag (String.t): ETag of this response for caching purposes. Defaults to: `null`. - items ([CustomChannel]): The custom channels returned in this list response. Defaults to: `null`. - kind (String.t): Kind of list this is, in this case adexchangeseller#customChannels. Defaults to: `null`. - nextPageToken (String.t): Continuation token used to page through custom channels. To retrieve the next page of results, set the next request&#39;s \&quot;pageToken\&quot; value to this. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :etag => any(), :items => list(GoogleApi.AdExchangeSeller.V20.Model.CustomChannel.t()), :kind => any(), :nextPageToken => any() } field(:etag) field(:items, as: GoogleApi.AdExchangeSeller.V20.Model.CustomChannel, type: :list) field(:kind) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.AdExchangeSeller.V20.Model.CustomChannels do def decode(value, options) do GoogleApi.AdExchangeSeller.V20.Model.CustomChannels.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AdExchangeSeller.V20.Model.CustomChannels do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.561404
211
0.733302
735004ab3b648a2a55bac9131a6e8696393b5741
1,107
exs
Elixir
config/dev.exs
shanesveller/ex_venture
68507da11442a9e0423073fcd305e9021f649ca1
[ "MIT" ]
null
null
null
config/dev.exs
shanesveller/ex_venture
68507da11442a9e0423073fcd305e9021f649ca1
[ "MIT" ]
null
null
null
config/dev.exs
shanesveller/ex_venture
68507da11442a9e0423073fcd305e9021f649ca1
[ "MIT" ]
null
null
null
use Mix.Config config :ex_venture, Data.Repo, adapter: Ecto.Adapters.Postgres, database: "ex_venture_dev", hostname: "localhost", pool_size: 10 config :ex_venture, Web.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, server: true, watchers: [ node: [ "node_modules/brunch/bin/brunch", "watch", "--stdin", cd: Path.expand("../assets", __DIR__) ] ] config :ex_venture, :networking, host: "localhost", port: {:system, "TELNET_PORT", 5555}, server: true, socket_module: Networking.Protocol config :ex_venture, :game, npc: Game.NPC, zone: Game.Zone, room: Game.Room, environment: Game.Environment, shop: Game.Shop, zone: Game.Zone, continue_wait: 500 config :logger, :level, :info config :logger, :console, format: "$time $metadata[$level] $levelpad$message\n", metadata: [:type] config :ex_venture, ExVenture.Mailer, adapter: Bamboo.LocalAdapter config :ex_venture, :mailer, from: "[email protected]" if File.exists?("config/dev.local.exs") do import_config("dev.local.exs") end
21.288462
66
0.682023
7350288f4d265d6522c779c41117e35dfbc3f730
1,441
ex
Elixir
test/support/live_views/events.ex
ohr486/phoenix_live_view
14a3e5a993de7767e38117852707c6c1feb1d485
[ "MIT" ]
null
null
null
test/support/live_views/events.ex
ohr486/phoenix_live_view
14a3e5a993de7767e38117852707c6c1feb1d485
[ "MIT" ]
null
null
null
test/support/live_views/events.ex
ohr486/phoenix_live_view
14a3e5a993de7767e38117852707c6c1feb1d485
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveViewTest.EventsLive do use Phoenix.LiveView, namespace: Phoenix.LiveViewTest def render(assigns) do ~L""" count: <%= @count %> """ end def mount(_params, _session, socket) do {:ok, assign(socket, events: [], count: 0)} end def handle_event("reply", %{"count" => new_count, "reply" => reply}, socket) do {:reply, reply, assign(socket, :count, new_count)} end def handle_event("reply", %{"reply" => reply}, socket) do {:reply, reply, socket} end def handle_call({:run, func}, _, socket), do: func.(socket) def handle_info({:run, func}, socket), do: func.(socket) end defmodule Phoenix.LiveViewTest.EventsInMountLive.Root do use Phoenix.LiveView, namespace: Phoenix.LiveViewTest def render(assigns) do ~L"<%= live_render @socket, Phoenix.LiveViewTest.EventsInMountLive.Child, id: :child_live %>" end def mount(_params, _session, socket) do socket = if connected?(socket), do: push_event(socket, "root-mount", %{root: "foo"}), else: socket {:ok, socket} end end defmodule Phoenix.LiveViewTest.EventsInMountLive.Child do use Phoenix.LiveView, namespace: Phoenix.LiveViewTest def render(assigns) do ~L"hello!" end def mount(_params, _session, socket) do socket = if connected?(socket), do: push_event(socket, "child-mount", %{child: "bar"}), else: socket {:ok, socket} end end
24.016667
97
0.657876
73503b182572808ae238bb0a7793f562aacd8706
1,820
ex
Elixir
lib/phoenix/pubsub/nats_conn.ex
netronixgroup/phoenix_pubsub_nats
6aec86fcc603f77c2fae3c0e9f1a543f6a5f375d
[ "MIT" ]
null
null
null
lib/phoenix/pubsub/nats_conn.ex
netronixgroup/phoenix_pubsub_nats
6aec86fcc603f77c2fae3c0e9f1a543f6a5f375d
[ "MIT" ]
null
null
null
lib/phoenix/pubsub/nats_conn.ex
netronixgroup/phoenix_pubsub_nats
6aec86fcc603f77c2fae3c0e9f1a543f6a5f375d
[ "MIT" ]
null
null
null
defmodule Phoenix.PubSub.NatsConn do use GenServer require Logger @reconnect_after_ms 500 @moduledoc """ Worker for pooled connections to NATS """ @doc """ Starts the server """ def start_link(opts) do GenServer.start_link(__MODULE__, opts) end def start_link(opts, name) do GenServer.start_link(__MODULE__, opts, name: name) end @doc false def init([opts]) do Process.flag(:trap_exit, true) send(self(), :connect) {:ok, %{opts: opts, status: :disconnected, conn: nil}} end def handle_call(:conn, _from, %{status: :connected, conn: conn} = status) do {:reply, {:ok, conn}, status} end def handle_call(:conn, _from, %{status: :disconnected} = status) do {:reply, {:error, :disconnected}, status} end def handle_info(:connect, state) do case Gnat.start_link(state.opts) do {:ok, pid} -> Logger.info "PubSub connected to Nats." {:noreply, %{state | conn: pid, status: :connected}} {:error, _reason} -> Logger.error "PubSub failed to connect to Nats. Attempting to reconnect..." :timer.send_after(@reconnect_after_ms, :connect) {:noreply, state} end end def handle_info({:EXIT, _ref, _reason}, %{status: :connected} = state) do Logger.error "PubSub lost Nats connection. Attempting to reconnect..." :timer.send_after(@reconnect_after_ms, :connect) {:noreply, %{state | conn: nil, status: :disconnected}} end def handle_info({:EXIT, _ref, _reason}, %{status: :disconnected} = state) do Logger.error "PubSub lost link while being disconnected." {:noreply, state} end def terminate(_reason, %{conn: pid, status: :connected}) do try do Gnat.stop(pid) catch _, _ -> :ok end end def terminate(_reason, _state) do :ok end end
26.376812
83
0.647802
7350439a54da51022f3f79986e9cb0cc5bf40a8c
2,240
ex
Elixir
lib/brando/cache/query.ex
brandocms/brando
4198e0c0920031bd909969055064e4e2b7230d21
[ "MIT" ]
4
2020-10-30T08:40:38.000Z
2022-01-07T22:21:37.000Z
lib/brando/cache/query.ex
brandocms/brando
4198e0c0920031bd909969055064e4e2b7230d21
[ "MIT" ]
1,162
2020-07-05T11:20:15.000Z
2022-03-31T06:01:49.000Z
lib/brando/cache/query.ex
brandocms/brando
4198e0c0920031bd909969055064e4e2b7230d21
[ "MIT" ]
null
null
null
defmodule Brando.Cache.Query do @moduledoc """ Interactions with query cache """ @type changeset :: Ecto.Changeset.t() @cache_module Application.get_env(:brando, :cache_module, Cachex) @spec get(any) :: any def get(key) do case get_from_cache(key) do {:ok, val} -> val {:error, _} -> nil end end def put(key, val, ttl \\ :timer.minutes(15)) def put(key, val, ttl), do: @cache_module.put(:query, key, val, ttl: ttl) def put({:single, src, hash}, val, ttl, id), do: @cache_module.put(:query, {:single, src, hash, id}, val, ttl: ttl) defp get_from_cache({:single, source, key}), do: find_single_entry(source, key) defp get_from_cache(key), do: @cache_module.get(:query, key) @spec evict({:ok, map()} | {:error, changeset}) :: {:ok, map()} | {:error, changeset} def evict({:ok, entry}) do source = entry.__struct__.__schema__(:source) perform_eviction(:list, source) perform_eviction(:single, source, entry.id) {:ok, entry} end def evict({:error, changeset}), do: {:error, changeset} # from insert!, update!, etc. def evict(entry) do source = entry.__struct__.__schema__(:source) perform_eviction(:list, source) perform_eviction(:single, source, entry.id) entry end @spec perform_eviction(:list, binary()) :: [:ok] defp perform_eviction(:list, schema) do ms = [{{:entry, {:list, schema, :_}, :_, :_, :_}, [], [:"$_"]}] :query |> Cachex.stream!(ms) |> Enum.map(fn {_, key, _, _, _} -> Cachex.del(:query, key) end) rescue Cachex.ExecutionError -> :ok end @spec perform_eviction(:single, binary(), integer()) :: [:ok] defp perform_eviction(:single, schema, id) do ms = [{{:entry, {:single, schema, :_, id}, :_, :_, :_}, [], [:"$_"]}] :query |> Cachex.stream!(ms) |> Enum.map(fn {_, key, _, _, _} -> Cachex.del(:query, key) end) rescue Cachex.ExecutionError -> :ok end defp find_single_entry(source, key) do ms = [{{:entry, {:single, source, key, :_}, :_, :_, :_}, [], [:"$_"]}] :query |> Cachex.stream!(ms) |> Enum.map(fn {_, _, _, _, entry} -> entry end) |> List.first() |> case do nil -> {:error, nil} entry -> {:ok, entry} end end end
28.717949
87
0.595089
73506267ff944387740aa7f5b705ad7ce643e4bc
517
ex
Elixir
server/lib/server_web/views/session_view.ex
Nymrinae/TimeManager
5048280da7c497909bca7faf7d2256c07438d442
[ "MIT" ]
null
null
null
server/lib/server_web/views/session_view.ex
Nymrinae/TimeManager
5048280da7c497909bca7faf7d2256c07438d442
[ "MIT" ]
null
null
null
server/lib/server_web/views/session_view.ex
Nymrinae/TimeManager
5048280da7c497909bca7faf7d2256c07438d442
[ "MIT" ]
null
null
null
defmodule ServerWeb.SessionView do use ServerWeb, :view def render("success.json", %{user: user, token: jwt }) do %{ status: :ok, user: %{ id: user.id, username: user.username, role: user.role }, token: jwt } end def render("success.json", %{message: message}) do %{ status: 200, message: message } end def render("error.json", %{message: message}) do %{ status: :bad_request, message: message } end end
17.233333
59
0.54352
73506f7a570ef807b6c6d4385aba28c740a5994e
1,393
ex
Elixir
lib/bubble_lib/xml/xmerl.ex
botsquad/bubble_lib
774860db5d19e94ad0f3d34618519d13cbe9cbfe
[ "MIT" ]
2
2018-09-25T19:35:00.000Z
2019-09-23T18:12:50.000Z
lib/bubble_lib/xml/xmerl.ex
botsquad/bubble_lib
774860db5d19e94ad0f3d34618519d13cbe9cbfe
[ "MIT" ]
null
null
null
lib/bubble_lib/xml/xmerl.ex
botsquad/bubble_lib
774860db5d19e94ad0f3d34618519d13cbe9cbfe
[ "MIT" ]
1
2019-09-23T18:12:53.000Z
2019-09-23T18:12:53.000Z
defmodule BubbleLib.XML.Xmerl do @moduledoc """ Convert 'plain' tuple notation into full XMerl XML notation """ use BubbleLib.XML.XmerlRecords def to_xmerl(content) when is_binary(content) do {doc, []} = content |> :binary.bin_to_list() |> :xmerl_scan.string(quiet: true) doc end def to_xmerl([_, _, _] = content) do content |> xmerl_element() end defp xmerl_element(value) when is_binary(value) do xmlText(value: value) end defp xmerl_element([name, attributes, content]) do xmlElement( name: atomize(name), attributes: xmerl_attributes(attributes), content: xmerl_content(content) ) end defp xmerl_attributes(nil), do: [] defp xmerl_attributes(attributes) do attributes |> Enum.map(fn {key, value} -> xmlAttribute(name: atomize(key), value: to_string(value)) end) end defp xmerl_content(nil), do: [] defp xmerl_content(value) when is_binary(value) do [xmlText(value: value)] end defp xmerl_content(content) when is_list(content) do content |> Enum.map(&xmerl_element/1) end def xmerl_to_string(e) do "<?xml version=\"1.0\"?>" <> xml = IO.chardata_to_string(:xmerl.export_simple([e], :xmerl_xml)) xml end defp atomize(name) when is_atom(name), do: name defp atomize(name) when is_binary(name), do: String.to_atom(name) end
22.111111
67
0.663317
7350aa00e2ac761beb48945f3abfe3020746b8e0
984
exs
Elixir
elixir/rna-transcription/rna_transcription_test.exs
esambo/exercism_solutions
520d9a5c28793c6fab2cb963b8c6de6c3404ac0b
[ "MIT" ]
1
2020-04-29T01:16:49.000Z
2020-04-29T01:16:49.000Z
elixir/rna-transcription/rna_transcription_test.exs
esambo/exorcism_solutions
520d9a5c28793c6fab2cb963b8c6de6c3404ac0b
[ "MIT" ]
null
null
null
elixir/rna-transcription/rna_transcription_test.exs
esambo/exorcism_solutions
520d9a5c28793c6fab2cb963b8c6de6c3404ac0b
[ "MIT" ]
null
null
null
if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("rna_transcription.exs", __DIR__) end ExUnit.start() ExUnit.configure(exclude: :pending, trace: true) defmodule RNATranscriptionTest do use ExUnit.Case test "transcribes guanine to cytosine" do assert RNATranscription.to_rna('G') == 'C' end test "transcribes cytosine to guanine" do assert RNATranscription.to_rna('C') == 'G' end test "transcribes thymidine to adenine" do assert RNATranscription.to_rna('T') == 'A' end test "transcribes adenine to uracil" do assert RNATranscription.to_rna('A') == 'U' end test "it transcribes some DNA nucleotides to RNA equivalents" do assert RNATranscription.to_rna('AC') == 'UG' end test "it transcribes doctest example" do assert RNATranscription.to_rna('ACTG') == 'UGAC' end test "it transcribes all DNA nucleotides to RNA equivalents" do assert RNATranscription.to_rna('ACGTGGTCTTAA') == 'UGCACCAGAAUU' end end
25.230769
68
0.723577
7350bf5dd4e6ee8c09b0556cd60ef0b0ef7eb6d4
7,730
ex
Elixir
clients/big_query_reservation/lib/google_api/big_query_reservation/v1/api/operations.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/big_query_reservation/lib/google_api/big_query_reservation/v1/api/operations.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/big_query_reservation/lib/google_api/big_query_reservation/v1/api/operations.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "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.BigQueryReservation.V1.Api.Operations do @moduledoc """ API calls for all endpoints tagged `Operations`. """ alias GoogleApi.BigQueryReservation.V1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. ## Parameters * `connection` (*type:* `GoogleApi.BigQueryReservation.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource to be deleted. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.BigQueryReservation.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec bigqueryreservation_operations_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.BigQueryReservation.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def bigqueryreservation_operations_delete(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.BigQueryReservation.V1.Model.Empty{}]) end @doc """ Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. To override the binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id. ## Parameters * `connection` (*type:* `GoogleApi.BigQueryReservation.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation's parent resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - The standard list filter. * `:pageSize` (*type:* `integer()`) - The standard list page size. * `:pageToken` (*type:* `String.t`) - The standard list page token. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.BigQueryReservation.V1.Model.ListOperationsResponse{}}` on success * `{:error, info}` on failure """ @spec bigqueryreservation_operations_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.BigQueryReservation.V1.Model.ListOperationsResponse.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def bigqueryreservation_operations_list(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.BigQueryReservation.V1.Model.ListOperationsResponse{}] ) end end
45.204678
196
0.645537
7350f8cbd424dc8f756011f994b2b0aa3eff1c00
2,716
ex
Elixir
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p2beta1_safe_search_annotation.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p2beta1_safe_search_annotation.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p2beta1_safe_search_annotation.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1SafeSearchAnnotation do @moduledoc """ Set of features pertaining to the image, computed by computer vision methods over safe-search verticals (for example, adult, spoof, medical, violence). ## Attributes * `adult` (*type:* `String.t`, *default:* `nil`) - Represents the adult content likelihood for the image. Adult content may contain elements such as nudity, pornographic images or cartoons, or sexual activities. * `medical` (*type:* `String.t`, *default:* `nil`) - Likelihood that this is a medical image. * `racy` (*type:* `String.t`, *default:* `nil`) - Likelihood that the request image contains racy content. Racy content may include (but is not limited to) skimpy or sheer clothing, strategically covered nudity, lewd or provocative poses, or close-ups of sensitive body areas. * `spoof` (*type:* `String.t`, *default:* `nil`) - Spoof likelihood. The likelihood that an modification was made to the image's canonical version to make it appear funny or offensive. * `violence` (*type:* `String.t`, *default:* `nil`) - Likelihood that this image contains violent content. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :adult => String.t(), :medical => String.t(), :racy => String.t(), :spoof => String.t(), :violence => String.t() } field(:adult) field(:medical) field(:racy) field(:spoof) field(:violence) end defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1SafeSearchAnnotation do def decode(value, options) do GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1SafeSearchAnnotation.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1SafeSearchAnnotation do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.205479
127
0.709867
7350fbca03d70f35a2df8d622d3cb67879e79206
2,312
ex
Elixir
lib/yourbot_web/components/bot_modal.ex
ConnorRigby/yourbot
eea40e63b0f93963ed14b7efab9ecbe898ab11dd
[ "Apache-2.0" ]
3
2021-11-08T15:19:19.000Z
2021-11-11T03:18:35.000Z
lib/yourbot_web/components/bot_modal.ex
ConnorRigby/yourbot
eea40e63b0f93963ed14b7efab9ecbe898ab11dd
[ "Apache-2.0" ]
null
null
null
lib/yourbot_web/components/bot_modal.ex
ConnorRigby/yourbot
eea40e63b0f93963ed14b7efab9ecbe898ab11dd
[ "Apache-2.0" ]
null
null
null
defmodule YourBotWeb.Components.BotModal do use Surface.Component alias SurfaceBulma.Button alias Surface.Components.{ Form, Form.ErrorTag, Form.Field, Form.Label, Form.TextInput, Form.NumberInput, Form.Submit } prop title, :string, required: true prop show, :boolean, required: true prop hide_event, :event, required: true prop changeset, :map, required: true def render(assigns) do ~F""" <div class={"modal", "is-active": @show}> <div class="modal-background" /> <div class="modal-card"> <header class="modal-card-head"> <p class="modal-card-title">{@title}</p> </header> <section class="modal-card-body"> These values should be coppied from your bot's settings page See <a href="https://discord.com/developers/applications"> here </a> for more details <Form for={@changeset} submit="save" change="change" opts={autocomplete: "off"}> <Field name={:name}> <Label/> <div class="control"> <TextInput opts={role: "bot_name_input"}/> </div> <ErrorTag class="help is-danger"/> </Field> <Field name={:token}> <Label/> <div class="control"> <TextInput opts={role: "bot_token_input"}/> </div> <ErrorTag class="help is-danger"/> </Field> <Field name={:application_id}> <Label/> <div class="control"> <NumberInput opts={role: "bot_application_id_input"}/> </div> <ErrorTag class="help is-danger"/> </Field> <Field name={:public_key}> <Label/> <div class="control"> <TextInput opts={role: "bot_public_key_input"}/> </div> <ErrorTag class="help is-danger" /> </Field> <Submit opts={disabled: [email protected]?, role: "bot_submit"} click={@hide_event}> Save </Submit> </Form> </section> <footer class="modal-card-foot" style="justify-content: flex-end"> <Button click={@hide_event}>Close</Button> </footer> </div> </div> """ end end
30.421053
111
0.532007
735117b824d6fd34dec20532f69fa9749d9c974f
55,899
ex
Elixir
lib/elixir/lib/module.ex
chulkilee/elixir
699231dcad52916a76f38856cbd7cf7c7bdadc51
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/module.ex
chulkilee/elixir
699231dcad52916a76f38856cbd7cf7c7bdadc51
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/module.ex
chulkilee/elixir
699231dcad52916a76f38856cbd7cf7c7bdadc51
[ "Apache-2.0" ]
null
null
null
defmodule Module do @moduledoc ~S''' Provides functions to deal with modules during compilation time. It allows a developer to dynamically add, delete and register attributes, attach documentation and so forth. After a module is compiled, using many of the functions in this module will raise errors, since it is out of their scope to inspect runtime data. Most of the runtime data can be inspected via the `__info__/1` function attached to each compiled module. ## Module attributes Each module can be decorated with one or more attributes. The following ones are currently defined by Elixir: ### `@after_compile` A hook that will be invoked right after the current module is compiled. Accepts a module or a `{module, function_name}`. See the "Compile callbacks" section below. ### `@before_compile` A hook that will be invoked before the module is compiled. Accepts a module or a `{module, function_or_macro_name}` tuple. See the "Compile callbacks" section below. ### `@behaviour` (notice the British spelling) Behaviours can be referenced by modules to ensure they implement required specific function signatures defined by `@callback`. For example, you could specify a `URI.Parser` behaviour as follows: defmodule URI.Parser do @doc "Defines a default port" @callback default_port() :: integer @doc "Parses the given URL" @callback parse(uri_info :: URI.t) :: URI.t end And then a module may use it as: defmodule URI.HTTP do @behaviour URI.Parser def default_port(), do: 80 def parse(info), do: info end If the behaviour changes or `URI.HTTP` does not implement one of the callbacks, a warning will be raised. ### `@impl` To aid in the correct implementation of behaviours, you may optionally declare `@impl` for implemented callbacks of a behaviour. This makes callbacks explicit and can help you to catch errors in your code (the compiler will warn you if you mark a function as `@impl` when in fact it is not a callback, and vice versa). It also helps with maintainability by making it clear to other developers that the function's purpose is to implement a callback. Using `@impl` the example above can be rewritten as: defmodule URI.HTTP do @behaviour URI.parser @impl true def default_port(), do: 80 @impl true def parse(info), do: info end You may pass either `false`, `true`, or a specific behaviour to `@impl`. defmodule Foo do @behaviour Bar @behaviour Baz @impl true # will warn if neither Bar nor Baz specify a callback named bar/0 def bar(), do: :ok @impl Baz # will warn if Baz does not specify a callback named baz/0 def baz(), do: :ok end ### `@compile` Defines options for module compilation. This is used to configure both Elixir and Erlang compilers, as any other compilation pass added by external tools. For example: defmodule MyModule do @compile {:inline, my_fun: 1} def my_fun(arg) do to_string(arg) end end Multiple uses of `@compile` will accumulate instead of overriding previous ones. See the "Compile options" section below. ### `@deprecated` Provides the deprecation reason for a function. For example: defmodule Keyword do @deprecated "Use Kernel.length/1 instead" def size(keyword) do length(keyword) end end The mix compiler automatically looks for calls to deprecated modules and emit warnings during compilation, computed via `mix xref warnings`. We recommend using this feature with care, especially library authors. Deprecating code always pushes the burden towards library users. We also recommend for deprecated functionality to be maintained for long periods of time, even after deprecation, giving developers plenty of time to update (except for cases where keeping the deprecated API is undesired, such as in the presence of security issues). ### `@doc` (and `@since`) Provides documentation for the function or macro that follows the attribute. Accepts a string (often a heredoc) or `false` where `@doc false` will make the function/macro invisible to documentation extraction tools like ExDoc. For example: defmodule MyModule do @doc "Hello world" @since "1.1.0" def hello do "world" end @doc """ Sums `a` to `b`. """ def sum(a, b) do a + b end end `@since` is an optional attribute that annotates which version the function was introduced. ### `@dialyzer` Defines warnings to request or suppress when using a version of `:dialyzer` that supports module attributes. Accepts an atom, a tuple, or a list of atoms and tuples. For example: defmodule MyModule do @dialyzer {:nowarn_function, my_fun: 1} def my_fun(arg) do M.not_a_function(arg) end end For the list of supported warnings, see [`:dialyzer` module](http://www.erlang.org/doc/man/dialyzer.html). Multiple uses of `@dialyzer` will accumulate instead of overriding previous ones. ### `@external_resource` Specifies an external resource for the current module. Sometimes a module embeds information from an external file. This attribute allows the module to annotate which external resources have been used. Tools like Mix may use this information to ensure the module is recompiled in case any of the external resources change. ### `@file` Changes the filename used in stacktraces for the function or macro that follows the attribute, such as: defmodule MyModule do @doc "Hello world" @file "hello.ex" def hello do "world" end end ### `@moduledoc` Provides documentation for the current module. defmodule MyModule do @moduledoc """ A very useful module. """ end Accepts a string (often a heredoc) or `false` where `@moduledoc false` will make the module invisible to documentation extraction tools like ExDoc. ### `@on_definition` A hook that will be invoked when each function or macro in the current module is defined. Useful when annotating functions. Accepts a module or a `{module, function_name}` tuple. See the "Compile callbacks" section below. ### `@on_load` A hook that will be invoked whenever the module is loaded. Accepts the function name (as an atom) of a function in the current module or `{function_name, 0}` tuple where `function_name` is the name of a function in the current module. The function must have arity 0 (no arguments) and has to return `:ok`, otherwise the loading of the module will be aborted. For example: defmodule MyModule do @on_load :load_check def load_check do if some_condition() do :ok else :abort end end def some_condition do false end end Modules compiled with HiPE would not call this hook. ### `@vsn` Specify the module version. Accepts any valid Elixir value, for example: defmodule MyModule do @vsn "1.0" end ### Typespec attributes The following attributes are part of typespecs and are also built-in in Elixir: * `@type` - defines a type to be used in `@spec` * `@typep` - defines a private type to be used in `@spec` * `@opaque` - defines an opaque type to be used in `@spec` * `@spec` - provides a specification for a function * `@callback` - provides a specification for a behaviour callback * `@macrocallback` - provides a specification for a macro behaviour callback * `@optional_callbacks` - specifies which behaviour callbacks and macro behaviour callbacks are optional * `@impl` - declares an implementation of a callback function or macro ### Custom attributes In addition to the built-in attributes outlined above, custom attributes may also be added. A custom attribute is any valid identifier prefixed with an `@` and followed by a valid Elixir value: defmodule MyModule do @custom_attr [some: "stuff"] end For more advanced options available when defining custom attributes, see `register_attribute/3`. ## Compile callbacks There are three callbacks that are invoked when functions are defined, as well as before and immediately after the module bytecode is generated. ### `@after_compile` A hook that will be invoked right after the current module is compiled. Accepts a module or a `{module, function_name}` tuple. The function must take two arguments: the module environment and its bytecode. When just a module is provided, the function is assumed to be `__after_compile__/2`. Callbacks registered first will run last. #### Example defmodule MyModule do @after_compile __MODULE__ def __after_compile__(env, _bytecode) do IO.inspect env end end ### `@before_compile` A hook that will be invoked before the module is compiled. Accepts a module or a `{module, function_or_macro_name}` tuple. The function/macro must take one argument: the module environment. If it's a macro, its returned value will be injected at the end of the module definition before the compilation starts. When just a module is provided, the function/macro is assumed to be `__before_compile__/1`. Callbacks registered first will run last. Any overridable definition will be made concrete before the first callback runs. A definition may be made overridable again in another before compile callback and it will be made concrete one last time after after all callbacks run. *Note*: unlike `@after_compile`, the callback function/macro must be placed in a separate module (because when the callback is invoked, the current module does not yet exist). #### Example defmodule A do defmacro __before_compile__(_env) do quote do def hello, do: "world" end end end defmodule B do @before_compile A end B.hello() #=> "world" ### `@on_definition` A hook that will be invoked when each function or macro in the current module is defined. Useful when annotating functions. Accepts a module or a `{module, function_name}` tuple. The function must take 6 arguments: * the module environment * the kind of the function/macro: `:def`, `:defp`, `:defmacro`, or `:defmacrop` * the function/macro name * the list of quoted arguments * the list of quoted guards * the quoted function body Note the hook receives the quoted arguments and it is invoked before the function is stored in the module. So `Module.defines?/2` will return `false` for the first clause of every function. If the function/macro being defined has multiple clauses, the hook will be called for each clause. Unlike other hooks, `@on_definition` will only invoke functions and never macros. This is to avoid `@on_definition` callbacks from redefining functions that have just been defined in favor of more explicit approaches. When just a module is provided, the function is assumed to be `__on_definition__/6`. #### Example defmodule Hooks do def on_def(_env, kind, name, args, guards, body) do IO.puts "Defining #{kind} named #{name} with args:" IO.inspect args IO.puts "and guards" IO.inspect guards IO.puts "and body" IO.puts Macro.to_string(body) end end defmodule MyModule do @on_definition {Hooks, :on_def} def hello(arg) when is_binary(arg) or is_list(arg) do "Hello" <> to_string(arg) end def hello(_) do :ok end end ## Compile options The `@compile` attribute accepts different options that are used by both Elixir and Erlang compilers. Some of the common use cases are documented below: * `@compile :debug_info` - includes `:debug_info` regardless of the corresponding setting in `Code.compiler_options/1` * `@compile {:debug_info, false}` - disables `:debug_info` regardless of the corresponding setting in `Code.compiler_options/1` * `@compile {:inline, some_fun: 2, other_fun: 3}` - inlines the given name/arity pairs * `@compile {:autoload, false}` - disables automatic loading of modules after compilation. Instead, the module will be loaded after it is dispatched to You can see a handful more options used by the Erlang compiler in the documentation for the [`:compile` module](http://www.erlang.org/doc/man/compile.html). ''' @typep definition :: {atom, arity} @typep def_kind :: :def | :defp | :defmacro | :defmacrop @doc """ Provides runtime information about functions and macros defined by the module, etc. Each module gets an `__info__/1` function when it's compiled. The function takes one of the following atoms: * `:functions` - keyword list of public functions along with their arities * `:macros` - keyword list of public macros along with their arities * `:module` - the module atom name * `:md5` - the MD5 of the module * `:compile` - a list with compiler metadata * `:attributes` - a list with all persisted attributes """ def __info__(kind) @doc """ Checks if a module is open. A module is "open" if it is currently being defined and its attributes and functions can be modified. """ @spec open?(module) :: boolean def open?(module) when is_atom(module) do :elixir_module.is_open(module) end @doc """ Evaluates the quoted contents in the given module's context. A list of environment options can also be given as argument. See `Code.eval_string/3` for more information. Raises an error if the module was already compiled. ## Examples defmodule Foo do contents = quote do: (def sum(a, b), do: a + b) Module.eval_quoted __MODULE__, contents end Foo.sum(1, 2) #=> 3 For convenience, you can pass any `Macro.Env` struct, such as `__ENV__/0`, as the first argument or as options. Both the module and all options will be automatically extracted from the environment: defmodule Foo do contents = quote do: (def sum(a, b), do: a + b) Module.eval_quoted __ENV__, contents end Foo.sum(1, 2) #=> 3 Note that if you pass a `Macro.Env` struct as first argument while also passing `opts`, they will be merged with `opts` having precedence. """ @spec eval_quoted(module | Macro.Env.t(), Macro.t(), list, keyword | Macro.Env.t()) :: term def eval_quoted(module_or_env, quoted, binding \\ [], opts \\ []) def eval_quoted(%Macro.Env{} = env, quoted, binding, opts) when is_list(binding) and is_list(opts) do eval_quoted(env.module, quoted, binding, Keyword.merge(Map.to_list(env), opts)) end def eval_quoted(module, quoted, binding, %Macro.Env{} = env) when is_atom(module) and is_list(binding) do eval_quoted(module, quoted, binding, Map.to_list(env)) end def eval_quoted(module, quoted, binding, opts) when is_atom(module) and is_list(binding) and is_list(opts) do assert_not_compiled!(:eval_quoted, module) :elixir_def.reset_last(module) {value, binding, _env, _scope} = :elixir.eval_quoted(quoted, binding, Keyword.put(opts, :module, module)) {value, binding} end @doc """ Creates a module with the given name and defined by the given quoted expressions. The line where the module is defined and its file **must** be passed as options. It returns a tuple of shape `{:module, module, binary, term}` where `module` is the module name, `binary` is the module byte code and `term` is the result of the last expression in `quoted`. Similar to `Kernel.defmodule/2`, the binary will only be written to disk as a `.beam` file if `Module.create/3` is invoked in a file that is currently being compiled. ## Examples contents = quote do def world, do: true end Module.create(Hello, contents, Macro.Env.location(__ENV__)) Hello.world #=> true ## Differences from `defmodule` `Module.create/3` works similarly to `Kernel.defmodule/2` and return the same results. While one could also use `defmodule` to define modules dynamically, this function is preferred when the module body is given by a quoted expression. Another important distinction is that `Module.create/3` allows you to control the environment variables used when defining the module, while `Kernel.defmodule/2` automatically uses the environment it is invoked at. """ @spec create(module, Macro.t(), Macro.Env.t() | keyword) :: {:module, module, binary, term} def create(module, quoted, opts) def create(module, quoted, %Macro.Env{} = env) when is_atom(module) do create(module, quoted, Map.to_list(env)) end def create(module, quoted, opts) when is_atom(module) and is_list(opts) do unless Keyword.has_key?(opts, :file) do raise ArgumentError, "expected :file to be given as option" end next = :erlang.unique_integer() line = Keyword.get(opts, :line, 0) quoted = :elixir_quote.linify_with_context_counter(line, {module, next}, quoted) :elixir_module.compile(module, quoted, [], :elixir.env_for_eval(opts)) end @doc """ Concatenates a list of aliases and returns a new alias. ## Examples iex> Module.concat([Foo, Bar]) Foo.Bar iex> Module.concat([Foo, "Bar"]) Foo.Bar """ @spec concat([binary | atom]) :: atom def concat(list) when is_list(list) do :elixir_aliases.concat(list) end @doc """ Concatenates two aliases and returns a new alias. ## Examples iex> Module.concat(Foo, Bar) Foo.Bar iex> Module.concat(Foo, "Bar") Foo.Bar """ @spec concat(binary | atom, binary | atom) :: atom def concat(left, right) when (is_binary(left) or is_atom(left)) and (is_binary(right) or is_atom(right)) do :elixir_aliases.concat([left, right]) end @doc """ Concatenates a list of aliases and returns a new alias only if the alias was already referenced. If the alias was not referenced yet, fails with `ArgumentError`. It handles charlists, binaries and atoms. ## Examples iex> Module.safe_concat([Module, Unknown]) ** (ArgumentError) argument error iex> Module.safe_concat([List, Chars]) List.Chars """ @spec safe_concat([binary | atom]) :: atom def safe_concat(list) when is_list(list) do :elixir_aliases.safe_concat(list) end @doc """ Concatenates two aliases and returns a new alias only if the alias was already referenced. If the alias was not referenced yet, fails with `ArgumentError`. It handles charlists, binaries and atoms. ## Examples iex> Module.safe_concat(Module, Unknown) ** (ArgumentError) argument error iex> Module.safe_concat(List, Chars) List.Chars """ @spec safe_concat(binary | atom, binary | atom) :: atom def safe_concat(left, right) when (is_binary(left) or is_atom(left)) and (is_binary(right) or is_atom(right)) do :elixir_aliases.safe_concat([left, right]) end # Build signatures to be stored in docs defp build_signature(args, env) do {reverse_args, counters} = simplify_args(args, %{}, [], env) expand_vars(reverse_args, counters, []) end defp simplify_args([arg | args], counters, acc, env) do {arg, counters} = simplify_arg(arg, counters, env) simplify_args(args, counters, [arg | acc], env) end defp simplify_args([], counters, reverse_args, _env) do {reverse_args, counters} end defp simplify_arg({:\\, _, [left, right]}, acc, env) do {left, acc} = simplify_arg(left, acc, env) right = Macro.prewalk(right, fn {:@, _, _} = attr -> Macro.expand_once(attr, env) other -> other end) {{:\\, [], [left, right]}, acc} end # If the variable is being used explicitly for naming, # we always give it a higher priority (nil) even if it # starts with underscore. defp simplify_arg({:=, _, [{var, _, atom}, _]}, acc, _env) when is_atom(atom) do {simplify_var(var, nil), acc} end defp simplify_arg({:=, _, [_, {var, _, atom}]}, acc, _env) when is_atom(atom) do {simplify_var(var, nil), acc} end # If we have only the variable as argument, it also gets # higher priority. However, if the variable starts with an # underscore, we give it a secondary context (Elixir) with # lower priority. defp simplify_arg({var, _, atom}, acc, _env) when is_atom(atom) do {simplify_var(var, Elixir), acc} end defp simplify_arg({:%, _, [left, _]}, acc, env) do case Macro.expand_once(left, env) do module when is_atom(module) -> autogenerated(acc, simplify_module_name(module)) _ -> autogenerated(acc, :struct) end end defp simplify_arg({:%{}, _, _}, acc, _env) do autogenerated(acc, :map) end defp simplify_arg({:@, _, _} = attr, acc, env) do simplify_arg(Macro.expand_once(attr, env), acc, env) end defp simplify_arg(other, acc, _env) when is_integer(other), do: autogenerated(acc, :int) defp simplify_arg(other, acc, _env) when is_boolean(other), do: autogenerated(acc, :bool) defp simplify_arg(other, acc, _env) when is_atom(other), do: autogenerated(acc, :atom) defp simplify_arg(other, acc, _env) when is_list(other), do: autogenerated(acc, :list) defp simplify_arg(other, acc, _env) when is_float(other), do: autogenerated(acc, :float) defp simplify_arg(other, acc, _env) when is_binary(other), do: autogenerated(acc, :binary) defp simplify_arg(_, acc, _env), do: autogenerated(acc, :arg) defp simplify_var(var, guess_priority) do case Atom.to_string(var) do "_" -> {:_, [], guess_priority} "_" <> rest -> {String.to_atom(rest), [], guess_priority} _ -> {var, [], nil} end end defp simplify_module_name(module) when is_atom(module) do try do split(module) rescue ArgumentError -> module else module_name -> String.to_atom(Macro.underscore(List.last(module_name))) end end defp autogenerated(acc, key) do case acc do %{^key => :once} -> {key, Map.put(acc, key, 2)} %{^key => value} -> {key, Map.put(acc, key, value + 1)} %{} -> {key, Map.put(acc, key, :once)} end end defp expand_vars([key | keys], counters, acc) when is_atom(key) do case counters do %{^key => count} when is_integer(count) and count >= 1 -> counters = Map.put(counters, key, count - 1) expand_vars(keys, counters, [{:"#{key}#{count}", [], Elixir} | acc]) _ -> expand_vars(keys, counters, [{key, [], Elixir} | acc]) end end defp expand_vars([arg | args], counters, acc) do expand_vars(args, counters, [arg | acc]) end defp expand_vars([], _counters, acc) do acc end # Merge defp merge_signatures([h1 | t1], [h2 | t2], i) do [merge_signature(h1, h2, i) | merge_signatures(t1, t2, i + 1)] end defp merge_signatures([], [], _) do [] end defp merge_signature({:\\, line, [left, right]}, newer, i) do {:\\, line, [merge_signature(left, newer, i), right]} end defp merge_signature(older, {:\\, _, [left, _]}, i) do merge_signature(older, left, i) end # The older signature, when given, always have higher precedence defp merge_signature({_, _, nil} = older, _newer, _), do: older defp merge_signature(_older, {_, _, nil} = newer, _), do: newer # Both are a guess, so check if they are the same guess defp merge_signature({var, _, _} = older, {var, _, _}, _), do: older # Otherwise, returns a generic guess defp merge_signature({_, line, _}, _newer, i), do: {:"arg#{i}", line, Elixir} @doc """ Checks if the module defines the given function or macro. Use `defines?/3` to assert for a specific type. This function can only be used on modules that have not yet been compiled. Use `Kernel.function_exported?/3` to check compiled modules. ## Examples defmodule Example do Module.defines? __MODULE__, {:version, 0} #=> false def version, do: 1 Module.defines? __MODULE__, {:version, 0} #=> true end """ @spec defines?(module, definition) :: boolean def defines?(module, {function_or_macro_name, arity} = tuple) when is_atom(module) and is_atom(function_or_macro_name) and is_integer(arity) and arity >= 0 and arity <= 255 do assert_not_compiled!(:defines?, module) table = defs_table_for(module) :ets.lookup(table, {:def, tuple}) != [] end @doc """ Checks if the module defines a function or macro of the given `kind`. `kind` can be any of `:def`, `:defp`, `:defmacro`, or `:defmacrop`. This function can only be used on modules that have not yet been compiled. Use `Kernel.function_exported?/3` to check compiled modules. ## Examples defmodule Example do Module.defines? __MODULE__, {:version, 0}, :defp #=> false def version, do: 1 Module.defines? __MODULE__, {:version, 0}, :defp #=> false end """ @spec defines?(module, definition, def_kind) :: boolean def defines?(module, {function_macro_name, arity} = tuple, def_kind) when is_atom(module) and is_atom(function_macro_name) and is_integer(arity) and arity >= 0 and arity <= 255 and def_kind in [:def, :defp, :defmacro, :defmacrop] do assert_not_compiled!(:defines?, module) table = defs_table_for(module) case :ets.lookup(table, {:def, tuple}) do [{_, ^def_kind, _, _, _, _}] -> true _ -> false end end @doc """ Returns all functions defined in `module`. ## Examples defmodule Example do def version, do: 1 Module.definitions_in __MODULE__ #=> [{:version, 0}] end """ @spec definitions_in(module) :: [definition] def definitions_in(module) when is_atom(module) do assert_not_compiled!(:definitions_in, module) table = defs_table_for(module) :lists.concat(:ets.match(table, {{:def, :"$1"}, :_, :_, :_, :_, :_})) end @doc """ Returns all functions defined in `module`, according to its kind. ## Examples defmodule Example do def version, do: 1 Module.definitions_in __MODULE__, :def #=> [{:version, 0}] Module.definitions_in __MODULE__, :defp #=> [] end """ @spec definitions_in(module, def_kind) :: [definition] def definitions_in(module, def_kind) when is_atom(module) and def_kind in [:def, :defp, :defmacro, :defmacrop] do assert_not_compiled!(:definitions_in, module) table = defs_table_for(module) :lists.concat(:ets.match(table, {{:def, :"$1"}, def_kind, :_, :_, :_, :_})) end @doc """ Makes the given functions in `module` overridable. An overridable function is lazily defined, allowing a developer to customize it. See `Kernel.defoverridable/1` for more information and documentation. """ @spec make_overridable(module, [definition]) :: :ok def make_overridable(module, tuples) when is_atom(module) and is_list(tuples) do assert_not_compiled!(:make_overridable, module) check_impls_for_overridable(module, tuples) func = fn {function_name, arity} = tuple when is_atom(function_name) and is_integer(arity) and arity >= 0 and arity <= 255 -> case :elixir_def.take_definition(module, tuple) do false -> raise ArgumentError, "cannot make function #{function_name}/#{arity} " <> "overridable because it was not defined" clause -> neighbours = :elixir_locals.yank(tuple, module) overridable_definitions = :elixir_overridable.overridable(module) count = case :maps.find(tuple, overridable_definitions) do {:ok, {count, _, _, _}} -> count + 1 :error -> 1 end overridable_definitions = :maps.put(tuple, {count, clause, neighbours, false}, overridable_definitions) :elixir_overridable.overridable(module, overridable_definitions) end other -> raise ArgumentError, "each element in tuple list has to be a " <> "{function_name :: atom, arity :: 0..255} tuple, got: #{inspect(other)}" end :lists.foreach(func, tuples) end @spec make_overridable(module, module) :: :ok def make_overridable(module, behaviour) when is_atom(module) and is_atom(behaviour) do case check_module_for_overridable(module, behaviour) do :ok -> :ok {:error, error_explanation} -> raise ArgumentError, "cannot pass module #{inspect(behaviour)} as argument " <> "to defoverridable/1 because #{error_explanation}" end behaviour_callbacks = for callback <- behaviour_info(behaviour, :callbacks) do {pair, _kind} = normalize_macro_or_function_callback(callback) pair end tuples = for definition <- definitions_in(module), definition in behaviour_callbacks, do: definition make_overridable(module, tuples) end defp check_impls_for_overridable(module, tuples) do table = data_table_for(module) impls = :ets.lookup_element(table, {:elixir, :impls}, 2) {overridable_impls, impls} = :lists.splitwith(fn {pair, _, _, _, _, _} -> pair in tuples end, impls) if overridable_impls != [] do :ets.insert(table, {{:elixir, :impls}, impls}) behaviours = :ets.lookup_element(table, :behaviour, 2) callbacks = for behaviour <- behaviours, function_exported?(behaviour, :behaviour_info, 1), callback <- behaviour_info(behaviour, :callbacks), {callback, kind} = normalize_macro_or_function_callback(callback), do: {callback, {kind, behaviour, true}}, into: %{} check_impls(behaviours, callbacks, overridable_impls) end end defp check_module_for_overridable(module, behaviour) do behaviour_definitions = :ets.lookup_element(data_table_for(module), :behaviour, 2) cond do not Code.ensure_compiled?(behaviour) -> {:error, "it was not defined"} not function_exported?(behaviour, :behaviour_info, 1) -> {:error, "it does not define any callbacks"} behaviour not in behaviour_definitions -> error_message = "its corresponding behaviour is missing. Did you forget to " <> "add @behaviour #{inspect(behaviour)}?" {:error, error_message} true -> :ok end end defp normalize_macro_or_function_callback({function_name, arity}) do case :erlang.atom_to_list(function_name) do # Macros are always provided one extra argument in behaviour_info/1 'MACRO-' ++ tail -> {{:erlang.list_to_atom(tail), arity - 1}, :defmacro} _ -> {{function_name, arity}, :def} end end defp behaviour_info(module, key) do case module.behaviour_info(key) do list when is_list(list) -> list :undefined -> [] end end @doc """ Returns `true` if `tuple` in `module` is marked as overridable. """ @spec overridable?(module, definition) :: boolean def overridable?(module, {function_name, arity} = tuple) when is_atom(function_name) and is_integer(arity) and arity >= 0 and arity <= 255 do :maps.is_key(tuple, :elixir_overridable.overridable(module)) end @doc """ Puts a module attribute with `key` and `value` in the given `module`. ## Examples defmodule MyModule do Module.put_attribute __MODULE__, :custom_threshold_for_lib, 10 end """ @spec put_attribute(module, atom, term) :: :ok def put_attribute(module, key, value) when is_atom(module) and is_atom(key) do put_attribute(module, key, value, nil, nil) end @doc """ Gets the given attribute from a module. If the attribute was marked with `accumulate` with `Module.register_attribute/3`, a list is always returned. `nil` is returned if the attribute has not been marked with `accumulate` and has not been set to any value. The `@` macro compiles to a call to this function. For example, the following code: @foo Expands to something akin to: Module.get_attribute(__MODULE__, :foo) ## Examples defmodule Foo do Module.put_attribute __MODULE__, :value, 1 Module.get_attribute __MODULE__, :value #=> 1 Module.register_attribute __MODULE__, :value, accumulate: true Module.put_attribute __MODULE__, :value, 1 Module.get_attribute __MODULE__, :value #=> [1] end """ @spec get_attribute(module, atom) :: term def get_attribute(module, key) when is_atom(module) and is_atom(key) do get_attribute(module, key, nil) end @doc """ Deletes the module attribute that matches the given key. It returns the deleted attribute value (or `nil` if nothing was set). ## Examples defmodule MyModule do Module.put_attribute __MODULE__, :custom_threshold_for_lib, 10 Module.delete_attribute __MODULE__, :custom_threshold_for_lib end """ @spec delete_attribute(module, atom) :: term def delete_attribute(module, key) when is_atom(module) and is_atom(key) do assert_not_compiled!(:delete_attribute, module) table = data_table_for(module) case :ets.take(table, key) do [{_, value, _accumulated? = true, _}] -> :ets.insert(table, {key, [], true, nil}) value [{_, value, _, _}] -> value [] -> nil end end @doc """ Registers an attribute. By registering an attribute, a developer is able to customize how Elixir will store and accumulate the attribute values. ## Options When registering an attribute, two options can be given: * `:accumulate` - several calls to the same attribute will accumulate instead of override the previous one. New attributes are always added to the top of the accumulated list. * `:persist` - the attribute will be persisted in the Erlang Abstract Format. Useful when interfacing with Erlang libraries. By default, both options are `false`. ## Examples defmodule MyModule do Module.register_attribute __MODULE__, :custom_threshold_for_lib, accumulate: true, persist: false @custom_threshold_for_lib 10 @custom_threshold_for_lib 20 @custom_threshold_for_lib #=> [20, 10] end """ @spec register_attribute(module, atom, [{:accumulate, boolean}, {:persist, boolean}]) :: :ok def register_attribute(module, attribute, options) when is_atom(module) and is_atom(attribute) and is_list(options) do assert_not_compiled!(:register_attribute, module) table = data_table_for(module) if Keyword.get(options, :persist) do attributes = :ets.lookup_element(table, {:elixir, :persisted_attributes}, 2) :ets.insert(table, {{:elixir, :persisted_attributes}, [attribute | attributes]}) end if Keyword.get(options, :accumulate) do :ets.insert_new(table, {attribute, [], _accumulated? = true, _unread_line = nil}) || :ets.update_element(table, attribute, {3, true}) end :ok end @doc """ Splits the given module name into binary parts. `module` has to be an Elixir module, as `split/1` won't work with Erlang-style modules (for example, `split(:lists)` raises an error). `split/1` also supports splitting the string representation of Elixir modules (that is, the result of calling `Atom.to_string/1` with the module name). ## Examples iex> Module.split(Very.Long.Module.Name.And.Even.Longer) ["Very", "Long", "Module", "Name", "And", "Even", "Longer"] iex> Module.split("Elixir.String.Chars") ["String", "Chars"] """ @spec split(module | String.t()) :: [String.t(), ...] def split(module) def split(module) when is_atom(module) do split(Atom.to_string(module), _original = module) end def split(module) when is_binary(module) do split(module, _original = module) end defp split("Elixir." <> name, _original) do String.split(name, ".") end defp split(_module, original) do raise ArgumentError, "expected an Elixir module, got: #{inspect(original)}" end @doc false # TODO: Remove in 2.0 - deprecated. def add_doc(module, line, kind, function_tuple, signature \\ [], doc) do assert_not_compiled!(:add_doc, module) if kind in [:defp, :defmacrop, :typep] do if doc, do: {:error, :private_doc}, else: :ok else table = data_table_for(module) compile_doc(table, line, kind, function_tuple, signature, doc, __ENV__, false) :ok end end @doc false # Used internally to compile documentation. # This function is private and must be used only internally. def compile_definition_attributes(env, kind, name, args, _guards, _body) do module = env.module table = data_table_for(module) arity = length(args) pair = {name, arity} impl = compile_impl(table, name, env, kind, args) _deprecated = compile_deprecated(table, pair) _since = compile_since(table) # TODO: Store @since and @deprecated alongside the docs {line, doc} = get_doc_info(table, env) compile_doc(table, line, kind, pair, args, doc, env, impl) :ok end defp compile_doc(_table, line, kind, {name, arity}, _args, doc, env, _impl) when kind in [:defp, :defmacrop] do if doc do error_message = "#{kind} #{name}/#{arity} is private, " <> "@doc attribute is always discarded for private functions/macros/types" :elixir_errors.warn(line, env.file, error_message) end end defp compile_doc(table, line, kind, pair, args, doc, env, impl) do signature = build_signature(args, env) case :ets.lookup(table, {:doc, pair}) do [] -> doc = if is_nil(doc) && impl, do: false, else: doc :ets.insert(table, {{:doc, pair}, line, kind, signature, doc}) [{doc_tuple, line, _current_kind, current_sign, current_doc}] -> signature = merge_signatures(current_sign, signature, 1) doc = if is_nil(doc), do: current_doc, else: doc doc = if is_nil(doc) && impl, do: false, else: doc :ets.insert(table, {doc_tuple, line, kind, signature, doc}) end end defp compile_since(table) do case :ets.take(table, :since) do [{:since, since, _, _}] when is_binary(since) -> since _ -> nil end end defp compile_deprecated(table, pair) do case :ets.take(table, :deprecated) do [{:deprecated, reason, _, _}] when is_binary(reason) -> :ets.insert(table, {{:deprecated, pair}, reason}) reason _ -> nil end end defp compile_impl(table, name, env, kind, args) do %{line: line, file: file} = env case :ets.take(table, :impl) do [{:impl, value, _, _}] -> impls = :ets.lookup_element(table, {:elixir, :impls}, 2) {total, defaults} = args_count(args, 0, 0) impl = {{name, total}, defaults, kind, line, file, value} :ets.insert(table, {{:elixir, :impls}, [impl | impls]}) value [] -> false end end defp args_count([{:\\, _, _} | tail], total, defaults) do args_count(tail, total + 1, defaults + 1) end defp args_count([_head | tail], total, defaults) do args_count(tail, total + 1, defaults) end defp args_count([], total, defaults), do: {total, defaults} @doc false def check_behaviours_and_impls(env, table, all_definitions, overridable_pairs) do behaviours = :ets.lookup_element(table, :behaviour, 2) impls = :ets.lookup_element(table, {:elixir, :impls}, 2) callbacks = check_behaviours(env, behaviours) pending_callbacks = if impls != [] do non_implemented_callbacks = check_impls(behaviours, callbacks, impls) warn_missing_impls(env, non_implemented_callbacks, all_definitions, overridable_pairs) non_implemented_callbacks else callbacks end check_callbacks(env, pending_callbacks, all_definitions) :ok end defp check_behaviours(%{lexical_tracker: pid} = env, behaviours) do Enum.reduce(behaviours, %{}, fn behaviour, acc -> cond do not is_atom(behaviour) -> message = "@behaviour #{inspect(behaviour)} must be an atom (in module #{inspect(env.module)})" :elixir_errors.warn(env.line, env.file, message) acc not Code.ensure_compiled?(behaviour) -> message = "@behaviour #{inspect(behaviour)} does not exist (in module #{inspect(env.module)})" unless standard_behaviour?(behaviour) do :elixir_errors.warn(env.line, env.file, message) end acc not function_exported?(behaviour, :behaviour_info, 1) -> message = "module #{inspect(behaviour)} is not a behaviour (in module #{inspect(env.module)})" unless standard_behaviour?(behaviour) do :elixir_errors.warn(env.line, env.file, message) end acc true -> :elixir_lexical.record_remote(behaviour, nil, pid) optional_callbacks = behaviour_info(behaviour, :optional_callbacks) callbacks = behaviour_info(behaviour, :callbacks) Enum.reduce(callbacks, acc, &add_callback(&1, behaviour, env, optional_callbacks, &2)) end end) end defp add_callback(original, behaviour, env, optional_callbacks, acc) do {callback, kind} = normalize_macro_or_function_callback(original) case acc do %{^callback => {_kind, conflict, _optional?}} -> message = "conflicting behaviours found. #{format_definition(kind, callback)} is required by " <> "#{inspect(behaviour)} and #{inspect(conflict)} (in module #{inspect(env.module)})" :elixir_errors.warn(env.line, env.file, message) %{} -> :ok end Map.put(acc, callback, {kind, behaviour, original in optional_callbacks}) end defp standard_behaviour?(behaviour) do behaviour in [ Collectable, Enumerable, Inspect, List.Chars, String.Chars ] end defp check_callbacks(env, callbacks, all_definitions) do for {callback, {kind, behaviour, optional?}} <- callbacks do case :lists.keyfind(callback, 1, all_definitions) do false when not optional? -> message = format_callback(callback, kind, behaviour) <> " is not implemented (in module #{inspect(env.module)})" :elixir_errors.warn(env.line, env.file, message) {_, wrong_kind, _, _} when kind != wrong_kind -> message = format_callback(callback, kind, behaviour) <> " was implemented as \"#{wrong_kind}\" but should have been \"#{kind}\" " <> "(in module #{inspect(env.module)})" :elixir_errors.warn(env.line, env.file, message) _ -> :ok end end :ok end defp format_callback(callback, kind, module) do protocol_or_behaviour = if protocol?(module), do: "protocol ", else: "behaviour " format_definition(kind, callback) <> " required by " <> protocol_or_behaviour <> inspect(module) end defp protocol?(module) do Code.ensure_loaded?(module) and function_exported?(module, :__protocol__, 1) and module.__protocol__(:module) == module end defp check_impls(behaviours, callbacks, impls) do Enum.reduce(impls, callbacks, fn {fa, defaults, kind, line, file, value}, acc -> case impl_behaviours(fa, defaults, kind, value, behaviours, callbacks) do {:ok, impl_behaviours} -> Enum.reduce(impl_behaviours, acc, fn {fa, _}, acc -> Map.delete(acc, fa) end) {:error, message} -> :elixir_errors.warn(line, file, format_impl_warning(fa, kind, message)) acc end end) end defp impl_behaviours({function, arity}, defaults, kind, value, behaviours, callbacks) do impls = for n <- arity..(arity - defaults), do: {function, n} impl_behaviours(impls, kind, value, behaviours, callbacks) end defp impl_behaviours(_, kind, _, _, _) when kind in [:defp, :defmacrop] do {:error, :private_function} end defp impl_behaviours(_, _, value, [], _) do {:error, {:no_behaviours, value}} end defp impl_behaviours(impls, _, false, _, callbacks) do case impl_callbacks(impls, callbacks) do [] -> {:ok, []} [impl | _] -> {:error, {:impl_not_defined, impl}} end end defp impl_behaviours(impls, _, true, _, callbacks) do case impl_callbacks(impls, callbacks) do [] -> {:error, {:impl_defined, callbacks}} impls -> {:ok, impls} end end defp impl_behaviours(impls, _, behaviour, behaviours, callbacks) do filtered = impl_behaviours(impls, behaviour, callbacks) cond do filtered != [] -> {:ok, filtered} behaviour not in behaviours -> {:error, {:behaviour_not_declared, behaviour}} true -> {:error, {:behaviour_not_defined, behaviour, callbacks}} end end defp impl_behaviours(impls, behaviour, callbacks) do impl_behaviours(impl_callbacks(impls, callbacks), behaviour) end defp impl_behaviours([], _) do [] end defp impl_behaviours([{_, behaviour} = impl | tail], behaviour) do [impl | impl_behaviours(tail, behaviour)] end defp impl_behaviours([_ | tail], behaviour) do impl_behaviours(tail, behaviour) end defp impl_callbacks([], _) do [] end defp impl_callbacks([fa | tail], callbacks) do case callbacks[fa] do nil -> impl_callbacks(tail, callbacks) {_, behaviour, _} -> [{fa, behaviour} | impl_callbacks(tail, callbacks)] end end defp format_impl_warning(fa, kind, :private_function) do "#{format_definition(kind, fa)} is private, @impl attribute is always discarded for private functions/macros" end defp format_impl_warning(fa, kind, {:no_behaviours, value}) do "got \"@impl #{inspect(value)}\" for #{format_definition(kind, fa)} but no behaviour was declared" end defp format_impl_warning(_, kind, {:impl_not_defined, {fa, behaviour}}) do "got \"@impl false\" for #{format_definition(kind, fa)} " <> "but it is a callback specified in #{inspect(behaviour)}" end defp format_impl_warning(fa, kind, {:impl_defined, callbacks}) do "got \"@impl true\" for #{format_definition(kind, fa)} " <> "but no behaviour specifies such callback#{known_callbacks(callbacks)}" end defp format_impl_warning(fa, kind, {:behaviour_not_declared, behaviour}) do "got \"@impl #{inspect(behaviour)}\" for #{format_definition(kind, fa)} " <> "but this behaviour was not declared with @behaviour" end defp format_impl_warning(fa, kind, {:behaviour_not_defined, behaviour, callbacks}) do "got \"@impl #{inspect(behaviour)}\" for #{format_definition(kind, fa)} " <> "but this behaviour does not specify such callback#{known_callbacks(callbacks)}" end defp warn_missing_impls(_env, callbacks, _defs, _) when map_size(callbacks) == 0 do :ok end defp warn_missing_impls(env, non_implemented_callbacks, defs, overridable_pairs) do for {pair, kind, meta, _clauses} <- defs, kind in [:def, :defmacro], pair not in overridable_pairs do case Map.fetch(non_implemented_callbacks, pair) do {:ok, {_, behaviour, _}} -> message = "module attribute @impl was not set for #{format_definition(kind, pair)} " <> "callback (specified in #{inspect(behaviour)}). " <> "This either means you forgot to add the \"@impl true\" annotation before the " <> "definition or that you are accidentally overriding this callback" :elixir_errors.warn(:elixir_utils.get_line(meta), env.file, message) :error -> :ok end end :ok end defp format_definition(kind, {name, arity}) do format_definition(kind) <> " #{name}/#{arity}" end defp format_definition(:defmacro), do: "macro" defp format_definition(:defmacrop), do: "macro" defp format_definition(:def), do: "function" defp format_definition(:defp), do: "function" defp known_callbacks(callbacks) when map_size(callbacks) == 0 do ". There are no known callbacks, please specify the proper @behaviour " <> "and make sure it defines callbacks" end defp known_callbacks(callbacks) do formatted_callbacks = for {{name, arity}, {kind, module, _}} <- callbacks do "\n * " <> Exception.format_mfa(module, name, arity) <> " (#{format_definition(kind)})" end ". The known callbacks are:\n#{formatted_callbacks}\n" end @doc false # Used internally to compile types. # This function is private and must be used only internally. def store_typespec(module, key, value) when is_atom(module) and is_atom(key) do assert_not_compiled!(:put_attribute, module) table = data_table_for(module) typespecs = case :ets.lookup(table, key) do [{^key, typespecs, _, _}] -> [value | typespecs] [] -> [value] end :ets.insert(table, {key, typespecs, true, nil}) :ok end @doc false # Used internally by Kernel's @. # This function is private and must be used only internally. def get_attribute(module, key, stack) when is_atom(key) do assert_not_compiled!(:get_attribute, module) table = data_table_for(module) case :ets.lookup(table, key) do [{^key, val, _, _}] -> :ets.update_element(table, key, {4, nil}) val [] when is_list(stack) -> # TODO: Consider raising instead of warning on v2.0 as it usually cascades error_message = "undefined module attribute @#{key}, " <> "please remove access to @#{key} or explicitly set it before access" IO.warn(error_message, stack) nil [] -> nil end end @doc false # Used internally by Kernel's @. # This function is private and must be used only internally. def put_attribute(module, key, value, stack, unread_line) when is_atom(key) do assert_not_compiled!(:put_attribute, module) table = data_table_for(module) value = preprocess_attribute(key, value) # TODO: Remove on Elixir v2.0 case value do {:parse_transform, _} when key == :compile and is_list(stack) -> error_message = "@compile {:parse_transform, _} is deprecated. " <> "Elixir will no longer support Erlang-based transforms in future versions" IO.warn(error_message, stack) _ -> :ok end case :ets.lookup(table, key) do [{^key, {line, <<_::binary>>}, accumulated?, _unread_line}] when key in [:doc, :typedoc, :moduledoc] and is_list(stack) -> IO.warn("redefining @#{key} attribute previously set at line #{line}", stack) :ets.insert(table, {key, value, accumulated?, unread_line}) [{^key, current, _accumulated? = true, _read?}] -> :ets.insert(table, {key, [value | current], true, unread_line}) _ -> :ets.insert(table, {key, value, false, unread_line}) end :ok end ## Helpers defp preprocess_attribute(key, value) when key in [:moduledoc, :typedoc, :doc] do case value do {line, doc} when is_integer(line) and (is_binary(doc) or is_boolean(doc) or is_nil(doc)) -> value {line, doc} when is_integer(line) -> raise ArgumentError, "@#{key} is a built-in module attribute for documentation. It should be " <> "a binary, a boolean, or nil, got: #{inspect(doc)}" _other -> raise ArgumentError, "@#{key} is a built-in module attribute for documentation. When set dynamically, " <> "it should be {line, doc} (where \"doc\" is a string, boolean, or nil), " <> "got: #{inspect(value)}" end end defp preprocess_attribute(:on_load, value) do case value do _ when is_atom(value) -> {value, 0} {atom, 0} = tuple when is_atom(atom) -> tuple _ -> raise ArgumentError, "@on_load is a built-in module attribute that annotates a function to be invoked " <> "when the module is loaded. It should be an atom or a {atom, 0} tuple, " <> "got: #{inspect(value)}" end end defp preprocess_attribute(:impl, value) do case value do _ when is_boolean(value) -> value module when is_atom(module) and module != nil -> # Attempt to compile behaviour but ignore failure (will warn later) _ = Code.ensure_compiled(module) value _ -> raise ArgumentError, "@impl is a built-in module attribute that marks the next definition " <> "as a callback implementation. It should be a module or a boolean, " <> "got: #{inspect(value)}" end end defp preprocess_attribute(:before_compile, atom) when is_atom(atom), do: {atom, :__before_compile__} defp preprocess_attribute(:after_compile, atom) when is_atom(atom), do: {atom, :__after_compile__} defp preprocess_attribute(:on_definition, atom) when is_atom(atom), do: {atom, :__on_definition__} defp preprocess_attribute(key, _value) when key in [:type, :typep, :export_type, :opaque, :callback, :macrocallback] do raise ArgumentError, "attributes type, typep, export_type, opaque, callback, and macrocallback" <> "must be set directly via the @ notation" end defp preprocess_attribute(:since, value) when not is_binary(value) do raise ArgumentError, "@since is a built-in module attribute used for documentation purposes. " <> "It should be a string representing the version a function, macro, type or " <> "callback was added, got: #{inspect(value)}" end defp preprocess_attribute(:deprecated, value) when not is_binary(value) do raise ArgumentError, "@deprecated is a built-in module attribute that annotates a definition as deprecated. " <> "It should be a string with the reason for the deprecation, got: #{inspect(value)}" end defp preprocess_attribute(:file, value) do case value do _ when is_binary(value) -> value {file, line} when is_binary(file) and is_integer(line) -> value _ -> raise ArgumentError, "@file is a built-in module attribute that annotates the file and line the next " <> "definition comes from. It should be a string or a {string, line} tuple as value, " <> "got: #{inspect(value)}" end end defp preprocess_attribute(_key, value) do value end defp get_doc_info(table, env) do case :ets.take(table, :doc) do [{:doc, {_, _} = pair, _, _}] -> pair [] -> {env.line, nil} end end defp data_table_for(module) do :elixir_module.data_table(module) end defp defs_table_for(module) do :elixir_module.defs_table(module) end defp assert_not_compiled!(fun, module) do open?(module) || raise ArgumentError, "could not call #{fun} with argument #{inspect(module)} because the module is already compiled" end end
31.037757
113
0.6557
735134d6b49290e3fb7fbba4c5ec531455a6701b
1,037
exs
Elixir
test/cizen/crash_logger_test.exs
ryo33/cizen
e1d3e232e4d3e72dfc7ef122d936ae26fa60c084
[ "MIT" ]
1
2019-04-08T08:00:06.000Z
2019-04-08T08:00:06.000Z
test/cizen/crash_logger_test.exs
ryo33/cizen
e1d3e232e4d3e72dfc7ef122d936ae26fa60c084
[ "MIT" ]
null
null
null
test/cizen/crash_logger_test.exs
ryo33/cizen
e1d3e232e4d3e72dfc7ef122d936ae26fa60c084
[ "MIT" ]
null
null
null
defmodule Cizen.CrashLoggerTest do use Cizen.SagaCase, async: false import ExUnit.CaptureLog alias Cizen.TestHelper alias Cizen.Dispatcher alias Cizen.Event alias Cizen.Filter require Filter defmodule(CrashTestEvent, do: defstruct([])) test "logs crashes" do saga_id = TestHelper.launch_test_saga( init: fn _id, _state -> Dispatcher.listen_event_type(CrashTestEvent) end, handle_event: fn _id, %Event{body: body}, state -> case body do %CrashTestEvent{} -> raise "Crash!!!" _ -> state end end ) output = capture_log(fn -> Dispatcher.dispatch(Event.new(nil, %CrashTestEvent{})) :timer.sleep(100) require Logger Logger.flush() end) assert output =~ "saga #{saga_id} is crashed" assert output =~ "%Cizen.TestSaga{" assert output =~ "(RuntimeError) Crash!!!" assert output =~ "test/cizen/crash_logger_test.exs:" end end
23.044444
62
0.599807
735155115d04d92cc6cc724447cf028da7b45347
191
ex
Elixir
lib/surface_bulma/dropdown/trigger.ex
justin-m-morgan/surface_bulma
c31faebc818c39d06250574b913096504bd6eeec
[ "MIT" ]
null
null
null
lib/surface_bulma/dropdown/trigger.ex
justin-m-morgan/surface_bulma
c31faebc818c39d06250574b913096504bd6eeec
[ "MIT" ]
null
null
null
lib/surface_bulma/dropdown/trigger.ex
justin-m-morgan/surface_bulma
c31faebc818c39d06250574b913096504bd6eeec
[ "MIT" ]
null
null
null
defmodule SurfaceBulma.Dropdown.CurrentItem do use Surface.Component, slot: "trigger" @moduledoc """ Contents to be displayed in the trigger """ slot default, required: true end
17.363636
46
0.732984
73516ee7a2f6f342bc23ef8b9224f70017a46b08
1,172
ex
Elixir
lib/preview/hex/adapter.ex
leandrocp/preview
9dd3a9bae4385dc4935e76f63328f70b9d78fe4d
[ "Apache-2.0" ]
26
2021-01-25T20:30:46.000Z
2021-12-16T08:42:35.000Z
lib/preview/hex/adapter.ex
leandrocp/preview
9dd3a9bae4385dc4935e76f63328f70b9d78fe4d
[ "Apache-2.0" ]
17
2021-01-25T18:45:43.000Z
2021-07-23T15:15:41.000Z
lib/preview/hex/adapter.ex
leandrocp/preview
9dd3a9bae4385dc4935e76f63328f70b9d78fe4d
[ "Apache-2.0" ]
4
2021-01-25T21:32:28.000Z
2021-07-07T12:36:19.000Z
defmodule Preview.Hex.Adapter do @behaviour :hex_http @opts [follow_redirect: true, max_redirect: 5] @impl true def request(:get, uri, req_headers, _req_body, _config) do req_headers = prepare_headers(req_headers, nil) {:ok, status, resp_headers, resp_body} = Preview.HTTP.get(uri, req_headers, @opts) # :hex_core expects headers to be a Map resp_headers = Map.new(resp_headers) {:ok, {status, resp_headers, resp_body}} end def request(:put, uri, req_headers, req_body, _config) do {content_type, payload} = deconstruct_body(req_body) req_headers = prepare_headers(req_headers, content_type) {:ok, status, resp_headers, resp_body} = Preview.HTTP.put(uri, req_headers, payload, @opts) # :hex_core expects headers to be a Map resp_headers = Map.new(resp_headers) {:ok, {status, resp_headers, resp_body}} end defp prepare_headers(req_headers, content_type) do if content_type do req_headers |> Map.put("content-type", content_type) else req_headers end |> Enum.to_list() end defp deconstruct_body(:undefined), do: {nil, ""} defp deconstruct_body(body), do: body end
28.585366
95
0.701365
735176d02403c4a6cbdc123ab56211fb32df7b7f
1,973
ex
Elixir
clients/vision/lib/google_api/vision/v1/model/image.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/vision/lib/google_api/vision/v1/model/image.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/vision/lib/google_api/vision/v1/model/image.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.Vision.V1.Model.Image do @moduledoc """ Client image to perform Google Cloud Vision API tasks over. ## Attributes * `content` (*type:* `String.t`, *default:* `nil`) - Image content, represented as a stream of bytes. Note: As with all `bytes` fields, protobuffers use a pure binary representation, whereas JSON representations use base64. * `source` (*type:* `GoogleApi.Vision.V1.Model.ImageSource.t`, *default:* `nil`) - Google Cloud Storage image location, or publicly-accessible image URL. If both `content` and `source` are provided for an image, `content` takes precedence and is used to perform the image annotation request. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :content => String.t(), :source => GoogleApi.Vision.V1.Model.ImageSource.t() } field(:content) field(:source, as: GoogleApi.Vision.V1.Model.ImageSource) end defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.Image do def decode(value, options) do GoogleApi.Vision.V1.Model.Image.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.Image do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.537037
152
0.725291
7351c4b6ebed1f5268e289cd2562b3cd8ac3d453
9,231
exs
Elixir
test/span_event_test.exs
VitorTrin/elixir_agent
03b1261eeafef6c016550ad51d939e75d59deda9
[ "Apache-2.0" ]
null
null
null
test/span_event_test.exs
VitorTrin/elixir_agent
03b1261eeafef6c016550ad51d939e75d59deda9
[ "Apache-2.0" ]
null
null
null
test/span_event_test.exs
VitorTrin/elixir_agent
03b1261eeafef6c016550ad51d939e75d59deda9
[ "Apache-2.0" ]
null
null
null
defmodule SpanEventTest do use ExUnit.Case use Plug.Test alias NewRelic.DistributedTrace alias NewRelic.Harvest.Collector @dt_header "newrelic" setup do prev_key = Collector.AgentRun.trusted_account_key() Collector.AgentRun.store(:trusted_account_key, "190") System.put_env("NEW_RELIC_HARVEST_ENABLED", "true") System.put_env("NEW_RELIC_LICENSE_KEY", "foo") send(DistributedTrace.BackoffSampler, :reset) on_exit(fn -> Collector.AgentRun.store(:trusted_account_key, prev_key) System.delete_env("NEW_RELIC_HARVEST_ENABLED") System.delete_env("NEW_RELIC_LICENSE_KEY") end) :ok end test "post a span event" do agent_run_id = Collector.AgentRun.agent_run_id() s1 = %NewRelic.Span.Event{ trace_id: "abc123" } sampling = %{ reservoir_size: 100, events_seen: 1 } span_events = NewRelic.Span.Event.format_events([s1]) payload = [agent_run_id, sampling, span_events] Collector.Protocol.span_event(payload) end test "collect and store top priority events" do Application.put_env(:new_relic_agent, :span_event_reservoir_size, 2) {:ok, harvester} = DynamicSupervisor.start_child( Collector.SpanEvent.HarvesterSupervisor, Collector.SpanEvent.Harvester ) s1 = %NewRelic.Span.Event{priority: 3, trace_id: "abc123"} s2 = %NewRelic.Span.Event{priority: 2, trace_id: "def456"} s3 = %NewRelic.Span.Event{priority: 1, trace_id: "ghi789"} GenServer.cast(harvester, {:report, s1}) GenServer.cast(harvester, {:report, s2}) GenServer.cast(harvester, {:report, s3}) events = GenServer.call(harvester, :gather_harvest) assert length(events) == 2 assert Enum.find(events, fn [span, _, _] -> span.priority == 3 end) assert Enum.find(events, fn [span, _, _] -> span.priority == 2 end) refute Enum.find(events, fn [span, _, _] -> span.priority == 1 end) # Verify that the Harvester shuts down w/o error Process.monitor(harvester) Collector.HarvestCycle.send_harvest(Collector.SpanEvent.HarvesterSupervisor, harvester) assert_receive {:DOWN, _ref, _, ^harvester, :shutdown}, 1000 Application.delete_env(:new_relic_agent, :span_event_reservoir_size) end test "report a span event through the harvester" do TestHelper.restart_harvest_cycle(Collector.SpanEvent.HarvestCycle) context = %DistributedTrace.Context{sampled: true} mfa = {:mod, :fun, 3} event = %NewRelic.Span.Event{ timestamp: System.system_time(:millisecond), duration: 0.120, name: "SomeSpan", category: "generic", category_attributes: %{} } Collector.SpanEvent.Harvester.report_span_event(event, context, span: {mfa, :ref}, parent: :root ) [[attrs, _, _]] = TestHelper.gather_harvest(Collector.SpanEvent.Harvester) assert attrs[:type] == "Span" assert attrs[:category] == "generic" TestHelper.pause_harvest_cycle(Collector.SpanEvent.HarvestCycle) end defmodule Traced do use NewRelic.Tracer @trace :hello def hello do do_hello() end @trace :do_hello def do_hello do Process.sleep(10) "world" end @trace :function def function do Process.sleep(10) NewRelic.set_span(:generic, some: "attribute") http_request() end @trace {:http_request, category: :external} def http_request do Process.sleep(10) NewRelic.set_span(:http, url: "http://example.com", method: "GET", component: "HTTPoison") "bar" end end defmodule TestPlugApp do use Plug.Router use NewRelic.Transaction plug(:match) plug(:dispatch) get "/hello" do Task.async(fn -> Process.sleep(5) Traced.http_request() end) |> Task.await() send_resp(conn, 200, Traced.hello()) end get "/reset_span" do Traced.function() send_resp(conn, 200, "Yo.") end end test "Reset span attributes at the end" do TestHelper.restart_harvest_cycle(Collector.SpanEvent.HarvestCycle) TestHelper.request( TestPlugApp, conn(:get, "/reset_span") |> put_req_header(@dt_header, generate_inbound_payload()) ) span_events = TestHelper.gather_harvest(Collector.SpanEvent.Harvester) [function, _, _] = Enum.find(span_events, fn [ev, _, _] -> ev[:name] == "SpanEventTest.Traced.function/0" end) [http_request, _, _] = Enum.find(span_events, fn [ev, _, _] -> ev[:name] == "SpanEventTest.Traced.http_request/0" end) assert function[:category] == "generic" assert function[:some] == "attribute" refute function[:url] assert http_request[:category] == "http" assert http_request[:"http.url"] TestHelper.pause_harvest_cycle(Collector.SpanEvent.HarvestCycle) TestHelper.pause_harvest_cycle(Collector.TransactionEvent.HarvestCycle) end test "report span events via function tracer inside transaction inside a DT" do TestHelper.restart_harvest_cycle(Collector.SpanEvent.HarvestCycle) TestHelper.restart_harvest_cycle(Collector.TransactionEvent.HarvestCycle) TestHelper.request( TestPlugApp, conn(:get, "/hello") |> put_req_header(@dt_header, generate_inbound_payload()) ) span_events = TestHelper.gather_harvest(Collector.SpanEvent.Harvester) [tx_root_process_event, _, _] = Enum.find(span_events, fn [ev, _, _] -> ev[:"nr.entryPoint"] == true end) [function_event, _, _] = Enum.find(span_events, fn [ev, _, _] -> ev[:name] == "SpanEventTest.Traced.hello/0" end) [nested_function_event, _, _] = Enum.find(span_events, fn [ev, _, _] -> ev[:name] == "SpanEventTest.Traced.do_hello/0" end) [task_event, _, _] = Enum.find(span_events, fn [ev, _, _] -> ev[:name] == "Process" end) [nested_event, _, _] = Enum.find(span_events, fn [ev, _, _] -> ev[:name] == "SpanEventTest.Traced.http_request/0" end) [[_intrinsics, tx_event]] = TestHelper.gather_harvest(Collector.TransactionEvent.Harvester) assert tx_event[:parentId] == "7d3efb1b173fecfa" assert tx_event[:traceId] == "d6b4ba0c3a712ca" assert tx_root_process_event[:traceId] == "d6b4ba0c3a712ca" assert function_event[:traceId] == "d6b4ba0c3a712ca" assert nested_function_event[:traceId] == "d6b4ba0c3a712ca" assert task_event[:traceId] == "d6b4ba0c3a712ca" assert nested_event[:traceId] == "d6b4ba0c3a712ca" assert tx_root_process_event[:transactionId] == tx_event[:guid] assert function_event[:transactionId] == tx_event[:guid] assert nested_function_event[:transactionId] == tx_event[:guid] assert task_event[:transactionId] == tx_event[:guid] assert nested_event[:transactionId] == tx_event[:guid] assert tx_event[:sampled] == true assert tx_root_process_event[:sampled] == true assert function_event[:sampled] == true assert nested_function_event[:sampled] == true assert task_event[:sampled] == true assert nested_event[:sampled] == true assert tx_event[:priority] == 0.987654 assert tx_root_process_event[:priority] == 0.987654 assert function_event[:priority] == 0.987654 assert nested_function_event[:priority] == 0.987654 assert task_event[:priority] == 0.987654 assert nested_event[:priority] == 0.987654 assert function_event[:duration] > 0.009 assert function_event[:duration] < 0.020 assert tx_root_process_event[:parentId] == "5f474d64b9cc9b2a" assert function_event[:parentId] == tx_root_process_event[:guid] assert nested_function_event[:parentId] == function_event[:guid] assert task_event[:parentId] == tx_root_process_event[:guid] assert nested_event[:parentId] == task_event[:guid] assert function_event[:duration] > 0 assert task_event[:duration] > 0 assert nested_event[:duration] > 0 assert nested_event[:category] == "http" assert nested_event[:"http.url"] == "http://example.com" assert nested_event[:"http.method"] == "GET" assert nested_event[:"span.kind"] == "client" assert nested_event[:component] == "HTTPoison" assert nested_event[:args] assert nested_function_event[:category] == "generic" assert nested_function_event[:name] == "SpanEventTest.Traced.do_hello/0" # Ensure these will encode properly Jason.encode!(tx_event) Jason.encode!(span_events) TestHelper.pause_harvest_cycle(Collector.SpanEvent.HarvestCycle) TestHelper.pause_harvest_cycle(Collector.TransactionEvent.HarvestCycle) end describe "Generate span GUIDs" do test "for a process" do NewRelic.DistributedTrace.generate_guid(pid: self()) NewRelic.DistributedTrace.generate_guid(pid: self(), label: {:m, :f, 1}, ref: make_ref()) end end def generate_inbound_payload() do """ { "v": [0,1], "d": { "ty": "Browser", "ac": "190", "tk": "190", "ap": "2827902", "tx": "7d3efb1b173fecfa", "tr": "d6b4ba0c3a712ca", "id": "5f474d64b9cc9b2a", "ti": #{System.system_time(:millisecond) - 100}, "sa": true, "pr": 0.987654 } } """ |> Base.encode64() end end
30.77
97
0.676308
7351fa6dac3027af900fa5f22aeb52eac643d189
18,785
ex
Elixir
lib/livebook/intellisense/identifier_matcher.ex
alaadahmed/livebook
24668c6edb6ee638a3f5291b27bd42a3dfc0c18d
[ "Apache-2.0" ]
null
null
null
lib/livebook/intellisense/identifier_matcher.ex
alaadahmed/livebook
24668c6edb6ee638a3f5291b27bd42a3dfc0c18d
[ "Apache-2.0" ]
null
null
null
lib/livebook/intellisense/identifier_matcher.ex
alaadahmed/livebook
24668c6edb6ee638a3f5291b27bd42a3dfc0c18d
[ "Apache-2.0" ]
null
null
null
defmodule Livebook.Intellisense.IdentifierMatcher do @moduledoc false # This module allows for extracting information about # identifiers based on code and runtime information # (binding, environment). # # This functionality is a basic building block to be # used for code completion and information extraction. # # The implementation is based primarily on `IEx.Autocomplete`. # It also takes insights from `ElixirSense.Providers.Suggestion.Complete`, # which is a very extensive implementation used in the # Elixir Language Server. alias Livebook.Intellisense.Docs @typedoc """ A single identifier together with relevant information. """ @type identifier_item :: {:variable, name(), value()} | {:map_field, name(), value()} | {:in_struct_field, module(), name(), default :: value()} | {:module, module(), display_name(), Docs.documentation()} | {:function, module(), name(), arity(), function_type(), display_name(), Docs.documentation(), list(Docs.signature()), list(Docs.spec())} | {:type, module(), name(), arity(), Docs.documentation()} | {:module_attribute, name(), Docs.documentation()} @type name :: atom() @type display_name :: String.t() @type value :: term() @type function_type :: :function | :macro @exact_matcher &Kernel.==/2 @prefix_matcher &String.starts_with?/2 @doc """ Returns a list of identifiers matching the given `hint` together with relevant information. Evaluation binding and environment is used to expand aliases, imports, nested maps, etc. `hint` may be a single token or line fragment like `if Enum.m`. """ @spec completion_identifiers(String.t(), Code.binding(), Macro.Env.t()) :: list(identifier_item()) def completion_identifiers(hint, binding, env) do context = Code.Fragment.cursor_context(hint) ctx = %{ fragment: hint, binding: binding, env: env, matcher: @prefix_matcher, type: :completion } context_to_matches(context, ctx) end @doc """ Extracts information about an identifier found in `column` in `line`. The function returns range of columns where the identifier is located and a list of matching identifier items. """ @spec locate_identifier(String.t(), pos_integer(), Code.binding(), Macro.Env.t()) :: %{ matches: list(identifier_item()), range: nil | %{from: pos_integer(), to: pos_integer()} } def locate_identifier(line, column, binding, env) do case Code.Fragment.surround_context(line, {1, column}) do %{context: context, begin: {_, from}, end: {_, to}} -> fragment = String.slice(line, 0, to - 1) ctx = %{ fragment: fragment, binding: binding, env: env, matcher: @exact_matcher, type: :locate } matches = context_to_matches(context, ctx) %{matches: matches, range: %{from: from, to: to}} :none -> %{matches: [], range: nil} end end # Takes a context returned from Code.Fragment.cursor_context # or Code.Fragment.surround_context and looks up matching # identifier items defp context_to_matches(context, ctx) do case context do {:alias, alias} -> match_alias(List.to_string(alias), ctx, false) {:unquoted_atom, unquoted_atom} -> match_erlang_module(List.to_string(unquoted_atom), ctx) {:dot, path, hint} -> match_dot(path, List.to_string(hint), ctx) {:dot_arity, path, hint} -> match_dot(path, List.to_string(hint), %{ctx | matcher: @exact_matcher}) {:dot_call, _path, _hint} -> match_default(ctx) :expr -> match_default(ctx) {:local_or_var, local_or_var} -> match_in_struct_fields_or_local_or_var(List.to_string(local_or_var), ctx) {:local_arity, local} -> match_local(List.to_string(local), %{ctx | matcher: @exact_matcher}) {:local_call, local} -> case ctx.type do :completion -> match_default(ctx) :locate -> match_local(List.to_string(local), %{ctx | matcher: @exact_matcher}) end {:operator, operator} -> match_local_or_var(List.to_string(operator), ctx) {:operator_arity, operator} -> match_local(List.to_string(operator), %{ctx | matcher: @exact_matcher}) {:operator_call, _operator} -> match_default(ctx) {:module_attribute, attribute} -> match_module_attribute(List.to_string(attribute), ctx) {:sigil, []} -> match_sigil("", ctx) ++ match_local("~", ctx) {:sigil, sigil} -> match_sigil(List.to_string(sigil), ctx) {:struct, struct} -> match_struct(List.to_string(struct), ctx) # :none _ -> [] end end defp match_dot(path, hint, ctx) do case expand_dot_path(path, ctx) do {:ok, mod} when is_atom(mod) and hint == "" -> match_module_member(mod, hint, ctx) ++ match_module(mod, hint, false, ctx) {:ok, mod} when is_atom(mod) -> match_module_member(mod, hint, ctx) {:ok, map} when is_map(map) -> match_map_field(map, hint, ctx) _ -> [] end end defp expand_dot_path({:var, var}, ctx) do Keyword.fetch(ctx.binding, List.to_atom(var)) end defp expand_dot_path({:alias, alias}, ctx) do {:ok, expand_alias(List.to_string(alias), ctx)} end defp expand_dot_path({:unquoted_atom, var}, _ctx) do {:ok, List.to_atom(var)} end defp expand_dot_path({:module_attribute, _attribute}, _ctx) do :error end defp expand_dot_path({:dot, parent, call}, ctx) do case expand_dot_path(parent, ctx) do {:ok, %{} = map} -> Map.fetch(map, List.to_atom(call)) _ -> :error end end defp match_default(ctx) do match_in_struct_fields_or_local_or_var("", ctx) end defp match_alias(hint, ctx, nested?) do case split_at_last_occurrence(hint, ".") do :error -> match_elixir_root_module(hint, nested?, ctx) ++ match_env_alias(hint, ctx) {:ok, alias, hint} -> mod = expand_alias(alias, ctx) match_module(mod, hint, nested?, ctx) end end defp match_struct(hint, ctx) do for {:module, module, name, documentation} <- match_alias(hint, ctx, true), has_struct?(module), not is_exception?(module), do: {:module, module, name, documentation} end defp has_struct?(mod) do Code.ensure_loaded?(mod) and function_exported?(mod, :__struct__, 1) end defp is_exception?(mod) do Code.ensure_loaded?(mod) and function_exported?(mod, :exception, 1) end defp match_module_member(mod, hint, ctx) do match_module_function(mod, hint, ctx) ++ match_module_type(mod, hint, ctx) end defp match_in_struct_fields_or_local_or_var(hint, ctx) do case expand_struct_fields(ctx) do {:ok, struct, fields} -> for {field, default} <- fields, name = Atom.to_string(field), ctx.matcher.(name, hint), do: {:in_struct_field, struct, field, default} _ -> match_local_or_var(hint, ctx) end end defp expand_struct_fields(ctx) do with {:ok, quoted} <- Code.Fragment.container_cursor_to_quoted(ctx.fragment), {aliases, pairs} <- find_struct_fields(quoted) do mod_name = Enum.join(aliases, ".") mod = expand_alias(mod_name, ctx) fields = if has_struct?(mod) do # Remove the keys that have already been filled, and internal keys Map.from_struct(mod.__struct__) |> Map.drop(Keyword.keys(pairs)) |> Map.reject(fn {key, _} -> key |> Atom.to_string() |> String.starts_with?("_") end) else %{} end {:ok, mod, fields} end end defp find_struct_fields(ast) do ast |> Macro.prewalker() |> Enum.find_value(fn node -> with {:%, _, [{:__aliases__, _, aliases}, {:%{}, _, pairs}]} <- node, {pairs, [{:__cursor__, _, []}]} <- Enum.split(pairs, -1), true <- Keyword.keyword?(pairs) do {aliases, pairs} else _ -> nil end end) end defp match_local_or_var(hint, ctx) do match_local(hint, ctx) ++ match_variable(hint, ctx) end defp match_local(hint, ctx) do imports = ctx.env |> imports_from_env() |> Enum.flat_map(fn {mod, funs} -> match_module_function(mod, hint, ctx, funs) end) special_forms = match_module_function(Kernel.SpecialForms, hint, ctx) imports ++ special_forms end defp match_variable(hint, ctx) do for {key, value} <- ctx.binding, is_atom(key), name = Atom.to_string(key), ctx.matcher.(name, hint), do: {:variable, key, value} end defp match_map_field(map, hint, ctx) do # Note: we need Map.to_list/1 in case this is a struct for {key, value} <- Map.to_list(map), is_atom(key), name = Atom.to_string(key), ctx.matcher.(name, hint), do: {:map_field, key, value} end defp match_sigil(hint, ctx) do for {:function, module, name, arity, type, "sigil_" <> sigil_name, documentation, signatures, specs} <- match_local("sigil_", %{ctx | matcher: @prefix_matcher}), ctx.matcher.(sigil_name, hint), do: {:function, module, name, arity, type, "~" <> sigil_name, documentation, signatures, specs} end defp match_erlang_module(hint, ctx) do for mod <- get_matching_modules(hint, ctx), usable_as_unquoted_module?(mod), name = ":" <> Atom.to_string(mod), do: {:module, mod, name, Livebook.Intellisense.Docs.get_module_documentation(mod)} end # Converts alias string to module atom with regard to the given env defp expand_alias(alias, ctx) do [name | rest] = alias |> String.split(".") |> Enum.map(&String.to_atom/1) case Keyword.fetch(ctx.env.aliases, Module.concat(Elixir, name)) do {:ok, name} when rest == [] -> name {:ok, name} -> Module.concat([name | rest]) :error -> Module.concat([name | rest]) end end defp match_env_alias(hint, ctx) do for {alias, mod} <- ctx.env.aliases, [name] = Module.split(alias), ctx.matcher.(name, hint), do: {:module, mod, name, Livebook.Intellisense.Docs.get_module_documentation(mod)} end defp match_module(base_mod, hint, nested?, ctx) do # Note: we specifically don't want further completion # if `base_mod` is an Erlang module. if base_mod == Elixir or elixir_module?(base_mod) do match_elixir_module(base_mod, hint, nested?, ctx) else [] end end defp elixir_module?(mod) do mod |> Atom.to_string() |> String.starts_with?("Elixir.") end defp match_elixir_root_module(hint, nested?, ctx) do items = match_elixir_module(Elixir, hint, nested?, ctx) # `Elixir` is not a existing module name, but `Elixir.Enum` is, # so if the user types `Eli` the completion should include `Elixir`. if ctx.matcher.("Elixir", hint) do [{:module, Elixir, "Elixir", nil} | items] else items end end defp match_elixir_module(base_mod, hint, nested?, ctx) do # Note: `base_mod` may be `Elixir`, even though it's not a valid module match_prefix = "#{base_mod}.#{hint}" depth = match_prefix |> Module.split() |> length() for mod <- get_matching_modules(match_prefix, ctx), parts = Module.split(mod), length(parts) >= depth, {parent_mod_parts, name_parts} = Enum.split(parts, depth - 1), name_parts = if(nested?, do: name_parts, else: [hd(name_parts)]), name = Enum.join(name_parts, "."), # Note: module can be defined dynamically and its name # may not be a valid alias (e.g. :"Elixir.My.module"). # That's why we explicitly check if the name part makes # for a valid alias piece. valid_alias_piece?("." <> name), mod = Module.concat(parent_mod_parts ++ name_parts), uniq: true, do: {:module, mod, name, Livebook.Intellisense.Docs.get_module_documentation(mod)} end defp valid_alias_piece?(<<?., char, rest::binary>>) when char in ?A..?Z, do: valid_alias_rest?(rest) defp valid_alias_piece?(_), do: false defp valid_alias_rest?(<<char, rest::binary>>) when char in ?A..?Z when char in ?a..?z when char in ?0..?9 when char == ?_, do: valid_alias_rest?(rest) defp valid_alias_rest?(<<>>), do: true defp valid_alias_rest?(rest), do: valid_alias_piece?(rest) defp usable_as_unquoted_module?(mod) do macro_classify_atom(mod) in [:identifier, :unquoted] end defp get_matching_modules(hint, ctx) do get_modules() |> Enum.filter(&ctx.matcher.(Atom.to_string(&1), hint)) |> Enum.uniq() end defp get_modules() do modules = Enum.map(:code.all_loaded(), &elem(&1, 0)) case :code.get_mode() do :interactive -> modules ++ get_modules_from_applications() _otherwise -> modules end end defp get_modules_from_applications do for [app] <- loaded_applications(), {:ok, modules} = :application.get_key(app, :modules), module <- modules, do: module end defp loaded_applications do # If we invoke :application.loaded_applications/0, # it can error if we don't call safe_fixtable before. # Since in both cases we are reaching over the # application controller internals, we choose to match # for performance. :ets.match(:ac_tab, {{:loaded, :"$1"}, :_}) end defp match_module_function(mod, hint, ctx, funs \\ nil) do if ensure_loaded?(mod) do funs = funs || exports(mod) matching_funs = Enum.filter(funs, fn {name, _arity, _type} -> name = Atom.to_string(name) ctx.matcher.(name, hint) end) doc_items = Livebook.Intellisense.Docs.lookup_module_members( mod, Enum.map(matching_funs, &Tuple.delete_at(&1, 2)), kinds: [:function, :macro] ) Enum.map(matching_funs, fn {name, arity, type} -> doc_item = Enum.find(doc_items, %{documentation: nil, signatures: [], specs: []}, fn doc_item -> doc_item.name == name && doc_item.arity == arity end) {:function, mod, name, arity, type, Atom.to_string(name), doc_item && doc_item.documentation, doc_item.signatures, doc_item.specs} end) else [] end end defp exports(mod) do if Code.ensure_loaded?(mod) and function_exported?(mod, :__info__, 1) do macros = mod.__info__(:macros) functions = mod.__info__(:functions) -- [__info__: 1] append_funs_type(macros, :macro) ++ append_funs_type(functions, :function) else functions = mod.module_info(:exports) -- [module_info: 0, module_info: 1] append_funs_type(functions, :function) end end defp append_funs_type(funs, type) do Enum.map(funs, &Tuple.append(&1, type)) end defp match_module_type(mod, hint, ctx) do types = get_module_types(mod) matching_types = Enum.filter(types, fn {name, _arity} -> name = Atom.to_string(name) ctx.matcher.(name, hint) end) doc_items = Livebook.Intellisense.Docs.lookup_module_members(mod, matching_types, kinds: [:type]) Enum.map(matching_types, fn {name, arity} -> doc_item = Enum.find(doc_items, %{documentation: nil}, fn doc_item -> doc_item.name == name && doc_item.arity == arity end) {:type, mod, name, arity, doc_item.documentation} end) end defp get_module_types(mod) do with true <- ensure_loaded?(mod), {:ok, types} <- Code.Typespec.fetch_types(mod) do for {kind, {name, _, args}} <- types, kind in [:type, :opaque] do {name, length(args)} end else _ -> [] end end defp ensure_loaded?(Elixir), do: false defp ensure_loaded?(mod), do: Code.ensure_loaded?(mod) defp imports_from_env(env) do Enum.map(env.functions, fn {mod, funs} -> {mod, append_funs_type(funs, :function)} end) ++ Enum.map(env.macros, fn {mod, funs} -> {mod, append_funs_type(funs, :macro)} end) end defp split_at_last_occurrence(string, pattern) do case :binary.matches(string, pattern) do [] -> :error parts -> {start, _} = List.last(parts) size = byte_size(string) {:ok, binary_part(string, 0, start), binary_part(string, start + 1, size - start - 1)} end end defp match_module_attribute(hint, ctx) do for {attribute, info} <- Module.reserved_attributes(), name = Atom.to_string(attribute), ctx.matcher.(name, hint), do: {:module_attribute, attribute, {"text/markdown", info.doc}} end # --- # TODO: use Macro.classify_atom/1 on Elixir 1.14 def macro_classify_atom(atom) do case macro_inner_classify(atom) do :alias -> :alias :identifier -> :identifier type when type in [:unquoted_operator, :not_callable] -> :unquoted _ -> :quoted end end defp macro_inner_classify(atom) when is_atom(atom) do cond do atom in [:%, :%{}, :{}, :<<>>, :..., :.., :., :"..//", :->] -> :not_callable atom in [:"::"] -> :quoted_operator Macro.operator?(atom, 1) or Macro.operator?(atom, 2) -> :unquoted_operator true -> charlist = Atom.to_charlist(atom) if macro_valid_alias?(charlist) do :alias else case :elixir_config.identifier_tokenizer().tokenize(charlist) do {kind, _acc, [], _, _, special} -> if kind == :identifier and not :lists.member(?@, special) do :identifier else :not_callable end _ -> :other end end end end defp macro_valid_alias?('Elixir' ++ rest), do: macro_valid_alias_piece?(rest) defp macro_valid_alias?(_other), do: false defp macro_valid_alias_piece?([?., char | rest]) when char >= ?A and char <= ?Z, do: macro_valid_alias_piece?(macro_trim_leading_while_valid_identifier(rest)) defp macro_valid_alias_piece?([]), do: true defp macro_valid_alias_piece?(_other), do: false defp macro_trim_leading_while_valid_identifier([char | rest]) when char >= ?a and char <= ?z when char >= ?A and char <= ?Z when char >= ?0 and char <= ?9 when char == ?_ do macro_trim_leading_while_valid_identifier(rest) end defp macro_trim_leading_while_valid_identifier(other) do other end end
29.960128
97
0.618792