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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0805eb7769023d4a96f2f261b4f065f3eb64d813 | 1,665 | ex | Elixir | lib/mix/tasks/gil.ex | modalsoul/Gil | db85866a52ba1e99fdb2e83b54233197f128654d | [
"MIT"
] | null | null | null | lib/mix/tasks/gil.ex | modalsoul/Gil | db85866a52ba1e99fdb2e83b54233197f128654d | [
"MIT"
] | null | null | null | lib/mix/tasks/gil.ex | modalsoul/Gil | db85866a52ba1e99fdb2e83b54233197f128654d | [
"MIT"
] | null | null | null | defmodule Mix.Tasks.Gil do
use Mix.Task
@shortdoc "Exchange rate check command"
def run(args) do
result = case currencies(args) do
{:ok, {currency_a, currency_b}} ->
case parse_response(get_rate(currency_a, currency_b)) do
{:ok, rate} ->
"#{String.upcase(currency_a)}/#{String.upcase(currency_b)}: #{rate}"
{:error, message} ->
message
end
{:error} -> "Illegal argument"
end
IO.puts result
end
def currencies(args) do
kc = key_currency
case args do
[a|[b|_]] -> {:ok, {a, b}}
[a|[a|_]] -> {:error}
[^kc|_] -> {:error}
[a|_] -> {:ok, {kc, a}}
_ -> {:error}
end
end
def get_rate(currency_a, currency_b) do
url = "http://jp.investing.com/currencies/#{String.downcase(currency_a <> "-" <> currency_b)}"
HTTPoison.start
HTTPoison.get(url)
end
def parse_response(response) do
case response do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
try do
{:ok, rate(body)}
rescue
e in RuntimeError -> {:error, e.message}
end
{:ok, %HTTPoison.Response{status_code: 404}} ->
{:error, "Failed to get currency rate."}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, "ERROR! #{reason}"}
end
end
def rate(body) do
case Floki.find(body, "#last_last") do
{_, _, [rate|_]} -> rate
_ -> raise "Failed to get currency rate."
end
end
def key_currency do
conf = Mix.Config.read!("config/config.exs")
case conf[:gil][:key_currency] do
nil -> "usd"
key -> key
end
end
end | 25.227273 | 98 | 0.559159 |
0805ee63628711ae5d0cf905a7fd77507ae65a5e | 11,058 | ex | Elixir | debian/manpage.xml.ex | sharkwouter/vaporos-flatpak-manager | da1dce2a806fdb51aa9366408ace50c28fbc3ff6 | [
"MIT"
] | null | null | null | debian/manpage.xml.ex | sharkwouter/vaporos-flatpak-manager | da1dce2a806fdb51aa9366408ace50c28fbc3ff6 | [
"MIT"
] | 21 | 2019-09-15T08:42:58.000Z | 2021-08-28T16:48:54.000Z | debian/manpage.xml.ex | sharkwouter/vaporos-flatpak-manager | da1dce2a806fdb51aa9366408ace50c28fbc3ff6 | [
"MIT"
] | null | null | null | <?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!--
`xsltproc -''-nonet \
-''-param man.charmap.use.subset "0" \
-''-param make.year.ranges "1" \
-''-param make.single.year.ranges "1" \
/usr/share/xml/docbook/stylesheet/docbook-xsl/manpages/docbook.xsl \
manpage.xml'
A manual page <package>.<section> will be generated. You may view the
manual page with: nroff -man <package>.<section> | less'. A typical entry
in a Makefile or Makefile.am is:
DB2MAN = /usr/share/sgml/docbook/stylesheet/xsl/docbook-xsl/manpages/docbook.xsl
XP = xsltproc -''-nonet -''-param man.charmap.use.subset "0"
manpage.1: manpage.xml
$(XP) $(DB2MAN) $<
The xsltproc binary is found in the xsltproc package. The XSL files are in
docbook-xsl. A description of the parameters you can use can be found in the
docbook-xsl-doc-* packages. Please remember that if you create the nroff
version in one of the debian/rules file targets (such as build), you will need
to include xsltproc and docbook-xsl in your Build-Depends control field.
Alternatively use the xmlto command/package. That will also automatically
pull in xsltproc and docbook-xsl.
Notes for using docbook2x: docbook2x-man does not automatically create the
AUTHOR(S) and COPYRIGHT sections. In this case, please add them manually as
<refsect1> ... </refsect1>.
To disable the automatic creation of the AUTHOR(S) and COPYRIGHT sections
read /usr/share/doc/docbook-xsl/doc/manpages/authors.html. This file can be
found in the docbook-xsl-doc-html package.
Validation can be done using: `xmllint -''-noout -''-valid manpage.xml`
General documentation about man-pages and man-page-formatting:
man(1), man(7), http://www.tldp.org/HOWTO/Man-Page/
-->
<!-- Fill in your name for FIRSTNAME and SURNAME. -->
<!ENTITY dhfirstname "FIRSTNAME">
<!ENTITY dhsurname "SURNAME">
<!-- dhusername could also be set to "&dhfirstname; &dhsurname;". -->
<!ENTITY dhusername "Wouter Wijsman">
<!ENTITY dhemail "wwijsman@live.nl">
<!-- SECTION should be 1-8, maybe w/ subsection other parameters are
allowed: see man(7), man(1) and
http://www.tldp.org/HOWTO/Man-Page/q2.html. -->
<!ENTITY dhsection "SECTION">
<!-- TITLE should be something like "User commands" or similar (see
http://www.tldp.org/HOWTO/Man-Page/q2.html). -->
<!ENTITY dhtitle "vaporos-flatpak-manager User Manual">
<!ENTITY dhucpackage "Vaporos-flatpak-manager">
<!ENTITY dhpackage "vaporos-flatpak-manager">
]>
<refentry>
<refentryinfo>
<title>&dhtitle;</title>
<productname>&dhpackage;</productname>
<authorgroup>
<author>
<firstname>&dhfirstname;</firstname>
<surname>&dhsurname;</surname>
<contrib>Wrote this manpage for the Debian system.</contrib>
<address>
<email>&dhemail;</email>
</address>
</author>
</authorgroup>
<copyright>
<year>2007</year>
<holder>&dhusername;</holder>
</copyright>
<legalnotice>
<para>This manual page was written for the Debian system
(and may be used by others).</para>
<para>Permission is granted to copy, distribute and/or modify this
document under the terms of the GNU General Public License,
Version 2 or (at your option) any later version published by
the Free Software Foundation.</para>
<para>On Debian systems, the complete text of the GNU General Public
License can be found in
<filename>/usr/share/common-licenses/GPL</filename>.</para>
</legalnotice>
</refentryinfo>
<refmeta>
<refentrytitle>&dhucpackage;</refentrytitle>
<manvolnum>&dhsection;</manvolnum>
</refmeta>
<refnamediv>
<refname>&dhpackage;</refname>
<refpurpose>program to do something</refpurpose>
</refnamediv>
<refsynopsisdiv>
<cmdsynopsis>
<command>&dhpackage;</command>
<!-- These are several examples, how syntaxes could look -->
<arg choice="plain"><option>-e <replaceable>this</replaceable></option></arg>
<arg choice="opt"><option>--example=<parameter>that</parameter></option></arg>
<arg choice="opt">
<group choice="req">
<arg choice="plain"><option>-e</option></arg>
<arg choice="plain"><option>--example</option></arg>
</group>
<replaceable class="option">this</replaceable>
</arg>
<arg choice="opt">
<group choice="req">
<arg choice="plain"><option>-e</option></arg>
<arg choice="plain"><option>--example</option></arg>
</group>
<group choice="req">
<arg choice="plain"><replaceable>this</replaceable></arg>
<arg choice="plain"><replaceable>that</replaceable></arg>
</group>
</arg>
</cmdsynopsis>
<cmdsynopsis>
<command>&dhpackage;</command>
<!-- Normally the help and version options make the programs stop
right after outputting the requested information. -->
<group choice="opt">
<arg choice="plain">
<group choice="req">
<arg choice="plain"><option>-h</option></arg>
<arg choice="plain"><option>--help</option></arg>
</group>
</arg>
<arg choice="plain">
<group choice="req">
<arg choice="plain"><option>-v</option></arg>
<arg choice="plain"><option>--version</option></arg>
</group>
</arg>
</group>
</cmdsynopsis>
</refsynopsisdiv>
<refsect1 id="description">
<title>DESCRIPTION</title>
<para>This manual page documents briefly the
<command>&dhpackage;</command> and <command>bar</command>
commands.</para>
<para>This manual page was written for the Debian distribution
because the original program does not have a manual page.
Instead, it has documentation in the GNU <citerefentry>
<refentrytitle>info</refentrytitle>
<manvolnum>1</manvolnum>
</citerefentry> format; see below.</para>
<para><command>&dhpackage;</command> is a program that...</para>
</refsect1>
<refsect1 id="options">
<title>OPTIONS</title>
<para>The program follows the usual GNU command line syntax,
with long options starting with two dashes (`-'). A summary of
options is included below. For a complete description, see the
<citerefentry>
<refentrytitle>info</refentrytitle>
<manvolnum>1</manvolnum>
</citerefentry> files.</para>
<variablelist>
<!-- Use the variablelist.term.separator and the
variablelist.term.break.after parameters to
control the term elements. -->
<varlistentry>
<term><option>-e <replaceable>this</replaceable></option></term>
<term><option>--example=<replaceable>that</replaceable></option></term>
<listitem>
<para>Does this and that.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-h</option></term>
<term><option>--help</option></term>
<listitem>
<para>Show summary of options.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-v</option></term>
<term><option>--version</option></term>
<listitem>
<para>Show version of program.</para>
</listitem>
</varlistentry>
</variablelist>
</refsect1>
<refsect1 id="files">
<title>FILES</title>
<variablelist>
<varlistentry>
<term><filename>/etc/foo.conf</filename></term>
<listitem>
<para>The system-wide configuration file to control the
behaviour of <application>&dhpackage;</application>. See
<citerefentry>
<refentrytitle>foo.conf</refentrytitle>
<manvolnum>5</manvolnum>
</citerefentry> for further details.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><filename>${HOME}/.foo.conf</filename></term>
<listitem>
<para>The per-user configuration file to control the
behaviour of <application>&dhpackage;</application>. See
<citerefentry>
<refentrytitle>foo.conf</refentrytitle>
<manvolnum>5</manvolnum>
</citerefentry> for further details.</para>
</listitem>
</varlistentry>
</variablelist>
</refsect1>
<refsect1 id="environment">
<title>ENVIRONMENT</title>
<variablelist>
<varlistentry>
<term><envar>FOO_CONF</envar></term>
<listitem>
<para>If used, the defined file is used as configuration
file (see also <xref linkend="files"/>).</para>
</listitem>
</varlistentry>
</variablelist>
</refsect1>
<refsect1 id="diagnostics">
<title>DIAGNOSTICS</title>
<para>The following diagnostics may be issued
on <filename class="devicefile">stderr</filename>:</para>
<variablelist>
<varlistentry>
<term><errortext>Bad configuration file. Exiting.</errortext></term>
<listitem>
<para>The configuration file seems to contain a broken configuration
line. Use the <option>--verbose</option> option, to get more info.
</para>
</listitem>
</varlistentry>
</variablelist>
<para><command>&dhpackage;</command> provides some return codes, that can
be used in scripts:</para>
<segmentedlist>
<segtitle>Code</segtitle>
<segtitle>Diagnostic</segtitle>
<seglistitem>
<seg><errorcode>0</errorcode></seg>
<seg>Program exited successfully.</seg>
</seglistitem>
<seglistitem>
<seg><errorcode>1</errorcode></seg>
<seg>The configuration file seems to be broken.</seg>
</seglistitem>
</segmentedlist>
</refsect1>
<refsect1 id="bugs">
<!-- Or use this section to tell about upstream BTS. -->
<title>BUGS</title>
<para>The program is currently limited to only work
with the <package>foobar</package> library.</para>
<para>The upstreams <acronym>BTS</acronym> can be found
at <ulink url="http://bugzilla.foo.tld"/>.</para>
</refsect1>
<refsect1 id="see_also">
<title>SEE ALSO</title>
<!-- In alpabetical order. -->
<para><citerefentry>
<refentrytitle>bar</refentrytitle>
<manvolnum>1</manvolnum>
</citerefentry>, <citerefentry>
<refentrytitle>baz</refentrytitle>
<manvolnum>1</manvolnum>
</citerefentry>, <citerefentry>
<refentrytitle>foo.conf</refentrytitle>
<manvolnum>5</manvolnum>
</citerefentry></para>
<para>The programs are documented fully by <citetitle>The Rise and
Fall of a Fooish Bar</citetitle> available via the <citerefentry>
<refentrytitle>info</refentrytitle>
<manvolnum>1</manvolnum>
</citerefentry> system.</para>
</refsect1>
</refentry>
| 37.869863 | 84 | 0.633297 |
08060b09518cdf82d9f05bfd49f5c054da624fd2 | 584 | exs | Elixir | made_at_eps/config/test.exs | EastsidePreparatorySchool/MadeAtEPS | cea5b6db5772ad4ad78b2bfb8ebd6643c35c38cb | [
"MIT"
] | null | null | null | made_at_eps/config/test.exs | EastsidePreparatorySchool/MadeAtEPS | cea5b6db5772ad4ad78b2bfb8ebd6643c35c38cb | [
"MIT"
] | null | null | null | made_at_eps/config/test.exs | EastsidePreparatorySchool/MadeAtEPS | cea5b6db5772ad4ad78b2bfb8ebd6643c35c38cb | [
"MIT"
] | null | null | null | import Config
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :made_at_eps, MadeAtEpsWeb.Endpoint,
http: [ip: {127, 0, 0, 1}, port: 4002],
secret_key_base: "bPDEOb86f9Fe4XAQ9oTXVjRDbLczby+fgYrOBGQ64lUWvL0BAT+7upYBu8YFaOa7",
server: false
# In test we don't send emails.
config :made_at_eps, MadeAtEps.Mailer,
adapter: Swoosh.Adapters.Test
# Print only warnings and errors during test
config :logger, level: :warn
# Initialize plugs at runtime for faster test compilation
config :phoenix, :plug_init_mode, :runtime
| 30.736842 | 86 | 0.767123 |
080648721a954a0cc63d18ae958543add151cd57 | 2,809 | exs | Elixir | mix.exs | zacky1972/swift_elixir_test | a60bace9478452f8c8e8a7016ccd495acef4b7b8 | [
"Apache-2.0"
] | null | null | null | mix.exs | zacky1972/swift_elixir_test | a60bace9478452f8c8e8a7016ccd495acef4b7b8 | [
"Apache-2.0"
] | null | null | null | mix.exs | zacky1972/swift_elixir_test | a60bace9478452f8c8e8a7016ccd495acef4b7b8 | [
"Apache-2.0"
] | null | null | null | defmodule SwiftElixirTest.MixProject do
use Mix.Project
def project do
[
app: :swift_elixir_test,
version: "0.1.0",
elixir: "~> 1.11",
start_permanent: Mix.env() == :prod,
deps: deps(),
compilers: [:elixir_make] ++ Mix.compilers(),
aliases: [
compile: [&autoreconf/1, &configure/1, "compile"],
clean: [&autoreconf/1, &configure/1, "clean"]
],
make_clean: ["clean"]
]
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
[
{:elixir_make, "~> 0.6.2", runtime: false}
]
end
defp autoreconf(_args) do
System.cmd("autoreconf", ["-i"])
end
defp configure(_args) do
arch = get_arch(System.get_env("REBAR_TARGET_ARCH"))
System.cmd(
"#{File.cwd!()}/configure",
["--prefix=#{Mix.Project.app_path()}/priv", "--host=#{arch}", "--target=#{arch}"]
)
end
defp get_arch(nil) do
lib_dir =
System.get_env(
"ERL_EI_LIBDIR",
:code.root_dir() |> to_string() |> Kernel.<>("/usr/lib")
)
System.cmd("ar", ["-xv", "#{lib_dir}/libei.a", "ei_compat.o"])
{uname_m, 0} = System.cmd("uname", ["-m"])
{uname_s, 0} = System.cmd("uname", ["-s"])
{uname_r, 0} = System.cmd("uname", ["-r"])
uname_m = String.trim(uname_m)
uname_s = String.trim(uname_s)
uname_r = String.trim(uname_r)
r =
case System.cmd("file", ["ei_compat.o"]) do
{result, 0} ->
l = result |> String.trim() |> String.split()
arch =
Enum.filter(
%{
"x86_64" => l |> Enum.filter(&String.match?(&1, ~r/x86.64/)) |> length,
"arm64" => l |> Enum.filter(&String.match?(&1, ~r/arm64/)) |> length,
"aarch64" => l |> Enum.filter(&String.match?(&1, ~r/aarch64/)) |> length
},
fn {_, v} -> v != 0 end
)
platform =
Enum.filter(
%{
"apple-darwin#{uname_r}" =>
l |> Enum.filter(&String.match?(&1, ~r/Mach-O/)) |> length,
"linux-gnu" => l |> Enum.filter(&String.match?(&1, ~r/ELF/)) |> length
},
fn {_, v} -> v != 0 end
)
"#{arch |> hd() |> elem(0)}-#{platform |> hd() |> elem(0) |> String.trim()}"
_ ->
platform =
case uname_s do
"Linux" -> "linux-gnu"
"Darwin" -> "apple-darwin#{uname_r}"
_ -> raise "unsupported platform"
end
"#{uname_m}-#{platform}"
end
File.rm("ei_compat.o")
r
end
defp get_arch(arch), do: arch
end
| 26.009259 | 88 | 0.491278 |
0806729bf2f418ca2daa9dbf699f0070d75b9212 | 799 | ex | Elixir | stringStuff.ex | ayarhlaine/hello-elixir | 57b19cd8bf0bd7bd8217b71a482c0da53ce8ae85 | [
"MIT"
] | null | null | null | stringStuff.ex | ayarhlaine/hello-elixir | 57b19cd8bf0bd7bd8217b71a482c0da53ce8ae85 | [
"MIT"
] | null | null | null | stringStuff.ex | ayarhlaine/hello-elixir | 57b19cd8bf0bd7bd8217b71a482c0da53ce8ae85 | [
"MIT"
] | null | null | null | # This module contain string methods.
defmodule StringStuff do
def main do
my_first_str = "My String"
my_longer_str = my_first_str <> " " <> "is longer"
IO.puts "First string length : #{String.length(my_first_str)}"
IO.puts "Longer string length : #{String.length(my_longer_str)}"
IO.puts "Equal : #{"Egg" === "egg"}"
IO.puts "Contain : #{String.contains?(my_first_str, "My")}"
IO.puts "First : #{String.first(my_first_str)}"
IO.puts "Index : #{String.at(my_first_str, 4)}"
IO.puts "Substring : #{String.slice(my_first_str, 1, 4)}"
IO.inspect String.split(my_longer_str, " ")
IO.puts String.reverse(my_longer_str)
IO.puts String.upcase(my_longer_str)
IO.puts String.downcase(my_longer_str)
IO.puts String.capitalize(my_longer_str)
end
end
| 39.95 | 68 | 0.680851 |
080685c80a622a9ed23d22f6e708c6a72c4bd135 | 734 | ex | Elixir | lib/subtitle.ex | san650/subtitle | d0bc4252b1b84fb167d09e68d4f1c977037f7f40 | [
"MIT"
] | null | null | null | lib/subtitle.ex | san650/subtitle | d0bc4252b1b84fb167d09e68d4f1c977037f7f40 | [
"MIT"
] | 3 | 2019-09-15T16:04:36.000Z | 2019-09-16T13:01:23.000Z | lib/subtitle.ex | san650/subtitle | d0bc4252b1b84fb167d09e68d4f1c977037f7f40 | [
"MIT"
] | 1 | 2021-04-24T07:40:12.000Z | 2021-04-24T07:40:12.000Z | alias Subtitle.SubRip
alias Subtitle.MicroDVD
defmodule Subtitle do
@moduledoc """
Documentation for Subtitle.
"""
@doc """
Returns a stream of %Subtitle.Frame{} structs
"""
def from_file(path, options \\ []) do
file_options =
case Keyword.get(options, :encoding) do
nil -> []
encoding -> [encoding: encoding]
end
path
|> File.stream!(file_options, :line)
|> by_file_extension(Path.extname(path), options)
end
defp by_file_extension(stream, ".srt", _options) do
SubRip.stream(stream)
end
defp by_file_extension(stream, ext, options) when ext in [".txt", ".sub"] do
fps = Keyword.get(options, :fps, 23.976)
MicroDVD.stream(stream, fps: fps)
end
end
| 21.588235 | 78 | 0.648501 |
08071fed6155e0004b2bfa7364630edf347cd566 | 5,469 | ex | Elixir | apps/rig_inbound_gateway/lib/rig_inbound_gateway_web/presence/channel.ex | maxglassie/reactive-interaction-gateway | 36b68fc75c71b9b4c3b6bd70fb11900c67172137 | [
"Apache-2.0"
] | null | null | null | apps/rig_inbound_gateway/lib/rig_inbound_gateway_web/presence/channel.ex | maxglassie/reactive-interaction-gateway | 36b68fc75c71b9b4c3b6bd70fb11900c67172137 | [
"Apache-2.0"
] | null | null | null | apps/rig_inbound_gateway/lib/rig_inbound_gateway_web/presence/channel.ex | maxglassie/reactive-interaction-gateway | 36b68fc75c71b9b4c3b6bd70fb11900c67172137 | [
"Apache-2.0"
] | null | null | null | defmodule RigInboundGatewayWeb.Presence.Channel do
@moduledoc """
The presence channel is used to track a user's connected devices.
To this end, there is also only a single room for every user. This is used,
for instance, by the Kafka consumer code to broadcast incoming messages to the
target users' channels, in order to distribute the messages to all connected
devices.
Note that keeping track of connected devices is done by the Phoenix PubSub
module, so it also works with distributed nodes.
"""
use RigInboundGatewayWeb, :channel
use Rig.Config, :custom_validation
require Logger
alias RigInboundGatewayWeb.Presence
# Confex callback
defp validate_config!(config) do
%{
jwt_user_field: config |> Keyword.fetch!(:jwt_user_field),
jwt_roles_field: config |> Keyword.fetch!(:jwt_roles_field),
privileged_roles: MapSet.new(config |> Keyword.fetch!(:privileged_roles))
}
end
@doc """
The room name for a specific user.
"""
@spec user_channel_name(String.t) :: String.t
def user_channel_name(username), do: "user:#{username}"
@doc """
The room name for a specific role.
"""
@spec role_channel_name(String.t) :: String.t
def role_channel_name(role), do: "role:#{role}"
defp extract_username_and_roles(socket) do
user_info = socket.assigns.user_info
conf = config()
{
_username = Map.fetch!(user_info, conf.jwt_user_field),
_roles = Map.fetch!(user_info, conf.jwt_roles_field)
}
end
@doc """
Join a channel.
For `user:*` channels, joining is only allowed for the owner of the channel (e.g.,
alice for `user:alice`) or for a person that has elevated privileges (= has
authorized role). The same applies to `role:*` channels, except that they have no
owner, so only users with an authorized role are permitted.
"""
@spec join(String.t, map, map) :: {atom, map}
def join("user:" <> user_subtopic_name = room, _params, socket) do
{username, roles} = extract_username_and_roles(socket)
cond do
username == user_subtopic_name ->
send(self(), {:after_join, username, roles})
authorized_join(room, username, socket)
has_authorized_role?(roles) ->
send(self(), {:after_join, user_subtopic_name})
authorized_join(room, username, socket)
true -> unauthorized_join(room, username)
end
end
@spec join(String.t, map, map) :: {atom, map}
def join("role:" <> _ = room, _params, socket) do
{username, roles} = extract_username_and_roles(socket)
if has_authorized_role?(roles) do
authorized_join(room, username, socket)
else
unauthorized_join(room, username)
end
end
@doc """
Sends off outgoing messages.
Apparently, this is needed as soon as an external PubSub server is in use, as this
disables "fastlane" - the result is that a different callback is being used that
expects this method to be implemented (see `Phoenix.Channel.Server`). According to
the docs, without fastlane the performance is degraded, but it doesn't state to what
extent.
"""
def handle_out(event, payload, socket) do
push(socket, event, payload)
{:noreply, socket}
end
@doc """
Start tracking presences.
"""
@spec handle_info({:after_join, String.t, [String.t]}, map) :: {:noreply, map}
def handle_info({:after_join, username, roles}, socket) do
# track global role channels
push(socket, "presence_state", Presence.list(socket))
track_multiple_presences("role", roles, socket)
# track user specific channel
track_presence("user:#{username}", socket)
{:noreply, socket}
end
@spec handle_info({:after_join, String.t}, map) :: {:noreply, map}
def handle_info({:after_join, username}, socket) do
# track user specific channel
track_presence("user:#{username}", socket)
{:noreply, socket}
end
@doc """
List all presences in given topic.
"""
@spec channels_list(String.t) :: map
def channels_list(topic), do: Presence.list(topic)
@spec track_multiple_presences(String.t, list(String.t), map) :: any
defp track_multiple_presences(topic_namespace, subtopics, socket) do
Enum.each(subtopics, fn(subtopic) ->
track_presence("#{topic_namespace}:#{subtopic}", socket)
end)
end
@spec track_presence(String.t, map) :: any
defp track_presence(topic, socket) do
user_field = config().jwt_user_field
username = socket.assigns.user_info |> Map.fetch!(user_field)
{:ok, _} = Presence.track(
socket.channel_pid,
topic,
username,
Map.merge(socket.assigns.user_info,
%{
time: System.system_time(:millisecond),
address: "192.168.0.1",
device: "desktop",
browser: "Chrome",
}
)
)
end
@spec has_authorized_role?(list(String.t)) :: boolean
defp has_authorized_role?(roles) do
roles
|> MapSet.new
|> MapSet.intersection(config().privileged_roles)
|> MapSet.size
|> Kernel.>(0)
end
@spec authorized_join(String.t, String.t, map) :: {:ok, map}
defp authorized_join(room, username, socket) do
Logger.debug(fn -> "user #{inspect username} has joined #{room}" end)
{:ok, socket}
end
@spec unauthorized_join(String.t, String.t) :: {:error, String.t}
defp unauthorized_join(room, username) do
msg = "unauthorized user with id #{inspect username} tried to join #{inspect room}!"
Logger.warn(msg)
{:error, msg}
end
end
| 31.431034 | 88 | 0.681477 |
08073b7506d19a8a27db9ed151c51f894e9c95d2 | 285 | ex | Elixir | lib/magpie_web/views/custom_record_view.ex | magpie-ea/magpie-backend | f8fe118583f2460f4f3dc1daa8758b7b758ab606 | [
"MIT"
] | 1 | 2020-05-31T21:54:40.000Z | 2020-05-31T21:54:40.000Z | lib/magpie_web/views/custom_record_view.ex | magpie-ea/magpie-backend | f8fe118583f2460f4f3dc1daa8758b7b758ab606 | [
"MIT"
] | 64 | 2019-07-29T22:06:16.000Z | 2022-03-28T23:46:58.000Z | lib/magpie_web/views/custom_record_view.ex | magpie-ea/magpie-backend | f8fe118583f2460f4f3dc1daa8758b7b758ab606 | [
"MIT"
] | 1 | 2021-02-06T10:23:25.000Z | 2021-02-06T10:23:25.000Z | defmodule Magpie.CustomRecordView do
use MagpieWeb, :view
def get_endpoint_url(type, id) do
base_url = Application.get_env(:magpie, :real_url, Magpie.Endpoint.url())
path = Magpie.Router.Helpers.custom_record_path(Magpie.Endpoint, type, id)
base_url <> path
end
end
| 28.5 | 78 | 0.74386 |
08077175988587b3aaee7644afa579ff1880ada8 | 1,615 | ex | Elixir | clients/content/lib/google_api/content/v2/model/lia_about_page_settings.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/model/lia_about_page_settings.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/model/lia_about_page_settings.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Content.V2.Model.LiaAboutPageSettings do
@moduledoc """
## Attributes
* `status` (*type:* `String.t`, *default:* `nil`) - The status of the verification process for the About page.
Acceptable values are:
- "`active`"
- "`inactive`"
- "`pending`"
* `url` (*type:* `String.t`, *default:* `nil`) - The URL for the About page.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:status => String.t(),
:url => String.t()
}
field(:status)
field(:url)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.LiaAboutPageSettings do
def decode(value, options) do
GoogleApi.Content.V2.Model.LiaAboutPageSettings.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.LiaAboutPageSettings do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 29.363636 | 114 | 0.700929 |
0807c057ea8e735ffd7a027b2b5803d7c3cd4de6 | 1,220 | exs | Elixir | mix.exs | vsajip/ex-cfg-lib | 8fcef6ef3f33f55071ef31d5a4b63b298ed21ce1 | [
"BSD-3-Clause"
] | null | null | null | mix.exs | vsajip/ex-cfg-lib | 8fcef6ef3f33f55071ef31d5a4b63b298ed21ce1 | [
"BSD-3-Clause"
] | null | null | null | mix.exs | vsajip/ex-cfg-lib | 8fcef6ef3f33f55071ef31d5a4b63b298ed21ce1 | [
"BSD-3-Clause"
] | null | null | null | #
# Copyright (C) 2021 Vinay Sajip <vinay_sajip@yahoo.co.uk>
#
# See LICENSE file for usage rights.
#
defmodule CFG.MixProject do
use Mix.Project
def project do
[
app: :cfg_lib,
version: "0.1.0",
elixir: "~> 1.1-dev",
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
description: description(),
source_url: "https://github.com/vsajip/ex-cfg-lib",
homepage_url: "https://docs.red-dove.com/cfg/",
package: package(),
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
applications: [:complex_num],
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:complex_num, "~> 1.0.0"},
{:ex_doc, "~> 0.25", only: [:dev, :test], runtime: false}
]
end
defp description() do
"A library for working with the CFG configuration format."
end
defp package() do
[
licenses: ["BSD-3-Clause"],
links: %{
"Source repository" => "https://github.com/vsajip/ex-cfg-lib",
"CFG documentation" => "https://docs.red-dove.com/cfg/"
}
]
end
end
| 22.592593 | 70 | 0.588525 |
0807c856aa9831c3bea398f7c61559a97b15773c | 1,188 | ex | Elixir | lib/trento/application/usecases/tags/tags.ex | trento-project/web | 3260b30c781bffbbb0e5205cd650966c4026b9ac | [
"Apache-2.0"
] | 1 | 2022-03-22T16:59:34.000Z | 2022-03-22T16:59:34.000Z | lib/trento/application/usecases/tags/tags.ex | trento-project/web | 3260b30c781bffbbb0e5205cd650966c4026b9ac | [
"Apache-2.0"
] | 24 | 2022-03-22T16:45:25.000Z | 2022-03-31T13:00:02.000Z | lib/trento/application/usecases/tags/tags.ex | trento-project/web | 3260b30c781bffbbb0e5205cd650966c4026b9ac | [
"Apache-2.0"
] | 1 | 2022-03-30T14:16:16.000Z | 2022-03-30T14:16:16.000Z | defmodule Trento.Tags do
@moduledoc """
Tag related functions
"""
import Ecto.Query
alias Trento.Tag
alias Trento.Repo
@type taggable_resource :: :host | :cluster | :sap_system | :database
@spec add_tag(String.t(), Ecto.UUID.t(), taggable_resource) ::
{:ok, Ecto.Schema.t()} | {:error, any}
def add_tag(value, resource_id, resource_type) do
changeset =
Tag.changeset(%Tag{}, %{
value: String.trim(value),
resource_id: resource_id,
resource_type: resource_type
})
case Repo.insert(changeset,
conflict_target: [:value, :resource_id],
on_conflict: :nothing
) do
{:ok, _} = result ->
result
{:error, changeset} ->
{:error,
Ecto.Changeset.traverse_errors(
changeset,
fn {msg, _} -> msg end
)}
end
end
@spec delete_tag(String.t(), Ecto.UUID.t()) :: :ok | :not_found
def delete_tag(value, resource_id) do
query =
from t in Tag,
where: ^value == t.value and ^resource_id == t.resource_id
case Repo.delete_all(query) do
{1, _} -> :ok
{0, _} -> :not_found
end
end
end
| 22.846154 | 71 | 0.574074 |
0807d2b6b36517bc16ba84193b93e731689bdc9a | 2,684 | ex | Elixir | lib/day_06_chronal_coordinates.ex | scmx/advent-of-code-2018-elixir | bad5a125fdc98519c29cbca1e5b7f64d61da5869 | [
"MIT"
] | 2 | 2019-01-16T16:10:31.000Z | 2019-05-14T04:41:15.000Z | lib/day_06_chronal_coordinates.ex | scmx/advent-of-code-2018-elixir | bad5a125fdc98519c29cbca1e5b7f64d61da5869 | [
"MIT"
] | null | null | null | lib/day_06_chronal_coordinates.ex | scmx/advent-of-code-2018-elixir | bad5a125fdc98519c29cbca1e5b7f64d61da5869 | [
"MIT"
] | 1 | 2019-01-02T18:13:23.000Z | 2019-01-02T18:13:23.000Z | defmodule Adventofcode.Day06ChronalCoordinates do
use Adventofcode
def largest_area_size(input) do
input
|> parse_coordinates
|> build_grid
|> finite_area_sizes(grid_locations(-99..599), grid_locations(-100..600))
|> hd()
|> elem(0)
end
def safe_area_size(input, distance) do
input
|> parse_coordinates
|> build_grid
|> do_safe_area_size
|> Enum.sort_by(fn {_, dist} -> dist end)
|> Enum.filter(fn {_, dist} -> dist < distance end)
|> length
end
defp do_safe_area_size(grid) do
0..360
|> grid_locations
|> Enum.map(&{&1, distance_to_all_coordinates(&1, grid)})
|> Enum.into(%{})
end
def finite_area_sizes(grid, range1, range2) do
area_sizes(grid, range1)
|> Enum.zip(area_sizes(grid, range2))
|> Enum.filter(fn {{_, n1}, {_, n2}} -> n1 == n2 end)
|> Enum.map(fn {{name, size}, _} -> {size, name} end)
|> Enum.sort()
|> Enum.reverse()
end
def area_sizes(grid, range) do
grid
|> closest_coordinates(range)
|> Map.values()
|> Enum.reduce(%{}, &do_sum_area_sizes/2)
end
defp do_sum_area_sizes(name, acc), do: Map.update(acc, name, 1, &(&1 + 1))
def manhattan_distance({x1, y1}, {x2, y2}), do: abs(x1 - x2) + abs(y1 - y2)
def parse_coordinates(input) do
input
|> String.trim("\n")
|> String.split("\n")
|> Enum.map(&parse_coordinate/1)
end
defp parse_coordinate(coordinate) do
coordinate
|> String.split(", ")
|> Enum.map(&String.to_integer/1)
|> List.to_tuple()
end
def build_grid(coordinates) do
coordinates
|> Enum.zip(names())
|> Enum.into(%{})
end
def names do
?A..?Z
|> Enum.map(&to_string([&1]))
|> Enum.flat_map(fn a -> Enum.map(0..1, &"#{&1}#{a}") end)
|> Enum.sort()
end
def grid_locations(range \\ 0..400) do
Enum.flat_map(range, fn n -> Enum.map(range, &{n, &1}) end)
end
def distance_to_all_coordinates(coordinate, grid) do
grid
|> Map.keys()
|> Enum.map(&manhattan_distance(&1, coordinate))
|> Enum.sum()
end
def closest_coordinates(grid, locations \\ grid_locations()) do
locations
|> Enum.map(&{&1, closest_coordinate(&1, grid)})
|> Enum.into(%{})
end
def closest_coordinate(coordinate, grid) do
case do_closest(coordinate, grid) |> Enum.sort() do
[{distance, _}, {distance, _} | _] -> ".."
[{_, other_coordinate_name} | _] -> String.downcase(other_coordinate_name)
end
end
defp do_closest(coordinate, grid) do
Enum.map(grid, fn {other_coordinate, other_coordinate_name} ->
{manhattan_distance(coordinate, other_coordinate), other_coordinate_name}
end)
end
end
| 25.084112 | 80 | 0.61997 |
0807e96214260019aa0a4a4dff0e032e6d08e7fd | 145 | exs | Elixir | config/config.exs | kianmeng/restlax | 6cded7cd34c49216d182efe4f71e62321545678d | [
"MIT"
] | 1 | 2021-02-09T09:25:37.000Z | 2021-02-09T09:25:37.000Z | config/config.exs | kianmeng/restlax | 6cded7cd34c49216d182efe4f71e62321545678d | [
"MIT"
] | 3 | 2021-05-17T01:33:35.000Z | 2022-01-27T00:23:31.000Z | config/config.exs | kianmeng/restlax | 6cded7cd34c49216d182efe4f71e62321545678d | [
"MIT"
] | 1 | 2022-01-27T00:06:03.000Z | 2022-01-27T00:06:03.000Z | import Config
if config_env() == :test do
config :logger, level: :error
config :tesla, HttpBinCustomAdapterClient, adapter: TestAdapter
end
| 20.714286 | 65 | 0.758621 |
0807ed762cf5d4c82467277a7e8b2a0acd75bd1d | 76 | exs | Elixir | test/test_helper.exs | mazz/Phoenix-File-Upload | 7ab9438bce9c3839ce8129cccb60b40dff2cc538 | [
"MIT"
] | 3 | 2019-04-19T15:55:58.000Z | 2021-06-04T14:02:34.000Z | test/test_helper.exs | mazz/Phoenix-File-Upload | 7ab9438bce9c3839ce8129cccb60b40dff2cc538 | [
"MIT"
] | null | null | null | test/test_helper.exs | mazz/Phoenix-File-Upload | 7ab9438bce9c3839ce8129cccb60b40dff2cc538 | [
"MIT"
] | 2 | 2019-04-19T15:56:02.000Z | 2020-11-15T06:13:49.000Z | ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(FileUploader.Repo, :manual)
| 15.2 | 58 | 0.776316 |
0808007c836bee3d721a748f795210faf530e914 | 1,236 | exs | Elixir | test/onesky/resources/order_test.exs | ahtung/onesky.ex | bd3a150d67e25e1ef6d4b7bc33a593b49a65f37f | [
"Apache-2.0"
] | 6 | 2018-11-22T14:44:26.000Z | 2020-01-20T14:33:26.000Z | test/onesky/resources/order_test.exs | dunyakirkali/onesky.ex | f28fc94722c3b13ff82ee307d2a1cc42db4b6df2 | [
"Apache-2.0"
] | 24 | 2021-01-13T16:45:34.000Z | 2022-03-24T04:07:33.000Z | test/onesky/resources/order_test.exs | dunyakirkali/onesky.ex | f28fc94722c3b13ff82ee307d2a1cc42db4b6df2 | [
"Apache-2.0"
] | null | null | null | defmodule OrderTest do
use ExUnit.Case, async: true
use ExVCR.Mock, adapter: ExVCR.Adapter.Hackney
doctest Onesky.Order
test "get_order" do
use_cassette "order#get" do
{:ok, %Tesla.Env{} = env} = Onesky.client() |> Onesky.Order.get_order(314_254, 1)
assert env.status == 200
assert env.body["meta"]["status"] == 200
assert env.body["data"]["amount"] == "695.00"
end
end
test "list_orders" do
use_cassette "order#list" do
{:ok, %Tesla.Env{} = env} = Onesky.client() |> Onesky.Order.list_orders(314_254)
assert env.status == 200
assert env.body["meta"]["status"] == 200
assert env.body["meta"]["record_count"] == 1
assert length(env.body["data"]) == 1
end
end
test "create_order" do
use_cassette "order#create" do
order = %{files: ["string.po"], to_locale: "zh-TW"}
{:ok, %Tesla.Env{} = env} = Onesky.client() |> Onesky.Order.create_order(314_254, order)
assert env.status == 201
assert env.body["meta"]["status"] == 201
assert env.body["data"]["id"] == 372
assert env.body["data"]["order_type"] == "translate-only"
assert env.body["data"]["note"] == "Message to translator"
end
end
end
| 26.297872 | 94 | 0.609223 |
080820ee1d1b19f752a1f1ae51e69ba8270c2802 | 1,494 | exs | Elixir | test/json_schema_test_suite/draft6/multiple_of_test.exs | romul/xema | 8273e10645cf54e8765a197b1ff0c097994275d9 | [
"MIT"
] | null | null | null | test/json_schema_test_suite/draft6/multiple_of_test.exs | romul/xema | 8273e10645cf54e8765a197b1ff0c097994275d9 | [
"MIT"
] | null | null | null | test/json_schema_test_suite/draft6/multiple_of_test.exs | romul/xema | 8273e10645cf54e8765a197b1ff0c097994275d9 | [
"MIT"
] | null | null | null | defmodule JsonSchemaTestSuite.Draft6.MultipleOfTest do
use ExUnit.Case
import Xema, only: [valid?: 2]
describe "by int" do
setup do
%{
schema:
Xema.from_json_schema(
%{"multipleOf" => 2},
draft: "draft6"
)
}
end
test "int by int", %{schema: schema} do
assert valid?(schema, 10)
end
test "int by int fail", %{schema: schema} do
refute valid?(schema, 7)
end
test "ignores non-numbers", %{schema: schema} do
assert valid?(schema, "foo")
end
end
describe "by number" do
setup do
%{
schema:
Xema.from_json_schema(
%{"multipleOf" => 1.5},
draft: "draft6"
)
}
end
test "zero is multiple of anything", %{schema: schema} do
assert valid?(schema, 0)
end
test "4.5 is multiple of 1.5", %{schema: schema} do
assert valid?(schema, 4.5)
end
test "35 is not multiple of 1.5", %{schema: schema} do
refute valid?(schema, 35)
end
end
describe "by small number" do
setup do
%{
schema:
Xema.from_json_schema(
%{"multipleOf" => 0.0001},
draft: "draft6"
)
}
end
test "0.0075 is multiple of 0.0001", %{schema: schema} do
assert valid?(schema, 0.0075)
end
test "0.00751 is not multiple of 0.0001", %{schema: schema} do
refute valid?(schema, 0.00751)
end
end
end
| 20.189189 | 66 | 0.535475 |
080837e902feeeab90a2144c0ceffe9487cb6838 | 5,173 | exs | Elixir | test/ecto/model/callbacks_test.exs | timgestson/ecto | 1c1eb6d322db04cfa48a4fc81da1332e91adbc1f | [
"Apache-2.0"
] | null | null | null | test/ecto/model/callbacks_test.exs | timgestson/ecto | 1c1eb6d322db04cfa48a4fc81da1332e91adbc1f | [
"Apache-2.0"
] | null | null | null | test/ecto/model/callbacks_test.exs | timgestson/ecto | 1c1eb6d322db04cfa48a4fc81da1332e91adbc1f | [
"Apache-2.0"
] | null | null | null | Code.require_file "../../support/mock_repo.exs", __DIR__
alias Ecto.MockRepo
defmodule Ecto.Model.CallbacksTest do
use ExUnit.Case, async: true
defmodule SomeCallback do
use Ecto.Model
schema "some_callback" do
field :x, :string, default: ""
end
before_delete __MODULE__, :add_to_x
before_delete __MODULE__, :add_to_x, [%{str: "2"}]
before_delete :add_to_x
before_delete :add_to_x, [%{str: "2"}]
before_update :bad_callback
def add_to_x(changeset, %{str: str} \\ %{str: "1"}) do
update_in changeset.model.x, &(&1 <> "," <> str)
end
defp bad_callback(_changeset) do
nil
end
end
test "defines functions for callbacks" do
assert function_exported?(SomeCallback, :before_delete, 1)
end
test "doesn't define callbacks for not-registered events" do
refute function_exported?(SomeCallback, :after_delete, 1)
end
test "applies callbacks" do
changeset = %Ecto.Changeset{model: %SomeCallback{x: "x"}}
assert Ecto.Model.Callbacks.__apply__(SomeCallback, :before_delete, changeset) ==
%Ecto.Changeset{model: %SomeCallback{x: "x,1,2,1,2"}}
end
test "raises on bad callbacks" do
msg = "expected `before_update` callbacks to return a Ecto.Changeset, got: nil"
assert_raise ArgumentError, msg, fn ->
Ecto.Model.Callbacks.__apply__(SomeCallback, :before_update, %Ecto.Changeset{})
end
end
## Repo integration
defmodule AllCallback do
use Ecto.Model
schema "all_callback" do
field :x, :string, default: ""
field :y, :string, default: ""
field :z, :string, default: ""
field :before, :any, virtual: true
field :after, :any, virtual: true
field :xyz, :string, virtual: true
end
before_insert __MODULE__, :changeset_before
after_insert __MODULE__, :changeset_after
before_update __MODULE__, :changeset_before
after_update __MODULE__, :changeset_after
before_delete __MODULE__, :changeset_before
after_delete __MODULE__, :changeset_after
after_load __MODULE__, :changeset_load
def changeset_before(%{repo: MockRepo} = changeset) do
put_in(changeset.model.before, changeset.changes)
|> delete_change(:z)
end
def changeset_after(%{repo: MockRepo} = changeset) do
put_in(changeset.model.after, changeset.changes)
end
def changeset_load(model) do
Map.put(model, :xyz, model.x <> model.y <> model.z)
end
end
test "wraps operations into transactions if callback present" do
model = %SomeCallback{x: "x"}
MockRepo.insert model
refute_received {:transaction, _fun}
model = %AllCallback{x: "x"}
MockRepo.insert model
assert_received {:transaction, _fun}
end
test "before_insert and after_insert with model" do
model = %AllCallback{x: "x"}
model = MockRepo.insert model
assert model.before == %{x: "x", y: "", z: ""}
assert model.after == %{x: "x", y: ""}
model = %AllCallback{id: 1, x: "x"}
model = MockRepo.insert model
assert model.before == %{id: 1, x: "x", y: "", z: ""}
assert model.after == %{id: 1, x: "x", y: ""}
end
test "before_update and after_update with model" do
model = %AllCallback{id: 1, x: "x"}
model = MockRepo.update model
assert model.before == %{x: "x", y: "", z: ""}
assert model.after == %{x: "x", y: ""}
end
test "before_delete and after_delete with model" do
model = %AllCallback{id: 1, x: "x"}
model = MockRepo.delete model
assert model.before == %{}
assert model.after == %{}
end
test "before_insert and after_insert with changeset" do
changeset = Ecto.Changeset.cast(%AllCallback{x: "x", y: "z"},
%{"y" => "y", "z" => "z"}, ~w(y z), ~w())
model = MockRepo.insert changeset
assert model.before == %{x: "x", y: "y", z: "z"}
assert model.after == %{x: "x", y: "y"}
assert model.x == "x"
assert model.y == "y"
assert model.z == ""
end
test "before_update and after_update with changeset" do
changeset = Ecto.Changeset.cast(%AllCallback{id: 1, x: "x", y: "z"},
%{"y" => "y", "z" => "z"}, ~w(y z), ~w())
model = MockRepo.update changeset
assert model.before == %{y: "y", z: "z"}
assert model.after == %{y: "y"}
assert model.x == "x"
assert model.y == "y"
assert model.z == ""
end
test "before_insert and after_insert with id in changeset" do
changeset = Ecto.Changeset.cast(%AllCallback{},
%{"id" => 1}, ~w(id), ~w())
model = MockRepo.insert changeset
assert model.before[:id] == 1
assert model.after[:id] == 1
end
test "before_update and after_update with id in changeset" do
changeset = Ecto.Changeset.cast(%AllCallback{id: 0},
%{"id" => 1}, ~w(id), ~w())
model = MockRepo.update changeset
assert model.before[:id] == 1
assert model.after[:id] == 1
end
test "after_load with model" do
model = AllCallback.__schema__(:load, 2, {nil, nil, 1, "x", "y", "z"})
assert model.id == 1
assert model.xyz == "xyz"
end
end
| 30.791667 | 85 | 0.618983 |
0808a6e52b910bb8b6f993e357cb38059eac3f40 | 1,721 | ex | Elixir | lib/encrypt.ex | flatiron-labs/encrypt | 2757aca85db885f7b0ce938249f7d5c1d3ede3ca | [
"MIT"
] | 3 | 2018-09-05T22:26:27.000Z | 2019-11-28T14:20:07.000Z | lib/encrypt.ex | flatiron-labs/encrypt | 2757aca85db885f7b0ce938249f7d5c1d3ede3ca | [
"MIT"
] | null | null | null | lib/encrypt.ex | flatiron-labs/encrypt | 2757aca85db885f7b0ce938249f7d5c1d3ede3ca | [
"MIT"
] | 2 | 2018-09-11T21:18:12.000Z | 2020-04-28T15:08:50.000Z | defmodule Encrypt do
@moduledoc """
Documentation for Encrypt.
"""
@aad "AES256GCM"
@doc """
`execute_action([action: "generate_secret"])`
Generates a random base64 encoded secret key.
`execute_action([file: path_to_file, action: "encrypt/decrypt", key: secret_key])`
Encrypts or decrypts and base64 encodes/decodes the given file with the secret key.
"""
def execute_action([action: "generate_secret"]) do
:crypto.strong_rand_bytes(16)
|> :base64.encode
end
def execute_action([file: file, action: action, key: key]) do
file_contents = File.read!(file)
apply(__MODULE__,String.to_atom(action), [file_contents, key])
|> write_to_file(file, action)
end
def write_to_file(contents, file, "encrypt") do
{:ok, file_pid } = File.open(file, [:write])
IO.binwrite(file_pid, :base64.encode(contents))
File.close(file_pid)
end
def write_to_file(contents, file, "decrypt") do
{:ok, file_pid } = File.open(file, [:write])
IO.binwrite(file_pid, contents)
File.close(file_pid)
end
@doc """
encrypts the given string of text with the given secret key
"""
def encrypt(val, key) do
iv = :crypto.strong_rand_bytes(16)
{ciphertext, tag} =
:crypto.block_encrypt(:aes_gcm, decode_key(key), iv, {@aad, to_string(val), 16})
iv <> tag <> ciphertext
end
@doc """
decrypts the given string of text with the given secret key
"""
def decrypt(ciphertext, key) do
ciphertext = :base64.decode(ciphertext)
<<iv::binary-16, tag::binary-16, ciphertext::binary>> = ciphertext
:crypto.block_decrypt(:aes_gcm, decode_key(key), iv, {@aad, ciphertext, tag})
end
def decode_key(key) do
:base64.decode(key)
end
end
| 28.683333 | 86 | 0.679256 |
0808b269277019e3ccde4f55bc8c95c41d862a81 | 1,158 | ex | Elixir | apps/fz_http/lib/fz_http/events.ex | mdp/firezone | 53d8f0803a7ef005fdca3ae8c6fa9c3483ae5cbc | [
"Apache-2.0"
] | null | null | null | apps/fz_http/lib/fz_http/events.ex | mdp/firezone | 53d8f0803a7ef005fdca3ae8c6fa9c3483ae5cbc | [
"Apache-2.0"
] | 1 | 2020-04-24T01:53:41.000Z | 2020-04-24T01:53:41.000Z | apps/fz_http/lib/fz_http/events.ex | CloudFire-LLC/cloudfire-ce | 416ea0d9c9528790fdf70c432aa4eb507d7b2074 | [
"Apache-2.0"
] | null | null | null | defmodule FzHttp.Events do
@moduledoc """
Handles interfacing with other processes in the system.
"""
alias FzHttp.{Devices, Rules}
# set_config is used because devices need to be re-evaluated in case a
# device is added to a User that's not active.
def update_device(_device) do
GenServer.call(vpn_pid(), {:set_config, Devices.to_peer_list()})
end
def delete_device(public_key) when is_binary(public_key) do
GenServer.call(vpn_pid(), {:remove_peer, public_key})
end
def delete_device(device) when is_struct(device) do
GenServer.call(vpn_pid(), {:remove_peer, device.public_key})
end
def add_rule(rule) do
GenServer.call(wall_pid(), {:add_rule, Rules.nftables_spec(rule)})
end
def delete_rule(rule) do
GenServer.call(wall_pid(), {:delete_rule, Rules.nftables_spec(rule)})
end
def set_config do
GenServer.call(vpn_pid(), {:set_config, Devices.to_peer_list()})
end
def set_rules do
GenServer.call(wall_pid(), {:set_rules, Rules.to_nftables()})
end
def vpn_pid do
:global.whereis_name(:fz_vpn_server)
end
def wall_pid do
:global.whereis_name(:fz_wall_server)
end
end
| 25.173913 | 73 | 0.71848 |
0808cdaceb83e83a6a56b8fdff74bc86130d3cbb | 337 | exs | Elixir | test/cash_flow_ex/factory_test.exs | diogobaracho/cashflowex | 7b66ff98239407f2ea2e11bf1693783dd94a725b | [
"Apache-2.0"
] | null | null | null | test/cash_flow_ex/factory_test.exs | diogobaracho/cashflowex | 7b66ff98239407f2ea2e11bf1693783dd94a725b | [
"Apache-2.0"
] | null | null | null | test/cash_flow_ex/factory_test.exs | diogobaracho/cashflowex | 7b66ff98239407f2ea2e11bf1693783dd94a725b | [
"Apache-2.0"
] | null | null | null | defmodule CashFlowEx.FactoryTest do
@moduledoc """
This is a test module to make sure our factory setup is working correctly.
You’ll probably want to delete it.
"""
use CashFlowEx.DataCase, async: true
import CashFlowEx.Factory
test "build/1 works with our factory setup" do
assert is_binary(build(:name))
end
end
| 22.466667 | 76 | 0.732938 |
0808d936712eb2b943d7041b0d955b5b76e49f8b | 1,136 | exs | Elixir | test/user/patch/throws_test.exs | kianmeng/patch | d7d8d70a0285129ec67a43473db587011524fe0c | [
"MIT"
] | 57 | 2020-04-22T00:19:04.000Z | 2022-03-20T11:57:00.000Z | test/user/patch/throws_test.exs | kianmeng/patch | d7d8d70a0285129ec67a43473db587011524fe0c | [
"MIT"
] | 9 | 2021-10-29T20:54:56.000Z | 2022-02-19T03:41:01.000Z | test/user/patch/throws_test.exs | kianmeng/patch | d7d8d70a0285129ec67a43473db587011524fe0c | [
"MIT"
] | 2 | 2021-07-02T14:41:48.000Z | 2022-01-12T11:47:26.000Z | defmodule Patch.Test.User.Patch.ThrowsTest do
use ExUnit.Case
use Patch
alias Patch.Test.Support.User.Patch.Throws
describe "patch/3 with throws" do
test "can be used to throw a value" do
assert Throws.example() == :original
patch(Throws, :example, throws(:patched))
assert catch_throw(Throws.example()) == :patched
end
test "can be embedded in a cycle" do
assert Throws.example() == :original
patch(Throws, :example, cycle([1, throws(:patched), 2]))
assert Throws.example() == 1
assert catch_throw(Throws.example()) == :patched
assert Throws.example() == 2
assert Throws.example() == 1
assert catch_throw(Throws.example()) == :patched
assert Throws.example() == 2
end
test "can be embedded in a sequence" do
assert Throws.example() == :original
patch(Throws, :example, sequence([1, throws(:patched), 2]))
assert Throws.example() == 1
assert catch_throw(Throws.example()) == :patched
assert Throws.example() == 2
assert Throws.example() == 2
assert Throws.example() == 2
end
end
end
| 26.418605 | 65 | 0.634683 |
0808ef1a4680f98428c5001c943e7566540cece1 | 506 | ex | Elixir | lib/p14_neplaces/places/visit.ex | tashavanes/p14_neplaces | dbb4fbc675e40b6d4f8e6bef39946987bfde35c8 | [
"MIT"
] | null | null | null | lib/p14_neplaces/places/visit.ex | tashavanes/p14_neplaces | dbb4fbc675e40b6d4f8e6bef39946987bfde35c8 | [
"MIT"
] | 1 | 2018-11-24T22:49:48.000Z | 2018-11-24T22:49:48.000Z | lib/p14_neplaces/places/visit.ex | tashavanes/p14_neplaces | dbb4fbc675e40b6d4f8e6bef39946987bfde35c8 | [
"MIT"
] | null | null | null | defmodule P14Neplaces.Places.Visit do
use Ecto.Schema
import Ecto.Changeset
schema "visits" do
field :date, :date
field :description, :string
field :place, :string
field :rating, :integer
field :state, :string
field :time, :time
timestamps()
end
@doc false
def changeset(visit, attrs) do
visit
|> cast(attrs, [:date, :time, :place, :state, :description, :rating])
|> validate_required([:date, :time, :place, :state, :description, :rating])
end
end
| 21.083333 | 79 | 0.650198 |
0808f54c5fd0a499075bc665bd8235d44e07aa6e | 1,092 | ex | Elixir | Microsoft.Azure.Management.Preview.BotService/lib/microsoft/azure/management/preview/bot_service/model/skype_channel_properties.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | 4 | 2018-09-29T03:43:15.000Z | 2021-04-01T18:30:46.000Z | Microsoft.Azure.Management.Preview.BotService/lib/microsoft/azure/management/preview/bot_service/model/skype_channel_properties.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | null | null | null | Microsoft.Azure.Management.Preview.BotService/lib/microsoft/azure/management/preview/bot_service/model/skype_channel_properties.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | null | null | null | # 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 Microsoft.Azure.Management.Preview.BotService.Model.SkypeChannelProperties do
@moduledoc """
The parameters to provide for the Microsoft Teams channel.
"""
@derive [Poison.Encoder]
defstruct [
:"enableMessaging",
:"enableMediaCards",
:"enableVideo",
:"enableCalling",
:"enableScreenSharing",
:"enableGroups",
:"groupsMode",
:"callingWebHook",
:"isEnabled"
]
@type t :: %__MODULE__{
:"enableMessaging" => boolean(),
:"enableMediaCards" => boolean(),
:"enableVideo" => boolean(),
:"enableCalling" => boolean(),
:"enableScreenSharing" => boolean(),
:"enableGroups" => boolean(),
:"groupsMode" => String.t,
:"callingWebHook" => String.t,
:"isEnabled" => boolean()
}
end
defimpl Poison.Decoder, for: Microsoft.Azure.Management.Preview.BotService.Model.SkypeChannelProperties do
def decode(value, _options) do
value
end
end
| 26 | 106 | 0.675824 |
0808fda51fb760e002b6de7bbead251757039202 | 1,213 | ex | Elixir | example/reactive/api/test/support/conn_case.ex | farolanf/phoenix-socket-dart | 3fb441c53a25e2f7ea6f8f0ca9e7bfc25e45cdfd | [
"BSD-3-Clause"
] | 30 | 2020-11-10T07:32:36.000Z | 2022-02-06T20:34:34.000Z | example/reactive/api/test/support/conn_case.ex | farolanf/phoenix-socket-dart | 3fb441c53a25e2f7ea6f8f0ca9e7bfc25e45cdfd | [
"BSD-3-Clause"
] | 22 | 2020-11-28T20:23:34.000Z | 2022-03-23T22:32:52.000Z | example/reactive/api/test/support/conn_case.ex | farolanf/phoenix-socket-dart | 3fb441c53a25e2f7ea6f8f0ca9e7bfc25e45cdfd | [
"BSD-3-Clause"
] | 19 | 2020-11-10T14:22:05.000Z | 2022-02-15T10:22:43.000Z | defmodule ApiWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use ApiWeb.ConnCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
import Plug.Conn
import Phoenix.ConnTest
import ApiWeb.ConnCase
alias ApiWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint ApiWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Api.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Api.Repo, {:shared, self()})
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 27.568182 | 65 | 0.718054 |
080903ab05265cb69d63a8429faf6dc0352599e3 | 761 | ex | Elixir | lib/rfx/change/convert/to_string.ex | pcorey/rfx | db5be95d93b7aba0cf9799db273d8583c21bfc26 | [
"MIT"
] | 31 | 2021-05-29T22:57:04.000Z | 2022-03-13T16:24:57.000Z | lib/rfx/change/convert/to_string.ex | pcorey/rfx | db5be95d93b7aba0cf9799db273d8583c21bfc26 | [
"MIT"
] | 4 | 2021-06-04T23:34:38.000Z | 2021-07-16T16:01:20.000Z | lib/rfx/change/convert/to_string.ex | pcorey/rfx | db5be95d93b7aba0cf9799db273d8583c21bfc26 | [
"MIT"
] | 4 | 2021-06-11T13:10:04.000Z | 2022-02-11T13:33:16.000Z | defmodule Rfx.Change.Convert.ToString do
@moduledoc false
alias Rfx.Util.Source
def changelist(changelist) when is_list(changelist) do
changelist
|> Enum.map(&changereq/1)
end
def changereq(changereq) do
tgt = changereq |> Map.get(:text_req)
genlog = %{to_string: gen_string(tgt)}
oldlog = Map.get(changereq, :log) || %{}
oldcon = Map.get(oldlog, :convert) || %{}
newcon = Map.merge(oldcon, genlog)
newlog = Map.merge(oldlog, %{convert: newcon})
Map.merge(changereq, %{log: newlog})
end
defp gen_string(%{input_file: path, diff: diff}) do
path
|> File.read!()
|> Source.patch(diff)
end
defp gen_string(%{input_text: source, diff: diff}) do
source
|> Source.patch(diff)
end
end
| 23.060606 | 56 | 0.646518 |
08091691acadce22edb5fb470a8ec2ee7423fe3f | 2,686 | ex | Elixir | lib/prima_auth0_ex/token_provider/cached_token_service.ex | primait/auth0_ex | 15ef5d6d91d8fe00ff703a4f58e1cb32bb169a82 | [
"MIT"
] | 5 | 2021-12-01T10:50:40.000Z | 2022-02-15T13:07:02.000Z | lib/prima_auth0_ex/token_provider/cached_token_service.ex | primait/auth0_ex | 15ef5d6d91d8fe00ff703a4f58e1cb32bb169a82 | [
"MIT"
] | 11 | 2021-12-22T09:19:28.000Z | 2022-03-24T06:15:04.000Z | lib/prima_auth0_ex/token_provider/cached_token_service.ex | primait/auth0_ex | 15ef5d6d91d8fe00ff703a4f58e1cb32bb169a82 | [
"MIT"
] | null | null | null | defmodule PrimaAuth0Ex.TokenProvider.CachedTokenService do
@moduledoc """
Implementation of `PrimaAuth0Ex.TokenProvider.TokenService` that caches tokens on
an external cache in order to limit the requests made to Auth0 by reusing tokens.
The external cache can be shared among different instances of the same service: in that
case, when one of the instances refreshes the token and updates the shared cache, the other
instances will retrieve the new token from the new cache and will not have to generate a new
one from the authorization provider.
"""
alias PrimaAuth0Ex.TokenProvider.{Auth0AuthorizationService, EncryptedRedisTokenCache, TokenService}
@behaviour TokenService
@impl TokenService
def retrieve_token(credentials, audience) do
audience
|> token_cache().get_token_for()
|> refresh_token_on_cache_miss(credentials, audience)
end
@impl TokenService
def refresh_token(credentials, audience, current_token, false = _force_cache_bust) do
audience
|> token_cache().get_token_for()
|> refresh_token_unless_it_changed(current_token, credentials, audience)
end
def refresh_token(credentials, audience, _current_token, true = _force_cache_bust) do
do_refresh_token(credentials, audience)
end
defp refresh_token_on_cache_miss({:error, _}, credentials, audience), do: do_refresh_token(credentials, audience)
defp refresh_token_on_cache_miss({:ok, nil}, credentials, audience), do: do_refresh_token(credentials, audience)
defp refresh_token_on_cache_miss({:ok, cached_token}, _credentials, _audience), do: {:ok, cached_token}
defp refresh_token_unless_it_changed({:error, _}, _, credentials, audience) do
do_refresh_token(credentials, audience)
end
defp refresh_token_unless_it_changed({:ok, nil}, _, credentials, audience) do
do_refresh_token(credentials, audience)
end
defp refresh_token_unless_it_changed({:ok, cached_token}, current_token, _, _) when cached_token != current_token do
{:ok, cached_token}
end
defp refresh_token_unless_it_changed({:ok, _cached_token}, _, credentials, audience) do
do_refresh_token(credentials, audience)
end
defp do_refresh_token(credentials, audience) do
case authorization_service().retrieve_token(credentials, audience) do
{:ok, token} ->
token_cache().set_token_for(audience, token)
{:ok, token}
{:error, description} ->
{:error, description}
end
end
defp authorization_service,
do: Application.get_env(:prima_auth0_ex, :authorization_service, Auth0AuthorizationService)
defp token_cache, do: Application.get_env(:prima_auth0_ex, :token_cache, EncryptedRedisTokenCache)
end
| 38.927536 | 118 | 0.769546 |
08091d532db465739527f208ae508317e172369d | 612 | ex | Elixir | test/support/pages.ex | RatioPBC/epi-locator | 58c90500c4e0071ce365d76ec9812f9051d6a9f9 | [
"Apache-2.0"
] | null | null | null | test/support/pages.ex | RatioPBC/epi-locator | 58c90500c4e0071ce365d76ec9812f9051d6a9f9 | [
"Apache-2.0"
] | 6 | 2021-10-19T01:55:57.000Z | 2022-02-15T01:04:19.000Z | test/support/pages.ex | RatioPBC/epi-locator | 58c90500c4e0071ce365d76ec9812f9051d6a9f9 | [
"Apache-2.0"
] | 2 | 2022-01-21T08:38:50.000Z | 2022-01-21T08:42:04.000Z | defmodule EpiLocatorWeb.Test.Pages do
import Phoenix.ConnTest
import Phoenix.LiveViewTest
alias EpiLocatorWeb.Test
alias Phoenix.LiveViewTest.View
@endpoint EpiLocatorWeb.Endpoint
def visit(conn, path, option \\ nil)
def visit(%Plug.Conn{} = conn, path, nil) do
{:ok, view, _html} = live(conn, path)
view
end
def parse(%Plug.Conn{} = conn),
do: conn |> html_response(200) |> Test.Html.parse_doc()
def parse(%View{} = view),
do: view |> render() |> Test.Html.parse()
def parse(html_string) when is_binary(html_string),
do: html_string |> Test.Html.parse_doc()
end
| 23.538462 | 59 | 0.683007 |
0809512f67e3d901623a07aa103bd31aa5df7db8 | 2,335 | exs | Elixir | test/farmbot_ext/mqtt/terminal_handler_test.exs | bahanni/custom_rpi4 | ddefa85d30bacaae40151a63a9a0ebbf4ad30ed5 | [
"MIT"
] | null | null | null | test/farmbot_ext/mqtt/terminal_handler_test.exs | bahanni/custom_rpi4 | ddefa85d30bacaae40151a63a9a0ebbf4ad30ed5 | [
"MIT"
] | null | null | null | test/farmbot_ext/mqtt/terminal_handler_test.exs | bahanni/custom_rpi4 | ddefa85d30bacaae40151a63a9a0ebbf4ad30ed5 | [
"MIT"
] | null | null | null | defmodule FarmbotOS.TerminalHandlerTest do
use ExUnit.Case
use Mimic
alias FarmbotOS.MQTT.{
TerminalHandler,
TerminalHandlerSupport
}
test "handle_info - unknown messages" do
expect(TerminalHandlerSupport, :tty_send, 1, fn state, message ->
assert message == "UNKNOWN TERMINAL MSG - :unknown_msg"
assert state == :misc_state
end)
reply = TerminalHandler.handle_info(:unknown_msg, :misc_state)
assert reply == {:noreply, :misc_state}
end
test "handle_info - activity timeout" do
fake_state = %TerminalHandler{
iex_pid: self()
}
expect(TerminalHandlerSupport, :tty_send, 1, fn state, message ->
assert message == "=== Session inactivity timeout ==="
assert state == fake_state
end)
expect(TerminalHandlerSupport, :stop_iex, 1, fn state ->
assert state == fake_state
:whatever_stop_iex_returns
end)
reply = TerminalHandler.handle_info(:timeout, fake_state)
assert reply == {:noreply, :whatever_stop_iex_returns}
end
test "handle_info({:tty_data, data}, state) - TTY => MQTT" do
expect(TerminalHandlerSupport, :tty_send, 1, fn state, message ->
assert message == "echo hi"
assert state == :misc_state
end)
reply = TerminalHandler.handle_info({:tty_data, "echo hi"}, :misc_state)
assert reply == {:noreply, :misc_state, 300_000}
end
test "handle_info({:inbound, _, _}, state) - IEX Session active" do
state = %TerminalHandler{iex_pid: self()}
expect(ExTTY, :send_text, 1, fn pid, message ->
assert pid == self()
assert message == "echo hi"
end)
reply = TerminalHandler.handle_info({:inbound, "...", "echo hi"}, state)
assert reply == {:noreply, state, 300_000}
end
test "handle_info - IEX Session NOT active" do
state = %TerminalHandler{iex_pid: nil}
expect(TerminalHandlerSupport, :start_iex, 1, fn old_state ->
assert old_state == state
%{state | iex_pid: self()}
end)
expect(TerminalHandlerSupport, :tty_send, 1, fn new_state, message ->
assert message == "Starting IEx..."
refute new_state.iex_pid
end)
msg = {:inbound, "?", "ls"}
{:noreply, new_state} = reply = TerminalHandler.handle_info(msg, state)
assert new_state.iex_pid
assert reply == {:noreply, new_state}
end
end
| 29.1875 | 76 | 0.663812 |
080983818ba5a1993c39fe3d1760149c12b41a9c | 507 | ex | Elixir | test/e2e/lib/hologram_e2e_web/pages/operators/list_subtraction_page.ex | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 40 | 2022-01-19T20:27:36.000Z | 2022-03-31T18:17:41.000Z | test/e2e/lib/hologram_e2e_web/pages/operators/list_subtraction_page.ex | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 42 | 2022-02-03T22:52:43.000Z | 2022-03-26T20:57:32.000Z | test/e2e/lib/hologram_e2e_web/pages/operators/list_subtraction_page.ex | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 3 | 2022-02-10T04:00:37.000Z | 2022-03-08T22:07:45.000Z | defmodule HologramE2E.Operators.ListSubtractionPage do
use Hologram.Page
route "/e2e/operators/list-subtraction"
def init(_params, _conn) do
%{
left: [1, 2, 3, 1, 2, 3, 1],
right: [1, 3, 3, 4],
result: 0
}
end
def template do
~H"""
<button id="button" on:click="calculate">Calculate</button>
<div id="text">Result = {@result}</div>
"""
end
def action(:calculate, _params, state) do
Map.put(state, :result, state.left -- state.right)
end
end
| 20.28 | 63 | 0.607495 |
0809bdfe1d6d01b598275447efe2921f18596c72 | 1,791 | ex | Elixir | clients/spanner/lib/google_api/spanner/v1/model/list_operations_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/spanner/lib/google_api/spanner/v1/model/list_operations_response.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/spanner/lib/google_api/spanner/v1/model/list_operations_response.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.Spanner.V1.Model.ListOperationsResponse do
@moduledoc """
The response message for Operations.ListOperations.
## Attributes
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - The standard List next-page token.
* `operations` (*type:* `list(GoogleApi.Spanner.V1.Model.Operation.t)`, *default:* `nil`) - A list of operations that matches the specified filter in the request.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:nextPageToken => String.t(),
:operations => list(GoogleApi.Spanner.V1.Model.Operation.t())
}
field(:nextPageToken)
field(:operations, as: GoogleApi.Spanner.V1.Model.Operation, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Spanner.V1.Model.ListOperationsResponse do
def decode(value, options) do
GoogleApi.Spanner.V1.Model.ListOperationsResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Spanner.V1.Model.ListOperationsResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.82 | 166 | 0.738693 |
0809be04d9c48759c4baf422eee3b643a4e1c1fe | 1,677 | ex | Elixir | lib/lifelog_web/controllers/user_reset_password_controller.ex | jahio/lifelog | a3660e65acb3abdaac388b494736a645d825df1f | [
"MIT"
] | null | null | null | lib/lifelog_web/controllers/user_reset_password_controller.ex | jahio/lifelog | a3660e65acb3abdaac388b494736a645d825df1f | [
"MIT"
] | null | null | null | lib/lifelog_web/controllers/user_reset_password_controller.ex | jahio/lifelog | a3660e65acb3abdaac388b494736a645d825df1f | [
"MIT"
] | null | null | null | defmodule LifelogWeb.UserResetPasswordController do
use LifelogWeb, :controller
alias Lifelog.Accounts
plug :get_user_by_reset_password_token when action in [:edit, :update]
def new(conn, _params) do
render(conn, "new.html")
end
def create(conn, %{"user" => %{"email" => email}}) do
if user = Accounts.get_user_by_email(email) do
Accounts.deliver_user_reset_password_instructions(
user,
&Routes.user_reset_password_url(conn, :edit, &1)
)
end
conn
|> put_flash(
:info,
"If your email is in our system, you will receive instructions to reset your password shortly."
)
|> redirect(to: "/")
end
def edit(conn, _params) do
render(conn, "edit.html", changeset: Accounts.change_user_password(conn.assigns.user))
end
# Do not log in the user after reset password to avoid a
# leaked token giving the user access to the account.
def update(conn, %{"user" => user_params}) do
case Accounts.reset_user_password(conn.assigns.user, user_params) do
{:ok, _} ->
conn
|> put_flash(:info, "Password reset successfully.")
|> redirect(to: Routes.user_session_path(conn, :new))
{:error, changeset} ->
render(conn, "edit.html", changeset: changeset)
end
end
defp get_user_by_reset_password_token(conn, _opts) do
%{"token" => token} = conn.params
if user = Accounts.get_user_by_reset_password_token(token) do
conn |> assign(:user, user) |> assign(:token, token)
else
conn
|> put_flash(:error, "Reset password link is invalid or it has expired.")
|> redirect(to: "/")
|> halt()
end
end
end
| 28.423729 | 101 | 0.65653 |
0809cb1844ac24dfb6e9e1a9c2ff65ffd56c6e41 | 312 | exs | Elixir | apps/ldap_write/config/test.exs | puppetlabs/openrobby | a4b70939ee1b878d44cb09d757b7f72e7109ac5d | [
"Apache-2.0"
] | 3 | 2021-04-16T21:54:55.000Z | 2021-04-30T22:15:41.000Z | apps/ldap_write/config/test.exs | puppetlabs/openrobby | a4b70939ee1b878d44cb09d757b7f72e7109ac5d | [
"Apache-2.0"
] | 1 | 2021-06-29T15:54:19.000Z | 2021-06-29T15:54:19.000Z | apps/ldap_write/config/test.exs | puppetlabs/openrobby | a4b70939ee1b878d44cb09d757b7f72e7109ac5d | [
"Apache-2.0"
] | 2 | 2021-04-16T22:23:16.000Z | 2021-05-26T15:52:55.000Z | use Mix.Config
config :ldap_write,
ldap_api: LdapWrapper.Ldap.Sandbox,
hosts: ["ldap1-test.ops.example.net"],
port: 636,
use_ssl: true,
write_dn: "cn=internal-password-reset,ou=service,ou=users,dc=example,dc=com",
write_password: "password"
config :ldap_wrapper, ldap_api: LdapWrapper.Ldap.Sandbox
| 26 | 79 | 0.75 |
0809d97fa7bb06d96cb8dae66249a712ef3a3bb6 | 620 | ex | Elixir | lib/segment/hkvvb.ex | Ablu/fintex | 3dd2088c01a4e035478d09df1e09ec244b54cf87 | [
"MIT"
] | 27 | 2015-08-09T16:36:31.000Z | 2020-01-26T17:47:17.000Z | lib/segment/hkvvb.ex | Ablu/fintex | 3dd2088c01a4e035478d09df1e09ec244b54cf87 | [
"MIT"
] | 14 | 2015-07-31T07:28:07.000Z | 2018-09-06T18:32:37.000Z | lib/segment/hkvvb.ex | Ablu/fintex | 3dd2088c01a4e035478d09df1e09ec244b54cf87 | [
"MIT"
] | 19 | 2015-07-31T01:25:17.000Z | 2019-06-29T16:28:42.000Z | defmodule FinTex.Segment.HKVVB do
@moduledoc false
alias FinTex.Model.Dialog
defstruct [segment: nil]
def new(
s,
%Dialog{
bank: bank,
user_agent_name: user_agent_name,
user_agent_version: user_agent_version
}) do
v = case bank.version do
"300" -> 3
_ -> 2
end
%__MODULE__{s |
segment:
[
["HKVVB", "?", v],
0,
0,
1,
user_agent_name,
user_agent_version
]
}
end
end
defimpl Inspect, for: FinTex.Segment.HKVVB do
use FinTex.Helper.Inspect
end
| 15.897436 | 45 | 0.529032 |
080a0f25d257fd52e5d483a38b6f6397f5dc0744 | 299 | ex | Elixir | lib/gameserver/utils/transform.ex | arcifius/gameserver | 10d5f958aa41484dee9fefd51799c79685c4e0bb | [
"MIT"
] | 4 | 2018-10-08T19:40:29.000Z | 2020-11-23T23:03:57.000Z | lib/gameserver/utils/transform.ex | arcifius/gameserver | 10d5f958aa41484dee9fefd51799c79685c4e0bb | [
"MIT"
] | null | null | null | lib/gameserver/utils/transform.ex | arcifius/gameserver | 10d5f958aa41484dee9fefd51799c79685c4e0bb | [
"MIT"
] | null | null | null | defmodule Gameserver.Utils.Transform do
def to_struct(kind, attrs) do
struct = struct(kind)
Enum.reduce(Map.to_list(struct), struct, fn {k, _}, acc ->
case Map.fetch(attrs, Atom.to_string(k)) do
{:ok, v} -> %{acc | k => v}
:error -> acc
end
end)
end
end
| 23 | 62 | 0.58194 |
080a160d6efe10f945df9c63fcaa6e504aa0b414 | 17,022 | ex | Elixir | lib/ecto/adapters/sql.ex | jwarwick/ecto | d1e43287775579e337a2e6a3763fa53ce2a33e4d | [
"Apache-2.0"
] | null | null | null | lib/ecto/adapters/sql.ex | jwarwick/ecto | d1e43287775579e337a2e6a3763fa53ce2a33e4d | [
"Apache-2.0"
] | null | null | null | lib/ecto/adapters/sql.ex | jwarwick/ecto | d1e43287775579e337a2e6a3763fa53ce2a33e4d | [
"Apache-2.0"
] | null | null | null | defmodule Ecto.Adapters.SQL do
@moduledoc """
Behaviour and implementation for SQL adapters.
The implementation for SQL adapter relies on `DBConnection`
to provide pooling, prepare, execute and more.
Developers that use `Ecto.Adapters.SQL` should implement
the callbacks required both by this module and the ones
from `Ecto.Adapters.SQL.Query` about building queries.
"""
@doc false
defmacro __using__(adapter) do
quote do
@behaviour Ecto.Adapter
@behaviour Ecto.Adapter.Migration
@behaviour Ecto.Adapter.Transaction
@conn __MODULE__.Connection
@adapter unquote(adapter)
@doc false
defmacro __before_compile__(env) do
Ecto.Adapters.SQL.__before_compile__(@conn, env)
end
@doc false
def ensure_all_started(repo, type) do
{_, opts} = repo.__pool__
with {:ok, pool} <- DBConnection.ensure_all_started(opts, type),
{:ok, adapter} <- Application.ensure_all_started(@adapter, type),
# We always return the adapter to force it to be restarted if necessary
do: {:ok, pool ++ List.delete(adapter, @adapter) ++ [@adapter]}
end
@doc false
def child_spec(repo, opts) do
Ecto.Adapters.SQL.child_spec(@conn, @adapter, repo, opts)
end
## Types
@doc false
def autogenerate(:id), do: nil
def autogenerate(:embed_id), do: Ecto.UUID.generate()
def autogenerate(:binary_id), do: Ecto.UUID.bingenerate()
@doc false
def loaders({:embed, _} = type, _), do: [&Ecto.Adapters.SQL.load_embed(type, &1)]
def loaders(:binary_id, type), do: [Ecto.UUID, type]
def loaders(_, type), do: [type]
@doc false
def dumpers({:embed, _} = type, _), do: [&Ecto.Adapters.SQL.dump_embed(type, &1)]
def dumpers(:binary_id, type), do: [type, Ecto.UUID]
def dumpers(_, type), do: [type]
## Query
@doc false
def prepare(:all, query),
do: {:cache, {System.unique_integer([:positive]), @conn.all(query)}}
def prepare(:update_all, query),
do: {:cache, {System.unique_integer([:positive]), @conn.update_all(query)}}
def prepare(:delete_all, query),
do: {:cache, {System.unique_integer([:positive]), @conn.delete_all(query)}}
@doc false
def execute(repo, meta, query, params, process, opts) do
Ecto.Adapters.SQL.execute(repo, meta, query, params, process, opts)
end
@doc false
def insert_all(repo, %{source: {prefix, source}}, header, rows, returning, opts) do
Ecto.Adapters.SQL.insert_all(repo, @conn, prefix, source, header, rows, returning, opts)
end
@doc false
def insert(repo, %{source: {prefix, source}}, params, returning, opts) do
{fields, values} = :lists.unzip(params)
sql = @conn.insert(prefix, source, fields, [fields], returning)
Ecto.Adapters.SQL.struct(repo, @conn, sql, values, returning, opts)
end
@doc false
def update(repo, %{source: {prefix, source}}, fields, filter, returning, opts) do
{fields, values1} = :lists.unzip(fields)
{filter, values2} = :lists.unzip(filter)
sql = @conn.update(prefix, source, fields, filter, returning)
Ecto.Adapters.SQL.struct(repo, @conn, sql, values1 ++ values2, returning, opts)
end
@doc false
def delete(repo, %{source: {prefix, source}}, filter, opts) do
{filter, values} = :lists.unzip(filter)
sql = @conn.delete(prefix, source, filter, [])
Ecto.Adapters.SQL.struct(repo, @conn, sql, values, [], opts)
end
## Transaction
@doc false
def transaction(repo, opts, fun) do
Ecto.Adapters.SQL.transaction(repo, opts, fun)
end
@doc false
def in_transaction?(repo) do
Ecto.Adapters.SQL.in_transaction?(repo)
end
@doc false
def rollback(repo, value) do
Ecto.Adapters.SQL.rollback(repo, value)
end
## Migration
@doc false
def execute_ddl(repo, definition, opts) do
sql = @conn.execute_ddl(definition)
Ecto.Adapters.SQL.query!(repo, sql, [], opts)
:ok
end
defoverridable [prepare: 2, execute: 6, insert: 5, update: 6, delete: 4, insert_all: 6,
execute_ddl: 3, loaders: 2, dumpers: 2, autogenerate: 1, ensure_all_started: 2]
end
end
@doc """
Converts the given query to SQL according to its kind and the
adapter in the given repository.
## Examples
The examples below are meant for reference. Each adapter will
return a different result:
Ecto.Adapters.SQL.to_sql(:all, repo, Post)
{"SELECT p.id, p.title, p.inserted_at, p.created_at FROM posts as p", []}
Ecto.Adapters.SQL.to_sql(:update_all, repo,
from(p in Post, update: [set: [title: ^"hello"]]))
{"UPDATE posts AS p SET title = $1", ["hello"]}
"""
@spec to_sql(:all | :update_all | :delete_all, Ecto.Repo.t, Ecto.Queryable.t) ::
{String.t, [term]}
def to_sql(kind, repo, queryable) do
adapter = repo.__adapter__
queryable
|> Ecto.Queryable.to_query()
|> Ecto.Query.Planner.returning(kind == :all)
|> Ecto.Query.Planner.query(kind, repo, adapter)
|> case do
{_meta, {:cached, {_id, cached}}, params} ->
{String.Chars.to_string(cached), params}
{_meta, {:cache, _update, {_id, prepared}}, params} ->
{prepared, params}
{_meta, {:nocache, {_id, prepared}}, params} ->
{prepared, params}
end
end
@doc """
Same as `query/4` but raises on invalid queries.
"""
@spec query!(Ecto.Repo.t, String.t, [term], Keyword.t) ::
%{rows: nil | [tuple], num_rows: non_neg_integer} | no_return
def query!(repo, sql, params \\ [], opts \\ []) do
query!(repo, sql, map_params(params), fn x -> x end, opts)
end
defp query!(repo, sql, params, mapper, opts) do
case query(repo, sql, params, mapper, opts) do
{:ok, result} -> result
{:error, err} -> raise err
end
end
@doc """
Runs custom SQL query on given repo.
In case of success, it must return an `:ok` tuple containing
a map with at least two keys:
* `:num_rows` - the number of rows affected
* `:rows` - the result set as a list. `nil` may be returned
instead of the list if the command does not yield any row
as result (but still yields the number of affected rows,
like a `delete` command without returning would)
## Options
* `:timeout` - The time in milliseconds to wait for a query to finish,
`:infinity` will wait indefinitely. (default: 15_000)
* `:pool_timeout` - The time in milliseconds to wait for a call to the pool
to finish, `:infinity` will wait indefinitely. (default: 5_000)
* `:log` - When false, does not log the query
## Examples
iex> Ecto.Adapters.SQL.query(MyRepo, "SELECT $1::integer + $2", [40, 2])
{:ok, %{rows: [{42}], num_rows: 1}}
"""
@spec query(Ecto.Repo.t, String.t, [term], Keyword.t) ::
{:ok, %{rows: nil | [tuple], num_rows: non_neg_integer}} | {:error, Exception.t}
def query(repo, sql, params \\ [], opts \\ []) do
query(repo, sql, map_params(params), fn x -> x end, opts)
end
defp query(repo, sql, params, mapper, opts) do
sql_call(repo, :execute, [sql], params, mapper, opts)
end
defp sql_call(repo, callback, args, params, mapper, opts) do
{pool, default_opts} = repo.__pool__
conn = get_conn(pool) || pool
opts = [decode_mapper: mapper] ++ with_log(repo, params, opts ++ default_opts)
args = args ++ [params, opts]
try do
apply(repo.__sql__, callback, [conn | args])
rescue
err in DBConnection.OwnershipError ->
message = err.message <> "\nSee Ecto.Adapters.SQL.Sandbox docs for more information."
reraise %{err | message: message}, System.stacktrace
end
end
defp map_params(params) do
Enum.map params, fn
%{__struct__: _} = value ->
{:ok, value} = Ecto.DataType.dump(value)
value
[_|_] = value ->
{:ok, value} = Ecto.DataType.dump(value)
value
value ->
value
end
end
## Worker
@pool_timeout 5_000
@timeout 15_000
@doc false
def __before_compile__(conn, env) do
config = Module.get_attribute(env.module, :config)
pool = Keyword.get(config, :pool, DBConnection.Poolboy)
if pool == Ecto.Adapters.SQL.Sandbox and config[:pool_size] == 1 do
IO.puts :stderr, "warning: setting the :pool_size to 1 for #{inspect env.module} " <>
"when using the Ecto.Adapters.SQL.Sandbox pool is deprecated and " <>
"won't work as expected. Please remove the :pool_size configuration " <>
"or set it to a reasonable number like 10"
end
pool_name = pool_name(env.module, config)
norm_config = normalize_config(config)
quote do
@doc false
def __sql__, do: unquote(conn)
@doc false
def __pool__, do: {unquote(pool_name), unquote(Macro.escape(norm_config))}
def query(sql, params \\ [], opts \\ []) do
Ecto.Adapters.SQL.query(__MODULE__, sql, params, opts)
end
def query!(sql, params \\ [], opts \\ []) do
Ecto.Adapters.SQL.query!(__MODULE__, sql, params, opts)
end
defoverridable [__pool__: 0]
end
end
defp normalize_config(config) do
config
|> Keyword.delete(:name)
|> Keyword.update(:pool, DBConnection.Poolboy, &normalize_pool/1)
|> Keyword.put_new(:timeout, @timeout)
|> Keyword.put_new(:pool_timeout, @pool_timeout)
end
defp normalize_pool(Ecto.Adapters.SQL.Sandbox),
do: DBConnection.Ownership
defp normalize_pool(pool),
do: pool
defp pool_name(module, config) do
Keyword.get(config, :pool_name, default_pool_name(module, config))
end
defp default_pool_name(repo, config) do
Module.concat(Keyword.get(config, :name, repo), Pool)
end
@doc false
def child_spec(connection, adapter, repo, opts) do
unless Code.ensure_loaded?(connection) do
raise """
could not find #{inspect connection}.
Please verify you have added #{inspect adapter} as a dependency:
{#{inspect adapter}, ">= 0.0.0"}
And remember to recompile Ecto afterwards by cleaning the current build:
mix deps.clean --build ecto
"""
end
# Check if the pool options should overriden
{pool_name, pool_opts} = case Keyword.fetch(opts, :pool) do
{:ok, pool} when pool != Ecto.Adapters.SQL.Sandbox ->
{pool_name(repo, opts), opts}
_ ->
repo.__pool__
end
opts = [name: pool_name] ++ Keyword.delete(opts, :pool) ++ pool_opts
opts =
if function_exported?(repo, :after_connect, 1) and not Keyword.has_key?(opts, :after_connect) do
IO.puts :stderr, "warning: #{inspect repo}.after_connect/1 is deprecated. If you want to " <>
"perform some action after connecting, please set after_connect: {module, fun, args}" <>
"in your repository configuration"
Keyword.put(opts, :after_connect, {repo, :after_connect, []})
else
opts
end
connection.child_spec(opts)
end
## Types
@doc false
def load_embed(type, value) do
Ecto.Type.load(type, value, fn
{:embed, _} = type, value -> load_embed(type, value)
type, value -> Ecto.Type.cast(type, value)
end)
end
@doc false
def dump_embed(type, value) do
Ecto.Type.dump(type, value, fn
{:embed, _} = type, value -> dump_embed(type, value)
_type, value -> {:ok, value}
end)
end
## Query
@doc false
def insert_all(repo, conn, prefix, source, header, rows, returning, opts) do
{rows, params} = unzip_inserts(header, rows)
sql = conn.insert(prefix, source, header, rows, returning)
%{rows: rows, num_rows: num} = query!(repo, sql, Enum.reverse(params), nil, opts)
{num, rows}
end
defp unzip_inserts(header, rows) do
Enum.map_reduce rows, [], fn fields, params ->
Enum.map_reduce header, params, fn key, acc ->
case :lists.keyfind(key, 1, fields) do
{^key, value} -> {key, [value|acc]}
false -> {nil, acc}
end
end
end
end
@doc false
def execute(repo, _meta, {:cache, update, {id, prepared}}, params, nil, opts) do
execute_and_cache(repo, id, update, prepared, params, nil, opts)
end
def execute(repo, %{fields: fields}, {:cache, update, {id, prepared}}, params, process, opts) do
mapper = &process_row(&1, process, fields)
execute_and_cache(repo, id, update, prepared, params, mapper, opts)
end
def execute(repo, _meta, {_, {_id, prepared_or_cached}}, params, nil, opts) do
%{rows: rows, num_rows: num} =
sql_call!(repo, :execute, [prepared_or_cached], params, nil, opts)
{num, rows}
end
def execute(repo, %{fields: fields}, {_, {_id, prepared_or_cached}}, params, process, opts) do
mapper = &process_row(&1, process, fields)
%{rows: rows, num_rows: num} =
sql_call!(repo, :execute, [prepared_or_cached], params, mapper, opts)
{num, rows}
end
defp execute_and_cache(repo, id, update, prepared, params, mapper, opts) do
name = "ecto_" <> Integer.to_string(id)
case sql_call(repo, :prepare_execute, [name, prepared], params, mapper, opts) do
{:ok, query, %{num_rows: num, rows: rows}} ->
update.({0, query})
{num, rows}
{:error, err} ->
raise err
end
end
defp sql_call!(repo, callback, args, params, mapper, opts) do
case sql_call(repo, callback, args, params, mapper, opts) do
{:ok, res} -> res
{:error, err} -> raise err
end
end
@doc false
def struct(repo, conn, sql, values, returning, opts) do
case query(repo, sql, values, fn x -> x end, opts) do
{:ok, %{rows: nil, num_rows: 1}} ->
{:ok, []}
{:ok, %{rows: [values], num_rows: 1}} ->
{:ok, Enum.zip(returning, values)}
{:ok, %{num_rows: 0}} ->
{:error, :stale}
{:error, err} ->
case conn.to_constraints(err) do
[] -> raise err
constraints -> {:invalid, constraints}
end
end
end
defp process_row(row, process, fields) do
Enum.map_reduce(fields, row, fn
{:&, _, [_, _, counter]} = field, acc ->
case split_and_not_nil(acc, counter, true, []) do
{nil, rest} -> {nil, rest}
{val, rest} -> {process.(field, val, nil), rest}
end
field, [h|t] ->
{process.(field, h, nil), t}
end) |> elem(0)
end
defp split_and_not_nil(rest, 0, true, _acc), do: {nil, rest}
defp split_and_not_nil(rest, 0, false, acc), do: {:lists.reverse(acc), rest}
defp split_and_not_nil([nil|t], count, all_nil?, acc) do
split_and_not_nil(t, count - 1, all_nil?, [nil|acc])
end
defp split_and_not_nil([h|t], count, _all_nil?, acc) do
split_and_not_nil(t, count - 1, false, [h|acc])
end
## Transactions
@doc false
def transaction(repo, opts, fun) do
{pool, default_opts} = repo.__pool__
opts = with_log(repo, [], opts ++ default_opts)
case get_conn(pool) do
nil -> do_transaction(pool, opts, fun)
conn -> DBConnection.transaction(conn, fn(_) -> fun.() end, opts)
end
end
defp do_transaction(pool, opts, fun) do
run = fn(conn) ->
try do
put_conn(pool, conn)
fun.()
after
delete_conn(pool)
end
end
DBConnection.transaction(pool, run, opts)
end
@doc false
def in_transaction?(repo) do
{pool, _} = repo.__pool__
!!get_conn(pool)
end
@doc false
def rollback(repo, value) do
{pool, _} = repo.__pool__
case get_conn(pool) do
nil -> raise "cannot call rollback outside of transaction"
conn -> DBConnection.rollback(conn, value)
end
end
## Log
defp with_log(repo, params, opts) do
case Keyword.pop(opts, :log, true) do
{true, opts} -> [log: &log(repo, params, &1)] ++ opts
{false, opts} -> opts
end
end
defp log(repo, params, entry) do
%{connection_time: query_time, decode_time: decode_time,
pool_time: queue_time, result: result, query: query} = entry
repo.__log__(%Ecto.LogEntry{query_time: query_time, decode_time: decode_time,
queue_time: queue_time, result: log_result(result),
params: params, query: String.Chars.to_string(query)})
end
defp log_result({:ok, _query, res}), do: {:ok, res}
defp log_result(other), do: other
## Connection helpers
defp put_conn(pool, conn) do
_ = Process.put(key(pool), conn)
:ok
end
defp get_conn(pool) do
Process.get(key(pool))
end
defp delete_conn(pool) do
_ = Process.delete(key(pool))
:ok
end
defp key(pool), do: {__MODULE__, pool}
end
| 31.463956 | 113 | 0.614146 |
080a4295f8c85de0e6446b852e8cd75b24299045 | 1,432 | ex | Elixir | lib/asciinema_web/controllers/session_controller.ex | acloudiator/asciinema-server | f0afa4cb4312822f5dd56008b0c5ec9c7a410f85 | [
"Apache-2.0"
] | null | null | null | lib/asciinema_web/controllers/session_controller.ex | acloudiator/asciinema-server | f0afa4cb4312822f5dd56008b0c5ec9c7a410f85 | [
"Apache-2.0"
] | null | null | null | lib/asciinema_web/controllers/session_controller.ex | acloudiator/asciinema-server | f0afa4cb4312822f5dd56008b0c5ec9c7a410f85 | [
"Apache-2.0"
] | null | null | null | defmodule AsciinemaWeb.SessionController do
use AsciinemaWeb, :controller
alias Asciinema.Accounts
alias AsciinemaWeb.Auth
alias Asciinema.Accounts.User
def new(conn, %{"t" => login_token}) do
conn
|> put_session(:login_token, login_token)
|> redirect(to: session_path(conn, :new))
end
def new(conn, _params) do
render(conn, "new.html")
end
def create(conn, _params) do
login_token = get_session(conn, :login_token)
conn = delete_session(conn, :login_token)
case Accounts.verify_login_token(login_token) do
{:ok, user} ->
conn
|> Auth.log_in(user)
|> put_rails_flash(:notice, "Welcome back!")
|> redirect_to_profile
{:error, :token_invalid} ->
conn
|> put_flash(:error, "Invalid login link.")
|> redirect(to: login_path(conn, :new))
{:error, :token_expired} ->
conn
|> put_flash(:error, "This login link has expired, sorry.")
|> redirect(to: login_path(conn, :new))
{:error, :user_not_found} ->
conn
|> put_flash(:error, "This account has been removed.")
|> redirect(to: login_path(conn, :new))
end
end
defp redirect_to_profile(conn) do
case conn.assigns.current_user do
%User{username: nil} ->
redirect(conn, to: "/username/new")
%User{} = user ->
redirect_back_or(conn, to: profile_path(user))
end
end
end
| 28.64 | 67 | 0.624302 |
080a47e7b6a5310b9f9347b77f9c9397dc505bc4 | 915 | ex | Elixir | Microsoft.Azure.Management.Network/lib/microsoft/azure/management/network/model/application_gateway_available_ssl_predefined_policies.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | 4 | 2018-09-29T03:43:15.000Z | 2021-04-01T18:30:46.000Z | Microsoft.Azure.Management.Network/lib/microsoft/azure/management/network/model/application_gateway_available_ssl_predefined_policies.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | null | null | null | Microsoft.Azure.Management.Network/lib/microsoft/azure/management/network/model/application_gateway_available_ssl_predefined_policies.ex | chgeuer/ex_microsoft_azure_management | 99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603 | [
"Apache-2.0"
] | null | null | null | # 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 Microsoft.Azure.Management.Network.Model.ApplicationGatewayAvailableSslPredefinedPolicies do
@moduledoc """
Response for ApplicationGatewayAvailableSslOptions API service call.
"""
@derive [Poison.Encoder]
defstruct [
:"value",
:"nextLink"
]
@type t :: %__MODULE__{
:"value" => [ApplicationGatewaySslPredefinedPolicy],
:"nextLink" => String.t
}
end
defimpl Poison.Decoder, for: Microsoft.Azure.Management.Network.Model.ApplicationGatewayAvailableSslPredefinedPolicies do
import Microsoft.Azure.Management.Network.Deserializer
def decode(value, options) do
value
|> deserialize(:"value", :list, Microsoft.Azure.Management.Network.Model.ApplicationGatewaySslPredefinedPolicy, options)
end
end
| 30.5 | 124 | 0.765027 |
080a53b1276aaad5cde1c501fd4945043de6cced | 409 | ex | Elixir | lib/conduit_web/views/profile_view.ex | rudyyazdi/conduit | 8defa60962482fb81f5093ea5d58b71a160db3c4 | [
"MIT"
] | null | null | null | lib/conduit_web/views/profile_view.ex | rudyyazdi/conduit | 8defa60962482fb81f5093ea5d58b71a160db3c4 | [
"MIT"
] | 2 | 2022-01-15T02:09:30.000Z | 2022-01-22T10:18:43.000Z | lib/conduit_web/views/profile_view.ex | rudyyazdi/conduit | 8defa60962482fb81f5093ea5d58b71a160db3c4 | [
"MIT"
] | null | null | null | defmodule ConduitWeb.ProfileView do
use ConduitWeb, :view
alias ConduitWeb.ProfileView
def render("show.json", %{author: author}) do
%{profile: render_one(author, ProfileView, "profile.json")}
end
def render("profile.json", %{profile: profile}) do
%{
username: profile.username,
bio: profile.bio,
image: profile.image,
following: profile.following,
}
end
end
| 22.722222 | 63 | 0.669927 |
080a6c7ef6bc045d1d036310114cbd83cd9a3d2b | 6,188 | ex | Elixir | lib/sanbase_web/graphql/resolvers/insight_resolver.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 1 | 2022-01-30T19:51:39.000Z | 2022-01-30T19:51:39.000Z | lib/sanbase_web/graphql/resolvers/insight_resolver.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | null | null | null | lib/sanbase_web/graphql/resolvers/insight_resolver.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | null | null | null | defmodule SanbaseWeb.Graphql.Resolvers.InsightResolver do
require Logger
import Absinthe.Resolution.Helpers, except: [async: 1]
alias SanbaseWeb.Graphql.SanbaseDataloader
alias Sanbase.Accounts.User
alias Sanbase.Insight.{Post, PopularAuthor}
alias Sanbase.Comments.EntityComment
require Logger
def popular_insight_authors(_root, _args, _resolution) do
PopularAuthor.get()
end
def insights(%User{} = user, %{page: page, page_size: page_size} = args, _resolution) do
opts = [
is_pulse: Map.get(args, :is_pulse),
is_paywall_required: Map.get(args, :is_paywall_required),
from: Map.get(args, :from),
to: Map.get(args, :to),
page: page,
page_size: page_size
]
{:ok, Post.user_insights(user.id, opts)}
end
def public_insights(%User{} = user, %{page: page, page_size: page_size} = args, _resolution) do
opts = [
is_pulse: Map.get(args, :is_pulse),
is_paywall_required: Map.get(args, :is_paywall_required),
from: Map.get(args, :from),
to: Map.get(args, :to),
page: page,
page_size: page_size
]
{:ok, Post.user_public_insights(user.id, opts)}
end
def related_projects(%Post{} = post, _, _) do
Post.related_projects(post)
end
def post(_root, %{id: post_id}, _resolution) do
Post.by_id(post_id, [])
end
def all_insights(_root, %{tags: tags, page: page, page_size: page_size} = args, _context)
when is_list(tags) do
opts = [
is_pulse: Map.get(args, :is_pulse),
is_paywall_required: Map.get(args, :is_paywall_required),
from: Map.get(args, :from),
to: Map.get(args, :to)
]
posts = Post.public_insights_by_tags(tags, page, page_size, opts)
{:ok, posts}
end
def all_insights(_root, %{page: page, page_size: page_size} = args, _resolution) do
opts = [
is_pulse: Map.get(args, :is_pulse),
is_paywall_required: Map.get(args, :is_paywall_required),
from: Map.get(args, :from),
to: Map.get(args, :to)
]
posts = Post.public_insights(page, page_size, opts)
{:ok, posts}
end
def all_insights_for_user(
_root,
%{user_id: user_id, page: page, page_size: page_size} = args,
_context
) do
opts = [
is_pulse: Map.get(args, :is_pulse),
is_paywall_required: Map.get(args, :is_paywall_required),
from: Map.get(args, :from),
to: Map.get(args, :to),
page: page,
page_size: page_size
]
posts = Post.user_public_insights(user_id, opts)
{:ok, posts}
end
def all_insights_user_voted_for(_root, %{user_id: user_id} = args, _context) do
opts = [
is_pulse: Map.get(args, :is_pulse),
is_paywall_required: Map.get(args, :is_paywall_required),
from: Map.get(args, :from),
to: Map.get(args, :to)
]
posts = Post.all_insights_user_voted_for(user_id, opts)
{:ok, posts}
end
def all_insights_by_tag(_root, %{tag: tag} = args, _context) do
opts = [
is_pulse: Map.get(args, :is_pulse),
is_paywall_required: Map.get(args, :is_paywall_required),
from: Map.get(args, :from),
to: Map.get(args, :to)
]
posts = Post.public_insights_by_tags([tag], opts)
{:ok, posts}
end
def all_insights_by_search_term(_root, %{search_term: search_term} = args, _context) do
opts = [
is_pulse: Map.get(args, :is_pulse),
is_paywall_required: Map.get(args, :is_paywall_required),
from: Map.get(args, :from),
to: Map.get(args, :to)
]
# Search is done only on the publicly visible (published) insights.
search_result_insights = Post.search_published_insights(search_term, opts)
{:ok, search_result_insights}
end
def all_insights_by_search_term_highlighted(
_root,
%{search_term: search_term, page: page, page_size: page_size} = args,
_context
) do
opts = [
is_pulse: Map.get(args, :is_pulse),
is_paywall_required: Map.get(args, :is_paywall_required),
from: Map.get(args, :from),
to: Map.get(args, :to),
page: page,
page_size: page_size
]
# Search is done only on the publicly visible (published) insights.
search_result_insights = Post.search_published_insights_highglight(search_term, opts)
{:ok, search_result_insights}
end
def create_post(_root, args, %{context: %{auth: %{current_user: user}}}) do
case Post.can_create?(user.id) do
{:ok, _} -> Post.create(user, args)
{:error, error} -> {:error, error}
end
end
def update_post(_root, %{id: post_id} = args, %{
context: %{auth: %{current_user: %User{} = user}}
}) do
Post.update(post_id, user, args)
end
def delete_post(_root, %{id: post_id}, %{
context: %{auth: %{current_user: %User{} = user}}
}) do
Post.delete(post_id, user)
end
def publish_insight(_root, %{id: post_id}, %{
context: %{auth: %{current_user: %User{id: user_id}}}
}) do
Post.publish(post_id, user_id)
end
def all_tags(_root, _args, _context) do
{:ok, Sanbase.Tag.all()}
end
def insights_count(%User{id: id}, _args, %{context: %{loader: loader}}) do
loader
|> Dataloader.load(SanbaseDataloader, :insights_count_per_user, id)
|> on_load(fn loader ->
{:ok,
Dataloader.get(loader, SanbaseDataloader, :insights_count_per_user, id) ||
%{total_count: 0, draft_count: 0, pulse_count: 0, paywall_count: 0}}
end)
end
# Note: deprecated - should be removed if not used by frontend
def insight_comments(_root, %{insight_id: insight_id} = args, _resolution) do
comments =
EntityComment.get_comments(:insight, insight_id, args)
|> Enum.map(& &1.comment)
{:ok, comments}
end
def comments_count(%{id: id}, _args, %{context: %{loader: loader}}) do
loader
|> Dataloader.load(SanbaseDataloader, :insights_comments_count, id)
|> on_load(fn loader ->
{:ok, Dataloader.get(loader, SanbaseDataloader, :insights_comments_count, id) || 0}
end)
end
def create_chart_event(_root, args, %{context: %{auth: %{current_user: user}}}) do
Post.create_chart_event(user.id, args)
end
end
| 28.516129 | 97 | 0.646251 |
080a75b1d07c2db988a85883ffd6806e4f43ca6d | 1,469 | exs | Elixir | apps/panacea_beacon/mix.exs | timjp87/panacea | 5edddfa12a8f18b040248b9b186479b9ec8aed51 | [
"MIT"
] | null | null | null | apps/panacea_beacon/mix.exs | timjp87/panacea | 5edddfa12a8f18b040248b9b186479b9ec8aed51 | [
"MIT"
] | null | null | null | apps/panacea_beacon/mix.exs | timjp87/panacea | 5edddfa12a8f18b040248b9b186479b9ec8aed51 | [
"MIT"
] | null | null | null | defmodule Beacon.MixProject do
use Mix.Project
def project do
[
app: :panacea_beacon,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.5",
elixirc_paths: elixirc_paths(Mix.env()),
compilers: [:phoenix, :gettext] ++ Mix.compilers(),
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {Beacon.Application, []},
extra_applications: [:logger, :runtime_tools, :ethereumex]
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[
{:cubdb, "~> 1.0.0-rc.3"},
{:ethereumex, "~> 0.6.2"},
{:ex_abi, "~> 0.4.0"},
{:libp2p, github: "timjp87/erlang-libp2p"},
{:basefiftyeight, "~> 0.1.0"},
{:open_api_spex, "~> 3.6"},
{:yaml_elixir, "~> 2.4"},
{:phoenix, "~> 1.4.0"},
{:phoenix_pubsub, "~> 1.1"},
{:prometheus_ex, "~> 3.0"},
{:prometheus_plugs, "~> 1.1"},
{:gettext, "~> 0.11"},
{:jason, "~> 1.0"},
{:plug_cowboy, "~> 2.0"}
]
end
end
| 26.232143 | 64 | 0.54595 |
080ac902db58fad4d1a4812cc00f76870104e819 | 184 | ex | Elixir | lib/noap/type/float.ex | bpardee/noap | 4c21c55ef2d88ad26a9fab94805beff954315dbf | [
"MIT"
] | 1 | 2022-03-04T03:55:46.000Z | 2022-03-04T03:55:46.000Z | lib/noap/type/float.ex | bpardee/noap | 4c21c55ef2d88ad26a9fab94805beff954315dbf | [
"MIT"
] | null | null | null | lib/noap/type/float.ex | bpardee/noap | 4c21c55ef2d88ad26a9fab94805beff954315dbf | [
"MIT"
] | null | null | null | defmodule Noap.Type.Float do
use Noap.Type
@impl true
def from_str(str, _opts) do
case Float.parse(str) do
{val, ""} -> {:ok, val}
_ -> :error
end
end
end
| 15.333333 | 29 | 0.576087 |
080ada4bfbacb8479ed60cacca31e0f89deee52a | 3,139 | ex | Elixir | lib/retro/phoenix_component.ex | c4710n/retro | 52494acbc38e24120f439d2a1a7f2951f771e49c | [
"MIT"
] | 1 | 2021-02-24T20:40:37.000Z | 2021-02-24T20:40:37.000Z | lib/retro/phoenix_component.ex | c4710n/retro | 52494acbc38e24120f439d2a1a7f2951f771e49c | [
"MIT"
] | null | null | null | lib/retro/phoenix_component.ex | c4710n/retro | 52494acbc38e24120f439d2a1a7f2951f771e49c | [
"MIT"
] | null | null | null | defmodule Retro.Phoenix.Component do
@moduledoc """
Toolkit for creating components for Phoenix.
Inspired by [Reusable Templates in Phoenix](https://blog.danielberkompas.com
/2017/01/17/reusable-templates-in-phoenix/).
## Usage
### Import `Retro.Phoenix.Component`
defmodule SampleWeb do
def view do
quote do
# ...
use Retro.Phoenix.Component,
view: SampleWeb.ComponentView,
type: :html
# ...
end
end
end
### Create a `SampleWeb.ComponentView`:
defmodule SampleWeb.ComponentView do
use SampleWeb, :view
end
### Create `templates/component` directory
It's used for storing templates for above view.
### Create a template
Edit `templates/component/example.html.eex`:
<div class="<%= @class %>">
<%= @inner %>
</div>
### Use the template
<%= c :example, class: "modal" do %>
<p>Hello World</p>
<button>OK</button>
<% end %>
"""
@moduledoc since: "0.3.0"
import Phoenix.View, only: [render: 3]
# TODO: Find a good method to move functions out of __using__/1
defmacro __using__(view: view, type: type) do
quote do
defp do_component(template, assigns, block) do
render(
unquote(view),
"#{template}.#{unquote(type)}",
Keyword.merge(assigns, inner: block)
)
end
@doc """
Render a component by template name.
## Example
<%= component "text_input.html" %>
"""
def component(template) do
do_component(template, [], "")
end
@doc """
Render a component by template name and inner block.
## Example
<%= component "form.html" do %>
<%= component "text_input.html" %>
<% end %>
"""
def component(template, do: block) do
do_component(template, [], block)
end
@doc """
Render a component by template name and assigns.
## Example
<%= component "text_input.html", class: "form-control" %>
"""
def component(template, assigns) when is_list(assigns) do
do_component(template, assigns, "")
end
@doc """
Render a component by template name, assigns and inner block.
## Example
<%= component "form.html", class: "form-control" do %>
<%= component "text_input.html" %>
<% end %>
"""
def component(template, assigns, do: block) when is_list(assigns) do
do_component(template, assigns, block)
end
@doc """
Define aliases for components.
## Example
<%= c "form.html", class: "form-control" do %>
<%= c "text_input.html" %>
<% end %>
"""
defdelegate c(template),
to: __MODULE__,
as: :component
defdelegate c(template, assigns_or_block),
to: __MODULE__,
as: :component
defdelegate c(template, assigns, optional_block),
to: __MODULE__,
as: :component
end
end
end
| 21.648276 | 78 | 0.552724 |
080ae35ee8e58543dcb6a696f66139b30182a441 | 1,398 | ex | Elixir | lib/holidefs/definition/store.ex | polyfox/holidefs | 6a4862e022bf245955331d60929cd915ca82ae44 | [
"MIT"
] | 1 | 2019-07-28T17:23:55.000Z | 2019-07-28T17:23:55.000Z | lib/holidefs/definition/store.ex | polyfox/holidefs | 6a4862e022bf245955331d60929cd915ca82ae44 | [
"MIT"
] | null | null | null | lib/holidefs/definition/store.ex | polyfox/holidefs | 6a4862e022bf245955331d60929cd915ca82ae44 | [
"MIT"
] | 1 | 2019-07-28T17:23:57.000Z | 2019-07-28T17:23:57.000Z | defmodule Holidefs.Definition.Store do
@moduledoc """
This module loads and stores all the holiday definitions.
"""
use Agent
alias Holidefs.Definition
@doc """
Starts the server and loads all calendar files
"""
@spec start_link(nil) :: Agent.on_start()
def start_link(nil) do
Agent.start_link(&load_all/0, name: __MODULE__)
end
@doc """
Returns all the loaded definitions with their rules
"""
@spec all_definitions :: [Holidefs.Definition.t()]
def all_definitions do
Agent.get(__MODULE__, &Map.fetch!(&1, :definitions))
end
@doc """
Returns the definitions for the given locale
"""
@spec get_definition(Holidefs.locale_code()) :: Holidefs.Definition.t() | nil
def get_definition(locale) do
Agent.get(__MODULE__, fn %{definitions: definitions} ->
Enum.find(definitions, &(&1.code == get_locale_atom(locale)))
end)
end
defp get_locale_atom(locale) when is_binary(locale) do
if locale in locale_keys() do
String.to_existing_atom(locale)
else
locale
end
end
defp get_locale_atom(locale) when is_atom(locale) do
locale
end
defp locale_keys do
Holidefs.locales()
|> Map.keys()
|> Enum.map(&Atom.to_string/1)
end
defp load_all do
%{
definitions:
for {code, name} <- Holidefs.locales() do
Definition.load!(code, name)
end
}
end
end
| 22.190476 | 79 | 0.665236 |
080b129a3b2ab2d5a8db1e4803266fdf98f7ebe0 | 47,598 | ex | Elixir | assets/node_modules/phoenix_html/lib/phoenix_html/form.ex | xiongxin/web_chat | 4123887993083058a358358595c06970a5ac873f | [
"MIT"
] | null | null | null | assets/node_modules/phoenix_html/lib/phoenix_html/form.ex | xiongxin/web_chat | 4123887993083058a358358595c06970a5ac873f | [
"MIT"
] | null | null | null | assets/node_modules/phoenix_html/lib/phoenix_html/form.ex | xiongxin/web_chat | 4123887993083058a358358595c06970a5ac873f | [
"MIT"
] | null | null | null | defmodule Phoenix.HTML.Form do
@moduledoc ~S"""
Helpers related to producing HTML forms.
The functions in this module can be used in three
distinct scenarios:
* with changeset data - when information to populate
the form comes from a changeset
* with connection data - when a form is created based
on the information in the connection (aka `Plug.Conn`)
* without form data - when the functions are used directly,
outside of a form
We will explore all three scenarios below.
## With changeset data
The entry point for defining forms in Phoenix is with
the `form_for/4` function. For this example, we will
use `Ecto.Changeset`, which integrates nicely with Phoenix
forms via the `phoenix_ecto` package.
Imagine you have the following action in your controller:
def new(conn, _params) do
changeset = User.changeset(%User{})
render conn, "new.html", changeset: changeset
end
where `User.changeset/2` is defined as follows:
def changeset(user, params \\ %{}) do
cast(user, params, [:name, :age])
end
Now a `@changeset` assign is available in views which we
can pass to the form:
<%= form_for @changeset, user_path(@conn, :create), fn f -> %>
<label>
Name: <%= text_input f, :name %>
</label>
<label>
Age: <%= select f, :age, 18..100 %>
</label>
<%= submit "Submit" %>
<% end %>
`form_for/4` receives the `Ecto.Changeset` and converts it
to a form, which is passed to the function as the argument
`f`. All the remaining functions in this module receive
the form and automatically generate the input fields, often
by extracting information from the given changeset. For example,
if the user had a default value for age set, it will
automatically show up as selected in the form.
#### A note on `:errors`
If no action has been applied to the changeset or action was set to `:ignore`,
no errors are shown on the form object even if the changeset has a non-empty
`:errors` value.
This is useful for things like validation hints on form fields, e.g. an empty
changeset for a new form. That changeset isn't valid, but we don't want to
show errors until an actual user action has been performed.
Ecto automatically applies the action for you when you call
Repo.insert/update/delete, but if you want to show errors manually you can
also set the action yourself, either directly on the `Ecto.Changeset` struct
field or by using `Ecto.Changeset.apply_action/2`.
## With connection data
`form_for/4` expects as first argument any data structure that
implements the `Phoenix.HTML.FormData` protocol. By default,
Phoenix implements this protocol for `Plug.Conn`, allowing us
to create forms based only on connection information.
This is useful when you are creating forms that are not backed
by any kind of data from the data layer, like a search form.
<%= form_for @conn, search_path(@conn, :new), [as: :search], fn f -> %>
<%= text_input f, :for %>
<%= submit "Search" %>
<% end %>
`form_for/4` uses the `Plug.Conn` to set input values from the
request parameters. In this case, the input's value would be set
to `@conn.params["search"]["for"]`.
## Without form data
Sometimes we may want to generate a `text_input/3` or any other
tag outside of a form. The functions in this module also support
such usage by simply passing an atom as first argument instead
of the form.
<%= text_input :user, :name, value: "This is a prepopulated value" %>
## Nested inputs
If your data layer supports embedding or nested associations,
you can use `inputs_for` to attach nested data to the form.
Imagine the following Ecto schemas:
defmodule User do
use Ecto.Schema
schema "users" do
field :name
embeds_one :permalink, Permalink
end
end
defmodule Permalink do
use Ecto.Schema
embedded_schema do
field :url
end
end
In the form, you now can:
<%= form_for @changeset, user_path(@conn, :create), fn f -> %>
<%= text_input f, :name %>
<%= inputs_for f, :permalink, fn fp -> %>
<%= text_input fp, :url %>
<% end %>
<% end %>
The default option can be given to populate the fields if none
is given:
<%= inputs_for f, :permalink, [default: %Permalink{title: "default"}], fn fp -> %>
<%= text_input fp, :url %>
<% end %>
`inputs_for/4` can be used to work with single entities or
collections. When working with collections, `:prepend` and
`:append` can be used to add entries to the collection
stored in the changeset.
## CSRF protection
The form generates a CSRF token by default. Your application should
check this token on the server to avoid attackers from making requests
on your server in behalf of other users. Phoenix by default checks
this token.
When posting a form with a host in its address, such as "//host.com/path"
instead of only "/path", Phoenix will include the host signature in the
token and validate the token only if the accessed host is the same as
the host in the token. This is to avoid tokens from leaking to third
party applications. If this behaviour is problematic, you can generate
a non-host specific token with `Plug.CSRFProtection.get_csrf_token/0` and
pass it to the form generator via the `:csrf_token` option.
"""
alias Phoenix.HTML.Form
import Phoenix.HTML
import Phoenix.HTML.Tag
@doc """
Defines the Phoenix.HTML.Form struct.
Its fields are:
* `:source` - the data structure given to `form_for/4` that
implements the form data protocol
* `:impl` - the module with the form data protocol implementation.
This is used to avoid multiple protocol dispatches.
* `:id` - the id to be used when generating input fields
* `:name` - the name to be used when generating input fields
* `:data` - the field used to store lookup data
* `:params` - the parameters associated to this form in case
they were sent as part of a previous request
* `:hidden` - a keyword list of fields that are required for
submitting the form behind the scenes as hidden inputs
* `:options` - a copy of the options given when creating the
form via `form_for/4` without any form data specific key
* `:errors` - a keyword list of errors that associated with
the form
"""
defstruct source: nil,
impl: nil,
id: nil,
name: nil,
data: nil,
hidden: [],
params: %{},
errors: [],
options: [],
index: nil
@type t :: %Form{
source: Phoenix.HTML.FormData.t(),
name: String.t(),
data: %{field => term},
params: %{binary => term},
hidden: Keyword.t(),
options: Keyword.t(),
errors: Keyword.t(),
impl: module,
id: String.t(),
index: nil | non_neg_integer
}
@type field :: atom | String.t()
@doc """
Converts an attribute/form field into its humanize version.
iex> humanize(:username)
"Username"
iex> humanize(:created_at)
"Created at"
iex> humanize("user_id")
"User"
"""
def humanize(atom) when is_atom(atom), do: humanize(Atom.to_string(atom))
def humanize(bin) when is_binary(bin) do
bin =
if String.ends_with?(bin, "_id") do
binary_part(bin, 0, byte_size(bin) - 3)
else
bin
end
bin |> String.replace("_", " ") |> String.capitalize()
end
@doc """
Generates a form tag with a form builder.
See the module documentation for examples of using this function.
## Options
* `:as` - the server side parameter in which all params for this
form will be collected (i.e. `as: :user_params` would mean all fields
for this form will be accessed as `conn.params.user_params` server
side). Automatically inflected when a changeset is given.
* `:method` - the HTTP method. If the method is not "get" nor "post",
an input tag with name `_method` is generated along-side the form tag.
Defaults to "post".
* `:multipart` - when true, sets enctype to "multipart/form-data".
Required when uploading files
* `:csrf_token` - for "post" requests, the form tag will automatically
include an input tag with name `_csrf_token`. When set to false, this
is disabled
* `:enforce_utf8` - the form will have an `accept-charset` attribute set
to "UTF-8" and a hidden input named `_utf8` containing a unicode
character to force the browser to use UTF-8 as the charset. When set to
false, this is disabled.
* Other options will be passed as html attributes.
ie, `class: "foo", id: "bar"`
See `Phoenix.HTML.Tag.form_tag/2` for more information on the
options above.
"""
@spec form_for(Phoenix.HTML.FormData.t(), String.t(), Keyword.t(), (t -> Phoenix.HTML.unsafe())) ::
Phoenix.HTML.safe()
def form_for(form_data, action, options \\ [], fun) when is_function(fun, 1) do
form = Phoenix.HTML.FormData.to_form(form_data, options)
html_escape([form_tag(action, form.options), fun.(form), raw("</form>")])
end
@doc """
Generate a new form builder for the given parameter in form.
See the module documentation for examples of using this function.
## Options
* `:id` - the id to be used in the form, defaults to the
concatenation of the given `field` to the parent form id
* `:as` - the name to be used in the form, defaults to the
concatenation of the given `field` to the parent form name
* `:default` - the value to use if none is available
* `:prepend` - the values to prepend when rendering. This only
applies if the field value is a list and no parameters were
sent through the form.
* `:append` - the values to append when rendering. This only
applies if the field value is a list and no parameters were
sent through the form.
"""
@spec inputs_for(t, field, Keyword.t(), (t -> Phoenix.HTML.unsafe())) :: Phoenix.HTML.safe()
def inputs_for(%{impl: impl} = form, field, options \\ [], fun)
when is_atom(field) or is_binary(field) do
options =
form.options
|> Keyword.take([:multipart])
|> Keyword.merge(options)
forms = impl.to_form(form.source, form, field, options)
html_escape(
Enum.map(forms, fn form ->
hidden = Enum.map(form.hidden, fn {k, v} -> hidden_input(form, k, value: v) end)
[hidden, fun.(form)]
end)
)
end
@doc """
Returns a value of a corresponding form field.
The `form` should either be a `Phoenix.HTML.Form` emitted
by `form_for` or an atom.
When a form is given, it will lookup for changes and then
fallback to parameters and finally fallback to the default
struct/map value.
"""
@spec input_value(t | atom, field) :: term
def input_value(%{source: source, impl: impl} = form, field)
when is_atom(field) or is_binary(field) do
try do
impl.input_value(source, form, field)
rescue
UndefinedFunctionError ->
case Map.fetch(form.params, field_to_string(field)) do
{:ok, value} ->
value
:error ->
Map.get(form.data, field)
end
end
end
def input_value(name, _field) when is_atom(name), do: nil
@doc """
Returns an id of a corresponding form field.
The form should either be a `Phoenix.HTML.Form` emitted
by `form_for` or an atom.
"""
@spec input_id(t | atom, field) :: String.t()
def input_id(%{id: nil}, field), do: "#{field}"
def input_id(%{id: id}, field) when is_atom(field) or is_binary(field) do
"#{id}_#{field}"
end
def input_id(name, field) when (is_atom(name) and is_atom(field)) or is_binary(field) do
"#{name}_#{field}"
end
@doc """
Returns an id of a corresponding form field and value attached to it.
Useful for radio buttons and inputs like multiselect checkboxes.
"""
@spec input_id(t | atom, field, Phoenix.HTML.Safe.t()) :: String.t()
def input_id(name, field, value) do
{:safe, value} = html_escape(value)
value_id = value |> IO.iodata_to_binary() |> String.replace(~r/\W/u, "_")
input_id(name, field) <> "_" <> value_id
end
@doc """
Returns a name of a corresponding form field.
The form should either be a `Phoenix.HTML.Form` emitted
by `form_for` or an atom.
"""
@spec input_name(t | atom, field) :: String.t()
def input_name(%{name: nil}, field), do: to_string(field)
def input_name(%{name: name}, field) when is_atom(field) or is_binary(field),
do: "#{name}[#{field}]"
def input_name(name, field) when (is_atom(name) and is_atom(field)) or is_binary(field),
do: "#{name}[#{field}]"
@doc """
Returns the HTML5 validations that would apply to
the given field.
"""
@spec input_validations(t, field) :: Keyword.t()
def input_validations(%{source: source, impl: impl} = form, field)
when is_atom(field) or is_binary(field) do
# TODO: Remove me on 3.0
try do
impl.input_validations(source, form, field)
rescue
UndefinedFunctionError -> impl.input_validations(source, field)
end
end
@mapping %{
"url" => :url_input,
"email" => :email_input,
"search" => :search_input,
"password" => :password_input
}
@doc """
Gets the input type for a given field.
If the underlying input type is a `:text_field`,
a mapping could be given to further inflect
the input type based solely on the field name.
The default mapping is:
%{"url" => :url_input,
"email" => :email_input,
"search" => :search_input,
"password" => :password_input}
"""
@spec input_type(t, field) :: atom
def input_type(%{impl: impl, source: source} = form, field, mapping \\ @mapping)
when is_atom(field) or is_binary(field) do
# TODO: Remove me on 3.0
type =
try do
impl.input_type(source, form, field)
rescue
UndefinedFunctionError -> impl.input_type(source, field)
end
if type == :text_input do
field = field_to_string(field)
Enum.find_value(mapping, type, fn {k, v} ->
String.contains?(field, k) && v
end)
else
type
end
end
## Form helpers
@doc """
Generates a text input.
The form should either be a `Phoenix.HTML.Form` emitted
by `form_for` or an atom.
All given options are forwarded to the underlying input,
default values are provided for id, name and value if
possible.
## Examples
# Assuming form contains a User schema
text_input(form, :name)
#=> <input id="user_name" name="user[name]" type="text" value="">
text_input(:user, :name)
#=> <input id="user_name" name="user[name]" type="text" value="">
"""
def text_input(form, field, opts \\ []) do
generic_input(:text, form, field, opts)
end
@doc """
Generates a hidden input.
See `text_input/3` for example and docs.
"""
def hidden_input(form, field, opts \\ []) do
generic_input(:hidden, form, field, opts)
end
@doc """
Generates an email input.
See `text_input/3` for example and docs.
"""
def email_input(form, field, opts \\ []) do
generic_input(:email, form, field, opts)
end
@doc """
Generates a number input.
See `text_input/3` for example and docs.
"""
def number_input(form, field, opts \\ []) do
generic_input(:number, form, field, opts)
end
@doc """
Generates a password input.
For security reasons, the form data and parameter values
are never re-used in `password_input/3`. Pass the value
explicitly if you would like to set one.
See `text_input/3` for example and docs.
"""
def password_input(form, field, opts \\ []) do
opts =
opts
|> Keyword.put_new(:type, "password")
|> Keyword.put_new(:id, input_id(form, field))
|> Keyword.put_new(:name, input_name(form, field))
tag(:input, opts)
end
@doc """
Generates an url input.
See `text_input/3` for example and docs.
"""
def url_input(form, field, opts \\ []) do
generic_input(:url, form, field, opts)
end
@doc """
Generates a search input.
See `text_input/3` for example and docs.
"""
def search_input(form, field, opts \\ []) do
generic_input(:search, form, field, opts)
end
@doc """
Generates a telephone input.
See `text_input/3` for example and docs.
"""
def telephone_input(form, field, opts \\ []) do
generic_input(:tel, form, field, opts)
end
@doc """
Generates a color input.
Warning: this feature isn't available in all browsers.
Check `http://caniuse.com/#feat=input-color` for further informations.
See `text_input/3` for example and docs.
"""
def color_input(form, field, opts \\ []) do
generic_input(:color, form, field, opts)
end
@doc """
Generates a range input.
See `text_input/3` for example and docs.
"""
def range_input(form, field, opts \\ []) do
generic_input(:range, form, field, opts)
end
@doc """
Generates a date input.
Warning: this feature isn't available in all browsers.
Check `http://caniuse.com/#feat=input-datetime` for further informations.
See `text_input/3` for example and docs.
"""
def date_input(form, field, opts \\ []) do
generic_input(:date, form, field, opts)
end
@doc """
Generates a datetime-local input.
Warning: this feature isn't available in all browsers.
Check `http://caniuse.com/#feat=input-datetime` for further informations.
See `text_input/3` for example and docs.
"""
def datetime_local_input(form, field, opts \\ []) do
opts =
case Keyword.fetch(opts, :value) do
{:ok, value} ->
Keyword.put(opts, :value, datetime_local_input_value(value))
:error ->
opts
end
generic_input(:"datetime-local", form, field, opts)
end
defp datetime_local_input_value(%NaiveDateTime{} = value) do
<<date::10-binary, ?\s, hour_minute::5-binary, _rest::binary>> =
NaiveDateTime.to_string(value)
[date, ?T, hour_minute]
end
defp datetime_local_input_value(other), do: other
@doc """
Generates a time input.
Warning: this feature isn't available in all browsers.
Check `http://caniuse.com/#feat=input-datetime` for further informations.
## Options
* `:precision` - Allowed values: `:minute`, `:second`, `:millisecond`.
Defaults to `:minute`.
All other options are forwarded. See `text_input/3` for example and docs.
## Examples
time_input form, :time
#=> <input id="form_time" name="form[time]" type="time" value="23:00">
time_input form, :time, precision: :second
#=> <input id="form_time" name="form[time]" type="time" value="23:00:00">
time_input form, :time, precision: :millisecond
#=> <input id="form_time" name="form[time]" type="time" value="23:00:00.000">
"""
def time_input(form, field, opts \\ []) do
{precision, opts} = Keyword.pop(opts, :precision, :minute)
value = opts[:value] || input_value(form, field)
opts = Keyword.put(opts, :value, truncate_time(value, precision))
generic_input(:time, form, field, opts)
end
defp truncate_time(%Time{} = time, :minute) do
time
|> Time.to_string()
|> String.slice(0, 5)
end
defp truncate_time(%Time{} = time, precision) do
time
|> Time.truncate(precision)
|> Time.to_string()
end
defp truncate_time(value, _), do: value
defp generic_input(type, form, field, opts)
when is_list(opts) and (is_atom(field) or is_binary(field)) do
opts =
opts
|> Keyword.put_new(:type, type)
|> Keyword.put_new(:id, input_id(form, field))
|> Keyword.put_new(:name, input_name(form, field))
|> Keyword.put_new(:value, input_value(form, field))
|> Keyword.update!(:value, &maybe_html_escape/1)
tag(:input, opts)
end
defp maybe_html_escape(nil), do: nil
defp maybe_html_escape(value), do: html_escape(value)
@doc """
Generates a textarea input.
All given options are forwarded to the underlying input,
default values are provided for id, name and textarea
content if possible.
## Examples
# Assuming form contains a User schema
textarea(form, :description)
#=> <textarea id="user_description" name="user[description]"></textarea>
## New lines
Notice the generated textarea includes a new line after
the opening tag. This is because the HTML spec says new
lines after tags must be ignored and all major browser
implementations do that.
So in order to avoid new lines provided by the user
from being ignored when the form is resubmitted, we
automatically add a new line before the text area
value.
"""
def textarea(form, field, opts \\ []) do
opts =
opts
|> Keyword.put_new(:id, input_id(form, field))
|> Keyword.put_new(:name, input_name(form, field))
{value, opts} = Keyword.pop(opts, :value, input_value(form, field) || "")
content_tag(:textarea, ["\n", html_escape(value)], opts)
end
@doc """
Generates a file input.
It requires the given form to be configured with `multipart: true`
when invoking `form_for/4`, otherwise it fails with `ArgumentError`.
See `text_input/3` for example and docs.
"""
def file_input(form, field, opts \\ []) do
if match?(%Form{}, form) and !form.options[:multipart] do
raise ArgumentError,
"file_input/3 requires the enclosing form_for/4 " <>
"to be configured with multipart: true"
end
opts =
opts
|> Keyword.put_new(:type, :file)
|> Keyword.put_new(:id, input_id(form, field))
|> Keyword.put_new(:name, input_name(form, field))
opts =
if opts[:multiple] do
Keyword.update!(opts, :name, &"#{&1}[]")
else
opts
end
tag(:input, opts)
end
@doc """
Generates a submit button to send the form.
All options are forwarded to the underlying button tag.
## Examples
submit "Submit"
#=> <button type="submit">Submit</button>
"""
def submit([do: _] = block_option), do: submit([], block_option)
def submit(_, opts \\ [])
def submit(opts, [do: _] = block_option) do
opts = Keyword.put_new(opts, :type, "submit")
content_tag(:button, opts, block_option)
end
def submit(value, opts) do
opts = Keyword.put_new(opts, :type, "submit")
content_tag(:button, value, opts)
end
@doc """
Generates a reset input to reset all the form fields to
their original state.
All options are forwarded to the underlying input tag.
## Examples
reset "Reset"
#=> <input type="reset" value="Reset">
reset "Reset", class: "btn"
#=> <input type="reset" value="Reset" class="btn">
"""
def reset(value, opts \\ []) do
opts =
opts
|> Keyword.put_new(:type, "reset")
|> Keyword.put_new(:value, value)
tag(:input, opts)
end
@doc """
Generates a radio button.
Invoke this function for each possible value you want
to be sent to the server.
## Examples
# Assuming form contains a User schema
radio_button(form, :role, "admin")
#=> <input id="user_role_admin" name="user[role]" type="radio" value="admin">
## Options
All options are simply forwarded to the underlying HTML tag.
"""
def radio_button(form, field, value, opts \\ []) do
escaped_value = html_escape(value)
opts =
opts
|> Keyword.put_new(:type, "radio")
|> Keyword.put_new(:id, input_id(form, field, escaped_value))
|> Keyword.put_new(:name, input_name(form, field))
opts =
if escaped_value == html_escape(input_value(form, field)) do
Keyword.put_new(opts, :checked, true)
else
opts
end
tag(:input, [value: escaped_value] ++ opts)
end
@doc """
Generates a checkbox.
This function is useful for sending boolean values to the server.
## Examples
# Assuming form contains a User schema
checkbox(form, :famous)
#=> <input name="user[famous]" type="hidden" value="false">
<input checked="checked" id="user_famous" name="user[famous]" type="checkbox" value="true">
## Options
* `:checked_value` - the value to be sent when the checkbox is checked.
Defaults to "true"
* `:unchecked_value` - the value to be sent when the checkbox is unchecked,
Defaults to "false"
* `:value` - the value used to check if a checkbox is checked or unchecked.
The default value is extracted from the form data if available
All other options are forwarded to the underlying HTML tag.
## Hidden fields
Because an unchecked checkbox is not sent to the server, Phoenix
automatically generates a hidden field with the unchecked_value
*before* the checkbox field to ensure the `unchecked_value` is sent
when the checkbox is not marked.
"""
def checkbox(form, field, opts \\ []) do
opts =
opts
|> Keyword.put_new(:type, "checkbox")
|> Keyword.put_new(:id, input_id(form, field))
|> Keyword.put_new(:name, input_name(form, field))
{value, opts} = Keyword.pop(opts, :value, input_value(form, field))
{checked_value, opts} = Keyword.pop(opts, :checked_value, true)
{unchecked_value, opts} = Keyword.pop(opts, :unchecked_value, false)
# We html escape all values to be sure we are comparing
# apples to apples. After all we may have true in the data
# but "true" in the params and both need to match.
value = html_escape(value)
checked_value = html_escape(checked_value)
unchecked_value = html_escape(unchecked_value)
opts =
if value == checked_value do
Keyword.put_new(opts, :checked, true)
else
opts
end
html_escape([
tag(:input, name: Keyword.get(opts, :name), type: "hidden", value: unchecked_value),
tag(:input, [value: checked_value] ++ opts)
])
end
@doc """
Generates a select tag with the given `options`.
`options` are expected to be an enumerable which will be used to
generate each respective `option`. The enumerable may have:
* keyword lists - each keyword list is expected to have the keys
`:key` and `:value`. Additional keys such as `:disabled` may
be given to customize the option
* two-item tuples - where the first element is an atom, string or
integer to be used as the option label and the second element is
an atom, string or integer to be used as the option value
* atom, string or integer - which will be used as both label and value
for the generated select
## Optgroups
If `options` is map or keyword list where the first element is a string,
atom or integer and the second element is a list or a map, it is assumed
the key will be wrapped in an `<optgroup>` and the value will be used to
generate `<options>` nested under the group.
## Examples
# Assuming form contains a User schema
select(form, :age, 0..120)
#=> <select id="user_age" name="user[age]">
<option value="0">0</option>
...
<option value="120">120</option>
</select>
select(form, :role, ["Admin": "admin", "User": "user"])
#=> <select id="user_role" name="user[role]">
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
select(form, :role, [[key: "Admin", value: "admin", disabled: true],
[key: "User", value: "user"]])
#=> <select id="user_role" name="user[role]">
<option value="admin" disabled="disabled">Admin</option>
<option value="user">User</option>
</select>
select(form, :role, ["Admin": "admin", "User": "user"], prompt: "Choose your role")
#=> <select id="user_role" name="user[role]">
<option value="">Choose your role</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
If you want to select an option that comes from the database,
such as a manager for a given project, you may write:
select(form, :manager_id, Enum.map(@managers, &{&1.name, &1.id}))
#=> <select id="manager_id" name="project[manager_id]">
<option value="1">Mary Jane</option>
<option value="2">John Doe</option>
</select>
Finally, if the values are a list or a map, we use the keys for
grouping:
select(form, :country, ["Europe": ["UK", "Sweden", "France"]], ...})
#=> <select id="user_country" name="user[country]">
<optgroup label="Europe">
<option>UK</option>
<option>Sweden</option>
<option>France</option>
</optgroup>
...
</select>
## Options
* `:prompt` - an option to include at the top of the options with
the given prompt text
* `:selected` - the default value to use when none was sent as parameter
Be aware that a `:multiple` option will not generate a correctly
functioning multiple select element. Use `multiple_select/4` instead.
All other options are forwarded to the underlying HTML tag.
"""
def select(form, field, options, opts \\ []) when is_atom(field) or is_binary(field) do
{selected, opts} = selected(form, field, opts) || []
{prefix, opts} =
case Keyword.pop(opts, :prompt) do
{nil, opts} -> {raw(""), opts}
{prompt, opts} -> {content_tag(:option, prompt, value: ""), opts}
end
opts =
opts
|> Keyword.put_new(:id, input_id(form, field))
|> Keyword.put_new(:name, input_name(form, field))
options = options_for_select(options, prefix, html_escape(selected))
content_tag(:select, options, opts)
end
defp selected(form, field, opts) do
{value, opts} = Keyword.pop(opts, :value)
{selected, opts} = Keyword.pop(opts, :selected)
if value != nil do
{value, opts}
else
param = field_to_string(field)
case form do
%{params: %{^param => sent}} ->
{sent, opts}
_ ->
{selected || input_value(form, field), opts}
end
end
end
defp options_for_select(values, options, value) do
Enum.reduce(values, options, fn
{option_key, option_value}, acc ->
[acc | option(option_key, option_value, [], value)]
options, acc when is_list(options) ->
{option_key, options} = Keyword.pop(options, :key)
option_key ||
raise ArgumentError,
"expected :key key when building <option> from keyword list: #{inspect(options)}"
{option_value, options} = Keyword.pop(options, :value)
option_value ||
raise ArgumentError,
"expected :value key when building <option> from keyword list: #{inspect(options)}"
[acc | option(option_key, option_value, options, value)]
option, acc ->
[acc | option(option, option, [], value)]
end)
end
defp option(group_label, group_values, [], value)
when is_list(group_values) or is_map(group_values) do
section_options = options_for_select(group_values, [], value)
content_tag(:optgroup, section_options, label: group_label)
end
defp option(option_key, option_value, extra, value) do
option_key = html_escape(option_key)
option_value = html_escape(option_value)
selected =
if is_list(value) do
option_value in value
else
value == option_value
end
opts = [value: option_value, selected: selected] ++ extra
content_tag(:option, option_key, opts)
end
@doc """
Generates a select tag with the given `options`.
Values are expected to be an Enumerable containing two-item tuples
(like maps and keyword lists) or any Enumerable where the element
will be used both as key and value for the generated select.
## Examples
# Assuming form contains a User schema
multiple_select(form, :roles, ["Admin": 1, "Power User": 2])
#=> <select id="user_roles" name="user[roles][]">
<option value="1">Admin</option>
<option value="2">Power User</option>
</select>
multiple_select(form, :roles, ["Admin": 1, "Power User": 2], selected: [1])
#=> <select id="user_roles" name="user[roles][]">
<option value="1" selected="selected">Admin</option>
<option value="2">Power User</option>
</select>
When working with structs, associations and embeds, you will need to tell
Phoenix how to extract the value out of the collection. For example,
imagine `user.roles` is a list of `%Role{}` structs. You must call it as:
multiple_select(form, :roles, ["Admin": 1, "Power User": 2],
selected: Enum.map(@user.roles, &(&1.id))
The `:selected` option will mark the given IDs as selected unless the form
is being resubmitted. When resubmitted, it uses the form params as values.
## Options
* `:selected` - the default options to be marked as selected. The values
on this list are ignored in case ids have been set as parameters.
All other options are forwarded to the underlying HTML tag.
"""
def multiple_select(form, field, options, opts \\ []) do
{selected, opts} = selected(form, field, opts)
opts =
opts
|> Keyword.put_new(:id, input_id(form, field))
|> Keyword.put_new(:name, input_name(form, field) <> "[]")
|> Keyword.put_new(:multiple, "")
options = options_for_select(options, "", Enum.map(List.wrap(selected), &html_escape/1))
content_tag(:select, options, opts)
end
## Datetime
@doc ~S'''
Generates select tags for datetime.
## Examples
# Assuming form contains a User schema
datetime_select form, :born_at
#=> <select id="user_born_at_year" name="user[born_at][year]">...</select> /
<select id="user_born_at_month" name="user[born_at][month]">...</select> /
<select id="user_born_at_day" name="user[born_at][day]">...</select> —
<select id="user_born_at_hour" name="user[born_at][hour]">...</select> :
<select id="user_born_at_min" name="user[born_at][minute]">...</select>
If you want to include the seconds field (hidden by default), pass `second: []`:
# Assuming form contains a User schema
datetime_select form, :born_at, second: []
If you want to configure the years range:
# Assuming form contains a User schema
datetime_select form, :born_at, year: [options: 1900..2100]
You are also able to configure `:month`, `:day`, `:hour`, `:minute` and
`:second`. All options given to those keys will be forwarded to the
underlying select. See `select/4` for more information.
For example, if you are using Phoenix with Gettext and you want to localize
the list of months, you can pass `:options` to the `:month` key:
# Assuming form contains a User schema
datetime_select form, :born_at, month: [
options: [
{gettext("January"), "1"},
{gettext("February"), "2"},
{gettext("March"), "3"},
{gettext("April"), "4"},
{gettext("May"), "5"},
{gettext("June"), "6"},
{gettext("July"), "7"},
{gettext("August"), "8"},
{gettext("September"), "9"},
{gettext("October"), "10"},
{gettext("November"), "11"},
{gettext("December"), "12"},
]
]
You may even provide your own `localized_datetime_select/3` built on top of
`datetime_select/3`:
defp localized_datetime_select(form, field, opts \\ []) do
opts =
Keyword.put(opts, :month, options: [
{gettext("January"), "1"},
{gettext("February"), "2"},
{gettext("March"), "3"},
{gettext("April"), "4"},
{gettext("May"), "5"},
{gettext("June"), "6"},
{gettext("July"), "7"},
{gettext("August"), "8"},
{gettext("September"), "9"},
{gettext("October"), "10"},
{gettext("November"), "11"},
{gettext("December"), "12"},
])
datetime_select(form, field, opts)
end
## Options
* `:value` - the value used to select a given option.
The default value is extracted from the form data if available
* `:default` - the default value to use when none was given in
`:value` and none is available in the form data
* `:year`, `:month`, `:day`, `:hour`, `:minute`, `:second` - options passed
to the underlying select. See `select/4` for more information.
The available values can be given in `:options`.
* `:builder` - specify how the select can be build. It must be a function
that receives a builder that should be invoked with the select name
and a set of options. See builder below for more information.
## Builder
The generated datetime_select can be customized at will by providing a
builder option. Here is an example from EEx:
<%= datetime_select form, :born_at, builder: fn b -> %>
Date: <%= b.(:day, []) %> / <%= b.(:month, []) %> / <%= b.(:year, []) %>
Time: <%= b.(:hour, []) %> : <%= b.(:minute, []) %>
<% end %>
Although we have passed empty lists as options (they are required), you
could pass any option there and it would be given to the underlying select
input.
In practice, we recommend you to create your own helper with your default
builder:
def my_datetime_select(form, field, opts \\ []) do
builder = fn b ->
~e"""
Date: <%= b.(:day, []) %> / <%= b.(:month, []) %> / <%= b.(:year, []) %>
Time: <%= b.(:hour, []) %> : <%= b.(:minute, []) %>
"""
end
datetime_select(form, field, [builder: builder] ++ opts)
end
Then you are able to use your own datetime_select throughout your whole
application.
## Supported date values
The following values are supported as date:
* a map containing the `year`, `month` and `day` keys (either as strings or atoms)
* a tuple with three elements: `{year, month, day}`
* a string in ISO 8601 format
* `nil`
## Supported time values
The following values are supported as time:
* a map containing the `hour` and `min` keys and an optional `sec` key (either as strings or atoms)
* a tuple with three elements: `{hour, min, sec}`
* a tuple with four elements: `{hour, min, sec, usec}`
* `nil`
'''
def datetime_select(form, field, opts \\ []) do
value = Keyword.get(opts, :value, input_value(form, field) || Keyword.get(opts, :default))
builder =
Keyword.get(opts, :builder) ||
fn b ->
date = date_builder(b, opts)
time = time_builder(b, opts)
html_escape([date, raw(" — "), time])
end
builder.(datetime_builder(form, field, date_value(value), time_value(value), opts))
end
@doc """
Generates select tags for date.
Check `datetime_select/3` for more information on options and supported values.
"""
def date_select(form, field, opts \\ []) do
value = Keyword.get(opts, :value, input_value(form, field) || Keyword.get(opts, :default))
builder = Keyword.get(opts, :builder) || &date_builder(&1, opts)
builder.(datetime_builder(form, field, date_value(value), nil, opts))
end
defp date_builder(b, _opts) do
html_escape([b.(:year, []), raw(" / "), b.(:month, []), raw(" / "), b.(:day, [])])
end
defp date_value(%{"year" => year, "month" => month, "day" => day}),
do: %{year: year, month: month, day: day}
defp date_value(%{year: year, month: month, day: day}),
do: %{year: year, month: month, day: day}
defp date_value({{year, month, day}, _}), do: %{year: year, month: month, day: day}
defp date_value({year, month, day}), do: %{year: year, month: month, day: day}
defp date_value(nil), do: %{year: nil, month: nil, day: nil}
defp date_value(string) when is_binary(string) do
string
|> Date.from_iso8601!()
|> date_value
end
defp date_value(other), do: raise(ArgumentError, "unrecognized date #{inspect(other)}")
@doc """
Generates select tags for time.
Check `datetime_select/3` for more information on options and supported values.
"""
def time_select(form, field, opts \\ []) do
value = Keyword.get(opts, :value, input_value(form, field) || Keyword.get(opts, :default))
builder = Keyword.get(opts, :builder) || &time_builder(&1, opts)
builder.(datetime_builder(form, field, nil, time_value(value), opts))
end
defp time_builder(b, opts) do
time = html_escape([b.(:hour, []), raw(" : "), b.(:minute, [])])
if Keyword.get(opts, :second) do
html_escape([time, raw(" : "), b.(:second, [])])
else
time
end
end
defp time_value(%{"hour" => hour, "minute" => min} = map),
do: %{hour: hour, minute: min, second: Map.get(map, "second", 0)}
defp time_value(%{hour: hour, minute: min} = map),
do: %{hour: hour, minute: min, second: Map.get(map, :second, 0)}
# Backwards compatibility with Ecto v1.1 versions
defp time_value(%{"hour" => hour, "min" => min} = map),
do: %{hour: hour, minute: min, second: Map.get(map, "sec", 0)}
defp time_value(%{hour: hour, min: min} = map),
do: %{hour: hour, minute: min, second: Map.get(map, :sec, 0)}
defp time_value({_, {hour, min, sec, _msec}}), do: %{hour: hour, minute: min, second: sec}
defp time_value({hour, min, sec, _mseg}), do: %{hour: hour, minute: min, second: sec}
defp time_value({_, {hour, min, sec}}), do: %{hour: hour, minute: min, second: sec}
defp time_value({hour, min, sec}), do: %{hour: hour, minute: min, second: sec}
defp time_value(nil), do: %{hour: nil, minute: nil, second: nil}
defp time_value(string) when is_binary(string) do
string
|> Time.from_iso8601!()
|> time_value
end
defp time_value(other), do: raise(ArgumentError, "unrecognized time #{inspect(other)}")
@months [
{"January", "1"},
{"February", "2"},
{"March", "3"},
{"April", "4"},
{"May", "5"},
{"June", "6"},
{"July", "7"},
{"August", "8"},
{"September", "9"},
{"October", "10"},
{"November", "11"},
{"December", "12"}
]
map =
&Enum.map(&1, fn i ->
pre = if i < 10, do: "0"
{"#{pre}#{i}", i}
end)
@days map.(1..31)
@hours map.(0..23)
@minsec map.(0..59)
defp datetime_builder(form, field, date, time, parent) do
id = Keyword.get(parent, :id, input_id(form, field))
name = Keyword.get(parent, :name, input_name(form, field))
fn
:year, opts when date != nil ->
{year, _, _} = :erlang.date()
{value, opts} =
datetime_options(:year, (year - 5)..(year + 5), id, name, parent, date, opts)
select(:datetime, :year, value, opts)
:month, opts when date != nil ->
{value, opts} = datetime_options(:month, @months, id, name, parent, date, opts)
select(:datetime, :month, value, opts)
:day, opts when date != nil ->
{value, opts} = datetime_options(:day, @days, id, name, parent, date, opts)
select(:datetime, :day, value, opts)
:hour, opts when time != nil ->
{value, opts} = datetime_options(:hour, @hours, id, name, parent, time, opts)
select(:datetime, :hour, value, opts)
:minute, opts when time != nil ->
{value, opts} = datetime_options(:minute, @minsec, id, name, parent, time, opts)
select(:datetime, :minute, value, opts)
:second, opts when time != nil ->
{value, opts} = datetime_options(:second, @minsec, id, name, parent, time, opts)
select(:datetime, :second, value, opts)
end
end
defp datetime_options(type, values, id, name, parent, datetime, opts) do
opts = Keyword.merge(Keyword.get(parent, type, []), opts)
suff = Atom.to_string(type)
{value, opts} = Keyword.pop(opts, :options, values)
{value,
opts
|> Keyword.put_new(:id, id <> "_" <> suff)
|> Keyword.put_new(:name, name <> "[" <> suff <> "]")
|> Keyword.put_new(:value, Map.get(datetime, type))}
end
@doc """
Generates a label tag.
Useful when wrapping another input inside a label.
## Examples
label do
radio_button :user, :choice, "Choice"
end
#=> <label class="control-label">...</label>
label class: "control-label" do
radio_button :user, :choice, "Choice"
end
#=> <label class="control-label">...</label>
"""
def label(do_block)
def label(do: block) do
content_tag(:label, block, [])
end
def label(opts, do: block) when is_list(opts) do
content_tag(:label, block, opts)
end
@doc """
Generates a label tag for the given field.
The form should either be a `Phoenix.HTML.Form` emitted
by `form_for` or an atom.
All given options are forwarded to the underlying tag.
A default value is provided for `for` attribute but can
be overriden if you pass a value to the `for` option.
Text content would be inferred from `field` if not specified.
To wrap a label around an input, see `label/1`.
## Examples
# Assuming form contains a User schema
label(form, :name, "Name")
#=> <label for="user_name">Name</label>
label(:user, :email, "Email")
#=> <label for="user_email">Email</label>
label(:user, :email)
#=> <label for="user_email">Email</label>
label(:user, :email, class: "control-label")
#=> <label for="user_email" class="control-label">Email</label>
label :user, :email do
"E-mail Address"
end
#=> <label for="user_email">E-mail Address</label>
label :user, :email, class: "control-label" do
"E-mail Address"
end
#=> <label class="control-label" for="user_email">E-mail Address</label>
"""
def label(form, field) when is_atom(field) or is_binary(field) do
label(form, field, humanize(field), [])
end
@doc """
See `label/2`.
"""
def label(form, field, text_or_do_block_or_attributes)
def label(form, field, text) when is_binary(text) do
label(form, field, text, [])
end
def label(form, field, do: block) do
label(form, field, [], do: block)
end
def label(form, field, opts) when is_list(opts) do
label(form, field, humanize(field), opts)
end
@doc """
See `label/2`.
"""
def label(form, field, text, do_block_or_attributes)
def label(form, field, text, opts) when is_binary(text) and is_list(opts) do
opts = Keyword.put_new(opts, :for, input_id(form, field))
content_tag(:label, text, opts)
end
def label(form, field, opts, do: block) when is_list(opts) do
opts = Keyword.put_new(opts, :for, input_id(form, field))
content_tag(:label, block, opts)
end
# Normalize field name to string version
defp field_to_string(field) when is_atom(field), do: Atom.to_string(field)
defp field_to_string(field) when is_binary(field), do: field
# TODO: Remove me on 3.0
@doc false
def field_value(form, field, default \\ nil), do: input_value(form, field) || default
@doc false
def field_name(form, field), do: input_name(form, field)
@doc false
def field_id(form, field), do: input_id(form, field)
end
| 30.649066 | 103 | 0.630594 |
080b16746f8021d8dd1af4c00076c002be43fb08 | 16,724 | exs | Elixir | test/teslamate_web/controllers/car_controller_test.exs | markusdd/teslamate | baada9c5455da2d3c400bf916ab29834772f6a88 | [
"MIT"
] | null | null | null | test/teslamate_web/controllers/car_controller_test.exs | markusdd/teslamate | baada9c5455da2d3c400bf916ab29834772f6a88 | [
"MIT"
] | null | null | null | test/teslamate_web/controllers/car_controller_test.exs | markusdd/teslamate | baada9c5455da2d3c400bf916ab29834772f6a88 | [
"MIT"
] | null | null | null | defmodule TeslaMateWeb.CarControllerTest do
use TeslaMateWeb.ConnCase
use TeslaMate.VehicleCase
alias TeslaMate.Settings.CarSettings
alias TeslaMate.{Log, Settings, Repo}
alias TeslaMate.Log.Car
defp table_row(html, key, value, opts \\ []) do
assert {"tr", _, [{"td", _, [^key]}, {"td", [], [v]}]} =
html
|> Floki.find("tr")
|> Enum.find(&match?({"tr", _, [{"td", _, [^key]}, _td]}, &1))
case Keyword.get(opts, :tooltip) do
nil -> assert value == v
str -> assert {"span", [_, {"data-tooltip", ^str}], [^value]} = v
end
end
defp icon(html, tooltip, icon) do
icon_class = "mdi mdi-#{icon}"
assert {"span", _, [{"span", [{"class", ^icon_class}], _}]} =
html
|> Floki.find(".icons .icon")
|> Enum.find(&match?({"span", [_, {"data-tooltip", ^tooltip}], _}, &1))
end
defp car_fixture(settings) do
{:ok, car} =
Log.create_car(%{
efficiency: 0.153,
eid: 4242,
vid: 404,
vin: "xxxxx",
model: "S",
name: "foo",
trim_badging: "P100D"
})
{:ok, _settings} =
car.settings
|> Repo.preload(:car)
|> Settings.update_car_settings(settings)
car
end
describe "index" do
test "redirects if not signed in", %{conn: conn} do
assert conn = get(conn, Routes.car_path(conn, :index))
assert redirected_to(conn, 302) == Routes.live_path(conn, TeslaMateWeb.SignInLive.Index)
end
@tag :signed_in
test "lists all active vehicles", %{conn: conn} do
{:ok, _pid} =
start_supervised(
{ApiMock, name: :api_vehicle, events: [{:ok, online_event()}], pid: self()}
)
{:ok, _pid} =
start_supervised(
{TeslaMate.Vehicles,
vehicle: VehicleMock,
vehicles: [
%TeslaApi.Vehicle{display_name: "f0o", id: 4241, vehicle_id: 11111, vin: "1221"},
%TeslaApi.Vehicle{display_name: "fo0", id: 1242, vehicle_id: 22222, vin: "2112"}
]}
)
conn = get(conn, Routes.car_path(conn, :index))
html = response(conn, 200)
assert [
{"div", [{"class", "car card"}], _},
{"div", [{"class", "car card"}], _}
] = Floki.find(html, ".car")
end
@tag :signed_in
test "renders last knwon vehicle stats", %{conn: conn} do
events = [
{:ok, %TeslaApi.Vehicle{state: "asleep", display_name: "FooCar"}}
]
{:ok, car} =
%Car{settings: %CarSettings{}}
|> Car.changeset(%{vid: 404, eid: 404, vin: "xxxxx"})
|> Log.create_or_update_car()
{:ok, _position} =
Log.insert_position(car, %{
date: DateTime.utc_now(),
longitude: 0,
latitude: 0,
ideal_battery_range_km: 380.25,
est_battery_range_km: 401.52,
rated_battery_range_km: 175.1,
battery_level: 80,
outside_temp: 20.1,
inside_temp: 21.0
})
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "asleep")
assert table_row(html, "Range (ideal)", "380.25 km")
assert table_row(html, "Range (est.)", "401.52 km")
assert table_row(html, "State of Charge", "80%", tooltip: "≈ 475 km at 100%")
assert table_row(html, "Outside temperature", "20.1 °C")
assert table_row(html, "Inside temperature", "21.0 °C")
end
@tag :signed_in
test "renders current vehicle stats [:online]", %{conn: conn} do
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
charge_state: %{
ideal_battery_range: 200,
est_battery_range: 180,
battery_range: 175,
usable_battery_level: 67,
battery_level: 69
},
climate_state: %{is_preconditioning: true, outside_temp: 24, inside_temp: 23.2},
vehicle_state: %{
car_version: "2019.40.50.7 ad132c7b057e",
software_update: %{status: "available"},
locked: true,
sentry_mode: true,
fd_window: 1,
fp_window: 0,
rd_window: 0,
rp_window: 0,
is_user_present: true
},
vehicle_config: %{car_type: "models2", trim_badging: "p90d"}
)}
]
:ok = start_vehicles(events)
Process.sleep(250)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert html =~ ~r/<p class="subtitle is-6 has-text-weight-light">Model S P90D<\/p>/
assert table_row(html, "Status", "online")
assert table_row(html, "Range (ideal)", "321.87 km")
assert table_row(html, "Range (est.)", "289.68 km")
assert table_row(html, "State of Charge", "69%", tooltip: "≈ 466 km at 100%")
assert table_row(html, "Usable State of Charge", "67%", tooltip: "≈ 480 km at 100%")
assert icon(html, "Locked", "lock")
assert icon(html, "Driver present", "account")
assert icon(html, "Preconditioning", "air-conditioner")
assert icon(html, "Sentry Mode", "shield-check")
assert icon(html, "Windows open", "window-open")
assert icon(html, "Software Update available", "gift-outline")
assert table_row(html, "Outside temperature", "24 °C")
assert table_row(html, "Inside temperature", "23.2 °C")
assert table_row(html, "Version", "2019.40.50.7")
end
@tag :signed_in
test "renders current vehicle stats [:charging]", %{conn: conn} do
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
charge_state: %{
timestamp: 0,
charger_power: 11,
charger_phases: 3,
charger_voltage: 229,
charger_actual_current: 16,
ideal_battery_range: 200,
est_battery_range: 180,
battery_range: 175,
charging_state: "Charging",
charge_energy_added: "4.32",
charge_port_latch: "Engaged",
charge_port_door_open: true,
scheduled_charging_start_time: 1_565_620_707,
charge_limit_soc: 85,
time_to_full_charge: 1.83
}
)}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "charging")
assert table_row(html, "Remaining Time", "1 h 49 min")
assert icon(html, "Plugged in", "power-plug")
assert table_row(html, "Range (ideal)", "321.87 km")
assert table_row(html, "Range (est.)", "289.68 km")
assert table_row(html, "Charged", "4.32 kWh")
assert table_row(html, "Charger Power", "11 kW")
assert table_row(
html,
"Scheduled charging",
{"span", [{"data-date", "2019-08-12T14:38:27Z"}, {"phx-hook", "LocalTime"}], []}
)
assert table_row(html, "Charge limit", "85%")
end
@tag :signed_in
test "does not render remaining seconds", %{conn: conn} do
events = [
{:ok,
online_event(
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
charge_state: %{
timestamp: 0,
charging_state: "Charging",
charge_energy_added: "4.32",
ideal_battery_range: 200,
time_to_full_charge: 0.33
}
)}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert table_row(html, "Remaining Time", "19 min")
end
@tag :signed_in
test "renders current vehicle stats [:driving]", %{conn: conn} do
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{
timestamp: 0,
latitude: 0.0,
longitude: 0.0,
shift_state: "D",
speed: 30
}
)}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "driving")
assert table_row(html, "Speed", "48 km/h")
end
@tag :signed_in
test "renders current vehicle stats [:updating]", %{conn: conn} do
alias TeslaApi.Vehicle.State.VehicleState.SoftwareUpdate
events = [
{:ok,
online_event(
display_name: "FooCar",
vehicle_state: %{
car_version: "2019.8.4 530d1d3",
software_update: %SoftwareUpdate{expected_duration_sec: 2700, status: "installing"}
}
)}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "updating")
end
@tag :signed_in
test "renders current vehicle stats [:asleep]", %{conn: conn} do
events = [
{:ok, %TeslaApi.Vehicle{display_name: "FooCar", state: "asleep"}}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "asleep")
end
@tag :signed_in
test "renders current vehicle stats [:offline]", %{conn: conn} do
events = [
{:ok, %TeslaApi.Vehicle{display_name: "FooCar", state: "offline"}}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "offline")
end
@tag :signed_in
test "renders current vehicle stats [:falling asleep]", %{conn: conn} do
_car = car_fixture(%{suspend_min: 60, suspend_after_idle_min: 1})
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
climate_state: %{is_preconditioning: false}
)}
]
:ok = start_vehicles(events)
Process.sleep(100)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "falling asleep")
end
@tag :capture_log
@tag :signed_in
test "renders current vehicle stats [:unavailable]", %{conn: conn} do
events = [
{:error, :unknown}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5"><\/p>/
assert table_row(html, "Status", "unavailable")
end
@tag :signed_in
test "displays the rated range if preferred", %{conn: conn} do
{:ok, _} =
Settings.get_global_settings!()
|> Settings.update_global_settings(%{preferred_range: :rated})
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
charge_state: %{
ideal_battery_range: 200,
est_battery_range: 180,
battery_range: 175,
battery_level: 69
},
climate_state: %{is_preconditioning: false, outside_temp: 24, inside_temp: 23.2},
vehicle_state: %{locked: true, sentry_mode: true},
vehicle_config: %{car_type: "models2", trim_badging: "p90d"}
)}
]
:ok = start_vehicles(events)
Process.sleep(250)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Range (rated)", "281.64 km")
assert table_row(html, "Range (est.)", "289.68 km")
end
@tag :signed_in
test "displays imperial units", %{conn: conn} do
{:ok, _} =
Settings.get_global_settings!()
|> Settings.update_global_settings(%{unit_of_length: :mi, unit_of_temperature: :F})
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{
timestamp: 0,
latitude: 0.0,
longitude: 0.0,
shift_state: "D",
speed: 30
},
charge_state: %{
ideal_battery_range: 200,
est_battery_range: 180,
battery_range: 175,
usable_battery_level: 67,
battery_level: 69
},
climate_state: %{is_preconditioning: false, outside_temp: 24, inside_temp: 23.2}
)}
]
:ok = start_vehicles(events)
conn = get(conn, Routes.car_path(conn, :index))
assert html = response(conn, 200)
assert html =~ ~r/<p class="title is-5">FooCar<\/p>/
assert table_row(html, "Status", "driving")
assert table_row(html, "Range (ideal)", "200.0 mi")
assert table_row(html, "Range (est.)", "180.0 mi")
assert table_row(html, "State of Charge", "69%", tooltip: "≈ 290 mi at 100%")
assert table_row(html, "Usable State of Charge", "67%", tooltip: "≈ 299 mi at 100%")
assert table_row(html, "Speed", "30 mph")
assert table_row(html, "Outside temperature", "75.2 °F")
assert table_row(html, "Inside temperature", "73.8 °F")
end
end
describe "supsend" do
setup %{conn: conn} do
{:ok, conn: put_req_header(conn, "accept", "application/json")}
end
test "suspends logging", %{conn: conn} do
_car = car_fixture(%{suspend_min: 60, suspend_after_idle_min: 60})
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
climate_state: %{is_preconditioning: false}
)}
]
:ok = start_vehicles(events)
%Car{id: id} = Log.get_car_by(vin: "xxxxx")
conn = put(conn, Routes.car_path(conn, :suspend_logging, id))
assert "" == response(conn, 204)
end
test "returns error if suspending is not possible", %{conn: conn} do
_car = car_fixture(%{suspend_min: 60, suspend_after_idle_min: 60})
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
climate_state: %{is_preconditioning: true}
)}
]
:ok = start_vehicles(events)
%Car{id: id} = Log.get_car_by(vin: "xxxxx")
conn = put(conn, Routes.car_path(conn, :suspend_logging, id))
assert "preconditioning" == json_response(conn, 412)["error"]
end
end
describe "resume" do
test "resumes logging", %{conn: conn} do
alias TeslaMate.Vehicles.Vehicle.Summary
_car = car_fixture(%{suspend_min: 60, suspend_after_idle_min: 1})
events = [
{:ok,
online_event(
display_name: "FooCar",
drive_state: %{timestamp: 0, latitude: 0.0, longitude: 0.0},
climate_state: %{is_preconditioning: false}
)}
]
:ok = start_vehicles(events)
Process.sleep(100)
%Car{id: id} = Log.get_car_by(vin: "xxxxx")
assert %Summary{state: :suspended} = TeslaMate.Vehicles.summary(id)
conn = put(conn, Routes.car_path(conn, :resume_logging, id))
assert "" == response(conn, 204)
end
end
def start_vehicles(events \\ []) do
{:ok, _pid} = start_supervised({ApiMock, name: :api_vehicle, events: events, pid: self()})
{:ok, _pid} =
start_supervised(
{TeslaMate.Vehicles,
vehicle: VehicleMock,
vehicles: [
%TeslaApi.Vehicle{
display_name: "foo",
id: 4242,
vehicle_id: 404,
vin: "xxxxx"
}
]}
)
:ok
end
end
| 30.856089 | 96 | 0.556924 |
080b2d7e0fa2f16c4dbfbc6120fe3fa8253ee019 | 936 | ex | Elixir | elixir/lib/homework/transactions/transaction.ex | ceejaay/web-homework | e5844609b62bdfa79a9b5b8f302c0d7ba81dc75d | [
"MIT"
] | null | null | null | elixir/lib/homework/transactions/transaction.ex | ceejaay/web-homework | e5844609b62bdfa79a9b5b8f302c0d7ba81dc75d | [
"MIT"
] | null | null | null | elixir/lib/homework/transactions/transaction.ex | ceejaay/web-homework | e5844609b62bdfa79a9b5b8f302c0d7ba81dc75d | [
"MIT"
] | null | null | null | defmodule Homework.Transactions.Transaction do
use Ecto.Schema
import Ecto.Changeset
alias Homework.Merchants.Merchant
alias Homework.Users.User
alias Homework.Companies.Company
@primary_key {:id, :binary_id, autogenerate: true}
schema "transactions" do
field(:amount, :integer)
field(:credit, :boolean, default: false)
field(:debit, :boolean, default: false)
field(:description, :string)
belongs_to(:merchant, Merchant, type: :binary_id, foreign_key: :merchant_id)
belongs_to(:user, User, type: :binary_id, foreign_key: :user_id)
belongs_to(:company, Company, type: :binary_id, foreign_key: :company_id)
timestamps()
end
@doc false
def changeset(transaction, attrs) do
transaction
|> cast(attrs, [:user_id, :amount, :debit, :description, :merchant_id, :company_id])
|> validate_required([:user_id, :amount, :debit, :description, :merchant_id, :company_id])
end
end
| 32.275862 | 94 | 0.720085 |
080b5bd21a723223355cf2f1adcde27b93243302 | 973 | exs | Elixir | apps/site/test/site_web/plugs/common_fares_test.exs | noisecapella/dotcom | d5ef869412102d2230fac3dcc216f01a29726227 | [
"MIT"
] | 42 | 2019-05-29T16:05:30.000Z | 2021-08-09T16:03:37.000Z | apps/site/test/site_web/plugs/common_fares_test.exs | noisecapella/dotcom | d5ef869412102d2230fac3dcc216f01a29726227 | [
"MIT"
] | 872 | 2019-05-29T17:55:50.000Z | 2022-03-30T09:28:43.000Z | apps/site/test/site_web/plugs/common_fares_test.exs | noisecapella/dotcom | d5ef869412102d2230fac3dcc216f01a29726227 | [
"MIT"
] | 12 | 2019-07-01T18:33:21.000Z | 2022-03-10T02:13:57.000Z | defmodule SiteWeb.Plugs.CommonFaresTest do
use SiteWeb.ConnCase, async: true
import SiteWeb.Plugs.CommonFares
alias Fares.Summary
@opts init([])
describe "init/1" do
test "returns 4 summaries: subway, bus, subway monthly, CR" do
assert [
%Summary{
duration: :single_trip,
modes: [:subway | _]
},
%Summary{
duration: :single_trip,
modes: [:bus | _]
},
%Summary{
duration: :month,
modes: [:subway | _]
},
%Summary{
duration: :single_trip,
modes: [:commuter_rail | _]
}
] = @opts
end
end
describe "call/2" do
test "assigns `common_fare_summaries`", %{conn: conn} do
conn = call(conn, @opts)
assert conn.assigns.common_fare_summaries == @opts
end
end
end
| 25.605263 | 66 | 0.48407 |
080b71bc706200792b6f142e73e40945ddcb0254 | 930 | exs | Elixir | test/mix.exs | balexand/nerves_system_rpi0_dht11 | 627828d1d932794a2c91a24f5727a87dd9c498eb | [
"Apache-2.0"
] | null | null | null | test/mix.exs | balexand/nerves_system_rpi0_dht11 | 627828d1d932794a2c91a24f5727a87dd9c498eb | [
"Apache-2.0"
] | null | null | null | test/mix.exs | balexand/nerves_system_rpi0_dht11 | 627828d1d932794a2c91a24f5727a87dd9c498eb | [
"Apache-2.0"
] | null | null | null | if Mix.env() == :test do
hash =
:os.cmd('git rev-parse HEAD')
|> to_string
|> String.trim()
System.put_env("NERVES_FW_VCS_IDENTIFIER", hash)
end
defmodule Test.MixProject do
use Mix.Project
def project do
[
app: :test,
version: "0.1.0",
elixir: "~> 1.4",
archives: [nerves_bootstrap: "~> 1.0-rc"],
start_permanent: Mix.env() == :prod,
aliases: [loadconfig: [&bootstrap/1]],
deps: deps()
]
end
# Type `mix help compile.app` to learn about applications.
def application, do: []
defp bootstrap(args) do
System.put_env("MIX_TARGET", "rpi0")
Application.start(:nerves_bootstrap)
Mix.Task.run("loadconfig", args)
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:nerves_system_rpi0, path: "../", runtime: false},
{:nerves_system_test, github: "nerves-project/nerves_system_test"}
]
end
end
| 22.142857 | 72 | 0.619355 |
080b762cb19913c795ccf5aac6fd1b0ffad2ebdd | 1,936 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/user_profile_list.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/user_profile_list.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/user_profile_list.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.DFAReporting.V33.Model.UserProfileList do
@moduledoc """
Represents the list of user profiles.
## Attributes
* `etag` (*type:* `String.t`, *default:* `nil`) - The eTag of this response for caching purposes.
* `items` (*type:* `list(GoogleApi.DFAReporting.V33.Model.UserProfile.t)`, *default:* `nil`) - The user profiles returned in this response.
* `kind` (*type:* `String.t`, *default:* `dfareporting#userProfileList`) - The kind of list this is, in this case dfareporting#userProfileList.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:etag => String.t(),
:items => list(GoogleApi.DFAReporting.V33.Model.UserProfile.t()),
:kind => String.t()
}
field(:etag)
field(:items, as: GoogleApi.DFAReporting.V33.Model.UserProfile, type: :list)
field(:kind)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.UserProfileList do
def decode(value, options) do
GoogleApi.DFAReporting.V33.Model.UserProfileList.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.UserProfileList do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.528302 | 147 | 0.724174 |
080b77cbb26b76bfdee127a14a2c66d1f5fd64bc | 2,380 | ex | Elixir | lib/sanbase_web/graphql/schema/queries/github_queries.ex | sitedata/sanbase2 | 8da5e44a343288fbc41b68668c6c80ae8547d557 | [
"MIT"
] | null | null | null | lib/sanbase_web/graphql/schema/queries/github_queries.ex | sitedata/sanbase2 | 8da5e44a343288fbc41b68668c6c80ae8547d557 | [
"MIT"
] | 1 | 2021-07-24T16:26:03.000Z | 2021-07-24T16:26:03.000Z | lib/sanbase_web/graphql/schema/queries/github_queries.ex | sitedata/sanbase2 | 8da5e44a343288fbc41b68668c6c80ae8547d557 | [
"MIT"
] | null | null | null | defmodule SanbaseWeb.Graphql.Schema.GithubQueries do
use Absinthe.Schema.Notation
import SanbaseWeb.Graphql.Cache, only: [cache_resolve: 1, cache_resolve: 2]
alias SanbaseWeb.Graphql.Resolvers.GithubResolver
alias SanbaseWeb.Graphql.Complexity
alias SanbaseWeb.Graphql.Middlewares.AccessControl
import_types(SanbaseWeb.Graphql.GithubTypes)
object :github_queries do
@desc "Returns a list of slugs of the projects that have a github link"
field :github_availables_repos, list_of(:string) do
meta(access: :free)
cache_resolve(&GithubResolver.available_repos/3)
end
@desc ~s"""
Returns a list of github activity for a given slug and time interval.
Arguments description:
* interval - an integer followed by one of: `s`, `m`, `h`, `d` or `w`
* transform - one of the following:
1. None (default)
2. movingAverage
* movingAverageIntervalBase - used only if transform is `movingAverage`.
An integer followed by one of: `s`, `m`, `h`, `d` or `w`, representing time units.
It is used to calculate the moving avarage interval.
"""
field :github_activity, list_of(:activity_point) do
meta(access: :free)
arg(:slug, :string)
arg(:from, non_null(:datetime))
arg(:to, non_null(:datetime))
arg(:interval, :interval, default_value: "1d")
arg(:transform, :string, default_value: "None")
arg(:moving_average_interval_base, :integer, default_value: 7)
complexity(&Complexity.from_to_interval/3)
middleware(AccessControl)
cache_resolve(&GithubResolver.github_activity/3)
end
@desc ~s"""
Gets the pure dev activity of a project. Pure dev activity is the number of all events
excluding Comments, Issues and PR Comments
"""
field :dev_activity, list_of(:activity_point) do
meta(access: :free)
arg(:slug, :string)
arg(:selector, :github_organizations_selector)
arg(:from, non_null(:datetime))
arg(:to, non_null(:datetime))
arg(:interval, non_null(:interval))
arg(:transform, :string, default_value: "None")
arg(:moving_average_interval_base, :integer, default_value: 7)
complexity(&Complexity.from_to_interval/3)
middleware(AccessControl)
cache_resolve(&GithubResolver.dev_activity/3, ttl: 600, max_ttl_offset: 600)
end
end
end
| 35.522388 | 90 | 0.692857 |
080b8d302d68c5952e21772a6306ba8a1811de30 | 218 | exs | Elixir | config/test.exs | smanolloff/tesla-aws-signer | 8f5ce9f33c2e86049449a1f089674b27b0d7eea9 | [
"Apache-2.0"
] | null | null | null | config/test.exs | smanolloff/tesla-aws-signer | 8f5ce9f33c2e86049449a1f089674b27b0d7eea9 | [
"Apache-2.0"
] | null | null | null | config/test.exs | smanolloff/tesla-aws-signer | 8f5ce9f33c2e86049449a1f089674b27b0d7eea9 | [
"Apache-2.0"
] | null | null | null | use Mix.Config
config :aws_signer,
cache_provider: Mocks.Cache,
datetime_provider: Mocks.DateTime,
aws_client: Mocks.AwsClient,
logger_middleware: Tesla.Middleware.Logger
config :tesla,
adapter: Tesla.Mock
| 19.818182 | 44 | 0.784404 |
080bc5fad9a04b61adccd1cf21e670d7051f9bb5 | 3,079 | ex | Elixir | implementations/elixir/ockam/ockam_vault_software/lib/vault_software.ex | kylematsuda/ockam | 1b89ef8164b6f9291a0d36bd1e2d8161938299f3 | [
"Apache-2.0"
] | 1 | 2021-08-25T03:33:52.000Z | 2021-08-25T03:33:52.000Z | implementations/elixir/ockam/ockam_vault_software/lib/vault_software.ex | Stupremee/ockam | ffadf0633adcae4d0a061fa322fb17dd15afe6e6 | [
"Apache-2.0"
] | null | null | null | implementations/elixir/ockam/ockam_vault_software/lib/vault_software.ex | Stupremee/ockam | ffadf0633adcae4d0a061fa322fb17dd15afe6e6 | [
"Apache-2.0"
] | null | null | null | defmodule Ockam.Vault.Software do
@moduledoc """
Ockam.Vault.Software
"""
use Application
defstruct [:id]
@dialyzer :no_return
@on_load {:load_natively_implemented_functions, 0}
app = Mix.Project.config()[:app]
def load_natively_implemented_functions do
path_components = [:code.priv_dir(unquote(app)), 'native', 'libockam_elixir_ffi']
path = :filename.join(path_components)
:ok = :erlang.load_nif(path, 0)
end
# Called when the Ockam application is started.
#
# This function is called when an application is started using
# `Application.start/2`, `Application.ensure_started/2` etc.
#
@doc false
def start(_type, _args) do
# Specifications of child processes that will be started and supervised.
#
# See the "Child specification" section in the `Supervisor` module for more
# detailed information.
children = []
# Start a supervisor with the given children. The supervisor will inturn
# start the given children.
#
# The :one_for_one supervision strategy is used, if a child process
# terminates, only that process is restarted.
#
# See the "Strategies" section in the `Supervisor` module for more
# detailed information.
Supervisor.start_link(children, strategy: :one_for_one, name: __MODULE__)
end
def init do
with {:ok, id} <- default_init() do
{:ok, %__MODULE__{id: id}}
end
end
def default_init do
raise "natively implemented default_init/0 not loaded"
end
def sha256(_vault, _input) do
raise "natively implemented sha256/2 not loaded"
end
def secret_generate(_vault, _attributes) do
raise "natively implemented secret_generate/2 not loaded"
end
def secret_import(_vault, _attributes, _input) do
raise "natively implemented secret_import/3 not loaded"
end
def secret_export(_vault, _secret_handle) do
raise "natively implemented secret_export/2 not loaded"
end
def secret_publickey_get(_vault, _secret_handle) do
raise "natively implemented secret_publickey_get/2 not loaded"
end
def secret_attributes_get(_vault, _secret_handle) do
raise "natively implemented secret_attributes_get/2 not loaded"
end
def secret_destroy(_vault, _secret_handle) do
raise "natively implemented secret_destroy/2 not loaded"
end
def ecdh(_vault, _secret_handle, _input) do
raise "natively implemented ecdh/3 not loaded"
end
def hkdf_sha256(_vault, _salt_handle, _ikm_handle, _derived_outputs_count) do
raise "natively implemented hkdf_sha256/4 not loaded"
end
def hkdf_sha256(_vault, _salt_handle, _ikm_handle) do
raise "natively implemented hkdf_sha256/3 not loaded"
end
def aead_aes_gcm_encrypt(_vault, _key_handle, _nonce, _ad, _plain_text) do
raise "natively implemented aead_aes_gcm_encrypt/5 not loaded"
end
def aead_aes_gcm_decrypt(_vault, _key_handle, _nonce, _ad, _cipher_text) do
raise "natively implemented aead_aes_gcm_decrypt/5 not loaded"
end
def deinit(_vault) do
raise "natively implemented deinit/1 not loaded"
end
end
| 28.509259 | 85 | 0.736603 |
080bdae0e476df7608667bb3dadf29ddcba54b40 | 1,357 | exs | Elixir | test/integration_test.exs | sb8244/statsd_logger | 3bf97bef353338730e9feb11a8b9a6cec964ad76 | [
"MIT"
] | 2 | 2019-09-02T02:10:07.000Z | 2021-04-02T03:56:30.000Z | test/integration_test.exs | sb8244/statsd_logger | 3bf97bef353338730e9feb11a8b9a6cec964ad76 | [
"MIT"
] | null | null | null | test/integration_test.exs | sb8244/statsd_logger | 3bf97bef353338730e9feb11a8b9a6cec964ad76 | [
"MIT"
] | 1 | 2021-08-15T00:32:53.000Z | 2021-08-15T00:32:53.000Z | defmodule IntegrationTest do
use ExUnit.Case, async: false
@port 8130
def send_event(msg) do
{:ok, port} = :gen_udp.open(0)
:gen_udp.send(port, 'localhost', @port, msg)
:ok = :gen_udp.close(port)
end
describe "starting" do
test "an already in used port will log an error" do
assert {:ok, _pid} = StatsDLogger.start_link(port: @port)
assert StatsDLogger.start_link(port: @port) == :ignore
end
end
describe "io formatter" do
# Visual test due to how STDIO capture works for global processes
test "valid / invalid messages are handled" do
StatsDLogger.start_link(port: @port)
send_event("a:1")
send_event("a:2")
send_event("invalid")
Process.sleep(50)
end
test "io is a valid formatter option" do
StatsDLogger.start_link(port: @port, formatter: :io)
send_event("a:1")
send_event("a:2")
send_event("invalid")
Process.sleep(50)
end
end
describe "send formatter" do
test "valid / invalid messages are handled" do
StatsDLogger.start_link(port: @port, formatter: :send)
send_event("a:1")
send_event("a:2|c")
send_event("invalid")
assert_receive {:statsd_recv, "a", "1"}
assert_receive {:statsd_recv, "a", "2|c"}
assert_receive {:statsd_recv_invalid, "invalid"}
end
end
end
| 25.12963 | 69 | 0.641857 |
080bdf695f6bbfca470388d3e4887a41ce926758 | 6,980 | ex | Elixir | apps/fz_http/lib/fz_http/devices/device.ex | amishakov/firezone | cd85b0847ac1792ca00aedab99fbf0f7a520f1a6 | [
"Apache-2.0"
] | null | null | null | apps/fz_http/lib/fz_http/devices/device.ex | amishakov/firezone | cd85b0847ac1792ca00aedab99fbf0f7a520f1a6 | [
"Apache-2.0"
] | 1 | 2022-03-30T03:57:41.000Z | 2022-03-30T03:57:41.000Z | apps/fz_http/lib/fz_http/devices/device.ex | amishakov/firezone | cd85b0847ac1792ca00aedab99fbf0f7a520f1a6 | [
"Apache-2.0"
] | null | null | null | defmodule FzHttp.Devices.Device do
@moduledoc """
Manages Device things
"""
use Ecto.Schema
import Ecto.Changeset
require Logger
import FzHttp.SharedValidators,
only: [
validate_fqdn_or_ip: 2,
validate_omitted: 2,
validate_list_of_ips: 2,
validate_no_duplicates: 2,
validate_list_of_ips_or_cidrs: 2
]
import FzHttp.Queries.INET
alias FzHttp.{Devices, Users.User}
@description_max_length 2048
schema "devices" do
field :rx_bytes, :integer
field :tx_bytes, :integer
field :uuid, Ecto.UUID, autogenerate: true
field :name, :string
field :description, :string
field :public_key, :string
field :preshared_key, FzHttp.Encrypted.Binary
field :use_site_allowed_ips, :boolean, read_after_writes: true, default: true
field :use_site_dns, :boolean, read_after_writes: true, default: true
field :use_site_endpoint, :boolean, read_after_writes: true, default: true
field :use_site_mtu, :boolean, read_after_writes: true, default: true
field :use_site_persistent_keepalive, :boolean, read_after_writes: true, default: true
field :endpoint, :string
field :mtu, :integer
field :persistent_keepalive, :integer
field :allowed_ips, :string
field :dns, :string
field :remote_ip, EctoNetwork.INET
field :ipv4, EctoNetwork.INET, read_after_writes: true
field :ipv6, EctoNetwork.INET, read_after_writes: true
field :latest_handshake, :utc_datetime_usec
field :key_regenerated_at, :utc_datetime_usec, read_after_writes: true
belongs_to :user, User
timestamps(type: :utc_datetime_usec)
end
def create_changeset(device, attrs) do
device
|> shared_cast(attrs)
|> put_next_ip(:ipv4)
|> put_next_ip(:ipv6)
|> shared_changeset()
|> validate_max_devices()
end
def update_changeset(device, attrs) do
device
|> shared_cast(attrs)
|> shared_changeset()
end
def field(changeset, field) do
get_field(changeset, field)
end
defp shared_cast(device, attrs) do
device
|> cast(attrs, [
:latest_handshake,
:rx_bytes,
:tx_bytes,
:use_site_allowed_ips,
:use_site_dns,
:use_site_endpoint,
:use_site_mtu,
:use_site_persistent_keepalive,
:allowed_ips,
:dns,
:endpoint,
:mtu,
:persistent_keepalive,
:remote_ip,
:ipv4,
:ipv6,
:user_id,
:name,
:description,
:public_key,
:preshared_key,
:key_regenerated_at
])
end
defp shared_changeset(changeset) do
changeset
|> validate_required([
:user_id,
:name,
:public_key
])
|> validate_required_unless_site([:endpoint])
|> validate_omitted_if_site([
:allowed_ips,
:dns,
:endpoint,
:persistent_keepalive,
:mtu
])
|> validate_list_of_ips_or_cidrs(:allowed_ips)
|> validate_list_of_ips(:dns)
|> validate_no_duplicates(:dns)
|> validate_fqdn_or_ip(:endpoint)
|> validate_number(:persistent_keepalive,
greater_than_or_equal_to: 0,
less_than_or_equal_to: 120
)
|> validate_number(:mtu,
greater_than_or_equal_to: 576,
less_than_or_equal_to: 1500
)
|> validate_length(:description, max: @description_max_length)
|> validate_ipv4_required()
|> validate_ipv6_required()
|> unique_constraint(:ipv4)
|> unique_constraint(:ipv6)
|> validate_exclusion(:ipv4, [ipv4_address()])
|> validate_exclusion(:ipv6, [ipv6_address()])
|> validate_in_network(:ipv4)
|> validate_in_network(:ipv6)
|> unique_constraint(:public_key)
|> unique_constraint([:user_id, :name])
end
defp validate_max_devices(changeset) do
user_id = changeset.changes.user_id || changeset.data.user_id
count = Devices.count(user_id)
max_devices = Application.fetch_env!(:fz_http, :max_devices_per_user)
if count >= max_devices do
add_error(
changeset,
:base,
"Maximum device limit reached. Remove an existing device before creating a new one."
)
else
changeset
end
end
defp validate_omitted_if_site(changeset, fields) when is_list(fields) do
validate_omitted(changeset, filter_site_fields(changeset, fields, use_site: true))
end
defp validate_required_unless_site(changeset, fields) when is_list(fields) do
validate_required(changeset, filter_site_fields(changeset, fields, use_site: false))
end
defp filter_site_fields(changeset, fields, use_site: use_site) when is_boolean(use_site) do
fields
|> Enum.map(fn field -> String.to_atom("use_site_#{field}") end)
|> Enum.filter(fn site_field -> get_field(changeset, site_field) == use_site end)
|> Enum.map(fn field ->
field
|> Atom.to_string()
|> String.trim("use_site_")
|> String.to_atom()
end)
end
defp validate_ipv4_required(changeset) do
if Application.fetch_env!(:fz_http, :wireguard_ipv4_enabled) do
validate_required(changeset, :ipv4)
else
changeset
end
end
defp validate_ipv6_required(changeset) do
if Application.fetch_env!(:fz_http, :wireguard_ipv6_enabled) do
validate_required(changeset, :ipv6)
else
changeset
end
end
defp validate_in_network(%Ecto.Changeset{changes: %{ipv4: ip}} = changeset, :ipv4) do
net = Application.fetch_env!(:fz_http, :wireguard_ipv4_network)
add_net_error_if_outside_bounds(changeset, net, ip, :ipv4)
end
defp validate_in_network(changeset, :ipv4), do: changeset
defp validate_in_network(%Ecto.Changeset{changes: %{ipv6: ip}} = changeset, :ipv6) do
net = Application.fetch_env!(:fz_http, :wireguard_ipv6_network)
add_net_error_if_outside_bounds(changeset, net, ip, :ipv6)
end
defp validate_in_network(changeset, :ipv6), do: changeset
defp add_net_error_if_outside_bounds(changeset, net, ip, ip_type) do
%{address: address} = ip
cidr = CIDR.parse(net)
if CIDR.match!(cidr, address) do
changeset
else
add_error(changeset, ip_type, "IP must be contained within network #{net}")
end
end
defp put_next_ip(changeset, ip_type) when ip_type in [:ipv4, :ipv6] do
case changeset do
# Don't put a new ip if the user is trying to assign one manually
%Ecto.Changeset{changes: %{^ip_type => _ip}} ->
changeset
_ ->
if ip = next_available(ip_type) do
put_change(changeset, ip_type, ip)
else
add_error(
changeset,
ip_type,
"address pool is exhausted. Increase network size or remove some devices."
)
end
end
end
defp ipv4_address do
{:ok, inet} =
Application.fetch_env!(:fz_http, :wireguard_ipv4_address)
|> EctoNetwork.INET.cast()
inet
end
defp ipv6_address do
{:ok, inet} =
Application.fetch_env!(:fz_http, :wireguard_ipv6_address)
|> EctoNetwork.INET.cast()
inet
end
end
| 27.588933 | 93 | 0.677937 |
080bfec15fb9898bce712ee13969adda95d5e576 | 4,261 | ex | Elixir | _index.ex/_alpha.ex/_vnc.ex | mirage335/CoreAutoSSH | d71c56b684f5bb45abe158d4bb9a51c9fa20e0fc | [
"CC0-1.0"
] | 1 | 2018-02-25T23:32:21.000Z | 2018-02-25T23:32:21.000Z | _index.ex/_alpha.ex/_vnc.ex | mirage335/CoreAutoSSH | d71c56b684f5bb45abe158d4bb9a51c9fa20e0fc | [
"CC0-1.0"
] | null | null | null | _index.ex/_alpha.ex/_vnc.ex | mirage335/CoreAutoSSH | d71c56b684f5bb45abe158d4bb9a51c9fa20e0fc | [
"CC0-1.0"
] | null | null | null | #!/usr/bin/env bash
#Critical prerequsites.
_realpath_L() {
if ! _compat_realpath_run -L . > /dev/null 2>&1
then
readlink -f "$@"
return
fi
realpath -L "$@"
}
_realpath_L_s() {
if ! _compat_realpath_run -L . > /dev/null 2>&1
then
readlink -f "$@"
return
fi
realpath -L -s "$@"
}
_getAbsolute_criticalDep() {
! type realpath > /dev/null 2>&1 && return 1
! type readlink > /dev/null 2>&1 && return 1
! type dirname > /dev/null 2>&1 && return 1
#Known issue on Mac. See https://github.com/mirage335/ubiquitous_bash/issues/1 .
! realpath -L . > /dev/null 2>&1 && return 1
return 0
}
! _getAbsolute_criticalDep && exit 1
#####Utilities.
#Retrieves absolute path of current script, while maintaining symlinks, even when "./" would translate with "readlink -f" into something disregarding symlinked components in $PWD.
#However, will dereference symlinks IF the script location itself is a symlink. This is to allow symlinking to scripts to function normally.
#Suitable for allowing scripts to find other scripts they depend on. May look like an ugly hack, but it has proven reliable over the years.
_getScriptAbsoluteLocation() {
if [[ "$0" == "-"* ]]
then
return 1
fi
local absoluteLocation
if [[ (-e $PWD\/$0) && ($0 != "") ]] && [[ "$0" != "/"* ]]
then
absoluteLocation="$PWD"\/"$0"
absoluteLocation=$(_realpath_L_s "$absoluteLocation")
else
absoluteLocation=$(_realpath_L "$0")
fi
if [[ -h "$absoluteLocation" ]]
then
absoluteLocation=$(readlink -f "$absoluteLocation")
absoluteLocation=$(_realpath_L "$absoluteLocation")
fi
echo $absoluteLocation
}
alias getScriptAbsoluteLocation=_getScriptAbsoluteLocation
#Retrieves absolute path of current script, while maintaining symlinks, even when "./" would translate with "readlink -f" into something disregarding symlinked components in $PWD.
#Suitable for allowing scripts to find other scripts they depend on.
_getScriptAbsoluteFolder() {
if [[ "$0" == "-"* ]]
then
return 1
fi
dirname "$(_getScriptAbsoluteLocation)"
}
alias getScriptAbsoluteFolder=_getScriptAbsoluteFolder
#Retrieves absolute path of parameter, while maintaining symlinks, even when "./" would translate with "readlink -f" into something disregarding symlinked components in $PWD.
#Suitable for finding absolute paths, when it is desirable not to interfere with symlink specified folder structure.
_getAbsoluteLocation() {
if [[ "$1" == "-"* ]]
then
return 1
fi
if [[ "$1" == "" ]]
then
echo
return
fi
local absoluteLocation
if [[ (-e $PWD\/$1) && ($1 != "") ]] && [[ "$1" != "/"* ]]
then
absoluteLocation="$PWD"\/"$1"
absoluteLocation=$(_realpath_L_s "$absoluteLocation")
else
absoluteLocation=$(_realpath_L "$1")
fi
echo "$absoluteLocation"
}
alias getAbsoluteLocation=_getAbsoluteLocation
#Generates random alphanumeric characters, default length 18.
_uid() {
local uidLength
! [[ -z "$1" ]] && uidLength="$1" || uidLength=18
cat /dev/urandom 2> /dev/null | base64 2> /dev/null | tr -dc 'a-zA-Z0-9' 2> /dev/null | head -c "$uidLength" 2> /dev/null
}
#Demarcate major steps.
_messageNormal() {
echo -e -n '\E[1;32;46m '
echo -n "$@"
echo -e -n ' \E[0m'
echo
return 0
}
_discoverResource() {
local testDir
testDir="$testScriptAbsoluteFolder" ; [[ -e "$testDir"/"$1" ]] && echo "$testDir"/"$1" && return
testDir="$testScriptAbsoluteFolder"/.. ; [[ -e "$testDir"/"$1" ]] && echo "$testDir"/"$1" && return
testDir="$testScriptAbsoluteFolder"/../.. ; [[ -e "$testDir"/"$1" ]] && echo "$testDir"/"$1" && return
testDir="$testScriptAbsoluteFolder"/../../.. ; [[ -e "$testDir"/"$1" ]] && echo "$testDir"/"$1" && return
}
##### META SCRIPT #####
export testScriptAbsoluteLocation=$(_getScriptAbsoluteLocation)
export testScriptAbsoluteFolder=$(_getScriptAbsoluteFolder)
export machineName=$(basename "$testScriptAbsoluteFolder")
export commandName=$(basename "$testScriptAbsoluteLocation")
##### Script Call
cautosshLocation=$(_discoverResource cautossh)
opsLocation=$(_discoverResource ops)
export SSHUSER=
[[ "$SSHUSER" != "" ]] && export SSHUSER="$SSHUSER"'@'
#Import settings.
. "$cautosshLocation"
#Launch in directory with needed resources.
"$cautosshLocation" "$commandName" "$SSHUSER""$machineName" "$@"
| 26.302469 | 179 | 0.68552 |
080c01f315dba3d4804f84536a64c4c74403a875 | 477 | exs | Elixir | code/enum/stream3.exs | alvarocamillont/introdu-o_elixir | 1d72d4f4b01d9312c4b066ce3c0fe8d9bfaaade1 | [
"MIT"
] | null | null | null | code/enum/stream3.exs | alvarocamillont/introdu-o_elixir | 1d72d4f4b01d9312c4b066ce3c0fe8d9bfaaade1 | [
"MIT"
] | 1 | 2021-03-09T16:27:25.000Z | 2021-03-09T16:27:25.000Z | programming-elixir-book/code/enum/stream3.exs | jordanhubbard/elixir-projects | dee341d672e83a45a17a4a85abd54a480f95c506 | [
"BSD-2-Clause"
] | null | null | null | #---
# Excerpted from "Programming Elixir ≥ 1.6",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/elixir16 for more book information.
#---
IO.puts File.stream!("/usr/share/dict/words") |> Enum.max_by(&String.length/1) | 53 | 85 | 0.744235 |
080c05f603d8ff27e5800c08106402ae932da6f1 | 103 | exs | Elixir | 03_recursion/elixir/03_factorial.exs | filchyboy/grokking_algorithms_work | 16dace97610e2cb0938704e2b8cfd6e92d6b024d | [
"MIT"
] | 13 | 2021-03-11T00:25:22.000Z | 2022-03-19T00:19:23.000Z | book04grokkingAlgo/03_recursion/elixir/03_factorial.exs | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 160 | 2021-04-26T19:04:15.000Z | 2022-03-26T20:18:37.000Z | book04grokkingAlgo/03_recursion/elixir/03_factorial.exs | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 12 | 2021-04-26T19:43:01.000Z | 2022-01-31T08:36:29.000Z | defmodule Factorial do
def of(1), do: 1
def of(n), do: n * of(n - 1)
end
IO.puts(Factorial.of(5))
| 14.714286 | 30 | 0.61165 |
080c0e1dfc48db65674df98a82d22bba3f1535cf | 2,123 | exs | Elixir | test/resource/calculations_test.exs | mario-mazo/ash | 8673a733c702971a1435514151ab434d87893685 | [
"MIT"
] | null | null | null | test/resource/calculations_test.exs | mario-mazo/ash | 8673a733c702971a1435514151ab434d87893685 | [
"MIT"
] | null | null | null | test/resource/calculations_test.exs | mario-mazo/ash | 8673a733c702971a1435514151ab434d87893685 | [
"MIT"
] | null | null | null | defmodule Ash.Test.Resource.CalculationsTest do
@moduledoc false
use ExUnit.Case, async: true
alias Ash.Resource.Calculation
defmacrop defposts(do: body) do
quote do
defmodule Post do
@moduledoc false
use Ash.Resource
attributes do
attribute :id, :uuid, primary_key?: true, default: &Ecto.UUID.generate/0
attribute :name, :string
attribute :contents, :string
end
unquote(body)
end
end
end
describe "representation" do
test "calculations are persisted on the resource properly" do
defposts do
calculations do
calculate :name_and_contents, concat([:name, :context])
calculate :another_cal_but_private, concat([:name, :context]), private?: true
end
end
assert [
%Calculation{
name: :name_and_contents,
calculation: {Calculation.Concat, [keys: [:name, :context], separator: ""]},
private?: false
},
%Calculation{
name: :another_cal_but_private,
calculation: {Calculation.Concat, [keys: [:name, :context], separator: ""]},
private?: true
}
] = Ash.Resource.calculations(Post)
assert [%Calculation{name: :name_and_contents}] = Ash.Resource.public_calculations(Post)
assert %Calculation{name: :another_cal_but_private} =
Ash.Resource.calculation(Post, :another_cal_but_private)
assert nil == Ash.Resource.public_calculation(Post, :another_cal_but_private)
assert nil == Ash.Resource.calculation(Post, :totally_legit_calculation)
end
test "Calculation descriptions are allowed" do
defposts do
calculations do
calculate :name_and_contents, concat([:name, :context]),
description: "require one of name/contents"
end
end
assert [
%Ash.Resource.Calculation{description: "require one of name/contents"}
] = Ash.Resource.calculations(Post)
end
end
end
| 29.901408 | 94 | 0.606689 |
080c1d2773f401e3beeee33808e331fde3a08138 | 5,868 | ex | Elixir | clients/double_click_bid_manager/lib/google_api/double_click_bid_manager/v11/api/lineitems.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/double_click_bid_manager/lib/google_api/double_click_bid_manager/v11/api/lineitems.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/double_click_bid_manager/lib/google_api/double_click_bid_manager/v11/api/lineitems.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DoubleClickBidManager.V11.Api.Lineitems do
@moduledoc """
API calls for all endpoints tagged `Lineitems`.
"""
alias GoogleApi.DoubleClickBidManager.V11.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Retrieves line items in CSV format. TrueView line items are not supported.
## Parameters
* `connection` (*type:* `GoogleApi.DoubleClickBidManager.V11.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.DoubleClickBidManager.V11.Model.DownloadLineItemsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DoubleClickBidManager.V11.Model.DownloadLineItemsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec doubleclickbidmanager_lineitems_downloadlineitems(
Tesla.Env.client(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.DoubleClickBidManager.V11.Model.DownloadLineItemsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def doubleclickbidmanager_lineitems_downloadlineitems(
connection,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/lineitems/downloadlineitems", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.DoubleClickBidManager.V11.Model.DownloadLineItemsResponse{}]
)
end
@doc """
Uploads line items in CSV format. TrueView line items are not supported.
## Parameters
* `connection` (*type:* `GoogleApi.DoubleClickBidManager.V11.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.DoubleClickBidManager.V11.Model.UploadLineItemsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.DoubleClickBidManager.V11.Model.UploadLineItemsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec doubleclickbidmanager_lineitems_uploadlineitems(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.DoubleClickBidManager.V11.Model.UploadLineItemsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def doubleclickbidmanager_lineitems_uploadlineitems(
connection,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/lineitems/uploadlineitems", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.DoubleClickBidManager.V11.Model.UploadLineItemsResponse{}]
)
end
end
| 40.75 | 187 | 0.654908 |
080c4590238570b6d8460b125993e0506c504aad | 2,682 | exs | Elixir | mix.exs | blacksph3re/alastair3 | d6064e322b8ef5c6eb8da59a080852179a71b9d5 | [
"Apache-2.0"
] | null | null | null | mix.exs | blacksph3re/alastair3 | d6064e322b8ef5c6eb8da59a080852179a71b9d5 | [
"Apache-2.0"
] | null | null | null | mix.exs | blacksph3re/alastair3 | d6064e322b8ef5c6eb8da59a080852179a71b9d5 | [
"Apache-2.0"
] | null | null | null | defmodule Alastair.Mixfile do
use Mix.Project
def project do
[app: :alastair,
version: "0.0.1",
elixir: "~> 1.2",
elixirc_paths: elixirc_paths(Mix.env),
compilers: [:phoenix, :gettext] ++ Mix.compilers,
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
aliases: aliases(),
deps: deps(),
test_coverage: coverex()
]
end
# Configure coverex to ignore all phoenix generated files and unnecessary things
def coverex do
[tool: Coverex.Task,
coveralls: true,
ignore_modules: [
Elixir.Alastair,
Elixir.Alastair.Router.Helpers,
Elixir.Alastair.Router,
Elixir.Alastair.Repo,
Elixir.Alastair.Seeds,
Elixir.Alastair.Seeds.CurrencySeed,
Elixir.Alastair.Seeds.ExampleSeed,
Elixir.Alastair.Seeds.IngredientSeed,
Elixir.Alastair.Seeds.MeasurementSeed,
Elixir.Phoenix.Param.Alastair.Event,
Elixir.Poison.Encoder.Alastair.Notification,
Elixir.Alastair.Web,
Elixir.Alastair.ChannelCase,
Elixir.Alastair.ConnCase,
Elixir.Alastair.ModelCase,
Elixir.Alastair.Gettext,
Elixir.Alastair.ChangesetView,
Elixir.Alastair.ErrorView,
Elixir.Alastair.ErrorHelpers,
Elixir.Alastair.Endpoint
]]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[mod: {Alastair, []},
applications: [:phoenix, :phoenix_pubsub, :phoenix_html, :cowboy, :logger, :gettext,
:phoenix_ecto, :postgrex, :httpoison]]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "web", "test/support"]
defp elixirc_paths(_), do: ["lib", "web"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[{:phoenix, "~> 1.2.4"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_ecto, "~> 3.0"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.6"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"},
{:ecto_enum, "~> 1.0"},
{:httpoison, "~> 0.13"},
{:coverex, "~> 1.4.10"}
]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, to create, migrate and run the seeds file at once:
#
# $ mix ecto.setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
["ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
"ecto.reset": ["ecto.drop", "ecto.setup"],
"test": ["ecto.create --quiet", "ecto.migrate", "test"]]
end
end
| 30.134831 | 89 | 0.62789 |
080c53cec4252b2a09cbd0d3753bd3bba45effd5 | 1,817 | ex | Elixir | lib/md0/rgx_scanner.ex | RobertDober/md0 | b2337e69a9bea6b2b17951b75daa15fe7fe8cfad | [
"Apache-2.0"
] | null | null | null | lib/md0/rgx_scanner.ex | RobertDober/md0 | b2337e69a9bea6b2b17951b75daa15fe7fe8cfad | [
"Apache-2.0"
] | null | null | null | lib/md0/rgx_scanner.ex | RobertDober/md0 | b2337e69a9bea6b2b17951b75daa15fe7fe8cfad | [
"Apache-2.0"
] | null | null | null | defmodule Md0.RgxScanner do
use Md0.Scanner.RgxMacros
@moduledoc """
A lexical Analyzer of markdown documents
"""
def scan_document(doc) do
doc
|> String.split(~r{\r\n?|\n})
|> Enum.zip(Stream.iterate(1, &(&1 + 1)))
|> Enum.flat_map(&scan_line/1)
end
defp scan_line({line, lnb}) do
with tokens <- tokenize(lnb, line, []), do: tokens |> Enum.reverse()
end
defp tokenize(lnb, line, tokens, col \\ 1)
defp tokenize(_lnb, "", tokens, _col), do: tokens
defp tokenize(lnb, line, tokens, col) do
with {{sym, txt, col1}, rest, new_col} <- get_token(line, col),
do: tokenize(lnb, rest, [{sym, txt, lnb, col1} | tokens], new_col)
end
# We define token in the *reverse* order they are searched, thusly
# it would be best to move the most frequent but also the
# not too expensive to check downwards, the actual order
# might not be ideal for the typical Elixir docstrings.
# In case of performance issues, some research might be
# in order.
deftoken(:any, "[^\\s`*]+")
deftoken(:back, "`+")
deftoken(:star, "\\*+")
deftoken(:ws, "\\s+")
deftoken(:li, "\\*\\s")
defstarttoken(:indent, "\\s+")
defp get_token(line, col) do
match(line, col) || {{:error, line, col}, "", col}
end
defp match(line, 1) do
@_defined_start_tokens
|> Enum.find_value(&match_token(&1, line, 1)) || match_later(line, 1)
end
defp match(line, col), do: match_later(line, col)
defp match_later(line, col) do
@_defined_tokens
|> Enum.find_value(&match_token(&1, line, col))
end
defp match_token({token_name, token_rgx}, line, col) do
case Regex.run(token_rgx, line) do
[_, token_string, rest] ->
{{token_name, token_string, col}, rest, col + String.length(token_string)}
_ ->
nil
end
end
end
| 27.119403 | 82 | 0.63016 |
080c775d0647b11029a98b47e847f0b817c9d704 | 322 | ex | Elixir | lib/idvote/polygon.ex | boisebrigade/idvote | fb1d3f348db094e0578d6976a0a349971bf7aab7 | [
"ISC"
] | 2 | 2018-08-15T02:03:36.000Z | 2019-02-06T23:27:56.000Z | lib/idvote/polygon.ex | boisebrigade/idvote | fb1d3f348db094e0578d6976a0a349971bf7aab7 | [
"ISC"
] | 14 | 2018-08-11T19:47:56.000Z | 2018-08-29T22:44:22.000Z | lib/idvote/polygon.ex | boisebrigade/idvote | fb1d3f348db094e0578d6976a0a349971bf7aab7 | [
"ISC"
] | 2 | 2018-08-11T16:44:02.000Z | 2018-08-28T03:45:55.000Z | defimpl Jason.Encoder, for: Geo.Polygon do
def encode(value, opts) do
%{coordinates: coordinates, srid: srid} = Map.take(value, [:srid,:coordinates])
coordinates = Enum.map(coordinates, &Enum.map(&1, fn point -> Tuple.to_list(point) end))
Jason.Encode.map(%{bbox: coordinates, srid: srid}, opts)
end
end
| 32.2 | 92 | 0.689441 |
080cc2e56e9acadb28f618df26802aa7d6aad640 | 6,430 | ex | Elixir | lib/ex_raft/state/leader.ex | bajankristof/ex_raft | 09c3234355d2792922b17a71e3c32b3e57f0a277 | [
"Apache-2.0"
] | 1 | 2021-08-25T10:49:26.000Z | 2021-08-25T10:49:26.000Z | lib/ex_raft/state/leader.ex | bajankristof/ex_raft | 09c3234355d2792922b17a71e3c32b3e57f0a277 | [
"Apache-2.0"
] | null | null | null | lib/ex_raft/state/leader.ex | bajankristof/ex_raft | 09c3234355d2792922b17a71e3c32b3e57f0a277 | [
"Apache-2.0"
] | null | null | null | defmodule ExRaft.State.Leader do
@moduledoc false
use ExRaft.State
require ExRaft.RPC
require ExRaft.Server.Context
import ExRaft.Server, only: [async_each: 2]
alias ExRaft.{Log, MatchIndex, NextIndex, RPC, Server, StateMachine}
alias ExRaft.Server.{Context, Logger}
def enter(_, ctx) do
ctx = Context.enter_leader(ctx)
Logger.debug("entered leader state for term #{ctx.term}", ctx)
StateMachine.transition(ctx.state_machine, :leader)
Enum.each(ctx.await_leader_queue, &GenStateMachine.reply(&1, ctx.self))
entry = Log.insert_new(ctx.log, ctx.term, :config, ctx.config)
handle_log_change(%{ctx | await_leader_queue: [], config_change: :leader, last_entry: entry})
end
def exit(_, ctx) do
Context.unset_leader(ctx)
end
# ========
# | info |
# ========
def info(:heartbeat_timeout, ctx)
when ctx.peers !== [] do
async_each(ctx.peers, fn peer ->
next_index = NextIndex.get(ctx.next_index, peer, ctx.last_entry.index + 1)
last_index = next_index + ctx.batch_size
prev_index = next_index - 1
prev_entry = Log.select_at(ctx.log, prev_index)
entries = Log.select_range(ctx.log, next_index..last_index)
RPC.async_call(ctx.rpc, peer, %RPC.AppendRequest{
term: ctx.term,
commit_index: ctx.commit_index,
prev_entry: prev_entry,
prev_index: prev_index,
config: ctx.config,
entries: entries
})
end)
{:keep_state, Context.reset_heartbeat_timeout(ctx)}
end
def info(_, _),
do: :keep_state_and_data
# ========
# | cast |
# ========
def cast(%RPC.AppendResponse{} = response, ctx)
when ctx.term < response.term do
Logger.debug("received higher term, stepping down", ctx)
{:next_state, :follower, Context.set_term(ctx, response.term)}
end
def cast(%RPC.AppendResponse{from: peer, index: index} = response, ctx)
when response.success === false do
next_index = NextIndex.decr(ctx.next_index, peer, index)
{:keep_state, %{ctx | next_index: next_index}}
end
def cast(%RPC.AppendResponse{from: peer, index: index} = response, ctx)
when response.index <= ctx.commit_index do
match_index = MatchIndex.incr(ctx.match_index, peer, index)
next_index = NextIndex.set(ctx.next_index, peer, index + 1)
{:keep_state, %{ctx | match_index: match_index, next_index: next_index}}
end
def cast(%RPC.AppendResponse{from: peer, index: index}, ctx) do
match_index = MatchIndex.incr(ctx.match_index, peer, index)
next_index = NextIndex.set(ctx.next_index, peer, index + 1)
ctx = %{ctx | match_index: match_index, next_index: next_index}
if Context.majority_replicates?(ctx, index) do
ctx = Context.set_commit_index(ctx, index)
Logger.debug("committed entries up to ##{index}", ctx)
ctx = Server.apply(ctx)
if ctx.step_down do
follower = MatchIndex.best_node(ctx.match_index)
spawn(fn -> Server.call(follower, :trigger_election) end)
{:next_state, :follower, ctx}
else
{:keep_state, ctx}
end
else
{:keep_state, ctx}
end
end
def cast(_, _),
do: :keep_state_and_data
# ========
# | call |
# ========
def call(request, from, ctx)
when RPC.is_request(request) and ctx.term < request.term do
Logger.debug("received higher term, stepping down", ctx)
{:next_state, :follower, Context.set_term(ctx, request.term),
[{:next_event, {:call, from}, request}]}
end
def call(:ping, from, _) do
GenStateMachine.reply(from, :pong)
:keep_state_and_data
end
def call(:await_leader, from, ctx) do
GenStateMachine.reply(from, ctx.self)
:keep_state_and_data
end
def call(:trigger_election, from, ctx) do
GenStateMachine.reply(from, :ok)
{:next_state, :candidate, ctx}
end
def call({:remove_server, server}, from, ctx)
when ctx.config === [server] do
GenStateMachine.reply(from, {:error, :last_server})
:keep_state_and_data
end
def call({command, _}, from, ctx)
when command in [:add_server, :remove_server] and
ctx.config_change === :leader do
GenStateMachine.reply(from, {:error, :unstable_leader})
:keep_state_and_data
end
def call({command, _}, from, ctx)
when command in [:add_server, :remove_server] and
not is_nil(ctx.config_change) do
GenStateMachine.reply(from, {:error, :unstable_config})
:keep_state_and_data
end
def call({:add_server, server}, from, ctx) do
if Enum.member?(ctx.config, server) do
GenStateMachine.reply(from, :ok)
:keep_state_and_data
else
:lists.usort([server | ctx.config])
|> handle_config_change(from, ctx)
end
end
def call({:remove_server, server}, from, ctx) do
if !Enum.member?(ctx.config, server) do
GenStateMachine.reply(from, :ok)
:keep_state_and_data
else
List.delete(ctx.config, server)
|> handle_config_change(from, ctx)
end
end
def call({:write, command}, from, ctx) do
if StateMachine.command?(ctx.state_machine, command) do
entry = Log.insert_new(ctx.log, ctx.term, :write, command, from)
handle_log_change(%{ctx | last_entry: entry})
else
:keep_state_and_data
end
end
def call({:read_dirty, _}, _, ctx)
when ctx.dirty_read !== true do
:keep_state_and_data
end
def call({command, query}, from, ctx)
when command in [:read, :read_dirty] do
case StateMachine.handle_read(ctx.state_machine, query) do
{:reply, reply} ->
GenStateMachine.reply(from, reply)
:keep_state_and_data
:noreply ->
:keep_state_and_data
end
end
def call(:leader, from, ctx) do
GenStateMachine.reply(from, ctx.self)
:keep_state_and_data
end
def call(_, _, _),
do: :keep_state_and_data
# ===========
# | private |
# ===========
defp handle_log_change(ctx)
when Context.is_single_server(ctx) do
{:keep_state,
Context.set_commit_index(ctx, ctx.last_entry.index)
|> Server.apply()}
end
defp handle_log_change(ctx) do
{:keep_state, Context.reset_heartbeat_timeout(ctx, 0)}
end
defp handle_config_change(config, from, ctx) do
entry = Log.insert_new(ctx.log, ctx.term, :config, config, from)
%{ctx | config_change: entry, last_entry: entry}
|> Context.set_config(config)
|> handle_log_change()
end
end
| 28.577778 | 97 | 0.657543 |
080cc5af77a423ac256095870e23ef3094a3e2f5 | 425 | ex | Elixir | blog_data_writer_server/lib/app/post.ex | xawe/elixir_micro_blog | eee893238a9647708336901f3ead4629067d590f | [
"MIT"
] | null | null | null | blog_data_writer_server/lib/app/post.ex | xawe/elixir_micro_blog | eee893238a9647708336901f3ead4629067d590f | [
"MIT"
] | null | null | null | blog_data_writer_server/lib/app/post.ex | xawe/elixir_micro_blog | eee893238a9647708336901f3ead4629067d590f | [
"MIT"
] | null | null | null | defmodule App.Post do
use Ecto.Schema
import Ecto.Changeset
schema "post" do
field(:user, :string)
field(:message, :string)
field(:referenceid, :string)
field(:fingerprint, :string)
timestamps()
end
def changeset(struct, params) do
struct
|> cast(params, [:user, :message, :referenceid, :fingerprint])
|> validate_required([:user, :message, :referenceid, :fingerprint])
end
end
| 21.25 | 71 | 0.665882 |
080cec3e4c2f1d94a797a80f50506213de4c9f9f | 961 | ex | Elixir | apps/admin_api/lib/admin_api/v1/views/balance_view.ex | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 322 | 2018-02-28T07:38:44.000Z | 2020-05-27T23:09:55.000Z | apps/admin_api/lib/admin_api/v1/views/balance_view.ex | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 643 | 2018-02-28T12:05:20.000Z | 2020-05-22T08:34:38.000Z | apps/admin_api/lib/admin_api/v1/views/balance_view.ex | 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 AdminAPI.V1.BalanceView do
use AdminAPI, :view
alias EWallet.Web.V1.{ResponseSerializer, BalanceSerializer}
alias EWallet.Web.{Paginator}
def render("balances.json", %{data: data, pagination: pagination}) do
%Paginator{pagination: pagination, data: data}
|> BalanceSerializer.serialize()
|> ResponseSerializer.serialize(success: true)
end
end
| 36.961538 | 74 | 0.756504 |
080d092acdfc024464f54c2647e2302ce41d4a5e | 9,457 | ex | Elixir | apps/core/lib/core/divisions/divisions.ex | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 8 | 2019-06-14T11:34:49.000Z | 2021-08-05T19:14:24.000Z | apps/core/lib/core/divisions/divisions.ex | edenlabllc/ehealth.api.public | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 1 | 2019-07-08T15:20:22.000Z | 2019-07-08T15:20:22.000Z | apps/core/lib/core/divisions/divisions.ex | ehealth-ua/ehealth.api | 4ffe26a464fe40c95fb841a4aa2e147068f65ca2 | [
"Apache-2.0"
] | 6 | 2018-05-11T13:59:32.000Z | 2022-01-19T20:15:22.000Z | defmodule Core.Divisions do
@moduledoc """
The boundary for the Divisions system.
"""
use Core.Search, Application.get_env(:core, :repos)[:read_prm_repo]
import Core.API.Helpers.Connection, only: [get_client_id: 1, get_consumer_id: 1]
import Ecto.Changeset, warn: false
alias Core.Divisions.Division
alias Core.Divisions.Search
alias Core.Email.Sanitizer
alias Core.LegalEntities
alias Core.LegalEntities.LegalEntity
alias Core.PRMRepo
alias Core.ValidationError
alias Core.Validators.Addresses
alias Core.Validators.Error
alias Core.Validators.JsonObjects
alias Core.Validators.JsonSchema
alias Ecto.Multi
alias EctoTrail.Changelog
alias Scrivener.Page
@uaddresses_api Application.get_env(:core, :api_resolvers)[:uaddresses]
@read_prm_repo Application.get_env(:core, :repos)[:read_prm_repo]
@search_fields ~w(
ids
name
legal_entity_id
type
status
)a
@fields_optional ~w(
external_id
mountain_group
is_active
location
working_hours
dls_id
dls_verified
)a
@fields_required ~w(
legal_entity_id
name
type
phones
status
email
)a
@mountain_group_required_types %{mountain_group: :boolean, settlement_id: Ecto.UUID}
@status_active Division.status(:active)
@default_mountain_group "0"
def list(params) do
with %Page{entries: entries} = page <-
%Search{}
|> changeset(params)
|> search(params, Division) do
%{page | entries: @read_prm_repo.preload(entries, :addresses)}
end
end
def get_by_id!(id) do
Division
|> @read_prm_repo.get!(id)
|> @read_prm_repo.preload(:addresses)
end
def get_by_id(id) do
Division
|> @read_prm_repo.get(id)
|> @read_prm_repo.preload(:addresses)
end
def get_by_ids(ids) when is_list(ids) do
Division
|> where([d], d.id in ^ids)
|> @read_prm_repo.all()
|> @read_prm_repo.preload(:addresses)
end
def search(legal_entity_id, params \\ %{}) do
params
|> Map.put("legal_entity_id", legal_entity_id)
|> list()
end
def create(params, headers) do
with {:ok, attrs} <- prepare_division_data(params, get_client_id(headers)),
attrs <- Map.merge(attrs, %{"status" => @status_active, "is_active" => true}) do
%Division{}
|> changeset(attrs)
|> PRMRepo.insert_and_log(get_consumer_id(headers))
end
end
def update(id, params, headers) do
legal_entity_id = get_client_id(headers)
with {:ok, attrs} <- prepare_division_data(params, legal_entity_id),
%Division{} = division <- get_by_id(id),
:ok <- validate_token(division, legal_entity_id) do
division
|> changeset(attrs)
|> PRMRepo.update_and_log(get_consumer_id(headers))
end
end
defp prepare_division_data(params, legal_entity_id) do
with %LegalEntity{} = legal_entity <- LegalEntities.get_by_id(legal_entity_id),
:ok <- validate_legal_entity(legal_entity),
:ok <- validate_division_type(legal_entity, params),
params <-
params
|> Map.delete("id")
|> Map.put("legal_entity_id", legal_entity_id),
:ok <- JsonSchema.validate(:division, params),
params <- lowercase_email(params),
:ok <- validate_json_objects(params),
:ok <- validate_addresses(params) do
put_mountain_group(params)
else
nil ->
Error.dump(%ValidationError{
description: "invalid legal entity",
path: "$.legal_entity_id"
})
err ->
err
end
end
defp validate_legal_entity(%LegalEntity{} = legal_entity) do
is_active? =
legal_entity.is_active and
legal_entity.status in [LegalEntity.status(:active), LegalEntity.status(:suspended)]
if is_active? do
:ok
else
{:error, {:conflict, "Legal entity is not active"}}
end
end
def update_status(id, status, headers) do
legal_entity_id = get_client_id(headers)
with %Division{} = division <- get_by_id(id),
:ok <- validate_token(division, legal_entity_id),
{_, %LegalEntity{} = legal_entity} <- {:legal_entity, LegalEntities.get_by_id(legal_entity_id)},
:ok <- validate_legal_entity(legal_entity),
attrs <- %{"status" => status, "is_active" => status == @status_active} do
division
|> changeset(attrs)
|> PRMRepo.update_and_log(get_consumer_id(headers))
else
{:legal_entity, _} -> {:error, %{"type" => "internal_error"}}
error -> error
end
end
def update_mountain_group(attrs, consumer_id) do
case mountain_group_changeset(attrs) do
%Ecto.Changeset{valid?: true} -> do_update_divisions_mountain_group(attrs, consumer_id)
err_changeset -> err_changeset
end
end
def validate_json_objects(data) do
with :ok <- JsonObjects.array_unique_by_key(data, ["addresses"], "type"),
:ok <- JsonObjects.array_unique_by_key(data, ["phones"], "type"),
do: :ok
end
def validate_addresses(data) do
addresses = Map.get(data, "addresses") || []
Addresses.validate(addresses, "RESIDENCE")
end
defp validate_division_type(%LegalEntity{type: legal_entity_type}, params) do
config = Confex.fetch_env!(:core, :legal_entity_division_types)
legal_entity_type =
legal_entity_type
|> String.downcase()
|> String.to_atom()
allowed_types = Keyword.get(config, legal_entity_type)
type = Map.get(params, "type")
if !type || Enum.member?(allowed_types, type) do
:ok
else
Error.dump(%ValidationError{
description: "value is not allowed in enum",
path: "$.type",
params: allowed_types,
rule: "inclusion"
})
end
end
def put_mountain_group(%{"addresses" => addresses} = division) do
settlement_id =
addresses
|> List.first()
|> Map.fetch!("settlement_id")
settlement_id
|> @uaddresses_api.get_settlement_by_id([])
|> put_mountain_group(division)
end
def put_mountain_group(err), do: err
def put_mountain_group({:ok, %{"data" => address}}, division) do
mountain_group = Map.get(address, "mountain_group", @default_mountain_group)
{:ok, Map.put(division, "mountain_group", mountain_group)}
end
def put_mountain_group(err, _division), do: err
def validate_token(%Division{} = division, legal_entity_id) do
case legal_entity_id == division.legal_entity_id do
true -> :ok
false -> {:error, :forbidden}
end
end
def changeset(
%Division{} = division,
%{"location" => %{"longitude" => lng, "latitude" => lat}} = attrs
) do
division
|> changeset(Map.put(attrs, "location", %Geo.Point{coordinates: {lng, lat}}))
|> cast_assoc(:addresses)
end
def changeset(%Division{} = division, attrs) do
division
|> cast(attrs, @fields_optional ++ @fields_required)
|> validate_required(@fields_required)
|> foreign_key_constraint(:legal_entity_id)
|> cast_assoc(:addresses)
end
def changeset(%Search{} = division, attrs) do
cast(division, attrs, @search_fields)
end
defp mountain_group_changeset(attrs) do
required_params = Map.keys(@mountain_group_required_types)
{%{}, @mountain_group_required_types}
|> cast(attrs, required_params)
|> validate_required(required_params)
end
def get_search_query(Division = entity, %{ids: _} = changes) do
super(entity, convert_comma_params_to_where_in_clause(changes, :ids, :id))
end
def get_search_query(Division = division, changes) do
params =
changes
|> Map.drop([:name])
|> Map.to_list()
division
|> select([d], d)
|> query_name(Map.get(changes, :name))
|> where(^params)
end
defp query_name(query, nil), do: query
defp query_name(query, name) do
query |> where([d], ilike(d.name, ^"%#{name}%"))
end
defp convert_comma_params_to_where_in_clause(changes, param_name, db_field) do
changes
|> Map.put(db_field, {String.split(changes[param_name], ","), :in})
|> Map.delete(param_name)
end
defp do_update_divisions_mountain_group(attrs, consumer_id) do
%{settlement_id: settlement_id, mountain_group: mountain_group} = attrs
query =
Division
|> select([d], [:id, :mountain_group])
|> where([d], d.mountain_group != ^mountain_group)
|> join(:inner, [d], c in assoc(d, :addresses))
|> where([d, c], c.settlement_id == ^settlement_id)
Multi.new()
|> Multi.update_all(
:update_divisions_mountain_group,
query,
set: [mountain_group: mountain_group, updated_at: DateTime.utc_now()]
)
|> Multi.run(:log_updates, &log_changes(&1, &2, consumer_id))
|> PRMRepo.transaction()
end
defp log_changes(_, %{update_divisions_mountain_group: {_, updated_divisions}}, consumer_id) do
changes =
updated_divisions
|> Enum.map(fn division ->
%{
actor_id: consumer_id,
resource: "divisions",
resource_id: division.id,
changeset: %{mountain_group: division.mountain_group}
}
end)
|> Enum.map(&Map.put(&1, :inserted_at, DateTime.utc_now()))
{_, changelog} = PRMRepo.insert_all(Changelog, changes, returning: true)
{:ok, changelog}
end
defp lowercase_email(params) do
email = Map.get(params, "email")
Map.put(params, email, Sanitizer.sanitize(email))
end
end
| 28.145833 | 105 | 0.65782 |
080d0b24c124b77f8b03f752684baea5eb8459fc | 3,189 | ex | Elixir | lib/tan/flicker_code.ex | Ablu/fintex | 3dd2088c01a4e035478d09df1e09ec244b54cf87 | [
"MIT"
] | 27 | 2015-08-09T16:36:31.000Z | 2020-01-26T17:47:17.000Z | lib/tan/flicker_code.ex | Ablu/fintex | 3dd2088c01a4e035478d09df1e09ec244b54cf87 | [
"MIT"
] | 14 | 2015-07-31T07:28:07.000Z | 2018-09-06T18:32:37.000Z | lib/tan/flicker_code.ex | Ablu/fintex | 3dd2088c01a4e035478d09df1e09ec244b54cf87 | [
"MIT"
] | 19 | 2015-07-31T01:25:17.000Z | 2019-06-29T16:28:42.000Z | defmodule FinTex.Tan.FlickerCode do
@moduledoc false
# Flicker code extraction for optic chipTAN challenges.
#
# Based on Olaf Willuhn's Java implementation of flicker codes for HHD 1.3 and HHD 1.4,
# available at https://github.com/willuhn/hbci4java/blob/master/src/org/kapott/hbci/manager/FlickerCode.java
#
# Based in parts on Lars-Dominik Braun's JavaScript implementation of HHD 1.3 flicker codes,
# available at http://6xq.net/media/00/20/flickercode.html
alias FinTex.Helper.Checksum
alias FinTex.Helper.Conversion
alias FinTex.Tan.StartCode
alias FinTex.Tan.DataElement
import Checksum
import Conversion
@lc_length_hhd14 3
@lc_length_hhd13 2
@type t :: %__MODULE__{
lc: String.t,
start_code: StartCode.t,
data_elements: [DataElement.t]
}
defstruct [
:lc,
:start_code,
:data_elements
]
def new(code, version \\ :hhd14) when is_binary(code) and is_atom(version) do
c = code |> clean
len = case version do
:hhd14 -> @lc_length_hhd14
:hhd13 -> @lc_length_hhd13
end
{lc, c} = c |> String.split_at(len)
c_len = String.length(c)
case Integer.parse(lc) do
:error -> :error
{lc, _} when c_len == lc -> c |> do_parse(lc)
_ -> code |> new(:hhd13)
end
end
@spec render(t) :: String.t
def render(module) do
payload = create_payload(module)
payload <> luhn(module) <> xor(payload)
end
defp do_parse(code, lc) do
{start_code, code} = StartCode.new(code)
{data_element1, code} = DataElement.new(code)
{data_element2, code} = DataElement.new(code)
{data_element3, _} = DataElement.new(code)
%__MODULE__{
lc: lc,
start_code: start_code,
data_elements: [data_element1, data_element2, data_element3]
}
end
defp clean(code) when is_binary(code) do
code = code
|> String.replace(" ", "")
|> String.trim
case ~r/.*CHLGUC\d{4}(.*)CHLGTEXT.*/ |> Regex.run(code) do
nil -> code
matches -> "0" <> (matches |> Enum.at(1))
end
end
@spec create_payload(t) :: String.t
defp create_payload(%{start_code: %{control_bytes: control_bytes} = start_code, data_elements: data_elements}) do
payload = StartCode.render_length(start_code) <>
(control_bytes |> Enum.map(&to_hex/1) |> Enum.join) <>
StartCode.render_data(start_code)
append = for data_element <- data_elements,
length <- [DataElement.render_length(data_element, start_code.version)],
data <- [DataElement.render_data(data_element)]
do
length <> data
end
append = append |> Enum.join
payload = payload <> append
lc = payload |> String.length |> Kernel.+(2) |> div(2) |> to_hex(2)
lc <> payload
end
defp luhn(%{start_code: %{control_bytes: control_bytes} = start_code, data_elements: data_elements}) do
luhnsum = [
StartCode.render_data(start_code),
control_bytes |> Enum.map(&to_hex/1),
data_elements |> Enum.map(&DataElement.render_data/1)
]
|> Enum.join
|> String.reverse
|> luhn(16, 10)
10
|> Kernel.-(luhnsum)
|> rem(10)
|> to_hex(1)
end
end
| 25.717742 | 115 | 0.641894 |
080d0ca92bc72d22d3559cc7d020e9bd069298ad | 6,602 | ex | Elixir | clients/managed_identities/lib/google_api/managed_identities/v1/model/google_cloud_saasaccelerator_management_providers_v1_instance.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/managed_identities/lib/google_api/managed_identities/v1/model/google_cloud_saasaccelerator_management_providers_v1_instance.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/managed_identities/lib/google_api/managed_identities/v1/model/google_cloud_saasaccelerator_management_providers_v1_instance.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.ManagedIdentities.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1Instance do
@moduledoc """
## Attributes
* `consumerDefinedName` (*type:* `String.t`, *default:* `nil`) - consumer_defined_name is the name that is set by the consumer. On the other
hand Name field represents system-assigned id of an instance so consumers
are not necessarily aware of it.
consumer_defined_name is used for notification/UI purposes for consumer to
recognize their instances.
* `createTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. Timestamp when the resource was created.
* `labels` (*type:* `map()`, *default:* `nil`) - Optional. Resource labels to represent user provided metadata. Each label
is a key-value pair, where both the key and the value are arbitrary strings
provided by the user.
* `maintenancePolicyNames` (*type:* `map()`, *default:* `nil`) - The MaintenancePolicies that have been attached to the instance.
The key must be of the type name of the oneof policy name defined in
MaintenancePolicy, and the referenced policy must define the same policy
type. For complete details of MaintenancePolicy, please refer to
go/cloud-saas-mw-ug.
* `maintenanceSchedules` (*type:* `%{optional(String.t) => GoogleApi.ManagedIdentities.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule.t}`, *default:* `nil`) - The MaintenanceSchedule contains the scheduling information of published
maintenance schedule.
* `name` (*type:* `String.t`, *default:* `nil`) - Unique name of the resource. It uses the form:
`projects/{project_id}/locations/{location_id}/instances/{instance_id}`
* `producerMetadata` (*type:* `map()`, *default:* `nil`) - Output only. Custom string attributes used primarily to expose
producer-specific information in monitoring dashboards.
See go/get-instance-metadata.
* `provisionedResources` (*type:* `list(GoogleApi.ManagedIdentities.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource.t)`, *default:* `nil`) - Output only. The list of data plane resources provisioned for this
instance, e.g. compute VMs. See go/get-instance-metadata.
* `slmInstanceTemplate` (*type:* `String.t`, *default:* `nil`) - Link to the SLM instance template. Only populated when updating SLM
instances via SSA's Actuation service adaptor.
Service producers with custom control plane (e.g. Cloud SQL) doesn't
need to populate this field. Instead they should use software_versions.
* `sloMetadata` (*type:* `GoogleApi.ManagedIdentities.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata.t`, *default:* `nil`) - Output only. SLO metadata for instance classification in the
Standardized dataplane SLO platform.
See go/cloud-ssa-standard-slo for feature description.
* `softwareVersions` (*type:* `map()`, *default:* `nil`) - Software versions that are used to deploy this instance. This can be
mutated by rollout services.
* `state` (*type:* `String.t`, *default:* `nil`) - Output only. Current lifecycle state of the resource (e.g. if it's being
created or ready to use).
* `tenantProjectId` (*type:* `String.t`, *default:* `nil`) - Output only. ID of the associated GCP tenant project.
See go/get-instance-metadata.
* `updateTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. Timestamp when the resource was last modified.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:consumerDefinedName => String.t(),
:createTime => DateTime.t(),
:labels => map(),
:maintenancePolicyNames => map(),
:maintenanceSchedules => %{
optional(String.t()) =>
GoogleApi.ManagedIdentities.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule.t()
},
:name => String.t(),
:producerMetadata => map(),
:provisionedResources =>
list(
GoogleApi.ManagedIdentities.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource.t()
),
:slmInstanceTemplate => String.t(),
:sloMetadata =>
GoogleApi.ManagedIdentities.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata.t(),
:softwareVersions => map(),
:state => String.t(),
:tenantProjectId => String.t(),
:updateTime => DateTime.t()
}
field(:consumerDefinedName)
field(:createTime, as: DateTime)
field(:labels, type: :map)
field(:maintenancePolicyNames, type: :map)
field(:maintenanceSchedules,
as:
GoogleApi.ManagedIdentities.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule,
type: :map
)
field(:name)
field(:producerMetadata, type: :map)
field(:provisionedResources,
as:
GoogleApi.ManagedIdentities.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource,
type: :list
)
field(:slmInstanceTemplate)
field(:sloMetadata,
as:
GoogleApi.ManagedIdentities.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
)
field(:softwareVersions, type: :map)
field(:state)
field(:tenantProjectId)
field(:updateTime, as: DateTime)
end
defimpl Poison.Decoder,
for:
GoogleApi.ManagedIdentities.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1Instance do
def decode(value, options) do
GoogleApi.ManagedIdentities.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1Instance.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.ManagedIdentities.V1.Model.GoogleCloudSaasacceleratorManagementProvidersV1Instance do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 47.157143 | 264 | 0.71751 |
080d1332b784818ebea72b3913b9aad029fe6af3 | 367 | ex | Elixir | web/views/bar_view.ex | matthewphilyaw/basic_auth_test | 9bd6b62c8680ec603314adab940b8840e50b240c | [
"MIT"
] | null | null | null | web/views/bar_view.ex | matthewphilyaw/basic_auth_test | 9bd6b62c8680ec603314adab940b8840e50b240c | [
"MIT"
] | null | null | null | web/views/bar_view.ex | matthewphilyaw/basic_auth_test | 9bd6b62c8680ec603314adab940b8840e50b240c | [
"MIT"
] | null | null | null | defmodule FooApi.BarView do
use FooApi.Web, :view
def render("index.json", %{bars: bars}) do
%{data: render_many(bars, FooApi.BarView, "bar.json")}
end
def render("show.json", %{bar: bar}) do
%{data: render_one(bar, FooApi.BarView, "bar.json")}
end
def render("bar.json", %{bar: bar}) do
%{id: bar.id,
barnism: bar.barnism}
end
end
| 21.588235 | 58 | 0.623978 |
080d1c7f80a2f876c7eca140cb704a89d9f70f1d | 5,319 | exs | Elixir | test/stats_server_test.exs | bougueil/kitto | a2b5fb10e632e9ee05dce2644193fd35eaa1938e | [
"MIT"
] | 1,047 | 2016-05-11T16:09:29.000Z | 2022-03-29T17:17:26.000Z | test/stats_server_test.exs | bougueil/kitto | a2b5fb10e632e9ee05dce2644193fd35eaa1938e | [
"MIT"
] | 132 | 2016-10-28T19:44:26.000Z | 2020-12-06T21:16:53.000Z | test/stats_server_test.exs | bougueil/kitto | a2b5fb10e632e9ee05dce2644193fd35eaa1938e | [
"MIT"
] | 70 | 2016-10-26T00:11:05.000Z | 2022-01-02T21:43:06.000Z | defmodule Kitto.StatsServerTest do
use ExUnit.Case
alias Kitto.StatsServer
defmodule BackoffMock do
@behaviour Kitto.Backoff
def succeed(_), do: {:ok, :success}
def fail(_), do: {:ok, :fail}
def backoff!(_), do: send self(), {:ok, :backoff}
end
setup do
Application.put_env :kitto, :backoff_module, Kitto.StatsServerTest.BackoffMock
definition = %{file: "jobs/dummy.exs", line: 1}
job = %{name: :dummy_job, options: %{}, definition: definition, job: fn -> :ok end}
{:ok, server} = StatsServer.start_link(name: :stats_server)
on_exit fn ->
Application.delete_env :kitto, :backoff_module
Application.delete_env :kitto, :job_backoff_enabled?
server |> Process.exit(:normal)
end
%{
successful_job: job,
failing_job: %{job | job: fn -> raise RuntimeError end},
server: server
}
end
test "#measure initializes the job stats", %{successful_job: job, server: server} do
server |> StatsServer.measure(job)
assert StatsServer.stats(server).dummy_job.times_completed == 1
end
test "#measure when a job succeeds increments :times_triggered",
%{successful_job: job, server: server} do
server |> StatsServer.measure(job)
server |> StatsServer.measure(job)
assert StatsServer.stats(server).dummy_job.times_triggered == 2
end
test "#measure when a job fails increments :times_triggered", context do
context.server |> StatsServer.measure(context.successful_job)
assert_raise Kitto.Job.Error, fn ->
context.server |> StatsServer.measure(context.failing_job)
end
assert StatsServer.stats(context.server).dummy_job.times_triggered == 2
end
test "#measure when a job succeeds increments :times_completed",
%{successful_job: job, server: server} do
server |> StatsServer.measure(job)
server |> StatsServer.measure(job)
assert StatsServer.stats(server).dummy_job.times_completed == 2
end
test "#measure when a job fails does not increment :times_completed", context do
context.server |> StatsServer.measure(context.successful_job)
assert_raise Kitto.Job.Error, fn ->
context.server |> StatsServer.measure(context.failing_job)
end
assert StatsServer.stats(context.server).dummy_job.times_completed == 1
end
test "#measure when a job succeeds increments :total_running_time", context do
context.server |> StatsServer.measure(context.successful_job)
running_time = StatsServer.stats(context.server).dummy_job.total_running_time
context.server |> StatsServer.measure(context.successful_job)
assert StatsServer.stats(context.server).dummy_job.total_running_time >= running_time
end
test "#measure when a job fails does not increment :total_running_time", context do
context.server |> StatsServer.measure(context.successful_job)
expected_running_time = StatsServer.stats(context.server).dummy_job.total_running_time
assert_raise Kitto.Job.Error, fn ->
context.server |> StatsServer.measure(context.failing_job)
end
actual_running_time = StatsServer.stats(context.server).dummy_job.total_running_time
assert_in_delta actual_running_time, expected_running_time, 0.1
end
test "#measure when a job fails, message contains job definition location", context do
job = context.failing_job
assert_raise Kitto.Job.Error, ~r/Defined in: #{job.definition.file}/, fn ->
context.server |> StatsServer.measure(job)
end
end
test "#measure when a job fails, message contains job name", context do
job = context.failing_job
assert_raise Kitto.Job.Error, ~r/Job :#{job.name} failed to run/, fn ->
context.server |> StatsServer.measure(job)
end
end
test "#measure when a job fails, message contains the original error", context do
job = context.failing_job
error = Exception.format_banner(:error, %RuntimeError{}) |> Regex.escape
assert_raise Kitto.Job.Error,
~r/Error: #{error}/,
fn -> context.server |> StatsServer.measure(job) end
end
test "#measure when a job fails, message contains the stacktrace", context do
job = context.failing_job
assert_raise Kitto.Job.Error,
~r/Stacktrace: .*? anonymous fn/,
fn -> context.server |> StatsServer.measure(job) end
end
describe "when :job_backoff_enabled? is set to false" do
setup [:disable_job_backoff]
test "#measure does not apply backoffs", context do
context.server |> StatsServer.measure(context.successful_job)
refute_received {:ok, :backoff}
end
end
describe "when :job_backoff_enabled? is set to true" do
setup [:enable_job_backoff]
test "#measure applies backoffs", context do
context.server |> StatsServer.measure(context.successful_job)
assert_received {:ok, :backoff}
end
end
describe "when :job_backoff_enabled? is not set" do
test "#measure applies backoffs", context do
context.server |> StatsServer.measure(context.successful_job)
assert_received {:ok, :backoff}
end
end
defp disable_job_backoff(_context) do
Application.put_env :kitto, :job_backoff_enabled?, false
end
defp enable_job_backoff(_context) do
Application.put_env :kitto, :job_backoff_enabled?, true
end
end
| 31.850299 | 90 | 0.710284 |
080d5d16ca88bd0a009e7ca2e9c2d7362c7b37b2 | 2,537 | exs | Elixir | test/openskill/bradley_terry_full_test.exs | philihp/openskill.ex | 18197c8b3c4237360e34a4aff70d455b9160f4e0 | [
"MIT"
] | 5 | 2020-07-22T12:44:05.000Z | 2022-03-02T01:46:03.000Z | test/openskill/bradley_terry_full_test.exs | philihp/openskill | 18197c8b3c4237360e34a4aff70d455b9160f4e0 | [
"MIT"
] | 2 | 2021-02-14T13:19:27.000Z | 2022-01-12T18:21:12.000Z | test/openskill/bradley_terry_full_test.exs | philihp/openskill.ex | 18197c8b3c4237360e34a4aff70d455b9160f4e0 | [
"MIT"
] | null | null | null | defmodule Openskill.BradleyTerryFullTest do
use ExUnit.Case
alias Openskill.BradleyTerryFull
@r Openskill.rating()
@team1 [@r]
@team2 [@r, @r]
@team3 [@r, @r, @r]
describe "#rate" do
test "solo game does not change rating" do
assert [@team1] == BradleyTerryFull.rate([@team1])
end
test "2p FFA" do
assert [
[{27.63523138347365, 8.065506316323548}],
[{22.36476861652635, 8.065506316323548}]
] == BradleyTerryFull.rate([@team1, @team1])
end
test "3p FFA" do
assert [
[{30.2704627669473, 7.788474807872566}],
[{25.0, 7.788474807872566}],
[{19.7295372330527, 7.788474807872566}]
] == BradleyTerryFull.rate([@team1, @team1, @team1])
end
test "4p FFA" do
assert [
[{32.90569415042095, 7.5012190693964005}],
[{27.63523138347365, 7.5012190693964005}],
[{22.36476861652635, 7.5012190693964005}],
[{17.09430584957905, 7.5012190693964005}]
] == BradleyTerryFull.rate([@team1, @team1, @team1, @team1])
end
test "5p FFA" do
assert [
[{35.5409255338946, 7.202515895247076}],
[{30.2704627669473, 7.202515895247076}],
[{25.0, 7.202515895247076}],
[{19.729537233052703, 7.202515895247076}],
[{14.4590744661054, 7.202515895247076}]
] == BradleyTerryFull.rate([@team1, @team1, @team1, @team1, @team1])
end
test "3 teams different sized players" do
assert [
[
{25.992743915179297, 8.19709997489984},
{25.992743915179297, 8.19709997489984},
{25.992743915179297, 8.19709997489984}
],
[{28.48909130001799, 8.220848339985736}],
[
{20.518164784802718, 8.127515465304823},
{20.518164784802718, 8.127515465304823}
]
] == BradleyTerryFull.rate([@team3, @team1, @team2])
end
test "1v1 win and then loss decreases mu" do
alice1 = @r
betty1 = @r
[[alice2], [betty2]] = BradleyTerryFull.rate([[alice1], [betty1]])
[[alice3], [betty3]] = BradleyTerryFull.rate([[betty2], [alice2]])
assert [
{25.4111001737357, 7.82210295723689},
{24.5888998262643, 7.82210295723689}
] == [
alice3,
betty3
]
end
end
end
| 31.7125 | 81 | 0.532913 |
080d6a5f8e43000a770c05eb58cd0cd2f9ada65f | 507 | exs | Elixir | mix.exs | zyzmoz/XCep_elixir | 665d008e96c174eec37a9cfc7b69024e011d1785 | [
"MIT"
] | null | null | null | mix.exs | zyzmoz/XCep_elixir | 665d008e96c174eec37a9cfc7b69024e011d1785 | [
"MIT"
] | null | null | null | mix.exs | zyzmoz/XCep_elixir | 665d008e96c174eec37a9cfc7b69024e011d1785 | [
"MIT"
] | null | null | null | defmodule Xcep.MixProject do
use Mix.Project
def project do
[
app: :xcep,
version: "0.1.0",
elixir: "~> 1.11",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger, :httpoison]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:httpoison, "~> 1.6"},
{:poison, "~> 3.1"}
]
end
end
| 17.482759 | 59 | 0.554241 |
080d75419760cc6aa99898f83dadf1a71fc66e1d | 81 | exs | Elixir | test/test_helper.exs | elitau/page_change_notifier | 55c02ef0a464040d98cf416c131e39e7a09df975 | [
"MIT"
] | null | null | null | test/test_helper.exs | elitau/page_change_notifier | 55c02ef0a464040d98cf416c131e39e7a09df975 | [
"MIT"
] | null | null | null | test/test_helper.exs | elitau/page_change_notifier | 55c02ef0a464040d98cf416c131e39e7a09df975 | [
"MIT"
] | null | null | null | ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(PageChangeNotifier.Repo, :manual)
| 20.25 | 64 | 0.802469 |
080dd30d044088a1453cbb5085a7076106adfed1 | 235 | ex | Elixir | lib/hologram/compiler/call_graph_builder/elixir_list.ex | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 40 | 2022-01-19T20:27:36.000Z | 2022-03-31T18:17:41.000Z | lib/hologram/compiler/call_graph_builder/elixir_list.ex | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 42 | 2022-02-03T22:52:43.000Z | 2022-03-26T20:57:32.000Z | lib/hologram/compiler/call_graph_builder/elixir_list.ex | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 3 | 2022-02-10T04:00:37.000Z | 2022-03-08T22:07:45.000Z | alias Hologram.Compiler.CallGraphBuilder
defimpl CallGraphBuilder, for: List do
def build(list, module_defs, templates, from_vertex) do
Enum.each(list, &CallGraphBuilder.build(&1, module_defs, templates, from_vertex))
end
end
| 29.375 | 85 | 0.787234 |
080de49b3ccdfd5b27bea6a0bc268d92a345d2f2 | 479 | ex | Elixir | server/lib/domsegserver_web/controllers/fallback_controller.ex | arpieb/domseg | 0c7165d69181e59902730c6e7ac41e8e849edd70 | [
"Apache-2.0"
] | null | null | null | server/lib/domsegserver_web/controllers/fallback_controller.ex | arpieb/domseg | 0c7165d69181e59902730c6e7ac41e8e849edd70 | [
"Apache-2.0"
] | 9 | 2021-12-09T18:19:21.000Z | 2022-01-09T03:45:33.000Z | server/lib/domsegserver_web/controllers/fallback_controller.ex | arpieb/domseg | 0c7165d69181e59902730c6e7ac41e8e849edd70 | [
"Apache-2.0"
] | null | null | null | defmodule DOMSegServerWeb.FallbackController do
@moduledoc """
Translates controller action results into valid `Plug.Conn` responses.
See `Phoenix.Controller.action_fallback/1` for more details.
"""
use DOMSegServerWeb, :controller
# This clause is an example of how to handle resources that cannot be found.
def call(conn, {:error, :not_found}) do
conn
|> put_status(:not_found)
|> put_view(DOMSegServerWeb.ErrorView)
|> render(:"404")
end
end
| 28.176471 | 78 | 0.724426 |
080e111fd7e3893b6949b2b941f8d9ea5a89a1bc | 1,606 | ex | Elixir | lib/talar_web.ex | hidnasio/talar | bb898a4e2654f2fec6f3cc367ab1576d10d3d435 | [
"MIT"
] | null | null | null | lib/talar_web.ex | hidnasio/talar | bb898a4e2654f2fec6f3cc367ab1576d10d3d435 | [
"MIT"
] | null | null | null | lib/talar_web.ex | hidnasio/talar | bb898a4e2654f2fec6f3cc367ab1576d10d3d435 | [
"MIT"
] | null | null | null | defmodule TalarWeb 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 TalarWeb, :controller
use TalarWeb, :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: TalarWeb
import Plug.Conn
import TalarWeb.Gettext
alias TalarWeb.Router.Helpers, as: Routes
end
end
def view do
quote do
use Phoenix.View,
root: "lib/talar_web/templates",
namespace: TalarWeb
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_flash: 1, get_flash: 2, view_module: 1]
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
import TalarWeb.ErrorHelpers
import TalarWeb.Gettext
alias TalarWeb.Router.Helpers, as: Routes
end
end
def router do
quote do
use Phoenix.Router
import Plug.Conn
import Phoenix.Controller
end
end
def channel do
quote do
use Phoenix.Channel
import TalarWeb.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
| 22.942857 | 83 | 0.684309 |
080e1858697952f5bd78a0651d3040939df83962 | 176 | ex | Elixir | lib/aoc2019_day5.ex | hvnsweeting/adventofcode2018 | 8e5a85ebb7b102361b844b0f92522c18148a672a | [
"BSD-3-Clause"
] | 1 | 2022-01-10T02:34:18.000Z | 2022-01-10T02:34:18.000Z | lib/aoc2019_day5.ex | hvnsweeting/adventofcode2018 | 8e5a85ebb7b102361b844b0f92522c18148a672a | [
"BSD-3-Clause"
] | null | null | null | lib/aoc2019_day5.ex | hvnsweeting/adventofcode2018 | 8e5a85ebb7b102361b844b0f92522c18148a672a | [
"BSD-3-Clause"
] | 1 | 2019-12-02T09:42:17.000Z | 2019-12-02T09:42:17.000Z | defmodule Aoc2019Day5 do
import Intcode
def solve_part_1(text) do
text |> check_output([1])
end
def solve_part_2(text) do
text |> check_output([5])
end
end
| 14.666667 | 29 | 0.681818 |
080e673bd16941da35e47e3b899c0dc552d23895 | 305 | ex | Elixir | lib/ccsp/main.ex | sbauer322/ccsp | 8ea6c26457e110c5f84cbc813b3f065c6161e6e6 | [
"Apache-2.0"
] | 7 | 2019-11-04T14:23:52.000Z | 2021-12-31T08:24:33.000Z | lib/ccsp/main.ex | sbauer322/ccsp | 8ea6c26457e110c5f84cbc813b3f065c6161e6e6 | [
"Apache-2.0"
] | 23 | 2019-10-02T02:13:36.000Z | 2019-12-03T03:52:37.000Z | lib/ccsp/main.ex | sbauer322/ccsp | 8ea6c26457e110c5f84cbc813b3f065c6161e6e6 | [
"Apache-2.0"
] | null | null | null | defmodule Main do
alias CCSP.Chapter1.Start, as: Start1
alias CCSP.Chapter2.Start, as: Start2
alias CCSP.Chapter3.Start, as: Start3
@moduledoc """
Convenience module to for quickly setting up and running more elaborate sections.
"""
def run() do
Start3.run_send_more_money()
end
end
| 21.785714 | 83 | 0.727869 |
080e6e9564d164405f2821906f6025c2b1c256fc | 1,160 | ex | Elixir | web/channels/user_socket.ex | kensupermen/javex | f7774e83f64980f3c1eb4b5701f46d835edd76da | [
"MIT"
] | null | null | null | web/channels/user_socket.ex | kensupermen/javex | f7774e83f64980f3c1eb4b5701f46d835edd76da | [
"MIT"
] | null | null | null | web/channels/user_socket.ex | kensupermen/javex | f7774e83f64980f3c1eb4b5701f46d835edd76da | [
"MIT"
] | null | null | null | defmodule Javex.UserSocket do
use Phoenix.Socket
## Channels
# channel "room:*", Javex.RoomChannel
## Transports
transport :websocket, Phoenix.Transports.WebSocket
# transport :longpoll, Phoenix.Transports.LongPoll
# Socket params are passed from the client and can
# be used to verify and authenticate a user. After
# verification, you can put default assigns into
# the socket that will be set for all channels, ie
#
# {:ok, assign(socket, :user_id, verified_user_id)}
#
# To deny connection, return `:error`.
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
def connect(_params, socket) do
{:ok, socket}
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "users_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# Javex.Endpoint.broadcast("users_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
def id(_socket), do: nil
end
| 30.526316 | 83 | 0.7 |
080e708c889250fe126f01aebee87f208b172efb | 18,755 | ex | Elixir | projects/api/lib/margaret/publications/publications.ex | strattadb/margaret | dde5d7b42f6d9b4d320069a0117136dae03b13b5 | [
"MIT"
] | 82 | 2017-11-06T01:00:55.000Z | 2020-12-09T10:35:29.000Z | projects/api/lib/margaret/publications/publications.ex | dbstratta/margaret | dde5d7b42f6d9b4d320069a0117136dae03b13b5 | [
"MIT"
] | 98 | 2017-11-06T22:57:32.000Z | 2020-07-03T04:46:39.000Z | projects/api/lib/margaret/publications/publications.ex | strattadb/margaret | dde5d7b42f6d9b4d320069a0117136dae03b13b5 | [
"MIT"
] | 10 | 2017-11-16T05:31:58.000Z | 2020-10-29T18:02:35.000Z | defmodule Margaret.Publications do
@moduledoc """
The Publications context.
"""
import Ecto.Query
alias Ecto.Multi
alias Margaret.{
Repo,
Accounts,
Stories,
Publications,
Follows,
Tags,
Helpers
}
alias Publications.{Publication, PublicationMembership, PublicationInvitation}
alias Accounts.User
@typedoc """
The role of a member in a publication.
"""
@type role :: atom()
@doc """
Gets a publication by its id.
## Examples
iex> get_publication(123)
%Publication{}
iex> get_publication(456)
nil
"""
@spec get_publication(String.t() | non_neg_integer()) :: Publication.t() | nil
def get_publication(id), do: Repo.get(Publication, id)
@doc """
Gets a publication by its name.
## Examples
iex> get_publication_by_name("publication123")
%Publication{}
iex> get_publication_by_name("publication456")
nil
"""
@spec get_publication_by_name(String.t()) :: Publication.t() | nil
def get_publication_by_name(name), do: get_publication_by(name: name)
@doc """
Gets a publication by given clauses.
"""
@spec get_publication_by(Keyword.t()) :: Publication.t() | nil
def get_publication_by(clauses), do: Repo.get_by(Publication, clauses)
@doc """
"""
@spec tags(Publication.t()) :: [Tag.t()]
def tags(%Publication{} = publication) do
publication
|> Publication.preload_tags()
|> Map.fetch!(:tags)
end
@doc """
Gets the role of a member of a publication.
Returns `nil` if the user is not a member.
## Examples
iex> member_role(%Publication{}, %User{})
:owner
iex> member_role(%Publication{}, %User{})
nil
"""
@spec member_role(Publication.t(), User.t()) :: role() | nil
def member_role(%Publication{id: publication_id}, %User{id: user_id}) do
case get_membership(publication_id: publication_id, member_id: user_id) do
%PublicationMembership{role: role} -> role
nil -> nil
end
end
@doc """
"""
def members(%Publication{} = publication, args \\ %{}) do
args
|> Map.put(:publication, publication)
|> Accounts.users()
end
@doc """
Returns the member count of the publication.
## Examples
iex> member_count(%Publication{})
3
"""
@spec member_count(Publication.t()) :: non_neg_integer()
def member_count(%Publication{} = publication, args \\ %{}) do
args
|> Map.put(:publication, publication)
|> Accounts.user_count()
end
@doc """
Returns a story connection of the publication.
## Examples
iex> stories(%Publication{})
{:ok, %{}}
iex> stories(%Publication{}, args)
{:ok, %{}}
"""
@spec stories(Publication.t(), map()) :: any()
def stories(%Publication{} = publication, args \\ %{}) do
args
|> Map.put(:publication, publication)
|> Stories.stories()
end
@doc """
Returns the story count of the publication.
## Examples
iex> story_count(%Publication{})
42
iex> story_count(%Publication{}, args)
10
"""
@spec story_count(Publication.t(), map()) :: non_neg_integer()
def story_count(%Publication{} = publication, args \\ %{}) do
args
|> Map.put(:publication, publication)
|> Stories.story_count()
end
@spec followers(Publication.t(), map()) :: any()
def followers(%Publication{} = publication, args \\ %{}) do
args
|> Map.put(:publication, publication)
|> Follows.followers()
end
@doc """
Gets the follower count of a publication.
"""
@spec follower_count(Publication.t(), map()) :: non_neg_integer()
def follower_count(%Publication{} = publication, args \\ %{}) do
args
|> Map.put(:publication, publication)
|> Follows.follower_count()
end
@doc """
Checks that the user's role in the publication
is in the list of permitted roles.
## Examples
iex> check_role(%Publication{}, %User{}, [:admin, :editor])
true
iex> check_role(%Publication{}, %User{}, :writer)
false
"""
@spec check_role(Publication.t(), User.t(), [role(), ...] | role()) :: boolean()
def check_role(publication, user, permitted_roles) when is_list(permitted_roles) do
member_role(publication, user) in permitted_roles
end
def check_role(publication, user, permitted_role),
do: check_role(publication, user, [permitted_role])
@doc """
Returns true if the user is a member
of the publication. False otherwise.
## Examples
iex> member?(%Publication{}, %User{})
true
iex> member?(%Publication{}, %User{})
false
"""
@spec member?(Publication.t(), User.t()) :: boolean()
def member?(publication, user), do: !!member_role(publication, user)
@doc """
Returns true if the user is a editor
of the publication. False otherwise.
## Examples
iex> editor?(%Publication{}, %User{})
true
iex> editor?(%Publication{}, %User{})
false
"""
@spec editor?(Publication.t(), User.t()) :: boolean()
def editor?(publication, user), do: check_role(publication, user, :editor)
@doc """
Returns true if the user is a writer
of the publication. False otherwise.
## Examples
iex> writer?(%Publication{}, %User{})
true
iex> writer?(%Publication{}, %User{})
false
"""
@spec writer?(Publication.t(), User.t()) :: boolean()
def writer?(publication, user), do: check_role(publication, user, :writer)
@doc """
Returns true if the user is an admin
of the publication. False otherwise.
## Examples
iex> admin?(%Publication{}, %User{})
true
iex> admin?(%Publication{}, %User{})
false
"""
@spec admin?(Publication.t(), User.t()) :: boolean()
def admin?(publication, user), do: check_role(publication, user, :admin)
@doc """
Returns true if the user is the owner
of the publication. False otherwise.
## Examples
iex> owner?(%Publication{}, %User{})
true
iex> owner?(%Publication{}, %User{})
false
"""
@spec owner?(Publication.t(), User.t()) :: boolean()
def owner?(publication, user), do: check_role(publication, user, :owner)
@doc """
Returns true if the user can write stories for the publication.
False otherwise.
## Examples
iex> can_write_stories?(%Publication{}, %User{})
true
iex> can_write_stories?(%Publication{}, %User{})
false
"""
@spec can_write_stories?(Publication.t(), User.t()) :: boolean()
def can_write_stories?(publication, user) do
roles = ~w(owner admin editor writer)a
check_role(publication, user, roles)
end
@doc """
Returns true if the user can publish stories for the publication.
False otherwise.
## Examples
iex> can_publish_stories?(%Publication{}, %User{})
true
iex> can_publish_stories?(%Publication{}, %User{})
false
"""
@spec can_publish_stories?(Publication.t(), User.t()) :: boolean()
def can_publish_stories?(publication, user) do
roles = ~w(owner admin editor)a
check_role(publication, user, roles)
end
@doc """
Returns true if the user can edit stories for the publication.
False otherwise.
## Examples
iex> can_edit_stories?(%Publication{}, %User{})
true
iex> can_edit_stories?(%Publication{}, %User{})
false
"""
@spec can_edit_stories?(Publication.t(), User.t()) :: boolean()
def can_edit_stories?(publication, user) do
roles = ~w(owner admin editor)a
check_role(publication, user, roles)
end
@doc """
Returns true if the user can see the invitations sent by the publication.
False otherwise.
## Examples
iex> can_see_invitations?(%Publication{}, %User{})
true
iex> can_see_invitations?(%Publication{}, %User{})
false
"""
@spec can_see_invitations?(Publication.t(), User.t()) :: boolean()
def can_see_invitations?(publication, user) do
roles = ~w(owner admin)a
check_role(publication, user, roles)
end
@doc """
Returns true if the user can invite a
user with a role to the publication.
False otherwise.
## Examples
iex> can_invite?(publication, inviter, invitee, :writer)
true
iex> can_invite?(publication, inviter, invitee, :owner)
false
"""
@spec can_invite?(Publication.t(), User.t(), User.t(), role()) :: boolean()
def can_invite?(publication, inviter, invitee, role) when role in [:writer, :editor] do
roles = ~w(owner admin)a
publication
|> check_role(inviter, roles)
|> do_can_invite?(publication, invitee)
end
def can_invite?(publication, inviter, invitee, role) when role === :admin do
publication
|> check_role(inviter, :owner)
|> do_can_invite?(publication, invitee)
end
def can_invite?(_publication, _inviter, _invitee, _role), do: false
@spec do_can_invite?(boolean(), Publication.t(), User.t()) :: boolean()
defp do_can_invite?(true, publication, invitee), do: not member?(publication, invitee)
defp do_can_invite?(false, _publication, _invitee), do: false
@doc """
Returns true if the user can update the publication information.
False otherwise.
## Examples
iex> can_update_publication?(%Publication{}, %User{})
true
iex> can_update_publication?(%Publication{}, %User{})
false
"""
@spec can_update_publication?(Publication.t(), User.t()) :: boolean()
def can_update_publication?(publication, user) do
roles = ~w(owner admin)a
check_role(publication, user, roles)
end
@doc """
"""
@spec can_kick?(Publication.t(), User.t(), User.t()) :: boolean()
def can_kick?(publication, kicker, user) do
case member_role(publication, user) do
nil -> false
:owner -> false
:admin -> check_role(publication, kicker, ~w(owner)a)
_role -> check_role(publication, kicker, ~w(owner admin)a)
end
end
@doc """
Returns `true` if the user can accept the invitation.
`false` otherwise.
"""
@spec can_accept_invitation?(PublicationInvitation.t(), User.t()) :: boolean()
def can_accept_invitation?(%PublicationInvitation{invitee_id: invitee_id}, %User{id: invitee_id}),
do: true
def can_accept_invitation?(_invitation, _user), do: false
@doc """
Returns `true` if the user can reject the invitation.
`false` otherwise.
"""
@spec can_reject_invitation?(PublicationInvitation.t(), User.t()) :: boolean()
def can_reject_invitation?(%PublicationInvitation{invitee_id: invitee_id}, %User{id: invitee_id}),
do: true
def can_reject_invitation?(_invitation, _user), do: false
@doc """
"""
@spec publications(map()) :: any()
def publications(args) do
args
|> Publications.Queries.publications()
|> Helpers.Connection.from_query(args)
end
@doc """
Returns the publication count.
## Examples
iex> publication_count(args)
8
"""
@spec publication_count(map()) :: non_neg_integer()
def publication_count(args \\ %{}) do
args
|> Publications.Queries.publications()
|> Repo.count()
end
@doc """
Inserts a publication.
"""
@spec insert_publication(map()) :: {:ok, map()} | {:error, atom(), any(), map()}
def insert_publication(attrs) do
Multi.new()
|> maybe_insert_tags(attrs)
|> insert_publication(attrs)
|> insert_owner(attrs)
|> Repo.transaction()
end
@spec insert_publication(Multi.t(), map()) :: Multi.t()
defp insert_publication(multi, attrs) do
insert_publication_fn = fn changes ->
maybe_put_tags = fn attrs ->
case changes do
%{tags: tags} -> Map.put(attrs, :tags, tags)
_ -> attrs
end
end
attrs
|> maybe_put_tags.()
|> Publication.changeset()
|> Repo.insert()
end
Multi.run(multi, :publication, insert_publication_fn)
end
@doc """
Updates a publication.
"""
@spec update_publication(Publication.t(), map()) ::
{:ok, map()} | {:error, atom(), any(), map()}
def update_publication(%Publication{} = publication, attrs) do
Multi.new()
|> maybe_insert_tags(attrs)
|> update_publication(publication, attrs)
|> Repo.transaction()
end
@spec update_publication(Multi.t(), Publication.t(), map()) :: Multi.t()
defp update_publication(multi, %Publication{} = publication, attrs) do
update_publication_fn = fn changes ->
maybe_put_tags = fn {publication, attrs} ->
case changes do
%{tags: tags} -> {Publication.preload_tags(publication), Map.put(attrs, :tags, tags)}
_ -> {publication, attrs}
end
end
{publication, attrs} = maybe_put_tags.({publication, attrs})
publication
|> Publication.update_changeset(attrs)
|> Repo.update()
end
Multi.run(multi, :publication, update_publication_fn)
end
@spec maybe_insert_tags(Multi.t(), map()) :: Multi.t()
defp maybe_insert_tags(multi, %{tags: tags}) do
insert_tags_fn = fn _ -> {:ok, Tags.insert_and_get_all_tags(tags)} end
Multi.run(multi, :tags, insert_tags_fn)
end
defp maybe_insert_tags(multi, _attrs), do: multi
@spec insert_owner(Multi.t(), map()) :: Multi.t()
defp insert_owner(multi, %{owner_id: owner_id}) do
insert_owner_fn = fn %{publication: %{id: publication_id}} ->
insert_membership(%{
role: :owner,
member_id: owner_id,
publication_id: publication_id
})
end
Multi.run(multi, :owner, insert_owner_fn)
end
@doc """
Inserts a publication membership.
"""
@spec insert_membership(map()) ::
{:ok, PublicationMembership.t()} | {:error, Ecto.Changeset.t()}
def insert_membership(attrs) do
attrs
|> PublicationMembership.changeset()
|> Repo.insert()
end
@doc """
Gets a publication membership.
"""
@spec get_membership(String.t() | non_neg_integer()) :: PublicationMembership.t() | nil
def get_membership(id) when not is_list(id), do: Repo.get(PublicationMembership, id)
@spec get_membership(Keyword.t()) :: PublicationMembership.t() | nil
def get_membership(clauses) when length(clauses) == 2,
do: Repo.get_by(PublicationMembership, clauses)
@doc """
Gets the owner of the publication.
"""
@spec owner(Publication.t()) :: User.t()
def owner(%Publication{} = publication) do
query =
User
|> join(:inner, [u], pm in assoc(u, :publication_memberships))
|> PublicationMembership.by_publication(publication)
|> PublicationMembership.owner()
Repo.one!(query)
end
@doc """
Deletes a publication membership.
"""
@spec delete_membership(PublicationMembership.t()) ::
{:ok, PublicationMembership.t()} | {:error, Ecto.Changeset.t()}
def delete_membership(%PublicationMembership{} = publication_membership),
do: Repo.delete(publication_membership)
@doc """
Gets a publication invitation.
## Examples
iex> get_invitation(123)
%PublicationInvitation{}
iex> get_invitation(456)
nil
"""
def get_invitation(id), do: Repo.get(PublicationInvitation, id)
@doc """
Inserts a publication invitation.
"""
@spec insert_invitation(map()) ::
{:ok, PublicationInvitation.t()} | {:error, Ecto.Changeset.t()}
def insert_invitation(attrs) do
attrs
|> PublicationInvitation.changeset()
|> Repo.insert()
end
@doc """
Updates a publication invitation.
"""
@spec update_invitation(PublicationInvitation.t(), map()) ::
{:ok, PublicationInvitation.t()} | {:error, Ecto.Changeset.t()}
def update_invitation(%PublicationInvitation{} = invitation, attrs) do
invitation
|> PublicationInvitation.update_changeset(attrs)
|> Repo.update()
end
@doc """
Updates a publication invitation.
"""
@spec update_invitation!(PublicationInvitation.t(), map()) ::
PublicationInvitation.t() | no_return()
def update_invitation!(%PublicationInvitation{} = invitation, attrs) do
case update_invitation(invitation, attrs) do
{:ok, invitation} ->
invitation
{:error, reason} ->
raise """
cannot update invitation.
Reason: #{inspect(reason)}
"""
end
end
@doc """
Accepts a publication invitation.
Rejects all other invitations to the invitee.
"""
@spec accept_invitation(PublicationInvitation.t()) ::
{:ok, map()} | {:error, atom(), any(), map()}
def accept_invitation(%PublicationInvitation{} = invitation) do
invitation_changeset =
PublicationInvitation.update_changeset(invitation, %{status: :accepted})
reject_others_invitations =
from i in PublicationInvitation,
where: i.invitee_id == ^invitation.invitee_id and i.id != ^invitation.id,
where: i.status == ^:pending,
update: [set: [status: ^:rejected]]
membership_attrs = %{
role: invitation.role,
publication_id: invitation.publication_id,
member_id: invitation.invitee_id
}
membership_changeset = PublicationMembership.changeset(membership_attrs)
Multi.new()
|> Multi.update(:invitation, invitation_changeset)
|> Multi.update_all(:reject_other_invitations, reject_others_invitations, [])
|> Multi.insert(:membership, membership_changeset)
|> Repo.transaction()
end
@doc """
Rejects a publcation invitation.
"""
@spec reject_invitation(PublicationInvitation.t()) ::
{:ok, PublicationInvitation.t()} | {:error, Ecto.Changeset.t()}
def reject_invitation(invitation), do: update_invitation(invitation, %{status: :rejected})
@doc """
Rejects a publcation invitation.
"""
@spec reject_invitation!(PublicationInvitation.t()) :: PublicationInvitation.t() | no_return()
def reject_invitation!(invitation) do
case reject_invitation(invitation) do
{:ok, invitation} ->
invitation
{:error, reason} ->
raise """
cannot reject invitation.
Reason: #{inspect(reason)}
"""
end
end
@doc """
Invites a user to a publication.
"""
@spec invite_user(Publication.t(), User.t(), User.t(), role()) ::
{:ok, PublicationInvitation.t()} | {:error, Ecto.Changeset.t()}
def invite_user(publication, inviter, invitee, role) do
attrs = %{
publication_id: publication.id,
inviter_id: inviter.id,
invitee_id: invitee.id,
role: role,
status: :pending
}
insert_invitation(attrs)
end
@doc """
Kicks a member out of a publication.
"""
def kick_member(%Publication{id: publication_id}, %User{id: user_id}) do
[publication_id: publication_id, member_id: user_id]
|> get_membership()
|> case do
%PublicationMembership{} = membership -> delete_membership(membership)
nil -> {:error, "User is not a member of the publication"}
end
end
end
| 25.621585 | 100 | 0.645108 |
080e7f68b0623ac9c5972d197931b009736a0ae4 | 6,462 | ex | Elixir | lib/credo/code/module.ex | codeclimate-community/credo | b960a25d604b4499a2577321f9d61b39dc4b0437 | [
"MIT"
] | null | null | null | lib/credo/code/module.ex | codeclimate-community/credo | b960a25d604b4499a2577321f9d61b39dc4b0437 | [
"MIT"
] | null | null | null | lib/credo/code/module.ex | codeclimate-community/credo | b960a25d604b4499a2577321f9d61b39dc4b0437 | [
"MIT"
] | null | null | null | defmodule Credo.Code.Module do
@moduledoc """
This module provides helper functions to analyse modules, return the defined
funcions or module attributes.
"""
alias Credo.Code
alias Credo.Code.Block
alias Credo.Code.Name
@def_ops [:def, :defp, :defmacro]
@doc "Returns the list of aliases defined in a given module source code."
def aliases({:defmodule, _, _arguments} = ast) do
ast
|> Credo.Code.postwalk(&find_aliases/2)
|> Enum.uniq()
end
defp find_aliases({:alias, _, [{:__aliases__, _, mod_list}]} = ast, aliases) do
module_names =
mod_list
|> Name.full()
|> List.wrap()
{ast, aliases ++ module_names}
end
# Multi alias
defp find_aliases(
{:alias, _,
[
{{:., _, [{:__aliases__, _, mod_list}, :{}]}, _, multi_mod_list}
]} = ast,
aliases
) do
module_names =
Enum.map(multi_mod_list, fn tuple ->
Name.full([Name.full(mod_list), Name.full(tuple)])
end)
{ast, aliases ++ module_names}
end
defp find_aliases(ast, aliases) do
{ast, aliases}
end
@doc "Reads an attribute from a module's `ast`"
def attribute(ast, attr_name) do
case Code.postwalk(ast, &find_attribute(&1, &2, attr_name), {:error, nil}) do
{:ok, value} ->
value
error ->
error
end
end
defp find_attribute({:@, _meta, arguments} = ast, tuple, attribute_name) do
case List.first(arguments) do
{^attribute_name, _meta, [value]} ->
{:ok, value}
_ ->
{ast, tuple}
end
end
defp find_attribute(ast, tuple, _name) do
{ast, tuple}
end
@doc "Returns the function/macro count for the given module's AST"
def def_count(nil), do: 0
def def_count({:defmodule, _, _arguments} = ast) do
ast
|> Code.postwalk(&collect_defs/2)
|> Enum.count()
end
def defs(nil), do: []
def defs({:defmodule, _, _arguments} = ast) do
Code.postwalk(ast, &collect_defs/2)
end
@doc "Returns the arity of the given function definition `ast`"
def def_arity(ast)
for op <- @def_ops do
def def_arity({unquote(op) = op, _, [{:when, _, fun_ast}, _]}) do
def_arity({op, nil, fun_ast})
end
def def_arity({unquote(op), _, [{_fun_name, _, arguments}, _]})
when is_list(arguments) do
Enum.count(arguments)
end
def def_arity({unquote(op), _, [{_fun_name, _, _}, _]}), do: 0
end
def def_arity(_), do: nil
@doc "Returns the name of the function/macro defined in the given `ast`"
for op <- @def_ops do
def def_name({unquote(op) = op, _, [{:when, _, fun_ast}, _]}) do
def_name({op, nil, fun_ast})
end
def def_name({unquote(op), _, [{fun_name, _, _arguments}, _]})
when is_atom(fun_name) do
fun_name
end
end
def def_name(_), do: nil
@doc "Returns the {fun_name, op} tuple of the function/macro defined in the given `ast`"
for op <- @def_ops do
def def_name_with_op({unquote(op) = op, _, _} = ast) do
{def_name(ast), op}
end
def def_name_with_op({unquote(op) = op, _, _} = ast, arity) do
if def_arity(ast) == arity do
{def_name(ast), op}
else
nil
end
end
end
def def_name_with_op(_), do: nil
@doc "Returns the name of the functions/macros for the given module's `ast`"
def def_names(nil), do: []
def def_names({:defmodule, _, _arguments} = ast) do
ast
|> Code.postwalk(&collect_defs/2)
|> Enum.map(&def_name/1)
|> Enum.uniq()
end
@doc "Returns the name of the functions/macros for the given module's `ast`"
def def_names_with_op(nil), do: []
def def_names_with_op({:defmodule, _, _arguments} = ast) do
ast
|> Code.postwalk(&collect_defs/2)
|> Enum.map(&def_name_with_op/1)
|> Enum.uniq()
end
@doc "Returns the name of the functions/macros for the given module's `ast` if it has the given `arity`."
def def_names_with_op(nil, _arity), do: []
def def_names_with_op({:defmodule, _, _arguments} = ast, arity) do
ast
|> Code.postwalk(&collect_defs/2)
|> Enum.map(&def_name_with_op(&1, arity))
|> Enum.reject(&is_nil/1)
|> Enum.uniq()
end
for op <- @def_ops do
defp collect_defs({:@, _, [{unquote(op), _, arguments} = ast]}, defs)
when is_list(arguments) do
{ast, defs -- [ast]}
end
defp collect_defs({unquote(op), _, arguments} = ast, defs)
when is_list(arguments) do
{ast, defs ++ [ast]}
end
end
defp collect_defs(ast, defs) do
{ast, defs}
end
@doc "Returns the list of modules used in a given module source code."
def modules({:defmodule, _, _arguments} = ast) do
ast
|> Code.postwalk(&find_dependent_modules/2)
|> Enum.uniq()
end
# exclude module name
defp find_dependent_modules(
{:defmodule, _, [{:__aliases__, _, mod_list}, _do_block]} = ast,
modules
) do
module_names =
mod_list
|> Name.full()
|> List.wrap()
{ast, modules -- module_names}
end
# single alias
defp find_dependent_modules(
{:alias, _, [{:__aliases__, _, mod_list}]} = ast,
aliases
) do
module_names =
mod_list
|> Name.full()
|> List.wrap()
{ast, aliases -- module_names}
end
# multi alias
defp find_dependent_modules(
{:alias, _,
[
{{:., _, [{:__aliases__, _, mod_list}, :{}]}, _, multi_mod_list}
]} = ast,
modules
) do
module_names =
Enum.flat_map(multi_mod_list, fn tuple ->
[Name.full(mod_list), Name.full(tuple)]
end)
{ast, modules -- module_names}
end
defp find_dependent_modules({:__aliases__, _, mod_list} = ast, modules) do
module_names =
mod_list
|> Name.full()
|> List.wrap()
{ast, modules ++ module_names}
end
defp find_dependent_modules(ast, modules) do
{ast, modules}
end
@doc "Returns the name of a module's given ast node."
def name({:defmodule, _, [{:__aliases__, _, name_list}, _]}) do
Enum.join(name_list, ".")
end
def name(_), do: "<Unknown Module Name>"
# TODO: write unit test
def exception?({:defmodule, _, [{:__aliases__, _, _name_list}, arguments]}) do
arguments
|> Block.calls_in_do_block()
|> Enum.any?(&defexception?/1)
end
def exception?(_), do: nil
defp defexception?({:defexception, _, _}), do: true
defp defexception?(_), do: false
end
| 24.293233 | 107 | 0.603683 |
080e8af39cc5f35e6e6e830a5313f146b7a32fc4 | 325 | exs | Elixir | test/mux/packet_test.exs | fishcakez/elixir-mux | 8be71643a79d8eddd93b78b9c74fd14cac436a21 | [
"Apache-2.0"
] | 2 | 2017-07-26T07:28:33.000Z | 2017-08-08T16:26:05.000Z | test/mux/packet_test.exs | fishcakez/elixir-mux | 8be71643a79d8eddd93b78b9c74fd14cac436a21 | [
"Apache-2.0"
] | null | null | null | test/mux/packet_test.exs | fishcakez/elixir-mux | 8be71643a79d8eddd93b78b9c74fd14cac436a21 | [
"Apache-2.0"
] | 1 | 2021-03-13T23:02:29.000Z | 2021-03-13T23:02:29.000Z | defmodule Mux.PacketTest do
use ExUnit.Case, async: true
import PropertyTest
import StreamData
import MuxData
property "encode/decode identity" do
check all packet <- packet() do
assert {type, iodata} = Mux.Packet.encode(packet)
assert Mux.Packet.decode(type, iodata) === packet
end
end
end
| 21.666667 | 55 | 0.701538 |
080ed5720adb6e6ca3451b165ae6564babf40d00 | 1,906 | ex | Elixir | clients/content/lib/google_api/content/v2/model/order_cancellation.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/model/order_cancellation.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/model/order_cancellation.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Content.V2.Model.OrderCancellation do
@moduledoc """
## Attributes
- actor (String): The actor that created the cancellation. Defaults to: `null`.
- creationDate (String): Date on which the cancellation has been created, in ISO 8601 format. Defaults to: `null`.
- quantity (Integer): The quantity that was canceled. Defaults to: `null`.
- reason (String): The reason for the cancellation. Orders that are cancelled with a noInventory reason will lead to the removal of the product from POG until you make an update to that product. This will not affect your Shopping ads. Defaults to: `null`.
- reasonText (String): The explanation of the reason. Defaults to: `null`.
"""
defstruct [
:"actor",
:"creationDate",
:"quantity",
:"reason",
:"reasonText"
]
end
defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.OrderCancellation do
def decode(value, _options) do
value
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.OrderCancellation do
def encode(value, options) do
GoogleApi.Content.V2.Deserializer.serialize_non_nil(value, options)
end
end
| 35.296296 | 257 | 0.741343 |
080eed8efc8b8456149e50679eb3d4aab07d4639 | 148 | exs | Elixir | plugins/one_wiki/config/config.exs | smpallen99/ucx_ucc | 47225f205a6ac4aacdb9bb4f7512dcf4092576ad | [
"MIT"
] | 11 | 2017-05-15T18:35:05.000Z | 2018-02-05T18:27:40.000Z | plugins/one_wiki/config/config.exs | anndream/infinity_one | 47225f205a6ac4aacdb9bb4f7512dcf4092576ad | [
"MIT"
] | 15 | 2017-11-27T10:38:05.000Z | 2018-02-09T20:42:08.000Z | plugins/one_wiki/config/config.exs | anndream/infinity_one | 47225f205a6ac4aacdb9bb4f7512dcf4092576ad | [
"MIT"
] | 4 | 2017-09-13T11:34:16.000Z | 2018-02-26T13:37:06.000Z | use Mix.Config
config :unbrella, :plugins, one_wiki: [
module: OneWiki,
schemas: [OneWiki.Accounts.User],
application: OneWiki.Application
]
| 18.5 | 39 | 0.736486 |
080f0de9bb4391ee73c1e289fdc85c1338cfb263 | 266 | exs | Elixir | test/colly_web/views/layout_view_test.exs | nidhindamodaran/colly | aaf5076afa24ea69ec084f19c5617f6808b40ade | [
"MIT"
] | null | null | null | test/colly_web/views/layout_view_test.exs | nidhindamodaran/colly | aaf5076afa24ea69ec084f19c5617f6808b40ade | [
"MIT"
] | 4 | 2020-05-30T13:25:44.000Z | 2021-05-11T13:32:44.000Z | test/colly_web/views/layout_view_test.exs | nidhinnambiar/colly | aaf5076afa24ea69ec084f19c5617f6808b40ade | [
"MIT"
] | null | null | null | defmodule CollyWeb.LayoutViewTest do
use CollyWeb.ConnCase, async: true
# When testing helpers, you may want to import Phoenix.HTML and
# use functions such as safe_to_string() to convert the helper
# result into an HTML string.
# import Phoenix.HTML
end
| 29.555556 | 65 | 0.763158 |
080f12bc78e3d6e74c68ece24aa8f23608ad5e0e | 10,238 | ex | Elixir | lib/poison/parser.ex | nobrick/poison | 5e299f922bf7ffdeeb44602f9d6d68134a3a75c2 | [
"CC0-1.0"
] | 1 | 2019-07-13T16:38:34.000Z | 2019-07-13T16:38:34.000Z | lib/poison/parser.ex | nobrick/poison | 5e299f922bf7ffdeeb44602f9d6d68134a3a75c2 | [
"CC0-1.0"
] | null | null | null | lib/poison/parser.ex | nobrick/poison | 5e299f922bf7ffdeeb44602f9d6d68134a3a75c2 | [
"CC0-1.0"
] | 1 | 2019-07-13T16:38:38.000Z | 2019-07-13T16:38:38.000Z | defmodule Poison.ParseError do
@type t :: %__MODULE__{pos: integer, value: String.t()}
alias Code.Identifier
defexception pos: 0, value: nil, rest: nil
def message(%{value: "", pos: pos}) do
"Unexpected end of input at position #{pos}"
end
def message(%{value: <<token::utf8>>, pos: pos}) do
"Unexpected token at position #{pos}: #{escape(token)}"
end
def message(%{value: value, pos: pos}) when is_binary(value) do
start = pos - String.length(value)
"Cannot parse value at position #{start}: #{inspect(value)}"
end
def message(%{value: value}) do
"Unsupported value: #{inspect(value)}"
end
defp escape(token) do
{value, _} = Identifier.escape(<<token::utf8>>, ?\\)
value
end
end
defmodule Poison.Parser do
@moduledoc """
An RFC 7159 and ECMA 404 conforming JSON parser.
See: https://tools.ietf.org/html/rfc7159
See: http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf
"""
@compile :inline
@compile {:inline_size, 256}
if Application.get_env(:poison, :native) do
@compile [:native, {:hipe, [:o3]}]
end
use Bitwise
alias Poison.ParseError
@type t :: nil | true | false | list | float | integer | String.t() | map
defmacrop stacktrace do
if Version.compare(System.version(), "1.7.0") != :lt do
quote do: __STACKTRACE__
else
quote do: System.stacktrace()
end
end
def parse!(iodata, options) do
string = IO.iodata_to_binary(iodata)
keys = Map.get(options, :keys)
{rest, pos} = skip_whitespace(skip_bom(string), 0)
{value, pos, rest} = value(rest, pos, keys)
case skip_whitespace(rest, pos) do
{"", _pos} -> value
{other, pos} -> syntax_error(other, pos)
end
rescue
ArgumentError ->
reraise %ParseError{value: iodata}, stacktrace()
end
def parse(iodata, options) do
{:ok, parse!(iodata, options)}
rescue
error in [ParseError] ->
{:error, error}
end
defp value("\"" <> rest, pos, _keys) do
string_continue(rest, pos + 1, [])
end
defp value("{" <> rest, pos, keys) do
{rest, pos} = skip_whitespace(rest, pos + 1)
object_pairs(rest, pos, keys, [])
end
defp value("[" <> rest, pos, keys) do
{rest, pos} = skip_whitespace(rest, pos + 1)
array_values(rest, pos, keys, [])
end
defp value("null" <> rest, pos, _keys), do: {nil, pos + 4, rest}
defp value("true" <> rest, pos, _keys), do: {true, pos + 4, rest}
defp value("false" <> rest, pos, _keys), do: {false, pos + 5, rest}
defp value(<<char, _::binary>> = string, pos, _keys)
when char in '-0123456789' do
number_start(string, pos)
end
defp value(other, pos, _keys), do: syntax_error(other, pos)
## Objects
defp object_pairs("\"" <> rest, pos, keys, acc) do
{name, pos, rest} = string_continue(rest, pos + 1, [])
{value, start, pos, rest} =
case skip_whitespace(rest, pos) do
{":" <> rest, start} ->
{rest, pos} = skip_whitespace(rest, start + 1)
{value, pos, rest} = value(rest, pos, keys)
{value, start, pos, rest}
{other, pos} ->
syntax_error(other, pos)
end
acc = [{object_name(name, start, keys), value} | acc]
case skip_whitespace(rest, pos) do
{"," <> rest, pos} ->
{rest, pos} = skip_whitespace(rest, pos + 1)
object_pairs(rest, pos, keys, acc)
{"}" <> rest, pos} ->
{:maps.from_list(acc), pos + 1, rest}
{other, pos} ->
syntax_error(other, pos)
end
end
defp object_pairs("}" <> rest, pos, _, []) do
{:maps.new(), pos + 1, rest}
end
defp object_pairs(other, pos, _, _), do: syntax_error(other, pos)
defp object_name(name, pos, :atoms!) do
String.to_existing_atom(name)
rescue
ArgumentError ->
reraise %ParseError{value: name, pos: pos}, stacktrace()
end
defp object_name(name, _pos, :atoms), do: String.to_atom(name)
defp object_name(name, _pos, _keys), do: name
## Arrays
defp array_values("]" <> rest, pos, _, []) do
{[], pos + 1, rest}
end
defp array_values(string, pos, keys, acc) do
{value, pos, rest} = value(string, pos, keys)
acc = [value | acc]
case skip_whitespace(rest, pos) do
{"," <> rest, pos} ->
{rest, pos} = skip_whitespace(rest, pos + 1)
array_values(rest, pos, keys, acc)
{"]" <> rest, pos} ->
{:lists.reverse(acc), pos + 1, rest}
{other, pos} ->
syntax_error(other, pos)
end
end
## Numbers
defp number_start("-" <> rest, pos) do
case rest do
"0" <> rest -> number_frac(rest, pos + 2, ["-0"])
rest -> number_int(rest, pos + 1, [?-])
end
end
defp number_start("0" <> rest, pos) do
number_frac(rest, pos + 1, [?0])
end
defp number_start(string, pos) do
number_int(string, pos, [])
end
defp number_int(<<char, _::binary>> = string, pos, acc)
when char in '123456789' do
{digits, pos, rest} = number_digits(string, pos)
number_frac(rest, pos, [acc, digits])
end
defp number_int(other, pos, _), do: syntax_error(other, pos)
defp number_frac("." <> rest, pos, acc) do
{digits, pos, rest} = number_digits(rest, pos + 1)
number_exp(rest, true, pos, [acc, ?., digits])
end
defp number_frac(string, pos, acc) do
number_exp(string, false, pos, acc)
end
defp number_exp(<<e>> <> rest, frac, pos, acc) when e in 'eE' do
e = if frac, do: ?e, else: ".0e"
case rest do
"-" <> rest -> number_exp_continue(rest, frac, pos + 2, [acc, e, ?-])
"+" <> rest -> number_exp_continue(rest, frac, pos + 2, [acc, e])
rest -> number_exp_continue(rest, frac, pos + 1, [acc, e])
end
end
defp number_exp(string, frac, pos, acc) do
{number_complete(acc, frac, pos), pos, string}
end
defp number_exp_continue(rest, frac, pos, acc) do
{digits, pos, rest} = number_digits(rest, pos)
pos = if frac, do: pos, else: pos + 2
{number_complete([acc, digits], true, pos), pos, rest}
end
defp number_complete(iolist, false, _pos) do
iolist |> IO.iodata_to_binary() |> String.to_integer()
end
defp number_complete(iolist, true, pos) do
iolist |> IO.iodata_to_binary() |> String.to_float()
rescue
ArgumentError ->
value = iolist |> IO.iodata_to_binary()
reraise %ParseError{pos: pos, value: value}, stacktrace()
end
defp number_digits(<<char>> <> rest = string, pos)
when char in '0123456789' do
count = number_digits_count(rest, 1)
<<digits::binary-size(count), rest::binary>> = string
{digits, pos + count, rest}
end
defp number_digits(other, pos), do: syntax_error(other, pos)
defp number_digits_count(<<char>> <> rest, acc) when char in '0123456789' do
number_digits_count(rest, acc + 1)
end
defp number_digits_count(_, acc), do: acc
## Strings
defp string_continue("\"" <> rest, pos, acc) do
{IO.iodata_to_binary(acc), pos + 1, rest}
end
defp string_continue("\\" <> rest, pos, acc) do
string_escape(rest, pos, acc)
end
defp string_continue("", pos, _), do: syntax_error(nil, pos)
defp string_continue(string, pos, acc) do
{count, pos} = string_chunk_size(string, pos, 0)
<<chunk::binary-size(count), rest::binary>> = string
string_continue(rest, pos, [acc, chunk])
end
for {seq, char} <- Enum.zip('"\\ntr/fb', '"\\\n\t\r/\f\b') do
defp string_escape(<<unquote(seq)>> <> rest, pos, acc) do
string_continue(rest, pos + 1, [acc, unquote(char)])
end
end
defguardp is_surrogate(a1, a2, b1, b2)
when a1 in 'dD' and a2 in 'dD' and b1 in '89abAB' and
(b2 in ?c..?f or b2 in ?C..?F)
# http://www.ietf.org/rfc/rfc2781.txt
# http://perldoc.perl.org/Encode/Unicode.html#Surrogate-Pairs
# http://mathiasbynens.be/notes/javascript-encoding#surrogate-pairs
defp string_escape(
<<?u, a1, b1, c1, d1, "\\u", a2, b2, c2, d2>> <> rest,
pos,
acc
)
when is_surrogate(a1, a2, b1, b2) do
hi = List.to_integer([a1, b1, c1, d1], 16)
lo = List.to_integer([a2, b2, c2, d2], 16)
codepoint = 0x10000 + ((hi &&& 0x03FF) <<< 10) + (lo &&& 0x03FF)
string_continue(rest, pos + 11, [acc, <<codepoint::utf8>>])
rescue
ArgumentError ->
value = <<"\\u", a1, b1, c1, d1, "\\u", a2, b2, c2, d2>>
reraise %ParseError{pos: pos + 12, value: value}, stacktrace()
end
defp string_escape(<<?u, seq::binary-size(4)>> <> rest, pos, acc) do
code = String.to_integer(seq, 16)
string_continue(rest, pos + 5, [acc, <<code::utf8>>])
rescue
ArgumentError ->
value = "\\u" <> seq
reraise %ParseError{pos: pos + 6, value: value}, stacktrace()
end
defp string_escape(other, pos, _), do: syntax_error(other, pos)
defp string_chunk_size("\"" <> _, pos, acc), do: {acc, pos}
defp string_chunk_size("\\" <> _, pos, acc), do: {acc, pos}
# Control Characters (http://seriot.ch/parsing_json.php#25)
defp string_chunk_size(<<char>> <> _rest, pos, _acc) when char <= 0x1F do
syntax_error(<<char>>, pos)
end
defp string_chunk_size(<<char>> <> rest, pos, acc) when char < 0x80 do
string_chunk_size(rest, pos + 1, acc + 1)
end
defp string_chunk_size(<<codepoint::utf8>> <> rest, pos, acc) do
string_chunk_size(rest, pos + 1, acc + string_codepoint_size(codepoint))
end
defp string_chunk_size(other, pos, _acc), do: syntax_error(other, pos)
defp string_codepoint_size(codepoint) when codepoint < 0x800, do: 2
defp string_codepoint_size(codepoint) when codepoint < 0x10000, do: 3
defp string_codepoint_size(_), do: 4
## Whitespace
defp skip_whitespace(<<char>> <> rest, pos) when char in '\s\n\t\r' do
skip_whitespace(rest, pos + 1)
end
defp skip_whitespace(string, pos), do: {string, pos}
# https://tools.ietf.org/html/rfc7159#section-8.1
# https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
defp skip_bom(<<0xEF, 0xBB, 0xBF>> <> rest) do
rest
end
defp skip_bom(string) do
string
end
## Errors
defp syntax_error(<<token::utf8>> <> _, pos) do
raise %ParseError{pos: pos, value: <<token::utf8>>}
end
defp syntax_error(_, pos) do
raise %ParseError{pos: pos, value: ""}
end
end
| 27.896458 | 80 | 0.612522 |
080f1c7ebe84704909b7cd31a61a3125aba59102 | 1,217 | exs | Elixir | code/general/map_put_vs_put_in.exs | TheMaikXX/fast-elixir | 0e622c3f8bb4751fd023fde1e34ec78cf4337dfd | [
"CC0-1.0"
] | 1,154 | 2017-05-04T10:18:30.000Z | 2022-03-29T06:43:28.000Z | code/general/map_put_vs_put_in.exs | TheMaikXX/fast-elixir | 0e622c3f8bb4751fd023fde1e34ec78cf4337dfd | [
"CC0-1.0"
] | 13 | 2017-05-22T21:58:36.000Z | 2022-02-25T15:52:12.000Z | code/general/map_put_vs_put_in.exs | TheMaikXX/fast-elixir | 0e622c3f8bb4751fd023fde1e34ec78cf4337dfd | [
"CC0-1.0"
] | 35 | 2017-05-27T17:55:07.000Z | 2022-03-13T18:55:48.000Z | defmodule MapPut.Fast do
def map_put(enumerator, map) do
enumerator
|> Enum.reduce(map, fn value, acc ->
Map.put(acc, value, value)
end)
end
end
defmodule MapPut.Slower do
def map_put(enumerator, map) do
enumerator
|> Enum.reduce(map, fn value, acc ->
put_in(acc[value], value)
end)
end
end
defmodule MapPut.Slowest do
def map_put(enumerator, map) do
enumerator
|> Enum.reduce(map, fn value, acc ->
put_in(acc, [value], value)
end)
end
end
defmodule MapPut.Benchmark do
@inputs %{
"Large (30,000 items)" => 1..10_000,
"Medium (3,000 items)" => 1..1_000,
"Small (30 items)" => 1..10
}
def benchmark do
Benchee.run(
%{
"Map.put/3" => fn enumerator -> bench_func(enumerator, MapPut.Fast) end,
"put_in/2" => fn enumerator -> bench_func(enumerator, MapPut.Slower) end,
"put_in/3" => fn enumerator -> bench_func(enumerator, MapPut.Slowest) end
},
time: 10,
inputs: @inputs,
print: [fast_warning: false]
)
end
@map %{
a: 1,
b: 2,
c: 3
}
def bench_func(enumerator, module) do
module.map_put(enumerator, @map)
end
end
MapPut.Benchmark.benchmark()
| 20.283333 | 81 | 0.608053 |
080f272f9a5e2cee99a2ae65aa3c05bc5c8b0847 | 1,048 | ex | Elixir | lib/coxir/model/entities/invite.ex | satom99/coxir | 75bce94dcbe5dfa49e920d2f4ce0de224c315ce4 | [
"Apache-2.0"
] | 178 | 2018-04-08T17:11:56.000Z | 2022-03-25T15:36:41.000Z | lib/coxir/model/entities/invite.ex | satom99/coxir | 75bce94dcbe5dfa49e920d2f4ce0de224c315ce4 | [
"Apache-2.0"
] | 21 | 2018-04-30T21:33:59.000Z | 2019-09-03T17:25:26.000Z | lib/coxir/model/entities/invite.ex | satom99/coxir | 75bce94dcbe5dfa49e920d2f4ce0de224c315ce4 | [
"Apache-2.0"
] | 25 | 2018-04-21T19:41:03.000Z | 2021-07-24T22:40:40.000Z | defmodule Coxir.Invite do
@moduledoc """
Work in progress.
"""
use Coxir.Model, storable?: false
@primary_key false
@type t :: %Invite{}
embedded_schema do
field(:code, :string, primary_key: true)
field(:uses, :integer)
field(:max_uses, :integer)
field(:max_age, :integer)
field(:temporary, :boolean)
field(:target_type, :integer)
field(:approximate_presence_count, :integer)
field(:approximate_member_count, :integer)
field(:created_at, :utc_datetime)
field(:expires_at, :utc_datetime)
belongs_to(:guild, Guild)
belongs_to(:channel, Channel)
belongs_to(:inviter, User)
belongs_to(:target_user, User)
end
def fetch(code, options) do
query = Keyword.take(options, [:with_counts, :with_expiration])
API.get("invites/#{code}", query, options)
end
def insert(%{channel_id: channel_id} = params, options) do
API.post("channels/#{channel_id}/invites", params, options)
end
def drop(code, options) do
API.delete("invites/#{code}", options)
end
end
| 24.952381 | 67 | 0.679389 |
080f39444fc4a85a810c49e31ca77b9d86c8aab6 | 558 | exs | Elixir | test/arkecosystem/crypto/transactions/serializers/delegate_registration_test.exs | whitehat/elixir-crypto | 6347868ee15c7b79676df58bef54376a8dc6fd02 | [
"MIT"
] | null | null | null | test/arkecosystem/crypto/transactions/serializers/delegate_registration_test.exs | whitehat/elixir-crypto | 6347868ee15c7b79676df58bef54376a8dc6fd02 | [
"MIT"
] | null | null | null | test/arkecosystem/crypto/transactions/serializers/delegate_registration_test.exs | whitehat/elixir-crypto | 6347868ee15c7b79676df58bef54376a8dc6fd02 | [
"MIT"
] | null | null | null | defmodule ArkEcosystem.Crypto.Transactions.Serializers.DelegateRegistrationTest do
use ExUnit.Case, async: false
alias ArkEcosystem.Crypto.Transactions.Serializer
alias ArkEcosystem.Test.TestHelper
setup_all do
ArkEcosystem.Crypto.Configuration.Network.set(ArkEcosystem.Crypto.Networks.Devnet)
:ok
end
test "should be ok" do
fixture = TestHelper.read_transaction_fixture("delegate_registration", "passphrase")
actual = Serializer.serialize(fixture.data, %{underscore: true})
assert(actual == fixture.serialized)
end
end
| 29.368421 | 88 | 0.783154 |
080f713afb7d3a0e525e7a212ade42ecae7016a2 | 965 | ex | Elixir | apps/nerves_hub_www/test/support/channel_case.ex | Gazler/nerves_hub_web | 9a636a17310382819eaa6cee590e053cb47f0dcc | [
"Apache-2.0"
] | 1 | 2019-10-13T10:56:28.000Z | 2019-10-13T10:56:28.000Z | apps/nerves_hub_www/test/support/channel_case.ex | Eaftos/nerves_hub_web | ac03bd044b97265bf3ba3edd8da249d300fa3668 | [
"Apache-2.0"
] | null | null | null | apps/nerves_hub_www/test/support/channel_case.ex | Eaftos/nerves_hub_web | ac03bd044b97265bf3ba3edd8da249d300fa3668 | [
"Apache-2.0"
] | null | null | null | defmodule NervesHubWWWWeb.ChannelCase do
@moduledoc """
This module defines the test case to be used by
channel tests.
Such tests rely on `Phoenix.ChannelTest` and also
import other functionality to make it easier
to build common datastructures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with channels
use Phoenix.ChannelTest
# The default endpoint for testing
@endpoint NervesHubWWWWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(NervesHubWebCore.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(NervesHubWebCore.Repo, {:shared, self()})
end
:ok
end
end
| 25.394737 | 78 | 0.724352 |
080f98e1a0c4155a79e585364d0b85c41a1fa1bb | 330 | ex | Elixir | test/factories/course/group_factory.ex | ZiHawkEye/cadet | f7f9143699054d12bf08ef94e6e20a8ac58aea50 | [
"Apache-2.0"
] | null | null | null | test/factories/course/group_factory.ex | ZiHawkEye/cadet | f7f9143699054d12bf08ef94e6e20a8ac58aea50 | [
"Apache-2.0"
] | null | null | null | test/factories/course/group_factory.ex | ZiHawkEye/cadet | f7f9143699054d12bf08ef94e6e20a8ac58aea50 | [
"Apache-2.0"
] | null | null | null | defmodule Cadet.Course.GroupFactory do
@moduledoc """
Factory for Group entity
"""
defmacro __using__(_opts) do
quote do
alias Cadet.Course.Group
def group_factory do
%Group{
name: Faker.Company.name(),
leader: build(:user, role: :staff)
}
end
end
end
end
| 17.368421 | 44 | 0.590909 |
080fcd74f50001eb5b471c9360bd39ae1e67aca4 | 696 | exs | Elixir | code/typespecs/simple/mix.exs | alvarocamillont/introdu-o_elixir | 1d72d4f4b01d9312c4b066ce3c0fe8d9bfaaade1 | [
"MIT"
] | null | null | null | code/typespecs/simple/mix.exs | alvarocamillont/introdu-o_elixir | 1d72d4f4b01d9312c4b066ce3c0fe8d9bfaaade1 | [
"MIT"
] | 1 | 2021-03-09T16:27:25.000Z | 2021-03-09T16:27:25.000Z | programming-elixir-book/code/typespecs/simple/mix.exs | jordanhubbard/elixir-projects | dee341d672e83a45a17a4a85abd54a480f95c506 | [
"BSD-2-Clause"
] | null | null | null | #---
# Excerpted from "Programming Elixir ≥ 1.6",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/elixir16 for more book information.
#---
defmodule Simple.Mixfile do
use Mix.Project
def project do
[
app: :simple,
version: "0.0.1",
deps: deps()
]
end
def application do
[mod: { Simple, [] }]
end
defp deps do
[
{ :dialyxir, "~> 0.5", only: [:dev], runtime: false }
]
end
end
| 23.2 | 85 | 0.647989 |
08100024c9d8c9891a52b9e97423e8a36b30bfc4 | 1,153 | exs | Elixir | config/config.exs | michaeljguarino/anchore-elixir-client | 156a44f429ecb62433729a2b4c52de5dc0ef44d2 | [
"MIT"
] | null | null | null | config/config.exs | michaeljguarino/anchore-elixir-client | 156a44f429ecb62433729a2b4c52de5dc0ef44d2 | [
"MIT"
] | null | null | null | config/config.exs | michaeljguarino/anchore-elixir-client | 156a44f429ecb62433729a2b4c52de5dc0ef44d2 | [
"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 :anchore_engine_api_server, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:anchore_engine_api_server, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 37.193548 | 73 | 0.75889 |
08101563836b7e832550639e2b4693a6ea8a077c | 298 | ex | Elixir | lib/empex_cookbook_web/absinthe_with_datadog_plug.ex | ludwikbukowski/recipes | cac5711d32874c3011da8da3329b70d0e28e725e | [
"MIT"
] | 4 | 2019-02-11T12:15:36.000Z | 2021-03-22T16:23:47.000Z | lib/empex_cookbook_web/absinthe_with_datadog_plug.ex | ludwikbukowski/recipes | cac5711d32874c3011da8da3329b70d0e28e725e | [
"MIT"
] | null | null | null | lib/empex_cookbook_web/absinthe_with_datadog_plug.ex | ludwikbukowski/recipes | cac5711d32874c3011da8da3329b70d0e28e725e | [
"MIT"
] | null | null | null | defmodule EmpexCookbookWeb.AbsintheWithDatadogPlug do
@behaviour Plug
def init(opts), do: Absinthe.Plug.GraphiQL.init(opts)
def call(conn, opts) do
conn
|> Absinthe.Plug.GraphiQL.call(opts)
|> Spandex.Plug.EndTrace.call(tracer: EmpexCookbook.Tracing, tracer_opts: [])
end
end
| 24.833333 | 81 | 0.734899 |
0810401b1d48e47badb64bac0d8dfc9c3d500897 | 1,982 | exs | Elixir | mix.exs | bfg1981/webbkoll | ec7c6167e46fe1e27f01f5d98f3daa068af40f63 | [
"MIT"
] | 1 | 2020-03-06T15:39:43.000Z | 2020-03-06T15:39:43.000Z | mix.exs | bfg1981/webbkoll | ec7c6167e46fe1e27f01f5d98f3daa068af40f63 | [
"MIT"
] | null | null | null | mix.exs | bfg1981/webbkoll | ec7c6167e46fe1e27f01f5d98f3daa068af40f63 | [
"MIT"
] | null | null | null | defmodule Webbkoll.Mixfile do
use Mix.Project
def project do
[
app: :webbkoll,
version: "0.0.1",
elixir: "~> 1.7",
elixirc_paths: elixirc_paths(Mix.env()),
compilers: [:phoenix, :gettext] ++ Mix.compilers(),
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {Webbkoll.Application, []},
applications: [
:phoenix,
:phoenix_pubsub,
:phoenix_html,
:cowboy,
:logger,
:gettext,
:httpoison,
:tzdata,
:ex_rated,
:quantum,
:timex,
:geolix,
:con_cache,
:jumbo,
:download,
:valid_url
],
included_applications: [:ex2ms, :floki, :public_suffix, :uuid]
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[
{:phoenix, "~> 1.4.0"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:plug_cowboy, "~> 2.0"},
{:plug, "~> 1.7"},
{:httpoison, "~> 1.0"},
{:floki, "~> 0.8"},
{:ex_rated, "~> 1.2"},
{:quantum, ">= 2.2.1"},
{:ex_machina, "~> 2.0", only: :test},
{:public_suffix, "~> 0.4"},
{:timex, "~> 3.0"},
{:hackney, "~> 1.8"},
{:geolix, "~> 0.13"},
{:idna, "~> 5.0", override: true},
{:con_cache, "~> 0.13"},
{:uuid, "~> 1.1"},
{:jumbo, "~> 1.0"},
{:download, "~> 0.0.4"},
{:stream_gzip, "~> 0.3.1"},
{:jason, "~> 1.0"},
{:valid_url, "~> 0.1.2"}
]
end
end
| 24.469136 | 68 | 0.490918 |
0811059585eddcc1094854833119b4c2f2c6385a | 75,868 | ex | Elixir | testData/org/elixir_lang/beam/decompiler/gl.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 1,668 | 2015-01-03T05:54:27.000Z | 2022-03-25T08:01:20.000Z | testData/org/elixir_lang/beam/decompiler/gl.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 2,018 | 2015-01-01T22:43:39.000Z | 2022-03-31T20:13:08.000Z | testData/org/elixir_lang/beam/decompiler/gl.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 145 | 2015-01-15T11:37:16.000Z | 2021-12-22T05:51:02.000Z | # Source code recreated from a .beam file by IntelliJ Elixir
defmodule :gl do
# Functions
def accum(p0, p1) do
# body not decompiled
end
def activeShaderProgram(p0, p1) do
# body not decompiled
end
def activeTexture(p0) do
# body not decompiled
end
def alphaFunc(p0, p1) do
# body not decompiled
end
def areTexturesResident(p0) do
# body not decompiled
end
def arrayElement(p0) do
# body not decompiled
end
def attachObjectARB(p0, p1) do
# body not decompiled
end
def attachShader(p0, p1) do
# body not decompiled
end
def begin(p0) do
# body not decompiled
end
def beginConditionalRender(p0, p1) do
# body not decompiled
end
def beginQuery(p0, p1) do
# body not decompiled
end
def beginQueryIndexed(p0, p1, p2) do
# body not decompiled
end
def beginTransformFeedback(p0) do
# body not decompiled
end
def bindAttribLocation(p0, p1, p2) do
# body not decompiled
end
def bindAttribLocationARB(p0, p1, p2) do
# body not decompiled
end
def bindBuffer(p0, p1) do
# body not decompiled
end
def bindBufferBase(p0, p1, p2) do
# body not decompiled
end
def bindBufferRange(p0, p1, p2, p3, p4) do
# body not decompiled
end
def bindFragDataLocation(p0, p1, p2) do
# body not decompiled
end
def bindFragDataLocationIndexed(p0, p1, p2, p3) do
# body not decompiled
end
def bindFramebuffer(p0, p1) do
# body not decompiled
end
def bindImageTexture(p0, p1, p2, p3, p4, p5, p6) do
# body not decompiled
end
def bindProgramARB(p0, p1) do
# body not decompiled
end
def bindProgramPipeline(p0) do
# body not decompiled
end
def bindRenderbuffer(p0, p1) do
# body not decompiled
end
def bindSampler(p0, p1) do
# body not decompiled
end
def bindTexture(p0, p1) do
# body not decompiled
end
def bindTransformFeedback(p0, p1) do
# body not decompiled
end
def bindVertexArray(p0) do
# body not decompiled
end
def bitmap(p0, p1, p2, p3, p4, p5, p6) do
# body not decompiled
end
def blendColor(p0, p1, p2, p3) do
# body not decompiled
end
def blendEquation(p0) do
# body not decompiled
end
def blendEquationSeparate(p0, p1) do
# body not decompiled
end
def blendEquationSeparatei(p0, p1, p2) do
# body not decompiled
end
def blendEquationi(p0, p1) do
# body not decompiled
end
def blendFunc(p0, p1) do
# body not decompiled
end
def blendFuncSeparate(p0, p1, p2, p3) do
# body not decompiled
end
def blendFuncSeparatei(p0, p1, p2, p3, p4) do
# body not decompiled
end
def blendFunci(p0, p1, p2) do
# body not decompiled
end
def blitFramebuffer(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) do
# body not decompiled
end
def bufferData(p0, p1, p2, p3) do
# body not decompiled
end
def bufferSubData(p0, p1, p2, p3) do
# body not decompiled
end
def call(p0, p1) do
# body not decompiled
end
def callList(p0) do
# body not decompiled
end
def callLists(p0) do
# body not decompiled
end
def cast(p0, p1) do
# body not decompiled
end
def checkFramebufferStatus(p0) do
# body not decompiled
end
def clampColor(p0, p1) do
# body not decompiled
end
def clear(p0) do
# body not decompiled
end
def clearAccum(p0, p1, p2, p3) do
# body not decompiled
end
def clearBufferfi(p0, p1, p2, p3) do
# body not decompiled
end
def clearBufferfv(p0, p1, p2) do
# body not decompiled
end
def clearBufferiv(p0, p1, p2) do
# body not decompiled
end
def clearBufferuiv(p0, p1, p2) do
# body not decompiled
end
def clearColor(p0, p1, p2, p3) do
# body not decompiled
end
def clearDepth(p0) do
# body not decompiled
end
def clearDepthf(p0) do
# body not decompiled
end
def clearIndex(p0) do
# body not decompiled
end
def clearStencil(p0) do
# body not decompiled
end
def clientActiveTexture(p0) do
# body not decompiled
end
def clientWaitSync(p0, p1, p2) do
# body not decompiled
end
def clipPlane(p0, p1) do
# body not decompiled
end
def color3b(p0, p1, p2) do
# body not decompiled
end
def color3bv(p0) do
# body not decompiled
end
def color3d(p0, p1, p2) do
# body not decompiled
end
def color3dv(p0) do
# body not decompiled
end
def color3f(p0, p1, p2) do
# body not decompiled
end
def color3fv(p0) do
# body not decompiled
end
def color3i(p0, p1, p2) do
# body not decompiled
end
def color3iv(p0) do
# body not decompiled
end
def color3s(p0, p1, p2) do
# body not decompiled
end
def color3sv(p0) do
# body not decompiled
end
def color3ub(p0, p1, p2) do
# body not decompiled
end
def color3ubv(p0) do
# body not decompiled
end
def color3ui(p0, p1, p2) do
# body not decompiled
end
def color3uiv(p0) do
# body not decompiled
end
def color3us(p0, p1, p2) do
# body not decompiled
end
def color3usv(p0) do
# body not decompiled
end
def color4b(p0, p1, p2, p3) do
# body not decompiled
end
def color4bv(p0) do
# body not decompiled
end
def color4d(p0, p1, p2, p3) do
# body not decompiled
end
def color4dv(p0) do
# body not decompiled
end
def color4f(p0, p1, p2, p3) do
# body not decompiled
end
def color4fv(p0) do
# body not decompiled
end
def color4i(p0, p1, p2, p3) do
# body not decompiled
end
def color4iv(p0) do
# body not decompiled
end
def color4s(p0, p1, p2, p3) do
# body not decompiled
end
def color4sv(p0) do
# body not decompiled
end
def color4ub(p0, p1, p2, p3) do
# body not decompiled
end
def color4ubv(p0) do
# body not decompiled
end
def color4ui(p0, p1, p2, p3) do
# body not decompiled
end
def color4uiv(p0) do
# body not decompiled
end
def color4us(p0, p1, p2, p3) do
# body not decompiled
end
def color4usv(p0) do
# body not decompiled
end
def colorMask(p0, p1, p2, p3) do
# body not decompiled
end
def colorMaski(p0, p1, p2, p3, p4) do
# body not decompiled
end
def colorMaterial(p0, p1) do
# body not decompiled
end
def colorPointer(p0, p1, p2, p3) do
# body not decompiled
end
def colorSubTable(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def colorTable(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def colorTableParameterfv(p0, p1, p2) do
# body not decompiled
end
def colorTableParameteriv(p0, p1, p2) do
# body not decompiled
end
def compileShader(p0) do
# body not decompiled
end
def compileShaderARB(p0) do
# body not decompiled
end
def compileShaderIncludeARB(p0, p1) do
# body not decompiled
end
def compressedTexImage1D(p0, p1, p2, p3, p4, p5, p6) do
# body not decompiled
end
def compressedTexImage2D(p0, p1, p2, p3, p4, p5, p6, p7) do
# body not decompiled
end
def compressedTexImage3D(p0, p1, p2, p3, p4, p5, p6, p7, p8) do
# body not decompiled
end
def compressedTexSubImage1D(p0, p1, p2, p3, p4, p5, p6) do
# body not decompiled
end
def compressedTexSubImage2D(p0, p1, p2, p3, p4, p5, p6, p7, p8) do
# body not decompiled
end
def compressedTexSubImage3D(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) do
# body not decompiled
end
def convolutionFilter1D(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def convolutionFilter2D(p0, p1, p2, p3, p4, p5, p6) do
# body not decompiled
end
def convolutionParameterf(p0, p1, p2) do
# body not decompiled
end
def convolutionParameterfv(p0, p1, p2) do
# body not decompiled
end
def convolutionParameteri(p0, p1, p2) do
# body not decompiled
end
def convolutionParameteriv(p0, p1, p2) do
# body not decompiled
end
def copyBufferSubData(p0, p1, p2, p3, p4) do
# body not decompiled
end
def copyColorSubTable(p0, p1, p2, p3, p4) do
# body not decompiled
end
def copyColorTable(p0, p1, p2, p3, p4) do
# body not decompiled
end
def copyConvolutionFilter1D(p0, p1, p2, p3, p4) do
# body not decompiled
end
def copyConvolutionFilter2D(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def copyPixels(p0, p1, p2, p3, p4) do
# body not decompiled
end
def copyTexImage1D(p0, p1, p2, p3, p4, p5, p6) do
# body not decompiled
end
def copyTexImage2D(p0, p1, p2, p3, p4, p5, p6, p7) do
# body not decompiled
end
def copyTexSubImage1D(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def copyTexSubImage2D(p0, p1, p2, p3, p4, p5, p6, p7) do
# body not decompiled
end
def copyTexSubImage3D(p0, p1, p2, p3, p4, p5, p6, p7, p8) do
# body not decompiled
end
def createProgram() do
# body not decompiled
end
def createProgramObjectARB() do
# body not decompiled
end
def createShader(p0) do
# body not decompiled
end
def createShaderObjectARB(p0) do
# body not decompiled
end
def createShaderProgramv(p0, p1) do
# body not decompiled
end
def cullFace(p0) do
# body not decompiled
end
def currentPaletteMatrixARB(p0) do
# body not decompiled
end
def debugMessageControlARB(p0, p1, p2, p3, p4) do
# body not decompiled
end
def debugMessageInsertARB(p0, p1, p2, p3, p4) do
# body not decompiled
end
def deleteBuffers(p0) do
# body not decompiled
end
def deleteFramebuffers(p0) do
# body not decompiled
end
def deleteLists(p0, p1) do
# body not decompiled
end
def deleteNamedStringARB(p0) do
# body not decompiled
end
def deleteObjectARB(p0) do
# body not decompiled
end
def deleteProgram(p0) do
# body not decompiled
end
def deleteProgramPipelines(p0) do
# body not decompiled
end
def deleteProgramsARB(p0) do
# body not decompiled
end
def deleteQueries(p0) do
# body not decompiled
end
def deleteRenderbuffers(p0) do
# body not decompiled
end
def deleteSamplers(p0) do
# body not decompiled
end
def deleteShader(p0) do
# body not decompiled
end
def deleteSync(p0) do
# body not decompiled
end
def deleteTextures(p0) do
# body not decompiled
end
def deleteTransformFeedbacks(p0) do
# body not decompiled
end
def deleteVertexArrays(p0) do
# body not decompiled
end
def depthBoundsEXT(p0, p1) do
# body not decompiled
end
def depthFunc(p0) do
# body not decompiled
end
def depthMask(p0) do
# body not decompiled
end
def depthRange(p0, p1) do
# body not decompiled
end
def depthRangeArrayv(p0, p1) do
# body not decompiled
end
def depthRangeIndexed(p0, p1, p2) do
# body not decompiled
end
def depthRangef(p0, p1) do
# body not decompiled
end
def detachObjectARB(p0, p1) do
# body not decompiled
end
def detachShader(p0, p1) do
# body not decompiled
end
def disable(p0) do
# body not decompiled
end
def disableClientState(p0) do
# body not decompiled
end
def disableVertexAttribArray(p0) do
# body not decompiled
end
def disablei(p0, p1) do
# body not decompiled
end
def drawArrays(p0, p1, p2) do
# body not decompiled
end
def drawArraysIndirect(p0, p1) do
# body not decompiled
end
def drawArraysInstanced(p0, p1, p2, p3) do
# body not decompiled
end
def drawArraysInstancedBaseInstance(p0, p1, p2, p3, p4) do
# body not decompiled
end
def drawBuffer(p0) do
# body not decompiled
end
def drawBuffers(p0) do
# body not decompiled
end
def drawElements(p0, p1, p2, p3) do
# body not decompiled
end
def drawElementsBaseVertex(p0, p1, p2, p3, p4) do
# body not decompiled
end
def drawElementsIndirect(p0, p1, p2) do
# body not decompiled
end
def drawElementsInstanced(p0, p1, p2, p3, p4) do
# body not decompiled
end
def drawElementsInstancedBaseInstance(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def drawElementsInstancedBaseVertex(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def drawElementsInstancedBaseVertexBaseInstance(p0, p1, p2, p3, p4, p5, p6) do
# body not decompiled
end
def drawPixels(p0, p1, p2, p3, p4) do
# body not decompiled
end
def drawRangeElements(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def drawRangeElementsBaseVertex(p0, p1, p2, p3, p4, p5, p6) do
# body not decompiled
end
def drawTransformFeedback(p0, p1) do
# body not decompiled
end
def drawTransformFeedbackInstanced(p0, p1, p2) do
# body not decompiled
end
def drawTransformFeedbackStream(p0, p1, p2) do
# body not decompiled
end
def drawTransformFeedbackStreamInstanced(p0, p1, p2, p3) do
# body not decompiled
end
def edgeFlag(p0) do
# body not decompiled
end
def edgeFlagPointer(p0, p1) do
# body not decompiled
end
def edgeFlagv(p0) do
# body not decompiled
end
def enable(p0) do
# body not decompiled
end
def enableClientState(p0) do
# body not decompiled
end
def enableVertexAttribArray(p0) do
# body not decompiled
end
def enablei(p0, p1) do
# body not decompiled
end
def unquote(:end)() do
# body not decompiled
end
def endConditionalRender() do
# body not decompiled
end
def endList() do
# body not decompiled
end
def endQuery(p0) do
# body not decompiled
end
def endQueryIndexed(p0, p1) do
# body not decompiled
end
def endTransformFeedback() do
# body not decompiled
end
def evalCoord1d(p0) do
# body not decompiled
end
def evalCoord1dv(p0) do
# body not decompiled
end
def evalCoord1f(p0) do
# body not decompiled
end
def evalCoord1fv(p0) do
# body not decompiled
end
def evalCoord2d(p0, p1) do
# body not decompiled
end
def evalCoord2dv(p0) do
# body not decompiled
end
def evalCoord2f(p0, p1) do
# body not decompiled
end
def evalCoord2fv(p0) do
# body not decompiled
end
def evalMesh1(p0, p1, p2) do
# body not decompiled
end
def evalMesh2(p0, p1, p2, p3, p4) do
# body not decompiled
end
def evalPoint1(p0) do
# body not decompiled
end
def evalPoint2(p0, p1) do
# body not decompiled
end
def feedbackBuffer(p0, p1, p2) do
# body not decompiled
end
def fenceSync(p0, p1) do
# body not decompiled
end
def finish() do
# body not decompiled
end
def flush() do
# body not decompiled
end
def flushMappedBufferRange(p0, p1, p2) do
# body not decompiled
end
def fogCoordPointer(p0, p1, p2) do
# body not decompiled
end
def fogCoordd(p0) do
# body not decompiled
end
def fogCoorddv(p0) do
# body not decompiled
end
def fogCoordf(p0) do
# body not decompiled
end
def fogCoordfv(p0) do
# body not decompiled
end
def fogf(p0, p1) do
# body not decompiled
end
def fogfv(p0, p1) do
# body not decompiled
end
def fogi(p0, p1) do
# body not decompiled
end
def fogiv(p0, p1) do
# body not decompiled
end
def framebufferRenderbuffer(p0, p1, p2, p3) do
# body not decompiled
end
def framebufferTexture(p0, p1, p2, p3) do
# body not decompiled
end
def framebufferTexture1D(p0, p1, p2, p3, p4) do
# body not decompiled
end
def framebufferTexture2D(p0, p1, p2, p3, p4) do
# body not decompiled
end
def framebufferTexture3D(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def framebufferTextureFaceARB(p0, p1, p2, p3, p4) do
# body not decompiled
end
def framebufferTextureLayer(p0, p1, p2, p3, p4) do
# body not decompiled
end
def frontFace(p0) do
# body not decompiled
end
def frustum(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def genBuffers(p0) do
# body not decompiled
end
def genFramebuffers(p0) do
# body not decompiled
end
def genLists(p0) do
# body not decompiled
end
def genProgramPipelines(p0) do
# body not decompiled
end
def genProgramsARB(p0) do
# body not decompiled
end
def genQueries(p0) do
# body not decompiled
end
def genRenderbuffers(p0) do
# body not decompiled
end
def genSamplers(p0) do
# body not decompiled
end
def genTextures(p0) do
# body not decompiled
end
def genTransformFeedbacks(p0) do
# body not decompiled
end
def genVertexArrays(p0) do
# body not decompiled
end
def generateMipmap(p0) do
# body not decompiled
end
def getActiveAttrib(p0, p1, p2) do
# body not decompiled
end
def getActiveAttribARB(p0, p1, p2) do
# body not decompiled
end
def getActiveSubroutineName(p0, p1, p2, p3) do
# body not decompiled
end
def getActiveSubroutineUniformName(p0, p1, p2, p3) do
# body not decompiled
end
def getActiveUniform(p0, p1, p2) do
# body not decompiled
end
def getActiveUniformARB(p0, p1, p2) do
# body not decompiled
end
def getActiveUniformBlockName(p0, p1, p2) do
# body not decompiled
end
def getActiveUniformBlockiv(p0, p1, p2, p3) do
# body not decompiled
end
def getActiveUniformName(p0, p1, p2) do
# body not decompiled
end
def getActiveUniformsiv(p0, p1, p2) do
# body not decompiled
end
def getAttachedObjectsARB(p0, p1) do
# body not decompiled
end
def getAttachedShaders(p0, p1) do
# body not decompiled
end
def getAttribLocation(p0, p1) do
# body not decompiled
end
def getAttribLocationARB(p0, p1) do
# body not decompiled
end
def getBooleani_v(p0, p1) do
# body not decompiled
end
def getBooleanv(p0) do
# body not decompiled
end
def getBufferParameteri64v(p0, p1) do
# body not decompiled
end
def getBufferParameteriv(p0, p1) do
# body not decompiled
end
def getBufferParameterivARB(p0, p1) do
# body not decompiled
end
def getBufferSubData(p0, p1, p2, p3) do
# body not decompiled
end
def getClipPlane(p0) do
# body not decompiled
end
def getColorTable(p0, p1, p2, p3) do
# body not decompiled
end
def getColorTableParameterfv(p0, p1) do
# body not decompiled
end
def getColorTableParameteriv(p0, p1) do
# body not decompiled
end
def getCompressedTexImage(p0, p1, p2) do
# body not decompiled
end
def getConvolutionFilter(p0, p1, p2, p3) do
# body not decompiled
end
def getConvolutionParameterfv(p0, p1) do
# body not decompiled
end
def getConvolutionParameteriv(p0, p1) do
# body not decompiled
end
def getDebugMessageLogARB(p0, p1) do
# body not decompiled
end
def getDoublei_v(p0, p1) do
# body not decompiled
end
def getDoublev(p0) do
# body not decompiled
end
def getError() do
# body not decompiled
end
def getFloati_v(p0, p1) do
# body not decompiled
end
def getFloatv(p0) do
# body not decompiled
end
def getFragDataIndex(p0, p1) do
# body not decompiled
end
def getFragDataLocation(p0, p1) do
# body not decompiled
end
def getFramebufferAttachmentParameteriv(p0, p1, p2) do
# body not decompiled
end
def getGraphicsResetStatusARB() do
# body not decompiled
end
def getHandleARB(p0) do
# body not decompiled
end
def getHistogram(p0, p1, p2, p3, p4) do
# body not decompiled
end
def getHistogramParameterfv(p0, p1) do
# body not decompiled
end
def getHistogramParameteriv(p0, p1) do
# body not decompiled
end
def getInfoLogARB(p0, p1) do
# body not decompiled
end
def getInteger64i_v(p0, p1) do
# body not decompiled
end
def getInteger64v(p0) do
# body not decompiled
end
def getIntegeri_v(p0, p1) do
# body not decompiled
end
def getIntegerv(p0) do
# body not decompiled
end
def getInternalformativ(p0, p1, p2, p3) do
# body not decompiled
end
def getLightfv(p0, p1) do
# body not decompiled
end
def getLightiv(p0, p1) do
# body not decompiled
end
def getMapdv(p0, p1, p2) do
# body not decompiled
end
def getMapfv(p0, p1, p2) do
# body not decompiled
end
def getMapiv(p0, p1, p2) do
# body not decompiled
end
def getMaterialfv(p0, p1) do
# body not decompiled
end
def getMaterialiv(p0, p1) do
# body not decompiled
end
def getMinmax(p0, p1, p2, p3, p4) do
# body not decompiled
end
def getMinmaxParameterfv(p0, p1) do
# body not decompiled
end
def getMinmaxParameteriv(p0, p1) do
# body not decompiled
end
def getMultisamplefv(p0, p1) do
# body not decompiled
end
def getNamedStringARB(p0, p1) do
# body not decompiled
end
def getNamedStringivARB(p0, p1) do
# body not decompiled
end
def getObjectParameterfvARB(p0, p1) do
# body not decompiled
end
def getObjectParameterivARB(p0, p1) do
# body not decompiled
end
def getPixelMapfv(p0, p1) do
# body not decompiled
end
def getPixelMapuiv(p0, p1) do
# body not decompiled
end
def getPixelMapusv(p0, p1) do
# body not decompiled
end
def getPolygonStipple() do
# body not decompiled
end
def getProgramBinary(p0, p1) do
# body not decompiled
end
def getProgramEnvParameterdvARB(p0, p1) do
# body not decompiled
end
def getProgramEnvParameterfvARB(p0, p1) do
# body not decompiled
end
def getProgramInfoLog(p0, p1) do
# body not decompiled
end
def getProgramLocalParameterdvARB(p0, p1) do
# body not decompiled
end
def getProgramLocalParameterfvARB(p0, p1) do
# body not decompiled
end
def getProgramPipelineInfoLog(p0, p1) do
# body not decompiled
end
def getProgramPipelineiv(p0, p1) do
# body not decompiled
end
def getProgramStageiv(p0, p1, p2) do
# body not decompiled
end
def getProgramStringARB(p0, p1, p2) do
# body not decompiled
end
def getProgramiv(p0, p1) do
# body not decompiled
end
def getQueryIndexediv(p0, p1, p2) do
# body not decompiled
end
def getQueryObjecti64v(p0, p1) do
# body not decompiled
end
def getQueryObjectiv(p0, p1) do
# body not decompiled
end
def getQueryObjectui64v(p0, p1) do
# body not decompiled
end
def getQueryObjectuiv(p0, p1) do
# body not decompiled
end
def getQueryiv(p0, p1) do
# body not decompiled
end
def getRenderbufferParameteriv(p0, p1) do
# body not decompiled
end
def getSamplerParameterIiv(p0, p1) do
# body not decompiled
end
def getSamplerParameterIuiv(p0, p1) do
# body not decompiled
end
def getSamplerParameterfv(p0, p1) do
# body not decompiled
end
def getSamplerParameteriv(p0, p1) do
# body not decompiled
end
def getShaderInfoLog(p0, p1) do
# body not decompiled
end
def getShaderPrecisionFormat(p0, p1) do
# body not decompiled
end
def getShaderSource(p0, p1) do
# body not decompiled
end
def getShaderSourceARB(p0, p1) do
# body not decompiled
end
def getShaderiv(p0, p1) do
# body not decompiled
end
def getString(p0) do
# body not decompiled
end
def getStringi(p0, p1) do
# body not decompiled
end
def getSubroutineIndex(p0, p1, p2) do
# body not decompiled
end
def getSubroutineUniformLocation(p0, p1, p2) do
# body not decompiled
end
def getSynciv(p0, p1, p2) do
# body not decompiled
end
def getTexEnvfv(p0, p1) do
# body not decompiled
end
def getTexEnviv(p0, p1) do
# body not decompiled
end
def getTexGendv(p0, p1) do
# body not decompiled
end
def getTexGenfv(p0, p1) do
# body not decompiled
end
def getTexGeniv(p0, p1) do
# body not decompiled
end
def getTexImage(p0, p1, p2, p3, p4) do
# body not decompiled
end
def getTexLevelParameterfv(p0, p1, p2) do
# body not decompiled
end
def getTexLevelParameteriv(p0, p1, p2) do
# body not decompiled
end
def getTexParameterIiv(p0, p1) do
# body not decompiled
end
def getTexParameterIuiv(p0, p1) do
# body not decompiled
end
def getTexParameterfv(p0, p1) do
# body not decompiled
end
def getTexParameteriv(p0, p1) do
# body not decompiled
end
def getTransformFeedbackVarying(p0, p1, p2) do
# body not decompiled
end
def getUniformBlockIndex(p0, p1) do
# body not decompiled
end
def getUniformIndices(p0, p1) do
# body not decompiled
end
def getUniformLocation(p0, p1) do
# body not decompiled
end
def getUniformLocationARB(p0, p1) do
# body not decompiled
end
def getUniformSubroutineuiv(p0, p1) do
# body not decompiled
end
def getUniformdv(p0, p1) do
# body not decompiled
end
def getUniformfv(p0, p1) do
# body not decompiled
end
def getUniformfvARB(p0, p1) do
# body not decompiled
end
def getUniformiv(p0, p1) do
# body not decompiled
end
def getUniformivARB(p0, p1) do
# body not decompiled
end
def getUniformuiv(p0, p1) do
# body not decompiled
end
def getVertexAttribIiv(p0, p1) do
# body not decompiled
end
def getVertexAttribIuiv(p0, p1) do
# body not decompiled
end
def getVertexAttribLdv(p0, p1) do
# body not decompiled
end
def getVertexAttribdv(p0, p1) do
# body not decompiled
end
def getVertexAttribfv(p0, p1) do
# body not decompiled
end
def getVertexAttribiv(p0, p1) do
# body not decompiled
end
def hint(p0, p1) do
# body not decompiled
end
def histogram(p0, p1, p2, p3) do
# body not decompiled
end
def indexMask(p0) do
# body not decompiled
end
def indexPointer(p0, p1, p2) do
# body not decompiled
end
def indexd(p0) do
# body not decompiled
end
def indexdv(p0) do
# body not decompiled
end
def indexf(p0) do
# body not decompiled
end
def indexfv(p0) do
# body not decompiled
end
def indexi(p0) do
# body not decompiled
end
def indexiv(p0) do
# body not decompiled
end
def indexs(p0) do
# body not decompiled
end
def indexsv(p0) do
# body not decompiled
end
def indexub(p0) do
# body not decompiled
end
def indexubv(p0) do
# body not decompiled
end
def initNames() do
# body not decompiled
end
def interleavedArrays(p0, p1, p2) do
# body not decompiled
end
def isBuffer(p0) do
# body not decompiled
end
def isEnabled(p0) do
# body not decompiled
end
def isEnabledi(p0, p1) do
# body not decompiled
end
def isFramebuffer(p0) do
# body not decompiled
end
def isList(p0) do
# body not decompiled
end
def isNamedStringARB(p0) do
# body not decompiled
end
def isProgram(p0) do
# body not decompiled
end
def isProgramPipeline(p0) do
# body not decompiled
end
def isQuery(p0) do
# body not decompiled
end
def isRenderbuffer(p0) do
# body not decompiled
end
def isSampler(p0) do
# body not decompiled
end
def isShader(p0) do
# body not decompiled
end
def isSync(p0) do
# body not decompiled
end
def isTexture(p0) do
# body not decompiled
end
def isTransformFeedback(p0) do
# body not decompiled
end
def isVertexArray(p0) do
# body not decompiled
end
def lightModelf(p0, p1) do
# body not decompiled
end
def lightModelfv(p0, p1) do
# body not decompiled
end
def lightModeli(p0, p1) do
# body not decompiled
end
def lightModeliv(p0, p1) do
# body not decompiled
end
def lightf(p0, p1, p2) do
# body not decompiled
end
def lightfv(p0, p1, p2) do
# body not decompiled
end
def lighti(p0, p1, p2) do
# body not decompiled
end
def lightiv(p0, p1, p2) do
# body not decompiled
end
def lineStipple(p0, p1) do
# body not decompiled
end
def lineWidth(p0) do
# body not decompiled
end
def linkProgram(p0) do
# body not decompiled
end
def linkProgramARB(p0) do
# body not decompiled
end
def listBase(p0) do
# body not decompiled
end
def loadIdentity() do
# body not decompiled
end
def loadMatrixd(p0) do
# body not decompiled
end
def loadMatrixf(p0) do
# body not decompiled
end
def loadName(p0) do
# body not decompiled
end
def loadTransposeMatrixd(p0) do
# body not decompiled
end
def loadTransposeMatrixdARB(p0) do
# body not decompiled
end
def loadTransposeMatrixf(p0) do
# body not decompiled
end
def loadTransposeMatrixfARB(p0) do
# body not decompiled
end
def logicOp(p0) do
# body not decompiled
end
def map1d(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def map1f(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def map2d(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) do
# body not decompiled
end
def map2f(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) do
# body not decompiled
end
def mapGrid1d(p0, p1, p2) do
# body not decompiled
end
def mapGrid1f(p0, p1, p2) do
# body not decompiled
end
def mapGrid2d(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def mapGrid2f(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def materialf(p0, p1, p2) do
# body not decompiled
end
def materialfv(p0, p1, p2) do
# body not decompiled
end
def materiali(p0, p1, p2) do
# body not decompiled
end
def materialiv(p0, p1, p2) do
# body not decompiled
end
def matrixIndexubvARB(p0) do
# body not decompiled
end
def matrixIndexuivARB(p0) do
# body not decompiled
end
def matrixIndexusvARB(p0) do
# body not decompiled
end
def matrixMode(p0) do
# body not decompiled
end
def memoryBarrier(p0) do
# body not decompiled
end
def minSampleShading(p0) do
# body not decompiled
end
def minmax(p0, p1, p2) do
# body not decompiled
end
def module_info() do
# body not decompiled
end
def module_info(p0) do
# body not decompiled
end
def multMatrixd(p0) do
# body not decompiled
end
def multMatrixf(p0) do
# body not decompiled
end
def multTransposeMatrixd(p0) do
# body not decompiled
end
def multTransposeMatrixdARB(p0) do
# body not decompiled
end
def multTransposeMatrixf(p0) do
# body not decompiled
end
def multTransposeMatrixfARB(p0) do
# body not decompiled
end
def multiDrawArrays(p0, p1, p2) do
# body not decompiled
end
def multiTexCoord1d(p0, p1) do
# body not decompiled
end
def multiTexCoord1dv(p0, p1) do
# body not decompiled
end
def multiTexCoord1f(p0, p1) do
# body not decompiled
end
def multiTexCoord1fv(p0, p1) do
# body not decompiled
end
def multiTexCoord1i(p0, p1) do
# body not decompiled
end
def multiTexCoord1iv(p0, p1) do
# body not decompiled
end
def multiTexCoord1s(p0, p1) do
# body not decompiled
end
def multiTexCoord1sv(p0, p1) do
# body not decompiled
end
def multiTexCoord2d(p0, p1, p2) do
# body not decompiled
end
def multiTexCoord2dv(p0, p1) do
# body not decompiled
end
def multiTexCoord2f(p0, p1, p2) do
# body not decompiled
end
def multiTexCoord2fv(p0, p1) do
# body not decompiled
end
def multiTexCoord2i(p0, p1, p2) do
# body not decompiled
end
def multiTexCoord2iv(p0, p1) do
# body not decompiled
end
def multiTexCoord2s(p0, p1, p2) do
# body not decompiled
end
def multiTexCoord2sv(p0, p1) do
# body not decompiled
end
def multiTexCoord3d(p0, p1, p2, p3) do
# body not decompiled
end
def multiTexCoord3dv(p0, p1) do
# body not decompiled
end
def multiTexCoord3f(p0, p1, p2, p3) do
# body not decompiled
end
def multiTexCoord3fv(p0, p1) do
# body not decompiled
end
def multiTexCoord3i(p0, p1, p2, p3) do
# body not decompiled
end
def multiTexCoord3iv(p0, p1) do
# body not decompiled
end
def multiTexCoord3s(p0, p1, p2, p3) do
# body not decompiled
end
def multiTexCoord3sv(p0, p1) do
# body not decompiled
end
def multiTexCoord4d(p0, p1, p2, p3, p4) do
# body not decompiled
end
def multiTexCoord4dv(p0, p1) do
# body not decompiled
end
def multiTexCoord4f(p0, p1, p2, p3, p4) do
# body not decompiled
end
def multiTexCoord4fv(p0, p1) do
# body not decompiled
end
def multiTexCoord4i(p0, p1, p2, p3, p4) do
# body not decompiled
end
def multiTexCoord4iv(p0, p1) do
# body not decompiled
end
def multiTexCoord4s(p0, p1, p2, p3, p4) do
# body not decompiled
end
def multiTexCoord4sv(p0, p1) do
# body not decompiled
end
def namedStringARB(p0, p1, p2) do
# body not decompiled
end
def newList(p0, p1) do
# body not decompiled
end
def normal3b(p0, p1, p2) do
# body not decompiled
end
def normal3bv(p0) do
# body not decompiled
end
def normal3d(p0, p1, p2) do
# body not decompiled
end
def normal3dv(p0) do
# body not decompiled
end
def normal3f(p0, p1, p2) do
# body not decompiled
end
def normal3fv(p0) do
# body not decompiled
end
def normal3i(p0, p1, p2) do
# body not decompiled
end
def normal3iv(p0) do
# body not decompiled
end
def normal3s(p0, p1, p2) do
# body not decompiled
end
def normal3sv(p0) do
# body not decompiled
end
def normalPointer(p0, p1, p2) do
# body not decompiled
end
def ortho(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def passThrough(p0) do
# body not decompiled
end
def patchParameterfv(p0, p1) do
# body not decompiled
end
def patchParameteri(p0, p1) do
# body not decompiled
end
def pauseTransformFeedback() do
# body not decompiled
end
def pixelMapfv(p0, p1, p2) do
# body not decompiled
end
def pixelMapuiv(p0, p1, p2) do
# body not decompiled
end
def pixelMapusv(p0, p1, p2) do
# body not decompiled
end
def pixelStoref(p0, p1) do
# body not decompiled
end
def pixelStorei(p0, p1) do
# body not decompiled
end
def pixelTransferf(p0, p1) do
# body not decompiled
end
def pixelTransferi(p0, p1) do
# body not decompiled
end
def pixelZoom(p0, p1) do
# body not decompiled
end
def pointParameterf(p0, p1) do
# body not decompiled
end
def pointParameterfv(p0, p1) do
# body not decompiled
end
def pointParameteri(p0, p1) do
# body not decompiled
end
def pointParameteriv(p0, p1) do
# body not decompiled
end
def pointSize(p0) do
# body not decompiled
end
def polygonMode(p0, p1) do
# body not decompiled
end
def polygonOffset(p0, p1) do
# body not decompiled
end
def polygonStipple(p0) do
# body not decompiled
end
def popAttrib() do
# body not decompiled
end
def popClientAttrib() do
# body not decompiled
end
def popMatrix() do
# body not decompiled
end
def popName() do
# body not decompiled
end
def primitiveRestartIndex(p0) do
# body not decompiled
end
def prioritizeTextures(p0, p1) do
# body not decompiled
end
def programBinary(p0, p1, p2) do
# body not decompiled
end
def programEnvParameter4dARB(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def programEnvParameter4dvARB(p0, p1, p2) do
# body not decompiled
end
def programEnvParameter4fARB(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def programEnvParameter4fvARB(p0, p1, p2) do
# body not decompiled
end
def programLocalParameter4dARB(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def programLocalParameter4dvARB(p0, p1, p2) do
# body not decompiled
end
def programLocalParameter4fARB(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def programLocalParameter4fvARB(p0, p1, p2) do
# body not decompiled
end
def programParameteri(p0, p1, p2) do
# body not decompiled
end
def programStringARB(p0, p1, p2) do
# body not decompiled
end
def programUniform1d(p0, p1, p2) do
# body not decompiled
end
def programUniform1dv(p0, p1, p2) do
# body not decompiled
end
def programUniform1f(p0, p1, p2) do
# body not decompiled
end
def programUniform1fv(p0, p1, p2) do
# body not decompiled
end
def programUniform1i(p0, p1, p2) do
# body not decompiled
end
def programUniform1iv(p0, p1, p2) do
# body not decompiled
end
def programUniform1ui(p0, p1, p2) do
# body not decompiled
end
def programUniform1uiv(p0, p1, p2) do
# body not decompiled
end
def programUniform2d(p0, p1, p2, p3) do
# body not decompiled
end
def programUniform2dv(p0, p1, p2) do
# body not decompiled
end
def programUniform2f(p0, p1, p2, p3) do
# body not decompiled
end
def programUniform2fv(p0, p1, p2) do
# body not decompiled
end
def programUniform2i(p0, p1, p2, p3) do
# body not decompiled
end
def programUniform2iv(p0, p1, p2) do
# body not decompiled
end
def programUniform2ui(p0, p1, p2, p3) do
# body not decompiled
end
def programUniform2uiv(p0, p1, p2) do
# body not decompiled
end
def programUniform3d(p0, p1, p2, p3, p4) do
# body not decompiled
end
def programUniform3dv(p0, p1, p2) do
# body not decompiled
end
def programUniform3f(p0, p1, p2, p3, p4) do
# body not decompiled
end
def programUniform3fv(p0, p1, p2) do
# body not decompiled
end
def programUniform3i(p0, p1, p2, p3, p4) do
# body not decompiled
end
def programUniform3iv(p0, p1, p2) do
# body not decompiled
end
def programUniform3ui(p0, p1, p2, p3, p4) do
# body not decompiled
end
def programUniform3uiv(p0, p1, p2) do
# body not decompiled
end
def programUniform4d(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def programUniform4dv(p0, p1, p2) do
# body not decompiled
end
def programUniform4f(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def programUniform4fv(p0, p1, p2) do
# body not decompiled
end
def programUniform4i(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def programUniform4iv(p0, p1, p2) do
# body not decompiled
end
def programUniform4ui(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def programUniform4uiv(p0, p1, p2) do
# body not decompiled
end
def programUniformMatrix2dv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix2fv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix2x3dv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix2x3fv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix2x4dv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix2x4fv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix3dv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix3fv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix3x2dv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix3x2fv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix3x4dv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix3x4fv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix4dv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix4fv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix4x2dv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix4x2fv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix4x3dv(p0, p1, p2, p3) do
# body not decompiled
end
def programUniformMatrix4x3fv(p0, p1, p2, p3) do
# body not decompiled
end
def provokingVertex(p0) do
# body not decompiled
end
def pushAttrib(p0) do
# body not decompiled
end
def pushClientAttrib(p0) do
# body not decompiled
end
def pushMatrix() do
# body not decompiled
end
def pushName(p0) do
# body not decompiled
end
def queryCounter(p0, p1) do
# body not decompiled
end
def rasterPos2d(p0, p1) do
# body not decompiled
end
def rasterPos2dv(p0) do
# body not decompiled
end
def rasterPos2f(p0, p1) do
# body not decompiled
end
def rasterPos2fv(p0) do
# body not decompiled
end
def rasterPos2i(p0, p1) do
# body not decompiled
end
def rasterPos2iv(p0) do
# body not decompiled
end
def rasterPos2s(p0, p1) do
# body not decompiled
end
def rasterPos2sv(p0) do
# body not decompiled
end
def rasterPos3d(p0, p1, p2) do
# body not decompiled
end
def rasterPos3dv(p0) do
# body not decompiled
end
def rasterPos3f(p0, p1, p2) do
# body not decompiled
end
def rasterPos3fv(p0) do
# body not decompiled
end
def rasterPos3i(p0, p1, p2) do
# body not decompiled
end
def rasterPos3iv(p0) do
# body not decompiled
end
def rasterPos3s(p0, p1, p2) do
# body not decompiled
end
def rasterPos3sv(p0) do
# body not decompiled
end
def rasterPos4d(p0, p1, p2, p3) do
# body not decompiled
end
def rasterPos4dv(p0) do
# body not decompiled
end
def rasterPos4f(p0, p1, p2, p3) do
# body not decompiled
end
def rasterPos4fv(p0) do
# body not decompiled
end
def rasterPos4i(p0, p1, p2, p3) do
# body not decompiled
end
def rasterPos4iv(p0) do
# body not decompiled
end
def rasterPos4s(p0, p1, p2, p3) do
# body not decompiled
end
def rasterPos4sv(p0) do
# body not decompiled
end
def readBuffer(p0) do
# body not decompiled
end
def readPixels(p0, p1, p2, p3, p4, p5, p6) do
# body not decompiled
end
def rectd(p0, p1, p2, p3) do
# body not decompiled
end
def rectdv(p0, p1) do
# body not decompiled
end
def rectf(p0, p1, p2, p3) do
# body not decompiled
end
def rectfv(p0, p1) do
# body not decompiled
end
def recti(p0, p1, p2, p3) do
# body not decompiled
end
def rectiv(p0, p1) do
# body not decompiled
end
def rects(p0, p1, p2, p3) do
# body not decompiled
end
def rectsv(p0, p1) do
# body not decompiled
end
def releaseShaderCompiler() do
# body not decompiled
end
def renderMode(p0) do
# body not decompiled
end
def renderbufferStorage(p0, p1, p2, p3) do
# body not decompiled
end
def renderbufferStorageMultisample(p0, p1, p2, p3, p4) do
# body not decompiled
end
def resetHistogram(p0) do
# body not decompiled
end
def resetMinmax(p0) do
# body not decompiled
end
def resumeTransformFeedback() do
# body not decompiled
end
def rotated(p0, p1, p2, p3) do
# body not decompiled
end
def rotatef(p0, p1, p2, p3) do
# body not decompiled
end
def sampleCoverage(p0, p1) do
# body not decompiled
end
def sampleMaski(p0, p1) do
# body not decompiled
end
def samplerParameterIiv(p0, p1, p2) do
# body not decompiled
end
def samplerParameterIuiv(p0, p1, p2) do
# body not decompiled
end
def samplerParameterf(p0, p1, p2) do
# body not decompiled
end
def samplerParameterfv(p0, p1, p2) do
# body not decompiled
end
def samplerParameteri(p0, p1, p2) do
# body not decompiled
end
def samplerParameteriv(p0, p1, p2) do
# body not decompiled
end
def scaled(p0, p1, p2) do
# body not decompiled
end
def scalef(p0, p1, p2) do
# body not decompiled
end
def scissor(p0, p1, p2, p3) do
# body not decompiled
end
def scissorArrayv(p0, p1) do
# body not decompiled
end
def scissorIndexed(p0, p1, p2, p3, p4) do
# body not decompiled
end
def scissorIndexedv(p0, p1) do
# body not decompiled
end
def secondaryColor3b(p0, p1, p2) do
# body not decompiled
end
def secondaryColor3bv(p0) do
# body not decompiled
end
def secondaryColor3d(p0, p1, p2) do
# body not decompiled
end
def secondaryColor3dv(p0) do
# body not decompiled
end
def secondaryColor3f(p0, p1, p2) do
# body not decompiled
end
def secondaryColor3fv(p0) do
# body not decompiled
end
def secondaryColor3i(p0, p1, p2) do
# body not decompiled
end
def secondaryColor3iv(p0) do
# body not decompiled
end
def secondaryColor3s(p0, p1, p2) do
# body not decompiled
end
def secondaryColor3sv(p0) do
# body not decompiled
end
def secondaryColor3ub(p0, p1, p2) do
# body not decompiled
end
def secondaryColor3ubv(p0) do
# body not decompiled
end
def secondaryColor3ui(p0, p1, p2) do
# body not decompiled
end
def secondaryColor3uiv(p0) do
# body not decompiled
end
def secondaryColor3us(p0, p1, p2) do
# body not decompiled
end
def secondaryColor3usv(p0) do
# body not decompiled
end
def secondaryColorPointer(p0, p1, p2, p3) do
# body not decompiled
end
def selectBuffer(p0, p1) do
# body not decompiled
end
def send_bin(p0) do
# body not decompiled
end
def separableFilter2D(p0, p1, p2, p3, p4, p5, p6, p7) do
# body not decompiled
end
def shadeModel(p0) do
# body not decompiled
end
def shaderBinary(p0, p1, p2) do
# body not decompiled
end
def shaderSource(p0, p1) do
# body not decompiled
end
def shaderSourceARB(p0, p1) do
# body not decompiled
end
def stencilClearTagEXT(p0, p1) do
# body not decompiled
end
def stencilFunc(p0, p1, p2) do
# body not decompiled
end
def stencilFuncSeparate(p0, p1, p2, p3) do
# body not decompiled
end
def stencilMask(p0) do
# body not decompiled
end
def stencilMaskSeparate(p0, p1) do
# body not decompiled
end
def stencilOp(p0, p1, p2) do
# body not decompiled
end
def stencilOpSeparate(p0, p1, p2, p3) do
# body not decompiled
end
def texBuffer(p0, p1, p2) do
# body not decompiled
end
def texCoord1d(p0) do
# body not decompiled
end
def texCoord1dv(p0) do
# body not decompiled
end
def texCoord1f(p0) do
# body not decompiled
end
def texCoord1fv(p0) do
# body not decompiled
end
def texCoord1i(p0) do
# body not decompiled
end
def texCoord1iv(p0) do
# body not decompiled
end
def texCoord1s(p0) do
# body not decompiled
end
def texCoord1sv(p0) do
# body not decompiled
end
def texCoord2d(p0, p1) do
# body not decompiled
end
def texCoord2dv(p0) do
# body not decompiled
end
def texCoord2f(p0, p1) do
# body not decompiled
end
def texCoord2fv(p0) do
# body not decompiled
end
def texCoord2i(p0, p1) do
# body not decompiled
end
def texCoord2iv(p0) do
# body not decompiled
end
def texCoord2s(p0, p1) do
# body not decompiled
end
def texCoord2sv(p0) do
# body not decompiled
end
def texCoord3d(p0, p1, p2) do
# body not decompiled
end
def texCoord3dv(p0) do
# body not decompiled
end
def texCoord3f(p0, p1, p2) do
# body not decompiled
end
def texCoord3fv(p0) do
# body not decompiled
end
def texCoord3i(p0, p1, p2) do
# body not decompiled
end
def texCoord3iv(p0) do
# body not decompiled
end
def texCoord3s(p0, p1, p2) do
# body not decompiled
end
def texCoord3sv(p0) do
# body not decompiled
end
def texCoord4d(p0, p1, p2, p3) do
# body not decompiled
end
def texCoord4dv(p0) do
# body not decompiled
end
def texCoord4f(p0, p1, p2, p3) do
# body not decompiled
end
def texCoord4fv(p0) do
# body not decompiled
end
def texCoord4i(p0, p1, p2, p3) do
# body not decompiled
end
def texCoord4iv(p0) do
# body not decompiled
end
def texCoord4s(p0, p1, p2, p3) do
# body not decompiled
end
def texCoord4sv(p0) do
# body not decompiled
end
def texCoordPointer(p0, p1, p2, p3) do
# body not decompiled
end
def texEnvf(p0, p1, p2) do
# body not decompiled
end
def texEnvfv(p0, p1, p2) do
# body not decompiled
end
def texEnvi(p0, p1, p2) do
# body not decompiled
end
def texEnviv(p0, p1, p2) do
# body not decompiled
end
def texGend(p0, p1, p2) do
# body not decompiled
end
def texGendv(p0, p1, p2) do
# body not decompiled
end
def texGenf(p0, p1, p2) do
# body not decompiled
end
def texGenfv(p0, p1, p2) do
# body not decompiled
end
def texGeni(p0, p1, p2) do
# body not decompiled
end
def texGeniv(p0, p1, p2) do
# body not decompiled
end
def texImage1D(p0, p1, p2, p3, p4, p5, p6, p7) do
# body not decompiled
end
def texImage2D(p0, p1, p2, p3, p4, p5, p6, p7, p8) do
# body not decompiled
end
def texImage2DMultisample(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def texImage3D(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) do
# body not decompiled
end
def texImage3DMultisample(p0, p1, p2, p3, p4, p5, p6) do
# body not decompiled
end
def texParameterIiv(p0, p1, p2) do
# body not decompiled
end
def texParameterIuiv(p0, p1, p2) do
# body not decompiled
end
def texParameterf(p0, p1, p2) do
# body not decompiled
end
def texParameterfv(p0, p1, p2) do
# body not decompiled
end
def texParameteri(p0, p1, p2) do
# body not decompiled
end
def texParameteriv(p0, p1, p2) do
# body not decompiled
end
def texStorage1D(p0, p1, p2, p3) do
# body not decompiled
end
def texStorage2D(p0, p1, p2, p3, p4) do
# body not decompiled
end
def texStorage3D(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def texSubImage1D(p0, p1, p2, p3, p4, p5, p6) do
# body not decompiled
end
def texSubImage2D(p0, p1, p2, p3, p4, p5, p6, p7, p8) do
# body not decompiled
end
def texSubImage3D(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) do
# body not decompiled
end
def transformFeedbackVaryings(p0, p1, p2) do
# body not decompiled
end
def translated(p0, p1, p2) do
# body not decompiled
end
def translatef(p0, p1, p2) do
# body not decompiled
end
def uniform1d(p0, p1) do
# body not decompiled
end
def uniform1dv(p0, p1) do
# body not decompiled
end
def uniform1f(p0, p1) do
# body not decompiled
end
def uniform1fv(p0, p1) do
# body not decompiled
end
def uniform1i(p0, p1) do
# body not decompiled
end
def uniform1iv(p0, p1) do
# body not decompiled
end
def uniform1ui(p0, p1) do
# body not decompiled
end
def uniform1uiv(p0, p1) do
# body not decompiled
end
def uniform2d(p0, p1, p2) do
# body not decompiled
end
def uniform2dv(p0, p1) do
# body not decompiled
end
def uniform2f(p0, p1, p2) do
# body not decompiled
end
def uniform2fv(p0, p1) do
# body not decompiled
end
def uniform2i(p0, p1, p2) do
# body not decompiled
end
def uniform2iv(p0, p1) do
# body not decompiled
end
def uniform2ui(p0, p1, p2) do
# body not decompiled
end
def uniform2uiv(p0, p1) do
# body not decompiled
end
def uniform3d(p0, p1, p2, p3) do
# body not decompiled
end
def uniform3dv(p0, p1) do
# body not decompiled
end
def uniform3f(p0, p1, p2, p3) do
# body not decompiled
end
def uniform3fv(p0, p1) do
# body not decompiled
end
def uniform3i(p0, p1, p2, p3) do
# body not decompiled
end
def uniform3iv(p0, p1) do
# body not decompiled
end
def uniform3ui(p0, p1, p2, p3) do
# body not decompiled
end
def uniform3uiv(p0, p1) do
# body not decompiled
end
def uniform4d(p0, p1, p2, p3, p4) do
# body not decompiled
end
def uniform4dv(p0, p1) do
# body not decompiled
end
def uniform4f(p0, p1, p2, p3, p4) do
# body not decompiled
end
def uniform4fv(p0, p1) do
# body not decompiled
end
def uniform4i(p0, p1, p2, p3, p4) do
# body not decompiled
end
def uniform4iv(p0, p1) do
# body not decompiled
end
def uniform4ui(p0, p1, p2, p3, p4) do
# body not decompiled
end
def uniform4uiv(p0, p1) do
# body not decompiled
end
def uniformBlockBinding(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix2dv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix2fv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix2x3dv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix2x3fv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix2x4dv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix2x4fv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix3dv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix3fv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix3x2dv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix3x2fv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix3x4dv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix3x4fv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix4dv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix4fv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix4x2dv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix4x2fv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix4x3dv(p0, p1, p2) do
# body not decompiled
end
def uniformMatrix4x3fv(p0, p1, p2) do
# body not decompiled
end
def uniformSubroutinesuiv(p0, p1) do
# body not decompiled
end
def useProgram(p0) do
# body not decompiled
end
def useProgramObjectARB(p0) do
# body not decompiled
end
def useProgramStages(p0, p1, p2) do
# body not decompiled
end
def validateProgram(p0) do
# body not decompiled
end
def validateProgramARB(p0) do
# body not decompiled
end
def validateProgramPipeline(p0) do
# body not decompiled
end
def vertex2d(p0, p1) do
# body not decompiled
end
def vertex2dv(p0) do
# body not decompiled
end
def vertex2f(p0, p1) do
# body not decompiled
end
def vertex2fv(p0) do
# body not decompiled
end
def vertex2i(p0, p1) do
# body not decompiled
end
def vertex2iv(p0) do
# body not decompiled
end
def vertex2s(p0, p1) do
# body not decompiled
end
def vertex2sv(p0) do
# body not decompiled
end
def vertex3d(p0, p1, p2) do
# body not decompiled
end
def vertex3dv(p0) do
# body not decompiled
end
def vertex3f(p0, p1, p2) do
# body not decompiled
end
def vertex3fv(p0) do
# body not decompiled
end
def vertex3i(p0, p1, p2) do
# body not decompiled
end
def vertex3iv(p0) do
# body not decompiled
end
def vertex3s(p0, p1, p2) do
# body not decompiled
end
def vertex3sv(p0) do
# body not decompiled
end
def vertex4d(p0, p1, p2, p3) do
# body not decompiled
end
def vertex4dv(p0) do
# body not decompiled
end
def vertex4f(p0, p1, p2, p3) do
# body not decompiled
end
def vertex4fv(p0) do
# body not decompiled
end
def vertex4i(p0, p1, p2, p3) do
# body not decompiled
end
def vertex4iv(p0) do
# body not decompiled
end
def vertex4s(p0, p1, p2, p3) do
# body not decompiled
end
def vertex4sv(p0) do
# body not decompiled
end
def vertexAttrib1d(p0, p1) do
# body not decompiled
end
def vertexAttrib1dv(p0, p1) do
# body not decompiled
end
def vertexAttrib1f(p0, p1) do
# body not decompiled
end
def vertexAttrib1fv(p0, p1) do
# body not decompiled
end
def vertexAttrib1s(p0, p1) do
# body not decompiled
end
def vertexAttrib1sv(p0, p1) do
# body not decompiled
end
def vertexAttrib2d(p0, p1, p2) do
# body not decompiled
end
def vertexAttrib2dv(p0, p1) do
# body not decompiled
end
def vertexAttrib2f(p0, p1, p2) do
# body not decompiled
end
def vertexAttrib2fv(p0, p1) do
# body not decompiled
end
def vertexAttrib2s(p0, p1, p2) do
# body not decompiled
end
def vertexAttrib2sv(p0, p1) do
# body not decompiled
end
def vertexAttrib3d(p0, p1, p2, p3) do
# body not decompiled
end
def vertexAttrib3dv(p0, p1) do
# body not decompiled
end
def vertexAttrib3f(p0, p1, p2, p3) do
# body not decompiled
end
def vertexAttrib3fv(p0, p1) do
# body not decompiled
end
def vertexAttrib3s(p0, p1, p2, p3) do
# body not decompiled
end
def vertexAttrib3sv(p0, p1) do
# body not decompiled
end
def vertexAttrib4Nbv(p0, p1) do
# body not decompiled
end
def vertexAttrib4Niv(p0, p1) do
# body not decompiled
end
def vertexAttrib4Nsv(p0, p1) do
# body not decompiled
end
def vertexAttrib4Nub(p0, p1, p2, p3, p4) do
# body not decompiled
end
def vertexAttrib4Nubv(p0, p1) do
# body not decompiled
end
def vertexAttrib4Nuiv(p0, p1) do
# body not decompiled
end
def vertexAttrib4Nusv(p0, p1) do
# body not decompiled
end
def vertexAttrib4bv(p0, p1) do
# body not decompiled
end
def vertexAttrib4d(p0, p1, p2, p3, p4) do
# body not decompiled
end
def vertexAttrib4dv(p0, p1) do
# body not decompiled
end
def vertexAttrib4f(p0, p1, p2, p3, p4) do
# body not decompiled
end
def vertexAttrib4fv(p0, p1) do
# body not decompiled
end
def vertexAttrib4iv(p0, p1) do
# body not decompiled
end
def vertexAttrib4s(p0, p1, p2, p3, p4) do
# body not decompiled
end
def vertexAttrib4sv(p0, p1) do
# body not decompiled
end
def vertexAttrib4ubv(p0, p1) do
# body not decompiled
end
def vertexAttrib4uiv(p0, p1) do
# body not decompiled
end
def vertexAttrib4usv(p0, p1) do
# body not decompiled
end
def vertexAttribDivisor(p0, p1) do
# body not decompiled
end
def vertexAttribI1i(p0, p1) do
# body not decompiled
end
def vertexAttribI1iv(p0, p1) do
# body not decompiled
end
def vertexAttribI1ui(p0, p1) do
# body not decompiled
end
def vertexAttribI1uiv(p0, p1) do
# body not decompiled
end
def vertexAttribI2i(p0, p1, p2) do
# body not decompiled
end
def vertexAttribI2iv(p0, p1) do
# body not decompiled
end
def vertexAttribI2ui(p0, p1, p2) do
# body not decompiled
end
def vertexAttribI2uiv(p0, p1) do
# body not decompiled
end
def vertexAttribI3i(p0, p1, p2, p3) do
# body not decompiled
end
def vertexAttribI3iv(p0, p1) do
# body not decompiled
end
def vertexAttribI3ui(p0, p1, p2, p3) do
# body not decompiled
end
def vertexAttribI3uiv(p0, p1) do
# body not decompiled
end
def vertexAttribI4bv(p0, p1) do
# body not decompiled
end
def vertexAttribI4i(p0, p1, p2, p3, p4) do
# body not decompiled
end
def vertexAttribI4iv(p0, p1) do
# body not decompiled
end
def vertexAttribI4sv(p0, p1) do
# body not decompiled
end
def vertexAttribI4ubv(p0, p1) do
# body not decompiled
end
def vertexAttribI4ui(p0, p1, p2, p3, p4) do
# body not decompiled
end
def vertexAttribI4uiv(p0, p1) do
# body not decompiled
end
def vertexAttribI4usv(p0, p1) do
# body not decompiled
end
def vertexAttribIPointer(p0, p1, p2, p3, p4) do
# body not decompiled
end
def vertexAttribL1d(p0, p1) do
# body not decompiled
end
def vertexAttribL1dv(p0, p1) do
# body not decompiled
end
def vertexAttribL2d(p0, p1, p2) do
# body not decompiled
end
def vertexAttribL2dv(p0, p1) do
# body not decompiled
end
def vertexAttribL3d(p0, p1, p2, p3) do
# body not decompiled
end
def vertexAttribL3dv(p0, p1) do
# body not decompiled
end
def vertexAttribL4d(p0, p1, p2, p3, p4) do
# body not decompiled
end
def vertexAttribL4dv(p0, p1) do
# body not decompiled
end
def vertexAttribLPointer(p0, p1, p2, p3, p4) do
# body not decompiled
end
def vertexAttribPointer(p0, p1, p2, p3, p4, p5) do
# body not decompiled
end
def vertexBlendARB(p0) do
# body not decompiled
end
def vertexPointer(p0, p1, p2, p3) do
# body not decompiled
end
def viewport(p0, p1, p2, p3) do
# body not decompiled
end
def viewportArrayv(p0, p1) do
# body not decompiled
end
def viewportIndexedf(p0, p1, p2, p3, p4) do
# body not decompiled
end
def viewportIndexedfv(p0, p1) do
# body not decompiled
end
def waitSync(p0, p1, p2) do
# body not decompiled
end
def weightbvARB(p0) do
# body not decompiled
end
def weightdvARB(p0) do
# body not decompiled
end
def weightfvARB(p0) do
# body not decompiled
end
def weightivARB(p0) do
# body not decompiled
end
def weightsvARB(p0) do
# body not decompiled
end
def weightubvARB(p0) do
# body not decompiled
end
def weightuivARB(p0) do
# body not decompiled
end
def weightusvARB(p0) do
# body not decompiled
end
def windowPos2d(p0, p1) do
# body not decompiled
end
def windowPos2dv(p0) do
# body not decompiled
end
def windowPos2f(p0, p1) do
# body not decompiled
end
def windowPos2fv(p0) do
# body not decompiled
end
def windowPos2i(p0, p1) do
# body not decompiled
end
def windowPos2iv(p0) do
# body not decompiled
end
def windowPos2s(p0, p1) do
# body not decompiled
end
def windowPos2sv(p0) do
# body not decompiled
end
def windowPos3d(p0, p1, p2) do
# body not decompiled
end
def windowPos3dv(p0) do
# body not decompiled
end
def windowPos3f(p0, p1, p2) do
# body not decompiled
end
def windowPos3fv(p0) do
# body not decompiled
end
def windowPos3i(p0, p1, p2) do
# body not decompiled
end
def windowPos3iv(p0) do
# body not decompiled
end
def windowPos3s(p0, p1, p2) do
# body not decompiled
end
def windowPos3sv(p0) do
# body not decompiled
end
# Private Functions
defp unquote(:"-areTexturesResident/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-callLists/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-clearBufferfv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-clearBufferiv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-clearBufferuiv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-compileShaderIncludeARB/2-lc$^0/1-0-")(p0) do
# body not decompiled
end
defp unquote(:"-convolutionParameterf/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-convolutionParameteri/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-createShaderProgramv/2-lc$^0/1-0-")(p0) do
# body not decompiled
end
defp unquote(:"-debugMessageControlARB/5-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-deleteBuffers/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-deleteFramebuffers/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-deleteProgramPipelines/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-deleteProgramsARB/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-deleteQueries/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-deleteRenderbuffers/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-deleteSamplers/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-deleteTextures/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-deleteTransformFeedbacks/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-deleteVertexArrays/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-depthRangeArrayv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-drawBuffers/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-fogfv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-fogiv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-getActiveUniformsiv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-getUniformIndices/2-lc$^0/1-0-")(p0) do
# body not decompiled
end
defp unquote(:"-lightModelfv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-lightModeliv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-lightfv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-lightiv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-materialfv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-materialiv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-matrixIndexubvARB/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-matrixIndexuivARB/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-matrixIndexusvARB/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-multiDrawArrays/3-lbc$^0/2-1-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-multiDrawArrays/3-lbc$^1/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-patchParameterfv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-pointParameterfv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-pointParameteriv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-prioritizeTextures/2-lbc$^0/2-1-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-prioritizeTextures/2-lbc$^1/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform1dv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform1fv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform1iv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform1uiv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform2dv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform2fv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform2iv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform2uiv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform3dv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform3fv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform3iv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform3uiv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform4dv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform4fv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform4iv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniform4uiv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix2dv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix2fv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix2x3dv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix2x3fv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix2x4dv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix2x4fv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix3dv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix3fv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix3x2dv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix3x2fv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix3x4dv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix3x4fv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix4dv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix4fv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix4x2dv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix4x2fv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix4x3dv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-programUniformMatrix4x3fv/4-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-samplerParameterIiv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-samplerParameterIuiv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-samplerParameterfv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-samplerParameteriv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-scissorArrayv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-shaderBinary/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-shaderSource/2-lc$^0/1-0-")(p0) do
# body not decompiled
end
defp unquote(:"-shaderSourceARB/2-lc$^0/1-0-")(p0) do
# body not decompiled
end
defp unquote(:"-texEnvfv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-texEnviv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-texGendv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-texGenfv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-texGeniv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-texParameterIiv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-texParameterIuiv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-texParameterfv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-texParameteriv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-transformFeedbackVaryings/3-lc$^0/1-0-")(p0) do
# body not decompiled
end
defp unquote(:"-uniform1dv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniform1fv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniform1iv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniform1uiv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniform2dv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniform2fv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniform2iv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniform2uiv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniform3dv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniform3fv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniform3iv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniform3uiv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniform4dv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniform4fv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniform4iv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniform4uiv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix2dv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix2fv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix2x3dv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix2x3fv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix2x4dv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix2x4fv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix3dv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix3fv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix3x2dv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix3x2fv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix3x4dv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix3x4fv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix4dv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix4fv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix4x2dv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix4x2fv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix4x3dv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformMatrix4x3fv/3-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-uniformSubroutinesuiv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-viewportArrayv/2-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-weightbvARB/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-weightdvARB/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-weightfvARB/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-weightivARB/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-weightsvARB/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-weightubvARB/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-weightuivARB/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp unquote(:"-weightusvARB/1-lbc$^0/2-0-")(p0, p1) do
# body not decompiled
end
defp rec(p0) do
# body not decompiled
end
end
| 17.726168 | 80 | 0.652344 |
0811128be681f497509403f4aa8b5afa0787f187 | 867 | exs | Elixir | peep_blog_api/config/config.exs | ultimatemonty/embloginator | b1b25374d56899e054e6df73a3841d388d095d83 | [
"MIT"
] | null | null | null | peep_blog_api/config/config.exs | ultimatemonty/embloginator | b1b25374d56899e054e6df73a3841d388d095d83 | [
"MIT"
] | null | null | null | peep_blog_api/config/config.exs | ultimatemonty/embloginator | b1b25374d56899e054e6df73a3841d388d095d83 | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
use Mix.Config
# Configures the endpoint
config :peep_blog_api, PeepBlogApi.Endpoint,
url: [host: "localhost"],
root: Path.dirname(__DIR__),
secret_key_base: "WWDggcIcAhiL7Rhywweav77PHN8nAc4H4mV2715YnByvP5B0sGmm0Li+mYJrqBqA",
render_errors: [accepts: ~w(html json)],
pubsub: [name: PeepBlogApi.PubSub,
adapter: Phoenix.PubSub.PG2]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"
| 34.68 | 86 | 0.761246 |
081118d427a3aae02f5d79617dd4bd50098af6ee | 6,220 | ex | Elixir | lib/quadquizaminos_web/live/privacy_live.ex | sparrell/quizquadaminos | 6388252b7c32aa4101486cbf45d0d57d4e3a79da | [
"MIT"
] | null | null | null | lib/quadquizaminos_web/live/privacy_live.ex | sparrell/quizquadaminos | 6388252b7c32aa4101486cbf45d0d57d4e3a79da | [
"MIT"
] | 9 | 2022-03-14T07:29:25.000Z | 2022-03-30T07:39:16.000Z | lib/quadquizaminos_web/live/privacy_live.ex | sparrell/quizquadaminos | 6388252b7c32aa4101486cbf45d0d57d4e3a79da | [
"MIT"
] | 1 | 2021-02-22T12:18:02.000Z | 2021-02-22T12:18:02.000Z | defmodule QuadquizaminosWeb.PrivacyLive do
use Phoenix.LiveView
def render(assigns) do
~L"""
<h1>Privacy Policy</h1>
<h3>Version 1.0.0 (last updated 6-May-2021)</h3>
sFractal takes your privacy as seriously
as you do.
We want to give you control over the little information we collect from you
and work transparently to keep that information no longer than necessary.
This Privacy Policy describes the policies and procedures we apply to the
use and disclosure of your information we collect
when you interact with our game. We also elaborate your privacy rights
and how the law protects you.
We use your personal data to provide and improve the game.
By using the service,
you agree to the collection
and use of information in accordance with this Privacy Policy.
Parts of this Privacy Policy has been created
with the help of the Privacy Policy Generator.
<h2>What data is collected by QuadBlockQuiz?</h2>
We are only collecting publicly accessbile information.
If you login using our anonymous feature,
we are collecting/keeping no information at all.
If you login using OAUTH from GitHub, Google, Twitter, LinkedIn
then we are only keeping enough information to display your score,
and to contact you should you win a prize.
<h2>How is my data used by QuadBlockQuiz?</h2>
We use your data to operate, maintain, and improve our game.
In particular, your identiy (if provided by OAUTH from GitHub,
Google, Twitter, or LinkedIn) is used to display your score
on the Leaderboard and on the Context Board.
We may use your contact information from OAUTH to inform you of prizes
should you win our contest.
<h2>How is my data shared?</h2>
Your data
(which we believe to only be publicly accessible information)
will not be shared other than
(1) if we are required to do so by law
(2) to establish, exercise, or defend our legal rights
(3) when we believe disclosure is necessary or appropriate to prevent
physical, fiancial, or other harm
(4) in conjunction with an investigation of suspected or actual illegal activity
(5) to protect the rights, property, or safety of sFractal or it's users.
<h2>Information from Third-Party Social Media Services</h2>
We allow you to create an account
and log in to use the game
through the following third-party Social Media Services:
GitHub,
Google,
Facebook,
Twitter,
LinkedIn.
If you decide to register through
or otherwise grant us access to a third-party Social Media Service,
We may collect personal data that is already associated
with your third-party Social Media Service's account,
such as your name, or your email address,
associated with that account.
<h2>What about cookies?</h2>
We may use techologies such as cookies, local storage,
web sessions, websockets
and other automated tecnologies on our websites.
We use these technologies for a number of reasons
including authentication, authorization, security,
and diagnostics.
You can control cookies through your browswer settings
and other tools.
Note that rejecting cookies may affect your ability
to interact with the website.
<h2>How do I access or delete my data?</h2>
Contact quadblockquiz@googlegroups.com
<h2>Retention</h2>
To the extent possible, we keep no data longer than necessary;
and will delete all data within one year unless we have
the owner's consent to retain for a specific purpose
(e.g. bragging rights to remain on Leaderboard).
<h2>How do we protect your information?</h2>
We intend to only collect publicly available information
and we maintain administrative, technical, and physical
safeguards to protect any data we maintain against
accidental, unlawful, or unauthorized
destruction, loss, adulteration, access, distortion, or use.
<h2>Children under 13</h2>
This website is intended for a general audience
and is not directed at children.
We do not knowlingly collect personal information
online from indivuals under the age of 13
or such other age as may be directed by applicable law.
<h2>Links to Other Websites</h2>
Our Service may contain links to other websites
that are not operated by Us.
If You click on a third party link,
You will be directed to that third party's site.
We strongly advise You to review the Privacy Policy
of every site You visit.
We have no control over and assume no responsibility
for the content, privacy policies or practices
of any third party sites or services.
<h2>Changes to this policy</h2>
sFractal may amend this policy from time to time.
We encourage you to regularly check this page to review any changes.
Near the top of this page, we will indicate when
it was most recently updated.
<h2>Security of Your Personal Data</h2>
The security of Your Personal Data is important to Us,
but remember that no method of transmission over the Internet,
or method of electronic storage is 100% secure.
While We strive to use commercially acceptable means
to protect Your Personal Data,
We cannot guarantee its absolute security.
"""
end
end
| 46.074074 | 92 | 0.630225 |
081164797f856ada878ff8be1e51f7721ad4a592 | 234 | ex | Elixir | 02-chapter/exercise_02.ex | herminiotorres/programming-elixir | 70add5ec9fe7f91129da0a4e39ab329afb9be598 | [
"MIT"
] | null | null | null | 02-chapter/exercise_02.ex | herminiotorres/programming-elixir | 70add5ec9fe7f91129da0a4e39ab329afb9be598 | [
"MIT"
] | null | null | null | 02-chapter/exercise_02.ex | herminiotorres/programming-elixir | 70add5ec9fe7f91129da0a4e39ab329afb9be598 | [
"MIT"
] | null | null | null | # ** (MatchError) no match of right hand side value: [1, 2, 3]
# IO.inspect([a, b, a] = [1, 2, 3])
# ** (MatchError) no match of right hand side value: [1, 1, 2]
# IO.inspect([a, b, a] = [1, 1, 2])
IO.inspect([a, b, a] = [1, 2, 1])
| 29.25 | 62 | 0.534188 |
08116a22eef3aff34c36143c38439d2cdd82b44a | 729 | exs | Elixir | server/config/test.exs | AlphaHydrae/boardr | 98eed02801f88c065a24bf13051c5cf96270a5f7 | [
"MIT"
] | 1 | 2021-04-08T17:26:27.000Z | 2021-04-08T17:26:27.000Z | server/config/test.exs | AlphaHydrae/boardr | 98eed02801f88c065a24bf13051c5cf96270a5f7 | [
"MIT"
] | 1 | 2022-02-13T05:50:46.000Z | 2022-02-13T05:50:46.000Z | server/config/test.exs | AlphaHydrae/boardr | 98eed02801f88c065a24bf13051c5cf96270a5f7 | [
"MIT"
] | null | null | null | use Mix.Config
config :boardr, Boardr.Auth,
secret_key_base: "15VLc5dynJrIq2HZb8qNfui7e4g0YImLVryvDJbx5SU5o5hdgW14u773KF1SlgdRh3a83YZGmbjZtY1Dkttauxc9bvutDwHW8jgX"
# Configure your database
config :boardr, Boardr.Repo,
database: System.get_env("BOARDR_TEST_DATABASE_NAME", "boardr-test"),
pool: Ecto.Adapters.SQL.Sandbox
# We don't run a server during test.
config :boardr, BoardrApi.Endpoint,
server: false
# Print only warnings and errors during test.
unless System.get_env("DEBUG") do
config :logger, :console, level: :warn
else
# Unless the $DEBUG variable is set (to any value).
config :logger, :console, level: :debug
end
# Do not wait for swarm nodes during test.
config :swarm,
sync_nodes_timeout: 0
| 28.038462 | 121 | 0.775034 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.