hexsha stringlengths 40 40 | size int64 2 991k | ext stringclasses 2 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 208 | max_stars_repo_name stringlengths 6 106 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses list | max_stars_count int64 1 33.5k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 208 | max_issues_repo_name stringlengths 6 106 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses list | max_issues_count int64 1 16.3k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 208 | max_forks_repo_name stringlengths 6 106 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses list | max_forks_count int64 1 6.91k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 991k | avg_line_length float64 1 36k | max_line_length int64 1 977k | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
085a868c005eed1c549985f42dc2ef1a62c789c1 | 4,386 | ex | Elixir | lib/membrane/log/logger.ex | eboskma/membrane_core | e216994fe1ba99c5d228a4b0959faa5fabb13b1c | [
"Apache-2.0"
] | null | null | null | lib/membrane/log/logger.ex | eboskma/membrane_core | e216994fe1ba99c5d228a4b0959faa5fabb13b1c | [
"Apache-2.0"
] | null | null | null | lib/membrane/log/logger.ex | eboskma/membrane_core | e216994fe1ba99c5d228a4b0959faa5fabb13b1c | [
"Apache-2.0"
] | null | null | null | defmodule Membrane.Log.Logger do
@moduledoc deprecated: "Use Elixir `Logger` instead"
@moduledoc """
Module containing functions spawning, shutting down, and handling messages
sent to logger.
"""
use GenServer
alias Membrane.Log.Logger.State
# Type that defines possible return values of start/start_link functions.
@type on_start :: GenServer.on_start()
# Type that defines possible process options passed to start/start_link
# functions.
@type process_options_t :: GenServer.options()
# Type that defines possible logger-specific options passed to
# start/start_link functions.
@type logger_options_t :: struct | nil
# Type that defines possible tags attached to the message
@type tag_t :: atom
# Type that defines possible messages, witch are passed to logger.
@type message_t :: list(message_t) | String.t() | {:binary, binary} | integer
# Type that defines possible log levels.
@type msg_level_t :: :warn | :debug | :info
@doc """
Starts process for logger of given module, initialized with given options and
links it to the current process in the supervision tree.
Works similarly to `GenServer.start_link/3` and has the same return values.
"""
@spec start_link(module, logger_options_t, process_options_t) :: on_start
def start_link(module, logger_options \\ nil, process_options \\ []) do
GenServer.start_link(__MODULE__, {module, logger_options}, process_options)
end
@doc """
Starts process for logger of given module, initialized with given options
outside of the supervision tree.
Works similarly to `GenServer.start/3` and has the same return values.
"""
@spec start(module, logger_options_t, process_options_t) :: on_start
def start(module, logger_options \\ nil, process_options \\ []) do
GenServer.start(__MODULE__, {module, logger_options}, process_options)
end
@doc """
Stops given logger process.
It will wait for reply for amount of time passed as second argument
(in milliseconds).
Will trigger calling `handle_shutdown/2` logger callback.
Returns `:ok`.
"""
@spec shutdown(pid, timeout) :: :ok
def shutdown(server, timeout \\ 5000) do
GenServer.stop(server, :normal, timeout)
:ok
end
# Private API
@impl true
def init({module, options}) do
# Call logger's initialization callback
case module.handle_init(options) do
{:ok, internal_state} ->
state = State.new(module, internal_state)
{:ok, state}
{:error, reason} ->
{:stop, reason}
end
end
@impl true
def terminate(_reason, %State{module: module, internal_state: internal_state}) do
module.handle_shutdown(internal_state)
end
# Callback invoked on incoming buffer.
#
# It will delegate actual processing to handle_log/5.
@impl true
def handle_info(
{:membrane_log, level, content, time, tags},
%State{module: module, internal_state: internal_state} = state
) do
level
|> module.handle_log(content, time, tags, internal_state)
|> handle_callback(state)
|> Membrane.Helper.GenServer.noreply()
end
# Generic handler that can be used to convert return value from
# logger callback to reply that is accepted by GenServer.handle_*.
#
# Case when callback returned successfully and requests no further action.
defp handle_callback({:ok, new_internal_state}, state) do
{:ok, %{state | internal_state: new_internal_state}}
end
# Generic handler that can be used to convert return value from
# logger callback to reply that is accepted by GenServer.handle_info.
#
# Case when callback returned failure.
defp handle_callback({:error, reason, new_internal_state}, %{module: module} = state) do
content = ["Error occurred while trying to log message. Reason = ", inspect(reason)]
case module.handle_log(:warn, content, Membrane.Time.pretty_now(), [], new_internal_state) do
{:ok, new_internal_state} ->
{:ok, %{state | internal_state: new_internal_state}}
{:error, reason, new_internal_state} ->
{{:error, reason}, %{state | internal_state: new_internal_state}}
invalid_callback ->
raise """
Logger callback replies are expected to be one of:
{:ok, state}
{:error, reason, state}
but got callback reply #{inspect(invalid_callback)}.
"""
end
end
end
| 32.25 | 97 | 0.702234 |
085a8d1dbe9f3001126cb7ec4ee2d3a0d3d22bf9 | 2,523 | exs | Elixir | config/dev.exs | helium/roaming-console | 0157d0f1666f50259d2887ed23f6bc5138ce67b6 | [
"Apache-2.0"
] | null | null | null | config/dev.exs | helium/roaming-console | 0157d0f1666f50259d2887ed23f6bc5138ce67b6 | [
"Apache-2.0"
] | 14 | 2022-03-02T17:01:59.000Z | 2022-03-30T17:45:47.000Z | config/dev.exs | helium/roaming-console | 0157d0f1666f50259d2887ed23f6bc5138ce67b6 | [
"Apache-2.0"
] | null | null | null | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :console, ConsoleWeb.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [yarn: ["run", "watch",
cd: Path.expand("../assets", __DIR__)]]
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# command from your terminal:
#
# openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com" -keyout priv/server.key -out priv/server.pem
#
# The `http:` config above can be replaced with:
#
# https: [port: 4000, keyfile: "priv/server.key", certfile: "priv/server.pem"],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Watch static and templates for browser reloading.
config :console, ConsoleWeb.Endpoint,
live_reload: [
patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
~r{priv/gettext/.*(po)$},
~r{lib/console_web/views/.*(ex)$},
~r{lib/console_web/templates/.*(eex)$}
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Configure your database
config :console, Console.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "postgres",
database: "rconsole_dev",
hostname: "localhost",
pool_size: 10
config :console,
packet_purchaser_secrets: [
"1524243720:2JD3juUA9RGaOf3Fpj7fNOylAgZ/jAalgOe45X6+jW4sy9gyCy1ELJrIWKvrgMx/"
]
config :console, Console.Mailer,
adapter: Bamboo.LocalAdapter
config :console, env: Mix.env
config :console,
magic_secret_key: "sk_live_22E51B6F77F4897C"
config :console,
stripe_secret_key: "sk_test_Lvy2r3SRCzwjfh3tvZsOBTrG00Cm8M7v1q"
config :console,
amqp_url: "amqp://guest:guest@localhost"
config :console,
amqp_queue_name: "packets_queue"
config :console,
allowed_ip_range: ["127.0.0.1"]
config :logger, level: :debug
config :console,
socket_check_origin: "//localhost"
| 28.348315 | 170 | 0.720174 |
085ae00bb3efa1f69552783e227e56cf793e868c | 2,427 | ex | Elixir | lib/harness/tree.ex | kianmeng/harness | b68ab97f86a09ebf847bb950068dd9c52a5288bd | [
"Apache-2.0"
] | 2 | 2020-10-30T13:59:02.000Z | 2021-05-03T16:34:01.000Z | lib/harness/tree.ex | kianmeng/harness | b68ab97f86a09ebf847bb950068dd9c52a5288bd | [
"Apache-2.0"
] | 9 | 2020-09-22T14:51:52.000Z | 2021-11-26T15:03:40.000Z | lib/harness/tree.ex | kianmeng/harness | b68ab97f86a09ebf847bb950068dd9c52a5288bd | [
"Apache-2.0"
] | 1 | 2020-10-06T13:11:02.000Z | 2020-10-06T13:11:02.000Z | # credo:disable-for-this-file Credo.Check.Consistency.ParameterPatternMatching
defmodule Harness.Tree do
@moduledoc """
Renders things as a tree
See the original implementation in Mix
[here](https://github.com/elixir-lang/elixir/blob/v1.10/lib/mix/lib/mix/utils.ex).
The original implementation has an optimization for dependency trees which
prevents showing the same dependency tree twice. That's great for printing
small dependency trees, but for file trees, we want to see the entire tree
every time, even if a file or directory name is present many times.
The changes to the original implementation are shown as comments below:
"""
@doc """
Prints the given tree according to the callback.
The callback will be invoked for each node and it
must return a `{printed, children}` tuple.
"""
def print_tree(nodes, callback, opts \\ []) do
pretty? =
case Keyword.get(opts, :format) do
"pretty" -> true
"plain" -> false
_other -> elem(:os.type(), 0) != :win32
end
print_tree(
nodes,
_depth = [],
_parent = nil,
_seen = MapSet.new(),
pretty?,
callback
)
:ok
end
defp print_tree(_nodes = [], _depth, _parent, seen, _pretty, _callback) do
seen
end
defp print_tree([node | nodes], depth, parent, seen, pretty?, callback) do
{{name, info}, children} = callback.(node)
# removed
# key = {parent, name}
info = if(info, do: " #{info}", else: "")
Mix.shell().info(
"#{depth(pretty?, depth)}#{prefix(pretty?, depth, nodes)}#{name}#{info}"
)
seen =
print_tree(
children,
[nodes != [] | depth],
name,
# switched this next line (51) for the next (52)
seen,
# MapSet.put(seen, key),
pretty?,
callback
)
print_tree(nodes, depth, parent, seen, pretty?, callback)
end
defp depth(_pretty?, []), do: ""
defp depth(pretty?, depth),
do: Enum.reverse(depth) |> tl |> Enum.map(&entry(pretty?, &1))
defp entry(false, true), do: "| "
defp entry(false, false), do: " "
defp entry(true, true), do: "│ "
defp entry(true, false), do: " "
defp prefix(false, [], _), do: ""
defp prefix(false, _, []), do: "`-- "
defp prefix(false, _, _), do: "|-- "
defp prefix(true, [], _), do: ""
defp prefix(true, _, []), do: "└── "
defp prefix(true, _, _), do: "├── "
end
| 27.269663 | 84 | 0.601154 |
085b215705c285f88218026c84be4c79199930ef | 2,206 | exs | Elixir | priv/templates/phx.gen.auth/registration_controller_test.exs | faheempatel/phoenix | a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9 | [
"MIT"
] | 18,092 | 2015-01-01T01:51:04.000Z | 2022-03-31T19:37:14.000Z | priv/templates/phx.gen.auth/registration_controller_test.exs | faheempatel/phoenix | a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9 | [
"MIT"
] | 3,905 | 2015-01-01T00:22:47.000Z | 2022-03-31T17:06:21.000Z | priv/templates/phx.gen.auth/registration_controller_test.exs | faheempatel/phoenix | a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9 | [
"MIT"
] | 3,205 | 2015-01-03T10:58:22.000Z | 2022-03-30T14:55:57.000Z | defmodule <%= inspect context.web_module %>.<%= inspect Module.concat(schema.web_namespace, schema.alias) %>RegistrationControllerTest do
use <%= inspect context.web_module %>.ConnCase<%= test_case_options %>
import <%= inspect context.module %>Fixtures
describe "GET <%= web_path_prefix %>/<%= schema.plural %>/register" do
test "renders registration page", %{conn: conn} do
conn = get(conn, Routes.<%= schema.route_helper %>_registration_path(conn, :new))
response = html_response(conn, 200)
assert response =~ "<h1>Register</h1>"
assert response =~ "Log in</a>"
assert response =~ "Register</a>"
end
test "redirects if already logged in", %{conn: conn} do
conn = conn |> log_in_<%= schema.singular %>(<%= schema.singular %>_fixture()) |> get(Routes.<%= schema.route_helper %>_registration_path(conn, :new))
assert redirected_to(conn) == "/"
end
end
describe "POST <%= web_path_prefix %>/<%= schema.plural %>/register" do
@tag :capture_log
test "creates account and logs the <%= schema.singular %> in", %{conn: conn} do
email = unique_<%= schema.singular %>_email()
conn =
post(conn, Routes.<%= schema.route_helper %>_registration_path(conn, :create), %{
"<%= schema.singular %>" => valid_<%= schema.singular %>_attributes(email: email)
})
assert get_session(conn, :<%= schema.singular %>_token)
assert redirected_to(conn) == "/"
# Now do a logged in request and assert on the menu
conn = get(conn, "/")
response = html_response(conn, 200)
assert response =~ email
assert response =~ "Settings</a>"
assert response =~ "Log out</a>"
end
test "render errors for invalid data", %{conn: conn} do
conn =
post(conn, Routes.<%= schema.route_helper %>_registration_path(conn, :create), %{
"<%= schema.singular %>" => %{"email" => "with spaces", "password" => "too short"}
})
response = html_response(conn, 200)
assert response =~ "<h1>Register</h1>"
assert response =~ "must have the @ sign and no spaces"
assert response =~ "should be at least 12 character"
end
end
end
| 40.109091 | 156 | 0.62602 |
085b34154ad9e9e0b7dd6b8917f6523dfdc4c74c | 1,235 | ex | Elixir | release/src-rt-6.x.4708/router/apcupsd/platforms/debian/examples/emacsen-install.ex | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 278 | 2015-11-03T03:01:20.000Z | 2022-01-20T18:21:05.000Z | release/src-rt-6.x.4708/router/apcupsd/platforms/debian/examples/emacsen-install.ex | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 374 | 2015-11-03T12:37:22.000Z | 2021-12-17T14:18:08.000Z | release/src-rt-6.x.4708/router/apcupsd/platforms/debian/examples/emacsen-install.ex | afeng11/tomato-arm | 1ca18a88480b34fd495e683d849f46c2d47bb572 | [
"FSFAP"
] | 96 | 2015-11-22T07:47:26.000Z | 2022-01-20T19:52:19.000Z | #! /bin/sh -e
# /usr/lib/emacsen-common/packages/install/apcupsd
# Written by Jim Van Zandt <jrv@vanzandt.mv.com>, borrowing heavily
# from the install scripts for gettext by Santiago Vila
# <sanvila@ctv.es> and octave by Dirk Eddelbuettel <edd@debian.org>.
FLAVOR=$1
PACKAGE=apcupsd
if [ ${FLAVOR} = emacs ]; then exit 0; fi
echo install/${PACKAGE}: Handling install for emacsen flavor ${FLAVOR}
#FLAVORTEST=`echo $FLAVOR | cut -c-6`
#if [ ${FLAVORTEST} = xemacs ] ; then
# SITEFLAG="-no-site-file"
#else
# SITEFLAG="--no-site-file"
#fi
FLAGS="${SITEFLAG} -q -batch -l path.el -f batch-byte-compile"
ELDIR=/usr/share/emacs/site-lisp/${PACKAGE}
ELCDIR=/usr/share/${FLAVOR}/site-lisp/${PACKAGE}
# Install-info-altdir does not actually exist.
# Maybe somebody will write it.
if test -x /usr/sbin/install-info-altdir; then
echo install/${PACKAGE}: install Info links for ${FLAVOR}
install-info-altdir --quiet --section "" "" --dirname=${FLAVOR} /usr/info/${PACKAGE}.info.gz
fi
install -m 755 -d ${ELCDIR}
cd ${ELDIR}
FILES=`echo *.el`
cp ${FILES} ${ELCDIR}
cd ${ELCDIR}
cat << EOF > path.el
(setq load-path (cons "." load-path) byte-compile-warnings nil)
EOF
${FLAVOR} ${FLAGS} ${FILES}
rm -f *.el path.el
exit 0
| 26.847826 | 96 | 0.68664 |
085b640f8a596c3587359aae0a98cc8a8ddfca31 | 467 | exs | Elixir | example/priv/repo/migrations/20160715134921_add_versions.exs | rschef/paper_trail | 6ab8b29ee97b46222cc48d376daea70fc5cb8105 | [
"MIT"
] | 484 | 2016-06-19T19:33:31.000Z | 2022-03-30T00:04:06.000Z | example/priv/repo/migrations/20160715134921_add_versions.exs | rschef/paper_trail | 6ab8b29ee97b46222cc48d376daea70fc5cb8105 | [
"MIT"
] | 125 | 2016-12-13T14:28:45.000Z | 2022-03-01T00:07:06.000Z | example/priv/repo/migrations/20160715134921_add_versions.exs | rschef/paper_trail | 6ab8b29ee97b46222cc48d376daea70fc5cb8105 | [
"MIT"
] | 80 | 2016-09-09T02:12:41.000Z | 2022-03-29T20:51:12.000Z | defmodule Repo.Migrations.AddVersions do
use Ecto.Migration
def change do
create table(:versions) do
add :event, :string
add :item_type, :string
add :item_id, :integer
add :item_changes, :map
add :origin, :string
add :originator_id, references(:people)
add :meta, :map
add :inserted_at, :utc_datetime, null: false
end
create index(:versions, [:originator_id])
end
end
| 23.35 | 51 | 0.608137 |
085b6abdfbadaf86a34da5da34c6c5c891d8df2d | 1,673 | exs | Elixir | test/teiserver/coordinator/setup_test.exs | badosu/teiserver | 19b623aeb7c2ab28756405f7486e92b714777c54 | [
"MIT"
] | 4 | 2021-07-29T16:23:20.000Z | 2022-02-23T05:34:36.000Z | test/teiserver/coordinator/setup_test.exs | Jazcash/teiserver | fec14784901cb2965d8c1350fe84107c57451877 | [
"MIT"
] | 14 | 2021-08-01T02:36:14.000Z | 2022-01-30T21:15:03.000Z | test/teiserver/coordinator/setup_test.exs | Jazcash/teiserver | fec14784901cb2965d8c1350fe84107c57451877 | [
"MIT"
] | 7 | 2021-05-13T12:55:28.000Z | 2022-01-14T06:39:06.000Z | defmodule Teiserver.Protocols.Coordinator.SetupTest do
use Central.ServerCase, async: false
alias Teiserver.{Client}
alias Teiserver.Account.UserCache
alias Teiserver.TeiserverTestLib
alias Teiserver.Battle.Lobby
alias Teiserver.Common.PubsubListener
import Teiserver.TeiserverTestLib,
only: [tachyon_auth_setup: 0, _tachyon_recv: 1]
@sleep 50
setup do
%{socket: socket, user: user, pid: pid} = tachyon_auth_setup()
UserCache.update_user(%{user | moderator: true})
Client.refresh_client(user.id)
{:ok, socket: socket, user: user, pid: pid}
end
test "test command vs no command", %{user: user, socket: socket} do
lobby = TeiserverTestLib.make_battle(%{
founder_id: user.id,
founder_name: user.name
})
lobby = Lobby.get_battle!(lobby.id)
listener = PubsubListener.new_listener(["legacy_battle_updates:#{lobby.id}"])
# No command
result = Lobby.say(user.id, "Test message", lobby.id)
assert result == :ok
:timer.sleep(@sleep)
messages = PubsubListener.get(listener)
assert messages == [{:battle_updated, lobby.id, {user.id, "Test message", lobby.id}, :say}]
# Now command
result = Lobby.say(user.id, "$settag tagname tagvalue", lobby.id)
assert result == :ok
:timer.sleep(@sleep)
reply = _tachyon_recv(socket)
assert reply == :timeout
# Converted message should appear here
[m1, m2] = PubsubListener.get(listener)
assert m1 == {:battle_updated, lobby.id, {user.id, "$settag tagname tagvalue", lobby.id}, :say}
{:battle_updated, _lobby_id, %{"tagname" => "tagvalue", "server/match/uuid" => _uuid}, :add_script_tags} = m2
end
end
| 30.981481 | 113 | 0.687986 |
085b6ae85cbc793e4ccc310272fd303ef1465385 | 908 | ex | Elixir | lib/web/views/error_view.ex | smartlogic/Challenge_gov | b4203d1fcfb742dd17ecfadb9e9c56ad836d4254 | [
"CC0-1.0"
] | 9 | 2020-02-26T20:24:38.000Z | 2022-03-22T21:14:52.000Z | lib/web/views/error_view.ex | smartlogic/Challenge_gov | b4203d1fcfb742dd17ecfadb9e9c56ad836d4254 | [
"CC0-1.0"
] | 15 | 2020-04-22T19:33:24.000Z | 2022-03-26T15:11:17.000Z | lib/web/views/error_view.ex | smartlogic/Challenge_gov | b4203d1fcfb742dd17ecfadb9e9c56ad836d4254 | [
"CC0-1.0"
] | 4 | 2020-04-27T22:58:57.000Z | 2022-01-14T13:42:09.000Z | defmodule Web.ErrorView do
use Web, :view
def render("errors.json", %{changeset: changeset}) do
errors =
Enum.reduce(changeset.errors, %{}, fn {field, error}, errors ->
error = translate_error(error)
field_errors = Map.get(errors, field, [])
Map.put(errors, field, [error | field_errors])
end)
%{errors: errors}
end
def render("500-fallthrough.html", _assigns) do
"Something fell through and reached an error"
end
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.html", _assigns) do
# "Internal Server Error"
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.html" becomes
# "Not Found".
def template_not_found(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
end
| 28.375 | 69 | 0.680617 |
085b74aca4689aa18869039001f6750af1d7a265 | 545 | exs | Elixir | chapter_5/process_bottleneck.exs | librity/elixir_in_action | d2df441ceb7e6a0d3f18bc3ab3c59570125fcdec | [
"MIT"
] | 3 | 2021-04-22T11:55:58.000Z | 2021-08-22T13:19:56.000Z | chapter_5/process_bottleneck.exs | librity/elixir_in_action | d2df441ceb7e6a0d3f18bc3ab3c59570125fcdec | [
"MIT"
] | null | null | null | chapter_5/process_bottleneck.exs | librity/elixir_in_action | d2df441ceb7e6a0d3f18bc3ab3c59570125fcdec | [
"MIT"
] | 3 | 2021-04-22T21:19:45.000Z | 2021-08-22T13:20:03.000Z | defmodule Server do
def start, do: spawn(&loop/0)
def send_msg(server, message) do
send(server, {self(), message})
receive do
{:response, response} -> response
end
end
defp loop do
receive do
{caller, msg} ->
Process.sleep(1000)
send(caller, {:response, msg})
end
loop()
end
end
pid = Server.start()
Enum.each(
1..5,
fn i ->
spawn(fn ->
IO.puts("Sending msg ##{i}")
response = Server.send_msg(pid, i)
IO.puts("Response: #{response}")
end)
end
)
| 15.571429 | 40 | 0.561468 |
085b9baf6b1be81aba51b04556276d38e9cd7256 | 425 | exs | Elixir | test/modules/definition_named.exs | kianmeng/unsafe | 76951b0b9e4f8b82e32fbb5a91e67de8963898e8 | [
"MIT"
] | 11 | 2017-11-09T05:58:25.000Z | 2020-01-23T02:12:27.000Z | test/modules/definition_named.exs | kianmeng/unsafe | 76951b0b9e4f8b82e32fbb5a91e67de8963898e8 | [
"MIT"
] | 3 | 2017-11-09T09:23:41.000Z | 2018-07-30T16:21:48.000Z | test/modules/definition_named.exs | kianmeng/unsafe | 76951b0b9e4f8b82e32fbb5a91e67de8963898e8 | [
"MIT"
] | 2 | 2018-07-30T02:59:14.000Z | 2021-11-27T13:05:58.000Z | defmodule UnsafeTest.DefinitionNamed do
use Unsafe.Generator
@unsafe { :test, [ :bool ], :private_handler }
@unsafe { :test, [ :bool, :opts ], :private_handler }
def test(bool, opts \\ [])
def test(true, _opts),
do: { :ok, true }
def test(false, _opts),
do: { :error, false }
defp private_handler({ :ok, true }),
do: true
defp private_handler({ :error, false }),
do: raise RuntimeError
end
| 23.611111 | 55 | 0.625882 |
085bcc7bedb537ec98ddbb5667de447f244187f1 | 3,184 | ex | Elixir | lib/securex_permissions.ex | wasitanbits/secruex | 5ae45935612e965fd0db682e510bf3d4dc14565e | [
"Apache-2.0"
] | 3 | 2022-03-05T13:46:23.000Z | 2022-03-07T13:15:29.000Z | lib/securex_permissions.ex | DevWasi/secruex | 5ae45935612e965fd0db682e510bf3d4dc14565e | [
"Apache-2.0"
] | null | null | null | lib/securex_permissions.ex | DevWasi/secruex | 5ae45935612e965fd0db682e510bf3d4dc14565e | [
"Apache-2.0"
] | null | null | null | defmodule SecureX.Permissions do
alias SecureXWeb.{PermissionController}
@moduledoc """
Contains CRUD For Permissions.
"""
@doc """
Get list of Permissions by User Roles.
List/1 is without pagination,
List/2 & List/3 is with pagination.
## Examples
iex> list([], 1)
{:error, :bad_input}
iex> list([])
{:error, :bad_input}
iex> list(["owner", "super_admin"], 1)
{:ok,
%Scrivener.Page{
entries: [
%{permission: 4, resource_id: "roles", role_id: "owner"},
%{permission: 4, resource_id: "users", role_id: "owner"},
%{permission: 4, resource_id: "stock_types", role_id: "owner"},
%{permission: 4, resource_id: "sales", role_id: "owner"},
%{permission: 4, resource_id: "stocks", role_id: "owner"},
%{permission: 4, resource_id: "providers", role_id: "owner"},
%{permission: 4, resource_id: "fuel_dispensers", role_id: "owner"},
%{permission: 4, resource_id: "employees", role_id: "owner"},
%{permission: 4, resource_id: "customers", role_id: "owner"},
%{permission: 4, resource_id: "stock_stats", role_id: "owner"}
],
page_number: 1,
page_size: 10,
total_entries: 22,
total_pages: 3
}
}
iex> list(["owner", "super_admin"])
[
%{ permission: 4, resource_id: "users", role_id: "admin"},
%{ permission: 4, resource_id: "person_form", role_id: "super_admin"}
]
"""
@spec list(list(), number(), number()) :: tuple()
def list(list, page \\ nil, page_size \\ 10),
do: PermissionController.list_permissions(list, page, page_size)
@doc """
Add a Permission. You can send either `Atom Map` or `String Map` to add a Permission.
## Examples
iex> add(%{"permission" => -1, "resource_id" => "users", "role_id" => "super_admin"})
%Permission{
id: 1,
permission: -1,
resource_id: "users",
role_id: "super_admin"
}
"""
@spec add(map()) :: tuple()
def add(params) do
case PermissionController.create(params) do
{:error, error} -> {:error, error}
{:ok, role} -> {:ok, role}
end
end
@doc """
Update a Permission. You can send either `Atom Map` or `String Map` to update a Permission.
## Examples
iex> update(%{"id" => "1", "resource_id" => "users", "permission" => 4, "role_id" => "admin"})
%Permission{
id: 1,
permission: 4,
resource_id: "users",
role_id: "admin"
}
"""
@spec update(map()) :: tuple()
def update(params) do
case PermissionController.update(params) do
{:error, error} -> {:error, error}
{:ok, role} -> {:ok, role}
end
end
@doc """
Delete a Permission.
## Examples
iex> delete(%{"id" => 1)
%Permission{
id: 1,
permission: 4,
resource_id: "users",
role_id: "admin"
}
"""
@spec delete(map()) :: tuple()
def delete(params) do
case PermissionController.delete(params) do
{:error, error} -> {:error, error}
{:ok, role} -> {:ok, role}
end
end
end
| 27.213675 | 100 | 0.556219 |
085be1f3f8a94f353b39628b922ed4eda69a94e3 | 132 | exs | Elixir | learn/test/learn_test.exs | Electrux/Elixir-Code | d0e2cf0c3caa7269f6438a378b750ced7531e0f4 | [
"BSD-3-Clause"
] | null | null | null | learn/test/learn_test.exs | Electrux/Elixir-Code | d0e2cf0c3caa7269f6438a378b750ced7531e0f4 | [
"BSD-3-Clause"
] | null | null | null | learn/test/learn_test.exs | Electrux/Elixir-Code | d0e2cf0c3caa7269f6438a378b750ced7531e0f4 | [
"BSD-3-Clause"
] | null | null | null | defmodule LearnTest do
use ExUnit.Case
doctest Learn
test "greets the world" do
assert Learn.hello() == :world
end
end
| 14.666667 | 34 | 0.69697 |
085c3a2c3ecfa6f54c6bdc73dbb1b5b52c2a0a17 | 247 | exs | Elixir | config/test.exs | exit9/jwt-google-tokens | 8e2d97fde486dc43687d92e91b6951515fef133b | [
"Apache-2.0"
] | null | null | null | config/test.exs | exit9/jwt-google-tokens | 8e2d97fde486dc43687d92e91b6951515fef133b | [
"Apache-2.0"
] | null | null | null | config/test.exs | exit9/jwt-google-tokens | 8e2d97fde486dc43687d92e91b6951515fef133b | [
"Apache-2.0"
] | 1 | 2019-11-23T12:09:14.000Z | 2019-11-23T12:09:14.000Z | use Mix.Config
config :logger, level: :debug
config :jwt, :googlecerts, Jwt.GoogleCerts.PublicKey.Mock
config :jwt, :firebasecerts, Jwt.FirebaseCerts.PublicKey.Mock
config :jwt, :timeutils, Jwt.TimeUtils.Mock
config :jwt, :check_signature, true
| 27.444444 | 61 | 0.785425 |
085c4726100db89f8ca30c72555c8c80e5704b78 | 829 | exs | Elixir | mix.exs | kipcole9/tempo | 817714acd6baf38be3a8a997ef1d205206d79adc | [
"Apache-2.0"
] | 16 | 2021-01-03T12:53:52.000Z | 2021-08-25T03:47:14.000Z | mix.exs | kipcole9/tempo | 817714acd6baf38be3a8a997ef1d205206d79adc | [
"Apache-2.0"
] | 3 | 2021-01-10T09:32:22.000Z | 2021-07-19T12:16:17.000Z | mix.exs | kipcole9/tempo | 817714acd6baf38be3a8a997ef1d205206d79adc | [
"Apache-2.0"
] | 1 | 2021-01-10T09:01:11.000Z | 2021-01-10T09:01:11.000Z | defmodule Tempo.MixProject do
use Mix.Project
def project do
[
app: :tempo,
version: "0.1.0",
elixir: "~> 1.11",
elixirc_paths: elixirc_paths(Mix.env()),
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
[
{:nimble_parsec, "~> 1.0"},
{:ex_cldr_calendars, "~> 1.15"},
{:astro, github: "kipcole9/astro", branch: "lunar"},
{:ex_doc, "~> 0.21", runtime: false}
]
end
defp elixirc_paths(:test), do: ["lib", "mix", "test", "test/support"]
defp elixirc_paths(:dev), do: ["lib", "mix", "bench"]
defp elixirc_paths(_), do: ["lib"]
end
| 23.027778 | 71 | 0.576598 |
085c5bc3f9fdbd0c5eff7744ac3144278f407a9f | 13,489 | ex | Elixir | lib/militerm/systems/mixins.ex | jgsmith/militerm | c4252d0a93f5620b90750ac2b61baf282e9ef7eb | [
"Apache-2.0"
] | 6 | 2017-06-16T10:26:35.000Z | 2021-04-07T15:01:00.000Z | lib/militerm/systems/mixins.ex | jgsmith/militerm | c4252d0a93f5620b90750ac2b61baf282e9ef7eb | [
"Apache-2.0"
] | 2 | 2020-04-14T02:17:46.000Z | 2021-03-10T11:09:05.000Z | lib/militerm/systems/mixins.ex | jgsmith/militerm | c4252d0a93f5620b90750ac2b61baf282e9ef7eb | [
"Apache-2.0"
] | null | null | null | defmodule Militerm.Systems.Mixins do
@moduledoc """
The Mixins system manages running code defined in a mixin and inspecting aspects
of the mixin.
"""
alias Militerm.Services.Mixins, as: MixinService
alias Militerm.Systems.Mixins
require Logger
def introspect(this_mixin) do
data = MixinService.get(this_mixin)
data.mixins
|> Enum.reverse()
|> Enum.reduce(%{}, fn mixin, acc ->
deep_merge(acc, introspect(mixin))
end)
|> deep_merge(%{
calculations: keys_with_attribution(data.calculations, this_mixin),
reactions: keys_with_attribution(data.reactions, this_mixin),
abilities: keys_with_attribution(data.abilities, this_mixin),
traits: keys_with_attribution(data.traits, this_mixin),
validators: keys_with_attribution(data.validators, this_mixin)
})
end
defp deep_merge(into, from) when is_map(into) and is_map(from) do
Map.merge(into, from, fn _k, v1, v2 -> deep_merge(v1, v2) end)
end
defp deep_merge(v1, v2), do: v2
defp keys_with_attribution(map, attr) do
map
|> Map.keys()
|> Enum.map(fn k -> {k, attr} end)
|> Enum.into(%{})
end
def execute_event(name, entity_id, event, role, args) when is_binary(event) do
path = event |> String.split(":", trim: true) |> Enum.reverse()
execute_event(name, entity_id, path, role, args)
end
def execute_event(name, entity_id, path, role, args) do
case get_mixin(name) do
{:ok, mixin} ->
cond do
do_has_event?(mixin, path, role) ->
do_event(mixin, entity_id, path, role, args)
do_has_event?(mixin, path, "any") ->
do_event(mixin, entity_id, path, "any", args)
:else ->
false
end
_ ->
false
end
end
def has_event?(name, event, role) when is_binary(event) do
path = event |> String.split(":", trim: true) |> Enum.reverse()
has_event?(name, path, role)
end
def has_event?(name, path, role) do
case get_mixin(name) do
{:ok, mixin} ->
res = do_has_event?(mixin, path, role)
Logger.debug(fn ->
[
"- (",
name,
") has event ",
Enum.join(Enum.reverse(path), ":"),
" as ",
role,
": ",
inspect(res)
]
end)
res
_ ->
Logger.debug(fn ->
[
"- (",
name,
") has event ",
Enum.join(Enum.reverse(path), ":"),
" as ",
role,
": false"
]
end)
false
end
end
def has_exact_event?(name, event, role) when is_binary(event) do
path = event |> String.split(":", trim: true) |> Enum.reverse()
has_exact_event?(name, path, role)
end
def has_exact_event?(name, path, role) do
case get_mixin(name) do
{:ok, mixin} ->
do_has_exact_event?(mixin, path, role)
_ ->
false
end
end
def ability(name, entity_id, ability, role, args) when is_binary(ability) do
path = ability |> String.split(":", trim: true) |> Enum.reverse()
ability(name, entity_id, path, role, args)
end
def ability(name, entity_id, ability, role, args) do
case get_mixin(name) do
{:ok, mixin} ->
if role == "any" or do_has_ability?(mixin, ability, role) do
do_ability(mixin, entity_id, ability, role, args)
else
do_ability(mixin, entity_id, ability, "any", args)
end
_ ->
false
end
end
def has_ability?(name, ability, role) when is_binary(ability) do
path = ability |> String.split(":", trim: true) |> Enum.reverse()
has_ability?(name, path, role)
end
def has_ability?(name, ability, role) do
case get_mixin(name) do
{:ok, mixin} ->
do_has_ability?(mixin, ability, role) or do_has_ability?(mixin, ability, "any")
_ ->
false
end
end
def has_exact_ability?(name, ability, role) when is_binary(ability) do
path = ability |> String.split(":", trim: true) |> Enum.reverse()
has_exact_ability?(name, path, role)
end
def has_exact_ability?(name, ability, role) do
case get_mixin(name) do
{:ok, mixin} ->
do_has_exact_ability?(mixin, ability, role)
_ ->
false
end
end
def trait(name, entity_id, trait, args) do
case get_mixin(name) do
{:ok, mixin} ->
if do_has_trait?(mixin, trait) do
do_trait(mixin, entity_id, trait, args)
else
false
end
_ ->
false
end
end
def has_trait?(name, trait) do
case get_mixin(name) do
{:ok, mixin} ->
do_has_trait?(mixin, trait)
_ ->
false
end
end
def has_exact_trait?(name, trait) do
case get_mixin(name) do
{:ok, mixin} ->
do_has_exact_trait?(mixin, trait)
_ ->
false
end
end
def validates?(name, path) do
case get_mixin(name) do
{:ok, mixin} ->
has_validation?(mixin, path)
_ ->
false
end
end
def has_validation?(%{validations: validations, mixins: mixins}, path) do
cond do
Map.has_key?(validations, path) ->
true
Enum.any?(mixins, fn mixin -> Mixins.validates?(mixin, path) end) ->
true
:else ->
false
end
end
def has_validation?(_, _), do: false
def validate(name, entity_id, path, args) do
case get_mixin(name) do
{:ok, mixin} ->
do_validation(mixin, entity_id, path, args)
_ ->
nil
end
end
defp do_validation(mixin, entity_id, path, args) do
with %{validations: validations, mixins: mixins} <- mixin,
{:ok, value} <-
validations
|> execute_if_in_map(entity_id, path, args)
|> execute_if_mixin(
mixins,
:has_validation?,
:validate,
entity_id,
path,
args
) do
value
else
_ -> nil
end
end
def calculates?(name, path) do
case get_mixin(name) do
{:ok, mixin} ->
has_calculation?(mixin, path)
_ ->
false
end
end
def has_calculation?(%{calculations: calculations, mixins: mixins}, path) do
cond do
Map.has_key?(calculations, path) ->
true
Enum.any?(mixins, fn mixin -> Mixins.calculates?(mixin, path) end) ->
true
:else ->
false
end
end
def has_calculation?(_, _), do: false
def calculate(name, entity_id, path, args) do
case get_mixin(name) do
{:ok, mixin} ->
do_calculation(mixin, entity_id, path, args)
_ ->
nil
end
end
defp do_calculation(mixin, entity_id, path, args) do
with %{calculations: calculations, mixins: mixins} <- mixin,
{:ok, value} <-
calculations
|> execute_if_in_map(entity_id, path, args)
|> execute_if_mixin(
mixins,
:calculates?,
:calculate,
entity_id,
path,
args
) do
value
else
_ -> nil
end
end
defp do_event(_, _, [], _, _), do: true
defp do_event(mixin, entity_id, event, role, args) do
case mixin do
%{reactions: events, mixins: mixins} ->
handled =
events
|> execute_if_in_map(entity_id, event, role, args)
|> execute_if_mixin(
mixins,
:has_exact_event?,
:execute_event,
entity_id,
event,
role,
args
)
case handled do
{:ok, value} ->
value
otherwise ->
otherwise
end
_ ->
false
end
end
defp do_has_event?(_, [], _), do: false
defp do_has_event?(nil, _, _), do: false
defp do_has_event?(mixin, event, role) do
if do_has_exact_event?(mixin, event, role) do
true
else
# chop off the last bit and run again - remember, we've reversed the event bits
do_has_event?(mixin, Enum.drop(event, 1), role)
end
end
defp do_has_exact_event?(nil, _, _), do: false
defp do_has_exact_event?(mixin, event, role) do
case mixin do
%{reactions: events, mixins: mixins} ->
if Map.has_key?(events, {event, role}) do
true
else
# check mixins
Enum.any?(mixins, fn name ->
has_exact_event?(name, event, role)
end)
end
_ ->
false
end
end
defp do_ability(_, _, [], _, _), do: false
defp do_ability(mixin, entity_id, ability, role, args) do
case mixin do
%{abilities: abilities, mixins: mixins} ->
handled =
abilities
|> execute_if_in_map(entity_id, ability, role, args)
|> execute_if_mixin(
mixins,
:has_exact_ability?,
:ability,
entity_id,
ability,
role,
args
)
case handled do
{:ok, value} ->
value
_ ->
do_ability(mixin, entity_id, Enum.drop(ability, 1), role, args)
end
_ ->
false
end
end
defp do_has_ability?(_, [], _), do: false
defp do_has_ability?(nil, _, _), do: false
defp do_has_ability?(mixin, ability, role) do
if do_has_exact_ability?(mixin, ability, role) do
true
else
# chop off the last bit and run again - remember, we've reversed the event bits
do_has_ability?(mixin, Enum.drop(ability, 1), role)
end
end
defp do_has_exact_ability?(mixin, ability, role) do
case mixin do
%{abilities: abilities, mixins: mixins} ->
cond do
Map.has_key?(abilities, {ability, role}) ->
true
Enum.any?(mixins, fn name -> has_exact_ability?(name, ability, role) end) ->
true
:else ->
false
end
_ ->
false
end
end
defp do_trait(mixin, entity_id, trait, args) do
with %{traits: traits, mixins: mixins} <- mixin,
{:ok, value} <-
traits
|> execute_if_in_map(entity_id, trait, args)
|> execute_if_mixin(
mixins,
:has_exact_trait?,
:trait,
entity_id,
trait,
args
) do
value
else
_ -> false
end
end
defp do_has_trait?(_, ""), do: false
defp do_has_trait?(nil, _), do: false
defp do_has_trait?(mixin, trait) do
do_has_exact_trait?(mixin, trait)
end
defp do_has_exact_trait?(mixin, trait) do
case mixin do
%{traits: traits, mixins: mixins} ->
cond do
Map.has_key?(traits, trait) ->
true
Enum.any?(mixins, fn mixin -> Mixins.has_exact_trait?(mixin, trait) end) ->
true
:else ->
false
end
_ ->
false
end
end
defp execute_if_in_map(events, entity_id, event, role, args) do
case Map.get(events, {event, role}) do
code when is_tuple(code) ->
# IO.inspect({:code, event, role, code}, limit: :infinity)
Logger.debug(fn ->
[
entity_id,
": execute code for ",
inspect(event),
" as ",
role,
": ",
inspect(code, limit: :infinity)
]
end)
ret =
{:ok, Militerm.Machines.Script.run(code, Map.put(args, "this", {:thing, entity_id}))}
Logger.debug([entity_id, ": finished executing code for ", inspect(event), " as ", role])
ret
_ ->
:unhandled
end
end
defp execute_if_in_map(events, entity_id, event, args) do
case Map.get(events, event) do
code when is_tuple(code) ->
Logger.debug(fn ->
[
entity_id,
": execute code for ",
inspect(event),
": ",
inspect(code, limit: :infinity)
]
end)
ret =
{:ok, Militerm.Machines.Script.run(code, Map.put(args, "this", {:thing, entity_id}))}
Logger.debug([entity_id, ": finished executing code for ", inspect(event)])
ret
_ ->
:unhandled
end
end
defp execute_if_mixin({:ok, _} = result, _, _, _, _, _, _, _), do: result
defp execute_if_mixin(:unhandled, mixins, predicate, method, entity_id, event, role, args) do
case Enum.find(mixins, fn mixin -> apply(Mixins, predicate, [mixin, event, role]) end) do
nil ->
:unhandled
mixin ->
Logger.debug([entity_id, " handing off ", inspect(event), " as ", role, " to ", mixin])
{:ok, apply(Mixins, method, [mixin, entity_id, event, role, args])}
end
end
defp execute_if_mixin({:ok, _} = result, _, _, _, _, _, _), do: result
defp execute_if_mixin(:unhandled, mixins, predicate, method, entity_id, event, args) do
case Enum.find(mixins, fn mixin -> apply(Mixins, predicate, [mixin, event]) end) do
nil ->
:unhandled
mixin ->
Logger.debug([entity_id, " handing off ", inspect(event), " to ", mixin])
{:ok, apply(Mixins, method, [mixin, entity_id, event, args])}
end
end
defp get_mixin(name) do
case MixinService.get(name) do
%{} = mixin ->
{:ok, mixin}
_ ->
:error
end
end
end
| 23.541012 | 97 | 0.54689 |
085ca33b4d3962209a6a4299a2373f7504589db2 | 9,470 | ex | Elixir | lib/astarte_flow/flows/flow.ex | matt-mazzucato/astarte_flow | e8644b5a27edf325977f5bced9a919f20e289ee2 | [
"Apache-2.0"
] | null | null | null | lib/astarte_flow/flows/flow.ex | matt-mazzucato/astarte_flow | e8644b5a27edf325977f5bced9a919f20e289ee2 | [
"Apache-2.0"
] | null | null | null | lib/astarte_flow/flows/flow.ex | matt-mazzucato/astarte_flow | e8644b5a27edf325977f5bced9a919f20e289ee2 | [
"Apache-2.0"
] | null | null | null | #
# This file is part of Astarte.
#
# Copyright 2020 Ispirata Srl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
defmodule Astarte.Flow.Flows.Flow do
@moduledoc """
This module implements an embedded_schema representing a Flow and also
the GenServer responsible of starting and monitoring the Flow.
"""
use GenServer
use Ecto.Schema
import Ecto.Changeset
alias Astarte.Flow.Blocks.Container
alias Astarte.Flow.Flows.Flow
alias Astarte.Flow.Flows.Registry, as: FlowsRegistry
alias Astarte.Flow.Flows.RealmRegistry
alias Astarte.Flow.K8s
alias Astarte.Flow.PipelineBuilder
alias Astarte.Flow.Pipelines
alias Astarte.Flow.Pipelines.Pipeline
require Logger
@retry_timeout_ms 10_000
@primary_key false
@derive {Phoenix.Param, key: :name}
embedded_schema do
field :config, :map, default: %{}
field :name, :string
field :pipeline, :string
end
@doc false
def changeset(%Flow{} = flow, attrs) do
flow
|> cast(attrs, [:pipeline, :name, :config])
|> validate_required([:pipeline, :name])
|> validate_format(:name, ~r/^[a-zA-Z0-9][a-zA-Z0-9-]+$/)
end
defmodule State do
defstruct [
:realm,
:flow,
:pipeline,
:status,
container_block_pids: [],
block_pids: []
]
end
@doc """
Start a Flow as linked process.
Arguments:
- `realm`: the realm the Flow belongs to.
- `flow`: a `%Flow{}` struct with the parameters of the Flow.
"""
def start_link(args) do
realm = Keyword.fetch!(args, :realm)
flow = Keyword.fetch!(args, :flow)
GenServer.start_link(__MODULE__, args, name: via_tuple(realm, flow.name))
end
@doc """
Returns the `%Flow{}` struct that was used to create the flow.
"""
def get_flow(realm, name) do
via_tuple(realm, name)
|> get_flow()
end
@doc """
See `get_flow/2`.
"""
def get_flow(pid_or_via_tuple) do
GenServer.call(pid_or_via_tuple, :get_flow)
end
@doc """
Returns a `Stream` created by calling `GenStage.stream/1` on the last stage of the Flow.
"""
def tap(realm, name) do
via_tuple(realm, name)
|> GenServer.call(:tap)
end
defp via_tuple(realm, name) do
{:via, Registry, {FlowsRegistry, {realm, name}}}
end
@impl true
def init(args) do
Process.flag(:trap_exit, true)
realm = Keyword.fetch!(args, :realm)
flow = Keyword.fetch!(args, :flow)
_ = Logger.info("Starting Flow #{flow.name}.", flow: flow.name, tag: "flow_start")
with {:ok, %Pipeline{source: source}} <- Pipelines.get_pipeline(realm, flow.pipeline),
pipeline = PipelineBuilder.build(source, %{"config" => flow.config}),
state = %State{realm: realm, flow: flow, pipeline: pipeline},
{:ok, state} <- start_flow(realm, flow, pipeline, state) do
_ = Registry.register(RealmRegistry, realm, flow)
# Right here all blocks are started, next step is bringing up the containers
Logger.debug("Flow #{flow.name} initialized.")
if state.container_block_pids == [] do
# No containers, so no need to use K8s
send(self(), :connect_blocks)
{:ok, %{state | status: :connecting_blocks}}
else
send(self(), :initialize_k8s_flow)
{:ok, %{state | status: :collecting_containers}}
end
else
{:error, :not_found} ->
{:stop, :pipeline_not_found}
{:error, reason} ->
{:stop, reason}
end
end
defp start_flow(realm, flow, pipeline, state) do
id_prefix = "#{realm}-#{flow.name}"
with {:ok, {block_pids, container_block_pids, _}} <-
start_blocks(id_prefix, pipeline, flow.config) do
{:ok,
%{
state
| block_pids: block_pids,
container_block_pids: container_block_pids
}}
end
end
defp start_blocks(id_prefix, pipeline, flow_config) do
Enum.reduce_while(pipeline, {:ok, {[], [], 0}}, fn
# Special case: container block
{Container = block_module, block_opts}, {:ok, {block_pids, container_block_pids, block_idx}} ->
# Pass a deterministic id
id = id_prefix <> to_string(block_idx)
full_opts =
block_opts
|> Keyword.put(:id, id)
|> Keyword.put(:config, flow_config)
case start_block(block_module, full_opts) do
{:ok, pid} ->
new_block_pids = [pid | block_pids]
new_container_block_pids = [pid | container_block_pids]
{:cont, {:ok, {new_block_pids, new_container_block_pids, block_idx + 1}}}
{:error, reason} ->
{:halt, {:error, reason}}
end
{block_module, block_opts}, {:ok, {block_pids, container_block_pids, block_idx}} ->
case start_block(block_module, block_opts) do
{:ok, pid} ->
new_block_pids = [pid | block_pids]
{:cont, {:ok, {new_block_pids, container_block_pids, block_idx + 1}}}
{:error, reason} ->
{:halt, {:error, reason}}
end
end)
end
defp start_block(block_module, block_opts) do
case block_module.start_link(block_opts) do
{:ok, pid} ->
{:ok, pid}
error ->
_ =
Logger.error(
"Could not start block #{inspect(block_module)} with opts #{inspect(block_opts)}: #{
inspect(error)
}"
)
{:error, :block_start_failed}
end
end
@impl true
def handle_info({:EXIT, port, _reason}, state) when is_port(port) do
# Ignore port exits
{:noreply, state}
end
def handle_info({:EXIT, pid, reason}, state)
when is_pid(pid) and reason in [:normal, :shutdown] do
# Don't log on normal or shutdown exits
{:stop, reason, state}
end
def handle_info({:EXIT, pid, reason}, %State{flow: flow} = state) when is_pid(pid) do
_ =
Logger.error("A block crashed with reason #{inspect(reason)}.",
flow: flow.name,
tag: "flow_block_crash"
)
{:stop, reason, state}
end
def handle_info(:initialize_k8s_flow, state) do
%{
realm: realm,
flow: flow,
container_block_pids: container_block_pids
} = state
with {:ok, container_blocks} <- collect_container_blocks(container_block_pids),
:ok <- K8s.create_flow(realm, flow.name, container_blocks) do
Logger.debug("Flow #{flow.name} K8s containers created.")
send(self(), :check_flow_status)
{:noreply, %{state | status: :creating_containers}}
else
error ->
Logger.warn(
"K8s initialization failed: #{inspect(error)}. Retrying in #{@retry_timeout_ms} ms.",
flow: flow.name
)
Process.send_after(self(), :initialize_k8s_flow, @retry_timeout_ms)
{:noreply, state}
end
end
def handle_info(:check_flow_status, %State{flow: flow} = state) do
case K8s.flow_status(flow.name) do
{:ok, "Flowing"} ->
Logger.debug("Flow #{flow.name} K8s in Flowing state.")
send(self(), :connect_blocks)
{:noreply, %{state | status: :connecting_blocks}}
_other ->
Process.send_after(self(), :check_flow_status, @retry_timeout_ms)
{:noreply, state}
end
{:noreply, %{state | status: :waiting_blocks_connection}}
end
def handle_info(:connect_blocks, state) do
%{
block_pids: block_pids,
flow: flow
} = state
# block_pids is populated reducing on the pipeline, so the first element is the last block
with :ok <- connect_blocks(block_pids) do
Logger.debug("Flow #{flow.name} is ready.")
{:noreply, %{state | status: :flowing}}
else
error ->
Logger.warn("Block connection failed: #{inspect(error)}.",
flow: flow.name,
tag: "flow_block_connection_failed"
)
# TODO: we don't try to recover from this state right now
{:stop, state}
end
end
defp connect_blocks([subscriber, publisher | tail]) do
with {:ok, _subscription_tag} <- GenStage.sync_subscribe(subscriber, to: publisher) do
connect_blocks([publisher | tail])
end
end
defp connect_blocks([_first_publisher]) do
:ok
end
defp collect_container_blocks(container_block_pids) do
Enum.reduce_while(container_block_pids, {:ok, []}, fn pid, {:ok, acc} ->
case Container.get_container_block(pid) do
{:ok, container_block} ->
{:cont, {:ok, [container_block | acc]}}
{:error, reason} ->
{:halt, {:error, reason}}
end
end)
end
@impl true
def handle_call(:get_flow, _from, %State{flow: flow} = state) do
{:reply, flow, state}
end
def handle_call(:tap, _from, %State{block_pids: [last_block_pid | _tail]} = state) do
# block_pids is populated reducing on the pipeline, so the first element is the last block
stream = GenStage.stream([last_block_pid])
{:reply, stream, state}
end
@impl true
def terminate(_reason, state) do
K8s.try_delete_flow(state.flow.name)
end
end
| 28.184524 | 101 | 0.632313 |
085cab7a0dfa6fcedc37cc770afeedb73236a9b4 | 4,182 | ex | Elixir | clients/big_query/lib/google_api/big_query/v2/model/training_run.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/big_query/lib/google_api/big_query/v2/model/training_run.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/big_query/lib/google_api/big_query/v2/model/training_run.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.BigQuery.V2.Model.TrainingRun do
@moduledoc """
Information about a single training query run for the model.
## Attributes
* `classLevelGlobalExplanations` (*type:* `list(GoogleApi.BigQuery.V2.Model.GlobalExplanation.t)`, *default:* `nil`) - Global explanation contains the explanation of top features on the class level. Applies to classification models only.
* `dataSplitResult` (*type:* `GoogleApi.BigQuery.V2.Model.DataSplitResult.t`, *default:* `nil`) - Data split result of the training run. Only set when the input data is actually split.
* `evaluationMetrics` (*type:* `GoogleApi.BigQuery.V2.Model.EvaluationMetrics.t`, *default:* `nil`) - The evaluation metrics over training/eval data that were computed at the end of training.
* `modelLevelGlobalExplanation` (*type:* `GoogleApi.BigQuery.V2.Model.GlobalExplanation.t`, *default:* `nil`) - Global explanation contains the explanation of top features on the model level. Applies to both regression and classification models.
* `results` (*type:* `list(GoogleApi.BigQuery.V2.Model.IterationResult.t)`, *default:* `nil`) - Output of each iteration run, results.size() <= max_iterations.
* `startTime` (*type:* `DateTime.t`, *default:* `nil`) - The start time of this training run.
* `trainingOptions` (*type:* `GoogleApi.BigQuery.V2.Model.TrainingOptions.t`, *default:* `nil`) - Options that were used for this training run, includes user specified and default options that were used.
* `vertexAiModelId` (*type:* `String.t`, *default:* `nil`) - The model id in Vertex AI Model Registry for this training run
* `vertexAiModelVersion` (*type:* `String.t`, *default:* `nil`) - The model version in Vertex AI Model Registry for this training run
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:classLevelGlobalExplanations =>
list(GoogleApi.BigQuery.V2.Model.GlobalExplanation.t()) | nil,
:dataSplitResult => GoogleApi.BigQuery.V2.Model.DataSplitResult.t() | nil,
:evaluationMetrics => GoogleApi.BigQuery.V2.Model.EvaluationMetrics.t() | nil,
:modelLevelGlobalExplanation => GoogleApi.BigQuery.V2.Model.GlobalExplanation.t() | nil,
:results => list(GoogleApi.BigQuery.V2.Model.IterationResult.t()) | nil,
:startTime => DateTime.t() | nil,
:trainingOptions => GoogleApi.BigQuery.V2.Model.TrainingOptions.t() | nil,
:vertexAiModelId => String.t() | nil,
:vertexAiModelVersion => String.t() | nil
}
field(:classLevelGlobalExplanations,
as: GoogleApi.BigQuery.V2.Model.GlobalExplanation,
type: :list
)
field(:dataSplitResult, as: GoogleApi.BigQuery.V2.Model.DataSplitResult)
field(:evaluationMetrics, as: GoogleApi.BigQuery.V2.Model.EvaluationMetrics)
field(:modelLevelGlobalExplanation, as: GoogleApi.BigQuery.V2.Model.GlobalExplanation)
field(:results, as: GoogleApi.BigQuery.V2.Model.IterationResult, type: :list)
field(:startTime, as: DateTime)
field(:trainingOptions, as: GoogleApi.BigQuery.V2.Model.TrainingOptions)
field(:vertexAiModelId)
field(:vertexAiModelVersion)
end
defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.TrainingRun do
def decode(value, options) do
GoogleApi.BigQuery.V2.Model.TrainingRun.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.TrainingRun do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 55.026316 | 249 | 0.732903 |
085cbf4b1be3a99934e2aea5bf3fcc4066734d10 | 2,534 | exs | Elixir | apps/core/test/pubsub/fanout/accounts_test.exs | michaeljguarino/forge | 50ee583ecb4aad5dee4ef08fce29a8eaed1a0824 | [
"Apache-2.0"
] | null | null | null | apps/core/test/pubsub/fanout/accounts_test.exs | michaeljguarino/forge | 50ee583ecb4aad5dee4ef08fce29a8eaed1a0824 | [
"Apache-2.0"
] | 2 | 2019-12-13T23:55:50.000Z | 2019-12-17T05:49:58.000Z | apps/core/test/pubsub/fanout/accounts_test.exs | michaeljguarino/chartmart | a34c949cc29d6a1ab91c04c5e4f797e6f0daabfc | [
"Apache-2.0"
] | null | null | null | defmodule Core.PubSub.Fanout.AccountsTest do
use Core.SchemaCase, async: true
alias Core.Services.Accounts
alias Core.PubSub
describe "ZoomMeetingCreated" do
test "it can post a message about the meeting" do
incident = insert(:incident)
event = %PubSub.ZoomMeetingCreated{
item: %{join_url: "join-url", incident_id: incident.id, password: "pwd"},
actor: incident.creator
}
{:ok, msg} = PubSub.Fanout.fanout(event)
assert msg.text == "I just created a zoom meeting, you can join here: join-url"
end
end
describe "GroupUpdated" do
test "it will add all users on the account to the group when globalized" do
acct = insert(:account)
users = insert_list(3, :user, account: acct)
group = insert(:group, account: acct, global: true)
event = %PubSub.GroupUpdated{item: %{group | globalized: true}}
:ok = PubSub.Fanout.fanout(event)
for user <- users,
do: assert Accounts.get_group_member(group.id, user.id)
end
test "it will ignore if not globalized" do
acct = insert(:account)
insert_list(3, :user, account: acct)
group = insert(:group, account: acct, global: true)
event = %PubSub.GroupUpdated{item: group}
:ignore = PubSub.Fanout.fanout(event)
end
end
describe "RoleCreated" do
test "it will cache all associated users" do
role = insert(:role)
group = insert(:group)
%{user: user1} = insert(:role_binding, role: role, user: build(:user))
insert(:role_binding, group: group, role: role)
%{user: user2} = insert(:group_member, group: group)
event = %PubSub.RoleCreated{item: role}
2 = PubSub.Fanout.fanout(event)
assert_receive {:event, %PubSub.CacheUser{item: found1}}
assert_receive {:event, %PubSub.CacheUser{item: found2}}
assert ids_equal([user1, user2], [found1, found2])
end
end
describe "RoleUpdated" do
test "it will cache all associated users" do
role = insert(:role)
group = insert(:group)
%{user: user1} = insert(:role_binding, role: role, user: build(:user))
insert(:role_binding, group: group, role: role)
%{user: user2} = insert(:group_member, group: group)
event = %PubSub.RoleUpdated{item: role}
2 = PubSub.Fanout.fanout(event)
assert_receive {:event, %PubSub.CacheUser{item: found1}}
assert_receive {:event, %PubSub.CacheUser{item: found2}}
assert ids_equal([user1, user2], [found1, found2])
end
end
end
| 31.675 | 85 | 0.651539 |
085cdc0637bfc173882f4f6650df96232c017310 | 1,587 | ex | Elixir | lib/pixel_font/table_source/gsub/reverse_chaining_context1.ex | Dalgona/pixel_font | 6a65bf85e5228296eb29fddbfdd690565767ff76 | [
"MIT"
] | 17 | 2020-09-14T15:25:38.000Z | 2022-03-05T17:14:24.000Z | lib/pixel_font/table_source/gsub/reverse_chaining_context1.ex | Dalgona/pixel_font | 6a65bf85e5228296eb29fddbfdd690565767ff76 | [
"MIT"
] | 1 | 2021-08-19T05:05:37.000Z | 2021-08-19T05:05:37.000Z | lib/pixel_font/table_source/gsub/reverse_chaining_context1.ex | Dalgona/pixel_font | 6a65bf85e5228296eb29fddbfdd690565767ff76 | [
"MIT"
] | null | null | null | defmodule PixelFont.TableSource.GSUB.ReverseChainingContext1 do
alias PixelFont.Glyph
alias PixelFont.TableSource.OTFLayout.GlyphCoverage
defstruct backtrack: [],
lookahead: [],
substitutions: []
@type t :: %__MODULE__{
backtrack: [GlyphCoverage.t()],
lookahead: [GlyphCoverage.t()],
substitutions: [{Glyph.id(), Glyph.id()}]
}
defimpl PixelFont.TableSource.GSUB.Subtable do
require PixelFont.Util, as: Util
import Util, only: :macros
alias PixelFont.TableSource.GSUB.ReverseChainingContext1
@spec compile(ReverseChainingContext1.t(), keyword()) :: binary()
def compile(subtable, _opts) do
{from_glyphs, to_glyphs} =
subtable.substitutions
|> Enum.map(fn {from, to} -> {gid!(from), gid!(to)} end)
|> Enum.sort(&(elem(&1, 0) <= elem(&2, 0)))
|> Enum.unzip()
input_count = length(from_glyphs)
seqs = [subtable.backtrack, subtable.lookahead]
counts = seqs |> Enum.map(&length/1) |> Enum.sum()
offset_base = 10 + counts * 2 + input_count * 2
compiled_coverage =
from_glyphs
|> GlyphCoverage.of()
|> GlyphCoverage.compile(internal: true)
{offsets, coverages} =
GlyphCoverage.compile_coverage_records(seqs, offset_base + byte_size(compiled_coverage))
IO.iodata_to_binary([
<<1::16>>,
<<offset_base::16>>,
offsets,
<<input_count::16>>,
Enum.map(to_glyphs, &<<&1::16>>),
compiled_coverage,
coverages
])
end
end
end
| 29.943396 | 96 | 0.611216 |
085cf68849be21dbe4ad1692ee63fe03a596f942 | 1,760 | ex | Elixir | lib/sobelow/config/https.ex | OldhamMade/sobelow | b0196d2655c2fdf744d5797d17e152f36d453d72 | [
"Apache-2.0"
] | null | null | null | lib/sobelow/config/https.ex | OldhamMade/sobelow | b0196d2655c2fdf744d5797d17e152f36d453d72 | [
"Apache-2.0"
] | null | null | null | lib/sobelow/config/https.ex | OldhamMade/sobelow | b0196d2655c2fdf744d5797d17e152f36d453d72 | [
"Apache-2.0"
] | null | null | null | defmodule Sobelow.Config.HTTPS do
@moduledoc """
# HTTPS
Without HTTPS, attackers in a priveleged network position can
intercept and modify traffic.
Sobelow detects missing HTTPS by checking the prod
configuration.
HTTPS checks can be ignored with the following command:
$ mix sobelow -i Config.HTTPS
"""
alias Sobelow.Config
@uid 9
@finding_type "Config.HTTPS: HTTPS Not Enabled"
use Sobelow.Finding
def run(dir_path, configs) do
path = dir_path <> "prod.exs"
if File.exists?(path) && Enum.member?(configs, "prod.exs") do
https = Config.get_configs_by_file(:https, path)
(Config.get_configs_by_file(:force_ssl, path) ++ https)
|> handle_https(path)
end
end
defp handle_https(opts, path) do
if length(opts) === 0 do
add_finding(path)
end
end
defp add_finding(file) do
reason = "HTTPS configuration details could not be found in `prod.exs`."
finding =
%Finding{
type: @finding_type,
filename: Utils.normalize_path(file),
fun_source: nil,
vuln_source: reason,
vuln_line_no: 0,
vuln_col_no: 0,
confidence: :high
}
|> Finding.fetch_fingerprint()
case Sobelow.format() do
"json" ->
json_finding = [
type: finding.type,
file: finding.filename,
line: finding.vuln_line_no
]
Sobelow.log_finding(json_finding, finding)
"txt" ->
Sobelow.log_finding(finding)
Print.print_custom_finding_metadata(finding, [])
"compact" ->
Print.log_compact_finding(finding)
"flycheck" ->
Print.log_flycheck_finding(finding)
_ ->
Sobelow.log_finding(finding)
end
end
end
| 22 | 76 | 0.631818 |
085d33b0adf9cc1211761feafd57f69bf0f0b25a | 937 | ex | Elixir | web/controllers/session_controller.ex | NorifumiKawamoto/ginjyo | 8e28438db4675bb55ba090614c6834190adb61b1 | [
"MIT"
] | null | null | null | web/controllers/session_controller.ex | NorifumiKawamoto/ginjyo | 8e28438db4675bb55ba090614c6834190adb61b1 | [
"MIT"
] | null | null | null | web/controllers/session_controller.ex | NorifumiKawamoto/ginjyo | 8e28438db4675bb55ba090614c6834190adb61b1 | [
"MIT"
] | null | null | null | defmodule Ginjyo.SessionController do
use Ginjyo.Web, :controller
alias Plug.Conn
alias Ginjyo.Session
alias Ginjyo.Repo
require Logger
def new(conn, _params) do
render conn, "new.html"
end
def create(conn, %{"session" => session_params}) do
case Session.login(session_params, Repo) do
{:ok, user} ->
Logger.metadata([user_id: user.id])
conn
|> Conn.put_session(
:current_user,
%{id: user.id, email: user.email, role_id: user.role_id}
)
|> put_flash(:info, "Sign in successfull!!")
|> redirect(to: page_path(conn, :index))
:error ->
conn
|> put_flash(:info, "Wrong email or password")
|> render("new.html")
end
end
def delete(conn, _params) do
conn
|> Conn.delete_session(:current_user)
|> put_flash(:info, "Signed out successfully!")
|> redirect(to: page_path(conn, :index))
end
end
| 25.324324 | 64 | 0.611526 |
085d559275a5e9bf8c74cd11f358f316db4206af | 145,012 | ex | Elixir | lib/elixir/lib/kernel.ex | tmikeschu/elixir | ae108c110af3220cd4f729ac25edb06f0f81c884 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/kernel.ex | tmikeschu/elixir | ae108c110af3220cd4f729ac25edb06f0f81c884 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/kernel.ex | tmikeschu/elixir | ae108c110af3220cd4f729ac25edb06f0f81c884 | [
"Apache-2.0"
] | null | null | null | # 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, etc
* macros for control-flow and defining new functionality (modules, functions, and so on)
* guard checks for augmenting pattern matching
You can use `Kernel` functions/macros without the `Kernel` prefix anywhere in
Elixir code as all its functions and macros are automatically imported. For
example, in IEx:
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 `Kernel.SpecialForms.fn/2`
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 `defprotocol/2` 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 char lists (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.html) - lists
compatibility between every Elixir version and Erlang/OTP, release schema;
lists all deprecated functions, when they were deprecated and alternatives
* [Guards](guards.html) - an introduction to guards and extensions
* [Library Guidelines](library-guidelines.html) - general guidelines, anti-patterns,
and rules for those writing libraries
* [Naming Conventions](naming-conventions.html) - naming conventions for Elixir code
* [Operators](operators.html) - lists all Elixir operators and their precedence
* [Syntax Reference](syntax-reference.html) - the language syntax reference
* [Typespecs](typespecs.html)- types and function specifications, including list of types
* [Unicode Syntax](unicode-syntax.html) - outlines Elixir support for Unicode
* [Writing Documentation](writing-documentation.html) - 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. A more complete introduction to guards is available
[in the Guards page](guards.html).
## Inlining
Some of the functions described in this module are inlined by
the Elixir compiler into their Erlang counterparts in the
[`:erlang` module](http://www.erlang.org/doc/man/erlang.html).
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`.
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.
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"
"""
@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 not greater than `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, etc.
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
shutdown 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 OS process to exit with the status given by
`integer` while signaling all linked Erlang processes to politely
shutdown.
Any other exit reason will cause the OS 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 not greater than `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([])
#=> ** (ArgumentError) argument error
hd([1 | 2])
#=> 1
"""
@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.
"""
@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.
"""
@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.
"""
@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 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
Erlang's term ordering.
If the terms compare equal, the first one is returned.
Inlined by the compiler.
## Examples
iex> max(1, 2)
2
iex> max(:a, :b)
:b
Using Erlang's term ordering means that comparisons are
structural and not semantic. For example, when comparing dates:
iex> max(~D[2017-03-31], ~D[2017-04-01])
~D[2017-03-31]
In the example above, `max/1` returned March 31st instead of April 1st
because the structural comparison compares the day before the year. In
such cases it is common for modules to provide functions such as
`Date.compare/1` that perform semantic comparison.
"""
@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
Erlang's term ordering.
If the terms compare equal, the first one is returned.
Inlined by the compiler.
## Examples
iex> min(1, 2)
1
iex> min("foo", "bar")
"bar"
Using Erlang's term ordering means that comparisons are
structural and not semantic. For example, when comparing dates:
iex> min(~D[2017-03-31], ~D[2017-04-01])
~D[2017-04-01]
In the example above, `min/1` returned April 1st instead of March 31st
because the structural comparison compares the day before the year. In
such cases it is common for modules to provide functions such as
`Date.compare/1` that perform semantic comparison.
"""
@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.
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
"""
@doc guard: true
@spec round(float) :: integer
@spec round(value) :: value when value: 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 """
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([])
#=> ** (ArgumentError) argument error
tl([:one])
#=> []
tl([:a, :b | :c])
#=> [:b | :c]
tl([:a | %{b: 1}])
#=> %{b: 1}
"""
@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(value) :: value when value: integer
@spec trunc(float) :: 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.
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.
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 unary plus.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> +1
1
"""
@doc guard: true
@spec +value :: value when value: number
def +value do
:erlang.+(value)
end
@doc """
Arithmetic unary minus.
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.
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.
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 """
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, e.g. `list ++ [item]`.
Instead, consider prepending via `[item | 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 """
Removes the first occurrence of an item on the left list
for each item on the right.
The complexity of `a -- b` is proportional to `length(a) * length(b)`,
meaning that it will be very slow if both `a` and `b` are long lists.
In such cases, consider converting each list to a `MapSet` and using
`MapSet.difference/2`.
Inlined by the compiler.
## Examples
iex> [1, 2, 3] -- [1, 2]
[3]
iex> [1, 2, 3, 2, 1] -- [1, 2, 2]
[3, 1]
"""
@spec list -- list :: list
def left -- right do
:erlang.--(left, right)
end
@doc """
Boolean not.
`arg` 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 """
Returns `true` if left is less than right.
All terms in Elixir can be compared with each other.
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 """
Returns `true` if left is more than right.
All terms in Elixir can be compared with each other.
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 """
Returns `true` if left is less than or equal to right.
All terms in Elixir can be compared with each other.
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 """
Returns `true` if left is more than or equal to right.
All terms in Elixir can be compared with each other.
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 """
Returns `true` if the two items 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 """
Returns `true` if the two items are not equal.
This operator considers 1 and 1.0 to be equal. For match
comparison, use `!==` 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 """
Returns `true` if the two items are exactly equal.
The items 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 """
Returns `true` if the two items are not 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 """
Boolean or.
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, an `ArgumentError` exception is
raised.
Allowed in guard tests.
## Examples
iex> true or false
true
iex> false or 42
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 """
Boolean and.
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, an `ArgumentError` exception is raised.
Allowed in guard tests.
## Examples
iex> true and false
false
iex> true and "yay!"
"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.
Receives any argument (not just booleans) and returns `true` if the argument
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 """
Concatenates two 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 have resulted in a `CompileError` 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 be always a literal " <>
"binary as its size can't be verified, got: #{arg}"
)
)
end
@doc """
Raises an exception.
If the argument `msg` is a binary, it raises a `RuntimeError` exception
using the given argument as message.
If `msg` is an atom, it just calls `raise/2` with the atom as the first
argument and `[]` as the second argument.
If `msg` is an exception struct, it is raised as is.
If `msg` 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
case message do
message when is_binary(message) ->
quote do
:erlang.error(RuntimeError.exception(unquote(message)))
end
{:<<>>, _, _} = message ->
quote do
:erlang.error(RuntimeError.exception(unquote(message)))
end
alias when is_atom(alias) ->
quote do
:erlang.error(unquote(alias).exception([]))
end
_ ->
quote do
:erlang.error(Kernel.Utils.raise(unquote(message)))
end
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 `attrs` as the
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.
Notice 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.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace))
end
{:<<>>, _, _} = message ->
quote do
:erlang.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace))
end
alias when is_atom(alias) ->
quote do
:erlang.raise(:error, unquote(alias).exception([]), unquote(stacktrace))
end
message ->
quote do
: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 """
Matches the term on the left against the regular expression or string on the
right.
Returns `true` if `left` matches `right` (if it's a regular expression)
or contains `right` (if it's a string).
## Examples
iex> "abcd" =~ ~r/c(d)/
true
iex> "abcd" =~ ~r/e/
false
iex> "abcd" =~ "bc"
true
iex> "abcd" =~ "ad"
false
iex> "abcd" =~ ""
true
"""
@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 = struct(Inspect.Opts, 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 structs.
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.
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
struct.__struct__(fields)
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
struct.__struct__()
end
defp struct(struct, fields, fun) when is_atom(struct) do
struct(struct.__struct__(), fields, fun)
end
defp struct(%_{} = struct, [], _fun) do
struct
end
defp struct(%_{} = struct, fields, fun) do
Enum.reduce(fields, struct, fun)
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.
If a key 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. The downside is that functions cannot be
stored as keys in the accessed data structures.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> get_in(users, ["john", :age])
27
In case any of the entries in the middle returns `nil`, `nil` will
be returned as per the `Access` module:
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> get_in(users, ["unknown", :age])
nil
When one of the keys is a function that takes three arguments, the function
is invoked. In the example below, we use a function to get all the maps
inside a list:
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]
If the previous value before invoking the function is `nil`,
the function *will* receive `nil` as a value and must handle it
accordingly.
"""
@spec get_in(Access.t(), nonempty_list(term)) :: term
def get_in(data, keys)
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(nil, [_]), do: nil
def get_in(nil, [_ | t]), do: get_in(nil, 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}}
In case any of the entries in the middle returns `nil`,
an error will be raised when trying to access it next.
"""
@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`.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> update_in(users, ["john", :age], &(&1 + 1))
%{"john" => %{age: 28}, "meg" => %{age: 23}}
In case any of the entries in the middle returns `nil`,
an error will be raised when trying to access it next.
"""
@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 `{get_value, new_value}`. In this case,
`get_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.
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.
## 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}}}
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 :: Access.t(),
keys,
(term -> {get_value, update_value} | :pop)
) :: {get_value, structure :: Access.t()}
when keys: nonempty_list(any),
get_value: var,
update_value: term
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)
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))
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})
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, 2)
false
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 of 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()
[]
"""
defmacro match?(pattern, expr) do
quote do
case unquote(expr) do
unquote(pattern) ->
true
_ ->
false
end
end
end
@doc """
Reads and writes attributes of 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`.
Finally, notice 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.
"""
defmacro @expr
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, you probably meant to use: @#{name} expression"
# Typespecs attributes are currently special cased by the compiler
is_list(args) and args != [] and tl(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"
:elixir_errors.warn(env.line, env.file, warn_message)
:lists.member(name, [:moduledoc, :typedoc, :doc]) ->
arg = {env.line, arg}
quote do
Module.put_attribute(__MODULE__, unquote(name), unquote(arg), unquote(line))
end
true ->
quote do
Module.put_attribute(__MODULE__, unquote(name), unquote(arg), unquote(line))
end
end
end
# @attribute or @attribute()
defp do_at(args, _meta, name, function?, env) when is_atom(args) or 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, :default, 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
# All other cases
defp do_at(args, _meta, name, _function?, _env) do
raise ArgumentError, "expected 0 or 1 argument for @#{name}, got: #{length(args)}"
end
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
`true` (i.e., it is 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 unless `clause` evaluates to `true`. 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 items 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 """
Returns a range with the specified `first` and `last` integers.
If last is larger than first, the range will be increasing from
first to last. If first is larger than last, the range will be
decreasing from first to last. If first is equal to last, the range
will contain one element, which is the number itself.
## Examples
iex> 0 in 1..3
false
iex> 1 in 1..3
true
iex> 2 in 1..3
true
iex> 3 in 1..3
true
"""
defmacro first..last when is_integer(first) and is_integer(last) do
{:%{}, [], [__struct__: Elixir.Range, first: first, last: last]}
end
defmacro 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) expect both sides to be integers, " <>
"got: #{Macro.to_string({:.., [], [first, last]})}"
end
defmacro first..last do
case __CALLER__.context do
nil ->
quote(do: Elixir.Range.new(unquote(first), unquote(last)))
_ ->
{:%{}, [], [__struct__: Elixir.Range, first: first, last: last]}
end
end
@doc """
Provides a short-circuit operator that evaluates and returns
the second expression only if the first one evaluates to `true`
(i.e., it is neither `nil` nor `false`). 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 """
Provides a short-circuit operator that evaluates and returns the second
expression only if the first one does not evaluate to `true` (i.e., 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 pitfall is that the `|>` operator works on calls.
For example, when you write:
"Hello" |> some_function()
Elixir sees the right-hand side is a function call and pipes
to it. This means that, if you want to pipe to an anonymous
or captured function, it must also be explicitly called.
Given the anonymous function:
fun = fn x -> IO.puts(x) end
fun.("Hello")
This won't work as it will rather try to invoke the local
function `fun`:
"Hello" |> fun()
This works:
"Hello" |> fun.()
As you can see, the `|>` operator retains the same semantics
as when the pipe is not used since both require the `fun.(...)`
notation.
"""
defmacro left |> right do
[{h, _} | t] = Macro.unpipe({:|>, [], [left, right]})
fun = fn {x, pos}, acc ->
case x do
{op, _, [_]} when op == :+ or op == :- ->
message =
<<"piping into a unary operator is deprecated, please use the ",
"qualified name. For example, Kernel.+(5), instead of +5">>
:elixir_errors.warn(__CALLER__.line, __CALLER__.file, message)
_ ->
:ok
end
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, :member?, 2)
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 """
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
When using ranges:
when x in 1..3
translates to:
when is_integer(x) and x >= 1 and x <= 3
Note that only integers can be considered inside a range by `in`.
### 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` will translate all occurrences of
this AST to `left not in right`.
"""
@doc guard: true
defmacro left in right do
in_module? = __CALLER__.context == nil
expand =
case bootstrapped?(Macro) do
true -> &Macro.expand(&1, __CALLER__)
false -> & &1
end
case expand.(right) do
[] when not in_module? ->
false
[head | tail] = list when not in_module? ->
in_var(in_module?, left, &in_list(&1, head, tail, expand, list, in_module?))
[_ | _] = list when in_module? ->
case ensure_evaled(list, {0, []}, expand) do
{[head | tail], {_, []}} ->
in_var(in_module?, left, &in_list(&1, head, tail, expand, list, in_module?))
{[head | tail], {_, vars_values}} ->
{vars, values} = :lists.unzip(:lists.reverse(vars_values))
is_in_list = &in_list(&1, head, tail, expand, list, in_module?)
quote do
{unquote_splicing(vars)} = {unquote_splicing(values)}
unquote(in_var(in_module?, left, is_in_list))
end
end
{:%{}, _meta, [__struct__: Elixir.Range, first: first, last: last]} ->
first = Macro.expand(first, __CALLER__)
last = Macro.expand(last, __CALLER__)
in_var(in_module?, left, &in_range(&1, first, last))
right when in_module? ->
quote(do: Elixir.Enum.member?(unquote(right), unquote(left)))
%{__struct__: Elixir.Range, first: _, last: _} ->
raise ArgumentError, "non-literal range in guard should be escaped with Macro.escape/2"
right ->
raise ArgumentError, <<
"invalid args 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
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
# Called as ensure_evaled(list, {0, []}). Note acc is reversed.
defp ensure_evaled(list, acc, expand) do
fun = fn
{:|, meta, [head, tail]}, acc ->
{head, acc} = ensure_evaled_element(head, acc)
{tail, acc} = ensure_evaled_tail(expand.(tail), acc, expand)
{{:|, meta, [head, tail]}, acc}
elem, acc ->
ensure_evaled_element(elem, acc)
end
:lists.mapfoldl(fun, acc, list)
end
defp ensure_evaled_element(elem, acc)
when is_number(elem) or is_atom(elem) or is_binary(elem) do
{elem, acc}
end
defp ensure_evaled_element(elem, acc) do
ensure_evaled_var(elem, acc)
end
defp ensure_evaled_tail(elem, acc, expand) when is_list(elem) do
ensure_evaled(elem, acc, expand)
end
defp ensure_evaled_tail(elem, acc, _expand) do
ensure_evaled_var(elem, acc)
end
defp ensure_evaled_var(elem, {index, ast}) do
var = {String.to_atom("arg" <> Integer.to_string(index)), [], __MODULE__}
{var, {index + 1, [{var, elem} | ast]}}
end
defp in_range(left, first, last) do
case is_integer(first) and is_integer(last) do
true ->
in_range_literal(left, first, last)
false ->
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
end
defp in_range_literal(left, first, first) do
quote do
:erlang."=:="(unquote(left), unquote(first))
end
end
defp in_range_literal(left, first, last) when first < last do
quote do
:erlang.andalso(
:erlang.is_integer(unquote(left)),
unquote(increasing_compare(left, first, last))
)
end
end
defp in_range_literal(left, first, last) do
quote do
:erlang.andalso(
:erlang.is_integer(unquote(left)),
unquote(decreasing_compare(left, first, last))
)
end
end
defp in_list(left, head, tail, expand, right, in_module?) do
fun = fn elem, acc ->
quote do
:erlang.orelse(unquote(comp(left, elem, expand, right, in_module?)), unquote(acc))
end
end
:lists.foldr(fun, comp(left, head, expand, right, in_module?), tail)
end
defp comp(left, {:|, _, [head, tail]}, expand, right, in_module?) 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_module?))
)
end
tail when in_module? ->
quote do
:erlang.orelse(
:erlang."=:="(unquote(left), unquote(head)),
:lists.member(unquote(left), unquote(tail))
)
end
_ ->
raise ArgumentError, <<
"invalid args 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
end
defp comp(left, right, _expand, _right, _in_module?) 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 """
When used inside quoting, marks that the given variable should
not be hygienized.
The argument can be either a variable unquoted or in standard tuple form
`{name, meta, context}`.
Check `Kernel.SpecialForms.quote/2` for more information.
"""
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(:var, 1, meta, {:var, true})
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
iex> defmodule Foo do
...> def bar, do: :baz
...> end
iex> Foo.bar()
:baz
## 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).
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
## Module names
A module name can be any atom, but Elixir provides a special syntax which is
usually used for module names. What is called a module name is an
_uppercase ASCII letter_ followed by any number of _lowercase or
uppercase ASCII letters_, _numbers_, or _underscores_.
This identifier is equivalent to an atom prefixed by `Elixir.`. So in the
`defmodule Foo` example `Foo` is equivalent to `:"Elixir.Foo"`
## 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__
boot? = bootstrapped?(Macro)
expanded =
case boot? do
true -> Macro.expand(alias, env)
false -> alias
end
{expanded, with_alias} =
case boot? and is_atom(expanded) do
true ->
# Expand the module considering the current environment/nesting
full = expand_module(alias, expanded, env)
# Generate the alias for this module definition
{new, old} = module_nesting(env.module, full)
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, :default, false)
end
# We reimplement Macro.Env.vars/1 due to bootstrap concerns.
module_vars = module_vars(:maps.keys(env.current_vars), 0)
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: []
# defmodule :foo
defp expand_module(raw, _module, _env) when is_atom(raw), do: raw
# defmodule Elixir.Alias
defp expand_module({:__aliases__, _, [:"Elixir" | t]}, module, _env) when t != [], do: module
# defmodule Alias in root
defp expand_module({:__aliases__, _, _}, module, %{module: nil}), do: module
# defmodule Alias nested
defp expand_module({:__aliases__, _, t}, _module, env),
do: :elixir_aliases.concat([env.module | t])
# defmodule _
defp expand_module(_raw, module, env), do: :elixir_aliases.concat([env.module, module])
# quote vars to be injected into the module definition
defp module_vars([{key, kind} | vars], counter) do
var =
case is_atom(kind) do
true -> {key, [generated: true], kind}
false -> {key, [counter: kind, generated: true], nil}
end
under = String.to_atom(<<"_@", :erlang.integer_to_binary(counter)::binary>>)
args = [key, kind, under, var]
[{:{}, [], args} | module_vars(vars, counter + 1)]
end
defp module_vars([], _counter) do
[]
end
# Gets two modules' names and returns an alias
# which can be passed down to the alias directive
# and it will create a proper shortcut representing
# the given nesting.
#
# Examples:
#
# module_nesting(:"Elixir.Foo.Bar", :"Elixir.Foo.Bar.Baz.Bat")
# {:"Elixir.Baz", :"Elixir.Foo.Bar.Baz"}
#
# In case there is no nesting/no module:
#
# module_nesting(nil, :"Elixir.Foo.Bar.Baz.Bat")
# {nil, :"Elixir.Foo.Bar.Baz.Bat"}
#
defp module_nesting(nil, full) do
{nil, full}
end
defp module_nesting(prefix, full) do
case split_module(prefix) do
[] -> {nil, full}
prefix -> module_nesting(prefix, split_module(full), [], full)
end
end
defp module_nesting([x | t1], [x | t2], acc, full) do
module_nesting(t1, t2, [x | acc], full)
end
defp module_nesting([], [h | _], acc, _full) do
as = String.to_atom(<<"Elixir.", h::binary>>)
alias = :elixir_aliases.concat(:lists.reverse([h | acc]))
{as, alias}
end
defp module_nesting(_, _, _acc, full) do
{nil, full}
end
defp split_module(atom) do
case :binary.split(Atom.to_string(atom), ".", [:global]) do
["Elixir" | t] -> t
_ -> []
end
end
@doc ~S"""
Defines a 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 `Foo.multiply_by/1` and `Foo.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.
## 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. For example, the following two functions are equivalent:
def format(value) do
try do
format!(value)
catch
:exit, reason -> {:error, reason}
end
end
def format(value) do
format!(value)
catch
:exit, reason -> {:error, reason}
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 macro with the given name and body.
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.
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, :default, true)
escaped_expr =
case unquoted_expr do
true ->
:elixir_quote.escape(expr, :default, 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.
To define a struct, a developer must define both `__struct__/0` and
`__struct__/1` functions. `defstruct/1` is a convenience macro which
defines such functions with some conveniences.
For more information about structs, please check `Kernel.SpecialForms.%/2`.
## 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) #=> works
For each protocol in the `@derive` list, Elixir will assert there is an
implementation of that protocol for any (regardless if `@fallback_to_any`
is `true`) and check if the any implementation defines a `__deriving__/3`
callback (via `Protocol.derive/3`). If so, the callback is invoked,
otherwise an implementation that simply points to the `Any` implementation
is automatically derived.
## 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
`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.get_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` - 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` - 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 is_binary(msg) do
exception(message: msg)
end
end
# TODO: Only call Kernel.struct! by 2.0
@impl true
def exception(args) when 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 " <>
"#{inspect(__MODULE__)}: #{inspect(invalid)}. " <>
"Please make sure to only give known fields when raising " <>
"or redefine #{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 ~S"""
Defines a protocol.
A protocol specifies an API that should be defined by its
implementations.
## Examples
In Elixir, we have two verbs for checking how many items there
are in a data structure: `length` and `size`. `length` means the
information must be computed. For example, `length(list)` needs to
traverse the whole list to calculate its length. On the other hand,
`tuple_size(tuple)` and `byte_size(binary)` do not depend on the
tuple and binary size as the size information is precomputed in
the data structure.
Although Elixir includes specific functions such as `tuple_size`,
`binary_size` and `map_size`, sometimes we want to be able to
retrieve the size of a data structure regardless of its type.
In Elixir we can write polymorphic code, i.e. code that works
with different shapes/types, by using protocols. A size protocol
could be implemented as follows:
defprotocol Size do
@doc "Calculates the size (and not the length!) of a data structure"
def size(data)
end
Now that the protocol can be implemented for every data structure
the protocol may have a compliant implementation for:
defimpl Size, for: BitString do
def size(binary), do: byte_size(binary)
end
defimpl Size, for: Map do
def size(map), do: map_size(map)
end
defimpl Size, for: Tuple do
def size(tuple), do: tuple_size(tuple)
end
Notice we didn't implement it for lists as we don't have the
`size` information on lists, rather its value needs to be
computed with `length`.
It is possible to implement protocols for all Elixir types:
* Structs (see below)
* `Tuple`
* `Atom`
* `List`
* `BitString`
* `Integer`
* `Float`
* `Function`
* `PID`
* `Map`
* `Port`
* `Reference`
* `Any` (see below)
## Protocols and Structs
The real benefit of protocols comes when mixed with structs.
For instance, Elixir ships with many data types implemented as
structs, like `MapSet`. We can implement the `Size` protocol
for those types as well:
defimpl Size, for: MapSet do
def size(map_set), do: MapSet.size(map_set)
end
When implementing a protocol for a struct, the `:for` option can
be omitted if the `defimpl` call is inside the module that defines
the struct:
defmodule User do
defstruct [:email, :name]
defimpl Size do
# two fields
def size(%User{}), do: 2
end
end
If a protocol implementation is not found for a given type,
invoking the protocol will raise unless it is configured to
fall back to `Any`. Conveniences for building implementations
on top of existing ones are also available, look at `defstruct/1`
for more information about deriving
protocols.
## Fallback to `Any`
In some cases, it may be convenient to provide a default
implementation for all types. This can be achieved by setting
the `@fallback_to_any` attribute to `true` in the protocol
definition:
defprotocol Size do
@fallback_to_any true
def size(data)
end
The `Size` protocol can now be implemented for `Any`:
defimpl Size, for: Any do
def size(_), do: 0
end
Although the implementation above is arguably not a reasonable
one. For example, it makes no sense to say a PID or an integer
have a size of `0`. That's one of the reasons why `@fallback_to_any`
is an opt-in behaviour. For the majority of protocols, raising
an error when a protocol is not implemented is the proper behaviour.
## Multiple implementations
Protocols can also be implemented for multiple types at once:
defprotocol Reversible do
def reverse(term)
end
defimpl Reversible, for: [Map, List] do
def reverse(term), do: Enum.reverse(term)
end
## Types
Defining a protocol automatically defines a type named `t`, which
can be used as follows:
@spec print_size(Size.t()) :: :ok
def print_size(data) do
result =
case Size.size(data) do
0 -> "data has no items"
1 -> "data has one item"
n -> "data has #{n} items"
end
IO.puts(result)
end
The `@spec` above expresses that all types allowed to implement the
given protocol are valid argument types for the given function.
## Reflection
Any protocol module contains three extra functions:
* `__protocol__/1` - returns the protocol name when `:name` is given, a
keyword list with the protocol functions and their arities when
`:functions` is given, and a list of the implementations when `:impls` is
given
* `impl_for/1` - receives a structure and returns the module that
implements the protocol for the structure, `nil` otherwise
* `impl_for!/1` - same as above but raises an error if an implementation is
not found
Enumerable.__protocol__(:functions)
#=> [count: 1, member?: 2, reduce: 3]
Enumerable.impl_for([])
#=> Enumerable.List
Enumerable.impl_for(42)
#=> nil
## Consolidation
In order to cope with code loading in development, protocols in
Elixir provide a slow implementation of protocol dispatching specific
to development.
In order to speed up dispatching in production environments, where
all implementations are known up-front, Elixir provides a feature
called protocol consolidation. Consolidation directly links protocols
to their implementations in a way that invoking a function from a
consolidated protocol is equivalent to invoking two remote functions.
Protocol consolidation is applied by default to all Mix projects during
compilation. This may be an issue during test. For instance, if you want
to implement a protocol during test, the implementation will have no
effect, as the protocol has already been consolidated. One possible
solution is to include compilation directories that are specific to your
test environment in your mix.exs:
def project do
...
elixirc_paths: elixirc_paths(Mix.env())
...
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
And then you can define the implementations specific to the test environment
inside `test/support/some_file.ex`.
Another approach is to disable protocol consolidation during tests in your
mix.exs:
def project do
...
consolidate_protocols: Mix.env() != :test
...
end
Although doing so is not recommended as it may affect your test suite
performance.
Finally note all protocols are compiled with `debug_info` set to `true`,
regardless of the option set by `elixirc` compiler. The debug info is
used for consolidation and it may be removed after consolidation.
"""
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 `defprotocol/2` for more information and examples on protocols.
Inside an implementation, the name of the protocol can be accessed
via `@protocol` and the current target as `@for`.
"""
defmacro defimpl(name, opts, do_block \\ []) do
merged = Keyword.merge(opts, do_block)
merged = Keyword.put_new(merged, :for, __CALLER__.module)
Protocol.__impl__(name, merged)
end
@doc """
Makes the given functions in the current module overridable.
An overridable function is lazily defined, allowing a developer to override
it.
## 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
the `__using__/1` macro from the `MyModule` module is invoked with the second
argument passed to `use` as its argument. Since `__using__/1` is 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.
## Examples
For example, in order 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, `ExUnit.Case.__using__/1` is called with the keyword list
`[async: true]` as its argument; `use/2` translates to:
defmodule AssertionTest do
require ExUnit.Case
ExUnit.Case.__using__(async: true)
test "always pass" do
assert true
end
end
`ExUnit.Case` will then define 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".
In case you want to provide some existing functionality to the user module,
please define it in a module which will be imported accordingly; for example,
`ExUnit.Case` doesn't define the `test/3` macro in the module that calls
`use ExUnit.Case`, but it defines `ExUnit.Case.test/3` and just imports that
into the caller when used.
"""
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 (like if they were defined using
`def/2`). When the desire is to delegate as private functions, `import/2` should
be used.
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)
quote bind_quoted: [funs: funs, opts: opts] do
target =
Keyword.get(opts, :to) || raise ArgumentError, "expected to: to be given as argument"
# TODO: Raise on 2.0
%{file: file, line: line} = __ENV__
if is_list(funs) do
message =
"passing a list to Kernel.defdelegate/2 is deprecated, " <>
"please define each delegate separately"
:elixir_errors.warn(line, file, message)
end
# TODO: Remove on 2.0
if Keyword.has_key?(opts, :append_first) do
:elixir_errors.warn(line, file, "Kernel.defdelegate/2 :append_first option is deprecated")
end
for fun <- List.wrap(funs) do
{name, args, as, as_args} = Kernel.Utils.defdelegate(fun, opts)
def unquote(name)(unquote_splicing(args)) do
unquote(target).unquote(as)(unquote_splicing(as_args))
end
end
end
end
## Sigils
@doc ~S"""
Handles the sigil `~S` for strings.
It simply returns a string without escaping characters and without
interpolations.
## Examples
iex> ~S(foo)
"foo"
iex> ~S(f#{o}o)
"f\#{o}o"
"""
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_chars(piece)
end
defmacro sigil_s({:<<>>, line, pieces}, []) do
{:<<>>, line, unescape_tokens(pieces)}
end
@doc ~S"""
Handles the sigil `~C` for charlists.
It simply returns a charlist without escaping characters and without
interpolations.
## 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_chars(string))
end
defmacro sigil_c({:<<>>, meta, pieces}, []) do
binary = {:<<>>, meta, unescape_tokens(pieces)}
quote(do: String.to_charlist(unquote(binary)))
end
@doc """
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
"""
defmacro sigil_r(term, modifiers)
defmacro sigil_r({:<<>>, _meta, [string]}, options) when is_binary(string) do
binary = :elixir_interpolation.unescape_chars(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 escaping
nor interpreting interpolations.
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.
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, modifiers)
defmacro sigil_D({:<<>>, _, [string]}, []) do
Macro.escape(Date.from_iso8601!(string))
end
@doc ~S"""
Handles the sigil `~T` for times.
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(date, modifiers)
defmacro sigil_T({:<<>>, _, [string]}, []) do
Macro.escape(Time.from_iso8601!(string))
end
@doc ~S"""
Handles the sigil `~N` for naive date times.
The lower case `~n` variant does not exist as interpolation
and escape characters are not useful for datetime 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(date, modifiers)
defmacro sigil_N({:<<>>, _, [string]}, []) do
Macro.escape(NaiveDateTime.from_iso8601!(string))
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]
"""
defmacro sigil_w(term, modifiers)
defmacro sigil_w({:<<>>, _meta, [string]}, modifiers) when is_binary(string) do
split_words(:elixir_interpolation.unescape_chars(string), modifiers)
end
defmacro sigil_w({:<<>>, meta, pieces}, modifiers) do
binary = {:<<>>, meta, unescape_tokens(pieces)}
split_words(binary, modifiers)
end
@doc ~S"""
Handles the sigil `~W` for list of words.
It returns a list of "words" split by whitespace without escaping nor
interpreting interpolations.
## 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)
end
defp split_words(string, []) do
split_words(string, [?s])
end
defp split_words(string, [mod])
when mod == ?s or mod == ?a or mod == ?c do
case is_binary(string) do
true ->
parts = String.split(string)
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) 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/guards.html"
_ ->
:ok
end
end
defp invalid_match!(exp) do
raise ArgumentError,
"invalid expression in match, #{exp} is not allowed on 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
defp unescape_tokens(tokens) do
case :elixir_interpolation.unescape_tokens(tokens) do
{:ok, unescaped_tokens} -> unescaped_tokens
{:error, reason} -> raise ArgumentError, to_string(reason)
end
end
defp unescape_tokens(tokens, unescape_map) do
case :elixir_interpolation.unescape_tokens(tokens, unescape_map) do
{:ok, unescaped_tokens} -> unescaped_tokens
{:error, reason} -> raise ArgumentError, to_string(reason)
end
end
@doc false
# TODO: Remove by 2.0 (also hard-coded in elixir_dispatch)
@deprecated "Use Kernel.to_charlist/1 instead"
defmacro to_char_list(arg) do
quote(do: Kernel.to_charlist(unquote(arg)))
end
end
| 26.864024 | 98 | 0.635899 |
085dd03097e275428d68e724bbc263e3bcf445a7 | 1,806 | ex | Elixir | clients/games_management/lib/google_api/games_management/v1management/model/profile_settings.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/games_management/lib/google_api/games_management/v1management/model/profile_settings.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/games_management/lib/google_api/games_management/v1management/model/profile_settings.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 "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.GamesManagement.V1management.Model.ProfileSettings do
@moduledoc """
This is a JSON template for profile settings
## Attributes
- kind (String.t): Uniquely identifies the type of this resource. Value is always the fixed string gamesManagement#profileSettings. Defaults to: `null`.
- profileVisible (boolean()): The player's current profile visibility. This field is visible to both 1P and 3P APIs. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kind => any(),
:profileVisible => any()
}
field(:kind)
field(:profileVisible)
end
defimpl Poison.Decoder, for: GoogleApi.GamesManagement.V1management.Model.ProfileSettings do
def decode(value, options) do
GoogleApi.GamesManagement.V1management.Model.ProfileSettings.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.GamesManagement.V1management.Model.ProfileSettings do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.411765 | 154 | 0.751384 |
085dfaf772fbac2bbb7b20283ec519f3273256a6 | 1,797 | ex | Elixir | clients/dataproc/lib/google_api/dataproc/v1/model/managed_group_config.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/dataproc/lib/google_api/dataproc/v1/model/managed_group_config.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/dataproc/lib/google_api/dataproc/v1/model/managed_group_config.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 "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Dataproc.V1.Model.ManagedGroupConfig do
@moduledoc """
Specifies the resources used to actively manage an instance group.
## Attributes
- instanceGroupManagerName (String.t): Output only. The name of the Instance Group Manager for this group. Defaults to: `null`.
- instanceTemplateName (String.t): Output only. The name of the Instance Template used for the Managed Instance Group. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:instanceGroupManagerName => any(),
:instanceTemplateName => any()
}
field(:instanceGroupManagerName)
field(:instanceTemplateName)
end
defimpl Poison.Decoder, for: GoogleApi.Dataproc.V1.Model.ManagedGroupConfig do
def decode(value, options) do
GoogleApi.Dataproc.V1.Model.ManagedGroupConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Dataproc.V1.Model.ManagedGroupConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.235294 | 141 | 0.752922 |
085e1754eaf9b3eca65ceae6cd18f29c5f5dcbe2 | 161 | exs | Elixir | demos/phoenix/config/config.exs | bucha/site_encrypt | b5559fa26ce84fd8cb84ebfcddb1b9967214e2eb | [
"MIT"
] | 387 | 2018-05-22T21:46:20.000Z | 2022-03-26T18:51:01.000Z | demos/phoenix/config/config.exs | bucha/site_encrypt | b5559fa26ce84fd8cb84ebfcddb1b9967214e2eb | [
"MIT"
] | 41 | 2018-06-03T13:02:24.000Z | 2022-02-14T11:16:24.000Z | demos/phoenix/config/config.exs | bucha/site_encrypt | b5559fa26ce84fd8cb84ebfcddb1b9967214e2eb | [
"MIT"
] | 24 | 2018-05-24T07:04:12.000Z | 2022-02-09T08:21:05.000Z | use Mix.Config
config :phoenix, json_library: Jason
config :phoenix_demo, PhoenixDemo.Endpoint, []
if Mix.env() == :test do
config :logger, level: :warn
end
| 17.888889 | 46 | 0.726708 |
085e2448604ec9e0b00baa6aaa4103e6f28afc81 | 429 | exs | Elixir | test/huemulixir_web/views/error_view_test.exs | NinjasCL/huemulixir | 0f0ceb69f19e5d361725284f0f8cb1264e7e1742 | [
"BSD-2-Clause"
] | 2 | 2022-03-21T00:57:19.000Z | 2022-03-25T14:28:15.000Z | test/huemulixir_web/views/error_view_test.exs | NinjasCL/huemulixir | 0f0ceb69f19e5d361725284f0f8cb1264e7e1742 | [
"BSD-2-Clause"
] | null | null | null | test/huemulixir_web/views/error_view_test.exs | NinjasCL/huemulixir | 0f0ceb69f19e5d361725284f0f8cb1264e7e1742 | [
"BSD-2-Clause"
] | null | null | null | defmodule HuemulixirWeb.ErrorViewTest do
use HuemulixirWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.html" do
assert render_to_string(HuemulixirWeb.ErrorView, "404.html", []) == "Not Found"
end
test "renders 500.html" do
assert render_to_string(HuemulixirWeb.ErrorView, "500.html", []) == "Internal Server Error"
end
end
| 28.6 | 95 | 0.741259 |
085e3ee47cc9f413e3821fde82cf906cc029ec04 | 2,696 | ex | Elixir | clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_key.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_key.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_key.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 "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Key do
@moduledoc """
A unique identifier for a Datastore entity.
If a key's partition ID or any of its path kinds or names are
reserved/read-only, the key is reserved/read-only.
A reserved/read-only key is forbidden in certain documented contexts.
## Attributes
* `partitionId` (*type:* `GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2PartitionId.t`, *default:* `nil`) - Entities are partitioned into subsets, currently identified by a project
ID and namespace ID.
Queries are scoped to a single partition.
* `path` (*type:* `list(GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2PathElement.t)`, *default:* `nil`) - The entity path.
An entity path consists of one or more elements composed of a kind and a
string or numerical identifier, which identify entities. The first
element identifies a _root entity_, the second element identifies
a _child_ of the root entity, the third element identifies a child of the
second entity, and so forth. The entities identified by all prefixes of
the path are called the element's _ancestors_.
A path can never be empty, and a path can have at most 100 elements.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:partitionId => GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2PartitionId.t(),
:path => list(GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2PathElement.t())
}
field(:partitionId, as: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2PartitionId)
field(:path, as: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2PathElement, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Key do
def decode(value, options) do
GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Key.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2Key do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 42.793651 | 179 | 0.746662 |
085e44ebb584e4567b1c6bd0fa6975295891f11f | 917 | exs | Elixir | apps/firestorm_web/test/unit/markdown_test.exs | CircleCI-Public/firestorm | 9ca2c46a2b2377370347ad94d6003eeb77be38d6 | [
"MIT"
] | 10 | 2017-06-28T08:06:52.000Z | 2022-03-19T17:49:21.000Z | apps/firestorm_web/test/unit/markdown_test.exs | CircleCI-Public/firestorm | 9ca2c46a2b2377370347ad94d6003eeb77be38d6 | [
"MIT"
] | null | null | null | apps/firestorm_web/test/unit/markdown_test.exs | CircleCI-Public/firestorm | 9ca2c46a2b2377370347ad94d6003eeb77be38d6 | [
"MIT"
] | 2 | 2017-10-21T12:01:02.000Z | 2021-01-29T10:26:22.000Z | defmodule FirestormWeb.MarkdownTest do
use ExUnit.Case
alias FirestormWeb.Markdown
test "renders basic things" do
assert "<p>foo</p>" == Markdown.render("foo")
end
test "autolinks URLs" do
assert "<p><a href=\"http://slashdot.org\">http://slashdot.org</a></p>" == Markdown.render("http://slashdot.org")
end
test "handles markdown links reasonably" do
input = "[This is a link](http://slashdot.org)"
output = "<p><a href=\"http://slashdot.org\">This is a link</a></p>"
assert output == Markdown.render(input)
end
test "converts words like :poop: into their emoji unicode representation" do
poop = Exmoji.from_short_name("poop") |> Exmoji.EmojiChar.render
fire = Exmoji.from_short_name("fire") |> Exmoji.EmojiChar.render
input = "This :poop::fire: is great!"
output = "<p>This #{poop}#{fire} is great!</p>"
assert output == Markdown.render(input)
end
end
| 33.962963 | 117 | 0.669575 |
085e45c3e283e8db8a53d96b1480ff1fa668e94e | 528 | exs | Elixir | test/alertlytics/adapters/rabbit_mq_adapter_test.exs | cultivatedcode/alertlytics | 92bbc071bfc667e8c15dca6aa3a5cc28627f2fed | [
"Apache-2.0"
] | null | null | null | test/alertlytics/adapters/rabbit_mq_adapter_test.exs | cultivatedcode/alertlytics | 92bbc071bfc667e8c15dca6aa3a5cc28627f2fed | [
"Apache-2.0"
] | 3 | 2019-02-24T18:04:02.000Z | 2020-06-12T04:36:44.000Z | test/alertlytics/adapters/rabbit_mq_adapter_test.exs | cultivatedcode/alertlytics | 92bbc071bfc667e8c15dca6aa3a5cc28627f2fed | [
"Apache-2.0"
] | null | null | null | defmodule RabbitMqAdapterTest do
use ExUnit.Case
alias Alertlytics.Adapters.RabbitMqAdapter, as: Subject
doctest Alertlytics.Adapters.RabbitMqAdapter
test "parse_response" do
assert 1 == Subject.consumer_count_from_response("{ \"consumers\": 1 }")
end
test "bad address" do
assert false ==
Subject.check(%{
"rabbit_admin_url" => "http://guest:guest@wrong:15672",
"rabbit_vhost" => "/",
"rabbit_queue_name" => "test.queue"
})
end
end
| 27.789474 | 76 | 0.625 |
085e72a88d8441a711b0196270ebf80c2b495dea | 1,084 | ex | Elixir | lib/seent_web/live/page_live.ex | seent-app/seent | 6071a0f90f1cb5345faa0c9e476d3c64310a7be9 | [
"0BSD"
] | null | null | null | lib/seent_web/live/page_live.ex | seent-app/seent | 6071a0f90f1cb5345faa0c9e476d3c64310a7be9 | [
"0BSD"
] | 1 | 2020-07-04T17:19:38.000Z | 2020-07-04T17:19:38.000Z | lib/seent_web/live/page_live.ex | seent-app/seent | 6071a0f90f1cb5345faa0c9e476d3c64310a7be9 | [
"0BSD"
] | null | null | null | defmodule SeentWeb.PageLive do
use SeentWeb, :live_view
@impl true
def mount(_params, _session, socket) do
{:ok, assign(socket, query: "", results: %{})}
end
@impl true
def handle_event("suggest", %{"q" => query}, socket) do
{:noreply, assign(socket, results: search(query), query: query)}
end
@impl true
def handle_event("search", %{"q" => query}, socket) do
case search(query) do
%{^query => vsn} ->
{:noreply, redirect(socket, external: "https://hexdocs.pm/#{query}/#{vsn}")}
_ ->
{:noreply,
socket
|> put_flash(:error, "No dependencies found matching \"#{query}\"")
|> assign(results: %{}, query: query)}
end
end
defp search(query) do
if not SeentWeb.Endpoint.config(:code_reloader) do
raise "action disabled when not in development"
end
for {app, desc, vsn} <- Application.started_applications(),
app = to_string(app),
String.starts_with?(app, query) and not List.starts_with?(desc, ~c"ERTS"),
into: %{},
do: {app, vsn}
end
end
| 27.1 | 84 | 0.599631 |
085eb63acb4a3d8c6d41121563f56b2b0d678636 | 323 | exs | Elixir | day_04/exercise1.exs | dams/adventofcode | dac9638c6fe3c99b726de8899e9baedf2efbb15a | [
"Artistic-2.0"
] | null | null | null | day_04/exercise1.exs | dams/adventofcode | dac9638c6fe3c99b726de8899e9baedf2efbb15a | [
"Artistic-2.0"
] | null | null | null | day_04/exercise1.exs | dams/adventofcode | dac9638c6fe3c99b726de8899e9baedf2efbb15a | [
"Artistic-2.0"
] | null | null | null | defmodule Exercise1 do
def compute(input) do
compute(input, nil, 0)
end
def compute(_input, "00000" <> _md5_rest, nb) do
nb
end
def compute(input, _md5, nb) do
compute(input, :crypto.hash(:md5, input <> to_string(nb+1)) |> Base.encode16, nb + 1)
end
end
input = "ckczppom"
IO.puts Exercise1.compute(input)
| 17 | 87 | 0.684211 |
085ed3ac4f4e09ab10a2424ab9027b5fae4032af | 1,547 | exs | Elixir | test/data/mutate_rows_test.exs | rockneurotiko/bigtable | a83d0c3e513a212265b2f6fc775407fa71ac049c | [
"MIT"
] | null | null | null | test/data/mutate_rows_test.exs | rockneurotiko/bigtable | a83d0c3e513a212265b2f6fc775407fa71ac049c | [
"MIT"
] | null | null | null | test/data/mutate_rows_test.exs | rockneurotiko/bigtable | a83d0c3e513a212265b2f6fc775407fa71ac049c | [
"MIT"
] | null | null | null | defmodule MutateRowsTest do
@moduledoc false
# TODO: Integration tests including errors
alias Bigtable.{MutateRows, Mutations}
use ExUnit.Case
setup do
[
entries: [Mutations.build("Test#123"), Mutations.build("Test#124")]
]
end
describe "MutateRow.build() " do
test "should build a MutateRowsRequest with configured table", context do
expected = %Google.Bigtable.V2.MutateRowsRequest{
app_profile_id: "",
entries: [
%Google.Bigtable.V2.MutateRowsRequest.Entry{
mutations: [],
row_key: "Test#123"
},
%Google.Bigtable.V2.MutateRowsRequest.Entry{
mutations: [],
row_key: "Test#124"
}
],
table_name: Bigtable.Utils.configured_table_name()
}
result = context.entries |> MutateRows.build()
assert result == expected
end
test "should build a MutateRowsRequest with custom table", context do
table_name = "custom-table"
expected = %Google.Bigtable.V2.MutateRowsRequest{
app_profile_id: "",
entries: [
%Google.Bigtable.V2.MutateRowsRequest.Entry{
mutations: [],
row_key: "Test#123"
},
%Google.Bigtable.V2.MutateRowsRequest.Entry{
mutations: [],
row_key: "Test#124"
}
],
table_name: table_name
}
result =
context.entries
|> MutateRows.build(table_name)
assert result == expected
end
end
end
| 24.555556 | 77 | 0.585003 |
085ef87beb155d7be9950f77e914f7bf7255bbe5 | 161 | ex | Elixir | debian/mingw-w64-libpcre.cron.d.ex | mingw-deb/libpcre | 3b506b85702c7a8f06115cea50dc41ffd9aaa7bc | [
"BSD-3-Clause"
] | null | null | null | debian/mingw-w64-libpcre.cron.d.ex | mingw-deb/libpcre | 3b506b85702c7a8f06115cea50dc41ffd9aaa7bc | [
"BSD-3-Clause"
] | null | null | null | debian/mingw-w64-libpcre.cron.d.ex | mingw-deb/libpcre | 3b506b85702c7a8f06115cea50dc41ffd9aaa7bc | [
"BSD-3-Clause"
] | null | null | null | #
# Regular cron jobs for the mingw-w64-libpcre package
#
0 4 * * * root [ -x /usr/bin/mingw-w64-libpcre_maintenance ] && /usr/bin/mingw-w64-libpcre_maintenance
| 32.2 | 102 | 0.720497 |
085f1cfe02758d8ff5123bf19386736c2b5a4b7c | 1,053 | exs | Elixir | apps/omg/test/omg/state/transaction/witness_test.exs | omgnetwork/omg-childchain-v1 | 1e2313029ece2282c22ce411edc078a17e6bba09 | [
"Apache-2.0"
] | 1 | 2020-10-06T03:07:47.000Z | 2020-10-06T03:07:47.000Z | apps/omg/test/omg/state/transaction/witness_test.exs | omgnetwork/omg-childchain-v1 | 1e2313029ece2282c22ce411edc078a17e6bba09 | [
"Apache-2.0"
] | 9 | 2020-09-16T15:31:17.000Z | 2021-03-17T07:12:35.000Z | apps/omg/test/omg/state/transaction/witness_test.exs | omgnetwork/omg-childchain-v1 | 1e2313029ece2282c22ce411edc078a17e6bba09 | [
"Apache-2.0"
] | 1 | 2020-09-30T17:17:27.000Z | 2020-09-30T17:17:27.000Z | # 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.
defmodule OMG.State.Transaction.WitnessTest do
@moduledoc false
use ExUnit.Case, async: true
alias OMG.State.Transaction.Witness
describe "valid?/1" do
test "returns true when is binary and 65 bytes long" do
assert Witness.valid?(<<0::520>>)
end
test "returns false when not a binary" do
refute Witness.valid?([<<0>>])
end
test "returns false when not 65 bytes long" do
refute Witness.valid?(<<0>>)
end
end
end
| 29.25 | 74 | 0.717949 |
085f1db0985a0be856c7a5cea2b51907f3861b33 | 2,731 | ex | Elixir | lib/model/sql.ex | diodechain/diode_server | 1692788bd92cc17654965878abd059d13b5e236c | [
"Apache-2.0"
] | 8 | 2021-03-12T15:35:09.000Z | 2022-03-06T06:37:49.000Z | lib/model/sql.ex | diodechain/diode_server_ex | 5cf47e5253a0caafd335d0af4dba711d4dcad42d | [
"Apache-2.0"
] | 15 | 2019-09-06T07:58:01.000Z | 2021-03-06T17:04:46.000Z | lib/model/sql.ex | diodechain/diode_server | 1692788bd92cc17654965878abd059d13b5e236c | [
"Apache-2.0"
] | 5 | 2021-10-01T12:52:28.000Z | 2022-02-02T19:29:56.000Z | # Diode Server
# Copyright 2021 Diode
# Licensed under the Diode License, Version 1.1
defmodule Model.Sql do
# Automatically defines child_spec/1
use Supervisor
# esqlite doesn't support :infinity
@infinity 300_000_000
defp databases() do
[
{Db.Sync, "sync.sq3"},
{Db.Cache, "cache.sq3"},
{Db.Default, "blockchain.sq3"},
{Db.Tickets, "tickets.sq3"},
{Db.Creds, "wallet.sq3"}
]
end
defp map_mod(Chain.BlockCache), do: Db.Cache
defp map_mod(Model.SyncSql), do: Db.Sync
defp map_mod(Model.CredSql), do: Db.Creds
defp map_mod(Model.TicketSql), do: Db.Tickets
defp map_mod(Model.KademliaSql), do: Db.Tickets
defp map_mod(pid) when is_pid(pid), do: pid
defp map_mod(_), do: Db.Default
def start_link() do
Application.put_env(:sqlitex, :call_timeout, 300_000)
{:ok, pid} = Supervisor.start_link(__MODULE__, [], name: __MODULE__)
Model.MerkleSql.init()
Model.ChainSql.init()
Model.StateSql.init()
Model.TicketSql.init()
Model.KademliaSql.init()
Enum.each(databases(), fn {atom, _file} ->
init_connection(atom)
end)
{:ok, pid}
end
defp init_connection(conn) do
query!(conn, "PRAGMA soft_heap_limit = 1000000000")
query!(conn, "PRAGMA journal_mode = WAL")
query!(conn, "PRAGMA synchronous = NORMAL")
query!(conn, "PRAGMA OPTIMIZE", call_timeout: @infinity)
end
def init(_args) do
File.mkdir(Diode.data_dir())
children =
Enum.map(databases(), fn {atom, file} ->
opts = [name: atom, db_timeout: @infinity, stmt_cache_size: 50]
%{
id: atom,
start: {Sqlitex.Server, :start_link, [Diode.data_dir(file) |> to_charlist(), opts]}
}
end)
children = children ++ [Model.CredSql, Model.SyncSql]
Supervisor.init(children, strategy: :one_for_one)
end
def query(mod, sql, params \\ []) do
params = Keyword.put_new(params, :call_timeout, @infinity)
Stats.tc(:query, fn ->
Sqlitex.Server.query(map_mod(mod), sql, params)
end)
end
def query!(mod, sql, params \\ []) do
{:ok, ret} = query(mod, sql, params)
ret
end
def query_async!(mod, sql, params \\ []) do
Sqlitex.Server.query_async(map_mod(mod), sql, params)
end
def fetch!(mod, sql, param1) do
case lookup!(mod, sql, param1) do
nil -> nil
binary -> BertInt.decode!(binary)
end
end
def lookup!(mod, sql, param1 \\ [], default \\ nil) do
case query!(mod, sql, bind: List.wrap(param1)) do
[] -> default
[[{_key, value}]] -> value
end
end
def with_transaction(mod, fun) do
{:ok, result} = Sqlitex.Server.with_transaction(map_mod(mod), fun, call_timeout: @infinity)
result
end
end
| 26.259615 | 95 | 0.637495 |
085f24d83e7ed1d9baaede3c0bf5bb5abaf73904 | 1,489 | ex | Elixir | lib/timetracker_web/views/error_helpers.ex | LunarLogic/timetracker | 5c2ffffc9023c7b099d7af8de7f21225352483ca | [
"MIT"
] | 1 | 2019-06-26T06:53:01.000Z | 2019-06-26T06:53:01.000Z | lib/timetracker_web/views/error_helpers.ex | LunarLogic/timetracker | 5c2ffffc9023c7b099d7af8de7f21225352483ca | [
"MIT"
] | null | null | null | lib/timetracker_web/views/error_helpers.ex | LunarLogic/timetracker | 5c2ffffc9023c7b099d7af8de7f21225352483ca | [
"MIT"
] | null | null | null | defmodule TimetrackerWeb.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(TimetrackerWeb.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(TimetrackerWeb.Gettext, "errors", msg, opts)
end
end
end
| 33.088889 | 80 | 0.672935 |
085f272be9b57f165015458130479d878c73ee05 | 191 | exs | Elixir | apps/core/priv/repo/migrations/20210427205933_add_publisher_icon.exs | michaeljguarino/forge | 50ee583ecb4aad5dee4ef08fce29a8eaed1a0824 | [
"Apache-2.0"
] | 59 | 2021-09-16T19:29:39.000Z | 2022-03-31T20:44:24.000Z | apps/core/priv/repo/migrations/20210427205933_add_publisher_icon.exs | svilenkov/plural | ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026 | [
"Apache-2.0"
] | 111 | 2021-08-15T09:56:37.000Z | 2022-03-31T23:59:32.000Z | apps/core/priv/repo/migrations/20210427205933_add_publisher_icon.exs | svilenkov/plural | ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026 | [
"Apache-2.0"
] | 4 | 2021-12-13T09:43:01.000Z | 2022-03-29T18:08:44.000Z | defmodule Core.Repo.Migrations.AddPublisherIcon do
use Ecto.Migration
def change do
alter table(:accounts) do
add :icon_id, :uuid
add :icon, :string
end
end
end
| 17.363636 | 50 | 0.670157 |
085f6c483d352b52680cfb56b6748d3536718028 | 313 | exs | Elixir | config/config.exs | LeonardSSH/lanyard | 407bc5c7dfcfcaf28ee72a70dc8695c39980f87d | [
"MIT"
] | 323 | 2021-03-12T17:42:44.000Z | 2022-03-31T21:32:30.000Z | config/config.exs | LeonardSSH/lanyard | 407bc5c7dfcfcaf28ee72a70dc8695c39980f87d | [
"MIT"
] | 56 | 2021-03-22T12:30:36.000Z | 2022-03-25T17:56:01.000Z | config/config.exs | LeonardSSH/lanyard | 407bc5c7dfcfcaf28ee72a70dc8695c39980f87d | [
"MIT"
] | 113 | 2021-03-13T17:30:36.000Z | 2022-03-29T13:19:24.000Z | use Mix.Config
config :lanyard,
discord_spotify_activity_id: "spotify:1",
command_prefix: System.get_env("COMMAND_PREFIX") || ".",
bot_presence: System.get_env("BOT_PRESENCE") || "you <3",
bot_presence_type: String.to_integer(System.get_env("BOT_PRESENCE_TYPE") || "3")
import_config "#{Mix.env()}.exs"
| 31.3 | 82 | 0.728435 |
085f75e663a47d98c12ead24d714352b91dd2f3f | 1,096 | exs | Elixir | test/openapi_compiler_test.exs | jshmrtn/openapi-compiler | 72ce58321bcaf7310b1286fa90dd2feaa2a7b565 | [
"MIT"
] | 3 | 2021-09-07T13:13:44.000Z | 2022-01-16T22:25:11.000Z | test/openapi_compiler_test.exs | jshmrtn/openapi-compiler | 72ce58321bcaf7310b1286fa90dd2feaa2a7b565 | [
"MIT"
] | 26 | 2020-03-31T17:26:58.000Z | 2020-04-01T17:32:21.000Z | test/openapi_compiler_test.exs | jshmrtn/openapi-compiler | 72ce58321bcaf7310b1286fa90dd2feaa2a7b565 | [
"MIT"
] | 1 | 2020-10-27T13:32:07.000Z | 2020-10-27T13:32:07.000Z | defmodule OpenAPICompilerTest do
@moduledoc false
use ExUnit.Case, async: true
doctest OpenAPICompiler
test "valid response" do
Tesla.Mock.mock(fn
%Tesla.Env{url: "https://dev.localhost:8080/valid"} ->
%Tesla.Env{
status: 200,
body: ~S("hello"),
headers: [{"content-type", "application/json"}]
}
end)
assert {:ok, {200, "hello", _}} =
Internal.post_id(%{
path: %{id: "valid"},
body: %{coutry: "CH", city: "St. Gallen", street: "Neugasse 51"}
})
end
test "invalid return code" do
Tesla.Mock.mock(fn
%Tesla.Env{url: "https://dev.localhost:8080/invalid"} ->
%Tesla.Env{
status: 400,
body: ~S({"error": "bad request"}),
headers: [{"content-type", "application/json"}]
}
end)
assert {:error, {:unexpected_response, _}} =
Internal.post_id(%{
path: %{id: "invalid"},
body: %{coutry: "CH", city: "St. Gallen", street: "Neugasse 51"}
})
end
end
| 26.095238 | 79 | 0.513686 |
085fd70018555269e570b6cc2c5ea50815206022 | 1,192 | exs | Elixir | config/config.exs | noelbk/battlesnake | cb50a40cc2fd47fb335835c5b0e92d7761e7ea13 | [
"MIT"
] | null | null | null | config/config.exs | noelbk/battlesnake | cb50a40cc2fd47fb335835c5b0e92d7761e7ea13 | [
"MIT"
] | null | null | null | config/config.exs | noelbk/battlesnake | cb50a40cc2fd47fb335835c5b0e92d7761e7ea13 | [
"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 :battlesnake, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:battlesnake, :key)
#
# Or configure a 3rd-party app:
#
config :logger,
backends: [:console],
level: :warn,
handle_sasl_reports: true,
handle_otp_reports: true
# 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"
| 35.058824 | 73 | 0.760906 |
085ff9081761894c12fbc03ceeb5ea42da72a10e | 3,823 | ex | Elixir | lib/koans/12_pattern_matching.ex | kapware/elixir-koans | 47f1d8705d7748fac026c3996c31b460e90697fe | [
"MIT"
] | null | null | null | lib/koans/12_pattern_matching.ex | kapware/elixir-koans | 47f1d8705d7748fac026c3996c31b460e90697fe | [
"MIT"
] | null | null | null | lib/koans/12_pattern_matching.ex | kapware/elixir-koans | 47f1d8705d7748fac026c3996c31b460e90697fe | [
"MIT"
] | null | null | null | defmodule PatternMatching do
use Koans
@intro "PatternMatching"
koan "One matches one" do
assert match?(1, 1)
end
koan "Patterns can be used to pull things apart" do
[head | tail] = [1, 2, 3, 4]
assert head == 1
assert tail == [2, 3, 4]
end
koan "And then put them back together" do
head = 1
tail = [2, 3, 4]
assert [1, 2, 3, 4] == [head | tail]
end
koan "Some values can be ignored" do
[_first, _second, third, _fourth] = [1, 2, 3, 4]
assert third == 3
end
koan "Strings come apart just as easily" do
"Shopping list: " <> items = "Shopping list: eggs, milk"
assert items == "eggs, milk"
end
koan "Maps support partial pattern matching" do
%{make: make} = %{type: "car", year: 2016, make: "Honda", color: "black"}
assert make == "Honda"
end
koan "Lists must match exactly" do
assert_raise MatchError, fn ->
[a, b] = [1,2,3]
end
end
koan "So does the keyword lists" do
kw_list = [type: "car", year: 2016, make: "Honda"]
[_type | [_year | [tuple]]] = kw_list
assert tuple == {:make, "Honda"}
end
koan "The pattern can make assertions about what it expects" do
assert match?([1, _second, _third], [1, "foo", "bar"])
end
def make_noise(%{type: "cat"}), do: "Meow"
def make_noise(%{type: "dog"}), do: "Woof"
def make_noise(_anything), do: "Eh?"
koan "Functions perform pattern matching on their arguments" do
cat = %{type: "cat"}
dog = %{type: "dog"}
snake = %{type: "snake"}
assert make_noise(cat) == "Meow"
assert make_noise(dog) == "Woof"
assert make_noise(snake) == "Eh?"
end
koan "And they will only run the code that matches the argument" do
name = fn
("duck") -> "Donald"
("mouse") -> "Mickey"
(_other) -> "I need a name!"
end
assert name.("mouse") == "Mickey"
assert name.("duck") == "Donald"
assert name.("donkey") == "I need a name!"
end
koan "Errors are shaped differently than successful results" do
dog = %{type: "dog"}
result = case Map.fetch(dog, :type) do
{:ok, value} -> value
:error -> "not present"
end
assert result == "dog"
end
defmodule Animal do
defstruct [:kind, :name]
end
koan "You can pattern match into the fields of a struct" do
%Animal{name: name} = %Animal{kind: "dog", name: "Max"}
assert name == "Max"
end
defmodule Plane do
defstruct passengers: 0, maker: :boeing
end
def plane?(%Plane{}), do: true
def plane?(_), do: false
koan "...or onto the type of the struct itself" do
assert plane?(%Plane{passengers: 417, maker: :boeing}) == true
assert plane?(%Animal{}) == false
end
koan "Structs will even match with a regular map" do
%{name: name} = %Animal{kind: "dog", name: "Max"}
assert name == "Max"
end
koan "A value can be bound to a variable" do
a = 1
assert a == 1
end
koan "A variable can be rebound" do
a = 1
a = 2
assert a == 2
end
koan "A variable can be pinned to use its value when matching instead of binding to a new value" do
pinned_variable = 1
example = fn
(^pinned_variable) -> "The number One"
(2) -> "The number Two"
(number) -> "The number #{number}"
end
assert example.(1) == "The number One"
assert example.(2) == "The number Two"
assert example.(3) == "The number 3"
end
koan "Pinning works anywhere one would match, including 'case'" do
pinned_variable = 1
result = case 1 do
^pinned_variable -> "same"
other -> "different #{other}"
end
assert result == "same"
end
koan "Trying to rebind a pinned variable will result in an error" do
a = 1
assert_raise MatchError, fn() ->
^a = 2
end
end
end
| 23.598765 | 101 | 0.592728 |
08600c03fda6cc9f1ce8296634b81ec40d707d3a | 1,418 | exs | Elixir | priv/repo/migrations/20220511024749_finance.exs | knoebber/petaller | 3532db5a3688459127d2427af42e32ca0f494d44 | [
"MIT"
] | null | null | null | priv/repo/migrations/20220511024749_finance.exs | knoebber/petaller | 3532db5a3688459127d2427af42e32ca0f494d44 | [
"MIT"
] | null | null | null | priv/repo/migrations/20220511024749_finance.exs | knoebber/petaller | 3532db5a3688459127d2427af42e32ca0f494d44 | [
"MIT"
] | null | null | null | defmodule Purple.Repo.Migrations.Finance do
use Ecto.Migration
def change do
create table(:merchants) do
add :name, :citext, null: false
add :description, :text, null: false, default: ""
timestamps()
end
create unique_index(:merchants, [:name])
create table(:payment_methods) do
add :name, :citext, null: false
timestamps()
end
create unique_index(:payment_methods, [:name])
create table(:transactions) do
add :cents, :int, null: false
add :timestamp, :naive_datetime, null: false
add :description, :text, null: false, default: ""
add :merchant_id, references(:merchants), null: false
add :payment_method_id, references(:payment_methods), null: false
add :user_id, references(:users), null: false
timestamps()
end
create table(:transaction_tags) do
add :transaction_id, references(:transactions, on_delete: :delete_all), null: false
add :tag_id, references(:tags), null: false
timestamps(updated_at: false)
end
create unique_index(:transaction_tags, [:transaction_id, :tag_id])
create table(:merchant_tags) do
add :merchant_id, references(:merchants, on_delete: :delete_all), null: false
add :tag_id, references(:tags), null: false
timestamps(updated_at: false)
end
create unique_index(:merchant_tags, [:merchant_id, :tag_id])
end
end
| 27.803922 | 89 | 0.673484 |
08604edfeac1d9dc0c475999182c1b7eed1b6ecb | 247 | exs | Elixir | priv/test_repo/migrations/1_migrate_all.exs | tineo/absinthe_ecto | 55e31dfd4e7932c1e31c8beac7aa22d663fdc304 | [
"MIT"
] | 132 | 2016-11-20T22:23:30.000Z | 2021-07-18T18:16:19.000Z | priv/test_repo/migrations/1_migrate_all.exs | tineo/absinthe_ecto | 55e31dfd4e7932c1e31c8beac7aa22d663fdc304 | [
"MIT"
] | 34 | 2016-11-24T05:06:57.000Z | 2022-02-23T16:57:40.000Z | priv/test_repo/migrations/1_migrate_all.exs | tineo/absinthe_ecto | 55e31dfd4e7932c1e31c8beac7aa22d663fdc304 | [
"MIT"
] | 36 | 2016-11-22T06:38:59.000Z | 2022-03-09T11:32:53.000Z | defmodule Absinthe.Ecto.TestRepo.Migrations.MigrateAll do
use Ecto.Migration
def change do
create table(:users) do
add :username, :string
end
create table(:posts) do
add :user_id, references(:users)
end
end
end
| 17.642857 | 57 | 0.680162 |
086070eaaa92af998a2bfe3ac9ef8219d8339fb7 | 1,962 | exs | Elixir | test/clienthandler_test.exs | ServusGameServer/Servus_Protobuf | cb870b7dccb6676e71045e231fd31547d63efa74 | [
"Apache-2.0"
] | 2 | 2018-10-19T06:14:08.000Z | 2018-11-23T00:56:09.000Z | test/clienthandler_test.exs | ServusGameServer/Servus_Protobuf | cb870b7dccb6676e71045e231fd31547d63efa74 | [
"Apache-2.0"
] | null | null | null | test/clienthandler_test.exs | ServusGameServer/Servus_Protobuf | cb870b7dccb6676e71045e231fd31547d63efa74 | [
"Apache-2.0"
] | null | null | null | defmodule ClientHandlerTests do
use ExUnit.Case
alias Servus.Serverutils
alias Servus.ProtoFactory
setup_all do
connect_opts = [
:binary,
packet: :raw,
active: false,
reuseaddr: true
]
{:ok, socket_alice} = :gen_tcp.connect('localhost', 3334, connect_opts)
{:ok,
[
alice: %{raw: socket_alice, type: :tcp, socket: "dummy"}
]}
end
test "Wrong ModuleName without Auth", context do
assert :ok == Serverutils.send(context.alice, ProtoFactory.newMessage_authFunctions(:UNKNOWN, :AUTH_REGISTER))
assert {:ok, returnMessage} = Serverutils.recv(context.alice)
data = LoadedProtobuf.ServusMessage.decode(returnMessage)
assert %LoadedProtobuf.ServusMessage{error: true, errorType: :ERROR_NO_AUTH} = data
end
test "Wrong ModuleName with Auth", context do
assert :ok == Serverutils.send(context.alice, ProtoFactory.newMessage_authFunctions_VString(:AUTH_ONLY, :AUTH_REGISTER, "JOHN DOE"))
assert {:ok, returnMessage} = Serverutils.recv(context.alice)
data = LoadedProtobuf.ServusMessage.decode(returnMessage)
assert %LoadedProtobuf.ServusMessage{error: false, value: {:value_OnlyAuth, _}} = data
# Logged in now
assert :ok == Serverutils.send(context.alice, ProtoFactory.newMessage_authFunctions(:UNKNOWN, :AUTH_REGISTER))
assert {:ok, returnMessage} = Serverutils.recv(context.alice)
data = LoadedProtobuf.ServusMessage.decode(returnMessage)
assert %LoadedProtobuf.ServusMessage{error: true, errorType: :ERROR_NO_AUTH} = data
end
test "Wrong FunctionName", context do
# Wrong first Account
assert :ok == Serverutils.send(context.alice, ProtoFactory.newMessage_authFunctions(:AUTH_SELF, :AUTH_UNKOWN))
assert {:ok, returnMessage} = Serverutils.recv(context.alice)
data = LoadedProtobuf.ServusMessage.decode(returnMessage)
assert %LoadedProtobuf.ServusMessage{error: true, errorType: :ERROR_WRONGMETHOD} = data
end
end
| 40.040816 | 136 | 0.732926 |
08607564abe599cf1fcb69535031394c0cdd330f | 424 | exs | Elixir | 2019/utilities.exs | KashMoneyMillionaire/adventofcode | 2160b4af4ad9a994cfde2bffb65a6f6758c8003d | [
"MIT"
] | null | null | null | 2019/utilities.exs | KashMoneyMillionaire/adventofcode | 2160b4af4ad9a994cfde2bffb65a6f6758c8003d | [
"MIT"
] | null | null | null | 2019/utilities.exs | KashMoneyMillionaire/adventofcode | 2160b4af4ad9a994cfde2bffb65a6f6758c8003d | [
"MIT"
] | null | null | null | defmodule Utilities do
def read_list_int() do
"input.txt"
|> File.read!()
|> String.trim()
|> String.split()
|> Enum.take_while(fn x -> x != "#" end)
|> Enum.map(&String.to_integer/1)
end
def read_list_int(split) do
"input.txt"
|> File.read!()
|> String.trim()
|> String.split(split)
|> Enum.take_while(fn x -> x != "#" end)
|> Enum.map(&String.to_integer/1)
end
end
| 21.2 | 44 | 0.563679 |
0860956e441f0891bd6d4ce2030fca60007fea1c | 708 | exs | Elixir | lib/iex/test/iex/evaluator_test.exs | mk/elixir | 2b2c66ecf7b1cc2167cae9cc3e88f950994223f1 | [
"Apache-2.0"
] | 4 | 2015-12-22T02:46:39.000Z | 2016-04-26T06:11:09.000Z | lib/iex/test/iex/evaluator_test.exs | mk/elixir | 2b2c66ecf7b1cc2167cae9cc3e88f950994223f1 | [
"Apache-2.0"
] | null | null | null | lib/iex/test/iex/evaluator_test.exs | mk/elixir | 2b2c66ecf7b1cc2167cae9cc3e88f950994223f1 | [
"Apache-2.0"
] | 1 | 2020-12-07T08:04:16.000Z | 2020-12-07T08:04:16.000Z | Code.require_file "../test_helper.exs", __DIR__
defmodule IEx.EvaluatorTest do
use ExUnit.Case, async: true
alias IEx.Evaluator, as: E
test "format_stacktrace returns formatted result in columns" do
frames = [
{List, :one, 1, [file: "loc", line: 1]},
{String, :second, 2, [file: "loc2", line: 102]},
{IEx, :three, 3, [file: "longer", line: 1234]},
{List, :four, 4, [file: "loc", line: 1]},
]
expected = """
(elixir) loc:1: List.one/1
(elixir) loc2:102: String.second/2
(iex) longer:1234: IEx.three/3
(elixir) loc:1: List.four/4
"""
assert E.format_stacktrace(frames) <> "\n" == expected
end
end
| 27.230769 | 65 | 0.564972 |
0860c29d3bbd4888890b9d5214f50fbecac53b0e | 2,913 | ex | Elixir | clients/you_tube_reporting/lib/google_api/you_tube_reporting/v1/model/gdata_composite_media.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/you_tube_reporting/lib/google_api/you_tube_reporting/v1/model/gdata_composite_media.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/you_tube_reporting/lib/google_api/you_tube_reporting/v1/model/gdata_composite_media.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.YouTubeReporting.V1.Model.GdataCompositeMedia do
@moduledoc """
gdata
## Attributes
* `blobRef` (*type:* `String.t`, *default:* `nil`) - gdata
* `blobstore2Info` (*type:* `GoogleApi.YouTubeReporting.V1.Model.GdataBlobstore2Info.t`, *default:* `nil`) - gdata
* `cosmoBinaryReference` (*type:* `String.t`, *default:* `nil`) - gdata
* `crc32cHash` (*type:* `integer()`, *default:* `nil`) - gdata
* `inline` (*type:* `String.t`, *default:* `nil`) - gdata
* `length` (*type:* `String.t`, *default:* `nil`) - gdata
* `md5Hash` (*type:* `String.t`, *default:* `nil`) - gdata
* `objectId` (*type:* `GoogleApi.YouTubeReporting.V1.Model.GdataObjectId.t`, *default:* `nil`) - gdata
* `path` (*type:* `String.t`, *default:* `nil`) - gdata
* `referenceType` (*type:* `String.t`, *default:* `nil`) - gdata
* `sha1Hash` (*type:* `String.t`, *default:* `nil`) - gdata
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:blobRef => String.t(),
:blobstore2Info => GoogleApi.YouTubeReporting.V1.Model.GdataBlobstore2Info.t(),
:cosmoBinaryReference => String.t(),
:crc32cHash => integer(),
:inline => String.t(),
:length => String.t(),
:md5Hash => String.t(),
:objectId => GoogleApi.YouTubeReporting.V1.Model.GdataObjectId.t(),
:path => String.t(),
:referenceType => String.t(),
:sha1Hash => String.t()
}
field(:blobRef)
field(:blobstore2Info, as: GoogleApi.YouTubeReporting.V1.Model.GdataBlobstore2Info)
field(:cosmoBinaryReference)
field(:crc32cHash)
field(:inline)
field(:length)
field(:md5Hash)
field(:objectId, as: GoogleApi.YouTubeReporting.V1.Model.GdataObjectId)
field(:path)
field(:referenceType)
field(:sha1Hash)
end
defimpl Poison.Decoder, for: GoogleApi.YouTubeReporting.V1.Model.GdataCompositeMedia do
def decode(value, options) do
GoogleApi.YouTubeReporting.V1.Model.GdataCompositeMedia.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.YouTubeReporting.V1.Model.GdataCompositeMedia do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 37.831169 | 118 | 0.673532 |
0860c3cf4e5c4b2dca5bf32a6b0ec49dfa5d20a4 | 331 | exs | Elixir | Books/Programming_Elixir-Dave_Thomas/ch_14/spawn/link2.exs | cjschneider2/book_example_problems | 18192a6d3ddb4371b79f88e4ab3444d25f2e1ce0 | [
"Unlicense"
] | null | null | null | Books/Programming_Elixir-Dave_Thomas/ch_14/spawn/link2.exs | cjschneider2/book_example_problems | 18192a6d3ddb4371b79f88e4ab3444d25f2e1ce0 | [
"Unlicense"
] | null | null | null | Books/Programming_Elixir-Dave_Thomas/ch_14/spawn/link2.exs | cjschneider2/book_example_problems | 18192a6d3ddb4371b79f88e4ab3444d25f2e1ce0 | [
"Unlicense"
] | null | null | null | defmodule Link2 do
import :timer, only: [sleep: 1]
def sad_function do
sleep 500
exit(:boom)
end
def run do
spawn_link(Link2, :sad_function, [])
receive do
msg ->
IO.puts "Message Revieved #{inspect msg}"
after 1000 ->
IO.puts "Nothing Happened..."
end
end
end
Link2.run
| 15.045455 | 49 | 0.598187 |
0860d500b8bf659b40a7dfdef657f7c7dbf58dc0 | 566 | exs | Elixir | test/chronos/timezone_test.exs | nurugger07/chronos | be8fcbee7330d938dff87532cf108125bf952d05 | [
"Apache-2.0"
] | 72 | 2015-01-28T16:30:45.000Z | 2021-05-21T03:33:16.000Z | test/chronos/timezone_test.exs | nurugger07/chronos | be8fcbee7330d938dff87532cf108125bf952d05 | [
"Apache-2.0"
] | 9 | 2015-01-20T21:08:43.000Z | 2018-04-04T02:57:05.000Z | test/chronos/timezone_test.exs | nurugger07/chronos | be8fcbee7330d938dff87532cf108125bf952d05 | [
"Apache-2.0"
] | 15 | 2015-01-20T04:34:06.000Z | 2019-02-10T22:42:12.000Z | defmodule TimezonesTest do
use ExUnit.Case
import Chronos.Timezones
test "retieve the timezone offset" do
assert "-6:00" == offset "CST"
assert "-6:00" == offset "Central Standard Time"
assert "-5:00" == offset "EST"
assert "" == offset "BOB"
end
test "retrieve the timezone abbreviation" do
assert "CST" == abbreviation "Central Standard Time"
assert "CST" == abbreviation "-6:00"
assert "EST" == abbreviation "Eastern Standard Time"
assert "EST" == abbreviation "-5:00"
assert "" == abbreviation "BOB"
end
end
| 23.583333 | 56 | 0.651943 |
0860d6468c41eab12578b311bff0f58cb73962c7 | 1,346 | ex | Elixir | lib/journal/adapter.ex | revelrylabs/journal | 82450c22a5f77e152a0f91ba37345bc411e002e0 | [
"MIT"
] | 1 | 2019-08-09T06:01:42.000Z | 2019-08-09T06:01:42.000Z | lib/journal/adapter.ex | revelrylabs/journal | 82450c22a5f77e152a0f91ba37345bc411e002e0 | [
"MIT"
] | 3 | 2019-02-23T23:31:16.000Z | 2019-03-07T15:22:23.000Z | lib/journal/adapter.ex | revelrylabs/journal | 82450c22a5f77e152a0f91ba37345bc411e002e0 | [
"MIT"
] | 1 | 2020-03-05T21:17:21.000Z | 2020-03-05T21:17:21.000Z | defmodule Journal.Adapter do
@moduledoc """
Specifies API for Journal adapters
"""
@type adapter_meta :: map
alias Journal.Entry
alias Journal.Error
@doc """
Initializes the adapter
"""
@callback init(config :: Keyword.t()) :: {:ok, :supervisor.child_spec() | nil, adapter_meta}
@doc """
Stores data by key. If there is data already associated with that key then the
new data is stored as a new version.
"""
@callback put(adapter_meta :: adapter_meta, key :: binary(), value :: any()) ::
{:ok, Entry.t()} | {:error, Error.t()}
@doc """
Gets the latest version of data with the associated key or nil
"""
@callback get(adapter_meta :: adapter_meta, key :: binary()) ::
{:ok, Entry.t()} | {:error, Error.t()}
@doc """
Gets the specified version of data with the associated key or nil
"""
@callback get(adapter_meta :: adapter_meta, key :: binary(), version :: integer) ::
{:ok, Entry.t()} | {:error, Error.t()}
@doc """
Returns version data for the given key
"""
@callback versions(adapter_meta :: adapter_meta, key :: binary()) ::
{:ok, [Entry.t()]} | {:error, Error.t()}
@doc """
Removes all data associated with the key
"""
@callback delete(adapter_meta :: adapter_meta, key :: binary()) :: :ok | {:error, Error.t()}
end
| 29.911111 | 94 | 0.611441 |
0860f586ef8f7c3350e6c7c098fccaae9092dd70 | 63 | ex | Elixir | lib/first_app_web/views/page_view.ex | marcogbarcellos/phoenix_first_app | f610831a05e32fc4b15cf49630008c307024d023 | [
"MIT"
] | null | null | null | lib/first_app_web/views/page_view.ex | marcogbarcellos/phoenix_first_app | f610831a05e32fc4b15cf49630008c307024d023 | [
"MIT"
] | null | null | null | lib/first_app_web/views/page_view.ex | marcogbarcellos/phoenix_first_app | f610831a05e32fc4b15cf49630008c307024d023 | [
"MIT"
] | null | null | null | defmodule FirstAppWeb.PageView do
use FirstAppWeb, :view
end
| 15.75 | 33 | 0.809524 |
0860fbf41caf832c2d09a5d02e85a096a06096af | 5,724 | ex | Elixir | clients/recommender/lib/google_api/recommender/v1/model/google_cloud_recommender_v1_operation.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/recommender/lib/google_api/recommender/v1/model/google_cloud_recommender_v1_operation.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/recommender/lib/google_api/recommender/v1/model/google_cloud_recommender_v1_operation.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Recommender.V1.Model.GoogleCloudRecommenderV1Operation do
@moduledoc """
Contains an operation for a resource loosely based on the JSON-PATCH format with support for: * Custom filters for describing partial array patch. * Extended path values for describing nested arrays. * Custom fields for describing the resource for which the operation is being described. * Allows extension to custom operations not natively supported by RFC6902. See https://tools.ietf.org/html/rfc6902 for details on the original RFC.
## Attributes
* `action` (*type:* `String.t`, *default:* `nil`) - Type of this operation. Contains one of 'and', 'remove', 'replace', 'move', 'copy', 'test' and custom operations. This field is case-insensitive and always populated.
* `path` (*type:* `String.t`, *default:* `nil`) - Path to the target field being operated on. If the operation is at the resource level, then path should be "/". This field is always populated.
* `pathFilters` (*type:* `map()`, *default:* `nil`) - Set of filters to apply if `path` refers to array elements or nested array elements in order to narrow down to a single unique element that is being tested/modified. This is intended to be an exact match per filter. To perform advanced matching, use path_value_matchers. * Example: { "/versions/*/name" : "it-123" "/versions/*/targetSize/percent": 20 } * Example: { "/bindings/*/role": "roles/owner" "/bindings/*/condition" : null } * Example: { "/bindings/*/role": "roles/owner" "/bindings/*/members/*" : ["x@example.com", "y@example.com"] } When both path_filters and path_value_matchers are set, an implicit AND must be performed.
* `pathValueMatchers` (*type:* `%{optional(String.t) => GoogleApi.Recommender.V1.Model.GoogleCloudRecommenderV1ValueMatcher.t}`, *default:* `nil`) - Similar to path_filters, this contains set of filters to apply if `path` field referes to array elements. This is meant to support value matching beyond exact match. To perform exact match, use path_filters. When both path_filters and path_value_matchers are set, an implicit AND must be performed.
* `resource` (*type:* `String.t`, *default:* `nil`) - Contains the fully qualified resource name. This field is always populated. ex: //cloudresourcemanager.googleapis.com/projects/foo.
* `resourceType` (*type:* `String.t`, *default:* `nil`) - Type of GCP resource being modified/tested. This field is always populated. Example: cloudresourcemanager.googleapis.com/Project, compute.googleapis.com/Instance
* `sourcePath` (*type:* `String.t`, *default:* `nil`) - Can be set with action 'copy' or 'move' to indicate the source field within resource or source_resource, ignored if provided for other operation types.
* `sourceResource` (*type:* `String.t`, *default:* `nil`) - Can be set with action 'copy' to copy resource configuration across different resources of the same type. Example: A resource clone can be done via action = 'copy', path = "/", from = "/", source_resource = and resource_name = . This field is empty for all other values of `action`.
* `value` (*type:* `any()`, *default:* `nil`) - Value for the `path` field. Will be set for actions:'add'/'replace'. Maybe set for action: 'test'. Either this or `value_matcher` will be set for 'test' operation. An exact match must be performed.
* `valueMatcher` (*type:* `GoogleApi.Recommender.V1.Model.GoogleCloudRecommenderV1ValueMatcher.t`, *default:* `nil`) - Can be set for action 'test' for advanced matching for the value of 'path' field. Either this or `value` will be set for 'test' operation.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:action => String.t(),
:path => String.t(),
:pathFilters => map(),
:pathValueMatchers => %{
optional(String.t()) =>
GoogleApi.Recommender.V1.Model.GoogleCloudRecommenderV1ValueMatcher.t()
},
:resource => String.t(),
:resourceType => String.t(),
:sourcePath => String.t(),
:sourceResource => String.t(),
:value => any(),
:valueMatcher => GoogleApi.Recommender.V1.Model.GoogleCloudRecommenderV1ValueMatcher.t()
}
field(:action)
field(:path)
field(:pathFilters, type: :map)
field(:pathValueMatchers,
as: GoogleApi.Recommender.V1.Model.GoogleCloudRecommenderV1ValueMatcher,
type: :map
)
field(:resource)
field(:resourceType)
field(:sourcePath)
field(:sourceResource)
field(:value)
field(:valueMatcher, as: GoogleApi.Recommender.V1.Model.GoogleCloudRecommenderV1ValueMatcher)
end
defimpl Poison.Decoder, for: GoogleApi.Recommender.V1.Model.GoogleCloudRecommenderV1Operation do
def decode(value, options) do
GoogleApi.Recommender.V1.Model.GoogleCloudRecommenderV1Operation.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Recommender.V1.Model.GoogleCloudRecommenderV1Operation do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 69.804878 | 691 | 0.722048 |
08610a0e8a1893e3f36665218cc2781d4aba1229 | 423 | exs | Elixir | day_5/day_5.exs | cjschneider2/advent_of_code_2015 | 347b45ba3201f874aab5fa74ec9a2594e68def48 | [
"MIT"
] | null | null | null | day_5/day_5.exs | cjschneider2/advent_of_code_2015 | 347b45ba3201f874aab5fa74ec9a2594e68def48 | [
"MIT"
] | null | null | null | day_5/day_5.exs | cjschneider2/advent_of_code_2015 | 347b45ba3201f874aab5fa74ec9a2594e68def48 | [
"MIT"
] | null | null | null | defmodule Day5 do
defp contains_vowels(input, vowel_count) do
end
defp contains_double_letter(input) do
end
defp contains_forbidden_strings(input, strings) do
end
def run_tests() do
{:ok, file} = File.read("day_5-test_input.txt")
strings = file
|> String.split(~r/\R/)
strings
|> Task.async_stream(fn x -> IO.puts(x) end)
|> Enum.to_list()
end
end
Day5.run_tests() | 16.269231 | 52 | 0.647754 |
086117a4e6d02afa0e43c21787192cef5e1e01c9 | 1,044 | ex | Elixir | test/support/conn_case.ex | jordyvanvorselen/chewie-backend | b382ee0726f54d8ae45f2b41f43e38469cecc326 | [
"MIT"
] | null | null | null | test/support/conn_case.ex | jordyvanvorselen/chewie-backend | b382ee0726f54d8ae45f2b41f43e38469cecc326 | [
"MIT"
] | null | null | null | test/support/conn_case.ex | jordyvanvorselen/chewie-backend | b382ee0726f54d8ae45f2b41f43e38469cecc326 | [
"MIT"
] | null | null | null | defmodule ChewieWeb.ConnCase do
alias Ecto.Adapters.SQL.Sandbox
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
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 connections
use Phoenix.ConnTest
alias ChewieWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint ChewieWeb.Endpoint
end
end
setup tags do
:ok = Sandbox.checkout(Chewie.Repo)
unless tags[:async] do
Sandbox.mode(Chewie.Repo, {:shared, self()})
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 25.463415 | 59 | 0.714559 |
08612a68ddee5e6eb04bcf66c1e48efea33d6f3b | 5,662 | ex | Elixir | kousa/lib/data-layer/user_data.ex | xeon3175x/dogehouse | 42e1ee0d19bc7838de6fffb4503f328619c6954a | [
"MIT"
] | 1 | 2021-02-13T17:42:22.000Z | 2021-02-13T17:42:22.000Z | kousa/lib/data-layer/user_data.ex | xeon3175x/dogehouse | 42e1ee0d19bc7838de6fffb4503f328619c6954a | [
"MIT"
] | null | null | null | kousa/lib/data-layer/user_data.ex | xeon3175x/dogehouse | 42e1ee0d19bc7838de6fffb4503f328619c6954a | [
"MIT"
] | null | null | null | defmodule Kousa.Data.User do
import Ecto.Query, warn: false
alias Beef.{Repo, User}
@fetch_limit 16
def search(query, offset) do
query_with_percent = "%" <> query <> "%"
items =
from(u in Beef.User,
where:
ilike(u.username, ^query_with_percent) or
ilike(u.displayName, ^query_with_percent),
left_join: cr in Beef.Room,
on: u.currentRoomId == cr.id and cr.isPrivate == false,
select: %{u | currentRoom: cr},
limit: @fetch_limit,
offset: ^offset
)
|> Beef.Repo.all()
{Enum.slice(items, 0, -1 + @fetch_limit),
if(length(items) == @fetch_limit, do: -1 + offset + @fetch_limit, else: nil)}
end
def bulk_insert(users) do
Beef.Repo.insert_all(
Beef.User,
users,
on_conflict: :nothing
)
end
def find_by_github_ids(ids) do
from(u in Beef.User, where: u.githubId in ^ids, select: u.id)
|> Beef.Repo.all()
end
def inc_num_following(user_id, n) do
from(u in User,
where: u.id == ^user_id,
update: [
inc: [
numFollowing: ^n
]
]
)
|> Repo.update_all([])
end
def change_mod(user_id_to_change, modForRoomId) do
from(u in User,
where: u.id == ^user_id_to_change,
update: [
set: [
modForRoomId: ^modForRoomId
]
]
)
|> Repo.update_all([])
end
def get_users_in_current_room(user_id) do
user = get_by_id(user_id)
if not is_nil(user.currentRoomId) do
{user.currentRoomId,
from(u in Beef.User,
where: u.currentRoomId == ^user.currentRoomId
)
|> Beef.Repo.all()}
else
{nil, []}
end
end
def get_by_id(user_id) do
Beef.Repo.get(Beef.User, user_id)
end
def get_by_username(username) do
from(u in Beef.User,
where: u.username == ^username,
limit: 1
)
|> Beef.Repo.one()
end
def set_reason_for_ban(user_id, reason_for_ban) do
from(u in User,
where: u.id == ^user_id,
update: [
set: [
reasonForBan: ^reason_for_ban
]
]
)
|> Repo.update_all([])
end
@spec get_by_id_with_current_room(any) :: any
def get_by_id_with_current_room(user_id) do
from(u in Beef.User,
left_join: a0 in assoc(u, :currentRoom),
where: u.id == ^user_id,
limit: 1,
preload: [
currentRoom: a0
]
)
|> Beef.Repo.one()
end
def set_online(user_id) do
from(u in User,
where: u.id == ^user_id,
update: [
set: [
online: true
]
]
)
|> Repo.update_all([])
end
def set_speaker(user_id, room_id) do
from(u in User,
where: u.id == ^user_id and u.currentRoomId == ^room_id,
update: [
set: [
canSpeakForRoomId: ^room_id
]
]
)
|> Repo.update_all([])
end
def set_user_left_current_room(user_id) do
Kousa.RegUtils.lookup_and_cast(Kousa.Gen.UserSession, user_id, {:set_current_room_id, nil})
from(u in User,
where: u.id == ^user_id,
update: [
set: [
currentRoomId: nil,
modForRoomId: nil,
canSpeakForRoomId: nil
]
]
)
|> Repo.update_all([])
end
def set_offline(user_id) do
from(u in User,
where: u.id == ^user_id,
update: [
set: [
online: false,
lastOnline: fragment("now()")
]
]
# select: u
)
|> Repo.update_all([])
end
def get_current_room_id(user_id) do
case Kousa.RegUtils.lookup_and_call(
Kousa.Gen.UserSession,
user_id,
{:get_current_room_id}
) do
{:ok, id} ->
id
_ ->
nil
end
end
def set_current_room(user_id, room_id, can_speak \\ false, returning \\ false) do
canSpeakForRoomId = if can_speak, do: room_id, else: nil
Kousa.RegUtils.lookup_and_cast(
Kousa.Gen.UserSession,
user_id,
{:set_current_room_id, room_id}
)
q =
from(u in Beef.User,
where: u.id == ^user_id,
update: [
set: [
currentRoomId: ^room_id,
canSpeakForRoomId: ^canSpeakForRoomId
]
]
)
q = if returning, do: select(q, [u], u), else: q
q
|> Beef.Repo.update_all([])
end
def find_or_create(user, github_access_token) do
githubId = Integer.to_string(user["id"])
db_user =
from(u in Beef.User,
where: u.githubId == ^githubId
)
|> Repo.one()
cond do
db_user ->
if is_nil(db_user.email) do
email = Kousa.Github.get_email(github_access_token)
from(u in Beef.User,
where: u.githubId == ^githubId,
update: [
set: [
hasLoggedIn: true,
email: ^email,
githubAccessToken: ^github_access_token
]
]
)
|> Repo.update_all([])
end
{:find, db_user}
true ->
{:create,
Repo.insert!(
%User{
username: user["login"],
githubId: githubId,
email: user["email"],
githubAccessToken: github_access_token,
avatarUrl: user["avatar_url"],
displayName:
if(is_nil(user["name"]) or String.trim(user["name"]) == "",
do: user["login"],
else: user["name"]
),
bio: user["bio"],
hasLoggedIn: true
},
returning: true
)}
end
end
end
| 21.776923 | 95 | 0.529142 |
0861396b8b2b4487e21bdbacbfbff045aa85eacc | 51,824 | exs | Elixir | backend/deps/ecto/integration_test/cases/repo.exs | hploscar/palike | 71618593ee6e6687e0d1cdc9e923ed8f9c2cc2cb | [
"MIT"
] | null | null | null | backend/deps/ecto/integration_test/cases/repo.exs | hploscar/palike | 71618593ee6e6687e0d1cdc9e923ed8f9c2cc2cb | [
"MIT"
] | null | null | null | backend/deps/ecto/integration_test/cases/repo.exs | hploscar/palike | 71618593ee6e6687e0d1cdc9e923ed8f9c2cc2cb | [
"MIT"
] | null | null | null | Code.require_file "../support/types.exs", __DIR__
defmodule Ecto.Integration.RepoTest do
use Ecto.Integration.Case, async: Application.get_env(:ecto, :async_integration_tests, true)
alias Ecto.Integration.TestRepo
import Ecto.Query
alias Ecto.Integration.Post
alias Ecto.Integration.User
alias Ecto.Integration.Comment
alias Ecto.Integration.Permalink
alias Ecto.Integration.Custom
alias Ecto.Integration.Barebone
alias Ecto.Integration.CompositePk
alias Ecto.Integration.PostUsecTimestamps
alias Ecto.Integration.PostUserCompositePk
test "returns already started for started repos" do
assert {:error, {:already_started, _}} = TestRepo.start_link
end
test "fetch empty" do
assert [] == TestRepo.all(Post)
assert [] == TestRepo.all(from p in Post)
end
test "fetch with in" do
TestRepo.insert!(%Post{title: "hello"})
assert [] = TestRepo.all from p in Post, where: p.title in []
assert [] = TestRepo.all from p in Post, where: p.title in ["1", "2", "3"]
assert [] = TestRepo.all from p in Post, where: p.title in ^[]
assert [_] = TestRepo.all from p in Post, where: not p.title in []
assert [_] = TestRepo.all from p in Post, where: p.title in ["1", "hello", "3"]
assert [_] = TestRepo.all from p in Post, where: p.title in ["1", ^"hello", "3"]
assert [_] = TestRepo.all from p in Post, where: p.title in ^["1", "hello", "3"]
end
test "fetch without schema" do
%Post{} = TestRepo.insert!(%Post{title: "title1"})
%Post{} = TestRepo.insert!(%Post{title: "title2"})
assert ["title1", "title2"] =
TestRepo.all(from(p in "posts", order_by: p.title, select: p.title))
assert [_] =
TestRepo.all(from(p in "posts", where: p.title == "title1", select: p.id))
end
@tag :invalid_prefix
test "fetch with invalid prefix" do
assert catch_error(TestRepo.all("posts", prefix: "oops"))
end
test "insert, update and delete" do
post = %Post{title: "insert, update, delete", text: "fetch empty"}
meta = post.__meta__
deleted_meta = put_in meta.state, :deleted
assert %Post{} = to_be_deleted = TestRepo.insert!(post)
assert %Post{__meta__: ^deleted_meta} = TestRepo.delete!(to_be_deleted)
loaded_meta = put_in meta.state, :loaded
assert %Post{__meta__: ^loaded_meta} = TestRepo.insert!(post)
post = TestRepo.one(Post)
assert post.__meta__.state == :loaded
assert post.inserted_at
end
@tag :composite_pk
test "insert, update and delete with composite pk" do
c1 = TestRepo.insert!(%CompositePk{a: 1, b: 2, name: "first"})
c2 = TestRepo.insert!(%CompositePk{a: 1, b: 3, name: "second"})
assert CompositePk |> first |> TestRepo.one == c1
assert CompositePk |> last |> TestRepo.one == c2
changeset = Ecto.Changeset.cast(c1, %{name: "first change"}, ~w(name))
c1 = TestRepo.update!(changeset)
assert TestRepo.get_by!(CompositePk, %{a: 1, b: 2}) == c1
TestRepo.delete!(c2)
assert TestRepo.all(CompositePk) == [c1]
assert_raise ArgumentError, ~r"to have exactly one primary key", fn ->
TestRepo.get(CompositePk, [])
end
assert_raise ArgumentError, ~r"to have exactly one primary key", fn ->
TestRepo.get!(CompositePk, [1, 2])
end
end
@tag :composite_pk
test "insert, update and delete with associated composite pk" do
user = TestRepo.insert!(%User{})
post = TestRepo.insert!(%Post{title: "post title", text: "post text"})
user_post = TestRepo.insert!(%PostUserCompositePk{user_id: user.id, post_id: post.id})
assert TestRepo.get_by!(PostUserCompositePk, [user_id: user.id, post_id: post.id]) == user_post
TestRepo.delete!(user_post)
assert TestRepo.all(PostUserCompositePk) == []
end
@tag :invalid_prefix
test "insert, update and delete with invalid prefix" do
post = TestRepo.insert!(%Post{})
changeset = Ecto.Changeset.change(post, title: "foo")
assert catch_error(TestRepo.insert(%Post{}, prefix: "oops"))
assert catch_error(TestRepo.update(changeset, prefix: "oops"))
assert catch_error(TestRepo.delete(changeset, prefix: "oops"))
end
test "insert and update with changeset" do
# On insert we merge the fields and changes
changeset = Ecto.Changeset.cast(%Post{text: "x", title: "wrong"},
%{"title" => "hello", "temp" => "unknown"}, ~w(title temp))
post = TestRepo.insert!(changeset)
assert %Post{text: "x", title: "hello", temp: "unknown"} = post
assert %Post{text: "x", title: "hello", temp: "temp"} = TestRepo.get!(Post, post.id)
# On update we merge only fields, direct schema changes are discarded
changeset = Ecto.Changeset.cast(%{post | text: "y"},
%{"title" => "world", "temp" => "unknown"}, ~w(title temp))
assert %Post{text: "y", title: "world", temp: "unknown"} = TestRepo.update!(changeset)
assert %Post{text: "x", title: "world", temp: "temp"} = TestRepo.get!(Post, post.id)
end
test "insert and update with empty changeset" do
# On insert we merge the fields and changes
changeset = Ecto.Changeset.cast(%Permalink{}, %{}, ~w())
assert %Permalink{} = permalink = TestRepo.insert!(changeset)
# Assert we can update the same value twice,
# without changes, without triggering stale errors.
changeset = Ecto.Changeset.cast(permalink, %{}, ~w())
assert TestRepo.update!(changeset) == permalink
assert TestRepo.update!(changeset) == permalink
end
test "insert with no primary key" do
assert %Barebone{num: nil} = TestRepo.insert!(%Barebone{})
assert %Barebone{num: 13} = TestRepo.insert!(%Barebone{num: 13})
end
@tag :read_after_writes
test "insert and update with changeset read after writes" do
defmodule RAW do
use Ecto.Schema
schema "comments" do
field :text, :string
field :lock_version, :integer, read_after_writes: true
end
end
changeset = Ecto.Changeset.cast(struct(RAW, %{}), %{}, ~w())
# If the field is nil, we will not send it
# and read the value back from the database.
assert %{id: cid, lock_version: 1} = raw = TestRepo.insert!(changeset)
# Set the counter to 11, so we can read it soon
TestRepo.update_all from(u in RAW, where: u.id == ^cid), set: [lock_version: 11]
# We will read back on update too
changeset = Ecto.Changeset.cast(raw, %{"text" => "0"}, ~w(text))
assert %{id: ^cid, lock_version: 11, text: "0"} = TestRepo.update!(changeset)
end
test "insert autogenerates for custom type" do
post = TestRepo.insert!(%Post{uuid: nil})
assert byte_size(post.uuid) == 36
assert TestRepo.get_by(Post, uuid: post.uuid) == post
end
@tag :id_type
test "insert autogenerates for custom id type" do
defmodule ID do
use Ecto.Schema
@primary_key {:id, Elixir.Custom.Permalink, autogenerate: true}
schema "posts" do
end
end
id = TestRepo.insert!(struct(ID, id: nil))
assert id.id
assert TestRepo.get_by(ID, id: "#{id.id}-hello") == id
end
@tag :id_type
@tag :assigns_id_type
test "insert with user-assigned primary key" do
assert %Post{id: 1} = TestRepo.insert!(%Post{id: 1})
end
@tag :id_type
@tag :assigns_id_type
test "insert and update with user-assigned primary key in changeset" do
changeset = Ecto.Changeset.cast(%Post{id: 11}, %{"id" => "13"}, ~w(id))
assert %Post{id: 13} = post = TestRepo.insert!(changeset)
changeset = Ecto.Changeset.cast(post, %{"id" => "15"}, ~w(id))
assert %Post{id: 15} = TestRepo.update!(changeset)
end
@tag :uses_usec
test "insert and fetch a schema with timestamps with usec" do
p1 = TestRepo.insert!(%PostUsecTimestamps{title: "hello"})
assert [p1] == TestRepo.all(PostUsecTimestamps)
end
test "insert and fetch a schema with utc timestamps" do
datetime = System.system_time(:seconds) * 1_000_000 |> DateTime.from_unix!(:microseconds)
TestRepo.insert!(%User{inserted_at: datetime})
assert [%{inserted_at: ^datetime}] = TestRepo.all(User)
end
test "optimistic locking in update/delete operations" do
import Ecto.Changeset, only: [cast: 3, optimistic_lock: 2]
base_post = TestRepo.insert!(%Comment{})
cs_ok =
base_post
|> cast(%{"text" => "foo.bar"}, ~w(text))
|> optimistic_lock(:lock_version)
TestRepo.update!(cs_ok)
cs_stale = optimistic_lock(base_post, :lock_version)
assert_raise Ecto.StaleEntryError, fn -> TestRepo.update!(cs_stale) end
assert_raise Ecto.StaleEntryError, fn -> TestRepo.delete!(cs_stale) end
end
@tag :unique_constraint
test "unique constraint" do
changeset = Ecto.Changeset.change(%Post{}, uuid: Ecto.UUID.generate())
{:ok, _} = TestRepo.insert(changeset)
exception =
assert_raise Ecto.ConstraintError, ~r/constraint error when attempting to insert struct/, fn ->
changeset
|> TestRepo.insert()
end
assert exception.message =~ "unique: posts_uuid_index"
assert exception.message =~ "The changeset has not defined any constraint."
message = ~r/constraint error when attempting to insert struct/
exception =
assert_raise Ecto.ConstraintError, message, fn ->
changeset
|> Ecto.Changeset.unique_constraint(:uuid, name: :posts_email_changeset)
|> TestRepo.insert()
end
assert exception.message =~ "unique: posts_email_changeset"
{:error, changeset} =
changeset
|> Ecto.Changeset.unique_constraint(:uuid)
|> TestRepo.insert()
assert changeset.errors == [uuid: {"has already been taken", []}]
assert changeset.data.__meta__.state == :built
end
@tag :unique_constraint
test "unique constraint from association" do
uuid = Ecto.UUID.generate()
post = & %Post{} |> Ecto.Changeset.change(uuid: &1) |> Ecto.Changeset.unique_constraint(:uuid)
{:error, changeset} =
TestRepo.insert %User{
comments: [%Comment{}],
permalink: %Permalink{},
posts: [post.(uuid), post.(uuid), post.(Ecto.UUID.generate)]
}
[_, p2, _] = changeset.changes.posts
assert p2.errors == [uuid: {"has already been taken", []}]
end
@tag :id_type
@tag :unique_constraint
test "unique constraint with binary_id" do
changeset = Ecto.Changeset.change(%Custom{}, uuid: Ecto.UUID.generate())
{:ok, _} = TestRepo.insert(changeset)
{:error, changeset} =
changeset
|> Ecto.Changeset.unique_constraint(:uuid)
|> TestRepo.insert()
assert changeset.errors == [uuid: {"has already been taken", []}]
assert changeset.data.__meta__.state == :built
end
test "unique pseudo-constraint violation error message with join table at the repository" do
post =
TestRepo.insert!(%Post{title: "some post"})
|> TestRepo.preload(:unique_users)
user =
TestRepo.insert!(%User{name: "some user"})
# Violate the unique composite index
{:error, changeset} =
post
|> Ecto.Changeset.change
|> Ecto.Changeset.put_assoc(:unique_users, [user, user])
|> TestRepo.update
errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
assert errors == %{unique_users: [%{}, %{id: ["has already been taken"]}]}
refute changeset.valid?
end
@tag :join
@tag :unique_constraint
test "unique constraint violation error message with join table in single changeset" do
post =
TestRepo.insert!(%Post{title: "some post"})
|> TestRepo.preload(:constraint_users)
user =
TestRepo.insert!(%User{name: "some user"})
# Violate the unique composite index
{:error, changeset} =
post
|> Ecto.Changeset.change
|> Ecto.Changeset.put_assoc(:constraint_users, [user, user])
|> Ecto.Changeset.unique_constraint(:user,
name: :posts_users_composite_pk_post_id_user_id_index,
message: "has already been assigned")
|> TestRepo.update
errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
assert errors == %{constraint_users: [%{}, %{user: ["has already been assigned"]}]}
refute changeset.valid?
end
@tag :join
@tag :unique_constraint
test "unique constraint violation error message with join table and separate changesets" do
post =
TestRepo.insert!(%Post{title: "some post"})
|> TestRepo.preload(:constraint_users)
user = TestRepo.insert!(%User{name: "some user"})
post
|> Ecto.Changeset.change
|> Ecto.Changeset.put_assoc(:constraint_users, [user])
|> TestRepo.update
# Violate the unique composite index
{:error, changeset} =
post
|> Ecto.Changeset.change
|> Ecto.Changeset.put_assoc(:constraint_users, [user])
|> Ecto.Changeset.unique_constraint(:user,
name: :posts_users_composite_pk_post_id_user_id_index,
message: "has already been assigned")
|> TestRepo.update
errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
assert errors == %{constraint_users: [%{user: ["has already been assigned"]}]}
refute changeset.valid?
end
@tag :foreign_key_constraint
test "foreign key constraint" do
changeset = Ecto.Changeset.change(%Comment{post_id: 0})
exception =
assert_raise Ecto.ConstraintError, ~r/constraint error when attempting to insert struct/, fn ->
changeset
|> TestRepo.insert()
end
assert exception.message =~ "foreign_key: comments_post_id_fkey"
assert exception.message =~ "The changeset has not defined any constraint."
message = ~r/constraint error when attempting to insert struct/
exception =
assert_raise Ecto.ConstraintError, message, fn ->
changeset
|> Ecto.Changeset.foreign_key_constraint(:post_id, name: :comments_post_id_other)
|> TestRepo.insert()
end
assert exception.message =~ "foreign_key: comments_post_id_other"
{:error, changeset} =
changeset
|> Ecto.Changeset.foreign_key_constraint(:post_id)
|> TestRepo.insert()
assert changeset.errors == [post_id: {"does not exist", []}]
end
@tag :foreign_key_constraint
test "assoc constraint" do
changeset = Ecto.Changeset.change(%Comment{post_id: 0})
exception =
assert_raise Ecto.ConstraintError, ~r/constraint error when attempting to insert struct/, fn ->
changeset
|> TestRepo.insert()
end
assert exception.message =~ "foreign_key: comments_post_id_fkey"
assert exception.message =~ "The changeset has not defined any constraint."
message = ~r/constraint error when attempting to insert struct/
exception =
assert_raise Ecto.ConstraintError, message, fn ->
changeset
|> Ecto.Changeset.assoc_constraint(:post, name: :comments_post_id_other)
|> TestRepo.insert()
end
assert exception.message =~ "foreign_key: comments_post_id_other"
{:error, changeset} =
changeset
|> Ecto.Changeset.assoc_constraint(:post)
|> TestRepo.insert()
assert changeset.errors == [post: {"does not exist", []}]
end
@tag :foreign_key_constraint
test "no assoc constraint error" do
user = TestRepo.insert!(%User{})
TestRepo.insert!(%Permalink{user_id: user.id})
exception =
assert_raise Ecto.ConstraintError, ~r/constraint error when attempting to delete struct/, fn ->
TestRepo.delete!(user)
end
assert exception.message =~ "foreign_key: permalinks_user_id_fkey"
assert exception.message =~ "The changeset has not defined any constraint."
end
@tag :foreign_key_constraint
test "no assoc constraint with changeset mismatch" do
user = TestRepo.insert!(%User{})
TestRepo.insert!(%Permalink{user_id: user.id})
message = ~r/constraint error when attempting to delete struct/
exception =
assert_raise Ecto.ConstraintError, message, fn ->
user
|> Ecto.Changeset.change
|> Ecto.Changeset.no_assoc_constraint(:permalink, name: :permalinks_user_id_pther)
|> TestRepo.delete()
end
assert exception.message =~ "foreign_key: permalinks_user_id_pther"
end
@tag :foreign_key_constraint
test "no assoc constraint with changeset match" do
user = TestRepo.insert!(%User{})
TestRepo.insert!(%Permalink{user_id: user.id})
{:error, changeset} =
user
|> Ecto.Changeset.change
|> Ecto.Changeset.no_assoc_constraint(:permalink)
|> TestRepo.delete()
assert changeset.errors == [permalink: {"is still associated with this entry", []}]
end
test "insert and update with failing child foreign key" do
defmodule Order do
use Ecto.Integration.Schema
import Ecto.Changeset
schema "orders" do
embeds_one :item, Ecto.Integration.Item
belongs_to :comment, Ecto.Integration.Comment
end
def changeset(order, params) do
order
|> cast(params, [:comment_id])
|> cast_embed(:item, with: &item_changeset/2)
|> cast_assoc(:comment, with: &comment_changeset/2)
end
def item_changeset(item, params) do
item
|> cast(params, [:price])
end
def comment_changeset(comment, params) do
comment
|> cast(params, [:post_id, :text])
|> cast_assoc(:post)
|> assoc_constraint(:post)
end
end
changeset = Order.changeset(struct(Order, %{}), %{item: %{price: 10}, comment: %{text: "1", post_id: 0}})
assert %Ecto.Changeset{} = changeset.changes.item
{:error, changeset} = TestRepo.insert(changeset)
assert %Ecto.Changeset{} = changeset.changes.item
order = TestRepo.insert!(Order.changeset(struct(Order, %{}), %{}))
|> TestRepo.preload([:comment])
changeset = Order.changeset(order, %{item: %{price: 10}, comment: %{text: "1", post_id: 0}})
assert %Ecto.Changeset{} = changeset.changes.item
{:error, changeset} = TestRepo.update(changeset)
assert %Ecto.Changeset{} = changeset.changes.item
end
test "get(!)" do
post1 = TestRepo.insert!(%Post{title: "1", text: "hai"})
post2 = TestRepo.insert!(%Post{title: "2", text: "hai"})
assert post1 == TestRepo.get(Post, post1.id)
assert post2 == TestRepo.get(Post, to_string post2.id) # With casting
assert post1 == TestRepo.get!(Post, post1.id)
assert post2 == TestRepo.get!(Post, to_string post2.id) # With casting
TestRepo.delete!(post1)
assert nil == TestRepo.get(Post, post1.id)
assert_raise Ecto.NoResultsError, fn ->
TestRepo.get!(Post, post1.id)
end
end
test "get(!) with custom source" do
custom = Ecto.put_meta(%Custom{}, source: "posts")
custom = TestRepo.insert!(custom)
bid = custom.bid
assert %Custom{bid: ^bid, __meta__: %{source: {nil, "posts"}}} =
TestRepo.get(from(c in {"posts", Custom}), bid)
end
test "get(!) with binary_id" do
custom = TestRepo.insert!(%Custom{})
bid = custom.bid
assert %Custom{bid: ^bid} = TestRepo.get(Custom, bid)
end
test "get_by(!)" do
post1 = TestRepo.insert!(%Post{title: "1", text: "hai"})
post2 = TestRepo.insert!(%Post{title: "2", text: "hello"})
assert post1 == TestRepo.get_by(Post, id: post1.id)
assert post1 == TestRepo.get_by(Post, text: post1.text)
assert post1 == TestRepo.get_by(Post, id: post1.id, text: post1.text)
assert post2 == TestRepo.get_by(Post, id: to_string(post2.id)) # With casting
assert nil == TestRepo.get_by(Post, text: "hey")
assert nil == TestRepo.get_by(Post, id: post2.id, text: "hey")
assert post1 == TestRepo.get_by!(Post, id: post1.id)
assert post1 == TestRepo.get_by!(Post, text: post1.text)
assert post1 == TestRepo.get_by!(Post, id: post1.id, text: post1.text)
assert post2 == TestRepo.get_by!(Post, id: to_string(post2.id)) # With casting
assert post1 == TestRepo.get_by!(Post, %{id: post1.id})
assert_raise Ecto.NoResultsError, fn ->
TestRepo.get_by!(Post, id: post2.id, text: "hey")
end
end
test "first, last and one(!)" do
post1 = TestRepo.insert!(%Post{title: "1", text: "hai"})
post2 = TestRepo.insert!(%Post{title: "2", text: "hai"})
assert post1 == Post |> first |> TestRepo.one
assert post2 == Post |> last |> TestRepo.one
query = from p in Post, order_by: p.title
assert post1 == query |> first |> TestRepo.one
assert post2 == query |> last |> TestRepo.one
query = from p in Post, order_by: [desc: p.title], limit: 10
assert post2 == query |> first |> TestRepo.one
assert post1 == query |> last |> TestRepo.one
query = from p in Post, where: is_nil(p.id)
refute query |> first |> TestRepo.one
refute query |> first |> TestRepo.one
assert_raise Ecto.NoResultsError, fn -> query |> first |> TestRepo.one! end
assert_raise Ecto.NoResultsError, fn -> query |> last |> TestRepo.one! end
end
test "aggregate" do
assert TestRepo.aggregate(Post, :max, :visits) == nil
TestRepo.insert!(%Post{visits: 10})
TestRepo.insert!(%Post{visits: 12})
TestRepo.insert!(%Post{visits: 14})
TestRepo.insert!(%Post{visits: 14})
# Barebones
assert TestRepo.aggregate(Post, :max, :visits) == 14
assert TestRepo.aggregate(Post, :min, :visits) == 10
assert TestRepo.aggregate(Post, :count, :visits) == 4
assert "50" = to_string(TestRepo.aggregate(Post, :sum, :visits))
assert "12.5" <> _ = to_string(TestRepo.aggregate(Post, :avg, :visits))
# With order_by
query = from Post, order_by: [asc: :visits]
assert TestRepo.aggregate(query, :max, :visits) == 14
# With order_by and limit
query = from Post, order_by: [asc: :visits], limit: 2
assert TestRepo.aggregate(query, :max, :visits) == 12
# With distinct
query = from Post, order_by: [asc: :visits], distinct: true
assert TestRepo.aggregate(query, :count, :visits) == 3
end
test "insert all" do
assert {2, nil} = TestRepo.insert_all("comments", [[text: "1"], %{text: "2", lock_version: 2}])
assert {2, nil} = TestRepo.insert_all({"comments", Comment}, [[text: "3"], %{text: "4", lock_version: 2}])
assert [%Comment{text: "1", lock_version: 1},
%Comment{text: "2", lock_version: 2},
%Comment{text: "3", lock_version: 1},
%Comment{text: "4", lock_version: 2}] = TestRepo.all(Comment)
assert {2, nil} = TestRepo.insert_all(Post, [[], []])
assert [%Post{}, %Post{}] = TestRepo.all(Post)
assert {0, nil} = TestRepo.insert_all("posts", [])
assert {0, nil} = TestRepo.insert_all({"posts", Post}, [])
end
@tag :invalid_prefix
test "insert all with invalid prefix" do
assert catch_error(TestRepo.insert_all(Post, [[], []], prefix: "oops"))
end
@tag :returning
test "insert all with returning with schema" do
assert {0, []} = TestRepo.insert_all(Comment, [], returning: true)
assert {0, nil} = TestRepo.insert_all(Comment, [], returning: false)
{2, [c1, c2]} = TestRepo.insert_all(Comment, [[text: "1"], [text: "2"]], returning: [:id, :text])
assert %Comment{text: "1", __meta__: %{state: :loaded}} = c1
assert %Comment{text: "2", __meta__: %{state: :loaded}} = c2
{2, [c1, c2]} = TestRepo.insert_all(Comment, [[text: "3"], [text: "4"]], returning: true)
assert %Comment{text: "3", __meta__: %{state: :loaded}} = c1
assert %Comment{text: "4", __meta__: %{state: :loaded}} = c2
end
@tag :returning
test "insert all with returning without schema" do
{2, [c1, c2]} = TestRepo.insert_all("comments", [[text: "1"], [text: "2"]], returning: [:id, :text])
assert %{id: _, text: "1"} = c1
assert %{id: _, text: "2"} = c2
assert_raise ArgumentError, fn ->
TestRepo.insert_all("comments", [[text: "1"], [text: "2"]], returning: true)
end
end
test "insert all with dumping" do
datetime = ~N[2014-01-16 20:26:51.000000]
assert {2, nil} = TestRepo.insert_all(Post, [%{inserted_at: datetime}, %{title: "date"}])
assert [%Post{inserted_at: ^datetime, title: nil},
%Post{inserted_at: nil, title: "date"}] = TestRepo.all(Post)
end
test "insert all autogenerates for binary_id type" do
custom = TestRepo.insert!(%Custom{bid: nil})
assert custom.bid
assert TestRepo.get(Custom, custom.bid)
assert TestRepo.delete!(custom)
refute TestRepo.get(Custom, custom.bid)
uuid = Ecto.UUID.generate
assert {2, nil} = TestRepo.insert_all(Custom, [%{uuid: uuid}, %{bid: custom.bid}])
assert [%Custom{bid: bid2, uuid: nil},
%Custom{bid: bid1, uuid: ^uuid}] = Enum.sort_by(TestRepo.all(Custom), & &1.uuid)
assert bid1 && bid2
assert custom.bid != bid1
assert custom.bid == bid2
end
test "update all" do
assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"})
assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"})
assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"})
assert {3, nil} = TestRepo.update_all(Post, set: [title: "x"])
assert %Post{title: "x"} = TestRepo.get(Post, id1)
assert %Post{title: "x"} = TestRepo.get(Post, id2)
assert %Post{title: "x"} = TestRepo.get(Post, id3)
assert {3, nil} = TestRepo.update_all("posts", [set: [title: nil]], returning: false)
assert %Post{title: nil} = TestRepo.get(Post, id1)
assert %Post{title: nil} = TestRepo.get(Post, id2)
assert %Post{title: nil} = TestRepo.get(Post, id3)
end
@tag :invalid_prefix
test "update all with invalid prefix" do
assert catch_error(TestRepo.update_all(Post, [set: [title: "x"]], prefix: "oops"))
end
@tag :returning
test "update all with returning with schema" do
assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"})
assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"})
assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"})
assert {3, posts} = TestRepo.update_all(Post, [set: [title: "x"]], returning: true)
[p1, p2, p3] = Enum.sort_by(posts, & &1.id)
assert %Post{id: ^id1, title: "x"} = p1
assert %Post{id: ^id2, title: "x"} = p2
assert %Post{id: ^id3, title: "x"} = p3
assert {3, posts} = TestRepo.update_all(Post, [set: [visits: 11]], returning: [:id, :visits])
[p1, p2, p3] = Enum.sort_by(posts, & &1.id)
assert %Post{id: ^id1, title: nil, visits: 11} = p1
assert %Post{id: ^id2, title: nil, visits: 11} = p2
assert %Post{id: ^id3, title: nil, visits: 11} = p3
end
@tag :returning
test "update all with returning without schema" do
assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"})
assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"})
assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"})
assert {3, posts} = TestRepo.update_all("posts", [set: [title: "x"]], returning: [:id, :title])
[p1, p2, p3] = Enum.sort_by(posts, & &1.id)
assert p1 == %{id: id1, title: "x"}
assert p2 == %{id: id2, title: "x"}
assert p3 == %{id: id3, title: "x"}
end
test "update all with filter" do
assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"})
assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"})
assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"})
query = from(p in Post, where: p.title == "1" or p.title == "2",
update: [set: [text: ^"y"]])
assert {2, nil} = TestRepo.update_all(query, set: [title: "x"])
assert %Post{title: "x", text: "y"} = TestRepo.get(Post, id1)
assert %Post{title: "x", text: "y"} = TestRepo.get(Post, id2)
assert %Post{title: "3", text: nil} = TestRepo.get(Post, id3)
end
test "update all no entries" do
assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1"})
assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2"})
assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3"})
query = from(p in Post, where: p.title == "4")
assert {0, nil} = TestRepo.update_all(query, set: [title: "x"])
assert %Post{title: "1"} = TestRepo.get(Post, id1)
assert %Post{title: "2"} = TestRepo.get(Post, id2)
assert %Post{title: "3"} = TestRepo.get(Post, id3)
end
test "update all increment syntax" do
assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1", visits: 0})
assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2", visits: 1})
# Positive
query = from p in Post, where: not is_nil(p.id), update: [inc: [visits: 2]]
assert {2, nil} = TestRepo.update_all(query, [])
assert %Post{visits: 2} = TestRepo.get(Post, id1)
assert %Post{visits: 3} = TestRepo.get(Post, id2)
# Negative
query = from p in Post, where: not is_nil(p.id), update: [inc: [visits: -1]]
assert {2, nil} = TestRepo.update_all(query, [])
assert %Post{visits: 1} = TestRepo.get(Post, id1)
assert %Post{visits: 2} = TestRepo.get(Post, id2)
end
@tag :id_type
test "update all with casting and dumping on id type field" do
assert %Post{id: id1} = TestRepo.insert!(%Post{})
assert {1, nil} = TestRepo.update_all(Post, set: [counter: to_string(id1)])
assert %Post{counter: ^id1} = TestRepo.get(Post, id1)
end
test "update all with casting and dumping" do
text = "hai"
datetime = ~N[2014-01-16 20:26:51.000000]
assert %Post{id: id} = TestRepo.insert!(%Post{})
assert {1, nil} = TestRepo.update_all(Post, set: [text: text, inserted_at: datetime])
assert %Post{text: "hai", inserted_at: ^datetime} = TestRepo.get(Post, id)
end
test "delete all" do
assert %Post{} = TestRepo.insert!(%Post{title: "1", text: "hai"})
assert %Post{} = TestRepo.insert!(%Post{title: "2", text: "hai"})
assert %Post{} = TestRepo.insert!(%Post{title: "3", text: "hai"})
assert {3, nil} = TestRepo.delete_all(Post, returning: false)
assert [] = TestRepo.all(Post)
end
@tag :invalid_prefix
test "delete all with invalid prefix" do
assert catch_error(TestRepo.delete_all(Post, prefix: "oops"))
end
@tag :returning
test "delete all with returning with schema" do
assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1", text: "hai"})
assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2", text: "hai"})
assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3", text: "hai"})
assert {3, posts} = TestRepo.delete_all(Post, returning: true)
[p1, p2, p3] = Enum.sort_by(posts, & &1.id)
assert %Post{id: ^id1, title: "1"} = p1
assert %Post{id: ^id2, title: "2"} = p2
assert %Post{id: ^id3, title: "3"} = p3
end
@tag :returning
test "delete all with returning without schema" do
assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1", text: "hai"})
assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2", text: "hai"})
assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3", text: "hai"})
assert {3, posts} = TestRepo.delete_all("posts", returning: [:id, :title])
[p1, p2, p3] = Enum.sort_by(posts, & &1.id)
assert p1 == %{id: id1, title: "1"}
assert p2 == %{id: id2, title: "2"}
assert p3 == %{id: id3, title: "3"}
end
test "delete all with filter" do
assert %Post{} = TestRepo.insert!(%Post{title: "1", text: "hai"})
assert %Post{} = TestRepo.insert!(%Post{title: "2", text: "hai"})
assert %Post{} = TestRepo.insert!(%Post{title: "3", text: "hai"})
query = from(p in Post, where: p.title == "1" or p.title == "2")
assert {2, nil} = TestRepo.delete_all(query)
assert [%Post{}] = TestRepo.all(Post)
end
test "delete all no entries" do
assert %Post{id: id1} = TestRepo.insert!(%Post{title: "1", text: "hai"})
assert %Post{id: id2} = TestRepo.insert!(%Post{title: "2", text: "hai"})
assert %Post{id: id3} = TestRepo.insert!(%Post{title: "3", text: "hai"})
query = from(p in Post, where: p.title == "4")
assert {0, nil} = TestRepo.delete_all(query)
assert %Post{title: "1"} = TestRepo.get(Post, id1)
assert %Post{title: "2"} = TestRepo.get(Post, id2)
assert %Post{title: "3"} = TestRepo.get(Post, id3)
end
test "virtual field" do
assert %Post{id: id} = TestRepo.insert!(%Post{title: "1", text: "hai"})
assert TestRepo.get(Post, id).temp == "temp"
end
## Query syntax
test "query select expressions" do
%Post{} = TestRepo.insert!(%Post{title: "1", text: "hai"})
assert [{"1", "hai"}] ==
TestRepo.all(from p in Post, select: {p.title, p.text})
assert [["1", "hai"]] ==
TestRepo.all(from p in Post, select: [p.title, p.text])
assert [%{:title => "1", 3 => "hai", "text" => "hai"}] ==
TestRepo.all(from p in Post, select: %{
:title => p.title,
"text" => p.text,
3 => p.text
})
assert [%{:title => "1", "1" => "hai", "text" => "hai"}] ==
TestRepo.all(from p in Post, select: %{
:title => p.title,
p.title => p.text,
"text" => p.text
})
end
test "query select map update" do
%Post{} = TestRepo.insert!(%Post{title: "1", text: "hai"})
assert [%Post{:title => "new title", text: "hai"}] =
TestRepo.all(from p in Post, select: %{p | title: "new title"})
assert_raise KeyError, fn ->
TestRepo.all(from p in Post, select: %{p | unknown: "new title"})
end
assert_raise BadMapError, fn ->
TestRepo.all(from p in Post, select: %{p.title | title: "new title"})
end
end
test "query select take with structs" do
%{id: pid1} = TestRepo.insert!(%Post{title: "1"})
%{id: pid2} = TestRepo.insert!(%Post{title: "2"})
%{id: pid3} = TestRepo.insert!(%Post{title: "3"})
[p1, p2, p3] = Post |> select([p], struct(p, [:title])) |> order_by([:title]) |> TestRepo.all
refute p1.id
assert p1.title == "1"
assert match?(%Post{}, p1)
refute p2.id
assert p2.title == "2"
assert match?(%Post{}, p2)
refute p3.id
assert p3.title == "3"
assert match?(%Post{}, p3)
[p1, p2, p3] = Post |> select([:id]) |> order_by([:id]) |> TestRepo.all
assert %Post{id: ^pid1} = p1
assert %Post{id: ^pid2} = p2
assert %Post{id: ^pid3} = p3
end
test "query select take with maps" do
%{id: pid1} = TestRepo.insert!(%Post{title: "1"})
%{id: pid2} = TestRepo.insert!(%Post{title: "2"})
%{id: pid3} = TestRepo.insert!(%Post{title: "3"})
[p1, p2, p3] = "posts" |> select([p], map(p, [:title])) |> order_by([:title]) |> TestRepo.all
assert p1 == %{title: "1"}
assert p2 == %{title: "2"}
assert p3 == %{title: "3"}
[p1, p2, p3] = "posts" |> select([:id]) |> order_by([:id]) |> TestRepo.all
assert p1 == %{id: pid1}
assert p2 == %{id: pid2}
assert p3 == %{id: pid3}
end
test "query select take with assocs" do
%{id: pid} = TestRepo.insert!(%Post{title: "post"})
TestRepo.insert!(%Comment{post_id: pid, text: "comment"})
fields = [:id, :title, comments: [:text, :post_id]]
[p] = Post |> preload(:comments) |> select([p], ^fields) |> TestRepo.all
assert %Post{title: "post"} = p
assert [%Comment{text: "comment"}] = p.comments
[p] = Post |> preload(:comments) |> select([p], struct(p, ^fields)) |> TestRepo.all
assert %Post{title: "post"} = p
assert [%Comment{text: "comment"}] = p.comments
[p] = Post |> preload(:comments) |> select([p], map(p, ^fields)) |> TestRepo.all
assert p == %{id: pid, title: "post", comments: [%{text: "comment", post_id: pid}]}
end
test "query select take with single nil column" do
%Post{} = TestRepo.insert!(%Post{title: "1", counter: nil})
assert %{counter: nil} =
TestRepo.one(from p in Post, where: p.title == "1", select: [:counter])
end
test "query select take with nil assoc" do
%{id: cid} = TestRepo.insert!(%Comment{text: "comment"})
fields = [:id, :text, post: [:title]]
[c] = Comment |> preload(:post) |> select([c], ^fields) |> TestRepo.all
assert %Comment{id: ^cid, text: "comment", post: nil} = c
[c] = Comment |> preload(:post) |> select([c], struct(c, ^fields)) |> TestRepo.all
assert %Comment{id: ^cid, text: "comment", post: nil} = c
[c] = Comment |> preload(:post) |> select([c], map(c, ^fields)) |> TestRepo.all
assert c == %{id: cid, text: "comment", post: nil}
end
test "query count distinct" do
TestRepo.insert!(%Post{title: "1"})
TestRepo.insert!(%Post{title: "1"})
TestRepo.insert!(%Post{title: "2"})
assert [3] == Post |> select([p], count(p.title)) |> TestRepo.all
assert [2] == Post |> select([p], count(p.title, :distinct)) |> TestRepo.all
end
test "query where interpolation" do
post1 = TestRepo.insert!(%Post{text: "x", title: "hello"})
post2 = TestRepo.insert!(%Post{text: "y", title: "goodbye"})
assert [post1, post2] == Post |> where([], []) |> TestRepo.all |> Enum.sort_by(& &1.id)
assert [post1] == Post |> where([], [title: "hello"]) |> TestRepo.all
assert [post1] == Post |> where([], [title: "hello", id: ^post1.id]) |> TestRepo.all
params0 = []
params1 = [title: "hello"]
params2 = [title: "hello", id: post1.id]
assert [post1, post2] == (from Post, where: ^params0) |> TestRepo.all |> Enum.sort_by(& &1.id)
assert [post1] == (from Post, where: ^params1) |> TestRepo.all
assert [post1] == (from Post, where: ^params2) |> TestRepo.all
post3 = TestRepo.insert!(%Post{text: "y", title: "goodbye", uuid: nil})
params3 = [title: "goodbye", uuid: post3.uuid]
assert [post3] == (from Post, where: ^params3) |> TestRepo.all
end
## Logging
test "log entry logged on query" do
log = fn entry ->
assert %Ecto.LogEntry{result: {:ok, _}} = entry
assert is_integer(entry.query_time) and entry.query_time >= 0
assert is_integer(entry.decode_time) and entry.query_time >= 0
assert is_integer(entry.queue_time) and entry.queue_time >= 0
send(self(), :logged)
end
Process.put(:on_log, log)
_ = TestRepo.all(Post)
assert_received :logged
end
test "log entry not logged when log is false" do
Process.put(:on_log, fn _ -> flunk("logged") end)
TestRepo.insert!(%Post{title: "1"}, [log: false])
end
test "load" do
inserted_at = ~N[2016-01-01 09:00:00.000000]
TestRepo.insert!(%Post{title: "title1", inserted_at: inserted_at, public: false})
result = Ecto.Adapters.SQL.query!(TestRepo, "SELECT * FROM posts", [])
posts = Enum.map(result.rows, &TestRepo.load(Post, {result.columns, &1}))
assert [%Post{title: "title1", inserted_at: ^inserted_at, public: false}] = posts
end
describe "upsert via insert" do
@describetag :upsert
test "on conflict raise" do
{:ok, inserted} = TestRepo.insert(%Post{title: "first"}, on_conflict: :raise)
assert catch_error(TestRepo.insert(%Post{id: inserted.id, title: "second"}, on_conflict: :raise))
end
test "on conflict ignore" do
post = %Post{title: "first", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"}
{:ok, inserted} = TestRepo.insert(post, on_conflict: :nothing)
assert inserted.id
assert inserted.__meta__.state == :loaded
{:ok, not_inserted} = TestRepo.insert(post, on_conflict: :nothing)
assert not_inserted.id == nil
assert not_inserted.__meta__.state == :loaded
end
@tag :with_conflict_target
test "on conflict and associations" do
on_conflict = [set: [title: "second"]]
post = %Post{uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e",
title: "first", comments: [%Comment{}]}
{:ok, inserted} = TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:uuid])
assert inserted.id
end
@tag :with_conflict_target
test "on conflict with inc" do
uuid = "6fa459ea-ee8a-3ca4-894e-db77e160355e"
post = %Post{title: "first", uuid: uuid}
{:ok, _} = TestRepo.insert(post)
post = %{title: "upsert", uuid: uuid}
TestRepo.insert_all(Post, [post], on_conflict: [inc: [visits: 1]], conflict_target: :uuid)
end
@tag :with_conflict_target
test "on conflict ignore and conflict target" do
post = %Post{title: "first", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"}
{:ok, inserted} = TestRepo.insert(post, on_conflict: :nothing, conflict_target: [:uuid])
assert inserted.id
# Error on non-conflict target
assert catch_error(TestRepo.insert(post, on_conflict: :nothing, conflict_target: [:id]))
# Error on conflict target
{:ok, not_inserted} = TestRepo.insert(post, on_conflict: :nothing, conflict_target: [:uuid])
assert not_inserted.id == nil
end
@tag :without_conflict_target
test "on conflict keyword list" do
on_conflict = [set: [title: "second"]]
post = %Post{title: "first", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"}
{:ok, inserted} = TestRepo.insert(post, on_conflict: on_conflict)
assert inserted.id
{:ok, updated} = TestRepo.insert(post, on_conflict: on_conflict)
assert updated.id == inserted.id
assert updated.title != "second"
assert TestRepo.get!(Post, inserted.id).title == "second"
end
@tag :with_conflict_target
test "on conflict keyword list and conflict target" do
on_conflict = [set: [title: "second"]]
post = %Post{title: "first", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"}
{:ok, inserted} = TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:uuid])
assert inserted.id
# Error on non-conflict target
assert catch_error(TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:id]))
{:ok, updated} = TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:uuid])
assert updated.id == inserted.id
assert updated.title != "second"
assert TestRepo.get!(Post, inserted.id).title == "second"
end
@tag :without_conflict_target
test "on conflict query" do
on_conflict = from Post, update: [set: [title: "second"]]
post = %Post{title: "first", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"}
{:ok, inserted} = TestRepo.insert(post, on_conflict: on_conflict)
assert inserted.id
{:ok, updated} = TestRepo.insert(post, on_conflict: on_conflict)
assert updated.id == inserted.id
assert updated.title != "second"
assert TestRepo.get!(Post, inserted.id).title == "second"
end
@tag :with_conflict_target
test "on conflict query and conflict target" do
on_conflict = from Post, update: [set: [title: "second"]]
post = %Post{title: "first", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"}
{:ok, inserted} = TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:uuid])
assert inserted.id
# Error on non-conflict target
assert catch_error(TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:id]))
{:ok, updated} = TestRepo.insert(post, on_conflict: on_conflict, conflict_target: [:uuid])
assert updated.id == inserted.id
assert updated.title != "second"
assert TestRepo.get!(Post, inserted.id).title == "second"
end
@tag :without_conflict_target
test "on conflict replace_all" do
post = %Post{title: "first", text: "text", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"}
{:ok, inserted} = TestRepo.insert(post, on_conflict: :replace_all)
assert inserted.id
# Error on non-conflict target
post = %Post{id: inserted.id, title: "updated",
text: "updated", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"}
# Error on conflict target
post = TestRepo.insert!(post, on_conflict: :replace_all)
assert post.title == "updated"
assert post.text == "updated"
assert TestRepo.all(from p in Post, select: p.title) == ["updated"]
assert TestRepo.all(from p in Post, select: p.text) == ["updated"]
assert TestRepo.all(from p in Post, select: count(p.id)) == [1]
end
@tag :with_conflict_target
test "on conflict replace_all and conflict target" do
post = %Post{title: "first", text: "text", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"}
{:ok, inserted} = TestRepo.insert(post, on_conflict: :replace_all, conflict_target: :id)
assert inserted.id
# Error on non-conflict target
post = %Post{id: inserted.id, title: "updated",
text: "updated", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"}
# Error on conflict target
post = TestRepo.insert!(post, on_conflict: :replace_all, conflict_target: :id)
assert post.title == "updated"
assert post.text == "updated"
assert TestRepo.all(from p in Post, select: p.title) == ["updated"]
assert TestRepo.all(from p in Post, select: p.text) == ["updated"]
assert TestRepo.all(from p in Post, select: count(p.id)) == [1]
end
end
describe "upsert via insert_all" do
@describetag :upsert_all
test "on conflict raise" do
post = [title: "first", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"]
{1, nil} = TestRepo.insert_all(Post, [post], on_conflict: :raise)
assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: :raise))
end
test "on conflict ignore" do
post = [title: "first", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"]
assert TestRepo.insert_all(Post, [post], on_conflict: :nothing) == {1, nil}
# PG returns 0, MySQL returns 1
{entries, nil} = TestRepo.insert_all(Post, [post], on_conflict: :nothing)
assert entries == 0 or entries == 1
assert length(TestRepo.all(Post)) == 1
end
@tag :with_conflict_target
test "on conflict ignore and conflict target" do
post = [title: "first", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"]
assert TestRepo.insert_all(Post, [post], on_conflict: :nothing, conflict_target: [:uuid]) ==
{1, nil}
# Error on non-conflict target
assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: :nothing, conflict_target: [:id]))
# Error on conflict target
assert TestRepo.insert_all(Post, [post], on_conflict: :nothing, conflict_target: [:uuid]) ==
{0, nil}
end
@tag :with_conflict_target
test "on conflict keyword list and conflict target" do
on_conflict = [set: [title: "second"]]
post = [title: "first", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"]
{1, nil} = TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid])
# Error on non-conflict target
assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:id]))
# Error on conflict target
assert TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid]) ==
{1, nil}
assert TestRepo.all(from p in Post, select: p.title) == ["second"]
end
@tag :with_conflict_target
test "on conflict query and conflict target" do
on_conflict = from Post, update: [set: [title: "second"]]
post = [title: "first", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"]
assert TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid]) ==
{1, nil}
# Error on non-conflict target
assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:id]))
# Error on conflict target
assert TestRepo.insert_all(Post, [post], on_conflict: on_conflict, conflict_target: [:uuid]) ==
{1, nil}
assert TestRepo.all(from p in Post, select: p.title) == ["second"]
end
@tag :returning
@tag :with_conflict_target
test "on conflict query and conflict target and returning" do
on_conflict = from Post, update: [set: [title: "second"]]
post = [title: "first", uuid: "6fa459ea-ee8a-3ca4-894e-db77e160355e"]
{1, [%{id: id}]} = TestRepo.insert_all(Post, [post], on_conflict: on_conflict,
conflict_target: [:uuid], returning: [:id])
# Error on non-conflict target
assert catch_error(TestRepo.insert_all(Post, [post], on_conflict: on_conflict,
conflict_target: [:id], returning: [:id]))
# Error on conflict target
{1, [%Post{id: ^id, title: "second"}]} =
TestRepo.insert_all(Post, [post], on_conflict: on_conflict,
conflict_target: [:uuid], returning: [:id, :title])
end
@tag :with_conflict_target
test "source (without an ecto schema) on conflict query and conflict target" do
on_conflict = [set: [title: "second"]]
{:ok, uuid} = Ecto.UUID.dump("6fa459ea-ee8a-3ca4-894e-db77e160355e")
post = [title: "first", uuid: uuid]
assert TestRepo.insert_all("posts", [post], on_conflict: on_conflict, conflict_target: [:uuid]) ==
{1, nil}
# Error on non-conflict target
assert catch_error(TestRepo.insert_all("posts", [post], on_conflict: on_conflict, conflict_target: [:id]))
# Error on conflict target
assert TestRepo.insert_all("posts", [post], on_conflict: on_conflict, conflict_target: [:uuid]) ==
{1, nil}
assert TestRepo.all(from p in Post, select: p.title) == ["second"]
end
@tag :without_conflict_target
test "on conflict replace_all" do
post_first = %Post{title: "first", public: true}
post_second = %Post{title: "second", public: false}
{:ok, inserted_first} = TestRepo.insert(post_first, on_conflict: :replace_all)
{:ok, inserted_second} = TestRepo.insert(post_second, on_conflict: :replace_all)
assert inserted_first.id
assert inserted_second.id
assert TestRepo.all(from p in Post, select: count(p.id)) == [2]
# multiple record change value
changes = [%{id: inserted_first.id, title: "first_updated", text: "first_updated"},
%{id: inserted_second.id, title: "second_updated", text: "second_updated"}]
TestRepo.insert_all(Post, changes, on_conflict: :replace_all)
assert TestRepo.all(from p in Post, select: count(p.id)) == [2]
updated_first = TestRepo.get(Post, inserted_first.id)
assert updated_first.title == "first_updated"
assert updated_first.text == "first_updated"
updated_first = TestRepo.get(Post, inserted_second.id)
assert updated_first.title == "second_updated"
assert updated_first.text == "second_updated"
end
@tag :with_conflict_target
test "on conflict replace_all and conflict_target" do
post_first = %Post{title: "first", public: true}
post_second = %Post{title: "second", public: false}
{:ok, inserted_first} = TestRepo.insert(post_first, on_conflict: :replace_all,conflict_target: :id)
{:ok, inserted_second} = TestRepo.insert(post_second, on_conflict: :replace_all,conflict_target: :id)
assert inserted_first.id
assert inserted_second.id
assert TestRepo.all(from p in Post, select: count(p.id)) == [2]
# multiple record change value
changes = [%{id: inserted_first.id, title: "first_updated", text: "first_updated"},
%{id: inserted_second.id, title: "second_updated", text: "second_updated"}]
TestRepo.insert_all(Post, changes, on_conflict: :replace_all,conflict_target: :id)
assert TestRepo.all(from p in Post, select: count(p.id)) == [2]
updated_first = TestRepo.get(Post, inserted_first.id)
assert updated_first.title == "first_updated"
assert updated_first.text == "first_updated"
updated_first = TestRepo.get(Post, inserted_second.id)
assert updated_first.title == "second_updated"
assert updated_first.text == "second_updated"
end
end
end
| 37.635439 | 112 | 0.637542 |
08616295e23c977bcbed4f97fe465a3988731e0a | 6,024 | ex | Elixir | lib/techblog_web/live/hangman_live.ex | aforward/anunknown | 67838fe6f60825fd8c057c825f497ce7ef046083 | [
"MIT"
] | null | null | null | lib/techblog_web/live/hangman_live.ex | aforward/anunknown | 67838fe6f60825fd8c057c825f497ce7ef046083 | [
"MIT"
] | null | null | null | lib/techblog_web/live/hangman_live.ex | aforward/anunknown | 67838fe6f60825fd8c057c825f497ce7ef046083 | [
"MIT"
] | null | null | null | defmodule TechblogWeb.HangmanLive do
use TechblogWeb, :live_view
alias Diet.Stepper
@colours [
"#5ED0FA",
"#54D1DB",
"#A368FC",
"#F86A6A",
"#FADB5F",
"#65D6AD",
"#127FBF",
"#0E7C86",
"#690CB0",
"#AB091E",
"#CB6E17",
"#147D64"
]
@hit "#D64545"
def render(assigns) do
~L"""
<div class="hangman" data-cheater=<%= @answer %>>
<div class="move-reply">
<%= assigns |> top_message() |> Phoenix.HTML.raw() %>
</div>
<svg width="159px" height="144px" viewBox="0 0 159 144" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="hangman" stroke="none" stroke-width="1" fill-rule="evenodd">
<g id="platform" fill="#D1D1D1">
<polygon id="left" fill="<%= colour() %>" points="14 -7.66053887e-15 21 -7.66053887e-15 21 138 14 138"></polygon>
<polygon id="bottom" fill="<%= colour() %>" transform="translate(79.500000, 141.000000) rotate(90.000000) translate(-79.500000, -141.000000) " points="76.5 61.5 82.5 61.5 82.5 220.5 76.5 220.5"></polygon>
<polygon id="top" fill="<%= colour() %>" transform="translate(54.500000, 3.000000) rotate(90.000000) translate(-54.500000, -3.000000) " points="51.5 -51.5 57.5 -51.5 57.5 57.5 51.5 57.5"></polygon>
<polygon id="rope" fill="<%= person(@rope) %>" points="109 -1.88737914e-15 116 -1.88737914e-15 116 34 109 34"></polygon>
</g>
<g id="person" transform="translate(83.000000, 34.000000)">
<ellipse id="head" fill="<%= person(@head) %>" cx="29.5" cy="12" rx="14.5" ry="12"></ellipse>
<rect id="body" fill="<%= person(@body) %>" x="26" y="23" width="7" height="36"></rect>
<polygon id="left_arm" fill="<%= person(@left_arm) %>" transform="translate(17.887481, 35.964726) rotate(100.000000) translate(-17.887481, -35.964726) " points="14.387481 21.4647257 21.387481 21.4647257 21.387481 50.4647257 14.387481 50.4647257"></polygon>
<polygon id="right_arm" fill="<%= person(@right_arm) %>" transform="translate(41.887481, 35.964726) rotate(80.000000) translate(-41.887481, -35.964726) " points="38.387481 21.4647257 45.387481 21.4647257 45.387481 50.4647257 38.387481 50.4647257"></polygon>
<polygon id="left_leg" fill="<%= person(@left_leg) %>" transform="translate(16.449946, 69.449946) rotate(45.000000) translate(-16.449946, -69.449946) " points="13.9041271 50.860171 20.7936782 50.5299419 18.9957643 88.0397203 12.1062131 88.3699494"></polygon>
<polygon id="right_leg" fill="<%= person(@right_leg) %>" transform="translate(42.449946, 71.449946) rotate(-45.000000) translate(-42.449946, -71.449946) " points="38.1062131 52.5299419 44.9957643 52.860171 46.7936782 90.3699494 39.9041271 90.0397203"></polygon>
</g>
</g>
</svg>
<div class="word">
<%= for l <- @word_so_far do %>
<span><%= l %></span>
<% end %>
</div>
<div class="form">
<form phx-submit="guess">
<%= if @continue do %>
<input name="letter" type="text" maxlength="1" />
<input type="submit" class="btn-guess" value="Guess" />
<% end %>
<button class="btn-new" phx-click="new-game">New</button>
</form>
</div>
</div>
"""
end
def mount(_params, _session, socket) do
{:ok, socket |> assign_game()}
end
def handle_event("guess", %{"letter" => l}, socket) do
{r, s} = Stepper.run(socket.assigns.stepper, {:make_move, l})
{:noreply, socket |> assign_game(s) |> assign_reply(l, r)}
end
def handle_event("guess", %{}, socket) do
{:noreply, socket}
end
def handle_event("new-game", _, socket) do
{:noreply, socket |> assign_game()}
end
defp assign_game(socket), do: assign_game(socket, Stepper.new(Hangman, Hangman.Words.pick()))
defp assign_game(socket, stepper) do
socket
|> assign(:stepper, stepper)
|> assign(:rope, body_part(6, stepper))
|> assign(:head, body_part(5, stepper))
|> assign(:body, body_part(4, stepper))
|> assign(:left_arm, body_part(3, stepper))
|> assign(:right_arm, body_part(2, stepper))
|> assign(:left_leg, body_part(1, stepper))
|> assign(:right_leg, body_part(0, stepper))
|> assign(:answer, stepper.model.word_to_guess |> Enum.join())
|> assign(:turns_left, stepper.model.turns_left)
|> assign(:word_so_far, Hangman.Model.word_so_far(stepper.model))
|> assign(:move_reply, nil)
|> assign(:continue, true)
|> assign(:letter, nil)
end
defp assign_reply(socket, letter, reply) do
socket
|> assign(:move_reply, reply)
|> assign(:letter, letter)
|> assign(
:continue,
case reply do
:game_won -> false
:game_lost -> false
_ -> true
end
)
end
defp body_part(num, s) do
cond do
s.model.turns_left == num -> :new
s.model.turns_left < num -> :on
s.model.turns_left > num -> :off
end
end
defp top_message(assigns) do
assigns[:move_reply]
|> case do
nil -> {:stop, "Welcome to hangman"}
:game_won -> {:stop, "Congratulations, you WON"}
:game_lost -> {:stop, "GAME OVER, you lose"}
:bad_guess -> {:continue, "Sorry, <span>#{assigns.letter}</span> not found!"}
:good_guess -> {:continue, "Excellent, <span>#{assigns.letter}</span> found."}
:already_tried -> {:continue, "Silly, you already guess <span>#{assigns.letter}</span>"}
move_reply -> move_reply
end
|> case do
{:stop, msg} ->
msg
{:continue, msg} ->
case assigns.turns_left do
1 -> "#{msg} (1 error remaining"
0 -> "#{msg} (no errors remaining)"
turns_left -> "#{msg} (#{turns_left} errors remaining)"
end
end
end
def colour(), do: @colours |> Enum.random()
def person(:on), do: @colours |> Enum.random()
def person(:off), do: "none"
def person(:new), do: @hit
end
| 39.372549 | 273 | 0.594124 |
086192b681d80bafcafa4b7968cdcbb2fc9935da | 1,233 | ex | Elixir | lib/juntos_web/live/page_live.ex | elixir-berlin/juntos | 64dd05888f357cf0c74da11d1eda69bab7f38e95 | [
"MIT"
] | 1 | 2019-11-15T15:39:24.000Z | 2019-11-15T15:39:24.000Z | lib/juntos_web/live/page_live.ex | elixir-berlin/juntos | 64dd05888f357cf0c74da11d1eda69bab7f38e95 | [
"MIT"
] | 166 | 2020-06-30T16:07:48.000Z | 2021-11-25T00:02:24.000Z | lib/juntos_web/live/page_live.ex | elixir-berlin/juntos | 64dd05888f357cf0c74da11d1eda69bab7f38e95 | [
"MIT"
] | null | null | null | defmodule JuntosWeb.PageLive do
@moduledoc false
use JuntosWeb, :live_view
@impl true
def mount(_params, session, socket) do
user =
session["user_token"] && Juntos.Accounts.get_user_by_session_token(session["user_token"])
{:ok, assign(socket, query: "", results: %{}, current_user: user)}
end
@impl true
def handle_event("suggest", %{"q" => query}, socket) do
{:noreply, assign(socket, results: search(query), query: query)}
end
@impl true
def handle_event("search", %{"q" => query}, socket) do
case search(query) do
%{^query => vsn} ->
{:noreply, redirect(socket, external: "https://hexdocs.pm/#{query}/#{vsn}")}
_ ->
{:noreply,
socket
|> put_flash(:error, "No dependencies found matching \"#{query}\"")
|> assign(results: %{}, query: query)}
end
end
defp search(query) do
if not JuntosWeb.Endpoint.config(:code_reloader) do
raise "action disabled when not in development"
end
for {app, desc, vsn} <- Application.started_applications(),
app = to_string(app),
String.starts_with?(app, query) and not List.starts_with?(desc, ~c"ERTS"),
into: %{},
do: {app, vsn}
end
end
| 28.022727 | 95 | 0.615572 |
0861ae99c3a50b63be755729199bcef6b23e86e2 | 982 | ex | Elixir | web/router.ex | cadorfo/SchoolAgenda | 5dd99f3482f103f7a3ac5ef83a07a36d15bbe17d | [
"MIT"
] | null | null | null | web/router.ex | cadorfo/SchoolAgenda | 5dd99f3482f103f7a3ac5ef83a07a36d15bbe17d | [
"MIT"
] | null | null | null | web/router.ex | cadorfo/SchoolAgenda | 5dd99f3482f103f7a3ac5ef83a07a36d15bbe17d | [
"MIT"
] | null | null | null | defmodule SchoolAgenda.Router do
use SchoolAgenda.Web, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
plug SchoolAgenda.Plugs.UserSession
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", SchoolAgenda do
pipe_through :browser # Use the default browser stack
get "/", PageController, :index
resources "/users", UserController
resources "/teachers", TeacherController
resources "/curriculum", SchoolCurriculumController
resources "/disciplines", DisciplineController
end
scope "/auth", SchoolAgenda do
pipe_through :browser
get "/delete", AuthController, :delete
get "/:provider", AuthController, :request
get "/:provider/callback", AuthController, :callback
end
# Other scopes may use custom stacks.
# scope "/api", SchoolAgenda do
# pipe_through :api
# end
end
| 24.55 | 57 | 0.703666 |
0861d252b0460493e99fe438a3686efc3fabe6b5 | 108 | exs | Elixir | test/littlechat_web/live/page_live_test.exs | BenBera/littleChatWebrtc | 91850323d0e60c4049a84ff8985b09856b356016 | [
"MIT"
] | 166 | 2020-07-15T14:47:19.000Z | 2022-03-25T03:57:35.000Z | test/littlechat_web/live/page_live_test.exs | BenBera/littleChatWebrtc | 91850323d0e60c4049a84ff8985b09856b356016 | [
"MIT"
] | 12 | 2020-07-01T23:32:47.000Z | 2021-03-18T21:21:28.000Z | test/littlechat_web/live/page_live_test.exs | BenBera/littleChatWebrtc | 91850323d0e60c4049a84ff8985b09856b356016 | [
"MIT"
] | 21 | 2020-07-15T14:59:39.000Z | 2022-03-20T21:05:16.000Z | defmodule LittlechatWeb.PageLiveTest do
# use LittlechatWeb.ConnCase
# import Phoenix.LiveViewTest
end
| 18 | 39 | 0.814815 |
0861e38432c4989c3f371c4f27987276dee1358b | 2,694 | ex | Elixir | lib/elixir_keeb_ui_web/contex/barchart_timer.ex | amalbuquerque/elixir_keeb_ui | d203ccc128547668febd13a35d9472e5b4b3151a | [
"MIT"
] | 3 | 2020-07-07T15:57:55.000Z | 2021-08-12T05:09:38.000Z | lib/elixir_keeb_ui_web/contex/barchart_timer.ex | amalbuquerque/elixir_keeb_ui | d203ccc128547668febd13a35d9472e5b4b3151a | [
"MIT"
] | 3 | 2020-09-28T20:53:30.000Z | 2021-08-31T20:41:04.000Z | lib/elixir_keeb_ui_web/contex/barchart_timer.ex | amalbuquerque/elixir_keeb_ui | d203ccc128547668febd13a35d9472e5b4b3151a | [
"MIT"
] | 1 | 2021-07-16T13:49:09.000Z | 2021-07-16T13:49:09.000Z | defmodule ElixirKeeb.UIWeb.Contex.BarchartTimer do
use Phoenix.LiveView
use Phoenix.HTML
import ElixirKeeb.UIWeb.Contex.Shared
alias Contex.{BarChart, Plot, Dataset}
def render(assigns) do
~L"""
<div class="container">
<div class="row">
<div class="column column-75">
<%= if @show_chart do %>
<%= basic_plot(@chart_data, @chart_options) %>
<% end %>
</div>
</div>
</div>
"""
end
def mount(params, _session, socket) do
initial_options = case params[:initial_options] do
nil ->
raise("`initial_options` used for the barchart need to be passed through the `params` argument. Params passed: #{inspect(params)}")
options when is_map(options) ->
options
end
socket =
socket
|> assign(chart_options: initial_options)
|> get_data()
wait_before_new_data_ms =
initial_options.data_source[:wait_before_new_data_ms]
socket = case connected?(socket) do
true ->
Process.send_after(self(), :tick, wait_before_new_data_ms)
assign(socket, show_chart: true)
false ->
assign(socket, show_chart: true)
end
{:ok, socket}
end
def handle_info(:tick, socket) do
wait_before_new_data_ms =
socket.assigns.chart_options.data_source[:wait_before_new_data_ms]
Process.send_after(self(), :tick, wait_before_new_data_ms)
{:noreply, get_data(socket)}
end
def basic_plot(chart_data, chart_options) do
plot_content = BarChart.new(chart_data)
|> BarChart.set_val_col_names(chart_options.series_columns)
|> BarChart.type(chart_options.type)
|> BarChart.orientation(chart_options.orientation)
|> BarChart.colours(lookup_colours(chart_options.colour_scheme))
|> BarChart.force_value_range(chart_options.values_range)
{width, height} = chart_options.plot_dimensions
plot = Plot.new(width, height, plot_content)
|> Plot.titles(chart_options.title, nil)
Plot.to_svg(plot)
end
defp get_data(socket) do
options = socket.assigns.chart_options
series = options.series
data = raw_data(options.data_source[:mfa])
series_cols = for i <- 1..series do
"Series #{i}"
end
options = Map.put(options, :series_columns, series_cols)
chart_data = Dataset.new(data, ["Category" | series_cols])
assign(socket, chart_data: chart_data, chart_options: options)
end
def raw_data({module, function, args}) when is_list(args) do
data = Kernel.apply(module, function, args)
data
|> Enum.zip(1..length(data))
|> Enum.map(fn {val, cat} -> ["#{cat}" | [val]] end)
end
end
| 26.411765 | 139 | 0.657758 |
0861f37a83c148c5a61d21b15f416f3998c788a3 | 423 | exs | Elixir | test/bus_web/views/error_view_test.exs | titouancreach/bus-rennes | 9d85a1c13a161b4f48e6efaf7ed52dbd7991f9d8 | [
"MIT"
] | 3 | 2018-06-16T22:34:46.000Z | 2018-06-20T07:15:27.000Z | test/bus_web/views/error_view_test.exs | titouancreach/bus-rennes | 9d85a1c13a161b4f48e6efaf7ed52dbd7991f9d8 | [
"MIT"
] | null | null | null | test/bus_web/views/error_view_test.exs | titouancreach/bus-rennes | 9d85a1c13a161b4f48e6efaf7ed52dbd7991f9d8 | [
"MIT"
] | null | null | null | defmodule BusWeb.ErrorViewTest do
use BusWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.html" do
assert render_to_string(BusWeb.ErrorView, "404.html", []) ==
"Not Found"
end
test "renders 500.html" do
assert render_to_string(BusWeb.ErrorView, "500.html", []) ==
"Internal Server Error"
end
end
| 24.882353 | 66 | 0.685579 |
08623b740135b270ec677baed617c00478a82a27 | 5,834 | ex | Elixir | lib/rtp_h264/payloader.ex | membraneframework/membrane-element-rtp-h264 | 807befb264775c9994108403214e039d039e18b1 | [
"Apache-2.0"
] | 3 | 2019-10-15T05:29:07.000Z | 2020-02-18T12:43:44.000Z | lib/rtp_h264/payloader.ex | membraneframework/membrane-element-rtp-h264 | 807befb264775c9994108403214e039d039e18b1 | [
"Apache-2.0"
] | 2 | 2019-08-21T07:43:21.000Z | 2020-07-16T10:46:13.000Z | lib/rtp_h264/payloader.ex | membraneframework/membrane-element-rtp-h264 | 807befb264775c9994108403214e039d039e18b1 | [
"Apache-2.0"
] | null | null | null | defmodule Membrane.RTP.H264.Payloader do
@moduledoc """
Payloads H264 NAL Units into H264 RTP payloads.
Based on [RFC 6184](https://tools.ietf.org/html/rfc6184)
Supported types: Single NALU, FU-A, STAP-A.
"""
use Bunch
use Membrane.Filter
alias Membrane.Buffer
alias Membrane.H264
alias Membrane.RTP
alias Membrane.RTP.H264.{FU, StapA}
def_options max_payload_size: [
spec: non_neg_integer(),
default: 1400,
description: """
Maximal size of outputted payloads in bytes. Doesn't work in
the `single_nalu` mode. The resulting RTP packet will also contain
RTP header (12B) and potentially RTP extensions. For most
applications, everything should fit in standard MTU size (1500B)
after adding L3 and L2 protocols' overhead.
"""
],
mode: [
spec: :single_nalu | :non_interleaved,
default: :non_interleaved,
description: """
In `:single_nalu` mode, payloader puts exactly one NAL unit
into each payload, altering only RTP metadata. `:non_interleaved`
mode handles also FU-A and STAP-A packetization. See
[RFC 6184](https://tools.ietf.org/html/rfc6184) for details.
"""
]
def_input_pad :input,
caps: {H264, stream_format: :byte_stream, alignment: :nal},
demand_mode: :auto
def_output_pad :output, caps: RTP, demand_mode: :auto
defmodule State do
@moduledoc false
defstruct [
:max_payload_size,
:mode,
stap_acc: %{
payloads: [],
# header size
byte_size: 1,
pts: 0,
dts: 0,
metadata: nil,
nri: 0,
reserved: 0
}
]
end
@impl true
def handle_init(options) do
{:ok, Map.merge(%State{}, Map.from_struct(options))}
end
@impl true
def handle_prepared_to_playing(_ctx, state) do
{{:ok, caps: {:output, %RTP{}}}, state}
end
@impl true
def handle_caps(:input, _caps, _context, state) do
{:ok, state}
end
@impl true
def handle_process(:input, %Buffer{} = buffer, _ctx, state) do
buffer = Map.update!(buffer, :payload, &delete_prefix/1)
{buffers, state} =
withl mode: :non_interleaved <- state.mode,
stap_a: {:deny, stap_acc_bufs, state} <- try_stap_a(buffer, state),
single_nalu: :deny <- try_single_nalu(buffer, state) do
{stap_acc_bufs ++ use_fu_a(buffer, state), state}
else
mode: :single_nalu -> {use_single_nalu(buffer), state}
stap_a: {:accept, buffers, state} -> {buffers, state}
single_nalu: {:accept, buffer} -> {stap_acc_bufs ++ [buffer], state}
end
{{:ok, buffer: {:output, buffers}}, state}
end
@impl true
def handle_end_of_stream(:input, _ctx, state) do
{buffers, state} = flush_stap_acc(state)
{{:ok, buffer: {:output, buffers}, end_of_stream: :output}, state}
end
defp delete_prefix(<<0, 0, 0, 1, nal::binary>>), do: nal
defp delete_prefix(<<0, 0, 1, nal::binary>>), do: nal
defp try_stap_a(buffer, state) do
with {:deny, acc_buffers, state} <- do_try_stap_a(buffer, state) do
# try again, after potential accumulator flush
{result, [], state} = do_try_stap_a(buffer, state)
{result, acc_buffers, state}
end
end
defp do_try_stap_a(buffer, state) do
%{stap_acc: stap_acc} = state
size = stap_acc.byte_size + StapA.aggregation_unit_size(buffer.payload)
metadata_match? = !stap_acc.metadata || stap_acc.pts == buffer.pts
if metadata_match? and size <= state.max_payload_size do
<<r::1, nri::2, _type::5, _rest::binary()>> = buffer.payload
stap_acc = %{
stap_acc
| payloads: [buffer.payload | stap_acc.payloads],
byte_size: size,
metadata: stap_acc.metadata || buffer.metadata,
pts: buffer.pts,
dts: buffer.dts,
reserved: stap_acc.reserved * r,
nri: min(stap_acc.nri, nri)
}
{:accept, [], %{state | stap_acc: stap_acc}}
else
{buffers, state} = flush_stap_acc(state)
{:deny, buffers, state}
end
end
defp flush_stap_acc(%{stap_acc: stap_acc} = state) do
buffers =
case stap_acc.payloads do
[] ->
[]
[payload] ->
# use single nalu
[
%Buffer{
payload: payload,
metadata: stap_acc.metadata,
pts: stap_acc.pts,
dts: stap_acc.dts
}
|> set_marker()
]
payloads ->
payload = StapA.serialize(payloads, stap_acc.reserved, stap_acc.nri)
[
%Buffer{
payload: payload,
metadata: stap_acc.metadata,
pts: stap_acc.pts,
dts: stap_acc.dts
}
|> set_marker()
]
end
{buffers, %{state | stap_acc: %State{}.stap_acc}}
end
defp try_single_nalu(buffer, state) do
if byte_size(buffer.payload) <= state.max_payload_size do
{:accept, use_single_nalu(buffer)}
else
:deny
end
end
defp use_single_nalu(buffer) do
set_marker(buffer)
end
defp use_fu_a(buffer, state) do
buffer.payload
|> FU.serialize(state.max_payload_size)
|> Enum.map(&%Buffer{buffer | payload: &1})
|> Enum.map(&clear_marker/1)
|> List.update_at(-1, &set_marker/1)
end
defp set_marker(buffer) do
marker = Map.get(buffer.metadata.h264, :end_access_unit, false)
Bunch.Struct.put_in(buffer, [:metadata, :rtp], %{marker: marker})
end
defp clear_marker(buffer) do
Bunch.Struct.put_in(buffer, [:metadata, :rtp], %{marker: false})
end
end
| 28.598039 | 82 | 0.588447 |
086240d36961e9a815eed4208f0ce6b1f166bdb2 | 532 | exs | Elixir | test/create_sequence_test.exs | jonseaberg/ecto_extract_migrations | 6372825495b702386c291a5dda2f63ad1c8317ca | [
"Apache-2.0"
] | 7 | 2020-09-02T14:50:12.000Z | 2021-11-12T20:07:36.000Z | test/create_sequence_test.exs | jonseaberg/ecto_extract_migrations | 6372825495b702386c291a5dda2f63ad1c8317ca | [
"Apache-2.0"
] | 2 | 2020-10-31T12:17:25.000Z | 2020-11-05T13:13:13.000Z | test/create_sequence_test.exs | jonseaberg/ecto_extract_migrations | 6372825495b702386c291a5dda2f63ad1c8317ca | [
"Apache-2.0"
] | 3 | 2020-10-31T11:46:31.000Z | 2022-02-11T15:23:10.000Z | defmodule CreateSequenceTest do
use ExUnit.Case
alias EctoExtractMigrations.Parsers.CreateSequence
test "create_sequence" do
sql = """
CREATE SEQUENCE chat.assignment_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
"""
expected = %{
name: ["chat", "assignment_id_seq"],
cache: 1,
increment: 1,
maxvalue: false,
minvalue: false,
start: 1,
}
assert {:ok, expected} == CreateSequence.parse(sql)
end
end
| 19 | 55 | 0.603383 |
08624fa09cfbf97bfbee94a8a364de570f7f7b4e | 67 | ex | Elixir | lib/issues.ex | vonum/issues | 5b453d17d0b15092d7cdf47bfb29abea4fecca5d | [
"MIT"
] | null | null | null | lib/issues.ex | vonum/issues | 5b453d17d0b15092d7cdf47bfb29abea4fecca5d | [
"MIT"
] | null | null | null | lib/issues.ex | vonum/issues | 5b453d17d0b15092d7cdf47bfb29abea4fecca5d | [
"MIT"
] | null | null | null | defmodule Issues do
def main(argv), do: Issues.CLI.run(argv)
end
| 16.75 | 42 | 0.731343 |
08626a61c56224ef15dd0ad92e537d8c724ee799 | 167 | ex | Elixir | lib/honeydew/please/events/task_reactivated.ex | christian-fei/honeydew | af06f5778de164fd50979ae20e59b6aeb3092485 | [
"MIT"
] | 13 | 2022-02-13T18:43:20.000Z | 2022-03-19T11:53:48.000Z | lib/honeydew/please/events/task_reactivated.ex | christian-fei/honeydew | af06f5778de164fd50979ae20e59b6aeb3092485 | [
"MIT"
] | 1 | 2022-02-23T13:57:19.000Z | 2022-02-23T13:57:19.000Z | lib/honeydew/please/events/task_reactivated.ex | christian-fei/honeydew | af06f5778de164fd50979ae20e59b6aeb3092485 | [
"MIT"
] | 3 | 2022-02-13T19:25:19.000Z | 2022-02-22T17:56:52.000Z | defmodule Honeydew.Please.Events.TaskReactivated do
@moduledoc """
OH NO! WHYYYYYY!
"""
@derive Jason.Encoder
defstruct [
:task_id,
:notes
]
end
| 12.846154 | 51 | 0.652695 |
0862ab7ed2a1e783f775c117f84fe3e4e22a8619 | 974 | exs | Elixir | test/absinthe/language/inline_fragment_test.exs | TheRealReal/absinthe | 6eae5bc36283e58f42d032b8afd90de3ad64f97b | [
"MIT"
] | 4,101 | 2016-03-02T03:49:20.000Z | 2022-03-31T05:46:01.000Z | test/absinthe/language/inline_fragment_test.exs | TheRealReal/absinthe | 6eae5bc36283e58f42d032b8afd90de3ad64f97b | [
"MIT"
] | 889 | 2016-03-02T16:06:59.000Z | 2022-03-31T20:24:12.000Z | test/absinthe/language/inline_fragment_test.exs | TheRealReal/absinthe | 6eae5bc36283e58f42d032b8afd90de3ad64f97b | [
"MIT"
] | 564 | 2016-03-02T07:49:59.000Z | 2022-03-06T14:40:59.000Z | defmodule Absinthe.Language.InlineFragmentTest do
use Absinthe.Case, async: true
alias Absinthe.{Blueprint, Language}
@query """
{
... on RootQueryType {
foo
bar
}
}
"""
describe "converting to Blueprint" do
test "builds a Document.Fragment.Inline.t" do
assert %Blueprint.Document.Fragment.Inline{
type_condition: %Blueprint.TypeReference.Name{name: "RootQueryType"},
selections: [
%Blueprint.Document.Field{name: "foo"},
%Blueprint.Document.Field{name: "bar"}
]
} = from_input(@query)
end
end
defp from_input(text) do
{:ok, %{input: doc}} = Absinthe.Phase.Parse.run(text)
doc
|> extract_ast_node
|> Blueprint.Draft.convert(doc)
end
defp extract_ast_node(%Language.Document{definitions: nodes}) do
op =
nodes
|> List.first()
op.selection_set.selections
|> List.first()
end
end
| 22.136364 | 84 | 0.601643 |
0862d4348ef0ab4ea0bec6d815cd31358fe3db70 | 1,681 | ex | Elixir | clients/big_query/lib/google_api/big_query/v2/model/job_statistics_reservation_usage.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/big_query/lib/google_api/big_query/v2/model/job_statistics_reservation_usage.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/big_query/lib/google_api/big_query/v2/model/job_statistics_reservation_usage.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.BigQuery.V2.Model.JobStatisticsReservationUsage do
@moduledoc """
## Attributes
- name (String.t): [Output-only] Reservation name or \"unreserved\" for on-demand resources usage. Defaults to: `null`.
- slotMs (String.t): [Output-only] Slot-milliseconds the job spent in the given reservation. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:name => any(),
:slotMs => any()
}
field(:name)
field(:slotMs)
end
defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.JobStatisticsReservationUsage do
def decode(value, options) do
GoogleApi.BigQuery.V2.Model.JobStatisticsReservationUsage.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.JobStatisticsReservationUsage do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.960784 | 131 | 0.740631 |
0862e76c90c8e410e572c53670125e30e6611871 | 2,765 | exs | Elixir | test/floki/selector/tokenizer_test.exs | nathanl/floki | 042b3f60f4d9a6218ec85d558d13cc6dac30c587 | [
"MIT"
] | 1,778 | 2015-01-07T14:12:31.000Z | 2022-03-29T22:42:48.000Z | test/floki/selector/tokenizer_test.exs | nathanl/floki | 042b3f60f4d9a6218ec85d558d13cc6dac30c587 | [
"MIT"
] | 279 | 2015-01-01T15:54:50.000Z | 2022-03-28T18:06:03.000Z | test/floki/selector/tokenizer_test.exs | nathanl/floki | 042b3f60f4d9a6218ec85d558d13cc6dac30c587 | [
"MIT"
] | 166 | 2015-04-24T20:48:02.000Z | 2022-03-28T17:29:05.000Z | defmodule Floki.Selector.TokenizerTest do
use ExUnit.Case, async: true
alias Floki.Selector.Tokenizer
test "empty selector" do
assert Tokenizer.tokenize("") == []
end
test "complex selector" do
complex = """
ns|a.link,
.b[title=hello],
[href~=foo] *,
a > b
"""
assert Tokenizer.tokenize(complex) == [
{:identifier, 1, 'ns'},
{:namespace_pipe, 1},
{:identifier, 1, 'a'},
{:class, 1, 'link'},
{:comma, 1},
{:class, 2, 'b'},
{'[', 2},
{:identifier, 2, 'title'},
{:equal, 2},
{:identifier, 2, 'hello'},
{']', 2},
{:comma, 2},
{'[', 3},
{:identifier, 3, 'href'},
{:includes, 3},
{:identifier, 3, 'foo'},
{']', 3},
{:space, 3},
{'*', 3},
{:comma, 3},
{:identifier, 4, 'a'},
{:greater, 4},
{:identifier, 4, 'b'}
]
end
test "prefix match with quoted val" do
assert Tokenizer.tokenize("#about-us[href^='contact']") == [
{:hash, 1, 'about-us'},
{'[', 1},
{:identifier, 1, 'href'},
{:prefix_match, 1},
{:quoted, 1, 'contact'},
{']', 1}
]
end
test "an unknown token" do
assert Tokenizer.tokenize("&") == [
{:unknown, 1, '&'}
]
end
test "pseudo classes" do
assert Tokenizer.tokenize(":nth-child(3)") == [
{:pseudo, 1, 'nth-child'},
{:pseudo_class_int, 1, 3}
]
assert Tokenizer.tokenize(":nth-child(odd)") == [
{:pseudo, 1, 'nth-child'},
{:pseudo_class_odd, 1}
]
assert Tokenizer.tokenize(":nth-child(even)") == [
{:pseudo, 1, 'nth-child'},
{:pseudo_class_even, 1}
]
assert Tokenizer.tokenize(":nth-child(2n+1)") == [
{:pseudo, 1, 'nth-child'},
{:pseudo_class_pattern, 1, '2n+1'}
]
assert Tokenizer.tokenize(":nth-child(2n-1)") == [
{:pseudo, 1, 'nth-child'},
{:pseudo_class_pattern, 1, '2n-1'}
]
assert Tokenizer.tokenize(":nth-child(n+0)") == [
{:pseudo, 1, 'nth-child'},
{:pseudo_class_pattern, 1, 'n+0'}
]
assert Tokenizer.tokenize(":nth-child(-n+6)") == [
{:pseudo, 1, 'nth-child'},
{:pseudo_class_pattern, 1, '-n+6'}
]
assert Tokenizer.tokenize(":fl-contains('foo')") == [
{:pseudo, 1, 'fl-contains'},
{:pseudo_class_quoted, 1, 'foo'}
]
end
end
| 26.84466 | 64 | 0.428571 |
086310026bed1b769f0bb9f8d10eb3a14648c343 | 1,050 | ex | Elixir | test/support/apps/example/test/support/conn_case.ex | mitchellhenke/torch | 2d0ab68f4e2d7f3bc37fbf7edbd1298b29b36e71 | [
"MIT"
] | 528 | 2019-09-13T15:10:36.000Z | 2022-03-31T10:28:27.000Z | test/support/apps/example/test/support/conn_case.ex | mitchellhenke/torch | 2d0ab68f4e2d7f3bc37fbf7edbd1298b29b36e71 | [
"MIT"
] | 133 | 2019-09-13T17:46:59.000Z | 2022-03-01T13:37:10.000Z | test/support/apps/example/test/support/conn_case.ex | mitchellhenke/torch | 2d0ab68f4e2d7f3bc37fbf7edbd1298b29b36e71 | [
"MIT"
] | 38 | 2019-10-29T20:37:13.000Z | 2022-03-03T05:19:33.000Z | defmodule ExampleWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
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 connections
use Phoenix.ConnTest
alias ExampleWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint ExampleWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Example.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Example.Repo, {:shared, self()})
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 26.923077 | 69 | 0.718095 |
086311472fbb244a5b088990d516900cacb14eec | 269 | ex | Elixir | lib/live_view_examples.ex | zorbash/observer_live | f78af309a85783ac61d97ba9bb5ffd7a64ec9823 | [
"MIT"
] | 219 | 2019-04-02T02:51:59.000Z | 2021-11-10T22:14:17.000Z | lib/live_view_examples.ex | zorbash/observer_live | f78af309a85783ac61d97ba9bb5ffd7a64ec9823 | [
"MIT"
] | 1 | 2021-05-08T11:51:29.000Z | 2021-05-08T11:51:29.000Z | lib/live_view_examples.ex | zorbash/observer_live | f78af309a85783ac61d97ba9bb5ffd7a64ec9823 | [
"MIT"
] | 14 | 2019-04-02T07:19:38.000Z | 2021-03-27T19:19:45.000Z | defmodule LiveViewExamples do
@moduledoc """
LiveViewExamples keeps the contexts that define your domain
and business logic.
Contexts are also responsible for managing your data, regardless
if it comes from the database, an external API or others.
"""
end
| 26.9 | 66 | 0.769517 |
0863294f0b5f2430c51141cfb29599f6a2dc7f08 | 4,398 | ex | Elixir | lib/mango_pay/preauthorization.ex | Eweev/mangopay-elixir | 7a4ff7b47c31bfa9a77d944803158f8297d51505 | [
"MIT"
] | 1 | 2020-04-07T22:17:25.000Z | 2020-04-07T22:17:25.000Z | lib/mango_pay/preauthorization.ex | Eweev/mangopay-elixir | 7a4ff7b47c31bfa9a77d944803158f8297d51505 | [
"MIT"
] | 17 | 2018-04-11T12:07:07.000Z | 2019-03-18T21:33:18.000Z | lib/mango_pay/preauthorization.ex | Eweev/mangopay-elixir | 7a4ff7b47c31bfa9a77d944803158f8297d51505 | [
"MIT"
] | 2 | 2020-06-22T09:31:41.000Z | 2020-06-22T09:34:23.000Z | defmodule MangoPay.PreAuthorization do
@moduledoc """
Functions for MangoPay [pre authorization](https://docs.mangopay.com/endpoints/v2.01/preauthorizations#e183_the-preauthorization-object).
"""
use MangoPay.Query.Base
set_path "preauthorizations"
@doc """
Get a preauthorization.
## Examples
{:ok, preauthorization} = MangoPay.PreAuthorization.get(id)
"""
def get id do
_get id
end
@doc """
Get a preauthorization.
## Examples
preauthorization = MangoPay.PreAuthorization.get!(id)
"""
def get! id do
_get! id
end
@doc """
Create a preauthorization.
## Examples
params = %{
"Tag": "custom meta",
"AuthorId": "8494514",
"DebitedFunds": %{
"Currency": "EUR",
"Amount": 12
},
"Billing": %{
"Address": %{
"AddressLine1": "1 Mangopay Street",
"AddressLine2": "The Loop",
"City": "Paris",
"Region": "Ile de France",
"PostalCode": "75001",
"Country": "FR"
}
},
"SecureMode": "DEFAULT",
"CardId": "14213157",
"SecureModeReturnURL": "http://www.my-site.com/returnURL"
}
{:ok, preauthorization} = MangoPay.PreAuthorization.create(params)
"""
def create params do
_create params, "/card/direct"
end
@doc """
Create a preauthorization.
## Examples
params = %{
"Tag": "custom meta",
"AuthorId": "8494514",
"DebitedFunds": %{
"Currency": "EUR",
"Amount": 12
},
"Billing": %{
"Address": %{
"AddressLine1": "1 Mangopay Street",
"AddressLine2": "The Loop",
"City": "Paris",
"Region": "Ile de France",
"PostalCode": "75001",
"Country": "FR"
}
},
"SecureMode": "DEFAULT",
"CardId": "14213157",
"SecureModeReturnURL": "http://www.my-site.com/returnURL"
}
preauthorization = MangoPay.PreAuthorization.create!(params)
"""
def create! params do
_create! params, "/card/direct"
end
@doc """
Cancel a preauthorization.
## Examples
params = %{
"Tag": "custom meta",
"PaymentStatus": "CANCELED"
}
{:ok, preauthorization} = MangoPay.PreAuthorization.cancel("preauthorization_id", params)
"""
def cancel id, params do
_update params, id
end
@doc """
Cancel a preauthorization.
## Examples
params = %{
"Tag": "custom meta",
"PaymentStatus": "CANCELED"
}
preauthorization = MangoPay.PreAuthorization.cancel!("preauthorization_id", params)
"""
def cancel! id, params do
_update! params, id
end
@doc """
List all preauthorizations for a credit card.
## Examples
{:ok, preauthorizations} = MangoPay.PreAuthorization.all_by_card("card_id")
"""
def all_by_card id, query \\ %{} do
_all [MangoPay.Card.path(id), resource()], query
end
@doc """
List all preauthorizations for a credit card.
## Examples
preauthorizations = MangoPay.PreAuthorization.all_by_card!("card_id")
"""
def all_by_card! id, query \\ %{} do
_all! [MangoPay.Card.path(id), resource()], query
end
@doc """
List all preauthorizations for a user.
## Examples
user_id = Id of a user object
query = %{
"Page": 1,
"Per_Page": 25,
"Sort": "CreationDate:DESC",
"ResultCode": "000000,009199",
"Status": "CREATED",
"PaymentStatus": "WAITING"
}
{:ok, preauthorizations} = MangoPay.PreAuthorization.all_by_user(user_id, query)
"""
def all_by_user id, query \\ %{} do
_all [MangoPay.User.path(id), resource()], query
end
@doc """
List all preauthorizations for a user.
## Examples
user_id = Id of a user
query = %{
"Page": 1,
"Per_Page": 25,
"Sort": "CreationDate:DESC",
"ResultCode": "000000,009199",
"Status": "CREATED",
"PaymentStatus": "WAITING"
}
preauthorizations = MangoPay.PreAuthorization.all_by_user!(user_id, query)
"""
def all_by_user! id, query \\ %{} do
_all! [MangoPay.User.path(id), resource()], query
end
end
| 23.393617 | 139 | 0.552979 |
086342f12c1d6015f9268b439bd2adf74e3bd22c | 136 | exs | Elixir | start_point/test/hiker_test.exs | cyber-dojo-start-points/elixir-exunit | ebc7a55024105e368b700aa212bfd668f6011665 | [
"BSD-2-Clause"
] | null | null | null | start_point/test/hiker_test.exs | cyber-dojo-start-points/elixir-exunit | ebc7a55024105e368b700aa212bfd668f6011665 | [
"BSD-2-Clause"
] | null | null | null | start_point/test/hiker_test.exs | cyber-dojo-start-points/elixir-exunit | ebc7a55024105e368b700aa212bfd668f6011665 | [
"BSD-2-Clause"
] | null | null | null | defmodule HIKERTest do
use ExUnit.Case
test "life the universe and everything" do
assert HIKER.answer == 42
end
end
| 15.111111 | 45 | 0.676471 |
08636f846b3898fb5ec502f42fb4b4a31cd16aef | 1,468 | exs | Elixir | test/sentry_test.exs | mbta/sentry-elixir | ce417a69efec0eeb968a3c8fdcd61d3115c69875 | [
"MIT"
] | null | null | null | test/sentry_test.exs | mbta/sentry-elixir | ce417a69efec0eeb968a3c8fdcd61d3115c69875 | [
"MIT"
] | null | null | null | test/sentry_test.exs | mbta/sentry-elixir | ce417a69efec0eeb968a3c8fdcd61d3115c69875 | [
"MIT"
] | null | null | null | defmodule SentryTest do
use ExUnit.Case
import ExUnit.CaptureLog
import Sentry.TestEnvironmentHelper
test "excludes events properly" do
bypass = Bypass.open
Bypass.expect bypass, fn conn ->
{:ok, body, conn} = Plug.Conn.read_body(conn)
assert body =~ "RuntimeError"
assert conn.request_path == "/api/1/store/"
assert conn.method == "POST"
Plug.Conn.resp(conn, 200, ~s<{"id": "340"}>)
end
modify_env(:sentry, filter: Sentry.TestFilter, dsn: "http://public:secret@localhost:#{bypass.port}/1", client: Sentry.Client)
assert {:ok, _} = Sentry.capture_exception(%RuntimeError{message: "error"}, [event_source: :plug, result: :sync])
assert :excluded = Sentry.capture_exception(%ArithmeticError{message: "error"}, [event_source: :plug, result: :sync])
assert {:ok, _} = Sentry.capture_message("RuntimeError: error", [event_source: :plug, result: :sync])
end
test "errors when taking too long to receive response" do
bypass = Bypass.open
Bypass.expect bypass, fn conn ->
:timer.sleep(100)
assert conn.request_path == "/api/1/store/"
assert conn.method == "POST"
Plug.Conn.send_resp(conn, 200, ~s<{"id": "340"}>)
end
modify_env(:sentry, filter: Sentry.TestFilter, dsn: "http://public:secret@localhost:#{bypass.port}/1")
assert capture_log(fn ->
assert :error = Sentry.capture_message("error", [])
end) =~ "Failed to send Sentry event"
Bypass.pass(bypass)
end
end
| 35.804878 | 128 | 0.678474 |
08638e033260f711ddcb1c62af22f8e7503241b9 | 820 | exs | Elixir | priv/repo/migrations/20170205004943_create_stock.exs | neilfulwiler/open_pantry | 4b705f2282c7b2365a784503c9f1bdd34c741798 | [
"MIT"
] | 41 | 2017-10-04T00:33:46.000Z | 2021-04-09T01:33:34.000Z | priv/repo/migrations/20170205004943_create_stock.exs | openpantry/open_pantry | 27d898a65dd6f44b325f48d41bc448bb486d9c6f | [
"MIT"
] | 74 | 2017-09-20T03:36:17.000Z | 2018-11-20T20:46:16.000Z | priv/repo/migrations/20170205004943_create_stock.exs | neilfulwiler/open_pantry | 4b705f2282c7b2365a784503c9f1bdd34c741798 | [
"MIT"
] | 12 | 2017-10-04T10:02:49.000Z | 2021-12-28T22:57:20.000Z | defmodule OpenPantry.Repo.Migrations.CreateStock do
use Ecto.Migration
def change do
create table(:stocks) do
add :quantity, :integer
add :arrival, :utc_datetime
add :expiration, :utc_datetime
add :reorder_quantity, :integer
add :aisle, :string
add :row, :string
add :shelf, :string
add :packaging, :string
add :credits_per_package, :integer
add :food_id, references(:foods, on_delete: :nothing, column: :ndb_no, type: :string), null: false
add :meal_id, references(:meals, on_delete: :nothing)
add :offer_id, references(:offers, on_delete: :nothing)
add :facility_id, references(:facilities, on_delete: :nothing)
timestamps()
end
create index(:stocks, [:food_id])
create index(:stocks, [:facility_id])
end
end
| 30.37037 | 104 | 0.667073 |
0863b36b0796ce9feb21994f6f7b9d10e4523916 | 1,957 | exs | Elixir | lib/logger/test/logger/formatter_test.exs | sunaku/elixir | 8aa43eaedd76be8ac0d495049eb9ecd56971f4fe | [
"Apache-2.0"
] | null | null | null | lib/logger/test/logger/formatter_test.exs | sunaku/elixir | 8aa43eaedd76be8ac0d495049eb9ecd56971f4fe | [
"Apache-2.0"
] | null | null | null | lib/logger/test/logger/formatter_test.exs | sunaku/elixir | 8aa43eaedd76be8ac0d495049eb9ecd56971f4fe | [
"Apache-2.0"
] | null | null | null | defmodule Logger.FormatterTest do
use Logger.Case, async: true
doctest Logger.Formatter
import Logger.Formatter
defmodule CompileMod do
def format(_level, _msg, _ts, _md) do
true
end
end
test "compile/1 with nil" do
assert compile(nil) ==
[:time, " ", :metadata, "[", :level, "] ", :levelpad, :message, "\n"]
end
test "compile/1 with str" do
assert compile("$level $time $date $metadata $message $node") ==
Enum.intersperse([:level, :time, :date, :metadata, :message, :node], " ")
assert_raise ArgumentError,"$bad is an invalid format pattern.", fn ->
compile("$bad $good")
end
end
test "compile/1 with {mod, fun}" do
assert compile({CompileMod, :format}) == {CompileMod, :format}
end
test "format with {mod, fun}" do
assert format({CompileMod, :format}, nil, nil, nil,nil) == true
end
test "format with format string" do
compiled = compile("[$level] $message")
assert format(compiled, :error, "hello", nil, []) ==
["[", "error", "] ", "hello"]
compiled = compile("$node")
assert format(compiled, :error, nil, nil, []) == [Atom.to_string(node())]
compiled = compile("$metadata")
assert IO.iodata_to_binary(format(compiled, :error, nil, nil, [meta: :data])) ==
"meta=data "
assert IO.iodata_to_binary(format(compiled, :error, nil, nil, [])) ==
""
timestamp = {{2014, 12, 30}, {12, 6, 30, 100}}
compiled = compile("$date $time")
assert IO.iodata_to_binary(format(compiled, :error, nil, timestamp, [])) ==
"2014-12-30 12:06:30.100"
end
test "padding takes account of length of level" do
compiled = compile("[$level] $levelpad $message")
assert format(compiled, :error, "hello", nil, []) ==
["[", "error", "] ", "", " ", "hello"]
assert format(compiled, :info, "hello", nil, []) ==
["[", "info", "] ", " ", " ", "hello"]
end
end
| 30.107692 | 84 | 0.584568 |
0863b801c493e6f072881eb56f1fb9bfdb504d0d | 1,309 | exs | Elixir | apps/ewallet_api/test/ewallet_api/v1/views/settings_view_test.exs | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 322 | 2018-02-28T07:38:44.000Z | 2020-05-27T23:09:55.000Z | apps/ewallet_api/test/ewallet_api/v1/views/settings_view_test.exs | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 643 | 2018-02-28T12:05:20.000Z | 2020-05-22T08:34:38.000Z | apps/ewallet_api/test/ewallet_api/v1/views/settings_view_test.exs | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 63 | 2018-02-28T10:57:06.000Z | 2020-05-27T23:10:38.000Z | # Copyright 2018-2019 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule EWalletAPI.V1.SettingsViewTest do
use EWalletAPI.ViewCase, :v1
alias EWallet.Web.V1.TokenSerializer
alias EWalletAPI.V1.SettingsView
describe "EWalletAPI.V1.SettingsView.render/2" do
test "renders settings.json with correct structure" do
token1 = build(:token)
token2 = build(:token)
expected = %{
version: @expected_version,
success: true,
data: %{
object: "setting",
tokens: [
TokenSerializer.serialize(token1),
TokenSerializer.serialize(token2)
]
}
}
settings = %{tokens: [token1, token2]}
assert SettingsView.render("settings.json", settings) == expected
end
end
end
| 31.166667 | 74 | 0.686784 |
0863b8189699add019e989a0855f83e4a5504945 | 722 | exs | Elixir | umbrella/apps/core/mix.exs | adamsnyk/elixir-goof | 73a59a681205a440401fdc0eb76f058d30487508 | [
"Apache-2.0"
] | null | null | null | umbrella/apps/core/mix.exs | adamsnyk/elixir-goof | 73a59a681205a440401fdc0eb76f058d30487508 | [
"Apache-2.0"
] | null | null | null | umbrella/apps/core/mix.exs | adamsnyk/elixir-goof | 73a59a681205a440401fdc0eb76f058d30487508 | [
"Apache-2.0"
] | 1 | 2021-11-29T16:27:10.000Z | 2021-11-29T16:27:10.000Z | defmodule Core.MixProject do
use Mix.Project
def project do
[
app: :core,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.7",
elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
def application do
[
extra_applications: [:logger],
mod: {Core.Application, []}
]
end
defp deps do
[
{:coherence, "0.5.1"},
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test"]
defp elixirc_paths(_), do: ["lib"]
end
| 20.055556 | 53 | 0.549861 |
0863bf79b3f7459150c9c1d5d7ff6ba331a1a898 | 662 | ex | Elixir | onboarding/service/web/models/merchant_application_business_profile.ex | FoxComm/highlander | 1aaf8f9e5353b94c34d574c2a92206a1c363b5be | [
"MIT"
] | 10 | 2018-04-12T22:29:52.000Z | 2021-10-18T17:07:45.000Z | onboarding/service/web/models/merchant_application_business_profile.ex | FoxComm/highlander | 1aaf8f9e5353b94c34d574c2a92206a1c363b5be | [
"MIT"
] | null | null | null | onboarding/service/web/models/merchant_application_business_profile.ex | FoxComm/highlander | 1aaf8f9e5353b94c34d574c2a92206a1c363b5be | [
"MIT"
] | 1 | 2018-07-06T18:42:05.000Z | 2018-07-06T18:42:05.000Z | defmodule OnboardingService.MerchantApplicationBusinessProfile do
use OnboardingService.Web, :model
schema "merchant_application_business_profiles" do
belongs_to :merchant_application, OnboardingService.MerchantApplication
belongs_to :business_profile, OnboardingService.BusinessProfile
end
@required_fields ~w(merchant_application_id business_profile_id)a
@optional_fields ~w()a
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields ++ @optional_fields)
|> validate_required_code(@required_fields)
|> unique_constraint_code(:merchant_application_id, name: :merch_app_business_index)
end
end
| 33.1 | 88 | 0.800604 |
0863d534a2747ceebfd24f442a550ec20e56a869 | 19,986 | ex | Elixir | lib/codes/codes_s74.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_s74.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_s74.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_S74 do
alias IcdCode.ICDCode
def _S7400XA do
%ICDCode{full_code: "S7400XA",
category_code: "S74",
short_code: "00XA",
full_name: "Injury of sciatic nerve at hip and thigh level, unspecified leg, initial encounter",
short_name: "Injury of sciatic nerve at hip and thigh level, unspecified leg, initial encounter",
category_name: "Injury of sciatic nerve at hip and thigh level, unspecified leg, initial encounter"
}
end
def _S7400XD do
%ICDCode{full_code: "S7400XD",
category_code: "S74",
short_code: "00XD",
full_name: "Injury of sciatic nerve at hip and thigh level, unspecified leg, subsequent encounter",
short_name: "Injury of sciatic nerve at hip and thigh level, unspecified leg, subsequent encounter",
category_name: "Injury of sciatic nerve at hip and thigh level, unspecified leg, subsequent encounter"
}
end
def _S7400XS do
%ICDCode{full_code: "S7400XS",
category_code: "S74",
short_code: "00XS",
full_name: "Injury of sciatic nerve at hip and thigh level, unspecified leg, sequela",
short_name: "Injury of sciatic nerve at hip and thigh level, unspecified leg, sequela",
category_name: "Injury of sciatic nerve at hip and thigh level, unspecified leg, sequela"
}
end
def _S7401XA do
%ICDCode{full_code: "S7401XA",
category_code: "S74",
short_code: "01XA",
full_name: "Injury of sciatic nerve at hip and thigh level, right leg, initial encounter",
short_name: "Injury of sciatic nerve at hip and thigh level, right leg, initial encounter",
category_name: "Injury of sciatic nerve at hip and thigh level, right leg, initial encounter"
}
end
def _S7401XD do
%ICDCode{full_code: "S7401XD",
category_code: "S74",
short_code: "01XD",
full_name: "Injury of sciatic nerve at hip and thigh level, right leg, subsequent encounter",
short_name: "Injury of sciatic nerve at hip and thigh level, right leg, subsequent encounter",
category_name: "Injury of sciatic nerve at hip and thigh level, right leg, subsequent encounter"
}
end
def _S7401XS do
%ICDCode{full_code: "S7401XS",
category_code: "S74",
short_code: "01XS",
full_name: "Injury of sciatic nerve at hip and thigh level, right leg, sequela",
short_name: "Injury of sciatic nerve at hip and thigh level, right leg, sequela",
category_name: "Injury of sciatic nerve at hip and thigh level, right leg, sequela"
}
end
def _S7402XA do
%ICDCode{full_code: "S7402XA",
category_code: "S74",
short_code: "02XA",
full_name: "Injury of sciatic nerve at hip and thigh level, left leg, initial encounter",
short_name: "Injury of sciatic nerve at hip and thigh level, left leg, initial encounter",
category_name: "Injury of sciatic nerve at hip and thigh level, left leg, initial encounter"
}
end
def _S7402XD do
%ICDCode{full_code: "S7402XD",
category_code: "S74",
short_code: "02XD",
full_name: "Injury of sciatic nerve at hip and thigh level, left leg, subsequent encounter",
short_name: "Injury of sciatic nerve at hip and thigh level, left leg, subsequent encounter",
category_name: "Injury of sciatic nerve at hip and thigh level, left leg, subsequent encounter"
}
end
def _S7402XS do
%ICDCode{full_code: "S7402XS",
category_code: "S74",
short_code: "02XS",
full_name: "Injury of sciatic nerve at hip and thigh level, left leg, sequela",
short_name: "Injury of sciatic nerve at hip and thigh level, left leg, sequela",
category_name: "Injury of sciatic nerve at hip and thigh level, left leg, sequela"
}
end
def _S7410XA do
%ICDCode{full_code: "S7410XA",
category_code: "S74",
short_code: "10XA",
full_name: "Injury of femoral nerve at hip and thigh level, unspecified leg, initial encounter",
short_name: "Injury of femoral nerve at hip and thigh level, unspecified leg, initial encounter",
category_name: "Injury of femoral nerve at hip and thigh level, unspecified leg, initial encounter"
}
end
def _S7410XD do
%ICDCode{full_code: "S7410XD",
category_code: "S74",
short_code: "10XD",
full_name: "Injury of femoral nerve at hip and thigh level, unspecified leg, subsequent encounter",
short_name: "Injury of femoral nerve at hip and thigh level, unspecified leg, subsequent encounter",
category_name: "Injury of femoral nerve at hip and thigh level, unspecified leg, subsequent encounter"
}
end
def _S7410XS do
%ICDCode{full_code: "S7410XS",
category_code: "S74",
short_code: "10XS",
full_name: "Injury of femoral nerve at hip and thigh level, unspecified leg, sequela",
short_name: "Injury of femoral nerve at hip and thigh level, unspecified leg, sequela",
category_name: "Injury of femoral nerve at hip and thigh level, unspecified leg, sequela"
}
end
def _S7411XA do
%ICDCode{full_code: "S7411XA",
category_code: "S74",
short_code: "11XA",
full_name: "Injury of femoral nerve at hip and thigh level, right leg, initial encounter",
short_name: "Injury of femoral nerve at hip and thigh level, right leg, initial encounter",
category_name: "Injury of femoral nerve at hip and thigh level, right leg, initial encounter"
}
end
def _S7411XD do
%ICDCode{full_code: "S7411XD",
category_code: "S74",
short_code: "11XD",
full_name: "Injury of femoral nerve at hip and thigh level, right leg, subsequent encounter",
short_name: "Injury of femoral nerve at hip and thigh level, right leg, subsequent encounter",
category_name: "Injury of femoral nerve at hip and thigh level, right leg, subsequent encounter"
}
end
def _S7411XS do
%ICDCode{full_code: "S7411XS",
category_code: "S74",
short_code: "11XS",
full_name: "Injury of femoral nerve at hip and thigh level, right leg, sequela",
short_name: "Injury of femoral nerve at hip and thigh level, right leg, sequela",
category_name: "Injury of femoral nerve at hip and thigh level, right leg, sequela"
}
end
def _S7412XA do
%ICDCode{full_code: "S7412XA",
category_code: "S74",
short_code: "12XA",
full_name: "Injury of femoral nerve at hip and thigh level, left leg, initial encounter",
short_name: "Injury of femoral nerve at hip and thigh level, left leg, initial encounter",
category_name: "Injury of femoral nerve at hip and thigh level, left leg, initial encounter"
}
end
def _S7412XD do
%ICDCode{full_code: "S7412XD",
category_code: "S74",
short_code: "12XD",
full_name: "Injury of femoral nerve at hip and thigh level, left leg, subsequent encounter",
short_name: "Injury of femoral nerve at hip and thigh level, left leg, subsequent encounter",
category_name: "Injury of femoral nerve at hip and thigh level, left leg, subsequent encounter"
}
end
def _S7412XS do
%ICDCode{full_code: "S7412XS",
category_code: "S74",
short_code: "12XS",
full_name: "Injury of femoral nerve at hip and thigh level, left leg, sequela",
short_name: "Injury of femoral nerve at hip and thigh level, left leg, sequela",
category_name: "Injury of femoral nerve at hip and thigh level, left leg, sequela"
}
end
def _S7420XA do
%ICDCode{full_code: "S7420XA",
category_code: "S74",
short_code: "20XA",
full_name: "Injury of cutaneous sensory nerve at hip and thigh level, unspecified leg, initial encounter",
short_name: "Injury of cutaneous sensory nerve at hip and thigh level, unspecified leg, initial encounter",
category_name: "Injury of cutaneous sensory nerve at hip and thigh level, unspecified leg, initial encounter"
}
end
def _S7420XD do
%ICDCode{full_code: "S7420XD",
category_code: "S74",
short_code: "20XD",
full_name: "Injury of cutaneous sensory nerve at hip and thigh level, unspecified leg, subsequent encounter",
short_name: "Injury of cutaneous sensory nerve at hip and thigh level, unspecified leg, subsequent encounter",
category_name: "Injury of cutaneous sensory nerve at hip and thigh level, unspecified leg, subsequent encounter"
}
end
def _S7420XS do
%ICDCode{full_code: "S7420XS",
category_code: "S74",
short_code: "20XS",
full_name: "Injury of cutaneous sensory nerve at hip and thigh level, unspecified leg, sequela",
short_name: "Injury of cutaneous sensory nerve at hip and thigh level, unspecified leg, sequela",
category_name: "Injury of cutaneous sensory nerve at hip and thigh level, unspecified leg, sequela"
}
end
def _S7421XA do
%ICDCode{full_code: "S7421XA",
category_code: "S74",
short_code: "21XA",
full_name: "Injury of cutaneous sensory nerve at hip and high level, right leg, initial encounter",
short_name: "Injury of cutaneous sensory nerve at hip and high level, right leg, initial encounter",
category_name: "Injury of cutaneous sensory nerve at hip and high level, right leg, initial encounter"
}
end
def _S7421XD do
%ICDCode{full_code: "S7421XD",
category_code: "S74",
short_code: "21XD",
full_name: "Injury of cutaneous sensory nerve at hip and high level, right leg, subsequent encounter",
short_name: "Injury of cutaneous sensory nerve at hip and high level, right leg, subsequent encounter",
category_name: "Injury of cutaneous sensory nerve at hip and high level, right leg, subsequent encounter"
}
end
def _S7421XS do
%ICDCode{full_code: "S7421XS",
category_code: "S74",
short_code: "21XS",
full_name: "Injury of cutaneous sensory nerve at hip and high level, right leg, sequela",
short_name: "Injury of cutaneous sensory nerve at hip and high level, right leg, sequela",
category_name: "Injury of cutaneous sensory nerve at hip and high level, right leg, sequela"
}
end
def _S7422XA do
%ICDCode{full_code: "S7422XA",
category_code: "S74",
short_code: "22XA",
full_name: "Injury of cutaneous sensory nerve at hip and thigh level, left leg, initial encounter",
short_name: "Injury of cutaneous sensory nerve at hip and thigh level, left leg, initial encounter",
category_name: "Injury of cutaneous sensory nerve at hip and thigh level, left leg, initial encounter"
}
end
def _S7422XD do
%ICDCode{full_code: "S7422XD",
category_code: "S74",
short_code: "22XD",
full_name: "Injury of cutaneous sensory nerve at hip and thigh level, left leg, subsequent encounter",
short_name: "Injury of cutaneous sensory nerve at hip and thigh level, left leg, subsequent encounter",
category_name: "Injury of cutaneous sensory nerve at hip and thigh level, left leg, subsequent encounter"
}
end
def _S7422XS do
%ICDCode{full_code: "S7422XS",
category_code: "S74",
short_code: "22XS",
full_name: "Injury of cutaneous sensory nerve at hip and thigh level, left leg, sequela",
short_name: "Injury of cutaneous sensory nerve at hip and thigh level, left leg, sequela",
category_name: "Injury of cutaneous sensory nerve at hip and thigh level, left leg, sequela"
}
end
def _S748X1A do
%ICDCode{full_code: "S748X1A",
category_code: "S74",
short_code: "8X1A",
full_name: "Injury of other nerves at hip and thigh level, right leg, initial encounter",
short_name: "Injury of other nerves at hip and thigh level, right leg, initial encounter",
category_name: "Injury of other nerves at hip and thigh level, right leg, initial encounter"
}
end
def _S748X1D do
%ICDCode{full_code: "S748X1D",
category_code: "S74",
short_code: "8X1D",
full_name: "Injury of other nerves at hip and thigh level, right leg, subsequent encounter",
short_name: "Injury of other nerves at hip and thigh level, right leg, subsequent encounter",
category_name: "Injury of other nerves at hip and thigh level, right leg, subsequent encounter"
}
end
def _S748X1S do
%ICDCode{full_code: "S748X1S",
category_code: "S74",
short_code: "8X1S",
full_name: "Injury of other nerves at hip and thigh level, right leg, sequela",
short_name: "Injury of other nerves at hip and thigh level, right leg, sequela",
category_name: "Injury of other nerves at hip and thigh level, right leg, sequela"
}
end
def _S748X2A do
%ICDCode{full_code: "S748X2A",
category_code: "S74",
short_code: "8X2A",
full_name: "Injury of other nerves at hip and thigh level, left leg, initial encounter",
short_name: "Injury of other nerves at hip and thigh level, left leg, initial encounter",
category_name: "Injury of other nerves at hip and thigh level, left leg, initial encounter"
}
end
def _S748X2D do
%ICDCode{full_code: "S748X2D",
category_code: "S74",
short_code: "8X2D",
full_name: "Injury of other nerves at hip and thigh level, left leg, subsequent encounter",
short_name: "Injury of other nerves at hip and thigh level, left leg, subsequent encounter",
category_name: "Injury of other nerves at hip and thigh level, left leg, subsequent encounter"
}
end
def _S748X2S do
%ICDCode{full_code: "S748X2S",
category_code: "S74",
short_code: "8X2S",
full_name: "Injury of other nerves at hip and thigh level, left leg, sequela",
short_name: "Injury of other nerves at hip and thigh level, left leg, sequela",
category_name: "Injury of other nerves at hip and thigh level, left leg, sequela"
}
end
def _S748X9A do
%ICDCode{full_code: "S748X9A",
category_code: "S74",
short_code: "8X9A",
full_name: "Injury of other nerves at hip and thigh level, unspecified leg, initial encounter",
short_name: "Injury of other nerves at hip and thigh level, unspecified leg, initial encounter",
category_name: "Injury of other nerves at hip and thigh level, unspecified leg, initial encounter"
}
end
def _S748X9D do
%ICDCode{full_code: "S748X9D",
category_code: "S74",
short_code: "8X9D",
full_name: "Injury of other nerves at hip and thigh level, unspecified leg, subsequent encounter",
short_name: "Injury of other nerves at hip and thigh level, unspecified leg, subsequent encounter",
category_name: "Injury of other nerves at hip and thigh level, unspecified leg, subsequent encounter"
}
end
def _S748X9S do
%ICDCode{full_code: "S748X9S",
category_code: "S74",
short_code: "8X9S",
full_name: "Injury of other nerves at hip and thigh level, unspecified leg, sequela",
short_name: "Injury of other nerves at hip and thigh level, unspecified leg, sequela",
category_name: "Injury of other nerves at hip and thigh level, unspecified leg, sequela"
}
end
def _S7490XA do
%ICDCode{full_code: "S7490XA",
category_code: "S74",
short_code: "90XA",
full_name: "Injury of unspecified nerve at hip and thigh level, unspecified leg, initial encounter",
short_name: "Injury of unspecified nerve at hip and thigh level, unspecified leg, initial encounter",
category_name: "Injury of unspecified nerve at hip and thigh level, unspecified leg, initial encounter"
}
end
def _S7490XD do
%ICDCode{full_code: "S7490XD",
category_code: "S74",
short_code: "90XD",
full_name: "Injury of unspecified nerve at hip and thigh level, unspecified leg, subsequent encounter",
short_name: "Injury of unspecified nerve at hip and thigh level, unspecified leg, subsequent encounter",
category_name: "Injury of unspecified nerve at hip and thigh level, unspecified leg, subsequent encounter"
}
end
def _S7490XS do
%ICDCode{full_code: "S7490XS",
category_code: "S74",
short_code: "90XS",
full_name: "Injury of unspecified nerve at hip and thigh level, unspecified leg, sequela",
short_name: "Injury of unspecified nerve at hip and thigh level, unspecified leg, sequela",
category_name: "Injury of unspecified nerve at hip and thigh level, unspecified leg, sequela"
}
end
def _S7491XA do
%ICDCode{full_code: "S7491XA",
category_code: "S74",
short_code: "91XA",
full_name: "Injury of unspecified nerve at hip and thigh level, right leg, initial encounter",
short_name: "Injury of unspecified nerve at hip and thigh level, right leg, initial encounter",
category_name: "Injury of unspecified nerve at hip and thigh level, right leg, initial encounter"
}
end
def _S7491XD do
%ICDCode{full_code: "S7491XD",
category_code: "S74",
short_code: "91XD",
full_name: "Injury of unspecified nerve at hip and thigh level, right leg, subsequent encounter",
short_name: "Injury of unspecified nerve at hip and thigh level, right leg, subsequent encounter",
category_name: "Injury of unspecified nerve at hip and thigh level, right leg, subsequent encounter"
}
end
def _S7491XS do
%ICDCode{full_code: "S7491XS",
category_code: "S74",
short_code: "91XS",
full_name: "Injury of unspecified nerve at hip and thigh level, right leg, sequela",
short_name: "Injury of unspecified nerve at hip and thigh level, right leg, sequela",
category_name: "Injury of unspecified nerve at hip and thigh level, right leg, sequela"
}
end
def _S7492XA do
%ICDCode{full_code: "S7492XA",
category_code: "S74",
short_code: "92XA",
full_name: "Injury of unspecified nerve at hip and thigh level, left leg, initial encounter",
short_name: "Injury of unspecified nerve at hip and thigh level, left leg, initial encounter",
category_name: "Injury of unspecified nerve at hip and thigh level, left leg, initial encounter"
}
end
def _S7492XD do
%ICDCode{full_code: "S7492XD",
category_code: "S74",
short_code: "92XD",
full_name: "Injury of unspecified nerve at hip and thigh level, left leg, subsequent encounter",
short_name: "Injury of unspecified nerve at hip and thigh level, left leg, subsequent encounter",
category_name: "Injury of unspecified nerve at hip and thigh level, left leg, subsequent encounter"
}
end
def _S7492XS do
%ICDCode{full_code: "S7492XS",
category_code: "S74",
short_code: "92XS",
full_name: "Injury of unspecified nerve at hip and thigh level, left leg, sequela",
short_name: "Injury of unspecified nerve at hip and thigh level, left leg, sequela",
category_name: "Injury of unspecified nerve at hip and thigh level, left leg, sequela"
}
end
end
| 48.509709 | 122 | 0.662514 |
0863dd8d51535a50f4444080907be6e2617ff7c7 | 688 | ex | Elixir | lib/grafanawebhook_web/live/index.ex | juanpabloaj/grafana-webhook-monitor | 5ee5048d572bf0e42d6464c3096c0842c23b69d4 | [
"MIT"
] | 2 | 2019-10-31T16:22:36.000Z | 2020-04-29T19:31:42.000Z | lib/grafanawebhook_web/live/index.ex | juanpabloaj/grafana-webhook-monitor | 5ee5048d572bf0e42d6464c3096c0842c23b69d4 | [
"MIT"
] | 4 | 2019-10-16T20:13:41.000Z | 2021-05-10T16:54:26.000Z | lib/grafanawebhook_web/live/index.ex | juanpabloaj/grafana-webhook-monitor | 5ee5048d572bf0e42d6464c3096c0842c23b69d4 | [
"MIT"
] | null | null | null | defmodule GrafanawebhookWeb.Live.Index do
use Phoenix.LiveView
alias Grafanawebhook.Dashboard
def mount(_session, socket) do
if connected?(socket), do: Dashboard.subscribe()
{:ok, fetch(socket)}
end
def render(assigns) do
GrafanawebhookWeb.DashboardView.render("index.html", assigns)
end
def fetch(socket, user_name \\ nil) do
assign(socket, %{
user_name: user_name,
messages: Dashboard.list_messages()
})
end
def handle_info({Dashboard, [:message, _event_type], _message}, socket) do
{:noreply, fetch(socket, get_user_name(socket))}
end
defp get_user_name(socket) do
socket.assigns
|> Map.get(:user_name)
end
end
| 22.193548 | 76 | 0.697674 |
0863f0e93c5eecdd46b03b36416c298833d25382 | 12,344 | exs | Elixir | test/plug/router_test.exs | CrowdHailer/plug | 22c96e556b83583bf56247c596ba137725f48bad | [
"Apache-2.0"
] | null | null | null | test/plug/router_test.exs | CrowdHailer/plug | 22c96e556b83583bf56247c596ba137725f48bad | [
"Apache-2.0"
] | null | null | null | test/plug/router_test.exs | CrowdHailer/plug | 22c96e556b83583bf56247c596ba137725f48bad | [
"Apache-2.0"
] | null | null | null | defmodule Plug.RouterTest do
defmodule Forward do
use Plug.Router
use Plug.ErrorHandler
plug :match
plug :dispatch
def call(conn, opts) do
super(conn, opts)
after
Process.put(:plug_forward_call, true)
end
get "/" do
resp(conn, 200, "forwarded")
end
get "/script_name" do
resp(conn, 200, Enum.join(conn.script_name, ","))
end
match "/params" do
resp(conn, 200, conn.params["param"])
end
match "/throw", via: [:get, :post] do
_ = conn
throw(:oops)
end
match "/raise" do
_ = conn
raise Plug.Parsers.RequestTooLargeError
end
match "/send_and_exit" do
send_resp(conn, 200, "ok")
exit(:oops)
end
match "/fancy_id/:id" do
send_resp(conn, 200, id <> "--" <> List.last(conn.path_info))
end
def handle_errors(conn, assigns) do
# Custom call is always invoked before
true = Process.get(:plug_forward_call)
Process.put(:plug_handle_errors, Map.put(assigns, :status, conn.status))
super(conn, assigns)
end
end
defmodule Reforward do
use Plug.Router
use Plug.ErrorHandler
plug :match
plug :dispatch
forward "/step2", to: Forward
end
defmodule SamplePlug do
import Plug.Conn
def init(:hello), do: :world
def init(options), do: options
def call(conn, options) do
send_resp(conn, 200, "#{inspect(options)}")
end
end
defmodule Sample do
use Plug.Router
use Plug.ErrorHandler
plug :match
plug :verify_router_options
plug :dispatch
get "/", host: "foo.bar", do: resp(conn, 200, "foo.bar root")
get "/", host: "foo.", do: resp(conn, 200, "foo.* root")
forward "/", to: Forward, host: "foo."
get "/" do
resp(conn, 200, "root")
end
get "/1/bar" do
resp(conn, 200, "ok")
end
get "/2/:bar" do
resp(conn, 200, inspect(bar))
end
get "/3/bar-:bar" do
resp(conn, 200, inspect(bar))
end
get "/4/*bar" do
resp(conn, 200, inspect(bar))
end
get "/5/bar-*bar" do
resp(conn, 200, inspect(bar))
end
match "/6/bar" do
resp(conn, 200, "ok")
end
get "/7/:bar" when byte_size(bar) <= 3,
some_option: :hello,
do: resp(conn, 200, inspect(bar))
get "/8/bar baz/:bat" do
resp(conn, 200, bat)
end
plug = SamplePlug
opts = :hello
get "/plug/match", to: SamplePlug
get "/plug/match/options", to: plug, init_opts: opts
forward "/step1", to: Reforward
forward "/forward", to: Forward
forward "/nested/forward", to: Forward
match "/params/get/:param" do
resp(conn, 200, conn.params["param"])
end
forward "/params/forward/:param", to: Forward
get "/options/map", private: %{an_option: :a_value} do
resp(conn, 200, inspect(conn.private))
end
get "/options/assigns", assigns: %{an_option: :a_value} do
resp(conn, 200, inspect(conn.assigns))
end
forward "/options/forward",
to: Forward,
private: %{an_option: :a_value},
assigns: %{another_option: :another_value}
plug = SamplePlug
opts = :hello
forward "/plug/forward", to: SamplePlug
forward "/plug/init_opts", to: plug, init_opts: opts, private: %{baz: :qux}
forward "/plug/forward_local", to: :forward_local
forward "/plug/forward_local_opts", to: :forward_local, init_opts: opts, private: %{baz: :qux}
def forward_local(conn, opts) do
resp(conn, 200, "#{inspect(opts)}")
end
match _ do
resp(conn, 404, "oops")
end
defp verify_router_options(conn, _opts) do
if conn.path_info == ["options", "map"] and is_nil(conn.private[:an_option]) do
raise "should be able to read option after match"
end
conn
end
end
use ExUnit.Case, async: true
use Plug.Test
test "dispatch root" do
conn = call(Sample, conn(:get, "/"))
assert conn.resp_body == "root"
end
test "dispatch literal segment" do
conn = call(Sample, conn(:get, "/1/bar"))
assert conn.resp_body == "ok"
end
test "dispatch dynamic segment" do
conn = call(Sample, conn(:get, "/2/value"))
assert conn.resp_body == ~s("value")
end
test "dispatch dynamic segment with prefix" do
conn = call(Sample, conn(:get, "/3/bar-value"))
assert conn.resp_body == ~s("value")
end
test "dispatch glob segment" do
conn = call(Sample, conn(:get, "/4/value"))
assert conn.resp_body == ~s(["value"])
conn = call(Sample, conn(:get, "/4/value/extra"))
assert conn.resp_body == ~s(["value", "extra"])
end
test "dispatch glob segment with prefix" do
conn = call(Sample, conn(:get, "/5/bar-value/extra"))
assert conn.resp_body == ~s(["bar-value", "extra"])
end
test "dispatch custom route" do
conn = call(Sample, conn(:get, "/6/bar"))
assert conn.resp_body == "ok"
end
test "dispatch with guards" do
conn = call(Sample, conn(:get, "/7/a"))
assert conn.resp_body == ~s("a")
conn = call(Sample, conn(:get, "/7/ab"))
assert conn.resp_body == ~s("ab")
conn = call(Sample, conn(:get, "/7/abc"))
assert conn.resp_body == ~s("abc")
conn = call(Sample, conn(:get, "/7/abcd"))
assert conn.resp_body == "oops"
end
test "dispatch after decoding guards" do
conn = call(Sample, conn(:get, "/8/bar baz/bat"))
assert conn.resp_body == "bat"
conn = call(Sample, conn(:get, "/8/bar%20baz/bat bag"))
assert conn.resp_body == "bat bag"
conn = call(Sample, conn(:get, "/8/bar%20baz/bat%20bag"))
assert conn.resp_body == "bat bag"
end
test "dispatch wrong verb" do
conn = call(Sample, conn(:post, "/1/bar"))
assert conn.resp_body == "oops"
end
test "dispatch to plug" do
conn = call(Sample, conn(:get, "/plug/match"))
assert conn.resp_body == "[]"
end
test "dispatch to plug with options" do
conn = call(Sample, conn(:get, "/plug/match/options"))
assert conn.resp_body == ":world"
end
test "dispatch with forwarding" do
conn = call(Sample, conn(:get, "/forward"))
assert conn.resp_body == "forwarded"
assert conn.path_info == ["forward"]
end
test "dispatch with forwarding with custom call" do
call(Sample, conn(:get, "/forward"))
assert Process.get(:plug_forward_call, true)
end
test "dispatch with forwarding including slashes" do
conn = call(Sample, conn(:get, "/nested/forward"))
assert conn.resp_body == "forwarded"
assert conn.path_info == ["nested", "forward"]
end
test "dispatch with forwarding handles urlencoded path segments" do
conn = call(Sample, conn(:get, "/nested/forward/fancy_id/%2BANcgj1jZc%2F9O%2B"))
assert conn.resp_body == "+ANcgj1jZc/9O+--%2BANcgj1jZc%2F9O%2B"
end
test "dispatch with forwarding handles un-urlencoded path segments" do
conn = call(Sample, conn(:get, "/nested/forward/fancy_id/+ANcgj1jZc9O+"))
assert conn.resp_body == "+ANcgj1jZc9O+--+ANcgj1jZc9O+"
end
test "dispatch with forwarding modifies script_name" do
conn = call(Sample, conn(:get, "/nested/forward/script_name"))
assert conn.resp_body == "nested,forward"
conn = call(Sample, conn(:get, "/step1/step2/script_name"))
assert conn.resp_body == "step1,step2"
end
test "dispatch any verb" do
conn = call(Sample, conn(:get, "/6/bar"))
assert conn.resp_body == "ok"
conn = call(Sample, conn(:post, "/6/bar"))
assert conn.resp_body == "ok"
conn = call(Sample, conn(:put, "/6/bar"))
assert conn.resp_body == "ok"
conn = call(Sample, conn(:patch, "/6/bar"))
assert conn.resp_body == "ok"
conn = call(Sample, conn(:delete, "/6/bar"))
assert conn.resp_body == "ok"
conn = call(Sample, conn(:options, "/6/bar"))
assert conn.resp_body == "ok"
conn = call(Sample, conn(:unknown, "/6/bar"))
assert conn.resp_body == "ok"
end
test "dispatches based on host" do
conn = call(Sample, conn(:get, "http://foo.bar/"))
assert conn.resp_body == "foo.bar root"
conn = call(Sample, conn(:get, "http://foo.other/"))
assert conn.resp_body == "foo.* root"
conn = call(Sample, conn(:get, "http://foo.other/script_name"))
assert conn.resp_body == ""
end
test "dispatch not found" do
conn = call(Sample, conn(:get, "/unknown"))
assert conn.status == 404
assert conn.resp_body == "oops"
end
@already_sent {:plug_conn, :sent}
test "handle errors" do
try do
call(Sample, conn(:get, "/forward/throw"))
flunk("oops")
catch
:throw, :oops ->
assert_received @already_sent
assigns = Process.get(:plug_handle_errors)
assert assigns.status == 500
assert assigns.kind == :throw
assert assigns.reason == :oops
assert is_list(assigns.stack)
end
end
test "handle errors translates exceptions to status code" do
try do
call(Sample, conn(:get, "/forward/raise"))
flunk("oops")
rescue
e in Plug.Conn.WrapperError ->
%{kind: :error, reason: %Plug.Parsers.RequestTooLargeError{}} = e
assert_received @already_sent
assigns = Process.get(:plug_handle_errors)
assert assigns.status == 413
assert assigns.kind == :error
assert assigns.reason.__struct__ == Plug.Parsers.RequestTooLargeError
assert is_list(assigns.stack)
end
end
test "handle errors when response was sent" do
try do
call(Sample, conn(:get, "/forward/send_and_exit"))
flunk("oops")
catch
:exit, :oops ->
assert_received @already_sent
assert is_nil(Process.get(:plug_handle_errors))
end
end
test "match_path/1" do
conn = call(Sample, conn(:get, "/params/get/a_value"))
assert Plug.Router.match_path(conn) == "/params/get/:param"
end
test "match_path/1 on forward to router" do
conn = call(Sample, conn(:get, "/step1/step2/fancy_id/abc123"))
assert Plug.Router.match_path(conn) == "/step1/*glob/step2/*glob/fancy_id/:id"
end
test "assigns path params to conn params and path_params" do
conn = call(Sample, conn(:get, "/params/get/a_value"))
assert conn.params["param"] == "a_value"
assert conn.path_params["param"] == "a_value"
assert conn.resp_body == "a_value"
end
test "assigns path params to conn params and path_params on forward" do
conn = call(Sample, conn(:get, "/params/forward/a_value/params"))
assert conn.params["param"] == "a_value"
assert conn.path_params["param"] == "a_value"
assert conn.resp_body == "a_value"
end
test "path params have priority over body and query params" do
conn =
conn(:post, "/params/get/p_value", "param=b_value")
|> put_req_header("content-type", "application/x-www-form-urlencoded")
|> Plug.Parsers.call(Plug.Parsers.init(parsers: [:urlencoded]))
conn = call(Sample, conn)
assert conn.resp_body == "p_value"
end
test "assigns route options to private conn map" do
conn = call(Sample, conn(:get, "/options/map"))
assert conn.private[:an_option] == :a_value
assert conn.resp_body =~ ~s(an_option: :a_value)
end
test "assigns route options to assigns conn map" do
conn = call(Sample, conn(:get, "/options/assigns"))
assert conn.assigns[:an_option] == :a_value
assert conn.resp_body =~ ~s(an_option: :a_value)
end
test "assigns options on forward" do
conn = call(Sample, conn(:get, "/options/forward"))
assert conn.private[:an_option] == :a_value
assert conn.assigns[:another_option] == :another_value
assert conn.resp_body == "forwarded"
end
test "forwards to a plug" do
conn = call(Sample, conn(:get, "/plug/forward"))
assert conn.resp_body == "[]"
end
test "forwards to a plug with init options" do
conn = call(Sample, conn(:get, "/plug/init_opts"))
assert conn.private[:baz] == :qux
assert conn.resp_body == ":world"
end
test "forwards to a function plug" do
conn = call(Sample, conn(:get, "/plug/forward_local"))
assert conn.resp_body == "[]"
end
test "forwards to a function plug with options" do
conn = call(Sample, conn(:get, "/plug/forward_local_opts"))
assert conn.private[:baz] == :qux
assert conn.resp_body == ":hello"
end
defp call(mod, conn) do
mod.call(conn, [])
end
end
| 27.070175 | 98 | 0.627835 |
086405013878d676f356604ab4da93f45cbd47b9 | 14,299 | ex | Elixir | lib/iex/lib/iex/helpers.ex | Tica2/elixir | 6cf1dcbfe4572fc75619f05e40c10fd0844083ef | [
"Apache-2.0"
] | null | null | null | lib/iex/lib/iex/helpers.ex | Tica2/elixir | 6cf1dcbfe4572fc75619f05e40c10fd0844083ef | [
"Apache-2.0"
] | null | null | null | lib/iex/lib/iex/helpers.ex | Tica2/elixir | 6cf1dcbfe4572fc75619f05e40c10fd0844083ef | [
"Apache-2.0"
] | null | null | null | defmodule IEx.Helpers do
@moduledoc """
Welcome to Interactive Elixir. You are currently
seeing the documentation for the module `IEx.Helpers`
which provides many helpers to make Elixir's shell
more joyful to work with.
This message was triggered by invoking the helper
`h()`, usually referred to as `h/0` (since it expects 0
arguments).
There are many other helpers available:
* `b/1` - prints callbacks info and docs for a given module
* `c/2` — compiles a file at the given path
* `cd/1` — changes the current directory
* `clear/0` — clears the screen
* `flush/0` — flushes all messages sent to the shell
* `h/0` — prints this help message
* `h/1` — prints help for the given module, function or macro
* `l/1` — loads the given module's beam code
* `ls/0` — lists the contents of the current directory
* `ls/1` — lists the contents of the specified directory
* `pid/3` — creates a PID with the 3 integer arguments passed
* `pwd/0` — prints the current working directory
* `r/1` — recompiles and reloads the given module's source file
* `respawn/0` — respawns the current shell
* `s/1` — prints spec information
* `t/1` — prints type information
* `v/0` — retrieves the last value from the history
* `v/1` — retrieves the nth value from the history
* `import_file/1` — evaluates the given file in the shell's context
Help for functions in this module can be consulted
directly from the command line, as an example, try:
h(c/2)
You can also retrieve the documentation for any module
or function. Try these:
h(Enum)
h(Enum.reverse/1)
To discover all available functions for a module, type the module name
followed by a dot, then press tab to trigger autocomplete. For example:
Enum.
To learn more about IEx as a whole, just type `h(IEx)`.
"""
import IEx, only: [dont_display_result: 0]
@doc """
Compiles the given files.
It expects a list of files to compile and an optional path to write
the compiled code to (defaults to the current directory). When compiling
one file, there is no need to wrap it in a list.
It returns the name of the compiled modules.
If you want to recompile an existing module, check `r/1` instead.
## Examples
c ["foo.ex", "bar.ex"], "ebin"
#=> [Foo, Bar]
c "baz.ex"
#=> [Baz]
"""
def c(files, path \\ ".") when is_binary(path) do
files = List.wrap(files)
unless Enum.all?(files, &is_binary/1) do
raise ArgumentError, "expected a binary or a list of binaries as argument"
end
{found, not_found} =
files
|> Enum.map(&Path.expand(&1, path))
|> Enum.partition(&File.exists?/1)
unless Enum.empty?(not_found) do
raise ArgumentError, "could not find files #{Enum.join(not_found, ", ")}"
end
{erls, exs} = Enum.partition(found, &String.ends_with?(&1, ".erl"))
modules = Enum.map(erls, fn(source) ->
{module, binary} = compile_erlang(source)
base = source |> Path.basename |> Path.rootname
File.write!(Path.join(path, base <> ".beam"), binary)
module
end)
modules ++ Kernel.ParallelCompiler.files_to_path(exs, path)
end
@doc """
Clears the console screen.
This function only works if ANSI escape codes are enabled
on the shell, which means this function is by default
unavailable on Windows machines.
"""
def clear do
if IO.ANSI.enabled? do
IO.write [IO.ANSI.home, IO.ANSI.clear]
else
IO.puts "Cannot clear the screen because ANSI escape codes are not enabled on this shell"
end
dont_display_result
end
@doc """
Prints the documentation for `IEx.Helpers`.
"""
def h() do
IEx.Introspection.h(IEx.Helpers)
dont_display_result
end
@doc """
Prints the documentation for the given module
or for the given function/arity pair.
## Examples
h(Enum)
#=> Prints documentation for Enum
It also accepts functions in the format `fun/arity`
and `module.fun/arity`, for example:
h receive/1
h Enum.all?/2
h Enum.all?
"""
@h_modules [__MODULE__, Kernel, Kernel.SpecialForms]
defmacro h(term)
defmacro h({:/, _, [call, arity]} = term) do
args =
case Macro.decompose_call(call) do
{_mod, :__info__, []} when arity == 1 ->
[Module, :__info__, 1]
{mod, fun, []} ->
[mod, fun, arity]
{fun, []} ->
[@h_modules, fun, arity]
_ ->
[term]
end
quote do
IEx.Introspection.h(unquote_splicing(args))
end
end
defmacro h(call) do
args =
case Macro.decompose_call(call) do
{_mod, :__info__, []} ->
[Module, :__info__, 1]
{mod, fun, []} ->
[mod, fun]
{fun, []} ->
[@h_modules, fun]
_ ->
[call]
end
quote do
IEx.Introspection.h(unquote_splicing(args))
end
end
@doc """
Prints the documentation for the given callback function.
It also accepts single module argument to list
all available behaviour callbacks.
## Examples
b(Mix.Task.run/1)
b(Mix.Task.run)
b(Dict)
"""
defmacro b(term)
defmacro b({:/, _, [{{:., _, [mod, fun]}, _, []}, arity]}) do
quote do
IEx.Introspection.b(unquote(mod), unquote(fun), unquote(arity))
end
end
defmacro b({{:., _, [mod, fun]}, _, []}) do
quote do
IEx.Introspection.b(unquote(mod), unquote(fun))
end
end
defmacro b(module) do
quote do
IEx.Introspection.b(unquote(module))
end
end
@doc """
Prints the types for the given module or for the given function/arity pair.
## Examples
t(Enum)
t(Enum.t/0)
t(Enum.t)
"""
defmacro t(term)
defmacro t({:/, _, [{{:., _, [mod, fun]}, _, []}, arity]}) do
quote do
IEx.Introspection.t(unquote(mod), unquote(fun), unquote(arity))
end
end
defmacro t({{:., _, [mod, fun]}, _, []}) do
quote do
IEx.Introspection.t(unquote(mod), unquote(fun))
end
end
defmacro t(module) do
quote do
IEx.Introspection.t(unquote(module))
end
end
@doc """
Prints the specs for the given module or for the given function/arity pair.
## Examples
s(Enum)
s(Enum.all?)
s(Enum.all?/2)
s(is_atom)
s(is_atom/1)
"""
defmacro s(term)
defmacro s({:/, _, [call, arity]} = term) do
args =
case Macro.decompose_call(call) do
{mod, fun, []} -> [mod, fun, arity]
{fun, []} -> [Kernel, fun, arity]
_ -> [term]
end
quote do
IEx.Introspection.s(unquote_splicing(args))
end
end
defmacro s(call) do
args =
case Macro.decompose_call(call) do
{mod, fun, []} -> [mod, fun]
{fun, []} -> [Kernel, fun]
_ -> [call]
end
quote do
IEx.Introspection.s(unquote_splicing(args))
end
end
@doc """
Retrieves the nth expression's value from the history.
Use negative values to lookup expression values relative to the current one.
For instance, v(-1) returns the result of the last evaluated expression.
"""
def v(n \\ -1) do
IEx.History.nth(history, n) |> elem(2)
end
@doc """
Recompiles and reloads the given `module`.
Please note that all the modules defined in the same
file as `module` are recompiled and reloaded.
## In-memory reloading
When we reload the module in IEx, we recompile the module source code,
updating its contents in memory. The original `.beam` file in disk,
probably the one where the first definition of the module came from,
does not change at all.
Since typespecs and docs are loaded from the .beam file (they are not
loaded in memory with the module because there is no need for them to
be in memory), they are not reloaded when you reload the module.
"""
def r(module) when is_atom(module) do
{:reloaded, module, do_r(module)}
end
defp do_r(module) do
unless Code.ensure_loaded?(module) do
raise ArgumentError, "could not load nor find module: #{inspect module}"
end
source = source(module)
cond do
source == nil ->
raise ArgumentError, "could not find source for module: #{inspect module}"
not File.exists?(source) ->
raise ArgumentError, "could not find source (#{source}) for module: #{inspect module}"
String.ends_with?(source, ".erl") ->
[compile_erlang(source) |> elem(0)]
true ->
Enum.map(Code.load_file(source), fn {name, _} -> name end)
end
end
@doc """
Loads the given module's beam code (and ensures any previous
old version was properly purged before).
This function is useful when you know the bytecode for module
has been updated in the filesystem and you want to tell the VM
to load it.
"""
def l(module) when is_atom(module) do
:code.purge(module)
:code.load_file(module)
end
@doc """
Flushes all messages sent to the shell and prints them out.
"""
def flush do
do_flush(IEx.inspect_opts)
end
defp do_flush(inspect_opts) do
receive do
msg ->
IO.inspect(msg, inspect_opts)
do_flush(inspect_opts)
after
0 -> :ok
end
end
defp source(module) do
source = module.module_info(:compile)[:source]
case source do
nil -> nil
source -> List.to_string(source)
end
end
@doc """
Prints the current working directory.
"""
def pwd do
IO.puts IEx.color(:eval_info, System.cwd!)
end
@doc """
Changes the current working directory to the given path.
"""
def cd(directory) when is_binary(directory) do
case File.cd(expand_home(directory)) do
:ok -> pwd
{:error, :enoent} ->
IO.puts IEx.color(:eval_error, "No directory #{directory}")
end
end
@doc """
Produces a simple list of a directory's contents.
If `path` points to a file, prints its full path.
"""
def ls(path \\ ".") when is_binary(path) do
path = expand_home(path)
case File.ls(path) do
{:ok, items} ->
sorted_items = Enum.sort(items)
ls_print(path, sorted_items)
{:error, :enoent} ->
IO.puts IEx.color(:eval_error, "No such file or directory #{path}")
{:error, :enotdir} ->
IO.puts IEx.color(:eval_info, Path.absname(path))
end
end
defp expand_home(<<?~, rest :: binary>>) do
System.user_home! <> rest
end
defp expand_home(other), do: other
defp ls_print(_, []) do
:ok
end
defp ls_print(path, list) do
# print items in multiple columns (2 columns in the worst case)
lengths = Enum.map(list, &String.length(&1))
maxlen = maxlength(lengths)
width = min(maxlen, 30) + 5
ls_print(path, list, width)
end
defp ls_print(path, list, width) do
Enum.reduce(list, 0, fn(item, len) ->
if len >= 80 do
IO.puts ""
len = 0
end
IO.write format_item(Path.join(path, item), String.ljust(item, width))
len+width
end)
IO.puts ""
end
defp maxlength(list) do
Enum.reduce(list, 0, &max(&1, &2))
end
defp format_item(path, representation) do
case File.stat(path) do
{:ok, %File.Stat{type: :device}} ->
IEx.color(:ls_device, representation)
{:ok, %File.Stat{type: :directory}} ->
IEx.color(:ls_directory, representation)
_ ->
representation
end
end
@doc """
Respawns the current shell by starting a new shell process.
Returns `true` if it worked.
"""
def respawn do
if whereis = IEx.Server.whereis do
send whereis, {:respawn, self}
dont_display_result
end
end
@doc """
Evaluates the contents of the file at `path` as if it were directly typed into
the shell.
`path` has to be a literal string. `path` is automatically expanded via
`Path.expand/1`.
## Non-existent files
By default, `import_file/1` fails when the given file does not exist. However,
since this macro is expanded at compile-time, it's not possible to
conditionally import a file since the macro is always expanded:
# This raises a File.Error if ~/.iex.exs doesn't exist.
if ("~/.iex.exs" |> Path.expand |> File.exists?) do
import_file "~/.iex.exs"
end
This is why an `:optional` option can be passed to `import_file/1`. The
default value of this option is `false`, meaning that an exception will be
raised if the given file is missing. If `:optional` is set to `true`, missing
files will be ignored and `import_file/1` will just compile to `nil`.
## Examples
# ~/file.exs
value = 13
# in the shell
iex(1)> import_file "~/file.exs"
13
iex(2)> value
13
iex(3)> import_file "nonexisting.file.ex", optional: true
nil
"""
defmacro import_file(path, opts \\ [])
defmacro import_file(path, opts) when is_binary(path) do
optional? = Keyword.get(opts, :optional, false)
path = Path.expand(path)
if not optional? or File.exists?(path) do
path |> File.read! |> Code.string_to_quoted!(file: path)
end
end
defmacro import_file(_path, _opts) do
raise ArgumentError, "import_file/1 expects a literal binary as its argument"
end
# Compiles and loads an erlang source file, returns {module, binary}
defp compile_erlang(source) do
source = Path.relative_to_cwd(source) |> String.to_char_list
case :compile.file(source, [:binary, :report]) do
{:ok, module, binary} ->
:code.purge(module)
{:module, module} = :code.load_binary(module, source, binary)
{module, binary}
_ ->
raise CompileError
end
end
defp history, do: Process.get(:iex_history)
@doc """
Creates a PID with 3 non negative integers passed as arguments
to the function.
## Examples
iex> pid(0, 21, 32)
#PID<0.21.32>
iex> pid(0, 64, 2048)
#PID<0.64.2048>
"""
def pid(x, y, z) when is_integer(x) and x >= 0 and
is_integer(y) and y >= 0 and
is_integer(z) and z >= 0 do
:c.pid(x, y, z)
end
end
| 25.998182 | 95 | 0.618295 |
08642fc92b4714f5d39f7f191290807f8f0955d3 | 1,601 | ex | Elixir | lib/auxilio_web.ex | HackathonSupport/auxilio | 7afc7372d0fbd902580a567be4cd106ece0d5b9b | [
"MIT"
] | null | null | null | lib/auxilio_web.ex | HackathonSupport/auxilio | 7afc7372d0fbd902580a567be4cd106ece0d5b9b | [
"MIT"
] | 1 | 2018-02-04T02:33:55.000Z | 2018-12-07T11:22:13.000Z | lib/auxilio_web.ex | HackathonSupport/auxilio | 7afc7372d0fbd902580a567be4cd106ece0d5b9b | [
"MIT"
] | null | null | null | defmodule AuxilioWeb do
@moduledoc """
The entrypoint for defining your web interface, such
as controllers, views, channels and so on.
This can be used in your application as:
use AuxilioWeb, :controller
use AuxilioWeb, :view
The definitions below will be executed for every view,
controller, etc, so keep them short and clean, focused
on imports, uses and aliases.
Do NOT define functions inside the quoted expressions
below. Instead, define any helper function in modules
and import those modules here.
"""
def controller do
quote do
use Phoenix.Controller, namespace: AuxilioWeb
import Plug.Conn
import AuxilioWeb.Router.Helpers
import AuxilioWeb.Gettext
end
end
def view do
quote do
use Phoenix.View, root: "lib/auxilio_web/templates",
namespace: AuxilioWeb
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_flash: 2, view_module: 1]
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
import AuxilioWeb.Router.Helpers
import AuxilioWeb.ErrorHelpers
import AuxilioWeb.Gettext
end
end
def router do
quote do
use Phoenix.Router
import Plug.Conn
import Phoenix.Controller
end
end
def channel do
quote do
use Phoenix.Channel
import AuxilioWeb.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.544118 | 69 | 0.686446 |
086454a345b074bcd4b92abdba46b98c15894e8c | 2,219 | ex | Elixir | clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v3/model/search_organizations_response.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v3/model/search_organizations_response.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v3/model/search_organizations_response.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.CloudResourceManager.V3.Model.SearchOrganizationsResponse do
@moduledoc """
The response returned from the `SearchOrganizations` method.
## Attributes
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - A pagination token to be used to retrieve the next page of results. If the result is too large to fit within the page size specified in the request, this field will be set with a token that can be used to fetch the next page of results. If this field is empty, it indicates that this response contains the last page of results.
* `organizations` (*type:* `list(GoogleApi.CloudResourceManager.V3.Model.Organization.t)`, *default:* `nil`) - The list of Organizations that matched the search query, possibly paginated.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:nextPageToken => String.t() | nil,
:organizations => list(GoogleApi.CloudResourceManager.V3.Model.Organization.t()) | nil
}
field(:nextPageToken)
field(:organizations, as: GoogleApi.CloudResourceManager.V3.Model.Organization, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.CloudResourceManager.V3.Model.SearchOrganizationsResponse do
def decode(value, options) do
GoogleApi.CloudResourceManager.V3.Model.SearchOrganizationsResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudResourceManager.V3.Model.SearchOrganizationsResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 44.38 | 390 | 0.7589 |
0864787b721fbe227308fa52b7b528a6f3655031 | 2,280 | ex | Elixir | lib/credo/build_info.ex | coryodaniel/credo | 840e9be99cb2ebcacb7d012e49b40714c0b37852 | [
"MIT"
] | null | null | null | lib/credo/build_info.ex | coryodaniel/credo | 840e9be99cb2ebcacb7d012e49b40714c0b37852 | [
"MIT"
] | null | null | null | lib/credo/build_info.ex | coryodaniel/credo | 840e9be99cb2ebcacb7d012e49b40714c0b37852 | [
"MIT"
] | null | null | null | defmodule Credo.BuildInfo do
@moduledoc false
# This is called at compile-time and should not be used at runtime!
@doc false
def version(mix_version) do
version(mix_version, git_info())
end
defp version(mix_version, nil) do
mix_version
end
defp version(mix_version, git_info) do
version =
if git_info.tag == "v#{mix_version}" do
mix_version
else
branch = git_info.branch || "nobranch"
commit = git_info.commit || "nocommit"
"#{mix_version}-ref.#{branch}.#{commit}"
end
if git_info.dirty? do
"#{version}+uncommittedchanges"
else
version
end
end
defp git_info do
if git_present?() do
%{
commit: git_commit(),
branch: git_branch(),
tag: git_tag(),
dirty?: git_dirty?()
}
end
end
defp git_present? do
{_, exit_status} = System.cmd("git", ["--help"])
exit_status == 0
end
defp git_branch do
case System.cmd("git", ["branch"]) do
{output, 0} -> git_branch(output)
{_, _} -> nil
end
end
defp git_branch(output) do
line_with_active_branch =
output
|> String.split("\n")
|> Enum.find(fn
"* " <> _ -> true
_ -> false
end)
case line_with_active_branch do
"* (HEAD detached at origin/" <> remote_branch_name ->
String.replace(remote_branch_name, ~r/\)$/, "")
"* (HEAD detached at " <> branch_name ->
String.replace(branch_name, ~r/\)$/, "")
"* " <> branch_name ->
branch_name
_ ->
nil
end
end
defp git_commit do
case System.cmd("git", ["rev-parse", "--short", "HEAD"]) do
{output, 0} -> String.trim(output)
{_, _} -> nil
end
end
defp git_tag do
case System.cmd("git", ["tag", "--points-at", "HEAD"]) do
{output, 0} -> String.trim(output)
{_, _} -> nil
end
end
defp git_dirty? do
case System.cmd("git", ["status", "--short"]) do
{output, 0} -> output |> String.trim() |> git_dirty?()
{_, _} -> nil
end
end
defp git_dirty?(""), do: false
# Hex puts a `.fetch` file in the working dir when downloading deps via git
defp git_dirty?("?? .fetch"), do: false
defp git_dirty?(_), do: true
end
| 21.308411 | 77 | 0.564474 |
0864bccd9cea8dae103400cfb845a4d9a4d3f748 | 5,132 | exs | Elixir | test/scenic/component/input/slider_list_test.exs | bruceme/scenic | bd8a1e63c122c44cc263e1fb5dfab2547ce8ef43 | [
"Apache-2.0"
] | null | null | null | test/scenic/component/input/slider_list_test.exs | bruceme/scenic | bd8a1e63c122c44cc263e1fb5dfab2547ce8ef43 | [
"Apache-2.0"
] | null | null | null | test/scenic/component/input/slider_list_test.exs | bruceme/scenic | bd8a1e63c122c44cc263e1fb5dfab2547ce8ef43 | [
"Apache-2.0"
] | null | null | null | #
# Created by Boyd Multerer on 2021-05-16
# Copyright © 2021 Kry10 Limited. All rights reserved.
#
defmodule Scenic.Component.Input.SliderListTest do
use ExUnit.Case, async: false
doctest Scenic.Component.Input.Slider
alias Scenic.Graph
alias Scenic.Scene
alias Scenic.ViewPort.Input
alias Scenic.Component
# import IEx
@press {:cursor_button, {:btn_left, 1, [], {20, 10}}}
@release {:cursor_button, {:btn_left, 0, [], {20, 10}}}
@pos_0 {:cursor_pos, {70, 10}}
@pos_1 {:cursor_pos, {140, 10}}
@pos_2 {:cursor_pos, {260, 10}}
@pos_3 {:cursor_pos, {360, 10}}
@pos_before {:cursor_pos, {-10, 10}}
@pos_after {:cursor_pos, {500, 10}}
defmodule TestScene do
use Scenic.Scene
import Scenic.Components
def graph() do
Graph.build()
|> slider({[:a, :b, :c, :d, :e], :b}, id: :slider_list)
end
@impl Scenic.Scene
def init(scene, pid, _opts) do
scene =
scene
|> assign(pid: pid)
|> push_graph(graph())
Process.send(pid, {:up, scene}, [])
{:ok, scene}
end
@impl Scenic.Scene
def handle_event(event, _from, %{assigns: %{pid: pid}} = scene) do
send(pid, {:fwd_event, event})
{:noreply, scene}
end
end
setup do
out = Scenic.Test.ViewPort.start({TestScene, self()})
# wait for a signal that the scene is up before proceeding
{:ok, scene} =
receive do
{:up, scene} -> {:ok, scene}
end
# make sure the button is up
{:ok, [pid]} = Scene.child(scene, :slider_list)
:_pong_ = GenServer.call(pid, :_ping_)
# needed to give time for the pid and vp to close
on_exit(fn -> Process.sleep(1) end)
out
|> Map.put(:scene, scene)
|> Map.put(:pid, pid)
end
defp force_sync(vp_pid, scene_pid) do
:_pong_ = GenServer.call(vp_pid, :_ping_)
:_pong_ = GenServer.call(scene_pid, :_ping_)
:_pong_ = GenServer.call(vp_pid, :_ping_)
end
test "validate passes list extents and initial value" do
data = {[:a, :b, :c], :b}
assert Component.Input.Slider.validate(data) == {:ok, data}
end
test "validate rejects initial value outside the extents" do
{:error, msg} = Component.Input.Slider.validate({[:a, :b, :c], :d})
assert msg =~ "not in"
end
test "press/release moves the slider and sends a message but pressing again in the same spot does not",
%{vp: vp, pid: pid} do
Input.send(vp, @press)
force_sync(vp.pid, pid)
assert_receive({:fwd_event, {:value_changed, :slider_list, :a}}, 100)
Input.send(vp, @release)
force_sync(vp.pid, pid)
Input.send(vp, @press)
force_sync(vp.pid, pid)
Input.send(vp, @release)
refute_receive(_, 10)
end
test "press & drag sends multiple messages", %{vp: vp, pid: pid} do
Input.send(vp, @press)
force_sync(vp.pid, pid)
assert_receive({:fwd_event, {:value_changed, :slider_list, :a}}, 100)
Input.send(vp, @pos_0)
assert_receive({:fwd_event, {:value_changed, :slider_list, :b}}, 100)
Input.send(vp, @pos_1)
assert_receive({:fwd_event, {:value_changed, :slider_list, :c}}, 100)
Input.send(vp, @pos_2)
assert_receive({:fwd_event, {:value_changed, :slider_list, :d}}, 100)
Input.send(vp, @pos_3)
assert_receive({:fwd_event, {:value_changed, :slider_list, :e}}, 100)
end
test "positions pin to the front and end of the slider", %{vp: vp, pid: pid} do
Input.send(vp, @press)
force_sync(vp.pid, pid)
assert_receive({:fwd_event, {:value_changed, :slider_list, :a}}, 100)
Input.send(vp, @pos_0)
assert_receive({:fwd_event, {:value_changed, :slider_list, :b}}, 100)
Input.send(vp, @pos_before)
assert_receive({:fwd_event, {:value_changed, :slider_list, :a}}, 100)
Input.send(vp, @pos_after)
assert_receive({:fwd_event, {:value_changed, :slider_list, :e}}, 100)
end
test "ignores non-main button clicks", %{vp: vp} do
Input.send(vp, {:cursor_button, {1, :press, 0, {20, 10}}})
Input.send(vp, {:cursor_button, {2, :press, 0, {20, 10}}})
refute_receive(_, 10)
end
test "implements get/put", %{scene: scene} do
assert Scene.get_child(scene, :slider_list) == [:b]
assert Scene.put_child(scene, :slider_list, :c) == :ok
assert Scene.get_child(scene, :slider_list) == [:c]
end
test "implements fetch/update", %{scene: scene} do
assert Scene.fetch_child(scene, :slider_list) == {:ok, [{[:a, :b, :c, :d, :e], :b}]}
%Scene{} = scene = Scene.update_child(scene, :slider_list, {[:aa, :bb, :cc, :dd, :ee], :ee})
assert Scene.fetch_child(scene, :slider_list) == {:ok, [{[:aa, :bb, :cc, :dd, :ee], :ee}]}
assert Scene.get_child(scene, :slider_list) == [:ee]
end
test "bounds works with defaults" do
graph =
Scenic.Graph.build()
|> Scenic.Components.slider({[:a, :b, :c, :d, :e], :b}, id: :sl)
{0.0, 0.0, 300.0, 18.0} = Scenic.Graph.bounds(graph)
end
test "bounds works with overrides" do
graph =
Graph.build()
|> Scenic.Components.slider({[:a, :b, :c, :d, :e], :b}, id: :sl, width: 400)
assert Graph.bounds(graph) == {0.0, 0.0, 400.0, 18.0}
end
end
| 29.66474 | 105 | 0.620811 |
0864c9619f2712faa4481752016e718b19c74d2b | 847 | exs | Elixir | mix.exs | JackyChiu/pageviews | aaa9a45444befd12cd5b73b26f2629e1a5eb4be7 | [
"MIT"
] | null | null | null | mix.exs | JackyChiu/pageviews | aaa9a45444befd12cd5b73b26f2629e1a5eb4be7 | [
"MIT"
] | null | null | null | mix.exs | JackyChiu/pageviews | aaa9a45444befd12cd5b73b26f2629e1a5eb4be7 | [
"MIT"
] | null | null | null | defmodule Pageviews.MixProject do
use Mix.Project
def project do
[
app: :pageviews,
version: "0.1.0",
elixir: "~> 1.8",
start_permanent: Mix.env() == :prod,
deps: deps(),
escript: escript(),
aliases: aliases()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {Pageviews.Application, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:httpoison, "~> 1.0"},
{:flow, "~> 0.14"},
{:benchee, "~> 1.0", only: :dev}
]
end
defp escript do
[
main_module: Pageviews.CLI,
path: "bin/pageviews"
]
end
defp aliases do
[
test: "test --no-start",
bench: "run test/bench.exs --no-start"
]
end
end
| 18.021277 | 59 | 0.543093 |
0864d89d462a5ac1efa88d0cf909dc518d311551 | 418 | ex | Elixir | episode06/test/web/views/json_post_view.ex | paulfioravanti/learn_phoenix | 3767f28b09bb5e740231dd261a0bfa8b3eea98d3 | [
"MIT"
] | null | null | null | episode06/test/web/views/json_post_view.ex | paulfioravanti/learn_phoenix | 3767f28b09bb5e740231dd261a0bfa8b3eea98d3 | [
"MIT"
] | null | null | null | episode06/test/web/views/json_post_view.ex | paulfioravanti/learn_phoenix | 3767f28b09bb5e740231dd261a0bfa8b3eea98d3 | [
"MIT"
] | null | null | null | defmodule Test.JSONPostView do
use Test.Web, :view
def render("index.json", %{json_posts: json_posts}) do
%{data: render_many(json_posts, Test.JSONPostView, "json_post.json")}
end
def render("show.json", %{json_post: json_post}) do
%{data: render_one(json_post, Test.JSONPostView, "json_post.json")}
end
def render("json_post.json", %{json_post: json_post}) do
%{id: json_post.id}
end
end
| 26.125 | 73 | 0.696172 |
0864f99893ba007baeb6cc2541d0e74a9a1e88c1 | 2,156 | ex | Elixir | lib/terraform.ex | tilo/terraform | 6315b34ddd6998d89fe67c6d979aae0a8673693d | [
"MIT"
] | 417 | 2016-08-08T06:24:51.000Z | 2022-02-20T12:34:14.000Z | lib/terraform.ex | tilo/terraform | 6315b34ddd6998d89fe67c6d979aae0a8673693d | [
"MIT"
] | 11 | 2016-08-08T01:07:45.000Z | 2021-06-29T11:54:50.000Z | lib/terraform.ex | tilo/terraform | 6315b34ddd6998d89fe67c6d979aae0a8673693d | [
"MIT"
] | 17 | 2016-08-16T00:12:44.000Z | 2021-07-27T05:04:36.000Z | defmodule Terraform do
@moduledoc """
A simple plug designed to work with Phoenix. Terraform allows you to incrementally transform an older API into one powered by Phoenix - one endpoint at a time.
## Usage
First, add to your router:
defmodule MyApp.Router do
use Terraform, terraformer: MyApp.Terraformers.Foo
# ...
end
Then, define a new `Terraformer`, which uses `Plug.Router`. Any request that goes to a route that isn't defined on your Phoenix app will hit this plug, and you can then handle it using a familiar DSL. Refer to [hexdocs](https://hexdocs.pm/plug/Plug.Router.html) for documentation about `Plug.Router`.
Here's a basic example:
defmodule MyApp.Terraformers.Foo do
alias MyApp.Clients.Foo # example client made with HTTPoison
use Plug.Router
plug :match
plug :dispatch
# match specific path
get "/v1/hello-world", do: send_resp(conn, 200, "Hello world")
# match all `get`s
get _ do
%{method: "GET", request_path: request_path, params: params, req_headers: req_headers} = conn
res = Foo.get!(request_path, req_headers, [params: Map.to_list(params)])
send_response({:ok, conn, res})
end
def send_response({:ok, conn, %{headers: headers, status_code: status_code, body: body}}) do
conn = %{conn | resp_headers: headers}
send_resp(conn, status_code, body)
end
end
"""
defmacro __using__(opts) do
quote location: :keep do
Module.register_attribute __MODULE__, :terraformer, []
@terraformer Keyword.get(unquote(opts), :terraformer)
@before_compile Terraform
end
end
@doc false
defmacro __before_compile__(_env) do
quote location: :keep do
defoverridable [call: 2]
def call(conn, opts) do
super(conn, opts)
catch
_, %Phoenix.Router.NoRouteError{conn: conn} ->
terraform(conn, @terraformer)
end
def terraform(%Plug.Conn{} = conn, terraformer) do
terraformer.call(conn, [])
end
defoverridable [terraform: 2]
end
end
end
| 30.366197 | 302 | 0.647959 |
086510310d41782fd9b8e3bfa4ec6eeef4fea64d | 969 | ex | Elixir | backend/lib/getaways/accounts/user.ex | Prumme/Projet_phx_ex_gql | 6324af91f94f96ee1f8403d5397ab930347e3e4f | [
"Unlicense"
] | null | null | null | backend/lib/getaways/accounts/user.ex | Prumme/Projet_phx_ex_gql | 6324af91f94f96ee1f8403d5397ab930347e3e4f | [
"Unlicense"
] | 6 | 2020-01-31T19:44:15.000Z | 2021-09-02T04:26:49.000Z | backend/lib/getaways/accounts/user.ex | Prumme/Projet_phx_ex_gql | 6324af91f94f96ee1f8403d5397ab930347e3e4f | [
"Unlicense"
] | null | null | null | defmodule Getaways.Accounts.User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field :username, :string
field :email, :string
field :password_hash, :string
field :password, :string, virtual: true
has_many :bookings, Getaways.Vacation.Booking
has_many :reviews, Getaways.Vacation.Review
timestamps()
end
def changeset(user, attrs) do
required_fields = [:username, :email, :password]
user
|> cast(attrs, required_fields)
|> validate_required(required_fields)
|> validate_length(:username, min: 2)
|> validate_length(:password, min: 6)
|> unique_constraint(:username)
|> unique_constraint(:email)
|> hash_password()
end
defp hash_password(changeset) do
case changeset do
%Ecto.Changeset{valid?: true, changes: %{password: password}} ->
put_change(changeset, :password_hash, Pbkdf2.hash_pwd_salt(password))
_ ->
changeset
end
end
end
| 24.846154 | 77 | 0.676987 |
0865174e92e89945da17f349842c22f2a84dbe6c | 1,395 | ex | Elixir | lib/ecto/adapter/migrations.ex | joshnuss/ecto | 17cc8d7ac39cd4f9331f2ff461f7d64ecebde9f0 | [
"Apache-2.0"
] | null | null | null | lib/ecto/adapter/migrations.ex | joshnuss/ecto | 17cc8d7ac39cd4f9331f2ff461f7d64ecebde9f0 | [
"Apache-2.0"
] | null | null | null | lib/ecto/adapter/migrations.ex | joshnuss/ecto | 17cc8d7ac39cd4f9331f2ff461f7d64ecebde9f0 | [
"Apache-2.0"
] | null | null | null | defmodule Ecto.Adapter.Migrations do
@moduledoc """
Specifies the adapter migrations API.
"""
use Behaviour
alias Ecto.Migration.Table
alias Ecto.Migration.Index
alias Ecto.Migration.Reference
@typedoc "All migration commands"
@type command ::
raw :: String.t |
{:create, Table.t, [table_subcommand]} |
{:alter, Table.t, [table_subcommand]} |
{:drop, Table.t} |
{:create, Index.t} |
{:drop, Index.t}
@typedoc "Table subcommands"
@type table_subcommand ::
{:add, field :: atom, type :: Ecto.Type.t | Reference.t, Keyword.t} |
{:modify, field :: atom, type :: Ecto.Type.t | Reference.t, Keyword.t} |
{:remove, field :: atom}
@doc """
Executes migration commands.
## Options
* `:timeout` - The time in milliseconds to wait for the call to finish,
`:infinity` will wait indefinitely (default: 5000);
* `:log` - When false, does not log begin/commit/rollback queries
"""
defcallback execute_ddl(Ecto.Repo.t, command, Keyword.t) :: :ok | no_return
@doc """
Checks if ddl value, like a table or index, exists.
## Options
* `:timeout` - The time in milliseconds to wait for the call to finish,
`:infinity` will wait indefinitely (default: 5000);
* `:log` - When false, does not log begin/commit/rollback queries
"""
defcallback ddl_exists?(Ecto.Repo.t, Table.t | Index.t, Keyword.t) :: boolean
end
| 28.469388 | 79 | 0.658781 |
086541169a10a41234948006d836a6f4a93edb49 | 5,018 | ex | Elixir | clients/content/lib/google_api/content/v21/model/order_promotion.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/content/lib/google_api/content/v21/model/order_promotion.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/content/lib/google_api/content/v21/model/order_promotion.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.Content.V21.Model.OrderPromotion do
@moduledoc """
## Attributes
* `applicableItems` (*type:* `list(GoogleApi.Content.V21.Model.OrderPromotionItem.t)`, *default:* `nil`) - Items that this promotion may be applied to. If empty, there are no restrictions on applicable items and quantity. This field will also be empty for shipping promotions because shipping is not tied to any specific item.
* `appliedItems` (*type:* `list(GoogleApi.Content.V21.Model.OrderPromotionItem.t)`, *default:* `nil`) - Items that this promotion have been applied to. Do not provide for `orders.createtestorder`. This field will be empty for shipping promotions because shipping is not tied to any specific item.
* `endTime` (*type:* `String.t`, *default:* `nil`) - Promotion end time in ISO 8601 format. Date, time, and offset required, e.g., "2020-01-02T09:00:00+01:00" or "2020-01-02T09:00:00Z".
* `funder` (*type:* `String.t`, *default:* `nil`) - Required. The party funding the promotion. Only `merchant` is supported for `orders.createtestorder`. Acceptable values are: - "`google`" - "`merchant`"
* `merchantPromotionId` (*type:* `String.t`, *default:* `nil`) - Required. This field is used to identify promotions within merchants' own systems.
* `priceValue` (*type:* `GoogleApi.Content.V21.Model.Price.t`, *default:* `nil`) - Estimated discount applied to price. Amount is pre-tax or post-tax depending on location of order.
* `shortTitle` (*type:* `String.t`, *default:* `nil`) - A short title of the promotion to be shown on the checkout page. Do not provide for `orders.createtestorder`.
* `startTime` (*type:* `String.t`, *default:* `nil`) - Promotion start time in ISO 8601 format. Date, time, and offset required, e.g., "2020-01-02T09:00:00+01:00" or "2020-01-02T09:00:00Z".
* `subtype` (*type:* `String.t`, *default:* `nil`) - Required. The category of the promotion. Only `moneyOff` is supported for `orders.createtestorder`. Acceptable values are: - "`buyMGetMoneyOff`" - "`buyMGetNMoneyOff`" - "`buyMGetNPercentOff`" - "`buyMGetPercentOff`" - "`freeGift`" - "`freeGiftWithItemId`" - "`freeGiftWithValue`" - "`freeShippingOvernight`" - "`freeShippingStandard`" - "`freeShippingTwoDay`" - "`moneyOff`" - "`percentOff`" - "`rewardPoints`" - "`salePrice`"
* `taxValue` (*type:* `GoogleApi.Content.V21.Model.Price.t`, *default:* `nil`) - Estimated discount applied to tax (if allowed by law). Do not provide for `orders.createtestorder`.
* `title` (*type:* `String.t`, *default:* `nil`) - Required. The title of the promotion.
* `type` (*type:* `String.t`, *default:* `nil`) - Required. The scope of the promotion. Only `product` is supported for `orders.createtestorder`. Acceptable values are: - "`product`" - "`shipping`"
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:applicableItems => list(GoogleApi.Content.V21.Model.OrderPromotionItem.t()) | nil,
:appliedItems => list(GoogleApi.Content.V21.Model.OrderPromotionItem.t()) | nil,
:endTime => String.t() | nil,
:funder => String.t() | nil,
:merchantPromotionId => String.t() | nil,
:priceValue => GoogleApi.Content.V21.Model.Price.t() | nil,
:shortTitle => String.t() | nil,
:startTime => String.t() | nil,
:subtype => String.t() | nil,
:taxValue => GoogleApi.Content.V21.Model.Price.t() | nil,
:title => String.t() | nil,
:type => String.t() | nil
}
field(:applicableItems, as: GoogleApi.Content.V21.Model.OrderPromotionItem, type: :list)
field(:appliedItems, as: GoogleApi.Content.V21.Model.OrderPromotionItem, type: :list)
field(:endTime)
field(:funder)
field(:merchantPromotionId)
field(:priceValue, as: GoogleApi.Content.V21.Model.Price)
field(:shortTitle)
field(:startTime)
field(:subtype)
field(:taxValue, as: GoogleApi.Content.V21.Model.Price)
field(:title)
field(:type)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V21.Model.OrderPromotion do
def decode(value, options) do
GoogleApi.Content.V21.Model.OrderPromotion.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V21.Model.OrderPromotion do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 62.725 | 485 | 0.69729 |
086558cf813905b78b4072fe8a8beeac3bc91dcf | 572 | ex | Elixir | lib/jeopardy_web/plugs.ex | banzr/CS4550proj2 | 4e7ce6098c2a8a9fe38dab1d83e52ef9e3247f2c | [
"MIT"
] | null | null | null | lib/jeopardy_web/plugs.ex | banzr/CS4550proj2 | 4e7ce6098c2a8a9fe38dab1d83e52ef9e3247f2c | [
"MIT"
] | 2 | 2020-04-30T14:14:00.000Z | 2020-07-07T20:57:31.000Z | lib/jeopardy_web/plugs.ex | banzr/CS4550proj2 | 4e7ce6098c2a8a9fe38dab1d83e52ef9e3247f2c | [
"MIT"
] | null | null | null | defmodule JeopardyWeb.Plugs do
import Plug.Conn
alias Jeopardy.Sessions
def fetch_user(conn, _opts) do
user_id = get_session(conn, :user_id)
if user_id do
user = Jeopardy.Users.get_user!(user_id)
assign(conn, :current_user, user)
else
assign(conn, :current_user, nil)
end
end
def fetch_game_session(conn, _opts) do
session_id = get_session(conn, :session_id)
session = Sessions.get_or_create_session(session_id)
conn
|> put_session(:session_id, session.id)
|> assign(:current_session, session)
end
end
| 22.88 | 56 | 0.699301 |
08657fbd7216fe3e610802113e4c87aa34cfb946 | 13,411 | ex | Elixir | lib/rayex/structs.ex | shiryel/rayex | 20cbffe788ef9df66d3e8ff918fe16a040aff737 | [
"Apache-2.0"
] | 8 | 2021-08-06T16:12:53.000Z | 2022-02-07T21:23:00.000Z | lib/rayex/structs.ex | shiryel/rayex | 20cbffe788ef9df66d3e8ff918fe16a040aff737 | [
"Apache-2.0"
] | 3 | 2021-07-31T20:04:29.000Z | 2021-12-17T19:52:41.000Z | lib/rayex/structs.ex | shiryel/rayex | 20cbffe788ef9df66d3e8ff918fe16a040aff737 | [
"Apache-2.0"
] | 3 | 2021-07-30T06:20:00.000Z | 2022-02-23T22:33:31.000Z | defmodule Rayex.Structs.Vector2 do
@moduledoc "Vector2"
@enforce_keys ~w[x y]a
defstruct ~w[x y]a
@type t :: %__MODULE__{x: float(), y: float()}
end
defmodule Rayex.Structs.Vector3 do
@moduledoc "Vector3"
@enforce_keys ~w[x y z]a
defstruct ~w[x y z]a
@type t :: %__MODULE__{x: float(), y: float(), z: float()}
end
defmodule Rayex.Structs.Vector4 do
@moduledoc "Vector3"
@enforce_keys ~w[x y z w]a
defstruct ~w[x y z w]a
@type t :: %__MODULE__{x: float(), y: float(), z: float(), w: float()}
end
# same as vector4
defmodule Rayex.Structs.Quaternion do
@moduledoc "Quaternion"
@enforce_keys ~w[x y z w]a
defstruct ~w[x y z w]a
@type t :: %__MODULE__{x: float(), y: float(), z: float(), w: float()}
end
defmodule Rayex.Structs.Matrix do
@moduledoc "Matrix"
@enforce_keys ~w[m0 m1 m2 m3 m4 m5 m6 m7 m8 m9 m10 m11 m12 m13 m14 m15]a
defstruct ~w[m0 m1 m2 m3 m4 m5 m6 m7 m8 m9 m10 m11 m12 m13 m14 m15]a
@type t :: %__MODULE__{
m0: float,
m1: float,
m2: float,
m3: float,
#
m4: float,
m5: float,
m6: float,
m7: float,
#
m8: float,
m9: float,
m10: float,
m11: float,
#
m12: float,
m13: float,
m14: float,
m15: float
}
end
defmodule Rayex.Structs.Color do
@moduledoc "Color"
@enforce_keys ~w[r g b a]a
defstruct ~w[r g b a]a
@type t :: %__MODULE__{
r: non_neg_integer(),
g: non_neg_integer(),
b: non_neg_integer(),
a: non_neg_integer()
}
end
defmodule Rayex.Structs.Rectangle do
@moduledoc "Rectangle"
@enforce_keys ~w[x y width height]a
defstruct ~w[x y width height]a
@type t :: %__MODULE__{x: float, y: float, width: float, height: float}
end
defmodule Rayex.Structs.Image do
@moduledoc "Image"
# XXX: verify if binary works as a void*
# take a look at https://hexdocs.pm/unifex/Unifex.Specs.DSL.html#spec/1-parameters
@enforce_keys ~w[data width height mipmaps format]a
defstruct ~w[data width height mipmaps format]a
@type t :: %__MODULE__{
data: binary(),
width: integer(),
height: integer(),
mipmaps: integer(),
format: integer()
}
end
defmodule Rayex.Structs.Texture2D do
@moduledoc "Texture2D"
@enforce_keys ~w[id width height mipmaps format]a
defstruct ~w[id width height mipmaps format]a
@type t :: %__MODULE__{
id: non_neg_integer(),
width: float(),
height: float(),
mipmaps: integer(),
format: integer()
}
end
# same as Texture
defmodule Rayex.Structs.TextureCubemap do
@moduledoc "Texture"
@enforce_keys ~w[id width height mipmaps format]a
defstruct ~w[id width height mipmaps format]a
@type t :: %__MODULE__{
id: non_neg_integer(),
width: float(),
height: float(),
mipmaps: integer(),
format: integer()
}
end
defmodule Rayex.Structs.RenderTexture do
@moduledoc "RenderTexture"
@enforce_keys ~w[id texture depth]a
defstruct ~w[id texture depth]a
@type t :: %__MODULE__{
id: non_neg_integer(),
texture: Rayex.Structs.Texture2D.t(),
depth: Rayex.Structs.Texture2D.t()
}
end
# same as render_texture
defmodule Rayex.Structs.RenderTexture2D do
@moduledoc "RenderTexture2D"
@enforce_keys ~w[id texture depth]a
defstruct ~w[id texture depth]a
@type t :: %__MODULE__{
id: non_neg_integer(),
texture: Rayex.Structs.Texture2D.t(),
depth: Rayex.Structs.Texture2D.t()
}
end
defmodule Rayex.Structs.NPatchInfo do
@moduledoc "NPatchInfo"
@enforce_keys ~w[source left top right bottom layout]a
defstruct ~w[source left top right bottom layout]a
@type t :: %__MODULE__{
source: Rayex.Structs.Rectangle.t(),
left: integer,
top: integer,
right: integer,
bottom: integer,
layout: integer
}
end
defmodule Rayex.Structs.GlyphInfo do
@moduledoc "GlyphInfo"
@enforce_keys ~w[value offset_x offset_y advance_x image]a
defstruct ~w[value offset_x offset_y advance_x image]a
@type t :: %__MODULE__{
value: integer,
offset_x: integer,
offset_y: integer,
advance_x: integer,
image: Rayex.Structs.Image.t()
}
end
defmodule Rayex.Structs.Font do
@moduledoc "Font"
@enforce_keys ~w[base_size glyph_count glyph_padding texture recs glyphs]a
defstruct ~w[base_size glyph_count glyph_padding texture recs glyphs]a
@type t :: %__MODULE__{
base_size: integer,
glyph_count: integer,
glyph_padding: integer,
texture: Rayex.Structs.Texture2D.t(),
recs: [Rayex.Structs.Rectangle.t()],
glyphs: [Rayex.Structs.GlyphInfo.t()]
}
end
defmodule Rayex.Structs.Camera3D do
@moduledoc "Camera3D"
@enforce_keys ~w[position target up fovy projection]a
defstruct ~w[position target up fovy projection]a
@type t :: %__MODULE__{
position: Rayex.Structs.Vector3.t(),
target: Rayex.Structs.Vector3.t(),
up: Rayex.Structs.Vector3.t(),
fovy: float(),
projection: integer()
}
end
defmodule Rayex.Structs.Camera2D do
@moduledoc "Camera2D"
@enforce_keys ~w[offset target rotation zoom]a
defstruct ~w[offset target rotation zoom]a
@type t :: %__MODULE__{
offset: Rayex.Structs.Vector2.t(),
target: Rayex.Structs.Vector2.t(),
rotation: float,
zoom: float
}
end
defmodule Rayex.Structs.Mesh do
@moduledoc "Mesh"
@enforce_keys ~w[vertex_count triangle_count vertices texcoords texcoords2
normals tangents colors indices anim_vertices anim_normals bone_ids
bone_weights vao_id vbo_id]a
defstruct ~w[vertex_count triangle_count vertices texcoords texcoords2 normals
tangents colors indices anim_vertices anim_normals bone_ids bone_weights
vao_id vbo_id]a
@type t :: %__MODULE__{
vertex_count: integer,
triangle_count: integer,
# Vertex attributes data
vertices: [float],
texcoords: [float],
texcoords2: [float],
normals: [float],
tangents: [float],
colors: [non_neg_integer()],
indices: [non_neg_integer()],
# Animation vertex data
anim_vertices: [float],
anim_normals: [float],
bone_ids: [non_neg_integer()],
bone_weights: [float],
# OpenGL identifiers
vao_id: [non_neg_integer()],
vbo_id: [non_neg_integer()]
}
end
defmodule Rayex.Structs.Shader do
@moduledoc "Shader"
@enforce_keys ~w[id locs]a
defstruct ~w[id locs]a
@type t :: %__MODULE__{
id: non_neg_integer(),
locs: [integer()]
}
end
defmodule Rayex.Structs.MaterialMap do
@moduledoc "MaterialMap"
@enforce_keys ~w[texture color value]a
defstruct ~w[texture color value]a
@type t :: %__MODULE__{
texture: Rayex.Structs.Texture2D.t(),
color: Rayex.Structs.Color.t(),
value: float
}
end
defmodule Rayex.Structs.Material do
@moduledoc "Material"
@enforce_keys ~w[shader maps params]a
defstruct ~w[shader maps params]a
@type t :: %__MODULE__{
shader: Rayex.Structs.Shader.t(),
maps: [Rayex.Structs.MaterialMap.t()],
params: [float]
}
end
defmodule Rayex.Structs.Transform do
@moduledoc "Transform"
@enforce_keys ~w[translation rotation scale]a
defstruct ~w[translation rotation scale]a
@type t :: %__MODULE__{
translation: Rayex.Structs.Vector3.t(),
rotation: Rayex.Structs.Quaternion.t(),
scale: Rayex.Structs.Vector3.t()
}
end
defmodule Rayex.Structs.BoneInfo do
@moduledoc "BoneInfo"
@enforce_keys ~w[name parent]a
defstruct ~w[name parent]a
@type t :: %__MODULE__{
name: String.t(),
parent: integer()
}
end
defmodule Rayex.Structs.Model do
@moduledoc "Model"
@enforce_keys ~w[transform mesh_count material_count mashes materials mesh_material bone_count bones bind_pose]a
defstruct ~w[transform mesh_count material_count mashes materials mesh_material bone_count bones bind_pose]a
@type t :: %__MODULE__{
transform: Rayex.Structs.Matrix.t(),
mesh_count: integer(),
material_count: integer(),
mashes: [Rayex.Structs.Mesh.t()],
materials: [Rayex.Structs.Material.t()],
mesh_material: [integer()],
bone_count: integer(),
bones: [Rayex.Structs.BoneInfo.t()],
bind_pose: [Rayex.Structs.Transform.t()]
}
end
defmodule Rayex.Structs.ModelAnimation do
@moduledoc "ModelAnimation"
@enforce_keys ~w[bone_count frame_count bones frame_poses]a
defstruct ~w[bone_count frame_count bones frame_poses]a
@type t :: %__MODULE__{
bone_count: integer(),
frame_count: integer(),
bones: [Rayex.Structs.BoneInfo.t()],
# XXX: should be **transform
frame_poses: [[Rayex.Structs.Transform.t()]]
}
end
defmodule Rayex.Structs.Ray do
@moduledoc "Ray"
@enforce_keys ~w[position direction]a
defstruct ~w[position direction]a
@type t :: %__MODULE__{
position: Rayex.Structs.Vector3.t(),
direction: Rayex.Structs.Vector3.t()
}
end
defmodule Rayex.Structs.RayCollision do
@moduledoc "RayCollision"
@enforce_keys ~w[hit distance point normal]a
defstruct ~w[hit distance point normal]a
@type t :: %__MODULE__{
hit: boolean(),
distance: float,
point: Rayex.Structs.Vector3.t(),
normal: Rayex.Structs.Vector3.t()
}
end
defmodule Rayex.Structs.BoundingBox do
@moduledoc "BoundingBox"
@enforce_keys ~w[min max]a
defstruct ~w[min max]a
@type t :: %__MODULE__{
min: Rayex.Structs.Vector3.t(),
max: Rayex.Structs.Vector3.t()
}
end
defmodule Rayex.Structs.Wave do
@moduledoc "Wave"
@enforce_keys ~w[frame_count sample_rate sample_size channels data]a
defstruct ~w[frame_count sample_rate sample_size channels data]a
@type t :: %__MODULE__{
frame_count: non_neg_integer(),
sample_rate: non_neg_integer(),
sample_size: non_neg_integer(),
channels: non_neg_integer(),
data: binary()
}
end
# XXX: ? https://github.com/raysan5/raylib/blob/master/src/raylib.h#L428
defmodule Rayex.Structs.RAudioBuffer do
@moduledoc "RAudioBuffer"
@enforce_keys ~w[]a
defstruct ~w[]a
@type t :: %__MODULE__{}
end
defmodule Rayex.Structs.AudioStream do
@moduledoc "AudioStream"
@enforce_keys ~w[buffer sample_rate sample_size channels]a
defstruct ~w[buffer sample_rate sample_size channels]a
@type t :: %__MODULE__{
buffer: [Rayex.Structs.RAudioBuffer.t()],
sample_rate: non_neg_integer(),
sample_size: non_neg_integer(),
channels: non_neg_integer()
}
end
defmodule Rayex.Structs.Sound do
@moduledoc "Sound"
@enforce_keys ~w[stream frame_count]a
defstruct ~w[stream frame_count]a
@type t :: %__MODULE__{
stream: Rayex.Structs.AudioStream.t(),
frame_count: non_neg_integer()
}
end
defmodule Rayex.Structs.Music do
@moduledoc "Music"
@enforce_keys ~w[stream frame_count looping ctx_type ctx_data]a
defstruct ~w[stream frame_count looping ctx_type ctx_data]a
@type t :: %__MODULE__{
stream: Rayex.Structs.AudioStream.t(),
frame_count: non_neg_integer(),
looping: boolean(),
ctx_type: integer(),
ctx_data: binary()
}
end
defmodule Rayex.Structs.VrDeviceInfo do
@moduledoc "VrDeviceInfo"
@enforce_keys ~w[h_resolution v_resolution h_screen_size v_screen_size
v_screen_center eye_to_screen_distance lens_separation_distance
interpupillary_distance lens_distortion_values chroma_ab_correction]a
defstruct ~w[h_resolution v_resolution h_screen_size v_screen_size
v_screen_center eye_to_screen_distance lens_separation_distance
interpupillary_distance lens_distortion_values chroma_ab_correction]a
@type t :: %__MODULE__{
h_resolution: integer(),
v_resolution: integer(),
h_screen_size: float,
v_screen_size: float,
v_screen_center: float,
eye_to_screen_distance: float,
lens_separation_distance: float,
interpupillary_distance: float,
lens_distortion_values: [float],
chroma_ab_correction: [float]
}
end
defmodule Rayex.Structs.VrStereoConfig do
@moduledoc "VrStereoConfig"
@enforce_keys ~w[projection view_offset left_lens_center right_lens_center
left_screen_center right_screen_center scale scale_in]a
defstruct ~w[projection view_offset left_lens_center right_lens_center
left_screen_center right_screen_center scale scale_in]a
@type t :: %__MODULE__{
projection: [Rayex.Structs.Matrix.t()],
view_offset: [Rayex.Structs.Matrix.t()],
left_lens_center: [float],
right_lens_center: [float],
left_screen_center: [float],
right_screen_center: [float],
scale: [float],
scale_in: [float]
}
end
| 27.651546 | 114 | 0.646559 |
08659ffb28ae4b3837e866580adeea5f8fcd1625 | 843 | ex | Elixir | lib/socket/handler/core/heartbeat.ex | sb8244/grapevine | effaaa01294d30114090c20f9cc40b8665d834f2 | [
"MIT"
] | null | null | null | lib/socket/handler/core/heartbeat.ex | sb8244/grapevine | effaaa01294d30114090c20f9cc40b8665d834f2 | [
"MIT"
] | null | null | null | lib/socket/handler/core/heartbeat.ex | sb8244/grapevine | effaaa01294d30114090c20f9cc40b8665d834f2 | [
"MIT"
] | null | null | null | defmodule Socket.Handler.Core.Heartbeat do
@moduledoc """
Handle a heartbeat internally to Grapevine
"""
require Logger
def handle(state = %{status: "inactive"}) do
state = Map.put(state, :heartbeat_count, state.heartbeat_count + 1)
case state.heartbeat_count > 3 do
true ->
:telemetry.execute([:grapevine, :sockets, :heartbeat, :disconnect], %{count: 1}, %{})
{:disconnect, state}
false ->
{:ok, state}
end
end
def handle(state) do
case state do
%{heartbeat_count: count} when count >= 3 ->
:telemetry.execute([:grapevine, :sockets, :heartbeat, :disconnect], %{count: 1}, %{})
{:disconnect, state}
_ ->
state = Map.put(state, :heartbeat_count, state.heartbeat_count + 1)
{:ok, %{event: "heartbeat"}, state}
end
end
end
| 24.794118 | 93 | 0.606168 |
0865c129bf4b8f7482433d6ee3d70d7a6d20dda5 | 1,163 | ex | Elixir | examples/alarm/lib/alarm.ex | asummers/grovepi | 8092fd704457265929e4d9676bedd8cf2176f48d | [
"Apache-2.0"
] | 34 | 2017-08-28T22:44:59.000Z | 2022-02-15T06:37:40.000Z | examples/alarm/lib/alarm.ex | schainks/grovepi | 2de21f12a2ab28f9788a2add4c6409871e098479 | [
"Apache-2.0"
] | 19 | 2017-08-14T17:27:44.000Z | 2019-05-26T02:49:39.000Z | examples/alarm/lib/alarm.ex | schainks/grovepi | 2de21f12a2ab28f9788a2add4c6409871e098479 | [
"Apache-2.0"
] | 5 | 2017-09-06T02:20:28.000Z | 2020-03-29T06:05:16.000Z | defmodule Alarm do
@moduledoc false
use Application
# Pick ports that work on both the GrovePi+ and GrovePi Zero
@button_pin 14 # Port A0
@buzzer_pin 3 # Port D3
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
# Start the GrovePi sensors that we want
worker(GrovePi.Button, [@button_pin]),
worker(GrovePi.Buzzer, [@buzzer_pin]),
# Start the main app
worker(Alarm.Worker, [[@button_pin, @buzzer_pin]]),
]
opts = [strategy: :one_for_one, name: Alarm.Supervisor]
Supervisor.start_link(children, opts)
end
defmodule Worker do
@moduledoc false
use GenServer
defstruct [:button, :buzzer]
def start_link(pins) do
GenServer.start_link(__MODULE__, pins)
end
def init([button, buzzer]) do
state = %Worker{button: button, buzzer: buzzer}
GrovePi.Button.subscribe(state.button, :pressed)
{:ok, state}
end
def handle_info({_, :pressed, _}, state) do
IO.puts("Alert!!!!")
# Sound the alarm, but only for a second
GrovePi.Buzzer.buzz(state.buzzer, 1000)
{:noreply, state}
end
end
end
| 22.365385 | 62 | 0.645744 |
0865c3d9b64b1a3945db56cdf1df1f523c631c23 | 615 | exs | Elixir | apps/day05/mix.exs | jochumb/aoc2017 | 813851fcab9270adea1bc532335f2228f5c015be | [
"MIT"
] | null | null | null | apps/day05/mix.exs | jochumb/aoc2017 | 813851fcab9270adea1bc532335f2228f5c015be | [
"MIT"
] | null | null | null | apps/day05/mix.exs | jochumb/aoc2017 | 813851fcab9270adea1bc532335f2228f5c015be | [
"MIT"
] | null | null | null | defmodule Day05.Mixfile do
use Mix.Project
def project do
[
app: :day05,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
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
[
{:utils, in_umbrella: true},
]
end
end
| 19.21875 | 59 | 0.554472 |
0865cac982aa2bb13dbf591977bd6e1b93d7bd87 | 1,539 | ex | Elixir | clients/big_query/lib/google_api/big_query/v2/model/test_iam_permissions_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/big_query/lib/google_api/big_query/v2/model/test_iam_permissions_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/big_query/lib/google_api/big_query/v2/model/test_iam_permissions_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.BigQuery.V2.Model.TestIamPermissionsResponse do
@moduledoc """
Response message for `TestIamPermissions` method.
## Attributes
* `permissions` (*type:* `list(String.t)`, *default:* `nil`) - A subset of `TestPermissionsRequest.permissions` that the caller is allowed.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:permissions => list(String.t()) | nil
}
field(:permissions, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.TestIamPermissionsResponse do
def decode(value, options) do
GoogleApi.BigQuery.V2.Model.TestIamPermissionsResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.TestIamPermissionsResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.744681 | 143 | 0.746589 |
0865ea84b025a43cb31797c8edd700f2767fff06 | 1,286 | ex | Elixir | lib/step_flow/amqp/common_emitter.ex | mathiaHT/ex_step_flow | 6496e9511239de64f00119428476338dfcde9dea | [
"MIT"
] | 4 | 2019-12-07T05:18:26.000Z | 2020-11-06T23:28:43.000Z | lib/step_flow/amqp/common_emitter.ex | mathiaHT/ex_step_flow | 6496e9511239de64f00119428476338dfcde9dea | [
"MIT"
] | 53 | 2020-01-06T11:23:09.000Z | 2021-06-25T15:30:07.000Z | lib/step_flow/amqp/common_emitter.ex | mathiaHT/ex_step_flow | 6496e9511239de64f00119428476338dfcde9dea | [
"MIT"
] | 3 | 2020-01-30T15:37:40.000Z | 2020-10-27T14:10:02.000Z | defmodule StepFlow.Amqp.CommonEmitter do
@moduledoc """
A common emitter to send job orders to workers.
"""
require Logger
alias StepFlow.Amqp.Connection
alias StepFlow.Metrics.JobInstrumenter
@doc """
Publish a message.
Example:
```elixir
StepFlow.Amqp.CommonEmitter.publish_json("my_rabbit_mq_queue", "{\\\"key\\\": \\\"value\\\"}")
```
"""
def publish(queue, message, options \\ []) do
Connection.publish(queue, message, options)
end
@doc """
Publish a message using JSON serialization before send it.
Example:
```elixir
StepFlow.Amqp.CommonEmitter.publish_json("my_rabbit_mq_queue", 0, %{key: "value"})
```
"""
def publish_json(queue, priority, message) do
message =
message
|> check_message_parameters
|> Jason.encode!()
options = [
priority: min(priority, 100)
]
JobInstrumenter.inc(:step_flow_jobs_created, queue)
publish(queue, message, options)
end
defp check_message_parameters(message) do
parameters =
message
|> StepFlow.Map.get_by_key_or_atom(:parameters, [])
|> Enum.filter(fn param ->
StepFlow.Map.get_by_key_or_atom(param, :type) != "filter"
end)
StepFlow.Map.replace_by_atom(message, :parameters, parameters)
end
end
| 22.172414 | 96 | 0.66563 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.