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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1cd72c915546d2d80c416a72cde689b270050b77 | 4,406 | ex | Elixir | lib/honeydew/job_monitor.ex | kianmeng/honeydew | 7c0e825c70ef4b72c82d02ca95491e7365d6b2e8 | [
"MIT"
] | 717 | 2015-06-15T19:30:54.000Z | 2022-03-22T06:10:09.000Z | lib/honeydew/job_monitor.ex | kianmeng/honeydew | 7c0e825c70ef4b72c82d02ca95491e7365d6b2e8 | [
"MIT"
] | 106 | 2015-06-25T05:38:05.000Z | 2021-12-08T23:17:19.000Z | lib/honeydew/job_monitor.ex | kianmeng/honeydew | 7c0e825c70ef4b72c82d02ca95491e7365d6b2e8 | [
"MIT"
] | 60 | 2015-06-07T00:48:37.000Z | 2022-03-06T08:20:23.000Z | defmodule Honeydew.JobMonitor do
@moduledoc false
use GenServer, restart: :transient
alias Honeydew.Crash
alias Honeydew.Logger, as: HoneydewLogger
alias Honeydew.Queue
alias Honeydew.Job
require Logger
require Honeydew
# when the queue casts a job to a worker, it spawns a local JobMonitor with the job as state,
# the JobMonitor watches the worker, if the worker dies (or its node is disconnected), the JobMonitor returns the
# job to the queue. it waits @claim_delay miliseconds for the worker to confirm receipt of the job.
@claim_delay 1_000 # ms
defmodule State do
@moduledoc false
defstruct [:queue_pid, :worker, :job, :failure_mode, :success_mode, :progress]
end
def start_link(job, queue_pid, failure_mode, success_mode) do
GenServer.start_link(__MODULE__, [job, queue_pid, failure_mode, success_mode])
end
def init([job, queue_pid, failure_mode, success_mode]) do
Process.send_after(self(), :return_job, @claim_delay)
{:ok, %State{job: job,
queue_pid: queue_pid,
failure_mode: failure_mode,
success_mode: success_mode,
progress: :awaiting_claim}}
end
#
# Internal API
#
def claim(job_monitor, job), do: GenServer.call(job_monitor, {:claim, job})
def job_succeeded(job_monitor, result), do: GenServer.call(job_monitor, {:job_succeeded, result})
def job_failed(job_monitor, %Crash{} = reason), do: GenServer.call(job_monitor, {:job_failed, reason})
def status(job_monitor), do: GenServer.call(job_monitor, :status)
def progress(job_monitor, progress), do: GenServer.call(job_monitor, {:progress, progress})
def handle_call({:claim, job}, {worker, _ref}, %State{worker: nil} = state) do
Honeydew.debug "[Honeydew] Monitor #{inspect self()} had job #{inspect job.private} claimed by worker #{inspect worker}"
Process.monitor(worker)
job = %{job | started_at: System.system_time(:millisecond)}
{:reply, :ok, %{state | job: job, worker: worker, progress: :running}}
end
def handle_call(:status, _from, %State{job: job, worker: worker, progress: progress} = state) do
{:reply, {worker, {job, progress}}, state}
end
def handle_call({:progress, progress}, _from, state) do
{:reply, :ok, %{state | progress: {:running, progress}}}
end
def handle_call({:job_succeeded, result}, {worker, _ref}, %State{job: %Job{from: from} = job, queue_pid: queue_pid, worker: worker, success_mode: success_mode} = state) do
job = %{job | completed_at: System.system_time(:millisecond), result: {:ok, result}}
with {owner, _ref} <- from,
do: send(owner, job)
Queue.ack(queue_pid, job)
with {success_mode_module, success_mode_args} <- success_mode,
do: success_mode_module.handle_success(job, success_mode_args)
{:stop, :normal, :ok, reset(state)}
end
def handle_call({:job_failed, reason}, {worker, _ref}, %State{worker: worker} = state) do
execute_failure_mode(reason, state)
{:stop, :normal, :ok, reset(state)}
end
# no worker has claimed the job, return it
def handle_info(:return_job, %State{job: job, queue_pid: queue_pid, worker: nil} = state) do
Queue.nack(queue_pid, job)
{:stop, :normal, reset(state)}
end
def handle_info(:return_job, state), do: {:noreply, state}
# worker died while busy
def handle_info({:DOWN, _ref, :process, worker, reason}, %State{worker: worker, job: job} = state) do
crash = Crash.new(:exit, reason)
HoneydewLogger.job_failed(job, crash)
execute_failure_mode(crash, state)
{:stop, :normal, reset(state)}
end
def handle_info(msg, state) do
Logger.warn "[Honeydew] Monitor #{inspect self()} received unexpected message #{inspect msg}"
{:noreply, state}
end
defp reset(state) do
%{state | job: nil, progress: :about_to_die}
end
defp execute_failure_mode(%Crash{} = crash, %State{job: job, failure_mode: {failure_mode, failure_mode_args}}) do
failure_mode.handle_failure(job, format_failure_reason(crash), failure_mode_args)
end
defp format_failure_reason(%Crash{type: :exception, reason: exception, stacktrace: stacktrace}) do
{exception, stacktrace}
end
defp format_failure_reason(%Crash{type: :throw, reason: thrown, stacktrace: stacktrace}) do
{thrown, stacktrace}
end
defp format_failure_reason(%Crash{type: :exit, reason: reason}), do: reason
end
| 34.692913 | 173 | 0.699047 |
1cd761781012af7ba4a83065092a4eae3f50bd72 | 6,096 | exs | Elixir | test/groupher_server/cms/hooks/notify_meetup_test.exs | coderplanets/coderplanets_server | 3663e56340d6d050e974c91f7e499d8424fc25e9 | [
"Apache-2.0"
] | 240 | 2018-11-06T09:36:54.000Z | 2022-02-20T07:12:36.000Z | test/groupher_server/cms/hooks/notify_meetup_test.exs | coderplanets/coderplanets_server | 3663e56340d6d050e974c91f7e499d8424fc25e9 | [
"Apache-2.0"
] | 363 | 2018-07-11T03:38:14.000Z | 2021-12-14T01:42:40.000Z | test/groupher_server/cms/hooks/notify_meetup_test.exs | mydearxym/mastani_server | f24034a4a5449200165cf4a547964a0961793eab | [
"Apache-2.0"
] | 22 | 2019-01-27T11:47:56.000Z | 2021-02-28T13:17:52.000Z | defmodule GroupherServer.Test.CMS.Hooks.NotifyMeetup do
use GroupherServer.TestTools
import GroupherServer.CMS.Delegate.Helper, only: [preload_author: 1]
alias GroupherServer.{CMS, Delivery, Repo}
alias CMS.Delegate.Hooks
setup do
{:ok, user} = db_insert(:user)
{:ok, user2} = db_insert(:user)
{:ok, user3} = db_insert(:user)
{:ok, community} = db_insert(:community)
meetup_attrs = mock_attrs(:meetup, %{community_id: community.id})
{:ok, meetup} = CMS.create_article(community, :meetup, meetup_attrs, user)
{:ok, comment} = CMS.create_comment(:meetup, meetup.id, mock_comment(), user)
{:ok, ~m(user2 user3 meetup comment)a}
end
describe "[upvote notify]" do
test "upvote hook should work on meetup", ~m(user2 meetup)a do
{:ok, meetup} = preload_author(meetup)
{:ok, article} = CMS.upvote_article(:meetup, meetup.id, user2)
Hooks.Notify.handle(:upvote, article, user2)
{:ok, notifications} =
Delivery.fetch(:notification, meetup.author.user, %{page: 1, size: 20})
assert notifications.total_count == 1
notify = notifications.entries |> List.first()
assert notify.action == "UPVOTE"
assert notify.article_id == meetup.id
assert notify.thread == "MEETUP"
assert notify.user_id == meetup.author.user.id
assert user_exist_in?(user2, notify.from_users)
end
test "upvote hook should work on meetup comment", ~m(user2 meetup comment)a do
{:ok, comment} = CMS.upvote_comment(comment.id, user2)
{:ok, comment} = preload_author(comment)
Hooks.Notify.handle(:upvote, comment, user2)
{:ok, notifications} = Delivery.fetch(:notification, comment.author, %{page: 1, size: 20})
assert notifications.total_count == 1
notify = notifications.entries |> List.first()
assert notify.action == "UPVOTE"
assert notify.article_id == meetup.id
assert notify.thread == "MEETUP"
assert notify.user_id == comment.author.id
assert notify.comment_id == comment.id
assert user_exist_in?(user2, notify.from_users)
end
test "undo upvote hook should work on meetup", ~m(user2 meetup)a do
{:ok, meetup} = preload_author(meetup)
{:ok, article} = CMS.upvote_article(:meetup, meetup.id, user2)
Hooks.Notify.handle(:upvote, article, user2)
{:ok, article} = CMS.undo_upvote_article(:meetup, meetup.id, user2)
Hooks.Notify.handle(:undo, :upvote, article, user2)
{:ok, notifications} =
Delivery.fetch(:notification, meetup.author.user, %{page: 1, size: 20})
assert notifications.total_count == 0
end
test "undo upvote hook should work on meetup comment", ~m(user2 comment)a do
{:ok, comment} = CMS.upvote_comment(comment.id, user2)
Hooks.Notify.handle(:upvote, comment, user2)
{:ok, comment} = CMS.undo_upvote_comment(comment.id, user2)
Hooks.Notify.handle(:undo, :upvote, comment, user2)
{:ok, comment} = preload_author(comment)
{:ok, notifications} = Delivery.fetch(:notification, comment.author, %{page: 1, size: 20})
assert notifications.total_count == 0
end
end
describe "[collect notify]" do
test "collect hook should work on meetup", ~m(user2 meetup)a do
{:ok, meetup} = preload_author(meetup)
{:ok, _} = CMS.collect_article(:meetup, meetup.id, user2)
Hooks.Notify.handle(:collect, meetup, user2)
{:ok, notifications} =
Delivery.fetch(:notification, meetup.author.user, %{page: 1, size: 20})
assert notifications.total_count == 1
notify = notifications.entries |> List.first()
assert notify.action == "COLLECT"
assert notify.article_id == meetup.id
assert notify.thread == "MEETUP"
assert notify.user_id == meetup.author.user.id
assert user_exist_in?(user2, notify.from_users)
end
test "undo collect hook should work on meetup", ~m(user2 meetup)a do
{:ok, meetup} = preload_author(meetup)
{:ok, _} = CMS.upvote_article(:meetup, meetup.id, user2)
Hooks.Notify.handle(:collect, meetup, user2)
{:ok, _} = CMS.undo_upvote_article(:meetup, meetup.id, user2)
Hooks.Notify.handle(:undo, :collect, meetup, user2)
{:ok, notifications} =
Delivery.fetch(:notification, meetup.author.user, %{page: 1, size: 20})
assert notifications.total_count == 0
end
end
describe "[comment notify]" do
test "meetup author should get notify after some one comment on it", ~m(user2 meetup)a do
{:ok, meetup} = preload_author(meetup)
{:ok, comment} = CMS.create_comment(:meetup, meetup.id, mock_comment(), user2)
Hooks.Notify.handle(:comment, comment, user2)
{:ok, notifications} =
Delivery.fetch(:notification, meetup.author.user, %{page: 1, size: 20})
assert notifications.total_count == 1
notify = notifications.entries |> List.first()
assert notify.action == "COMMENT"
assert notify.thread == "MEETUP"
assert notify.article_id == meetup.id
assert notify.user_id == meetup.author.user.id
assert user_exist_in?(user2, notify.from_users)
end
test "meetup comment author should get notify after some one reply it",
~m(user2 user3 meetup)a do
{:ok, meetup} = preload_author(meetup)
{:ok, comment} = CMS.create_comment(:meetup, meetup.id, mock_comment(), user2)
{:ok, replyed_comment} = CMS.reply_comment(comment.id, mock_comment(), user3)
Hooks.Notify.handle(:reply, replyed_comment, user3)
comment = Repo.preload(comment, :author)
{:ok, notifications} = Delivery.fetch(:notification, comment.author, %{page: 1, size: 20})
assert notifications.total_count == 1
notify = notifications.entries |> List.first()
assert notify.action == "REPLY"
assert notify.thread == "MEETUP"
assert notify.article_id == meetup.id
assert notify.comment_id == replyed_comment.id
assert notify.user_id == comment.author_id
assert user_exist_in?(user3, notify.from_users)
end
end
end
| 34.834286 | 96 | 0.665682 |
1cd78426f8a41876516a7e3c7a478a2f530c3291 | 121 | exs | Elixir | config/dev.exs | denvera/ex-yapay | 18ac9a20108f21554a4c61b9c822694fa5189eb8 | [
"MIT"
] | 3 | 2020-08-11T19:05:55.000Z | 2020-08-19T21:57:39.000Z | config/dev.exs | denvera/ex-yapay | 18ac9a20108f21554a4c61b9c822694fa5189eb8 | [
"MIT"
] | 2 | 2020-08-20T16:32:02.000Z | 2021-09-27T18:46:40.000Z | config/dev.exs | denvera/ex-yapay | 18ac9a20108f21554a4c61b9c822694fa5189eb8 | [
"MIT"
] | 3 | 2020-08-11T19:20:22.000Z | 2021-10-17T17:29:59.000Z | import Config
config :ex_yapay,
base_url: System.get_env("YAPAY_URL") || "https://intermediador.sandbox.yapay.com.br"
| 24.2 | 87 | 0.752066 |
1cd796a53176b4862cdac57b802f33cf252b6abe | 1,871 | ex | Elixir | lib/hierbautberlin/importer/mein_berlin.ex | gildesmarais/website-1 | 7a19bd98d06a064e52fa279e226002e9c3b986f0 | [
"MIT"
] | null | null | null | lib/hierbautberlin/importer/mein_berlin.ex | gildesmarais/website-1 | 7a19bd98d06a064e52fa279e226002e9c3b986f0 | [
"MIT"
] | null | null | null | lib/hierbautberlin/importer/mein_berlin.ex | gildesmarais/website-1 | 7a19bd98d06a064e52fa279e226002e9c3b986f0 | [
"MIT"
] | null | null | null | defmodule Hierbautberlin.Importer.MeinBerlin do
alias Hierbautberlin.GeoData
def import(http_connection \\ HTTPoison) do
{:ok, source} =
GeoData.upsert_source(%{
short_name: "MEIN_BERLIN",
name: "meinBerlin",
url: "https://mein.berlin.de/",
copyright: "Stadt Berlin"
})
items =
fetch_data(http_connection, "https://mein.berlin.de/api/projects/?format=json") ++
fetch_data(http_connection, "https://mein.berlin.de/api/plans/?format=json")
Enum.map(items, fn item ->
attrs = to_geo_item(item)
{:ok, geo_item} = GeoData.upsert_geo_item(Map.merge(%{source_id: source.id}, attrs))
geo_item
end)
end
defp to_geo_item(item) do
point = parse_point(item["point"])
date = parse_date(item["created_or_modified"])
%{
external_id: item["url"],
title: item["title"],
subtitle: item["organisation"],
description: item["description"],
url: "https://mein.berlin.de" <> item["url"],
state: if(item["status"] == 0, do: "active", else: "finished"),
geo_point: point,
participation_open: if(item["participation"] == 0, do: true, else: false),
inserted_at: date,
updated_at: date
}
end
defp fetch_data(http_connection, url) do
response =
http_connection.get!(
url,
["User-Agent": "hierbautberlin.de"],
timeout: 60_000,
recv_timeout: 60_000
)
if response.status_code != 200 do
[]
else
Jason.decode!(response.body)
end
end
defp parse_point(%{"geometry" => %{"type" => "Point"} = point}) do
[long, lat] = point["coordinates"]
%Geo.Point{coordinates: {long, lat}, srid: 4326}
end
defp parse_point(_) do
nil
end
defp parse_date(date) do
Timex.parse!(date, "%Y-%m-%d %k:%M:%S.%f%z:00", :strftime)
end
end
| 25.630137 | 90 | 0.607696 |
1cd7974c26084aded1c8f6d4e99d9d9ad9113c26 | 1,175 | ex | Elixir | lib/atecc508a/info.ex | bcdevices/atecc508a | 934652947ac1de2022f1da556adffa3e8cba31e3 | [
"Apache-2.0"
] | 6 | 2018-12-13T16:33:09.000Z | 2022-03-02T08:57:20.000Z | lib/atecc508a/info.ex | bcdevices/atecc508a | 934652947ac1de2022f1da556adffa3e8cba31e3 | [
"Apache-2.0"
] | 10 | 2019-01-30T19:33:48.000Z | 2022-03-03T21:07:37.000Z | lib/atecc508a/info.ex | bcdevices/atecc508a | 934652947ac1de2022f1da556adffa3e8cba31e3 | [
"Apache-2.0"
] | 9 | 2019-08-22T06:26:45.000Z | 2022-03-01T18:05:01.000Z | defmodule ATECC508A.Info do
@moduledoc """
This struct contains all of the data stored on the device. Depending on how the device has been provisioned (or not),
some fields may be nil.
"""
defstruct serial_number: <<0::72>>,
otp_flags: 0,
board_name: "",
mfg_serial_number: "",
otp_user: <<>>,
device_public_key: <<0::512>>,
device_compressed_cert: <<0::576>>,
signer_public_key: <<0::512>>,
signer_compressed_cert: <<0::576>>,
signer_serial_number: <<>>,
root_cert_sha256: <<0::256>>
@type t :: %__MODULE__{
serial_number: ATECC508A.serial_number(),
otp_flags: integer(),
board_name: String.t(),
mfg_serial_number: String.t(),
otp_user: binary(),
device_public_key: ATECC508A.ecc_public_key(),
device_compressed_cert: ATECC508A.compressed_cert(),
signer_public_key: ATECC508A.ecc_public_key(),
signer_compressed_cert: ATECC508A.compressed_cert(),
signer_serial_number: binary(),
root_cert_sha256: ATECC508A.sha256()
}
end
| 35.606061 | 119 | 0.596596 |
1cd826f5048a81b2112c6acc11fc523702cfb7a5 | 3,445 | ex | Elixir | lib/one_dhcpd/arp.ex | fhunleth/one_dhcpd | d1a4a6c7e8c86e7ae33c67231984b3665fa7382a | [
"Apache-2.0"
] | 6 | 2018-08-27T16:32:28.000Z | 2020-10-07T09:47:53.000Z | lib/one_dhcpd/arp.ex | fhunleth/one_dhcpd | d1a4a6c7e8c86e7ae33c67231984b3665fa7382a | [
"Apache-2.0"
] | null | null | null | lib/one_dhcpd/arp.ex | fhunleth/one_dhcpd | d1a4a6c7e8c86e7ae33c67231984b3665fa7382a | [
"Apache-2.0"
] | 1 | 2019-03-28T23:48:26.000Z | 2019-03-28T23:48:26.000Z | defmodule OneDHCPD.ARP do
@moduledoc """
This module contains utilities to view or update the ARP cache.
OneDHCPD uses this to update the ARP cache when the IP address is given
out. If networking isn't working, `OneDHCPD.ARP.entries/0` is useful
for debugging.
"""
defmodule Entry do
@moduledoc """
One entry in the ARP table
"""
defstruct ip: nil,
ifname: nil,
hwaddr: nil,
state: nil
@type t :: %__MODULE__{
ip: :inet.ip_address(),
ifname: String.t(),
hwaddr: [byte()],
state: String.t()
}
end
@doc """
Query the ARP cache and return everything in it.
Currently this function is only used for debug.
"""
@spec entries() :: [Entry.t()]
def entries() do
{output, 0} = System.cmd("ip", ["neigh", "show"])
output
|> String.split("\n")
|> Enum.map(&line_to_entry/1)
|> Enum.filter(&is_map/1)
end
@doc """
Replace an entry in the ARP cache.
"""
@spec replace(String.t(), :inet.ip_address(), [byte()]) :: :ok | {:error, any()}
def replace(ifname, ip, hwaddr) do
ip_str = :inet.ntoa(ip) |> to_string()
hwaddr_str = format_hw_address(hwaddr)
# This could be done by running:
#
# ip neigh replace dev <ifname> to <ip_str> lladdr <hwaddr_str> nud reachable
# or calling arp -s
#
# Unfortunately Nerves doesn't support either since Busybox's ip doesn't
# support replace and arp isn't enabled. So... we made a little port to
# call the ioctl.
arp_set = Application.app_dir(:one_dhcpd, "priv/arp_set")
case System.cmd(arp_set, [
ifname,
ip_str,
hwaddr_str
]) do
{_output, 0} -> :ok
{output, _rc} -> {:error, output}
end
end
defp line_to_entry(line) do
line
|> String.split(" ")
|> make_entry()
end
# iproute2 format
defp make_entry([ip, "dev", ifname, "lladdr", hwaddr, state]) do
{:ok, ip_address} = parse_ip_address(ip)
%Entry{
ip: ip_address,
ifname: ifname,
hwaddr: parse_hw_address(hwaddr),
state: state
}
end
# iproute2 format
defp make_entry([ip, "dev", ifname, "lladdr", hwaddr, "router", state]) do
{:ok, ip_address} = parse_ip_address(ip)
%Entry{
ip: ip_address,
ifname: ifname,
hwaddr: parse_hw_address(hwaddr),
state: state
}
end
# Busybox ip-neigh
defp make_entry([
ip,
"dev",
ifname,
"lladdr",
hwaddr | rest
]) do
{:ok, ip_address} = parse_ip_address(ip)
state = List.last(rest)
%Entry{
ip: ip_address,
ifname: ifname,
hwaddr: parse_hw_address(hwaddr),
state: state
}
end
defp make_entry(_other), do: nil
defp parse_ip_address(s) do
:inet.parse_address(to_charlist(s))
end
defp parse_hw_address(
<<a::2-bytes, ":", b::2-bytes, ":", c::2-bytes, ":", d::2-bytes, ":", e::2-bytes, ":",
f::2-bytes>>
) do
[
String.to_integer(a, 16),
String.to_integer(b, 16),
String.to_integer(c, 16),
String.to_integer(d, 16),
String.to_integer(e, 16),
String.to_integer(f, 16)
]
end
defp format_hw_address(addr) when is_list(addr) and length(addr) == 6 do
:io_lib.format('~2.16.0B:~2.16.0B:~2.16.0B:~2.16.0B:~2.16.0B:~2.16.0B', addr)
|> to_string()
end
end
| 23.758621 | 95 | 0.576488 |
1cd85d575eab1dc08927f649a86d8f5eb086e325 | 972 | exs | Elixir | test/wanon/cache/edit_test.exs | graffic/wanon-elixir | 65fcde17cbbeb1af3fda5f6423dba112dfa3b9a9 | [
"MIT"
] | 1 | 2018-11-28T07:44:28.000Z | 2018-11-28T07:44:28.000Z | test/wanon/cache/edit_test.exs | graffic/wanon-elixir | 65fcde17cbbeb1af3fda5f6423dba112dfa3b9a9 | [
"MIT"
] | 1 | 2018-10-24T20:59:09.000Z | 2018-10-24T20:59:09.000Z | test/wanon/cache/edit_test.exs | graffic/wanon-elixir | 65fcde17cbbeb1af3fda5f6423dba112dfa3b9a9 | [
"MIT"
] | null | null | null | defmodule EditTest do
use ExUnit.Case
alias Wanon.Cache.CacheEntry
import Ecto.Query, only: [from: 1]
setup do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Wanon.Repo)
end
@update %{
"edited_message" => %{
"message_id" => 2,
"date" => 1540590127,
"edit_date" => 1540590133,
"text" => "My message II"
}
}
test "select edit messages" do
assert Wanon.Cache.Edit.selector(@update)
end
test "ignore other messages" do
refute Wanon.Cache.Edit.selector(%{"message" => %{}})
end
test "edit existing message in cache" do
Wanon.Repo.insert(%CacheEntry{chat_id: 1, message_id: 2, date: 3, message: %{"spam" => 2}})
Wanon.Cache.Edit.execute(@update)
updated = Wanon.Repo.one(from(c in CacheEntry))
assert updated.message == @update["edited_message"]
end
test "edit missing message in cache" do
Wanon.Cache.Edit.execute(@update)
refute Wanon.Repo.one(from(c in CacheEntry))
end
end
| 23.142857 | 95 | 0.651235 |
1cd897bb4a311acd989518c0bd427ccd3207e369 | 1,331 | exs | Elixir | mix.exs | ConnorRigby/turtletube_web | 0e6618395918234584edbb74ccceb589fc79bc68 | [
"MIT"
] | null | null | null | mix.exs | ConnorRigby/turtletube_web | 0e6618395918234584edbb74ccceb589fc79bc68 | [
"MIT"
] | null | null | null | mix.exs | ConnorRigby/turtletube_web | 0e6618395918234584edbb74ccceb589fc79bc68 | [
"MIT"
] | null | null | null | defmodule TurtleTube.MixProject do
use Mix.Project
def project do
[
app: :turtle_tube,
version: "0.1.0",
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: {TurtleTube.Application, []},
extra_applications: [:logger, :runtime_tools]
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[
{:phoenix, "~> 1.4.0-rc or ~> 1.4", override: true},
{:phoenix_pubsub, "~> 1.1"},
{:phoenix_live_reload, "~> 1.2.0-rc or ~> 1.2", only: :dev},
{:phoenix_html, "~> 2.12"},
{:plug, "~> 1.7"},
{:plug_cowboy, "~> 2.0"},
{:cowboy, "~> 2.0", override: true},
{:jason, "~> 1.0"},
{:gettext, "~> 0.11"},
{:distillery, "~> 2.0"},
{:phoenix_channel_client, "~> 0.3", only: :test},
{:websocket_client, "~> 1.3", only: :test},
]
end
end
| 26.62 | 66 | 0.562735 |
1cd8d49ee5d29f32bdc40fb36d55a8834fe65f39 | 303 | ex | Elixir | lib/rienkun_web/channels/presence.ex | fcapovilla/rienkun | 7a3bf6aed5685aa2ab69260fc5a2f9d64696d6a1 | [
"BSD-3-Clause"
] | null | null | null | lib/rienkun_web/channels/presence.ex | fcapovilla/rienkun | 7a3bf6aed5685aa2ab69260fc5a2f9d64696d6a1 | [
"BSD-3-Clause"
] | null | null | null | lib/rienkun_web/channels/presence.ex | fcapovilla/rienkun | 7a3bf6aed5685aa2ab69260fc5a2f9d64696d6a1 | [
"BSD-3-Clause"
] | null | null | null | defmodule RienkunWeb.Presence do
@moduledoc """
Provides presence tracking to channels and processes.
See the [`Phoenix.Presence`](http://hexdocs.pm/phoenix/Phoenix.Presence.html)
docs for more details.
"""
use Phoenix.Presence,
otp_app: :rienkun,
pubsub_server: Rienkun.PubSub
end
| 25.25 | 79 | 0.735974 |
1cd8f53b4094968e8a70b12ca977fb669b470c21 | 14,212 | exs | Elixir | test/cases/integration_test.exs | dgmcguire/distillery | 137c9b1920ab1d03080d0cfb0fb4835c8a763fbb | [
"MIT"
] | null | null | null | test/cases/integration_test.exs | dgmcguire/distillery | 137c9b1920ab1d03080d0cfb0fb4835c8a763fbb | [
"MIT"
] | null | null | null | test/cases/integration_test.exs | dgmcguire/distillery | 137c9b1920ab1d03080d0cfb0fb4835c8a763fbb | [
"MIT"
] | null | null | null | defmodule Distillery.Test.IntegrationTest do
use ExUnit.Case, async: false
alias Mix.Releases.Utils
import Distillery.Test.Helpers
@moduletag integration: true
@moduletag timeout: 60_000 * 5
@fixtures_path Path.join([__DIR__, "..", "fixtures"])
@standard_app_path Path.join([@fixtures_path, "standard_app"])
@standard_build_path Path.join([@standard_app_path, "_build", "prod"])
@standard_output_path Path.join([@standard_build_path, "rel", "standard_app"])
@umbrella_app_path Path.join([@fixtures_path, "umbrella_app"])
@umbrella_build_path Path.join([@umbrella_app_path, "_build", "prod"])
@umbrella_output_path Path.join([@umbrella_build_path, "rel", "umbrella"])
defmacrop with_standard_app(do: body) do
quote do
with_app @standard_app_path do
unquote(body)
end
end
end
defmacrop with_umbrella_app(do: body) do
quote do
with_app @umbrella_app_path do
unquote(body)
end
end
end
defmacrop with_app(app_path, do: body) do
quote do
old_dir = File.cwd!()
File.cd!(unquote(app_path))
try do
unquote(body)
after
File.cd!(old_dir)
end
end
end
setup_all do
for app_path <- [@standard_app_path, @umbrella_app_path] do
with_app app_path do
{:ok, _} = File.rm_rf(Path.join(app_path, "_build"))
_ = File.rm(Path.join(app_path, "mix.lock"))
{:ok, _} = mix("deps.get")
{:ok, _} = mix("compile")
end
end
:ok
end
setup do
for app_path <- [@standard_app_path, @umbrella_app_path] do
with_app app_path do
reset_changes!(app_path)
end
end
:ok
end
describe "standard application" do
test "can build a release and start it - dev" do
with_standard_app do
assert {:ok, output} = build_release(env: :dev, no_tar: true)
# Release plugin was run
for callback <- ~w(before_assembly after_assembly) do
assert output =~ "EnvLoggerPlugin in dev executing #{callback}"
end
bin = Path.join([@standard_output_path, "bin", "standard_app"])
try do
# Can start
assert {:ok, _} = release_cmd(bin, "start")
assert :ok = wait_for_app(bin)
# Base config is correct
assert {:ok, "2\n"} =
release_cmd(bin, "rpc", ["Application.get_env(:standard_app, :num_procs)"])
# Config provider was run
assert {:ok, ":config_provider\n"} =
release_cmd(bin, "rpc", ["Application.get_env(:standard_app, :source)"])
# Can stop
assert {:ok, _} = release_cmd(bin, "stop")
rescue
e ->
release_cmd(bin, "stop")
reraise e, System.stacktrace()
end
end
end
test "can build release and start it - prod" do
with_standard_app do
assert {:ok, output} = build_release()
# All release plugins ran
for callback <- ~w(before_assembly after_assembly before_package after_package) do
assert output =~ "EnvLoggerPlugin in prod executing #{callback}"
assert output =~ "ProdPlugin in prod executing #{callback}"
end
# Extract release to temporary directory
assert {:ok, tmpdir} = Utils.insecure_mkdir_temp()
bin = Path.join([tmpdir, "bin", "standard_app"])
try do
deploy_tarball(@standard_output_path, "0.0.1", tmpdir)
# Can start
assert {:ok, _} = release_cmd(bin, "start")
assert :ok = wait_for_app(bin)
# Config provider was run
assert {:ok, ":config_provider\n"} =
release_cmd(bin, "rpc", ["Application.get_env(:standard_app, :source)"])
# Additional config files were used
assert {:ok, ":bar\n"} =
release_cmd(bin, "rpc", ["Application.get_env(:standard_app, :foo)"])
# Can stop
assert {:ok, _} = release_cmd(bin, "stop")
rescue
e ->
release_cmd(bin, "stop")
reraise e, System.stacktrace()
after
File.rm_rf!(tmpdir)
end
end
end
test "can build and deploy a hot upgrade" do
with_standard_app do
assert {:ok, tmpdir} = Utils.insecure_mkdir_temp()
bin_path = Path.join([tmpdir, "bin", "standard_app"])
try do
# Build v1 release
assert {:ok, _} = build_release()
# Apply v2 changes
v1_to_v2()
# Build v2 release
assert {:ok, _} = build_release(upgrade: true)
# Ensure the versions we expected were produced
assert ["0.0.2", "0.0.1"] == Utils.get_release_versions(@standard_output_path)
# Unpack and verify
deploy_tarball(@standard_output_path, "0.0.1", tmpdir)
# Push upgrade release to the staging directory
deploy_upgrade_tarball(@standard_output_path, "0.0.2", tmpdir)
assert {:ok, _} = release_cmd(bin_path, "start")
assert :ok = wait_for_app(bin_path)
# Interact with running release by changing the state of some processes
assert {:ok, ":ok\n"} = release_cmd(bin_path, "rpc", ["StandardApp.A.push(8)"])
assert {:ok, ":ok\n"} = release_cmd(bin_path, "rpc", ["StandardApp.B.push(8)"])
# Install upgrade and verify output
assert {:ok, output} = release_cmd(bin_path, "upgrade", ["0.0.2"])
assert output =~ "Made release standard_app:0.0.2 permanent"
# Verify that the state changes we made were persistent across code changes
assert {:ok, "{:ok, 8}\n"} = release_cmd(bin_path, "rpc", ["StandardApp.A.pop()"])
assert {:ok, "{:ok, 8}\n"} = release_cmd(bin_path, "rpc", ["StandardApp.B.pop()"])
assert {:ok, "{:ok, 2}\n"} = release_cmd(bin_path, "rpc", ["StandardApp.A.version()"])
assert {:ok, "{:ok, 2}\n"} = release_cmd(bin_path, "rpc", ["StandardApp.B.version()"])
# Verify that configuration changes took effect
assert {:ok, "4\n"} =
release_cmd(bin_path, "rpc", ["Application.get_env(:standard_app, :num_procs)"])
assert {:ok, _} = release_cmd(bin_path, "stop")
rescue
e ->
release_cmd(bin_path, "stop")
reraise e, System.stacktrace()
after
File.rm_rf(tmpdir)
reset_changes!(@standard_app_path)
end
end
end
test "can build and deploy hot upgrade with custom appup" do
with_standard_app do
# Build v1 release
assert {:ok, _} = build_release()
# Apply v2 changes
v1_to_v2()
# Generate appup from old to new version
assert {:ok, _} = mix("compile")
assert {:ok, _} = mix("release.gen.appup", ["--app=standard_app"])
# Build v2 release
assert {:ok, _} = build_release(upgrade: true)
# Verify versions
assert ["0.0.2", "0.0.1"] == Utils.get_release_versions(@standard_output_path)
# Deploy it
assert {:ok, tmpdir} = Utils.insecure_mkdir_temp()
bin_path = Path.join([tmpdir, "bin", "standard_app"])
try do
# Unpack v1 to target directory
deploy_tarball(@standard_output_path, "0.0.1", tmpdir)
# Push v2 release to staging directory
deploy_upgrade_tarball(@standard_output_path, "0.0.2", tmpdir)
# Boot v1
assert {:ok, _} = release_cmd(bin_path, "start")
assert :ok = wait_for_app(bin_path)
# Interact with running release by changing state of some processes
assert {:ok, ":ok\n"} = release_cmd(bin_path, "rpc", ["StandardApp.A.push(8)"])
assert {:ok, ":ok\n"} = release_cmd(bin_path, "rpc", ["StandardApp.B.push(8)"])
# Install v2
assert {:ok, output} = release_cmd(bin_path, "upgrade", ["0.0.2"])
assert output =~ "Made release standard_app:0.0.2 permanent"
# Verify that state changes were persistent across code changes
assert {:ok, "{:ok, 8}\n"} = release_cmd(bin_path, "rpc", ["StandardApp.A.pop()"])
assert {:ok, "{:ok, 8}\n"} = release_cmd(bin_path, "rpc", ["StandardApp.B.pop()"])
assert {:ok, "{:ok, 2}\n"} = release_cmd(bin_path, "rpc", ["StandardApp.A.version()"])
assert {:ok, "{:ok, 2}\n"} = release_cmd(bin_path, "rpc", ["StandardApp.B.version()"])
# Verify configuration changes took effect
assert {:ok, "4\n"} =
release_cmd(bin_path, "rpc", ["Application.get_env(:standard_app, :num_procs)"])
assert {:ok, _} = release_cmd(bin_path, "stop")
rescue
e ->
release_cmd(bin_path, "stop")
reraise e, System.stacktrace()
after
File.rm_rf(tmpdir)
reset_changes!(@standard_app_path)
end
end
end
test "when installation directory contains a space" do
with_standard_app do
assert {:ok, _} = build_release()
# Deploy release to path with spaces
assert {:ok, tmpdir} = Utils.insecure_mkdir_temp()
tmpdir = Path.join(tmpdir, "dir with space")
bin_path = Path.join([tmpdir, "bin", "standard_app"])
try do
deploy_tarball(@standard_output_path, "0.0.1", tmpdir)
# Boot release
assert {:ok, _} = release_cmd(bin_path, "start")
assert :ok = wait_for_app(bin_path)
# Verify configuration
assert {:ok, "2\n"} =
release_cmd(bin_path, "rpc", ["Application.get_env(:standard_app, :num_procs)"])
assert {:ok, ":bar\n"} =
release_cmd(bin_path, "rpc", ["Application.get_env(:standard_app, :foo)"])
assert {:ok, _} = release_cmd(bin_path, "stop")
rescue
e ->
release_cmd(bin_path, "stop")
reraise e, System.stacktrace()
after
File.rm_rf!(tmpdir)
end
end
end
end
describe "umbrella application" do
test "can build umbrella and deploy it - dev" do
with_umbrella_app do
assert {:ok, output} = build_release(env: :dev, no_tar: true)
bin = Path.join([@umbrella_output_path, "bin", "umbrella"])
try do
# Can start
assert {:ok, _} = release_cmd(bin, "start")
assert :ok = wait_for_app(bin)
# We should be able to execute an HTTP request against the API
url = 'http://localhost:4000/healthz'
headers = [{'accepts', 'application/json'}, {'content-type', 'application/json'}]
opts = [body_format: :binary, full_result: false]
assert {:ok, {200, _}} = :httpc.request(:get, {url, headers}, [], opts)
# Can stop
assert {:ok, _} = release_cmd(bin, "stop")
rescue
e ->
release_cmd(bin, "stop")
reraise e, System.stacktrace()
end
end
end
end
defp v1_to_v2 do
config_path = Path.join([@standard_app_path, "config", "config.exs"])
a_path = Path.join([@standard_app_path, "lib", "standard_app", "a.ex"])
b_path = Path.join([@standard_app_path, "lib", "standard_app", "b.ex"])
upgrade(@standard_app_path, "0.0.2", [
{config_path, "num_procs: 2", "num_procs: 4"},
{a_path, "{:ok, {1, []}}", "{:ok, {2, []}}"},
{b_path, "loop({1, []}, parent, debug)", "loop({2, []}, parent, debug)"}
])
end
defp reset!(path) do
backup = path <> ".backup"
if File.exists?(backup) do
File.cp!(backup, path)
File.rm!(backup)
end
end
defp reset_changes!(app_path) do
app = Path.basename(app_path)
changes =
Path.join([app_path, "**", "*.backup"])
|> Path.wildcard()
|> Enum.map(&(Path.join(Path.dirname(&1), Path.basename(&1, ".backup"))))
Enum.each(changes, &reset!/1)
File.rm_rf!(Path.join([app_path, "rel", app]))
File.rm_rf!(Path.join([app_path, "rel", "appups", app]))
:ok
end
defp apply_change(path, match, replacement) do
apply_changes(path, [{match, replacement}])
end
defp apply_changes(path, changes) when is_list(changes) do
unless File.exists?(path <> ".backup") do
File.cp!(path, path <> ".backup")
end
old = File.read!(path)
new =
changes
|> Enum.reduce(old, fn {match, replacement}, acc ->
String.replace(acc, match, replacement)
end)
File.write!(path, new)
end
defp upgrade(app_path, version, changes) do
# Set new version in mix.exs
mix_exs = Path.join([app_path, "mix.exs"])
apply_change(mix_exs, ~r/(version: )"\d+.\d+.\d+"/, "\\1\"#{version}\"")
# Set new version in release config
rel_config_path = Path.join([app_path, "rel", "config.exs"])
apply_change(rel_config_path, ~r/(version: )"\d+.\d+.\d+"/, "\\1\"#{version}\"")
# Apply other changes for this upgrade
for change <- changes do
case change do
{path, changeset} when is_list(changeset) ->
apply_changes(path, changeset)
{path, match, replacement} ->
apply_change(path, match, replacement)
end
end
:ok
end
defp deploy_tarball(release_root_dir, version, directory) do
dir = String.to_charlist(directory)
tar =
case Path.wildcard(Path.join([release_root_dir, "releases", version, "*.tar.gz"])) do
[tar] ->
String.to_charlist(tar)
end
case :erl_tar.extract(tar, [{:cwd, dir}, :compressed]) do
:ok ->
:ok = Utils.write_term(Path.join(directory, "extra.config"), standard_app: [foo: :bar])
other ->
other
end
end
defp deploy_upgrade_tarball(release_root_dir, version, directory) do
target = Path.join([directory, "releases", version])
File.mkdir_p!(Path.join([directory, "releases", version]))
source =
case Path.wildcard(Path.join([release_root_dir, "releases", version, "*.tar.gz"])) do
[source] ->
source
end
name = Path.basename(source)
File.cp!(source, Path.join(target, name))
end
end
| 35.004926 | 99 | 0.582325 |
1cd914ea0a821aed5b456d0441366e8a1241f43f | 972 | ex | Elixir | lib/unifex/specs_parser.ex | wishdev/unifex | f16a65b73e2a482e784b1bf6816b73c0f7bdb2a7 | [
"Apache-2.0"
] | null | null | null | lib/unifex/specs_parser.ex | wishdev/unifex | f16a65b73e2a482e784b1bf6816b73c0f7bdb2a7 | [
"Apache-2.0"
] | null | null | null | lib/unifex/specs_parser.ex | wishdev/unifex | f16a65b73e2a482e784b1bf6816b73c0f7bdb2a7 | [
"Apache-2.0"
] | null | null | null | defmodule Unifex.SpecsParser do
@moduledoc """
Module that handles parsing Unifex specs for native boilerplate code generation.
For information on how to create such specs, see `Unifex.Specs` module.
"""
@type parsed_specs_t :: [{:module, module()} | {:fun_specs, tuple()}]
@doc """
Parses Unifex specs of native functions.
"""
@spec parse_specs(specs :: Macro.t()) :: parsed_specs_t()
def parse_specs(specs) do
{_res, binds} = Code.eval_string(specs, [{:unifex_config__, []}], make_env())
binds |> Keyword.fetch!(:unifex_config__) |> Enum.reverse()
end
# Returns clear __ENV__ with proper functions/macros imported. Useful for invoking
# user code without possibly misleading macros and aliases from the current scope,
# while providing needed functions/macros.
defp make_env() do
{env, _binds} =
Code.eval_quoted(
quote do
import Unifex.Specs
__ENV__
end
)
env
end
end
| 28.588235 | 84 | 0.673868 |
1cd91a337779e38d19c1f1b5ea7ba93f76e2221e | 4,554 | ex | Elixir | backend/lib/kjer_si/rooms.ex | danesjenovdan/kjer.si | 185410ede2d42892e4d91c000099283254c5dc7a | [
"Unlicense"
] | 2 | 2019-11-02T21:28:34.000Z | 2019-11-28T18:01:08.000Z | backend/lib/kjer_si/rooms.ex | danesjenovdan/kjer.si | 185410ede2d42892e4d91c000099283254c5dc7a | [
"Unlicense"
] | 17 | 2019-11-29T16:23:38.000Z | 2022-02-14T05:11:41.000Z | backend/lib/kjer_si/rooms.ex | danesjenovdan/kjer.si | 185410ede2d42892e4d91c000099283254c5dc7a | [
"Unlicense"
] | null | null | null | defmodule KjerSi.Rooms do
@moduledoc """
The Rooms context.
"""
import Ecto.Query, warn: false
import Geo.PostGIS
alias KjerSi.Repo
alias KjerSi.Rooms.Category
@doc """
Returns the list of categories.
## Examples
iex> list_categories()
[%Category{}, ...]
"""
def list_categories do
Repo.all(Category)
end
@doc """
Gets a single category.
Raises `Ecto.NoResultsError` if the Category does not exist.
## Examples
iex> get_category!(123)
%Category{}
iex> get_category!(456)
** (Ecto.NoResultsError)
"""
def get_category!(id), do: Repo.get!(Category, id)
@doc """
Creates a category.
## Examples
iex> create_category(%{field: value})
{:ok, %Category{}}
iex> create_category(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_category(attrs \\ %{}) do
%Category{}
|> Category.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a category.
## Examples
iex> update_category(category, %{field: new_value})
{:ok, %Category{}}
iex> update_category(category, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_category(%Category{} = category, attrs) do
category
|> Category.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a Category.
## Examples
iex> delete_category(category)
{:ok, %Category{}}
iex> delete_category(category)
{:error, %Ecto.Changeset{}}
"""
def delete_category(%Category{} = category) do
Repo.delete(category)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking category changes.
## Examples
iex> change_category(category)
%Ecto.Changeset{source: %Category{}}
"""
def change_category(%Category{} = category) do
Category.changeset(category, %{})
end
alias KjerSi.Rooms.Room
@doc """
Returns the list of rooms.
## Examples
iex> list_rooms()
[%Room{}, ...]
"""
def list_rooms do
Room
|> Repo.all()
|> Repo.preload([:users, :events, :category])
end
@doc """
Gets a single room.
Raises `Ecto.NoResultsError` if the Room does not exist.
## Examples
iex> get_room!(123)
%Room{}
iex> get_room!(456)
** (Ecto.NoResultsError)
"""
def get_room!(id, preload \\ []) do
Repo.get!(Room, id) |> Repo.preload(preload)
end
@doc """
Gets a single room.
## Examples
iex> get_room(123)
{:ok, %Room{}}
iex> get_room(456)
{:error, :not_found}
"""
def get_room(id, preload \\ []) do
case Repo.get(Room, id) do
nil ->
{:error, :not_found}
room ->
preloaded_room = Repo.preload(room, preload)
{:ok, preloaded_room}
end
end
@doc """
Creates a room.
## Examples
iex> create_room(%{field: value})
{:ok, %Room{}}
iex> create_room(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_room(attrs \\ %{}) do
case %Room{} |> Room.changeset(attrs) |> Repo.insert() do
{:ok, room} ->
preloaded_room = Repo.preload(room, [:users])
{:ok, preloaded_room}
{:error, error} ->
{:error, error}
end
end
@doc """
Updates a room.
## Examples
iex> update_room(room, %{field: new_value})
{:ok, %Room{}}
iex> update_room(room, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_room(%Room{} = room, attrs) do
room
|> Room.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a Room.
## Examples
iex> delete_room(room)
{:ok, %Room{}}
iex> delete_room(room)
{:error, %Ecto.Changeset{}}
"""
def delete_room(%Room{} = room) do
Repo.delete(room)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking room changes.
## Examples
iex> change_room(room)
%Ecto.Changeset{source: %Room{}}
"""
def change_room(%Room{} = room) do
Room.changeset(room, %{})
end
@doc """
Returns all rooms that are close enough to
the specified point (based on each room's
individual radius).
## Examples
iex> get_rooms_around_point(point)
[%Room{}, ...]
"""
def get_rooms_around_point(point) do
query =
from room in Room,
where: st_dwithin_in_meters(room.coordinates, ^point, room.radius),
order_by: [asc: st_distance_in_meters(room.coordinates, ^point)],
limit: 5
query
|> Repo.all()
|> Repo.preload(:users)
end
end
| 17.789063 | 75 | 0.581906 |
1cd94c0cdcd5e470c2b2da21ea55fb1a8dcc78ae | 897 | ex | Elixir | test/support/fixtures/field_schema_fixture.ex | patrotom/adaptable-costs-evaluator | c97e65af1e021d7c6acf6564f4671c60321346e3 | [
"MIT"
] | null | null | null | test/support/fixtures/field_schema_fixture.ex | patrotom/adaptable-costs-evaluator | c97e65af1e021d7c6acf6564f4671c60321346e3 | [
"MIT"
] | 4 | 2021-12-07T12:26:50.000Z | 2021-12-30T14:17:25.000Z | test/support/fixtures/field_schema_fixture.ex | patrotom/adaptable-costs-evaluator | c97e65af1e021d7c6acf6564f4671c60321346e3 | [
"MIT"
] | null | null | null | defmodule AdaptableCostsEvaluator.Fixtures.FieldSchemaFixture do
use ExUnit.CaseTemplate
alias AdaptableCostsEvaluator.FieldSchemas
alias AdaptableCostsEvaluator.FieldSchemas.FieldSchema
using do
quote do
@valid_field_schema_attrs %{definition: %{}, name: "some name"}
@update_field_schema_attrs %{definition: %{}, name: "some updated name"}
@invalid_field_schema_attrs %{definition: nil, name: nil}
def field_schema_fixture(attrs \\ %{}) do
{:ok, field_schema} =
attrs
|> Enum.into(@valid_field_schema_attrs)
|> FieldSchemas.create_field_schema()
field_schema
end
def field_schema_response(%FieldSchema{} = field_schema) do
%{
"id" => field_schema.id,
"name" => field_schema.name,
"definition" => field_schema.definition
}
end
end
end
end
| 28.03125 | 78 | 0.655518 |
1cd9b4cf34e8ec4784fbdd5edd5c649f04c8473f | 543 | ex | Elixir | lib/lrucache_api_web/views/error_view.ex | anakind/phoenix-lrucache-api | cfb0dfba181fe196dd0d77dba9854dd9c50ba070 | [
"MIT"
] | null | null | null | lib/lrucache_api_web/views/error_view.ex | anakind/phoenix-lrucache-api | cfb0dfba181fe196dd0d77dba9854dd9c50ba070 | [
"MIT"
] | null | null | null | lib/lrucache_api_web/views/error_view.ex | anakind/phoenix-lrucache-api | cfb0dfba181fe196dd0d77dba9854dd9c50ba070 | [
"MIT"
] | null | null | null | defmodule LrucacheApiWeb.ErrorView do
use LrucacheApiWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.json", _assigns) do
# %{errors: %{detail: "Internal Server Error"}}
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.json" becomes
# "Not Found".
def template_not_found(template, _assigns) do
%{errors: %{detail: Phoenix.Controller.status_message_from_template(template)}}
end
end
| 31.941176 | 83 | 0.723757 |
1cd9b979f62ea810f63924152354a6f45208e254 | 739 | exs | Elixir | elixir/elixir-sips/samples/sdl_playground/examples/window.exs | afronski/playground-erlang | 6ac4b58b2fd717260c22a33284547d44a9b5038e | [
"MIT"
] | 2 | 2015-12-09T02:16:51.000Z | 2021-07-26T22:53:43.000Z | elixir/elixir-sips/samples/sdl_playground/examples/window.exs | afronski/playground-erlang | 6ac4b58b2fd717260c22a33284547d44a9b5038e | [
"MIT"
] | null | null | null | elixir/elixir-sips/samples/sdl_playground/examples/window.exs | afronski/playground-erlang | 6ac4b58b2fd717260c22a33284547d44a9b5038e | [
"MIT"
] | 1 | 2016-05-08T18:40:31.000Z | 2016-05-08T18:40:31.000Z | defmodule SdlWindow do
def start do
:ok = :sdl.start([:video])
:ok = :sdl.stop_on_exit
{:ok, window} = :sdl_window.create('Hello SDL', 10, 10, 500, 500, [])
{:ok, renderer} = :sdl_renderer.create(window, -1, [:accelereated, :present_vsync])
loop(renderer)
end
defp loop(renderer) do
:ok = :sdl_renderer.set_draw_color(renderer, 255, 255, 255, 255)
:ok = :sdl_renderer.clear(renderer)
:ok = :sdl_renderer.set_draw_color(renderer, 255, 0, 0, 255)
:ok = :sdl_renderer.fill_rect(renderer, %{x: 100, y: 100, w: 50, h: 50})
:ok = :sdl_renderer.present(renderer)
case :sdl_events.poll do
%{type: :quit} -> :ok
_ -> loop(renderer)
end
end
end
SdlWindow.start
| 25.482759 | 87 | 0.61705 |
1cd9c2ebc8bf248aaa00636b89eeb5daae843aca | 981 | ex | Elixir | lib/codes/codes_w07.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_w07.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_w07.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_W07 do
alias IcdCode.ICDCode
def _W07XXXA do
%ICDCode{full_code: "W07XXXA",
category_code: "W07",
short_code: "XXXA",
full_name: "Fall from chair, initial encounter",
short_name: "Fall from chair, initial encounter",
category_name: "Fall from chair, initial encounter"
}
end
def _W07XXXD do
%ICDCode{full_code: "W07XXXD",
category_code: "W07",
short_code: "XXXD",
full_name: "Fall from chair, subsequent encounter",
short_name: "Fall from chair, subsequent encounter",
category_name: "Fall from chair, subsequent encounter"
}
end
def _W07XXXS do
%ICDCode{full_code: "W07XXXS",
category_code: "W07",
short_code: "XXXS",
full_name: "Fall from chair, sequela",
short_name: "Fall from chair, sequela",
category_name: "Fall from chair, sequela"
}
end
end
| 28.852941 | 64 | 0.61366 |
1cd9c50bab635a6dae3926d88623f5f24d3abe4f | 1,672 | ex | Elixir | lib/bongo/map_to_model.ex | anuragdalia/bongo | c83c9ef70f76968e122ea7f5ed7ed2857266a13b | [
"MIT"
] | 1 | 2019-01-31T04:50:18.000Z | 2019-01-31T04:50:18.000Z | lib/bongo/map_to_model.ex | yatender-oktalk/bongo | bf68a4ffd67f850d6dd1c05fd3eb01f73d677812 | [
"MIT"
] | null | null | null | lib/bongo/map_to_model.ex | yatender-oktalk/bongo | bf68a4ffd67f850d6dd1c05fd3eb01f73d677812 | [
"MIT"
] | null | null | null | defmodule Bongo.MapToModel do
def type(k, v) do
type_text = type_raw(k, v)
"\t\tfield(:#{k}, #{type_text}, enforce: true)\n"
end
def type_raw(k, v) do
cond do
is_boolean(v) ->
":boolean, :boolean"
is_integer(v) ->
":integer, :integer"
is_float(v) -> ":float, :float"
is_object_id(v) ->
":objectId, :string"
is_list(v) ->
cond do
length(v) > 0 ->
first_item = Enum.at(v, 0)
type = type_raw(k, first_item)
type
|> String.split(", ")
|> Enum.map(&("[#{&1}]"))
|> Enum.join(", ")
true ->
"[:any], [:any]"
end
is_map(v) ->
new_mod = generate_model_for(k, v, false)
"#{new_mod}.t(), #{new_mod}.t()"
String.valid?(v) ->
":string, :string"
true ->
":any, :any"
end
end
def is_object_id(%BSON.ObjectId{} = _v) do
true
end
def is_object_id(_) do
false
end
def generate_model_for(pmodel_name, model, is_collection \\ true) do
fields = Enum.map(model, fn {k, v} -> type(k, v) end)
model_name = "Models.#{String.capitalize(to_string(pmodel_name))}"
collection_name = String.downcase(to_string(pmodel_name))
config_text =
case is_collection do
true -> "[collection_name: \"#{collection_name}\"]"
false -> "[is_collection: false]"
end
File.write!(
"#{collection_name}.ex",
"""
defmodule #{model_name} do
\tuse Bongo.Model, #{config_text}\n
\tmodel do
#{fields}
\tend
end
"""
)
model_name
end
end
| 21.435897 | 70 | 0.513756 |
1cd9c97c5a2f7782363c38871d3d529ac3e4a434 | 1,543 | ex | Elixir | clients/service_directory/lib/google_api/service_directory/v1/model/empty.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/service_directory/lib/google_api/service_directory/v1/model/empty.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/service_directory/lib/google_api/service_directory/v1/model/empty.ex | dazuma/elixir-google-api | 6a9897168008efe07a6081d2326735fe332e522c | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.ServiceDirectory.V1.Model.Empty do
@moduledoc """
A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`.
## Attributes
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{}
end
defimpl Poison.Decoder, for: GoogleApi.ServiceDirectory.V1.Model.Empty do
def decode(value, options) do
GoogleApi.ServiceDirectory.V1.Model.Empty.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceDirectory.V1.Model.Empty do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.738095 | 345 | 0.760207 |
1cda01749e5e64cf11d59255201f27aa94ad7709 | 1,986 | exs | Elixir | mix.exs | anthonyfalzetti/gremlex | 210ddbfb0ca9448e5e1ad910fc9ae055b4c1c44c | [
"MIT"
] | null | null | null | mix.exs | anthonyfalzetti/gremlex | 210ddbfb0ca9448e5e1ad910fc9ae055b4c1c44c | [
"MIT"
] | null | null | null | mix.exs | anthonyfalzetti/gremlex | 210ddbfb0ca9448e5e1ad910fc9ae055b4c1c44c | [
"MIT"
] | null | null | null | defmodule Gremlex.MixProject do
use Mix.Project
def project do
[
app: :gremlex,
version: "0.1.1",
elixir: "~> 1.6",
elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod,
deps: deps(),
description: description(),
package: package(),
test_coverage: [tool: ExCoveralls],
source_url: "https://github.com/Revmaker/gremlex",
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
],
docs: [
main: "Gremlex", # The main page in the docs
logo: "logo.png",
extras: ["README.md"]
]
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {Gremlex.Application, []}
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:poison, "~> 3.1"},
{:httpoison, "~> 1.3.1"},
{:confex, "~> 3.2.3"},
{:websockex, "~> 0.4.0"},
{:uuid, "~> 1.1"},
{:poolboy, "~> 1.5.1"},
{:socket, "~> 0.3"},
{:mix_test_watch, "~> 0.3", only: :dev, runtime: false},
{:ex_doc, "~> 0.19", only: :dev, runtime: false},
{:mock, "~> 0.2.0", only: :test},
{:excoveralls, "~> 0.7", only: :test},
{:stream_data, "~> 0.1", only: :test}
]
end
defp description do
"An Elixir client for Gremlin.
Gremlex does not support all functions (yet). It is pretty early on in it's development. But you can always use raw Gremlin queries by using Client.query(\"<Insert gremlin query>\")"
end
defp package() do
[
name: "gremlex",
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/Revmaker/gremlex"}
]
end
end
| 26.837838 | 186 | 0.556898 |
1cda09b840416cdb4ca04ee55c9c1e733d8b118c | 7,056 | exs | Elixir | test/io/reader_test.exs | Tux9001/05AB1E | 8b28b648961c19217cc8e481714e33a4a16f41c2 | [
"MIT"
] | 734 | 2015-12-23T01:53:01.000Z | 2022-03-26T04:06:21.000Z | test/io/reader_test.exs | Tux9001/05AB1E | 8b28b648961c19217cc8e481714e33a4a16f41c2 | [
"MIT"
] | 166 | 2016-01-01T00:57:56.000Z | 2022-03-25T19:11:54.000Z | test/io/reader_test.exs | Tux9001/05AB1E | 8b28b648961c19217cc8e481714e33a4a16f41c2 | [
"MIT"
] | 88 | 2015-12-23T17:20:19.000Z | 2022-03-16T19:07:55.000Z | defmodule ReaderTest do
use ExUnit.Case
alias Reading.Reader
alias Reading.CodePage
import ExUnit.CaptureIO
import TestHelper
test "utf8 to osabie encoding" do
assert CodePage.utf8_to_osabie("Γ") == 16
assert CodePage.utf8_to_osabie("λ") == 173
assert capture_io(:stderr, fn -> CodePage.utf8_to_osabie("物") end) == "Unrecognized byte value: 物\n"
end
test "osabie to utf8 encoding" do
assert CodePage.osabie_to_utf8(16) == "Γ"
assert CodePage.osabie_to_utf8(173) == "λ"
assert capture_io(:stderr, fn -> CodePage.osabie_to_utf8(399) end) == "Invalid osabie byte found: 399\n"
end
test "read utf8 encoded file" do
assert file_test(fn file -> File.write!(file, "5L€È3+"); Reader.read_file(file, :utf_8) end) == ["5", "L", "€", "È", "3", "+"]
end
test "read osabie encoded file" do
assert file_test(fn file -> File.write!(file, <<53, 76, 128, 200, 51, 43>>); Reader.read_file(file, :osabie) end) == ["5", "L", "€", "È", "3", "+"]
end
test "read number from code" do
assert Reader.read_step("123abc") == {:number, "123", "abc"}
end
test "read number from code with no remaining code" do
assert Reader.read_step("123") == {:number, "123", ""}
end
test "read number from code with leading zeroes" do
assert Reader.read_step("0123c") == {:number, "0123", "c"}
end
test "read decimal number" do
assert Reader.read_step("1.2a") == {:number, "1.2", "a"}
end
test "read decimal number without leading number" do
assert Reader.read_step(".2a") == {:number, ".2", "a"}
end
test "read decimal number with no remaining code" do
assert Reader.read_step(".2") == {:number, ".2", ""}
end
test "read nullary function" do
assert Reader.read_step("∞abc") == {:nullary_op, "∞", "abc"}
end
test "read nullary function with no remaining code" do
assert Reader.read_step("∞") == {:nullary_op, "∞", ""}
end
test "read unary function" do
assert Reader.read_step(">abc") == {:unary_op, ">", "abc"}
end
test "read unary function with no remaining code" do
assert Reader.read_step(">") == {:unary_op, ">", ""}
end
test "read binary function" do
assert Reader.read_step("+abc") == {:binary_op, "+", "abc"}
end
test "read binary function with no remaining code" do
assert Reader.read_step("+") == {:binary_op, "+", ""}
end
test "read normal string" do
assert Reader.read_step("\"abc\"def") == {:string, "abc", "def"}
end
test "read normal string with newlines" do
assert Reader.read_step("\"abc\ndef\"ghi") == {:string, "abc\ndef", "ghi"}
end
test "read normal with no remaining code" do
assert Reader.read_step("\"abc\"") == {:string, "abc", ""}
end
test "read string without end delimiter" do
assert Reader.read_step("\"abc") == {:string, "abc", ""}
end
test "read string with newlines without end delimiter" do
assert Reader.read_step("\"abc\n") == {:string, "abc\n", ""}
end
test "read end of file" do
assert Reader.read_step("") == {:eof, nil, nil}
end
test "read compressed number" do
assert Reader.read_step("•1æa•") == {:number, 123456, ""}
end
test "read compressed number without end delimiter" do
assert Reader.read_step("•1æa") == {:number, 123456, ""}
end
test "read empty compressed number" do
assert Reader.read_step("••") == {:number, 0, ""}
end
test "read compressed string upper" do
assert Reader.read_step("‘Ÿ™,‚ï!‘") == {:string, "HELLO, WORLD!", ""}
end
test "read compressed string one compressed char" do
assert Reader.read_step("‘Ÿ") == {:string, "Ÿ", ""}
end
test "read compressed string title" do
assert Reader.read_step("”Ÿ™,‚ï!") == {:string, "Hello, World!", ""}
end
test "read compressed string title one compressed char" do
assert Reader.read_step("”Ÿ") == {:string, "Ÿ", ""}
end
test "read compressed string normal" do
assert Reader.read_step("“Ÿ™,‚ï!") == {:string, "hello, world!", ""}
end
test "read compressed string normal one compressed char" do
assert Reader.read_step("“Ÿ") == {:string, "Ÿ", ""}
end
test "read compressed string no space" do
assert Reader.read_step("’Ÿ™,‚ï!") == {:string, "hello,world!", ""}
end
test "read compressed string no space one compressed char" do
assert Reader.read_step("’Ÿ") == {:string, "Ÿ", ""}
end
test "read normal 1 char string" do
assert Reader.read_step("'a1") == {:string, "a", "1"}
end
test "read normal 2 char string" do
assert Reader.read_step("„ab1") == {:string, "ab", "1"}
end
test "read normal 3 char string" do
assert Reader.read_step("…abc1") == {:string, "abc", "1"}
end
test "read compressed 1 word string" do
assert Reader.read_step("'٪1") == {:string, "hello", "1"}
end
test "read compressed 2 word string" do
assert Reader.read_step("„Ÿ™‚ï1") == {:string, "hello world", "1"}
end
test "read compressed 3 word string" do
assert Reader.read_step("…Ÿ™‚1") == {:string, "hello world hello", "1"}
end
test "read compressed char 1 char string" do
assert Reader.read_step("'Ÿ1") == {:string, "Ÿ", "1"}
end
test "read 2 char string with one word and one char" do
assert Reader.read_step("„Ÿ™12") == {:string, "hello1", "2"}
assert Reader.read_step("„1Ÿ™2") == {:string, "1 hello", "2"}
end
test "read 2 char string with one compressed char and one char" do
assert Reader.read_step("„1™2") == {:string, "1™", "2"}
end
test "read 3 char string with one word and two chars" do
assert Reader.read_step("…Ÿ™abc") == {:string, "helloab", "c"}
end
test "read 3 char string with one word and one char and one compressed char" do
assert Reader.read_step("…Ÿ™aŸc") == {:string, "helloaŸ", "c"}
end
test "read compressed number char" do
assert Reader.read_step("Ƶ1abc") == {:number, 102, "abc"}
end
test "read compressed number char without remaining code" do
assert Reader.read_step("Ƶa") == {:number, 137, ""}
end
test "read two-char compressed number" do
assert Reader.read_step("Ž4çabc") == {:number, 1250, "abc"}
end
test "read two-char compressed number without remaining code" do
assert Reader.read_step("Ž4ç") == {:number, 1250, ""}
end
test "read compressed alphabetic string" do
assert Reader.read_step(".•Uÿ/õDÀтÂñ‚Δθñ8=öwÁβPb•") == {:string, "i want this string to be compressed", ""}
end
test "read compressed alphabetic string without end delimiter" do
assert Reader.read_step(".•Uÿ/õDÀтÂñ‚Δθñ8=öwÁβPb") == {:string, "i want this string to be compressed", ""}
end
end | 33.126761 | 155 | 0.595522 |
1cda19ab3af77216475de06b0b7c2fd2ab4c9dcf | 518 | ex | Elixir | test/support/factories/contato_factory.ex | prefeitura-municipal-campos/kirby | 290835751a28cd7e39be2e721de243e495273be7 | [
"BSD-3-Clause"
] | null | null | null | test/support/factories/contato_factory.ex | prefeitura-municipal-campos/kirby | 290835751a28cd7e39be2e721de243e495273be7 | [
"BSD-3-Clause"
] | null | null | null | test/support/factories/contato_factory.ex | prefeitura-municipal-campos/kirby | 290835751a28cd7e39be2e721de243e495273be7 | [
"BSD-3-Clause"
] | null | null | null | defmodule Kirby.ContatoFactory do
@moduledoc false
defmacro __using__(_opts) do
quote do
def unique_user_email, do: "user#{System.unique_integer()}@example.com"
def contato_factory(attrs) do
contact = %Kirby.Entities.Contato{
email: unique_user_email(),
celular: "(11)98765-4329",
endereco: sequence(:endereco, &"Endereço #{&1}")
}
contact
|> merge_attributes(attrs)
|> evaluate_lazy_attributes()
end
end
end
end
| 23.545455 | 77 | 0.617761 |
1cda358361394e02b09db1568e2ff7b12f425e86 | 1,697 | ex | Elixir | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v3alpha1_create_version_operation_metadata.ex | ukrbublik/elixir-google-api | 364cec36bc76f60bec94cbcad34844367a29d174 | [
"Apache-2.0"
] | null | null | null | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v3alpha1_create_version_operation_metadata.ex | ukrbublik/elixir-google-api | 364cec36bc76f60bec94cbcad34844367a29d174 | [
"Apache-2.0"
] | null | null | null | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v3alpha1_create_version_operation_metadata.ex | ukrbublik/elixir-google-api | 364cec36bc76f60bec94cbcad34844367a29d174 | [
"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.Dialogflow.V2.Model.GoogleCloudDialogflowV3alpha1CreateVersionOperationMetadata do
@moduledoc """
Metadata associated with the long running operation for Versions.CreateVersion.
## Attributes
* `version` (*type:* `String.t`, *default:* `nil`) - Name of the created version. Format: `projects//locations//agents//flows//versions/`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:version => String.t()
}
field(:version)
end
defimpl Poison.Decoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV3alpha1CreateVersionOperationMetadata do
def decode(value, options) do
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV3alpha1CreateVersionOperationMetadata.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV3alpha1CreateVersionOperationMetadata do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.634615 | 142 | 0.757808 |
1cda74ac80075697239d12d5cf74f5d246d155b6 | 1,268 | ex | Elixir | lib/stripe_mock/id.ex | whitepaperclip/stripe_mock | a8ba9101a04216f26d0650eb38448173d8e090a1 | [
"MIT"
] | 4 | 2019-06-04T20:35:21.000Z | 2021-09-02T04:04:21.000Z | lib/stripe_mock/id.ex | whitepaperclip/stripe_mock | a8ba9101a04216f26d0650eb38448173d8e090a1 | [
"MIT"
] | 2 | 2020-02-04T17:38:12.000Z | 2021-04-29T06:59:06.000Z | lib/stripe_mock/id.ex | whitepaperclip/stripe_mock | a8ba9101a04216f26d0650eb38448173d8e090a1 | [
"MIT"
] | null | null | null | defmodule StripeMock.ID do
@moduledoc """
Generates a somewhat Stripe-esque random ID string. Pretty much a base52-encoded UUID.
"""
alias StripeMock.API
@spec generate() :: String.t()
def generate() do
from_bytes(:crypto.strong_rand_bytes(16))
end
@spec from_uuid(String.t()) :: String.t() | none()
def from_uuid(uuid) do
{:ok, bytes} = Ecto.UUID.dump(uuid)
from_bytes(bytes)
end
defp from_bytes(bytes) do
bytes
|> :erlang.binary_to_list()
|> Enum.reduce(1, &if(&1 > 0, do: &1 * &2, else: &2))
|> StripeMock.Base52.encode()
end
@spec type(module()) :: atom()
def type(%{} = map), do: type(map.__struct__)
def type(API.Card), do: :card
def type(API.Charge), do: :charge
def type(API.Customer), do: :customer
def type(API.PaymentMethod), do: :payment_method
def type(API.PaymentIntent), do: :payment_intent
def type(API.Refund), do: :refund
def type(API.Token), do: :token
@spec type(map()) :: String.t()
def prefix(%API.Card{}), do: "card"
def prefix(%API.Charge{}), do: "ch"
def prefix(%API.Customer{}), do: "cus"
def prefix(%API.PaymentMethod{}), do: "pm"
def prefix(%API.PaymentIntent{}), do: "pi"
def prefix(%API.Refund{}), do: "re"
def prefix(%API.Token{}), do: "tok"
end
| 28.818182 | 88 | 0.63959 |
1cdac1d3577655290cdd9574466c7994719174df | 3,675 | exs | Elixir | test/doumi/case_helper_test.exs | nallwhy/doumi | 6324c340e0ad1974000f7ce2903fc0cccfae12f4 | [
"MIT"
] | 1 | 2020-08-25T23:43:51.000Z | 2020-08-25T23:43:51.000Z | test/doumi/case_helper_test.exs | nallwhy/doumi | 6324c340e0ad1974000f7ce2903fc0cccfae12f4 | [
"MIT"
] | null | null | null | test/doumi/case_helper_test.exs | nallwhy/doumi | 6324c340e0ad1974000f7ce2903fc0cccfae12f4 | [
"MIT"
] | null | null | null | defmodule Doumi.CaseHelperTest do
use ExUnit.Case, async: true
alias Doumi.CaseHelper
describe "same_records?/2" do
defmodule RecordTestModule do
use Ecto.Schema
@primary_key false
schema "record_test" do
field(:primary_key0, :integer, primary_key: true)
field(:primary_key1, :string, primary_key: true)
field(:field0, :integer)
end
end
test "returns true with the same records" do
record = %RecordTestModule{
primary_key0: 1,
primary_key1: "a",
field0: 1
}
assert CaseHelper.same_records?(record, record) == true
end
test "returns true with the two records have the same primary keys" do
primary_key0 = 1
primary_key1 = "a"
record0 = %RecordTestModule{
primary_key0: primary_key0,
primary_key1: primary_key1,
field0: 1
}
record1 = %RecordTestModule{
primary_key0: primary_key0,
primary_key1: primary_key1,
field0: 2
}
assert CaseHelper.same_records?(record0, record1) == true
end
test "returns false with the two records have different primary keys" do
primary_key0 = 1
record0 = %RecordTestModule{
primary_key0: primary_key0,
primary_key1: "a",
field0: 1
}
record1 = %RecordTestModule{
primary_key0: primary_key0,
primary_key1: "b",
field0: 1
}
assert CaseHelper.same_records?(record0, record1) == false
end
end
describe "same_fields?/3" do
defmodule FieldTestModule do
defstruct [:field0, :field1]
end
test "returns true with the two struct have the same values with the fields" do
struct0 = %FieldTestModule{field0: 1, field1: "a"}
struct1 = %FieldTestModule{field0: 1, field1: "b"}
assert CaseHelper.same_fields?(struct0, struct1, [:field0]) == true
end
test "returns true with the two struct have not the same values with the fields" do
struct0 = %FieldTestModule{field0: 1, field1: "a"}
struct1 = %FieldTestModule{field0: 1, field1: "b"}
assert CaseHelper.same_fields?(struct0, struct1, [:field1]) == false
end
end
describe "same_values?/2 with DateTime" do
test "returns true with the same datetimes" do
now = DateTime.utc_now()
assert CaseHelper.same_values?(now, now) == true
end
test "returns true with the same time but not the same precision datetimes" do
{:ok, datetime0, _} = DateTime.from_iso8601("2015-01-23T23:50:07.123000+09:00")
{:ok, datetime1, _} = DateTime.from_iso8601("2015-01-23T23:50:07.123+09:00")
assert datetime0 != datetime1
assert CaseHelper.same_values?(datetime0, datetime1) == true
end
test "returns false with not the same time datetimes" do
datetime0 = DateTime.utc_now()
datetime1 = DateTime.utc_now()
assert CaseHelper.same_values?(datetime0, datetime1) == false
end
end
describe "same_values?/2 with Decimal" do
test "returns true with the same decimals" do
decimal = Decimal.new("0.1")
assert CaseHelper.same_values?(decimal, decimal) == true
end
test "returns true with the same value but not the same precision decimals" do
decimal0 = Decimal.new("0.1")
decimal1 = Decimal.new("0.10")
assert decimal0 != decimal1
assert CaseHelper.same_values?(decimal0, decimal1) == true
end
test "returns false with not the same value decimals" do
decimal0 = Decimal.new("0.1")
decimal1 = Decimal.new("0.2")
assert CaseHelper.same_values?(decimal0, decimal1) == false
end
end
end
| 28.053435 | 87 | 0.651156 |
1cdac384799f06ca821a7d649a9f546e0f88670a | 1,244 | exs | Elixir | mix.exs | Tochemey/ExString | 340175ed6602def53b76d3fa1eb735d598468060 | [
"Apache-2.0"
] | 3 | 2017-05-07T21:07:17.000Z | 2018-09-13T13:28:14.000Z | mix.exs | Tochemey/ExString | 340175ed6602def53b76d3fa1eb735d598468060 | [
"Apache-2.0"
] | null | null | null | mix.exs | Tochemey/ExString | 340175ed6602def53b76d3fa1eb735d598468060 | [
"Apache-2.0"
] | null | null | null | defmodule ExStringUtil.Mixfile do
use Mix.Project
def project do
[app: :ex_string_util,
version: "0.1.0",
elixir: "~> 1.4",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps()]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
# Specify extra applications you'll use from Erlang/Elixir
[extra_applications: [:logger]]
end
defp description do
"""
String Utility module. It helps perform some validation during application development
particularly the ones that involve user input like REST API or Web Applications.
"""
end
defp package do
[
files: ["lib", "mix.exs", "README.md"],
maintainers: ["Arsene Tochemey GANDOTE"],
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/Tochemey/ExString.git",
"Docs" => "https://hexdocs.pm/ex_string_util"}
]
end
# Type "mix help deps" for more examples and options
defp deps do
[
{:ex_doc, "~> 0.11", only: :dev},
{:earmark, "~> 0.1", only: :dev},
{:dialyxir, "~> 0.3", only: [:dev]}
]
end
end
| 25.387755 | 90 | 0.625402 |
1cdad646db4b799c66f0a9ad2bd33e425d9815f9 | 26 | ex | Elixir | lib/keen_auth.ex | KeenMate/keen_auth | 55ef1903e446a666ff2762a03080999196c5c355 | [
"MIT"
] | null | null | null | lib/keen_auth.ex | KeenMate/keen_auth | 55ef1903e446a666ff2762a03080999196c5c355 | [
"MIT"
] | null | null | null | lib/keen_auth.ex | KeenMate/keen_auth | 55ef1903e446a666ff2762a03080999196c5c355 | [
"MIT"
] | null | null | null | defmodule KeenAuth do
end
| 8.666667 | 21 | 0.846154 |
1cdae2a92d33cf9f5e424edd627241869fd8b235 | 1,345 | exs | Elixir | test/crit_biz/view_models/setup/bulk_animal_vm_4_insert_all_test.exs | brownt23/crit19 | c45c7b3ae580c193168d83144da0eeb9bc91c8a9 | [
"MIT"
] | 6 | 2019-07-16T19:31:23.000Z | 2021-06-05T19:01:05.000Z | test/crit_biz/view_models/setup/bulk_animal_vm_4_insert_all_test.exs | brownt23/crit19 | c45c7b3ae580c193168d83144da0eeb9bc91c8a9 | [
"MIT"
] | null | null | null | test/crit_biz/view_models/setup/bulk_animal_vm_4_insert_all_test.exs | brownt23/crit19 | c45c7b3ae580c193168d83144da0eeb9bc91c8a9 | [
"MIT"
] | 3 | 2020-02-24T23:38:27.000Z | 2020-08-01T23:50:17.000Z | defmodule CritBiz.ViewModels.Setup.BulkAnimalVM.InsertAllTest do
use Crit.DataCase, async: true
alias CritBiz.ViewModels.Setup, as: VM
alias Crit.Schemas
use FlowAssertions
@daisy_to_insert Factory.build(:animal, name: "Daisy")
setup do
{:ok, [daisy_vm]} =
VM.BulkAnimal.insert_all([@daisy_to_insert], @institution)
[daisy_vm: daisy_vm]
end
describe "success" do
test "what the on-disk version looks like", %{daisy_vm: daisy_vm} do
Schemas.Animal.Get.one_by_id(daisy_vm.id, @institution)
|> assert_shape(%Schemas.Animal{})
|> assert_same_schema(@daisy_to_insert, ignoring: [:id, :lock_version])
# We don't check the lock version because we don't care what it's starting
# value is, so long as it increments correctly. (It happens to be 2.)
end
test "what the returned view models look like", %{daisy_vm: daisy_vm} do
expected = VM.Animal.fetch(:one_for_summary, daisy_vm.id, @institution)
daisy_vm
|> assert_shape(%VM.Animal{})
|> assert_same_map(expected)
end
end
test "trying to rename an animal to an existing animal", %{daisy_vm: daisy_vm} do
assert {:error, :constraint, %{message: message}} =
VM.BulkAnimal.insert_all([@daisy_to_insert], @institution)
assert message =~ daisy_vm.name
end
end
| 31.27907 | 83 | 0.684758 |
1cdb14485bcaf600f5e1dfe7e4f907dc89ed065d | 187 | ex | Elixir | lib/cielo/entities/base.ex | brunolouvem/cielo | ec1bc4c728ccf2f0a577aec5e0c1657bc97c964b | [
"MIT"
] | 1 | 2020-11-05T01:21:29.000Z | 2020-11-05T01:21:29.000Z | lib/cielo/entities/base.ex | brunolouvem/cielo | ec1bc4c728ccf2f0a577aec5e0c1657bc97c964b | [
"MIT"
] | null | null | null | lib/cielo/entities/base.ex | brunolouvem/cielo | ec1bc4c728ccf2f0a577aec5e0c1657bc97c964b | [
"MIT"
] | null | null | null | defmodule Cielo.Entities.Base do
@moduledoc false
defmacro __using__(_opts) do
quote do
@moduledoc false
use Ecto.Schema
import Ecto.Changeset
end
end
end
| 17 | 32 | 0.684492 |
1cdb271a761d67b32f0ae7cd262e6d466f0ef084 | 1,479 | exs | Elixir | mix.exs | ex-aws/ex_aws_cloudformation | 8fe8ceb62ab9d018a572038387fe98f3ffdc4212 | [
"Unlicense",
"MIT"
] | null | null | null | mix.exs | ex-aws/ex_aws_cloudformation | 8fe8ceb62ab9d018a572038387fe98f3ffdc4212 | [
"Unlicense",
"MIT"
] | 3 | 2017-10-19T01:31:27.000Z | 2021-02-18T13:14:02.000Z | mix.exs | ex-aws/ex_aws_cloudformation | 8fe8ceb62ab9d018a572038387fe98f3ffdc4212 | [
"Unlicense",
"MIT"
] | 4 | 2017-10-27T05:36:35.000Z | 2019-10-29T07:28:30.000Z | defmodule ExAws.Cloudformation.Mixfile do
use Mix.Project
@version "2.0.1"
@service "cloudformation"
@url "https://github.com/ex-aws/ex_aws_#{@service}"
def project do
[
app: :ex_aws_cloudformation,
version: @version,
elixir: "~> 1.5",
elixirc_paths: elixirc_paths(Mix.env),
start_permanent: Mix.env == :prod,
deps: deps(),
name: "ExAws.Cloudformation",
package: package(),
deps: deps(),
docs: [main: "ExAws.Cloudformation", source_ref: "v#{@version}",
source_url: @url]
]
end
defp package do
[description: "ExAws.Cloudformation service package",
files: ["lib", "config", "mix.exs", "README*"],
maintainers: ["Ben Wilson"],
licenses: ["MIT"],
links: %{github: @url},
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib",]
# 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
[
{:ex_doc, ">= 0.0.0", only: :dev},
{:hackney, ">= 0.0.0", only: [:dev, :test]},
{:sweet_xml, ">= 0.0.0", only: [:dev, :test]},
{:poison, ">= 0.0.0", only: [:dev, :test]},
ex_aws(),
]
end
defp ex_aws() do
case System.get_env("AWS") do
"LOCAL" -> {:ex_aws, path: "../ex_aws"}
_ -> {:ex_aws, "~> 2.0"}
end
end
end
| 24.245902 | 70 | 0.563895 |
1cdb711bc3a74164c02886999f60f89750961616 | 948 | ex | Elixir | lib/format_parser/video.ex | ahtung/format_parser.ex | b4c858f9f3dedd8e62ac17b633d951eb247b7c1f | [
"Apache-2.0"
] | 21 | 2018-02-17T18:49:37.000Z | 2020-03-13T11:14:30.000Z | lib/format_parser/video.ex | ahtung/format_parser.ex | b4c858f9f3dedd8e62ac17b633d951eb247b7c1f | [
"Apache-2.0"
] | 20 | 2018-02-15T07:17:56.000Z | 2021-01-13T13:08:49.000Z | lib/format_parser/video.ex | dunyakirkali/format_parser.ex | 418a6ff5d83be4bcaaa057b4f7eb652c1add2ae6 | [
"Apache-2.0"
] | 1 | 2020-01-28T09:39:00.000Z | 2020-01-28T09:39:00.000Z | defmodule FormatParser.Video do
alias __MODULE__
@moduledoc """
A Video struct and functions.
The Video struct contains the fields format, width_px, height_px and nature.
"""
defstruct [:format, :width_px, :height_px, nature: :video]
@doc """
Parses a file and extracts some information from it.
Takes a `binary file` as argument.
Returns a struct which contains all information that has been extracted from the file if the file is recognized.
Returns the following tuple if file not recognized: `{:error, file}`.
"""
def parse({:error, file}) when is_binary(file) do
parse_video(file)
end
def parse(file) when is_binary(file) do
parse_video(file)
end
def parse(result) do
result
end
defp parse_video(file) do
case file do
<<"FLV", 0x01, x::binary>> -> parse_flv(x)
_ -> {:error, file}
end
end
defp parse_flv(<<_::binary>>) do
%Video{format: :flv}
end
end
| 21.066667 | 114 | 0.675105 |
1cdb808e8bda1e62603a28f0509bf781466b1f31 | 679 | exs | Elixir | mix.exs | renovate-tests/ex | 2e02d5a1e59122c13a0ebd2321f5cb291160aaa8 | [
"MIT"
] | null | null | null | mix.exs | renovate-tests/ex | 2e02d5a1e59122c13a0ebd2321f5cb291160aaa8 | [
"MIT"
] | null | null | null | mix.exs | renovate-tests/ex | 2e02d5a1e59122c13a0ebd2321f5cb291160aaa8 | [
"MIT"
] | null | null | null | defmodule Ex2.MixProject do
use Mix.Project
def project do
[
apps_path: "apps",
elixir: "~> 1.4",
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
deps: deps(),
preferred_cli_env: [
coveralls: :test,
"coveralls.html": :test,
"coveralls.json": :test
],
test_coverage: [tool: ExCoveralls]
]
end
# Dependencies listed here are available only for this
# project and cannot be accessed from applications inside
# the apps folder.
#
# Run "mix help deps" for examples and options.
defp deps do
[
{:excoveralls, "~> 0.10", only: :test}
]
end
end
| 21.903226 | 59 | 0.590574 |
1cdb9a49c0fbf85eede306d75cc7a88eedd3d30e | 5,012 | ex | Elixir | lib/media_server/accounts/user.ex | MNDL-27/midarr-server | b749707a1777205cea2d93349cde2ef922e527ec | [
"MIT"
] | null | null | null | lib/media_server/accounts/user.ex | MNDL-27/midarr-server | b749707a1777205cea2d93349cde2ef922e527ec | [
"MIT"
] | null | null | null | lib/media_server/accounts/user.ex | MNDL-27/midarr-server | b749707a1777205cea2d93349cde2ef922e527ec | [
"MIT"
] | null | null | null | defmodule MediaServer.Accounts.User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field :email, :string
field :name, :string
field :password, :string, virtual: true, redact: true
field :hashed_password, :string, redact: true
field :confirmed_at, :naive_datetime
field :is_admin, :boolean
has_many :movie_watches, MediaServer.Watches.Movie
has_many :episode_watches, MediaServer.Watches.Episode
timestamps()
end
@doc """
A user changeset for registration.
It is important to validate the length of both email and password.
Otherwise databases may truncate the email without warnings, which
could lead to unpredictable or insecure behaviour. Long passwords may
also be very expensive to hash for certain algorithms.
## Options
* `:hash_password` - Hashes the password so it can be stored securely
in the database and ensures the password field is cleared to prevent
leaks in the logs. If password hashing is not needed and clearing the
password field is not desired (like when using this changeset for
validations on a LiveView form), this option can be set to `false`.
Defaults to `true`.
"""
def registration_changeset(user, attrs, opts \\ []) do
user
|> cast(attrs, [:email, :name, :password, :is_admin])
|> validate_email()
|> validate_name()
|> validate_password(opts)
end
defp validate_email(changeset) do
changeset
|> validate_required([:email])
|> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces")
|> validate_length(:email, max: 160)
|> unsafe_validate_unique(:email, MediaServer.Repo)
|> unique_constraint(:email)
end
defp validate_name(changeset) do
changeset
|> validate_required([:name])
|> validate_length(:name, max: 40)
end
defp validate_password(changeset, opts) do
changeset
|> validate_required([:password])
|> validate_length(:password, min: 12, max: 72)
# |> validate_format(:password, ~r/[a-z]/, message: "at least one lower case character")
# |> validate_format(:password, ~r/[A-Z]/, message: "at least one upper case character")
# |> validate_format(:password, ~r/[!?@#$%^&*_0-9]/, message: "at least one digit or punctuation character")
|> maybe_hash_password(opts)
end
defp maybe_hash_password(changeset, opts) do
hash_password? = Keyword.get(opts, :hash_password, true)
password = get_change(changeset, :password)
if hash_password? && password && changeset.valid? do
changeset
# If using Bcrypt, then further validate it is at most 72 bytes long
|> validate_length(:password, max: 72, count: :bytes)
|> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password))
|> delete_change(:password)
else
changeset
end
end
@doc """
A user changeset for changing the email.
It requires the email to change otherwise an error is added.
"""
def email_changeset(user, attrs) do
user
|> cast(attrs, [:email])
|> validate_email()
|> case do
%{changes: %{email: _}} = changeset -> changeset
%{} = changeset -> add_error(changeset, :email, "did not change")
end
end
@doc """
A user changeset for changing the password.
## Options
* `:hash_password` - Hashes the password so it can be stored securely
in the database and ensures the password field is cleared to prevent
leaks in the logs. If password hashing is not needed and clearing the
password field is not desired (like when using this changeset for
validations on a LiveView form), this option can be set to `false`.
Defaults to `true`.
"""
def password_changeset(user, attrs, opts \\ []) do
user
|> cast(attrs, [:password])
|> validate_confirmation(:password, message: "does not match password")
|> validate_password(opts)
end
def name_changeset(user, attrs \\ %{}) do
user
|> cast(attrs, [:name])
|> validate_name()
end
@doc """
Confirms the account by setting `confirmed_at`.
"""
def confirm_changeset(user) do
now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)
change(user, confirmed_at: now)
end
@doc """
Verifies the password.
If there is no user or the user doesn't have a password, we call
`Bcrypt.no_user_verify/0` to avoid timing attacks.
"""
def valid_password?(%MediaServer.Accounts.User{hashed_password: hashed_password}, password)
when is_binary(hashed_password) and byte_size(password) > 0 do
Bcrypt.verify_pass(password, hashed_password)
end
def valid_password?(_, _) do
Bcrypt.no_user_verify()
false
end
@doc """
Validates the current password otherwise adds an error to the changeset.
"""
def validate_current_password(changeset, password) do
if valid_password?(changeset.data, password) do
changeset
else
add_error(changeset, :current_password, "is not valid")
end
end
end
| 31.721519 | 112 | 0.684557 |
1cdba458f37a9a8ef9b96da05cfdbfd70069f85c | 1,156 | ex | Elixir | apps/gullintanni_web/lib/gullintanni_web/application.ex | gullintanni/gullintanni | 63c58b7ea438a4c6885a13842d8e33d3b1273ced | [
"0BSD"
] | 15 | 2016-08-09T21:27:54.000Z | 2020-12-03T11:21:10.000Z | apps/gullintanni_web/lib/gullintanni_web/application.ex | gullintanni/gullintanni | 63c58b7ea438a4c6885a13842d8e33d3b1273ced | [
"0BSD"
] | 15 | 2016-08-04T21:11:05.000Z | 2017-08-02T17:46:17.000Z | apps/gullintanni_web/lib/gullintanni_web/application.ex | gullintanni/gullintanni | 63c58b7ea438a4c6885a13842d8e33d3b1273ced | [
"0BSD"
] | null | null | null | defmodule GullintanniWeb.Application do
@moduledoc false
use Application
require Logger
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = http_workers()
opts = [strategy: :one_for_one, name: GullintanniWeb.Supervisor]
Supervisor.start_link(children, opts)
end
defp http_workers() do
if Application.get_env(:gullintanni_web, :enable_http_workers) do
[gullintanni_web_router()]
else
[]
end
end
defp gullintanni_web_router do
bind_ip = Application.fetch_env!(:gullintanni_web, :bind_ip)
bind_port = Application.fetch_env!(:gullintanni_web, :bind_port)
cowboy_opts =
case SocketAddress.new(bind_ip, bind_port) do
{:ok, socket} ->
_ = Logger.info "started listening on #{socket}"
SocketAddress.to_opts(socket)
{:error, :invalid_ip} ->
raise ArgumentError, "invalid :bind_ip configuration setting"
{:error, :invalid_port} ->
raise ArgumentError, "invalid :bind_port configuration setting"
end
Plug.Adapters.Cowboy.child_spec(:http, GullintanniWeb.Router, [], cowboy_opts)
end
end
| 27.52381 | 82 | 0.688581 |
1cdbdc84155b792f311f71492833bdea0cde291b | 607 | ex | Elixir | lib/webapp/notifications/notify_console.ex | runhyve/webapp | 434b074f98c1ebac657b56062c1c1a54e683dea1 | [
"BSD-2-Clause"
] | 12 | 2019-07-02T14:30:06.000Z | 2022-03-12T08:22:18.000Z | lib/webapp/notifications/notify_console.ex | runhyve/webapp | 434b074f98c1ebac657b56062c1c1a54e683dea1 | [
"BSD-2-Clause"
] | 9 | 2020-03-16T20:10:50.000Z | 2021-06-17T17:45:44.000Z | lib/webapp/notifications/notify_console.ex | runhyve/webapp | 434b074f98c1ebac657b56062c1c1a54e683dea1 | [
"BSD-2-Clause"
] | null | null | null | defmodule Webapp.Notifications.NotifyConsole do
use GenServer
require Logger
alias Phoenix.Socket.Broadcast
def start_link(_opts) do
GenServer.start_link(__MODULE__, [])
end
def init(_) do
Logger.info("Starting #{__MODULE__} module. Subscribing to events topic.")
WebappWeb.Endpoint.subscribe("events")
{:ok, %{}}
end
def handle_call(:get, _, state) do
{:reply, state, state}
end
def handle_info(%Broadcast{topic: _, event: _event, payload: payload}, _socket) do
Logger.info("[NotifyConsole] #{payload.severity}: #{payload.msg}")
{:noreply, []}
end
end | 24.28 | 84 | 0.69028 |
1cdbea60ca280cb7678e00e995631aaeb8af11a4 | 693 | ex | Elixir | platform/target/network/tzdata_task.ex | pdgonzalez872/farmbot_os | a444248f05ee8f4fe57f6a4865b942131960f76c | [
"MIT"
] | 2 | 2018-08-01T23:07:52.000Z | 2018-10-17T12:49:21.000Z | platform/target/network/tzdata_task.ex | pdgonzalez872/farmbot_os | a444248f05ee8f4fe57f6a4865b942131960f76c | [
"MIT"
] | null | null | null | platform/target/network/tzdata_task.ex | pdgonzalez872/farmbot_os | a444248f05ee8f4fe57f6a4865b942131960f76c | [
"MIT"
] | 1 | 2017-07-22T21:51:14.000Z | 2017-07-22T21:51:14.000Z | defmodule Farmbot.Target.Network.TzdataTask do
use GenServer
@fb_data_dir Path.join(Application.get_env(:farmbot, :data_path), "tmp_downloads")
@timer_ms round(1.2e+6) # 20 minutes
def start_link(_, _) do
GenServer.start_link(__MODULE__, [], [name: __MODULE__])
end
def init([]) do
send self(), :do_checkup
{:ok, nil, :hibernate}
end
def handle_info(:do_checkup, _) do
dir = @fb_data_dir
if File.exists?(dir) do
for obj <- File.ls!(dir) do
File.rm_rf!(Path.join(dir, obj))
end
end
{:noreply, restart_timer(self()), :hibernate}
end
defp restart_timer(pid) do
Process.send_after pid, :do_checkup, @timer_ms
end
end
| 22.354839 | 84 | 0.660895 |
1cdbef68e7944c003261455918a79244d4ce043a | 20,583 | ex | Elixir | lib/elixir/lib/regex.ex | ellbee/elixir | c1acfe9827f12ef58f7f301baad7497472cb4bc9 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/regex.ex | ellbee/elixir | c1acfe9827f12ef58f7f301baad7497472cb4bc9 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/regex.ex | ellbee/elixir | c1acfe9827f12ef58f7f301baad7497472cb4bc9 | [
"Apache-2.0"
] | null | null | null | defmodule Regex do
@moduledoc ~S"""
Provides regular expressions for Elixir. Built on top of Erlang's `:re`
module.
As the [`:re` module](http://www.erlang.org/doc/man/re.html), Regex is based on PCRE
(Perl Compatible Regular Expressions). More information can be
found in the [`:re` module documentation](http://www.erlang.org/doc/man/re.html).
Regular expressions in Elixir can be created using `Regex.compile!/2`
or using the special form with [`~r`](Kernel.html#sigil_r/2) or [`~R`](Kernel.html#sigil_R/2):
# A simple regular expressions that matches foo anywhere in the string
~r/foo/
# A regular expression with case insensitive and Unicode options
~r/foo/iu
A Regex is represented internally as the `Regex` struct. Therefore,
`%Regex{}` can be used whenever there is a need to match on them.
## Modifiers
The modifiers available when creating a Regex are:
* `unicode` (u) - enables Unicode specific patterns like `\p` and change
modifiers like `\w`, `\W`, `\s` and friends to also match on Unicode.
It expects valid Unicode strings to be given on match
* `caseless` (i) - adds case insensitivity
* `dotall` (s) - causes dot to match newlines and also set newline to
anycrlf; the new line setting can be overridden by setting `(*CR)` or
`(*LF)` or `(*CRLF)` or `(*ANY)` according to re documentation
* `multiline` (m) - causes `^` and `$` to mark the beginning and end of
each line; use `\A` and `\z` to match the end or beginning of the string
* `extended` (x) - whitespace characters are ignored except when escaped
and allow `#` to delimit comments
* `firstline` (f) - forces the unanchored pattern to match before or at the
first newline, though the matched text may continue over the newline
* `ungreedy` (U) - inverts the "greediness" of the regexp
(the previous `r` option is deprecated in favor of `U`)
The options not available are:
* `anchored` - not available, use `^` or `\A` instead
* `dollar_endonly` - not available, use `\z` instead
* `no_auto_capture` - not available, use `?:` instead
* `newline` - not available, use `(*CR)` or `(*LF)` or `(*CRLF)` or
`(*ANYCRLF)` or `(*ANY)` at the beginning of the regexp according to the
re documentation
## Captures
Many functions in this module handle what to capture in a regex
match via the `:capture` option. The supported values are:
* `:all` - all captured subpatterns including the complete matching string
(this is the default)
* `:first` - only the first captured subpattern, which is always the
complete matching part of the string; all explicitly captured subpatterns
are discarded
* `:all_but_first`- all but the first matching subpattern, i.e. all
explicitly captured subpatterns, but not the complete matching part of
the string
* `:none` - does not return matching subpatterns at all
* `:all_names` - captures all names in the Regex
* `list(binary)` - a list of named captures to capture
"""
defstruct re_pattern: nil, source: "", opts: ""
@type t :: %__MODULE__{re_pattern: term, source: binary, opts: binary}
defmodule CompileError do
defexception message: "regex could not be compiled"
end
@doc """
Compiles the regular expression.
The given options can either be a binary with the characters
representing the same regex options given to the `~r` sigil,
or a list of options, as expected by the Erlang's [`:re` module](http://www.erlang.org/doc/man/re.html).
It returns `{:ok, regex}` in case of success,
`{:error, reason}` otherwise.
## Examples
iex> Regex.compile("foo")
{:ok, ~r"foo"}
iex> Regex.compile("*foo")
{:error, {'nothing to repeat', 0}}
"""
@spec compile(binary, binary | [term]) :: {:ok, t} | {:error, any}
def compile(source, options \\ "")
def compile(source, options) when is_binary(options) do
case translate_options(options, []) do
{:error, rest} ->
{:error, {:invalid_option, rest}}
translated_options ->
compile(source, translated_options, options)
end
end
def compile(source, options) when is_list(options) do
compile(source, options, "")
end
defp compile(source, opts, doc_opts) when is_binary(source) do
case :re.compile(source, opts) do
{:ok, re_pattern} ->
{:ok, %Regex{re_pattern: re_pattern, source: source, opts: doc_opts}}
error ->
error
end
end
@doc """
Compiles the regular expression according to the given options.
Fails with `Regex.CompileError` if the regex cannot be compiled.
"""
@spec compile!(binary, binary | [term]) :: t
def compile!(source, options \\ "") do
case compile(source, options) do
{:ok, regex} -> regex
{:error, {reason, at}} -> raise Regex.CompileError, message: "#{reason} at position #{at}"
end
end
@doc """
Returns a boolean indicating whether there was a match or not.
## Examples
iex> Regex.match?(~r/foo/, "foo")
true
iex> Regex.match?(~r/foo/, "bar")
false
"""
@spec match?(t, String.t) :: boolean
def match?(%Regex{re_pattern: compiled}, string) when is_binary(string) do
:re.run(string, compiled, [{:capture, :none}]) == :match
end
@doc """
Returns `true` if the given `term` is a regex.
Otherwise returns `false`.
## Examples
iex> Regex.regex?(~r/foo/)
true
iex> Regex.regex?(0)
false
"""
@spec regex?(any) :: boolean
def regex?(term)
def regex?(%Regex{}), do: true
def regex?(_), do: false
@doc """
Runs the regular expression against the given string until the first match.
It returns a list with all captures or `nil` if no match occurred.
## Options
* `:return` - sets to `:index` to return indexes. Defaults to `:binary`.
* `:capture` - what to capture in the result. Check the moduledoc for `Regex`
to see the possible capture values.
## Examples
iex> Regex.run(~r/c(d)/, "abcd")
["cd", "d"]
iex> Regex.run(~r/e/, "abcd")
nil
iex> Regex.run(~r/c(d)/, "abcd", return: :index)
[{2, 2}, {3, 1}]
"""
@spec run(t, binary, [term]) :: nil | [binary] | [{integer, integer}]
def run(regex, string, options \\ [])
def run(%Regex{re_pattern: compiled}, string, options) when is_binary(string) do
return = Keyword.get(options, :return, :binary)
captures = Keyword.get(options, :capture, :all)
case :re.run(string, compiled, [{:capture, captures, return}]) do
:nomatch -> nil
:match -> []
{:match, results} -> results
end
end
@doc """
Returns the given captures as a map or `nil` if no captures are
found. The option `:return` can be set to `:index` to get indexes
back.
## Examples
iex> Regex.named_captures(~r/c(?<foo>d)/, "abcd")
%{"foo" => "d"}
iex> Regex.named_captures(~r/a(?<foo>b)c(?<bar>d)/, "abcd")
%{"bar" => "d", "foo" => "b"}
iex> Regex.named_captures(~r/a(?<foo>b)c(?<bar>d)/, "efgh")
nil
"""
@spec named_captures(t, String.t, [term]) :: map | nil
def named_captures(regex, string, options \\ []) when is_binary(string) do
names = names(regex)
options = Keyword.put(options, :capture, names)
results = run(regex, string, options)
if results, do: Enum.zip(names, results) |> Enum.into(%{})
end
@doc """
Returns the underlying `re_pattern` in the regular expression.
"""
@spec re_pattern(t) :: term
def re_pattern(%Regex{re_pattern: compiled}) do
compiled
end
@doc """
Returns the regex source as a binary.
## Examples
iex> Regex.source(~r(foo))
"foo"
"""
@spec source(t) :: String.t
def source(%Regex{source: source}) do
source
end
@doc """
Returns the regex options as a string.
## Examples
iex> Regex.opts(~r(foo)m)
"m"
"""
@spec opts(t) :: String.t
def opts(%Regex{opts: opts}) do
opts
end
@doc """
Returns a list of names in the regex.
## Examples
iex> Regex.names(~r/(?<foo>bar)/)
["foo"]
"""
@spec names(t) :: [String.t]
def names(%Regex{re_pattern: re_pattern}) do
{:namelist, names} = :re.inspect(re_pattern, :namelist)
names
end
@doc ~S"""
Same as `run/3`, but scans the target several times collecting all
matches of the regular expression.
A list of lists is returned, where each entry in the primary list represents a
match and each entry in the secondary list represents the captured contents.
## Options
* `:return` - sets to `:index` to return indexes. Defaults to `:binary`.
* `:capture` - what to capture in the result. Check the moduledoc for `Regex`
to see the possible capture values.
## Examples
iex> Regex.scan(~r/c(d|e)/, "abcd abce")
[["cd", "d"], ["ce", "e"]]
iex> Regex.scan(~r/c(?:d|e)/, "abcd abce")
[["cd"], ["ce"]]
iex> Regex.scan(~r/e/, "abcd")
[]
iex> Regex.scan(~r/\p{Sc}/u, "$, £, and €")
[["$"], ["£"], ["€"]]
"""
@spec scan(t, String.t, [term]) :: [[String.t]]
def scan(regex, string, options \\ [])
def scan(%Regex{re_pattern: compiled}, string, options) when is_binary(string) do
return = Keyword.get(options, :return, :binary)
captures = Keyword.get(options, :capture, :all)
options = [{:capture, captures, return}, :global]
case :re.run(string, compiled, options) do
:match -> []
:nomatch -> []
{:match, results} -> results
end
end
@doc """
Splits the given target based on the given pattern and in the given number of
parts.
## Options
* `:parts` - when specified, splits the string into the given number of
parts. If not specified, `:parts` defaults to `:infinity`, which will
split the string into the maximum number of parts possible based on the
given pattern.
* `:trim` - when `true`, removes empty strings (`""`) from the result.
* `:on` - specifies which captures to split the string on, and in what
order. Defaults to `:first` which means captures inside the regex do not
affect the splitting process.
* `:include_captures` - when `true`, includes in the result the matches of
the regular expression. Defaults to `false`.
## Examples
iex> Regex.split(~r{-}, "a-b-c")
["a", "b", "c"]
iex> Regex.split(~r{-}, "a-b-c", [parts: 2])
["a", "b-c"]
iex> Regex.split(~r{-}, "abc")
["abc"]
iex> Regex.split(~r{}, "abc")
["a", "b", "c", ""]
iex> Regex.split(~r{a(?<second>b)c}, "abc")
["", ""]
iex> Regex.split(~r{a(?<second>b)c}, "abc", on: [:second])
["a", "c"]
iex> Regex.split(~r{(x)}, "Elixir", include_captures: true)
["Eli", "x", "ir"]
iex> Regex.split(~r{a(?<second>b)c}, "abc", on: [:second], include_captures: true)
["a", "b", "c"]
"""
@spec split(t, String.t, [term]) :: [String.t]
def split(regex, string, options \\ [])
def split(%Regex{}, "", opts) do
if Keyword.get(opts, :trim, false) do
[]
else
[""]
end
end
def split(%Regex{re_pattern: compiled}, string, opts) when is_binary(string) and is_list(opts) do
on = Keyword.get(opts, :on, :first)
case :re.run(string, compiled, [:global, capture: on]) do
{:match, matches} ->
do_split(matches, string, 0,
parts_to_index(Keyword.get(opts, :parts, :infinity)),
Keyword.get(opts, :trim, false),
Keyword.get(opts, :include_captures, false))
:match ->
[string]
:nomatch ->
[string]
end
end
defp parts_to_index(:infinity), do: 0
defp parts_to_index(n) when is_integer(n) and n > 0, do: n
defp do_split(_, string, offset, _counter, true, _with_captures) when byte_size(string) <= offset,
do: []
defp do_split(_, string, offset, 1, _trim, _with_captures),
do: [binary_part(string, offset, byte_size(string) - offset)]
defp do_split([], string, offset, _counter, _trim, _with_captures),
do: [binary_part(string, offset, byte_size(string) - offset)]
defp do_split([[{pos, _} | h] | t], string, offset, counter, trim, with_captures) when pos - offset < 0,
do: do_split([h | t], string, offset, counter, trim, with_captures)
defp do_split([[] | t], string, offset, counter, trim, with_captures),
do: do_split(t, string, offset, counter, trim, with_captures)
defp do_split([[{pos, length} | h] | t], string, offset, counter, trim, true) do
new_offset = pos + length
keep = pos - offset
if keep == 0 and length == 0 do
do_split([h | t], string, new_offset, counter, trim, true)
else
<<_::binary-size(offset), part::binary-size(keep), match::binary-size(length), _::binary>> = string
if keep == 0 and (length == 0 or trim) do
[match | do_split([h | t], string, new_offset, counter - 1, trim, true)]
else
[part, match | do_split([h | t], string, new_offset, counter - 1, trim, true)]
end
end
end
defp do_split([[{pos, length} | h] | t], string, offset, counter, trim, false) do
new_offset = pos + length
keep = pos - offset
if keep == 0 and (length == 0 or trim) do
do_split([h | t], string, new_offset, counter, trim, false)
else
<<_::binary-size(offset), part::binary-size(keep), _::binary>> = string
[part | do_split([h | t], string, new_offset, counter - 1, trim, false)]
end
end
@doc ~S"""
Receives a regex, a binary and a replacement, returns a new
binary where all matches are replaced by the replacement.
The replacement can be either a string or a function. The string
is used as a replacement for every match and it allows specific
captures to be accessed via `\N` or `\g{N}`, where `N` is the
capture. In case `\0` is used, the whole match is inserted. Note
that in regexes the backslash needs to be escaped, hence in practice
you'll need to use `\\N` and `\\g{N}`.
When the replacement is a function, the function may have arity
N where each argument maps to a capture, with the first argument
being the whole match. If the function expects more arguments
than captures found, the remaining arguments will receive `""`.
## Options
* `:global` - when `false`, replaces only the first occurrence
(defaults to `true`)
## Examples
iex> Regex.replace(~r/d/, "abc", "d")
"abc"
iex> Regex.replace(~r/b/, "abc", "d")
"adc"
iex> Regex.replace(~r/b/, "abc", "[\\0]")
"a[b]c"
iex> Regex.replace(~r/a(b|d)c/, "abcadc", "[\\1]")
"[b][d]"
iex> Regex.replace(~r/\.(\d)$/, "500.5", ".\\g{1}0")
"500.50"
iex> Regex.replace(~r/a(b|d)c/, "abcadc", fn _, x -> "[#{x}]" end)
"[b][d]"
iex> Regex.replace(~r/a/, "abcadc", "A", global: false)
"Abcadc"
"""
@spec replace(t, String.t, String.t | (... -> String.t), [term]) :: String.t
def replace(regex, string, replacement, options \\ [])
def replace(regex, string, replacement, options)
when is_binary(string) and is_binary(replacement) and is_list(options) do
do_replace(regex, string, precompile_replacement(replacement), options)
end
def replace(regex, string, replacement, options)
when is_binary(string) and is_function(replacement) and is_list(options) do
{:arity, arity} = :erlang.fun_info(replacement, :arity)
do_replace(regex, string, {replacement, arity}, options)
end
defp do_replace(%Regex{re_pattern: compiled}, string, replacement, options) do
opts = if Keyword.get(options, :global) != false, do: [:global], else: []
opts = [{:capture, :all, :index} | opts]
case :re.run(string, compiled, opts) do
:nomatch ->
string
{:match, [mlist | t]} when is_list(mlist) ->
apply_list(string, replacement, [mlist | t]) |> IO.iodata_to_binary
{:match, slist} ->
apply_list(string, replacement, [slist]) |> IO.iodata_to_binary
end
end
defp precompile_replacement(""),
do: []
defp precompile_replacement(<<?\\, ?g, ?{, rest::binary>>) when byte_size(rest) > 0 do
{ns, <<?}, rest::binary>>} = pick_int(rest)
[List.to_integer(ns) | precompile_replacement(rest)]
end
defp precompile_replacement(<<?\\, ?\\, rest::binary>>) do
[<<?\\>> | precompile_replacement(rest)]
end
defp precompile_replacement(<<?\\, x, rest::binary>>) when x in ?0..?9 do
{ns, rest} = pick_int(rest)
[List.to_integer([x | ns]) | precompile_replacement(rest)]
end
defp precompile_replacement(<<x, rest::binary>>) do
case precompile_replacement(rest) do
[head | t] when is_binary(head) ->
[<<x, head::binary>> | t]
other ->
[<<x>> | other]
end
end
defp pick_int(<<x, rest::binary>>) when x in ?0..?9 do
{found, rest} = pick_int(rest)
{[x | found], rest}
end
defp pick_int(bin) do
{[], bin}
end
defp apply_list(string, replacement, list) do
apply_list(string, string, 0, replacement, list)
end
defp apply_list(_, "", _, _, []) do
[]
end
defp apply_list(_, string, _, _, []) do
string
end
defp apply_list(whole, string, pos, replacement, [[{mpos, _} | _] | _] = list) when mpos > pos do
length = mpos - pos
<<untouched::binary-size(length), rest::binary>> = string
[untouched | apply_list(whole, rest, mpos, replacement, list)]
end
defp apply_list(whole, string, pos, replacement, [[{pos, length} | _] = head | tail]) do
<<_::size(length)-binary, rest::binary>> = string
new_data = apply_replace(whole, replacement, head)
[new_data | apply_list(whole, rest, pos + length, replacement, tail)]
end
defp apply_replace(string, {fun, arity}, indexes) do
apply(fun, get_indexes(string, indexes, arity))
end
defp apply_replace(_, [bin], _) when is_binary(bin) do
bin
end
defp apply_replace(string, repl, indexes) do
indexes = List.to_tuple(indexes)
for part <- repl do
cond do
is_binary(part) ->
part
part >= tuple_size(indexes) ->
""
true ->
get_index(string, elem(indexes, part))
end
end
end
defp get_index(_string, {pos, _len}) when pos < 0 do
""
end
defp get_index(string, {pos, len}) do
<<_::size(pos)-binary, res::size(len)-binary, _::binary>> = string
res
end
defp get_indexes(_string, _, 0) do
[]
end
defp get_indexes(string, [], arity) do
["" | get_indexes(string, [], arity - 1)]
end
defp get_indexes(string, [h | t], arity) do
[get_index(string, h) | get_indexes(string, t, arity - 1)]
end
{:ok, pattern} = :re.compile(~S"[.^$*+?()\[\]{}\\\|\s#]", [:unicode])
@escape_pattern pattern
@doc ~S"""
Escapes a string to be literally matched in a regex.
## Examples
iex> Regex.escape(".")
"\\."
iex> Regex.escape("\\what if")
"\\\\what\\ if"
"""
@spec escape(String.t) :: String.t
def escape(string) when is_binary(string) do
:re.replace(string, @escape_pattern, "\\\\&", [:global, {:return, :binary}])
end
# Helpers
@doc false
# Unescape map function used by Macro.unescape_string.
def unescape_map(?f), do: ?\f
def unescape_map(?n), do: ?\n
def unescape_map(?r), do: ?\r
def unescape_map(?t), do: ?\t
def unescape_map(?v), do: ?\v
def unescape_map(?a), do: ?\a
def unescape_map(_), do: false
# Private Helpers
defp translate_options(<<?u, t::binary>>, acc), do: translate_options(t, [:unicode, :ucp | acc])
defp translate_options(<<?i, t::binary>>, acc), do: translate_options(t, [:caseless | acc])
defp translate_options(<<?x, t::binary>>, acc), do: translate_options(t, [:extended | acc])
defp translate_options(<<?f, t::binary>>, acc), do: translate_options(t, [:firstline | acc])
defp translate_options(<<?U, t::binary>>, acc), do: translate_options(t, [:ungreedy | acc])
defp translate_options(<<?s, t::binary>>, acc), do: translate_options(t, [:dotall, {:newline, :anycrlf} | acc])
defp translate_options(<<?m, t::binary>>, acc), do: translate_options(t, [:multiline | acc])
# TODO: Remove on 2.0
defp translate_options(<<?r, t::binary>>, acc) do
IO.warn "the /r modifier in regular expressions is deprecated, please use /U instead"
translate_options(t, [:ungreedy | acc])
end
defp translate_options(<<>>, acc), do: acc
defp translate_options(rest, _acc), do: {:error, rest}
end
| 30.136164 | 113 | 0.617548 |
1cdbefff52a2a11dc830cacd6950c3060930f54e | 1,584 | ex | Elixir | lib/tentacat/issues/reactions.ex | hi-rustin/tentacat | be0b4a671f90faab2598b6d58a691d506f46cfb5 | [
"MIT"
] | 432 | 2015-01-19T20:38:35.000Z | 2022-01-11T14:32:28.000Z | lib/tentacat/issues/reactions.ex | hi-rustin/tentacat | be0b4a671f90faab2598b6d58a691d506f46cfb5 | [
"MIT"
] | 183 | 2015-01-19T08:55:29.000Z | 2022-03-01T20:26:03.000Z | lib/tentacat/issues/reactions.ex | hi-rustin/tentacat | be0b4a671f90faab2598b6d58a691d506f46cfb5 | [
"MIT"
] | 189 | 2015-01-04T14:56:59.000Z | 2021-12-14T20:48:18.000Z | defmodule Tentacat.Issues.Reactions do
import Tentacat
alias Tentacat.Client
@doc """
List the reactions on a issue.
## Example
Tentacat.Issues.Reactions.list "elixir-lang" , "elixir", "3"
More info at: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue
"""
@spec list(Client.t(), binary, binary, binary | integer) :: Tentacat.response()
def list(client \\ %Client{}, owner, repo, issue_id) do
get("repos/#{owner}/#{repo}/issues/#{issue_id}/reactions", client)
end
@doc """
Create a reaction on an issue.
Reaction Request body example:
```elixir
%{
content: "heart"
}
```
## Example
Tentacat.Issues.Reactions.create "elixir-lang", "elixir", "3"
More info at: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue
"""
@spec create(Client.t(), binary, binary, binary | integer, Keyword.t() | map) ::
Tentacat.response()
def create(client \\ %Client{}, owner, repo, issue_id, body) do
post("repos/#{owner}/#{repo}/issues/#{issue_id}/reactions", client, body)
end
@doc """
Delete a reaction on an issue.
## Example
Tentacat.Issues.Reactions.delete "elixir-lang", "elixir", "3", "4"
More info at: https://developer.github.com/v3/reactions/#delete-an-issue-reaction
"""
@spec delete(Client.t(), binary, binary, binary | integer, binary) ::
Tentacat.response()
def delete(client \\ %Client{}, owner, repo, issue_id, reaction_id) do
delete("repos/#{owner}/#{repo}/issues/#{issue_id}/reactions/#{reaction_id}", client)
end
end
| 26.847458 | 88 | 0.657197 |
1cdbf9a03fea71bc3c65314f32a2333de41b12ea | 2,873 | ex | Elixir | lib/mix/lib/mix/scm.ex | bruce/elixir | d77ccf941541959079e5f677f8717da24b486fac | [
"Apache-2.0"
] | 1 | 2017-09-09T20:59:04.000Z | 2017-09-09T20:59:04.000Z | lib/mix/lib/mix/scm.ex | bruce/elixir | d77ccf941541959079e5f677f8717da24b486fac | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/scm.ex | bruce/elixir | d77ccf941541959079e5f677f8717da24b486fac | [
"Apache-2.0"
] | null | null | null | defmodule Mix.SCM do
use Behaviour
@typep opts :: [{ atom, any }]
@typep lock
@moduledoc """
This module provides helper functions and defines the
behavior required by any SCM used by mix.
"""
@doc """
Returns an Elixir term that contains relevant SCM
information for printing.
"""
defcallback format(opts) :: term
@doc """
Returns an Elixir term that contains relevant SCM
lock information for printing.
"""
defcallback format_lock(lock) :: term
@doc """
This behavior function receives a keyword list of `opts`
and should return an updated list in case the SCM consumes
the available options. For example, when a developer specifies
a dependency:
{ :foo, "0.1.0", github: "foo/bar" }
Each registered SCM will be asked if they consume this dependency,
receiving [github: "foo/bar"] as argument. Since this option makes
sense for the Git SCM, it will return an update list of options
while other SCMs would simply return nil.
"""
defcallback accepts_options(app :: atom, opts) :: opts | nil
@doc """
This behavior function returns a boolean if the
dependency is available.
"""
defcallback checked_out?(opts) :: boolean
@doc """
This behavior function checks out dependencies.
If the dependency is locked, a lock is received in `opts`
and the repository must be check out at the lock. Otherwise,
no lock is given and the repository can be checked out
to the latest version.
"""
defcallback checkout(opts) :: any
@doc """
This behavior function updates dependencies. It may be
called by `deps.get` or `deps.update`.
In the first scenario, a lock is received in `opts` and
the repository must be updated to the lock. In the second,
no lock is given and the repository can be updated freely.
It must return the current lock.
"""
defcallback update(opts) :: any
@doc """
This behavior function checks if the dependency is locked and
the current repository version matches the lock. Note that some
SCMs do not require a lock, for such, this function can simply
return true.
"""
defcallback matches_lock?(opts) :: boolean
@doc """
Receives two options and must return true if the refer to the
same repository. The options are guaranteed to belong to the
same SCM.
"""
defcallback equal?(opts1 :: opts, opts2 :: opts) :: boolean
@doc """
This behavior function should clean the given dependency.
"""
defcallback clean(opts) :: any
@doc """
Returns all available SCM.
"""
def available do
Mix.Server.call(:scm)
end
@doc """
Register the scm repository with the given `key` and `mod`.
"""
def register(mod) when is_atom(mod) do
Mix.Server.cast({ :add_scm, mod })
end
@doc """
Register builtin SCMs.
"""
def register_builtin do
register Mix.SCM.Git
register Mix.SCM.Path
end
end
| 26.357798 | 68 | 0.696833 |
1cdc10354fafc88454919bbf982440711a7fc4c2 | 13,151 | ex | Elixir | clients/people/lib/google_api/people/v1/model/person.ex | Contractbook/elixir-google-api | 342751041aaf8c2e7f76f9922cf24b9c5895802b | [
"Apache-2.0"
] | null | null | null | clients/people/lib/google_api/people/v1/model/person.ex | Contractbook/elixir-google-api | 342751041aaf8c2e7f76f9922cf24b9c5895802b | [
"Apache-2.0"
] | null | null | null | clients/people/lib/google_api/people/v1/model/person.ex | Contractbook/elixir-google-api | 342751041aaf8c2e7f76f9922cf24b9c5895802b | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.People.V1.Model.Person do
@moduledoc """
Information about a person merged from various data sources such as the authenticated user's contacts and profile data. Most fields can have multiple items. The items in a field have no guaranteed order, but each non-empty field is guaranteed to have exactly one field with `metadata.primary` set to true.
## Attributes
* `relationshipStatuses` (*type:* `list(GoogleApi.People.V1.Model.RelationshipStatus.t)`, *default:* `nil`) - Output only. **DEPRECATED**: No data will be returned The person's relationship statuses.
* `genders` (*type:* `list(GoogleApi.People.V1.Model.Gender.t)`, *default:* `nil`) - The person's genders. This field is a singleton for contact sources.
* `biographies` (*type:* `list(GoogleApi.People.V1.Model.Biography.t)`, *default:* `nil`) - The person's biographies. This field is a singleton for contact sources.
* `etag` (*type:* `String.t`, *default:* `nil`) - The [HTTP entity tag](https://en.wikipedia.org/wiki/HTTP_ETag) of the resource. Used for web cache validation.
* `names` (*type:* `list(GoogleApi.People.V1.Model.Name.t)`, *default:* `nil`) - The person's names. This field is a singleton for contact sources.
* `taglines` (*type:* `list(GoogleApi.People.V1.Model.Tagline.t)`, *default:* `nil`) - Output only. **DEPRECATED**: No data will be returned The person's taglines.
* `residences` (*type:* `list(GoogleApi.People.V1.Model.Residence.t)`, *default:* `nil`) - **DEPRECATED**: (Please use `person.locations` instead) The person's residences.
* `sipAddresses` (*type:* `list(GoogleApi.People.V1.Model.SipAddress.t)`, *default:* `nil`) - The person's SIP addresses.
* `externalIds` (*type:* `list(GoogleApi.People.V1.Model.ExternalId.t)`, *default:* `nil`) - The person's external IDs.
* `metadata` (*type:* `GoogleApi.People.V1.Model.PersonMetadata.t`, *default:* `nil`) - Output only. Metadata about the person.
* `occupations` (*type:* `list(GoogleApi.People.V1.Model.Occupation.t)`, *default:* `nil`) - The person's occupations.
* `imClients` (*type:* `list(GoogleApi.People.V1.Model.ImClient.t)`, *default:* `nil`) - The person's instant messaging clients.
* `addresses` (*type:* `list(GoogleApi.People.V1.Model.Address.t)`, *default:* `nil`) - The person's street addresses.
* `clientData` (*type:* `list(GoogleApi.People.V1.Model.ClientData.t)`, *default:* `nil`) - The person's client data.
* `skills` (*type:* `list(GoogleApi.People.V1.Model.Skill.t)`, *default:* `nil`) - The person's skills.
* `phoneNumbers` (*type:* `list(GoogleApi.People.V1.Model.PhoneNumber.t)`, *default:* `nil`) - The person's phone numbers. For [`connections.list`](/people/api/rest/v1/people.connections/list), [`otherContacts.list`](/people/api/rest/v1/otherContacts/list), and [`people.listDirectoryPeople`](/people/api/rest/v1/people/listDirectoryPeople) the number of phone numbers is limited to 100. If a Person has more phone numbers the entire set can be obtained by calling ['people.get'](/people/api/rest/v1/people/get).
* `relations` (*type:* `list(GoogleApi.People.V1.Model.Relation.t)`, *default:* `nil`) - The person's relations.
* `ageRanges` (*type:* `list(GoogleApi.People.V1.Model.AgeRangeType.t)`, *default:* `nil`) - Output only. The person's age ranges.
* `coverPhotos` (*type:* `list(GoogleApi.People.V1.Model.CoverPhoto.t)`, *default:* `nil`) - Output only. The person's cover photos.
* `birthdays` (*type:* `list(GoogleApi.People.V1.Model.Birthday.t)`, *default:* `nil`) - The person's birthdays. This field is a singleton for contact sources.
* `calendarUrls` (*type:* `list(GoogleApi.People.V1.Model.CalendarUrl.t)`, *default:* `nil`) - The person's calendar URLs.
* `locales` (*type:* `list(GoogleApi.People.V1.Model.Locale.t)`, *default:* `nil`) - The person's locale preferences.
* `locations` (*type:* `list(GoogleApi.People.V1.Model.Location.t)`, *default:* `nil`) - The person's locations.
* `interests` (*type:* `list(GoogleApi.People.V1.Model.Interest.t)`, *default:* `nil`) - The person's interests.
* `nicknames` (*type:* `list(GoogleApi.People.V1.Model.Nickname.t)`, *default:* `nil`) - The person's nicknames.
* `braggingRights` (*type:* `list(GoogleApi.People.V1.Model.BraggingRights.t)`, *default:* `nil`) - **DEPRECATED**: No data will be returned The person's bragging rights.
* `fileAses` (*type:* `list(GoogleApi.People.V1.Model.FileAs.t)`, *default:* `nil`) - The person's file-ases.
* `photos` (*type:* `list(GoogleApi.People.V1.Model.Photo.t)`, *default:* `nil`) - Output only. The person's photos.
* `events` (*type:* `list(GoogleApi.People.V1.Model.Event.t)`, *default:* `nil`) - The person's events.
* `userDefined` (*type:* `list(GoogleApi.People.V1.Model.UserDefined.t)`, *default:* `nil`) - The person's user defined data.
* `relationshipInterests` (*type:* `list(GoogleApi.People.V1.Model.RelationshipInterest.t)`, *default:* `nil`) - Output only. **DEPRECATED**: No data will be returned The person's relationship interests.
* `memberships` (*type:* `list(GoogleApi.People.V1.Model.Membership.t)`, *default:* `nil`) - The person's group memberships.
* `emailAddresses` (*type:* `list(GoogleApi.People.V1.Model.EmailAddress.t)`, *default:* `nil`) - The person's email addresses. For [`connections.list`](/people/api/rest/v1/people.connections/list), [`otherContacts.list`](/people/api/rest/v1/otherContacts/list), and [`people.listDirectoryPeople`](/people/api/rest/v1/people/listDirectoryPeople) the number of email addresses is limited to 100. If a Person has more email addresses the entire set can be obtained by calling ['people.get'](/people/api/rest/v1/people/get).
* `ageRange` (*type:* `String.t`, *default:* `nil`) - Output only. **DEPRECATED** (Please use `person.ageRanges` instead) The person's age range.
* `urls` (*type:* `list(GoogleApi.People.V1.Model.Url.t)`, *default:* `nil`) - The person's associated URLs.
* `resourceName` (*type:* `String.t`, *default:* `nil`) - The resource name for the person, assigned by the server. An ASCII string with a max length of 27 characters, in the form of `people/{person_id}`.
* `miscKeywords` (*type:* `list(GoogleApi.People.V1.Model.MiscKeyword.t)`, *default:* `nil`) - The person's miscellaneous keywords.
* `organizations` (*type:* `list(GoogleApi.People.V1.Model.Organization.t)`, *default:* `nil`) - The person's past or current organizations.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:relationshipStatuses => list(GoogleApi.People.V1.Model.RelationshipStatus.t()) | nil,
:genders => list(GoogleApi.People.V1.Model.Gender.t()) | nil,
:biographies => list(GoogleApi.People.V1.Model.Biography.t()) | nil,
:etag => String.t() | nil,
:names => list(GoogleApi.People.V1.Model.Name.t()) | nil,
:taglines => list(GoogleApi.People.V1.Model.Tagline.t()) | nil,
:residences => list(GoogleApi.People.V1.Model.Residence.t()) | nil,
:sipAddresses => list(GoogleApi.People.V1.Model.SipAddress.t()) | nil,
:externalIds => list(GoogleApi.People.V1.Model.ExternalId.t()) | nil,
:metadata => GoogleApi.People.V1.Model.PersonMetadata.t() | nil,
:occupations => list(GoogleApi.People.V1.Model.Occupation.t()) | nil,
:imClients => list(GoogleApi.People.V1.Model.ImClient.t()) | nil,
:addresses => list(GoogleApi.People.V1.Model.Address.t()) | nil,
:clientData => list(GoogleApi.People.V1.Model.ClientData.t()) | nil,
:skills => list(GoogleApi.People.V1.Model.Skill.t()) | nil,
:phoneNumbers => list(GoogleApi.People.V1.Model.PhoneNumber.t()) | nil,
:relations => list(GoogleApi.People.V1.Model.Relation.t()) | nil,
:ageRanges => list(GoogleApi.People.V1.Model.AgeRangeType.t()) | nil,
:coverPhotos => list(GoogleApi.People.V1.Model.CoverPhoto.t()) | nil,
:birthdays => list(GoogleApi.People.V1.Model.Birthday.t()) | nil,
:calendarUrls => list(GoogleApi.People.V1.Model.CalendarUrl.t()) | nil,
:locales => list(GoogleApi.People.V1.Model.Locale.t()) | nil,
:locations => list(GoogleApi.People.V1.Model.Location.t()) | nil,
:interests => list(GoogleApi.People.V1.Model.Interest.t()) | nil,
:nicknames => list(GoogleApi.People.V1.Model.Nickname.t()) | nil,
:braggingRights => list(GoogleApi.People.V1.Model.BraggingRights.t()) | nil,
:fileAses => list(GoogleApi.People.V1.Model.FileAs.t()) | nil,
:photos => list(GoogleApi.People.V1.Model.Photo.t()) | nil,
:events => list(GoogleApi.People.V1.Model.Event.t()) | nil,
:userDefined => list(GoogleApi.People.V1.Model.UserDefined.t()) | nil,
:relationshipInterests =>
list(GoogleApi.People.V1.Model.RelationshipInterest.t()) | nil,
:memberships => list(GoogleApi.People.V1.Model.Membership.t()) | nil,
:emailAddresses => list(GoogleApi.People.V1.Model.EmailAddress.t()) | nil,
:ageRange => String.t() | nil,
:urls => list(GoogleApi.People.V1.Model.Url.t()) | nil,
:resourceName => String.t() | nil,
:miscKeywords => list(GoogleApi.People.V1.Model.MiscKeyword.t()) | nil,
:organizations => list(GoogleApi.People.V1.Model.Organization.t()) | nil
}
field(:relationshipStatuses, as: GoogleApi.People.V1.Model.RelationshipStatus, type: :list)
field(:genders, as: GoogleApi.People.V1.Model.Gender, type: :list)
field(:biographies, as: GoogleApi.People.V1.Model.Biography, type: :list)
field(:etag)
field(:names, as: GoogleApi.People.V1.Model.Name, type: :list)
field(:taglines, as: GoogleApi.People.V1.Model.Tagline, type: :list)
field(:residences, as: GoogleApi.People.V1.Model.Residence, type: :list)
field(:sipAddresses, as: GoogleApi.People.V1.Model.SipAddress, type: :list)
field(:externalIds, as: GoogleApi.People.V1.Model.ExternalId, type: :list)
field(:metadata, as: GoogleApi.People.V1.Model.PersonMetadata)
field(:occupations, as: GoogleApi.People.V1.Model.Occupation, type: :list)
field(:imClients, as: GoogleApi.People.V1.Model.ImClient, type: :list)
field(:addresses, as: GoogleApi.People.V1.Model.Address, type: :list)
field(:clientData, as: GoogleApi.People.V1.Model.ClientData, type: :list)
field(:skills, as: GoogleApi.People.V1.Model.Skill, type: :list)
field(:phoneNumbers, as: GoogleApi.People.V1.Model.PhoneNumber, type: :list)
field(:relations, as: GoogleApi.People.V1.Model.Relation, type: :list)
field(:ageRanges, as: GoogleApi.People.V1.Model.AgeRangeType, type: :list)
field(:coverPhotos, as: GoogleApi.People.V1.Model.CoverPhoto, type: :list)
field(:birthdays, as: GoogleApi.People.V1.Model.Birthday, type: :list)
field(:calendarUrls, as: GoogleApi.People.V1.Model.CalendarUrl, type: :list)
field(:locales, as: GoogleApi.People.V1.Model.Locale, type: :list)
field(:locations, as: GoogleApi.People.V1.Model.Location, type: :list)
field(:interests, as: GoogleApi.People.V1.Model.Interest, type: :list)
field(:nicknames, as: GoogleApi.People.V1.Model.Nickname, type: :list)
field(:braggingRights, as: GoogleApi.People.V1.Model.BraggingRights, type: :list)
field(:fileAses, as: GoogleApi.People.V1.Model.FileAs, type: :list)
field(:photos, as: GoogleApi.People.V1.Model.Photo, type: :list)
field(:events, as: GoogleApi.People.V1.Model.Event, type: :list)
field(:userDefined, as: GoogleApi.People.V1.Model.UserDefined, type: :list)
field(:relationshipInterests, as: GoogleApi.People.V1.Model.RelationshipInterest, type: :list)
field(:memberships, as: GoogleApi.People.V1.Model.Membership, type: :list)
field(:emailAddresses, as: GoogleApi.People.V1.Model.EmailAddress, type: :list)
field(:ageRange)
field(:urls, as: GoogleApi.People.V1.Model.Url, type: :list)
field(:resourceName)
field(:miscKeywords, as: GoogleApi.People.V1.Model.MiscKeyword, type: :list)
field(:organizations, as: GoogleApi.People.V1.Model.Organization, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.People.V1.Model.Person do
def decode(value, options) do
GoogleApi.People.V1.Model.Person.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.People.V1.Model.Person do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 82.710692 | 525 | 0.694852 |
1cdc2e6cc6c9a6b450a719decdd5bc245e83c63a | 1,113 | exs | Elixir | apps/stops/config/config.exs | noisecapella/dotcom | d5ef869412102d2230fac3dcc216f01a29726227 | [
"MIT"
] | 42 | 2019-05-29T16:05:30.000Z | 2021-08-09T16:03:37.000Z | apps/stops/config/config.exs | noisecapella/dotcom | d5ef869412102d2230fac3dcc216f01a29726227 | [
"MIT"
] | 872 | 2019-05-29T17:55:50.000Z | 2022-03-30T09:28:43.000Z | apps/stops/config/config.exs | noisecapella/dotcom | d5ef869412102d2230fac3dcc216f01a29726227 | [
"MIT"
] | 12 | 2019-07-01T18:33:21.000Z | 2022-03-10T02:13:57.000Z | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :stops, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:stops, :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"
| 35.903226 | 73 | 0.750225 |
1cdc746dd76c9e285c142615874563dbf4409f0f | 2,113 | exs | Elixir | config/prod.exs | joshcrews/phoenix-react-redux-heroku | cc31f9c58da29167464e9a90b9a52d1f36a882ef | [
"MIT"
] | null | null | null | config/prod.exs | joshcrews/phoenix-react-redux-heroku | cc31f9c58da29167464e9a90b9a52d1f36a882ef | [
"MIT"
] | null | null | null | config/prod.exs | joshcrews/phoenix-react-redux-heroku | cc31f9c58da29167464e9a90b9a52d1f36a882ef | [
"MIT"
] | null | null | null | use Mix.Config
# For production, we configure the host to read the PORT
# from the system environment. Therefore, you will need
# to set PORT=80 before running your server.
#
# You should also configure the url host to something
# meaningful, we use this information when generating URLs.
#
# Finally, we also include the path to a manifest
# containing the digested version of static files. This
# manifest is generated by the mix phoenix.digest task
# which you typically run after static files are built.
config :react_webpack, ReactWebpack.Endpoint,
http: [port: {:system, "PORT"}],
url: [host: "jc-phoenix-react-redux.herokuapp.com", port: 80],
cache_static_manifest: "priv/static/manifest.json",
secret_key_base: System.get_env("SECRET_KEY_BASE")
# Do not print debug messages in production
config :logger, level: :info
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :react_webpack, ReactWebpack.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [port: 443,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")]
#
# Where those two env variables return an absolute path to
# the key and cert in disk or a relative path inside priv,
# for example "priv/ssl/server.key".
#
# We also recommend setting `force_ssl`, ensuring no data is
# ever sent via http, always redirecting to https:
#
# config :react_webpack, ReactWebpack.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start the server for all endpoints:
#
# config :phoenix, :serve_endpoints, true
#
# Alternatively, you can configure exactly which server to
# start per endpoint:
#
# config :react_webpack, ReactWebpack.Endpoint, server: true
#
# Finally import the config/prod.secret.exs
# which should be versioned separately.
# import_config "prod.secret.exs"
| 33.539683 | 67 | 0.722196 |
1cdc9a9104d8839817c477b2487fd9b549b4d815 | 178 | exs | Elixir | machine_translation/MorpHIN/Learned/Resources/Set2/TrainingInstances/46.exs | AdityaPrasadMishra/NLP--Project-Group-16 | fb62cc6a1db4a494058171f11c14a2be3933a9a1 | [
"MIT"
] | null | null | null | machine_translation/MorpHIN/Learned/Resources/Set2/TrainingInstances/46.exs | AdityaPrasadMishra/NLP--Project-Group-16 | fb62cc6a1db4a494058171f11c14a2be3933a9a1 | [
"MIT"
] | null | null | null | machine_translation/MorpHIN/Learned/Resources/Set2/TrainingInstances/46.exs | AdityaPrasadMishra/NLP--Project-Group-16 | fb62cc6a1db4a494058171f11c14a2be3933a9a1 | [
"MIT"
] | null | null | null | **EXAMPLE FILE**
verb SYM pn demonstrative inj;
pnoun cm noun adjective noun;
cm nst noun demonstrative noun;
pn particle cardinal noun quantifier;
SYM pnoun noun cm noun;
| 22.25 | 38 | 0.764045 |
1cdcbbb195c8d7401136f25e087cd52cbfb75e40 | 4,917 | exs | Elixir | test/smart_city/dataset_test.exs | SmartColumbusOS/smart_city | 7c18d4d7e9c67c7aa8b97e11d72af1865ef6c562 | [
"Apache-2.0"
] | 2 | 2019-07-09T15:52:17.000Z | 2020-01-17T08:01:27.000Z | test/smart_city/dataset_test.exs | SmartColumbusOS/smart_city | 7c18d4d7e9c67c7aa8b97e11d72af1865ef6c562 | [
"Apache-2.0"
] | 24 | 2019-06-06T15:36:12.000Z | 2020-02-06T16:45:53.000Z | test/smart_city/dataset_test.exs | SmartColumbusOS/smart_city | 7c18d4d7e9c67c7aa8b97e11d72af1865ef6c562 | [
"Apache-2.0"
] | 1 | 2022-03-08T23:44:23.000Z | 2022-03-08T23:44:23.000Z | defmodule SmartCity.DatasetTest do
use ExUnit.Case
use Placebo
import Checkov
doctest SmartCity.Dataset
alias SmartCity.Dataset
alias SmartCity.Dataset.{Business, Technical}
setup do
message = %{
"id" => "uuid",
"technical" => %{
"dataName" => "dataset",
"orgName" => "org",
"orgId" => "uuid",
"systemName" => "org__dataset",
"sourceUrl" => "https://example.com",
"sourceFormat" => "gtfs",
"sourceType" => "stream",
"cadence" => 9000,
"sourceHeaders" => %{},
"partitioner" => %{type: nil, query: nil},
"sourceQueryParams" => %{},
"schema" => []
},
"business" => %{
"dataTitle" => "dataset title",
"description" => "description",
"keywords" => ["one", "two"],
"modifiedDate" => "2019-01-31T01:31:31Z",
"orgTitle" => "org title",
"contactName" => "contact name",
"contactEmail" => "contact@email.com",
"license" => "license",
"rights" => "rights information",
"homepage" => ""
}
}
json = Jason.encode!(message)
{:ok, message: message, json: json}
end
describe "new/1" do
test "turns a map with string keys into a Dataset", %{message: map} do
{:ok, actual} = Dataset.new(map)
assert actual.id == "uuid"
assert actual.business.dataTitle == "dataset title"
assert actual.technical.dataName == "dataset"
end
test "turns a map with atom keys into a Dataset", %{message: map} do
%{"technical" => tech, "business" => biz} = map
technical = Technical.new(tech)
business = Business.new(biz)
atom_tech = Map.new(tech, fn {k, v} -> {String.to_atom(k), v} end)
atom_biz = Map.new(biz, fn {k, v} -> {String.to_atom(k), v} end)
map = %{id: "uuid", business: atom_biz, technical: atom_tech}
assert {:ok, %Dataset{id: "uuid", business: ^business, technical: ^technical}} = Dataset.new(map)
end
test "is idempotent", %{message: map} do
{:ok, dataset} = Dataset.new(map)
assert {:ok, ^dataset} = Dataset.new(dataset)
end
test "can be serialize and deserialized", %{message: message} do
{:ok, dataset} = Dataset.new(message)
{:ok, serialized} = Brook.Serializer.serialize(dataset)
assert {:ok, dataset} == Brook.Deserializer.deserialize(struct(Dataset), serialized)
end
test "returns error tuple when creating Dataset without required fields" do
assert {:error, _} = Dataset.new(%{id: "", technical: ""})
end
test "converts a JSON message into a Dataset", %{message: map, json: json} do
assert Dataset.new(json) == Dataset.new(map)
end
test "returns an error tuple when string message can't be decoded" do
assert {:error, ~s|Invalid Dataset: "Unable to json decode: foo"|} = Dataset.new("foo")
end
test "creates a private dataset by default", %{message: map} do
%{"technical" => tech} = map
technical = Technical.new(tech)
assert technical.private == true
end
end
describe "sourceType function:" do
data_test "#{inspect(func)} returns #{expected} when sourceType is #{sourceType}", %{
message: msg
} do
result =
msg
|> put_in(["technical", "sourceType"], sourceType)
|> Dataset.new()
|> ok()
|> func.()
assert result == expected
where([
[:func, :sourceType, :expected],
[&Dataset.is_stream?/1, "stream", true],
[&Dataset.is_stream?/1, "remote", false],
[&Dataset.is_stream?/1, "ingest", false],
[&Dataset.is_stream?/1, "host", false],
[&Dataset.is_ingest?/1, "ingest", true],
[&Dataset.is_ingest?/1, "stream", false],
[&Dataset.is_ingest?/1, "remote", false],
[&Dataset.is_ingest?/1, "host", false],
[&Dataset.is_remote?/1, "remote", true],
[&Dataset.is_remote?/1, "stream", false],
[&Dataset.is_remote?/1, "ingest", false],
[&Dataset.is_remote?/1, "host", false],
[&Dataset.is_host?/1, "host", true],
[&Dataset.is_host?/1, "stream", false],
[&Dataset.is_host?/1, "ingest", false],
[&Dataset.is_host?/1, "remote", false]
])
end
end
describe "access behaviors" do
test "can use put_in a business field", %{message: map} do
{:ok, dataset} = Dataset.new(map)
date = "12-13-19"
new_dataset = put_in(dataset, [:business, :modifiedDate], date)
assert date == new_dataset.business.modifiedDate
end
test "can use put_in a technical field", %{message: map} do
{:ok, dataset} = Dataset.new(map)
source_url = "https://newUrl.com"
new_dataset = put_in(dataset, [:technical, :sourceUrl], source_url)
assert source_url == new_dataset.technical.sourceUrl
end
end
defp ok({:ok, value}), do: value
end
| 32.348684 | 103 | 0.582672 |
1cdcc5641def81a5d05028e9b934eb6af520ca14 | 946 | ex | Elixir | lib/ctrlv/pastes/language.ex | ryanwinchester/ctrlv | eee44962dda062ba2154cc8bb57d86a6d814c71f | [
"Apache-2.0"
] | 1 | 2022-03-31T17:55:16.000Z | 2022-03-31T17:55:16.000Z | lib/ctrlv/pastes/language.ex | ryanwinchester/ctrlv | eee44962dda062ba2154cc8bb57d86a6d814c71f | [
"Apache-2.0"
] | 7 | 2022-03-30T02:52:54.000Z | 2022-03-30T23:11:01.000Z | lib/ctrlv/pastes/language.ex | ryanwinchester/ctrlv | eee44962dda062ba2154cc8bb57d86a6d814c71f | [
"Apache-2.0"
] | 1 | 2022-03-31T03:37:16.000Z | 2022-03-31T03:37:16.000Z | defmodule Ctrlv.Pastes.Language do
@moduledoc """
The languages supported by <ctrlv.io>.
"""
@supported_languages ~w(
cpp css html java javascript json markdown php python rust apl asciiArmor
asn1 asterisk brainfuck c csharp dart clojure cmake cobol coffeeScript
commonLisp crystal sCSS less cypher d diff dockerFile dtd dylan ebnf ecl
eiffel elixir elm erlang factor fcl forth fortran fSharp gas gherkin go
groovy haskell haxe http idl kotlin jinja2 julia liveScript lua mathematica
mbox mirc msSQL oCaml plSQL sml modelica mscgen mumps nginx nsis ntriples
objectiveC octave oz pascal perl pig powerShell properties protobuf puppet
q r ruby sas scala scheme shell sieve smalltalk solr sparql spreadsheet sql
stex stylus swift tcl textile tiki toml troff ttcn turtle typescript vb
vbScript velocity verilog vhdl wast webIDL xml xQuery yacas yaml z80
)a
def list, do: @supported_languages
end
| 45.047619 | 79 | 0.780127 |
1cdcc89f276a4872df520421abe02b02b6325e84 | 1,323 | ex | Elixir | lib/oidc/client_config.ex | YuriiZdyrko/oidc | 5587586a3ce00d43aa9df38052e95e17d8536033 | [
"Apache-2.0"
] | null | null | null | lib/oidc/client_config.ex | YuriiZdyrko/oidc | 5587586a3ce00d43aa9df38052e95e17d8536033 | [
"Apache-2.0"
] | 1 | 2021-09-22T13:25:07.000Z | 2021-09-22T13:25:07.000Z | lib/oidc/client_config.ex | YuriiZdyrko/oidc | 5587586a3ce00d43aa9df38052e95e17d8536033 | [
"Apache-2.0"
] | null | null | null | defmodule OIDC.ClientConfig do
@moduledoc """
Behaviour to retrieve client configuration at runtime
Client configuration is a map whose keys are those documented in
[OpenID Connect Dynamic Client Registration 1.0 incorporating errata set 1](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
, those used being:
- `"client_id"`
- `"client_secret"`: the client secret to authenticate to OAuth2 / OpenID Connect
API endpoints when the `"token_endpoint_auth_method"` is one of:
- `"client_secret_post"`
- `"client_secret_basic"`
- `"client_secret_jwt"` (if a JWK is not used)
- `"id_token_encrypted_response_alg"`
- `"id_token_encrypted_response_enc"`
- `"id_token_signed_response_alg"`
- `"jwks"`: the client's JWKs (must be maps, will be used calling `JOSE.JWK.from_map/1`)
- `"jwks_uri"`: the client's JWKs URI
- `"token_endpoint_auth_method"`: the client's authentication method for the token endpoint
"""
@type t :: %{optional(String.t()) => any()}
defmodule MissingFieldError do
defexception [:field]
@impl true
def message(%{field: field}), do: "Client `#{field}` field is not configured"
end
@doc """
Returns the client configuration, or `nil` if not found
"""
@callback get(client_id :: String.t()) :: t() | nil
end
| 35.756757 | 155 | 0.707483 |
1cdcd5e12c3242273e611e39197a357ec732597d | 1,686 | ex | Elixir | lib/elixir/lib/port.ex | jbcrail/elixir | f30ef15d9d028a6d0f74d10c2bb320d5f8501bdb | [
"Apache-2.0"
] | 1 | 2015-02-23T00:01:48.000Z | 2015-02-23T00:01:48.000Z | lib/elixir/lib/port.ex | jbcrail/elixir | f30ef15d9d028a6d0f74d10c2bb320d5f8501bdb | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/port.ex | jbcrail/elixir | f30ef15d9d028a6d0f74d10c2bb320d5f8501bdb | [
"Apache-2.0"
] | 1 | 2020-12-07T08:04:16.000Z | 2020-12-07T08:04:16.000Z | defmodule Port do
@moduledoc """
Functions related to Erlang ports.
"""
@doc """
See http://www.erlang.org/doc/man/erlang.html#open_port-2.
Inlined by the compiler.
"""
def open(name, settings) do
:erlang.open_port(name, settings)
end
@doc """
See http://www.erlang.org/doc/man/erlang.html#port_close-1.
Inlined by the compiler.
"""
def close(port) do
:erlang.port_close(port)
end
@doc """
See http://www.erlang.org/doc/man/erlang.html#port_command-2.
Inlined by the compiler.
"""
def command(port, data, options \\ []) do
:erlang.port_command(port, data, options)
end
@doc """
See http://www.erlang.org/doc/man/erlang.html#port_connect-2.
Inlined by the compiler.
"""
def connect(port, pid) do
:erlang.port_connect(port, pid)
end
@doc """
See http://www.erlang.org/doc/man/erlang.html#port_control-3.
Inlined by the compiler.
"""
def control(port, operation, data) do
:erlang.port_control(port, operation, data)
end
@doc """
See http://www.erlang.org/doc/man/erlang.html#port_call-3.
Inlined by the compiler.
"""
def call(port, operation, data) do
:erlang.port_call(port, operation, data)
end
@doc """
See http://www.erlang.org/doc/man/erlang.html#port_info-1.
Inlined by the compiler.
"""
def info(port) do
:erlang.port_info(port)
end
@doc """
See http://www.erlang.org/doc/man/erlang.html#port_info-2.
Inlined by the compiler.
"""
def info(port, item) do
:erlang.port_info(port, item)
end
@doc """
See http://www.erlang.org/doc/man/erlang.html#ports-0.
Inlined by the compiler.
"""
def list do
:erlang.ports
end
end | 19.604651 | 63 | 0.653025 |
1cdcfeef2d9c2ac955fef997665af505cd9a1b78 | 5,858 | ex | Elixir | lib/aws/appstream.ex | ttyerl/aws-elixir | 48f6360fccee5dd587fab7a6efb109a399ff9a46 | [
"Apache-2.0"
] | 223 | 2015-05-29T17:45:35.000Z | 2021-06-29T08:37:14.000Z | lib/aws/appstream.ex | ttyerl/aws-elixir | 48f6360fccee5dd587fab7a6efb109a399ff9a46 | [
"Apache-2.0"
] | 33 | 2015-11-20T20:56:43.000Z | 2021-07-09T20:13:34.000Z | lib/aws/appstream.ex | ttyerl/aws-elixir | 48f6360fccee5dd587fab7a6efb109a399ff9a46 | [
"Apache-2.0"
] | 62 | 2015-06-14T20:53:24.000Z | 2021-12-13T07:20:15.000Z | # WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
# See https://github.com/jkakar/aws-codegen for more details.
defmodule AWS.AppStream do
@moduledoc """
Amazon AppStream 2.0
API documentation for Amazon AppStream 2.0.
"""
@doc """
Associate a fleet to a stack.
"""
def associate_fleet(client, input, options \\ []) do
request(client, "AssociateFleet", input, options)
end
@doc """
Creates a new fleet.
"""
def create_fleet(client, input, options \\ []) do
request(client, "CreateFleet", input, options)
end
@doc """
Create a new stack.
"""
def create_stack(client, input, options \\ []) do
request(client, "CreateStack", input, options)
end
@doc """
Creates a URL to start an AppStream 2.0 streaming session for a user. By
default, the URL is valid only for 1 minute from the time that it is
generated.
"""
def create_streaming_u_r_l(client, input, options \\ []) do
request(client, "CreateStreamingURL", input, options)
end
@doc """
Deletes a fleet.
"""
def delete_fleet(client, input, options \\ []) do
request(client, "DeleteFleet", input, options)
end
@doc """
Deletes the stack. After this operation completes, the environment can no
longer be activated, and any reservations made for the stack are released.
"""
def delete_stack(client, input, options \\ []) do
request(client, "DeleteStack", input, options)
end
@doc """
If fleet names are provided, this operation describes the specified fleets;
otherwise, all the fleets in the account are described.
"""
def describe_fleets(client, input, options \\ []) do
request(client, "DescribeFleets", input, options)
end
@doc """
Describes the images. If a list of names is not provided, all images in
your account are returned. This operation does not return a paginated
result.
"""
def describe_images(client, input, options \\ []) do
request(client, "DescribeImages", input, options)
end
@doc """
Describes the streaming sessions for a stack and a fleet. If a user ID is
provided, this operation returns streaming sessions for only that user.
Pass this value for the `nextToken` parameter in a subsequent call to this
operation to retrieve the next set of items.
"""
def describe_sessions(client, input, options \\ []) do
request(client, "DescribeSessions", input, options)
end
@doc """
If stack names are not provided, this operation describes the specified
stacks; otherwise, all stacks in the account are described. Pass the
`nextToken` value in a subsequent call to this operation to retrieve the
next set of items.
"""
def describe_stacks(client, input, options \\ []) do
request(client, "DescribeStacks", input, options)
end
@doc """
Disassociates a fleet from a stack.
"""
def disassociate_fleet(client, input, options \\ []) do
request(client, "DisassociateFleet", input, options)
end
@doc """
This operation immediately stops a streaming session.
"""
def expire_session(client, input, options \\ []) do
request(client, "ExpireSession", input, options)
end
@doc """
Lists all fleets associated with the stack.
"""
def list_associated_fleets(client, input, options \\ []) do
request(client, "ListAssociatedFleets", input, options)
end
@doc """
Lists all stacks to which the specified fleet is associated.
"""
def list_associated_stacks(client, input, options \\ []) do
request(client, "ListAssociatedStacks", input, options)
end
@doc """
Starts a fleet.
"""
def start_fleet(client, input, options \\ []) do
request(client, "StartFleet", input, options)
end
@doc """
Stops a fleet.
"""
def stop_fleet(client, input, options \\ []) do
request(client, "StopFleet", input, options)
end
@doc """
Updates an existing fleet. All the attributes except the fleet name can be
updated in the **STOPPED** state. Only **ComputeCapacity** and
**ImageName** can be updated in any other state.
"""
def update_fleet(client, input, options \\ []) do
request(client, "UpdateFleet", input, options)
end
@doc """
Updates the specified fields in the stack with the specified name.
"""
def update_stack(client, input, options \\ []) do
request(client, "UpdateStack", input, options)
end
@spec request(map(), binary(), map(), list()) ::
{:ok, Poison.Parser.t | nil, Poison.Response.t} |
{:error, Poison.Parser.t} |
{:error, HTTPoison.Error.t}
defp request(client, action, input, options) do
client = %{client | service: "appstream2"}
host = get_host("appstream2", client)
url = get_url(host, client)
headers = [{"Host", host},
{"Content-Type", "application/x-amz-json-1.1"},
{"X-Amz-Target", "PhotonAdminProxyService.#{action}"}]
payload = Poison.Encoder.encode(input, [])
headers = AWS.Request.sign_v4(client, "POST", url, headers, payload)
case HTTPoison.post(url, payload, headers, options) do
{:ok, response=%HTTPoison.Response{status_code: 200, body: ""}} ->
{:ok, nil, response}
{:ok, response=%HTTPoison.Response{status_code: 200, body: body}} ->
{:ok, Poison.Parser.parse!(body), response}
{:ok, _response=%HTTPoison.Response{body: body}} ->
error = Poison.Parser.parse!(body)
exception = error["__type"]
message = error["message"]
{:error, {exception, message}}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, %HTTPoison.Error{reason: reason}}
end
end
defp get_host(endpoint_prefix, client) do
if client.region == "local" do
"localhost"
else
"#{endpoint_prefix}.#{client.region}.#{client.endpoint}"
end
end
defp get_url(host, %{:proto => proto, :port => port}) do
"#{proto}://#{host}:#{port}/"
end
end
| 30.510417 | 77 | 0.66422 |
1cdd21df3f927bb90cc2c7f3ad5a729724b3dbc1 | 1,135 | exs | Elixir | config/config.exs | keathley/butler_tableflip | bff056d04e1e25dca903346446c62557fbc6ff3a | [
"MIT"
] | 3 | 2016-02-19T01:32:54.000Z | 2019-01-25T13:52:53.000Z | config/config.exs | keathley/butler_tableflip | bff056d04e1e25dca903346446c62557fbc6ff3a | [
"MIT"
] | null | null | null | config/config.exs | keathley/butler_tableflip | bff056d04e1e25dca903346446c62557fbc6ff3a | [
"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 :butler_tableflip, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:butler_tableflip, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 36.612903 | 73 | 0.755066 |
1cdd350011f48fe214b2485388472450fe7757fe | 1,829 | ex | Elixir | clients/private_ca/lib/google_api/private_ca/v1beta1/model/issuance_modes.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | clients/private_ca/lib/google_api/private_ca/v1beta1/model/issuance_modes.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/private_ca/lib/google_api/private_ca/v1beta1/model/issuance_modes.ex | mcrumm/elixir-google-api | 544f22797cec52b3a23dfb6e39117f0018448610 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.PrivateCA.V1beta1.Model.IssuanceModes do
@moduledoc """
IssuanceModes specifies the allowed ways in which Certificates may be requested from this CertificateAuthority.
## Attributes
* `allowConfigBasedIssuance` (*type:* `boolean()`, *default:* `nil`) - Required. When true, allows callers to create Certificates by specifying a CertificateConfig.
* `allowCsrBasedIssuance` (*type:* `boolean()`, *default:* `nil`) - Required. When true, allows callers to create Certificates by specifying a CSR.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:allowConfigBasedIssuance => boolean(),
:allowCsrBasedIssuance => boolean()
}
field(:allowConfigBasedIssuance)
field(:allowCsrBasedIssuance)
end
defimpl Poison.Decoder, for: GoogleApi.PrivateCA.V1beta1.Model.IssuanceModes do
def decode(value, options) do
GoogleApi.PrivateCA.V1beta1.Model.IssuanceModes.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.PrivateCA.V1beta1.Model.IssuanceModes do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.58 | 168 | 0.750137 |
1cdd8acab76703d1442f9f7b70c34c5e7c04ac40 | 1,468 | exs | Elixir | mix.exs | lukaszsamson/elixir_zabbix_sender | 213cc1c8eb3294bedc9b52ae09fda6603d427ea9 | [
"MIT"
] | null | null | null | mix.exs | lukaszsamson/elixir_zabbix_sender | 213cc1c8eb3294bedc9b52ae09fda6603d427ea9 | [
"MIT"
] | null | null | null | mix.exs | lukaszsamson/elixir_zabbix_sender | 213cc1c8eb3294bedc9b52ae09fda6603d427ea9 | [
"MIT"
] | null | null | null | defmodule ZabbixSender.MixProject do
use Mix.Project
@version "1.1.1"
@source_url "https://github.com/lukaszsamson/elixir_zabbix_sender"
def project do
[
app: :zabbix_sender,
version: @version,
elixir: "~> 1.7",
start_permanent: Mix.env() == :prod,
deps: deps(),
description: description(),
package: package(),
name: "ZabbixSender",
source_url: @source_url,
docs: [
extras: ["README.md"],
main: "readme",
source_ref: "v#{@version}",
source_url: @source_url
],
dialyzer: [
flags: [
# :unmatched_returns,
:unknown,
:error_handling,
:race_conditions
# :underspecs
]
]
]
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
[
{:jason, "~> 1.0"},
{:ex_doc, "~> 0.19", only: :dev},
{:dialyxir, "~> 1.0.0", only: [:dev], runtime: false},
{:mock, "~> 0.3", only: :test}
]
end
defp description do
"""
Zabbix Sender Protocol client.
"""
end
defp package do
[
name: :zabbix_sender,
files: ["lib", "mix.exs", ".formatter.exs", "README*", "LICENSE*"],
maintainers: ["Łukasz Samson"],
licenses: ["MIT"],
links: %{"GitHub" => @source_url}
]
end
end
| 21.910448 | 73 | 0.540191 |
1cdd970bd99650bc7c7afb9d524501a61d02fbeb | 488 | ex | Elixir | apps/cam_web/lib/cam_web/live/common/server_connection_component.ex | paulanthonywilson/mcam | df9c5aaae00b568749dff22613636f5cb92f905a | [
"MIT"
] | null | null | null | apps/cam_web/lib/cam_web/live/common/server_connection_component.ex | paulanthonywilson/mcam | df9c5aaae00b568749dff22613636f5cb92f905a | [
"MIT"
] | 8 | 2020-11-16T09:59:12.000Z | 2020-11-16T10:13:07.000Z | apps/cam_web/lib/cam_web/live/common/server_connection_component.ex | paulanthonywilson/mcam | df9c5aaae00b568749dff22613636f5cb92f905a | [
"MIT"
] | null | null | null | defmodule CamWeb.ServerConnectionComponent do
@moduledoc """
Shows the status of the connection to the server.
"""
use CamWeb, :live_component
def render(assigns) do
~L"""
<div class="row server-connection-component">
<div class="column column-20"> Server connection status:</div>
<div class="column column-20 status status-<%=@server_connection_status%>"><%= @server_connection_status %></div>
<div class="column"></div>
</div>
"""
end
end
| 28.705882 | 119 | 0.670082 |
1cdd99b87db80e687725c501d08ca9d2a333f9b7 | 1,916 | exs | Elixir | mix.exs | milmazz/bamboo | b0c66e5880ec970f5d46757a64bbebb14962659f | [
"MIT"
] | null | null | null | mix.exs | milmazz/bamboo | b0c66e5880ec970f5d46757a64bbebb14962659f | [
"MIT"
] | null | null | null | mix.exs | milmazz/bamboo | b0c66e5880ec970f5d46757a64bbebb14962659f | [
"MIT"
] | null | null | null | defmodule Bamboo.Mixfile do
use Mix.Project
@project_url "https://github.com/paulcsmith/bamboo"
def project do
[
app: :bamboo,
version: "1.0.0",
elixir: "~> 1.2",
source_url: @project_url,
homepage_url: @project_url,
compilers: compilers(Mix.env()),
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [coveralls: :test, "coveralls.circle": :test],
elixirc_paths: elixirc_paths(Mix.env()),
description:
"Straightforward, powerful, and adapter based Elixir email library." <>
" Works with Mandrill, Mailgun, SendGrid, SparkPost, Postmark, in-memory, and test.",
build_embedded: Mix.env() == :prod,
start_permanent: Mix.env() == :prod,
package: package(),
docs: [main: "readme", extras: ["README.md"]],
deps: deps()
]
end
defp compilers(:test), do: [:phoenix] ++ Mix.compilers()
defp compilers(_), do: Mix.compilers()
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
[
applications: [:logger, :hackney, :poison],
mod: {Bamboo, []}
]
end
defp package do
[
maintainers: ["Paul Smith"],
licenses: ["MIT"],
links: %{"GitHub" => @project_url}
]
end
defp elixirc_paths(:test), do: elixirc_paths() ++ ["test/support"]
defp elixirc_paths(_), do: elixirc_paths()
defp elixirc_paths, do: ["lib"]
defp deps do
[
{:plug, "~> 1.0"},
{:ex_machina, "~> 2.2", only: :test},
{:cowboy, "~> 1.0", only: [:test, :dev]},
{:phoenix, "~> 1.1", only: :test},
{:phoenix_html, "~> 2.2", only: :test},
{:excoveralls, "~> 0.4", only: :test},
{:floki, "~> 0.8", only: :test},
{:ex_doc, "~> 0.9", only: :dev},
{:earmark, ">= 0.0.0", only: :dev},
{:hackney, "~> 1.13.0"},
{:poison, ">= 1.5.0"}
]
end
end
| 27.768116 | 95 | 0.56524 |
1cdde0102d752e07517552aaa4719d291f9cb8f9 | 1,093 | ex | Elixir | test/support/channel_case.ex | juliandicks/phoenix-startbootstrap-sb-admin-2 | 609e78528684b00ab7228abc136c1c2b692590de | [
"MIT"
] | 12 | 2020-12-31T21:53:57.000Z | 2021-02-12T15:18:17.000Z | test/support/channel_case.ex | juliandicks/phoenix-startbootstrap-sb-admin-2 | 609e78528684b00ab7228abc136c1c2b692590de | [
"MIT"
] | null | null | null | test/support/channel_case.ex | juliandicks/phoenix-startbootstrap-sb-admin-2 | 609e78528684b00ab7228abc136c1c2b692590de | [
"MIT"
] | 2 | 2021-05-13T22:09:56.000Z | 2021-10-03T02:45:54.000Z | defmodule DemoWeb.ChannelCase do
@moduledoc """
This module defines the test case to be used by
channel tests.
Such tests rely on `Phoenix.ChannelTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
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 DemoWeb.ChannelCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with channels
import Phoenix.ChannelTest
import DemoWeb.ChannelCase
# The default endpoint for testing
@endpoint DemoWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Demo.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Demo.Repo, {:shared, self()})
end
:ok
end
end
| 26.658537 | 66 | 0.722781 |
1cde0c3c25002f8c82f56ab4c7e705b06960dd69 | 498 | exs | Elixir | test/hubtel_ussd_phoenix_example_web/views/error_view_test.exs | papamarfo/hubtel-ussd-phoenix-example | ddd6c5a64a70ad9a0fbb780ef140708ea295aafd | [
"MIT"
] | 4 | 2019-04-21T22:26:19.000Z | 2019-11-26T17:19:46.000Z | test/hubtel_ussd_phoenix_example_web/views/error_view_test.exs | manfordbenjamin/hubtel-ussd-phoenix-example | ddd6c5a64a70ad9a0fbb780ef140708ea295aafd | [
"MIT"
] | null | null | null | test/hubtel_ussd_phoenix_example_web/views/error_view_test.exs | manfordbenjamin/hubtel-ussd-phoenix-example | ddd6c5a64a70ad9a0fbb780ef140708ea295aafd | [
"MIT"
] | null | null | null | defmodule HubtelUssdPhoenixExampleWeb.ErrorViewTest do
use HubtelUssdPhoenixExampleWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.html" do
assert render_to_string(HubtelUssdPhoenixExampleWeb.ErrorView, "404.html", []) == "Not Found"
end
test "renders 500.html" do
assert render_to_string(HubtelUssdPhoenixExampleWeb.ErrorView, "500.html", []) ==
"Internal Server Error"
end
end
| 31.125 | 97 | 0.751004 |
1cde1f48de4dbde2da4312028e2d271f4e98d6fb | 2,007 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/http_health_check_list_warning_data.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/http_health_check_list_warning_data.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/compute/lib/google_api/compute/v1/model/http_health_check_list_warning_data.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Compute.V1.Model.HttpHealthCheckListWarningData do
@moduledoc """
## Attributes
* `key` (*type:* `String.t`, *default:* `nil`) - [Output Only] A key that provides more detail on the warning being returned. For example, for warnings where there are no results in a list request for a particular zone, this key might be scope and the key value might be the zone name. Other examples might be a key indicating a deprecated resource and a suggested replacement, or a warning about invalid network settings (for example, if an instance attempts to perform IP forwarding but is not enabled for IP forwarding).
* `value` (*type:* `String.t`, *default:* `nil`) - [Output Only] A warning data value corresponding to the key.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:key => String.t(),
:value => String.t()
}
field(:key)
field(:value)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.HttpHealthCheckListWarningData do
def decode(value, options) do
GoogleApi.Compute.V1.Model.HttpHealthCheckListWarningData.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.HttpHealthCheckListWarningData do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.14 | 527 | 0.742402 |
1cde434549835fde05a40a86cec450af20ab0090 | 751 | ex | Elixir | memorex/lib/memorex/eraser.ex | ballPointPenguin/liveview_elixirconf_2021 | 5c33cdd27f9f132129907c8f7016609a02ea622d | [
"MIT"
] | null | null | null | memorex/lib/memorex/eraser.ex | ballPointPenguin/liveview_elixirconf_2021 | 5c33cdd27f9f132129907c8f7016609a02ea622d | [
"MIT"
] | null | null | null | memorex/lib/memorex/eraser.ex | ballPointPenguin/liveview_elixirconf_2021 | 5c33cdd27f9f132129907c8f7016609a02ea622d | [
"MIT"
] | null | null | null | defmodule Memorex.Eraser do
def new(phrase, steps) do
size = String.length(phrase)
chunk_size = div(size + steps - 1, steps)
plan = 0..(size - 1) |> Enum.shuffle |> Enum.chunk_every(chunk_size)
%{plan: plan, phrase: phrase}
end
def erase(%{plan: []} = eraser) do
eraser
end
def erase(%{plan: [head_plan | tail_plan], phrase: phrase}) do
new_phrase = enact_plan_step(head_plan, phrase)
%{plan: tail_plan, phrase: new_phrase}
end
def as_string(%{phrase: phrase}), do: phrase
defp enact_plan_step(plan_step, phrase) do
graphemes = String.graphemes(phrase)
Enum.reduce(plan_step, graphemes, fn (plan_index, acc) ->
List.replace_at(acc, plan_index, "_")
end)
|> Enum.join()
end
end
| 25.033333 | 72 | 0.656458 |
1cde5ea4de6a2d7e2d91416c2f3a6810c458cd83 | 463 | ex | Elixir | lib/kv/bucket_agent.ex | welaika/key-value-elixir | 39672c505b99554c56c6880754ba8e6b9b925b7d | [
"MIT",
"Unlicense"
] | 1 | 2019-12-19T20:02:53.000Z | 2019-12-19T20:02:53.000Z | lib/kv/bucket_agent.ex | welaika/key-value-elixir | 39672c505b99554c56c6880754ba8e6b9b925b7d | [
"MIT",
"Unlicense"
] | null | null | null | lib/kv/bucket_agent.ex | welaika/key-value-elixir | 39672c505b99554c56c6880754ba8e6b9b925b7d | [
"MIT",
"Unlicense"
] | null | null | null | defmodule KV.BucketAgent do
use Agent
def start_link(options \\ []) do
Agent.start_link(fn -> %{} end, options)
end
def get(bucket, key) do
Agent.get(bucket, &Map.get(&1, key))
end
def put(bucket, key, value) do
Agent.update(bucket, &Map.put(&1, key, value))
end
def delete(bucket, key) do
Agent.get_and_update(bucket, &Map.pop(&1, key))
end
def stop(bucket, reason \\ :normal) do
Agent.stop(bucket, reason)
end
end
| 19.291667 | 51 | 0.641469 |
1cde6e5b986ae078ec4030e1ef0317a4d977e925 | 226 | ex | Elixir | lib/co2_offset_web/views/calculator_view.ex | styx/co2_offset | ac4b2bce8142e2d33ea089322c8dade34839448b | [
"Apache-2.0"
] | null | null | null | lib/co2_offset_web/views/calculator_view.ex | styx/co2_offset | ac4b2bce8142e2d33ea089322c8dade34839448b | [
"Apache-2.0"
] | null | null | null | lib/co2_offset_web/views/calculator_view.ex | styx/co2_offset | ac4b2bce8142e2d33ea089322c8dade34839448b | [
"Apache-2.0"
] | null | null | null | defmodule Co2OffsetWeb.CalculatorView do
use Co2OffsetWeb, :view
def to_float_string(float) do
float
|> :erlang.float_to_binary([:compact, {:decimals, 2}])
end
def to_int(float) do
round(float)
end
end
| 17.384615 | 58 | 0.699115 |
1cde91c697877e8848bddb3492bfa61100365342 | 1,608 | exs | Elixir | test/unit/hologram/compiler/call_graph_builder/case_expression_test.exs | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 40 | 2022-01-19T20:27:36.000Z | 2022-03-31T18:17:41.000Z | test/unit/hologram/compiler/call_graph_builder/case_expression_test.exs | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 42 | 2022-02-03T22:52:43.000Z | 2022-03-26T20:57:32.000Z | test/unit/hologram/compiler/call_graph_builder/case_expression_test.exs | gregjohnsonsaltaire/hologram | aa8e9ea0d599def864c263cc37cc8ee31f02ac4a | [
"MIT"
] | 3 | 2022-02-10T04:00:37.000Z | 2022-03-08T22:07:45.000Z | defmodule Hologram.Compiler.CallGraphBuilder.CaseExpressionTest do
use Hologram.Test.UnitCase, async: false
alias Hologram.Compiler.{CallGraph, CallGraphBuilder}
alias Hologram.Compiler.IR.{Block, CaseExpression, IntegerType, ModuleType}
alias Hologram.Test.Fixtures.{
PlaceholderModule1,
PlaceholderModule2,
PlaceholderModule3,
PlaceholderModule4,
PlaceholderModule5,
PlaceholderModule6
}
@module_defs %{}
@templates %{}
setup do
CallGraph.run()
:ok
end
test "build/4" do
ir = %CaseExpression{
clauses: [
%{
bindings: [],
body: %Block{expressions: [
%ModuleType{module: PlaceholderModule3},
%ModuleType{module: PlaceholderModule4}
]},
pattern: %IntegerType{value: 1}
},
%{
bindings: [],
body: %Block{expressions: [
%ModuleType{module: PlaceholderModule5},
%ModuleType{module: PlaceholderModule6}
]},
pattern: %IntegerType{value: 2}
}
],
condition: %ModuleType{module: PlaceholderModule2}
}
from_vertex = PlaceholderModule1
CallGraphBuilder.build(ir, @module_defs, @templates, from_vertex)
assert CallGraph.has_edge?(PlaceholderModule1, PlaceholderModule2)
assert CallGraph.has_edge?(PlaceholderModule1, PlaceholderModule3)
assert CallGraph.has_edge?(PlaceholderModule1, PlaceholderModule4)
assert CallGraph.has_edge?(PlaceholderModule1, PlaceholderModule5)
assert CallGraph.has_edge?(PlaceholderModule1, PlaceholderModule6)
end
end
| 28.210526 | 77 | 0.672886 |
1cdeb1a5069649de60caa717b7180b2e0401e82f | 1,774 | ex | Elixir | lib/codes/codes_i36.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_i36.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_i36.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_I36 do
alias IcdCode.ICDCode
def _I360 do
%ICDCode{full_code: "I360",
category_code: "I36",
short_code: "0",
full_name: "Nonrheumatic tricuspid (valve) stenosis",
short_name: "Nonrheumatic tricuspid (valve) stenosis",
category_name: "Nonrheumatic tricuspid (valve) stenosis"
}
end
def _I361 do
%ICDCode{full_code: "I361",
category_code: "I36",
short_code: "1",
full_name: "Nonrheumatic tricuspid (valve) insufficiency",
short_name: "Nonrheumatic tricuspid (valve) insufficiency",
category_name: "Nonrheumatic tricuspid (valve) insufficiency"
}
end
def _I362 do
%ICDCode{full_code: "I362",
category_code: "I36",
short_code: "2",
full_name: "Nonrheumatic tricuspid (valve) stenosis with insufficiency",
short_name: "Nonrheumatic tricuspid (valve) stenosis with insufficiency",
category_name: "Nonrheumatic tricuspid (valve) stenosis with insufficiency"
}
end
def _I368 do
%ICDCode{full_code: "I368",
category_code: "I36",
short_code: "8",
full_name: "Other nonrheumatic tricuspid valve disorders",
short_name: "Other nonrheumatic tricuspid valve disorders",
category_name: "Other nonrheumatic tricuspid valve disorders"
}
end
def _I369 do
%ICDCode{full_code: "I369",
category_code: "I36",
short_code: "9",
full_name: "Nonrheumatic tricuspid valve disorder, unspecified",
short_name: "Nonrheumatic tricuspid valve disorder, unspecified",
category_name: "Nonrheumatic tricuspid valve disorder, unspecified"
}
end
end
| 34.115385 | 85 | 0.644307 |
1cded5c4e5af65b88fa1d92ebcfa1f932a36c639 | 980 | exs | Elixir | test/juvet/middleware/action_generator_test.exs | juvet/juvet | 5590ff7b1e5f411195d0becfe8b5740deb977cc5 | [
"MIT"
] | 19 | 2018-07-14T16:54:11.000Z | 2022-03-01T09:02:19.000Z | test/juvet/middleware/action_generator_test.exs | juvet/juvet | 5590ff7b1e5f411195d0becfe8b5740deb977cc5 | [
"MIT"
] | 31 | 2018-06-29T15:30:40.000Z | 2022-02-26T01:07:12.000Z | test/juvet/middleware/action_generator_test.exs | juvet/juvet | 5590ff7b1e5f411195d0becfe8b5740deb977cc5 | [
"MIT"
] | null | null | null | defmodule Juvet.Middleware.ActionGeneratorTest do
use ExUnit.Case, async: true
describe "Juvet.Middleware.ActionGenerator.call/1" do
setup do
[context: %{path: "test#action"}]
end
test "returns an error if the context does not contain a path" do
result = Juvet.Middleware.ActionGenerator.call(%{})
assert result == {:error, "`path` missing in the `context`"}
end
test "returns an endpoint Tuple with the controller and action",
%{
context: context
} do
assert {:ok, ctx} = Juvet.Middleware.ActionGenerator.call(context)
assert ctx[:action] == {:"Elixir.TestController", :action}
end
test "handle namespacing in the controller path" do
assert {:ok, context} =
Juvet.Middleware.ActionGenerator.call(%{
path: "namespace.test#action"
})
assert context[:action] == {:"Elixir.Namespace.TestController", :action}
end
end
end
| 29.69697 | 78 | 0.630612 |
1cded867234a3a5f093a7f31ee72aa9972f8d598 | 3,892 | ex | Elixir | clients/logging/lib/google_api/logging/v2/model/monitored_resource_descriptor.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/logging/lib/google_api/logging/v2/model/monitored_resource_descriptor.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/logging/lib/google_api/logging/v2/model/monitored_resource_descriptor.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Logging.V2.Model.MonitoredResourceDescriptor do
@moduledoc """
An object that describes the schema of a MonitoredResource object using a type name and a set of labels. For example, the monitored resource descriptor for Google Compute Engine VM instances has a type of "gce_instance" and specifies the use of the labels "instance_id" and "zone" to identify particular VM instances.Different APIs can support different monitored resource types. APIs generally provide a list method that returns the monitored resource descriptors used by the API.
## Attributes
* `description` (*type:* `String.t`, *default:* `nil`) - Optional. A detailed description of the monitored resource type that might be used in documentation.
* `displayName` (*type:* `String.t`, *default:* `nil`) - Optional. A concise name for the monitored resource type that might be displayed in user interfaces. It should be a Title Cased Noun Phrase, without any article or other determiners. For example, "Google Cloud SQL Database".
* `labels` (*type:* `list(GoogleApi.Logging.V2.Model.LabelDescriptor.t)`, *default:* `nil`) - Required. A set of labels used to describe instances of this monitored resource type. For example, an individual Google Cloud SQL database is identified by values for the labels "database_id" and "zone".
* `launchStage` (*type:* `String.t`, *default:* `nil`) - Optional. The launch stage of the monitored resource definition.
* `name` (*type:* `String.t`, *default:* `nil`) - Optional. The resource name of the monitored resource descriptor: "projects/{project_id}/monitoredResourceDescriptors/{type}" where {type} is the value of the type field in this object and {project_id} is a project ID that provides API-specific context for accessing the type. APIs that do not use project information can use the resource name format "monitoredResourceDescriptors/{type}".
* `type` (*type:* `String.t`, *default:* `nil`) - Required. The monitored resource type. For example, the type "cloudsql_database" represents databases in Google Cloud SQL. For a list of types, see Monitoring resource types (https://cloud.google.com/monitoring/api/resources) and Logging resource types (https://cloud.google.com/logging/docs/api/v2/resource-list).
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:description => String.t() | nil,
:displayName => String.t() | nil,
:labels => list(GoogleApi.Logging.V2.Model.LabelDescriptor.t()) | nil,
:launchStage => String.t() | nil,
:name => String.t() | nil,
:type => String.t() | nil
}
field(:description)
field(:displayName)
field(:labels, as: GoogleApi.Logging.V2.Model.LabelDescriptor, type: :list)
field(:launchStage)
field(:name)
field(:type)
end
defimpl Poison.Decoder, for: GoogleApi.Logging.V2.Model.MonitoredResourceDescriptor do
def decode(value, options) do
GoogleApi.Logging.V2.Model.MonitoredResourceDescriptor.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Logging.V2.Model.MonitoredResourceDescriptor do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 62.774194 | 483 | 0.741264 |
1cded916ab668fac15d164fa85146ebf56d75489 | 12,086 | ex | Elixir | clients/cloud_search/lib/google_api/cloud_search/v1/api/query.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/cloud_search/lib/google_api/cloud_search/v1/api/query.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/cloud_search/lib/google_api/cloud_search/v1/api/query.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.CloudSearch.V1.Api.Query do
@moduledoc """
API calls for all endpoints tagged `Query`.
"""
alias GoogleApi.CloudSearch.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
The Cloud Search Query API provides the search method, which returns
the most relevant results from a user query. The results can come from
G Suite Apps, such as Gmail or Google Drive, or they can come from data
that you have indexed from a third party.
**Note:** This API requires a standard end user account to execute.
A service account can't perform Query API requests directly; to use a
service account to perform queries, set up [G Suite domain-wide delegation
of
authority](https://developers.google.com/cloud-search/docs/guides/delegation/).
## Parameters
* `connection` (*type:* `GoogleApi.CloudSearch.V1.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.CloudSearch.V1.Model.SearchRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudSearch.V1.Model.SearchResponse{}}` on success
* `{:error, info}` on failure
"""
@spec cloudsearch_query_search(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.CloudSearch.V1.Model.SearchResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def cloudsearch_query_search(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/query/search", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.CloudSearch.V1.Model.SearchResponse{}])
end
@doc """
Provides suggestions for autocompleting the query.
**Note:** This API requires a standard end user account to execute.
A service account can't perform Query API requests directly; to use a
service account to perform queries, set up [G Suite domain-wide delegation
of
authority](https://developers.google.com/cloud-search/docs/guides/delegation/).
## Parameters
* `connection` (*type:* `GoogleApi.CloudSearch.V1.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:body` (*type:* `GoogleApi.CloudSearch.V1.Model.SuggestRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudSearch.V1.Model.SuggestResponse{}}` on success
* `{:error, info}` on failure
"""
@spec cloudsearch_query_suggest(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.CloudSearch.V1.Model.SuggestResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def cloudsearch_query_suggest(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/query/suggest", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.CloudSearch.V1.Model.SuggestResponse{}])
end
@doc """
Returns list of sources that user can use for Search and Suggest APIs.
**Note:** This API requires a standard end user account to execute.
A service account can't perform Query API requests directly; to use a
service account to perform queries, set up [G Suite domain-wide delegation
of
authority](https://developers.google.com/cloud-search/docs/guides/delegation/).
## Parameters
* `connection` (*type:* `GoogleApi.CloudSearch.V1.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:"$.xgafv"` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:pageToken` (*type:* `String.t`) - Number of sources to return in the response.
* `:"requestOptions.debugOptions.enableDebugging"` (*type:* `boolean()`) - If you are asked by Google to help with debugging, set this field.
Otherwise, ignore this field.
* `:"requestOptions.languageCode"` (*type:* `String.t`) - The BCP-47 language code, such as "en-US" or "sr-Latn".
For more information, see
http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
For translations.
Set this field using the language set in browser or for the page. In the
event that the user's language preference is known, set this field to the
known user language.
When specified, the documents in search results are biased towards the
specified language.
The suggest API does not use this parameter. Instead, suggest autocompletes
only based on characters in the query.
* `:"requestOptions.searchApplicationId"` (*type:* `String.t`) - Id of the application created using SearchApplicationsService.
* `:"requestOptions.timeZone"` (*type:* `String.t`) - Current user's time zone id, such as "America/Los_Angeles" or
"Australia/Sydney". These IDs are defined by
[Unicode Common Locale Data Repository (CLDR)](http://cldr.unicode.org/)
project, and currently available in the file
[timezone.xml](http://unicode.org/repos/cldr/trunk/common/bcp47/timezone.xml).
This field is used to correctly interpret date and time queries.
If this field is not specified, the default time zone (UTC) is used.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.CloudSearch.V1.Model.ListQuerySourcesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec cloudsearch_query_sources_list(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.CloudSearch.V1.Model.ListQuerySourcesResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def cloudsearch_query_sources_list(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:pageToken => :query,
:"requestOptions.debugOptions.enableDebugging" => :query,
:"requestOptions.languageCode" => :query,
:"requestOptions.searchApplicationId" => :query,
:"requestOptions.timeZone" => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/query/sources", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.CloudSearch.V1.Model.ListQuerySourcesResponse{}]
)
end
end
| 47.770751 | 196 | 0.648519 |
1cdf0924982d0ea9d69e40a2726dc38d2ca108c4 | 867 | ex | Elixir | test/support/test_agent.ex | schrockwell/appsignal-elixir | 550b5eae63488f9068aa1c38fe4c136541e93e8b | [
"MIT"
] | 234 | 2016-08-18T20:43:15.000Z | 2022-02-27T11:31:48.000Z | test/support/test_agent.ex | schrockwell/appsignal-elixir | 550b5eae63488f9068aa1c38fe4c136541e93e8b | [
"MIT"
] | 563 | 2016-07-25T17:45:14.000Z | 2022-03-21T11:39:29.000Z | test/support/test_agent.ex | schrockwell/appsignal-elixir | 550b5eae63488f9068aa1c38fe4c136541e93e8b | [
"MIT"
] | 86 | 2016-09-13T22:53:46.000Z | 2022-02-16T11:03:51.000Z | defmodule TestAgent do
defmacro __using__(default_state) do
quote do
import ExUnit.Assertions
def start_link do
{:ok, pid} =
Agent.start_link(
fn ->
unquote(default_state) |> Enum.into(%{})
end,
name: __MODULE__
)
{:ok, pid}
end
def get(pid_or_module, key) do
Agent.get(pid_or_module, &Map.get(&1, key))
end
def update(pid_or_module, key, value) do
Agent.update(pid_or_module, &Map.put(&1, key, value))
end
def alive?() do
!!Process.whereis(__MODULE__)
end
def child_spec(_opts) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, []},
type: :worker,
restart: :permanent,
shutdown: 500
}
end
end
end
end
| 20.642857 | 61 | 0.514418 |
1cdf2697f8f1627e87c11ff52122a94df287100c | 2,036 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/autoscalers_scoped_list_warning_data.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/compute/lib/google_api/compute/v1/model/autoscalers_scoped_list_warning_data.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/autoscalers_scoped_list_warning_data.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.Compute.V1.Model.AutoscalersScopedListWarningData do
@moduledoc """
## Attributes
* `key` (*type:* `String.t`, *default:* `nil`) - [Output Only] A key that provides more detail on the warning being returned. For example, for warnings where there are no results in a list request for a particular zone, this key might be scope and the key value might be the zone name. Other examples might be a key indicating a deprecated resource and a suggested replacement, or a warning about invalid network settings (for example, if an instance attempts to perform IP forwarding but is not enabled for IP forwarding).
* `value` (*type:* `String.t`, *default:* `nil`) - [Output Only] A warning data value corresponding to the key.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:key => String.t(),
:value => String.t()
}
field(:key)
field(:value)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.AutoscalersScopedListWarningData do
def decode(value, options) do
GoogleApi.Compute.V1.Model.AutoscalersScopedListWarningData.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.AutoscalersScopedListWarningData do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.72 | 527 | 0.744106 |
1cdf4b22ac64f78fbacbaea84db64eae16eb240c | 299 | exs | Elixir | priv/repo/migrations/20150116045636_initial_rooms_create.exs | billsaysthis/fd-events | 3316e25565f4c4bca12d697b3614283689ff6807 | [
"MIT"
] | null | null | null | priv/repo/migrations/20150116045636_initial_rooms_create.exs | billsaysthis/fd-events | 3316e25565f4c4bca12d697b3614283689ff6807 | [
"MIT"
] | null | null | null | priv/repo/migrations/20150116045636_initial_rooms_create.exs | billsaysthis/fd-events | 3316e25565f4c4bca12d697b3614283689ff6807 | [
"MIT"
] | null | null | null | defmodule FdEvents.Repo.Migrations.InitialRoomsCreate do
use Ecto.Migration
def up do
create table(:rooms) do
add :name, :string, size: 255
add :capacity, :integer
add :active, :boolean
timestamps
end
end
def down do
drop table(:rooms)
end
end
| 16.611111 | 56 | 0.638796 |
1cdf9dd0d91322e00a440431a61ee2f1dc04eaa9 | 1,957 | ex | Elixir | clients/android_publisher/lib/google_api/android_publisher/v3/model/bundle.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/android_publisher/lib/google_api/android_publisher/v3/model/bundle.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/android_publisher/lib/google_api/android_publisher/v3/model/bundle.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.AndroidPublisher.V3.Model.Bundle do
@moduledoc """
Information about an app bundle. The resource for BundlesService.
## Attributes
* `sha1` (*type:* `String.t`, *default:* `nil`) - A sha1 hash of the upload payload, encoded as a hex string and matching the output of the sha1sum command.
* `sha256` (*type:* `String.t`, *default:* `nil`) - A sha256 hash of the upload payload, encoded as a hex string and matching the output of the sha256sum command.
* `versionCode` (*type:* `integer()`, *default:* `nil`) - The version code of the Android App Bundle, as specified in the Android App Bundle's base module APK manifest file.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:sha1 => String.t() | nil,
:sha256 => String.t() | nil,
:versionCode => integer() | nil
}
field(:sha1)
field(:sha256)
field(:versionCode)
end
defimpl Poison.Decoder, for: GoogleApi.AndroidPublisher.V3.Model.Bundle do
def decode(value, options) do
GoogleApi.AndroidPublisher.V3.Model.Bundle.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AndroidPublisher.V3.Model.Bundle do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.924528 | 177 | 0.716914 |
1cdfa04228688cd3bd81db1082f8a4e5a7bf2631 | 5,473 | ex | Elixir | lib/muontrap/options.ex | se-apc/muontrap | a6d91b6b5676c7345e53420c615b04ff3798fe3c | [
"Apache-2.0"
] | null | null | null | lib/muontrap/options.ex | se-apc/muontrap | a6d91b6b5676c7345e53420c615b04ff3798fe3c | [
"Apache-2.0"
] | null | null | null | lib/muontrap/options.ex | se-apc/muontrap | a6d91b6b5676c7345e53420c615b04ff3798fe3c | [
"Apache-2.0"
] | null | null | null | defmodule MuonTrap.Options do
@moduledoc """
Validate and normalize the options passed to MuonTrap.cmd/3 and MuonTrap.Daemon.start_link/3
This module is generally not called directly, but it's likely
the source of exceptions if any options aren't quite right. Call `validate/4` directly to
debug or check options without invoking a command.
"""
@typedoc """
The following fields are always present:
* `:cmd` - the command to run
* `:args` - a list of arguments to the command
The next fields are optional:
* `:into` - `MuonTrap.cmd/3` only
* `:cd`
* `:arg0`
* `:stderr_to_stdout`
* `:parallelism`
* `:env`
* `:name` - `MuonTrap.Daemon`-only
* `:log_output` - `MuonTrap.Daemon`-only
* `:log_prefix` - `MuonTrap.Daemon`-only
* `:cgroup_controllers`
* `:cgroup_path`
* `:cgroup_base`
* `:delay_to_sigkill`
* `:force_close_port_after`
* `:cgroup_sets`
* `:uid`
* `:gid`
"""
@type t() :: map()
@doc """
Validate options and normalize them for invoking commands
Pass in `:cmd` or `:daemon` for the first parameter to allow function-specific
options.
"""
@spec validate(:cmd | :daemon, binary(), [binary()], keyword()) :: t()
def validate(context, cmd, args, opts) when context in [:cmd, :daemon] do
assert_no_null_byte!(cmd, context)
unless Enum.all?(args, &is_binary/1) do
raise ArgumentError, "all arguments for #{operation(context)} must be binaries"
end
abs_command = System.find_executable(cmd) || :erlang.error(:enoent, [cmd, args, opts])
validate_options(context, abs_command, args, opts)
|> resolve_cgroup_path()
end
defp resolve_cgroup_path(%{cgroup_path: _path, cgroup_base: _base}) do
raise ArgumentError, "cannot specify both a cgroup_path and a cgroup_base"
end
defp resolve_cgroup_path(%{cgroup_base: base} = options) do
# Create a random subfolder for this invocation
Map.put(options, :cgroup_path, Path.join(base, random_string()))
end
defp resolve_cgroup_path(other), do: other
# Thanks https://github.com/danhper/elixir-temp/blob/master/lib/temp.ex
defp random_string() do
Integer.to_string(:rand.uniform(0x100000000), 36) |> String.downcase()
end
defp validate_options(context, cmd, args, opts) do
Enum.reduce(
opts,
%{cmd: cmd, args: args, into: ""},
&validate_option(context, &1, &2)
)
end
# System.cmd/3 options
defp validate_option(:cmd, {:into, what}, opts), do: Map.put(opts, :into, what)
defp validate_option(_any, {:cd, bin}, opts) when is_binary(bin), do: Map.put(opts, :cd, bin)
defp validate_option(_any, {:arg0, bin}, opts) when is_binary(bin),
do: Map.put(opts, :arg0, bin)
defp validate_option(_any, {:stderr_to_stdout, bool}, opts) when is_boolean(bool),
do: Map.put(opts, :stderr_to_stdout, bool)
defp validate_option(_any, {:parallelism, bool}, opts) when is_boolean(bool),
do: Map.put(opts, :parallelism, bool)
defp validate_option(_any, {:env, enum}, opts),
do: Map.put(opts, :env, validate_env(enum))
# MuonTrap.Daemon options
defp validate_option(:daemon, {:name, name}, opts),
do: Map.put(opts, :name, name)
defp validate_option(:daemon, {:log_output, level}, opts)
when level in [:error, :warn, :info, :debug],
do: Map.put(opts, :log_output, level)
defp validate_option(:daemon, {:log_prefix, prefix}, opts) when is_binary(prefix),
do: Map.put(opts, :log_prefix, prefix)
# MuonTrap common options
defp validate_option(_any, {:cgroup_controllers, controllers}, opts) when is_list(controllers),
do: Map.put(opts, :cgroup_controllers, controllers)
defp validate_option(_any, {:cgroup_path, path}, opts) when is_binary(path) do
Map.put(opts, :cgroup_path, path)
end
defp validate_option(_any, {:cgroup_base, path}, opts) when is_binary(path) do
Map.put(opts, :cgroup_base, path)
end
defp validate_option(_any, {:delay_to_sigkill, delay}, opts) when is_integer(delay),
do: Map.put(opts, :delay_to_sigkill, delay)
defp validate_option(_any, {:force_close_port_after, delay}, opts) when is_integer(delay),
do: Map.put(opts, :force_close_port_after, delay)
defp validate_option(_any, {:cgroup_sets, sets}, opts) when is_list(sets),
do: Map.put(opts, :cgroup_sets, sets)
defp validate_option(_any, {:uid, id}, opts) when is_integer(id) or is_binary(id),
do: Map.put(opts, :uid, id)
defp validate_option(_any, {:gid, id}, opts) when is_integer(id) or is_binary(id),
do: Map.put(opts, :gid, id)
defp validate_option(_any, {key, val}, _opts),
do: raise(ArgumentError, "invalid option #{inspect(key)} with value #{inspect(val)}")
defp validate_env(enum) do
Enum.map(enum, fn
{k, nil} ->
{String.to_charlist(k), false}
{k, v} ->
{String.to_charlist(k), String.to_charlist(v)}
other ->
raise ArgumentError, "invalid environment key-value #{inspect(other)}"
end)
end
# Copied from Elixir's system.ex to make MuonTrap.cmd pass System.cmd's tests
defp assert_no_null_byte!(binary, context) do
case :binary.match(binary, "\0") do
{_, _} ->
raise ArgumentError,
"cannot execute #{operation(context)} for program with null byte, got: #{
inspect(binary)
}"
:nomatch ->
:ok
end
end
defp operation(:cmd), do: "MuonTrap.cmd/3"
defp operation(:daemon), do: "MuonTrap.Daemon.start_link/3"
end
| 32.194118 | 97 | 0.672392 |
1cdfb1c521b36d96650d35f71934bcc98d18e220 | 63 | ex | Elixir | web/views/layout_view.ex | PandemicPlayers/pandemic-server | 39ce8c12b5f08be7dc66623a69423265f01d23e1 | [
"MIT"
] | null | null | null | web/views/layout_view.ex | PandemicPlayers/pandemic-server | 39ce8c12b5f08be7dc66623a69423265f01d23e1 | [
"MIT"
] | null | null | null | web/views/layout_view.ex | PandemicPlayers/pandemic-server | 39ce8c12b5f08be7dc66623a69423265f01d23e1 | [
"MIT"
] | null | null | null | defmodule Pandemic.LayoutView do
use Pandemic.Web, :view
end
| 15.75 | 32 | 0.793651 |
1cdfbd5d476abe38352dff7c203a81cb9ad02d58 | 2,556 | exs | Elixir | braccino_firmware/mix.exs | darcros/braccino | 33f4d945daf8eac36e4e88ef412dd53cb1389376 | [
"MIT"
] | null | null | null | braccino_firmware/mix.exs | darcros/braccino | 33f4d945daf8eac36e4e88ef412dd53cb1389376 | [
"MIT"
] | null | null | null | braccino_firmware/mix.exs | darcros/braccino | 33f4d945daf8eac36e4e88ef412dd53cb1389376 | [
"MIT"
] | null | null | null | defmodule BraccinoFirmware.MixProject do
use Mix.Project
@app :braccino_firmware
@version "0.1.0"
@all_targets [:rpi, :rpi0, :rpi2, :rpi3, :rpi3a, :rpi4, :bbb, :osd32mp1, :x86_64]
def project do
[
app: @app,
version: @version,
elixir: "~> 1.9",
archives: [nerves_bootstrap: "~> 1.10"],
start_permanent: Mix.env() == :prod,
build_embedded: true,
deps: deps(),
releases: [{@app, release()}],
preferred_cli_target: [run: :host, test: :host],
compilers: [:elixir_make] ++ Mix.compilers(),
make_clean: ["clean"]
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
mod: {BraccinoFirmware.Application, []},
extra_applications: [:logger, :runtime_tools]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# Dependencies for all targets
{:nerves, "~> 1.7.0", runtime: false},
{:elixir_make, "~> 0.6.2", runtime: false},
{:shoehorn, "~> 0.7.0"},
{:ring_logger, "~> 0.8.1"},
{:toolshed, "~> 0.2.13"},
{:circuits_uart, "~> 1.3"},
{:cobs, "~> 0.2.0"},
{:braccino, path: "../braccino", targets: @all_targets},
{:braccino_ui, path: "../braccino_ui", targets: @all_targets},
# Dependencies for all targets except :host
{:nerves_runtime, "~> 0.11.3", targets: @all_targets},
{:nerves_pack, "~> 0.4.0", targets: @all_targets},
# Dependencies for specific targets
{:nerves_system_rpi, "~> 1.13", runtime: false, targets: :rpi},
{:nerves_system_rpi0, "~> 1.13", runtime: false, targets: :rpi0},
{:nerves_system_rpi2, "~> 1.13", runtime: false, targets: :rpi2},
{:nerves_system_rpi3, "~> 1.13", runtime: false, targets: :rpi3},
{:nerves_system_rpi3a, "~> 1.13", runtime: false, targets: :rpi3a},
{:nerves_system_rpi4, "~> 1.13", runtime: false, targets: :rpi4},
{:nerves_system_bbb, "~> 2.8", runtime: false, targets: :bbb},
{:nerves_system_osd32mp1, "~> 0.4", runtime: false, targets: :osd32mp1},
{:nerves_system_x86_64, "~> 1.13", runtime: false, targets: :x86_64}
]
end
def release do
[
overwrite: true,
# Erlang distribution is not started automatically.
# See https://hexdocs.pm/nerves_pack/readme.html#erlang-distribution
cookie: "#{@app}_cookie",
include_erts: &Nerves.Release.erts/0,
steps: [&Nerves.Release.init/1, :assemble],
strip_beams: Mix.env() == :prod or [keep: ["Docs"]]
]
end
end
| 34.08 | 83 | 0.595462 |
1cdfe85b45d3c20be1bc0647b5c02388f829aa13 | 2,142 | exs | Elixir | apps/blockchain_web/config/prod.exs | sandhose/elixir-blockchain | 4b5c91816ca0710524c352b57fcf2bb37c64c728 | [
"MIT"
] | null | null | null | apps/blockchain_web/config/prod.exs | sandhose/elixir-blockchain | 4b5c91816ca0710524c352b57fcf2bb37c64c728 | [
"MIT"
] | null | null | null | apps/blockchain_web/config/prod.exs | sandhose/elixir-blockchain | 4b5c91816ca0710524c352b57fcf2bb37c64c728 | [
"MIT"
] | null | null | null | use Mix.Config
# For production, we often load configuration from external
# sources, such as your system environment. For this reason,
# you won't find the :http configuration below, but set inside
# BlockchainWeb.Endpoint.init/2 when load_from_system_env is
# true. Any dynamic configuration should be done there.
#
# Don't forget to configure the url host to something meaningful,
# Phoenix uses this information when generating URLs.
#
# Finally, we also include the path to a cache manifest
# containing the digested version of static files. This
# manifest is generated by the mix phx.digest task
# which you typically run after static files are built.
config :blockchain_web, BlockchainWeb.Endpoint,
load_from_system_env: true,
url: [host: "example.com", port: 80],
cache_static_manifest: "priv/static/cache_manifest.json"
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :blockchain_web, BlockchainWeb.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [:inet6,
# port: 443,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")]
#
# Where those two env variables return an absolute path to
# the key and cert in disk or a relative path inside priv,
# for example "priv/ssl/server.key".
#
# We also recommend setting `force_ssl`, ensuring no data is
# ever sent via http, always redirecting to https:
#
# config :blockchain_web, BlockchainWeb.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start the server for all endpoints:
#
# config :phoenix, :serve_endpoints, true
#
# Alternatively, you can configure exactly which server to
# start per endpoint:
#
# config :blockchain_web, BlockchainWeb.Endpoint, server: true
#
# Finally import the config/prod.secret.exs
# which should be versioned separately.
import_config "prod.secret.exs"
| 34.548387 | 67 | 0.725957 |
1cdfe9787d024845dea3463a4987b9d57727ba50 | 787 | ex | Elixir | test/support/test_helpers.ex | SwiftAusterity/gossip | d79c53acd02fcb9905acb9730e59065efdd5a589 | [
"MIT"
] | null | null | null | test/support/test_helpers.ex | SwiftAusterity/gossip | d79c53acd02fcb9905acb9730e59065efdd5a589 | [
"MIT"
] | null | null | null | test/support/test_helpers.ex | SwiftAusterity/gossip | d79c53acd02fcb9905acb9730e59065efdd5a589 | [
"MIT"
] | null | null | null | defmodule Gossip.TestHelpers do
alias Gossip.Accounts
alias Gossip.Channels
alias Gossip.Games
def create_channel(attributes \\ %{}) do
attributes = Map.merge(%{
name: "gossip",
desription: "A channel",
}, attributes)
{:ok, channel} = Channels.create(attributes)
channel
end
def create_user(attributes \\ %{}) do
attributes = Map.merge(%{
email: "admin@example.com",
password: "password",
password_confirmation: "password",
}, attributes)
{:ok, game} = Accounts.register(attributes)
game
end
def create_game(user, attributes \\ %{}) do
attributes = Map.merge(%{
name: "A MUD",
short_name: "AM",
}, attributes)
{:ok, game} = Games.register(user, attributes)
game
end
end
| 19.675 | 50 | 0.621347 |
1cdff3e1f2ee0bf98dfca62d2cae05f32e6dd464 | 1,982 | ex | Elixir | lib/pow/store/backend/base.ex | thejones/pow | 217d3d915ce6832a5b138535a54fa2c39b2d9be5 | [
"MIT"
] | 1 | 2021-06-25T10:36:01.000Z | 2021-06-25T10:36:01.000Z | lib/pow/store/backend/base.ex | thejones/pow | 217d3d915ce6832a5b138535a54fa2c39b2d9be5 | [
"MIT"
] | null | null | null | lib/pow/store/backend/base.ex | thejones/pow | 217d3d915ce6832a5b138535a54fa2c39b2d9be5 | [
"MIT"
] | null | null | null | defmodule Pow.Store.Backend.Base do
@moduledoc """
Used to set up API for key-value cache store.
## Usage
This is an example using [Cachex](https://hex.pm/packages/cachex):
defmodule MyApp.CachexCache do
@behaviour Pow.Store.Backend.Base
alias Pow.Config
@cachex_tab __MODULE__
@impl true
def put(config, record_or_records) do
records =
record_or_records
|> List.wrap()
|> Enum.map(fn {key, value} ->
{wrap_namespace(config, key), value}
end)
Cachex.put_many(@cachex_tab, records, ttl: Config.get(config, :ttl))
end
@impl true
def delete(config, key) do
key = wrap_namespace(config, key)
Cachex.del(@cachex_tab, key)
end
@impl true
def get(config, key) do
key = wrap_namespace(config, key)
case Cachex.get(@cachex_tab, key) do
{:ok, nil} -> :not_found
{:ok, value} -> value
end
end
@impl true
def all(config, match_spec) do
query = Cachex.Query.create(match_spec, :key)
@cachex_tab
|> Cachex.stream!(query)
|> Enum.map(fn {key, value} -> {unwrap_namespace(key), value} end)
end
defp wrap_namespace(config, key) do
namespace = Config.get(config, :namespace, "cache")
[namespace | List.wrap(key)]
end
defp unwrap_namespace([_namespace, key]), do: key
defp unwrap_namespace([_namespace | key]), do: key
end
"""
alias Pow.Config
@type key() :: [binary() | atom()] | binary()
@type record() :: {key(), any()}
@type key_match() :: [atom() | binary()]
@callback put(Config.t(), record() | [record()]) :: :ok
@callback delete(Config.t(), key()) :: :ok
@callback get(Config.t(), key()) :: any() | :not_found
@callback all(Config.t(), key_match()) :: [record()]
end
| 26.426667 | 78 | 0.552472 |
1cdffa2ad9c0c99a22a52b5d7c3a18e9b7367bba | 2,723 | exs | Elixir | exercises/all-your-base/all_your_base_test.exs | Tuxified/elixir | 6230e2237851cf35532b6a34e4c67b44a28cde1b | [
"MIT"
] | null | null | null | exercises/all-your-base/all_your_base_test.exs | Tuxified/elixir | 6230e2237851cf35532b6a34e4c67b44a28cde1b | [
"MIT"
] | 1 | 2019-06-13T09:31:54.000Z | 2019-06-13T09:31:54.000Z | exercises/all-your-base/all_your_base_test.exs | Tuxified/elixir | 6230e2237851cf35532b6a34e4c67b44a28cde1b | [
"MIT"
] | 1 | 2019-06-13T04:29:09.000Z | 2019-06-13T04:29:09.000Z | if !System.get_env("EXERCISM_TEST_EXAMPLES") do
Code.load_file("all_your_base.exs", __DIR__)
end
ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)
defmodule AllYourBaseTest do
use ExUnit.Case
test "convert single bit one to decimal" do
assert AllYourBase.convert([1], 2, 10) == [1]
end
@tag :pending
test "convert binary to single decimal" do
assert AllYourBase.convert([1, 0, 1], 2, 10) == [5]
end
@tag :pending
test "convert single decimal to binary" do
assert AllYourBase.convert([5], 10, 2) == [1, 0, 1]
end
@tag :pending
test "convert binary to multiple decimal" do
assert AllYourBase.convert([1, 0, 1, 0, 1, 0], 2, 10) == [4, 2]
end
@tag :pending
test "convert decimal to binary" do
assert AllYourBase.convert([4, 2], 10, 2) == [1, 0, 1, 0, 1, 0]
end
@tag :pending
test "convert trinary to hexadecimal" do
assert AllYourBase.convert([1, 1, 2, 0], 3, 16) == [2, 10]
end
@tag :pending
test "convert hexadecimal to trinary" do
assert AllYourBase.convert([2, 10], 16, 3) == [1, 1, 2, 0]
end
@tag :pending
test "convert 15-bit integer" do
assert AllYourBase.convert([3, 46, 60], 97, 73) == [6, 10, 45]
end
@tag :pending
test "convert empty list" do
assert AllYourBase.convert([], 2, 10) == nil
end
@tag :pending
test "convert single zero" do
assert AllYourBase.convert([0], 10, 2) == [0]
end
@tag :pending
test "convert multiple zeros" do
assert AllYourBase.convert([0, 0, 0], 10, 2) == [0]
end
@tag :pending
test "convert leading zeros" do
assert AllYourBase.convert([0, 6, 0], 7, 10) == [4, 2]
end
@tag :pending
test "convert negative digit" do
assert AllYourBase.convert([1, -1, 1, 0, 1, 0], 2, 10) == nil
end
@tag :pending
test "convert invalid positive digit" do
assert AllYourBase.convert([1, 2, 1, 0, 1, 0], 2, 10) == nil
end
@tag :pending
test "convert first base is one" do
assert AllYourBase.convert([0], 1, 10) == nil
end
@tag :pending
test "convert second base is one" do
assert AllYourBase.convert([1, 0, 1, 0, 1, 0], 2, 1) == nil
end
@tag :pending
test "convert first base is zero" do
assert AllYourBase.convert([], 0, 10) == nil
end
@tag :pending
test "convert second base is zero" do
assert AllYourBase.convert([7], 10, 0) == nil
end
@tag :pending
test "convert first base is negative" do
assert AllYourBase.convert([1], -2, 10) == nil
end
@tag :pending
test "convert second base is negative" do
assert AllYourBase.convert([1], 2, -7) == nil
end
@tag :pending
test "convert both bases are negative" do
assert AllYourBase.convert([1], -2, -7) == nil
end
end
| 23.678261 | 67 | 0.63643 |
1ce018d6318bbb3761cd8d4d2b0c512f32ee560f | 2,215 | ex | Elixir | video-code/21-processes/servy/lib/servy/handler.ex | anwarsky/elixir_sample2 | 613599113e15fcd400853fc0e560a39001435f6d | [
"Unlicense"
] | null | null | null | video-code/21-processes/servy/lib/servy/handler.ex | anwarsky/elixir_sample2 | 613599113e15fcd400853fc0e560a39001435f6d | [
"Unlicense"
] | null | null | null | video-code/21-processes/servy/lib/servy/handler.ex | anwarsky/elixir_sample2 | 613599113e15fcd400853fc0e560a39001435f6d | [
"Unlicense"
] | null | null | null | defmodule Servy.Handler do
@moduledoc "Handles HTTP requests."
alias Servy.Conv
alias Servy.BearController
@pages_path Path.expand("../../pages", __DIR__)
import Servy.Plugins, only: [rewrite_path: 1, log: 1, track: 1]
import Servy.Parser, only: [parse: 1]
@doc "Transforms the request into a response."
def handle(request) do
request
|> parse
|> rewrite_path
#|> log
|> route
|> track
|> format_response
end
def route(%Conv{ method: "GET", path: "/kaboom" } = conv) do
raise "Kaboom!"
end
def route(%Conv{ method: "GET", path: "/hibernate/" <> time } = conv) do
time |> String.to_integer |> :timer.sleep
%{ conv | status: 200, resp_body: "Awake!" }
end
def route(%Conv{ method: "GET", path: "/wildthings" } = conv) do
%{ conv | status: 200, resp_body: "Bears, Lions, Tigers" }
end
def route(%Conv{ method: "GET", path: "/api/bears" } = conv) do
Servy.Api.BearController.index(conv)
end
def route(%Conv{ method: "GET", path: "/bears" } = conv) do
BearController.index(conv)
end
def route(%Conv{ method: "GET", path: "/bears/" <> id } = conv) do
params = Map.put(conv.params, "id", id)
BearController.show(conv, params)
end
def route(%Conv{method: "POST", path: "/bears"} = conv) do
BearController.create(conv, conv.params)
end
def route(%Conv{method: "GET", path: "/about"} = conv) do
@pages_path
|> Path.join("about.html")
|> File.read
|> handle_file(conv)
end
def route(%Conv{ path: path } = conv) do
%{ conv | status: 404, resp_body: "No #{path} here!"}
end
def handle_file({:ok, content}, conv) do
%{ conv | status: 200, resp_body: content }
end
def handle_file({:error, :enoent}, conv) do
%{ conv | status: 404, resp_body: "File not found!" }
end
def handle_file({:error, reason}, conv) do
%{ conv | status: 500, resp_body: "File error: #{reason}" }
end
def format_response(%Conv{} = conv) do
"""
HTTP/1.1 #{Conv.full_status(conv)}\r
Content-Type: #{conv.resp_content_type}\r
Content-Length: #{String.length(conv.resp_body)}\r
\r
#{conv.resp_body}
"""
end
end
| 24.611111 | 74 | 0.604515 |
1ce04de8afd0ba8e76dd7472a9b8fe37439c8fb6 | 208 | ex | Elixir | examples/simple_blog/web/models/post.ex | inaka/Dayron | d6773dacdc681766bfcb41dd792c102ab7217b1c | [
"Apache-2.0"
] | 169 | 2016-05-05T17:21:45.000Z | 2022-01-31T20:23:07.000Z | examples/simple_blog/web/models/post.ex | inaka/Dayron | d6773dacdc681766bfcb41dd792c102ab7217b1c | [
"Apache-2.0"
] | 51 | 2016-04-22T20:46:37.000Z | 2022-02-22T00:15:40.000Z | examples/simple_blog/web/models/post.ex | inaka/RestRepo | d6773dacdc681766bfcb41dd792c102ab7217b1c | [
"Apache-2.0"
] | 26 | 2016-05-21T09:52:26.000Z | 2022-02-11T18:07:14.000Z | defmodule SimpleBlog.Post do
@moduledoc """
A Dayron Model to interact with /posts resource in api
"""
use Dayron.Model, resource: "posts"
defstruct id: nil, userId: nil, title: "", body: ""
end
| 23.111111 | 58 | 0.673077 |
1ce057e39e568d559217e46a64c37a68c03a1057 | 2,247 | ex | Elixir | lib/jti_register/ets.ex | tanguilp/jti_register | 4b0e261980c6051d66af82bbbf8b2f4e026dde1f | [
"Apache-2.0"
] | null | null | null | lib/jti_register/ets.ex | tanguilp/jti_register | 4b0e261980c6051d66af82bbbf8b2f4e026dde1f | [
"Apache-2.0"
] | null | null | null | lib/jti_register/ets.ex | tanguilp/jti_register | 4b0e261980c6051d66af82bbbf8b2f4e026dde1f | [
"Apache-2.0"
] | null | null | null | defmodule JTIRegister.ETS do
@default_cleanup_interval 15
@moduledoc """
Implementation of the `JTIRegister` behaviour relying on ETS
Stores the JTIs in an ETS table. It is therefore **not** distributed and not suitable
when having more than one node.
Uses monotonic time, so that erroneous server time does not result in JTIs not being deleted.
## Options
- `:cleanup_interval`: the interval between cleanups of the underlying ETS table in seconds.
Defaults to #{@default_cleanup_interval}
## Starting the register
In your `MyApp.Application` module, add:
children = [
JTIRegister.ETS
]
or
children = [
{JTIRegister.ETS, cleanup_interval: 30}
]
"""
@behaviour JTIRegister
use GenServer
@impl JTIRegister
def start_link(opts \\ []) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
@impl JTIRegister
def register(jti, exp) do
expires_in = exp - now()
exp_monotonic = now_monotonic() + expires_in
GenServer.cast(__MODULE__, {:add_jti, {jti, exp_monotonic}})
end
@impl JTIRegister
def registered?(jti) do
now_monotonic = now_monotonic()
case :ets.lookup(__MODULE__, jti) do
[{_jti, exp_monotonic}] when exp_monotonic > now_monotonic ->
true
_ ->
false
end
end
@impl GenServer
def init(opts) do
schedule_cleanup(opts)
:ets.new(__MODULE__, [:named_table, :set, :protected])
{:ok, opts}
end
@impl GenServer
def handle_cast({:add_jti, {jti, exp_monotonic}}, state) do
:ets.insert(__MODULE__, {jti, exp_monotonic})
{:noreply, state}
end
@impl GenServer
def handle_info(:cleanup, state) do
cleanup()
schedule_cleanup(state)
{:noreply, state}
end
defp cleanup() do
match_spec = [
{
{:_, :"$1"},
[{:<, :"$1", now_monotonic()}],
[true]
}
]
:ets.select_delete(__MODULE__, match_spec)
end
defp schedule_cleanup(state) do
interval = (state[:cleanup_interval] || @default_cleanup_interval) * 1000
Process.send_after(self(), :cleanup, interval)
end
defp now(), do: System.system_time(:second)
defp now_monotonic(), do: System.monotonic_time(:second)
end
| 20.427273 | 95 | 0.657766 |
1ce08a433f8bd11d7c4796f08db968eb7b6dd321 | 344 | ex | Elixir | game/dictionary/lib/dictionary/word_list.ex | herminiotorres/elixir-for-programmers | 6a02e3312ad0f7b1e543627e3cf8b54db00d0a1e | [
"MIT"
] | 1 | 2020-08-10T21:07:43.000Z | 2020-08-10T21:07:43.000Z | game/dictionary/lib/dictionary/word_list.ex | herminiotorres/elixir-for-programmers | 6a02e3312ad0f7b1e543627e3cf8b54db00d0a1e | [
"MIT"
] | null | null | null | game/dictionary/lib/dictionary/word_list.ex | herminiotorres/elixir-for-programmers | 6a02e3312ad0f7b1e543627e3cf8b54db00d0a1e | [
"MIT"
] | null | null | null | defmodule Dictionary.WordList do
use Agent
@me __MODULE__
def start_link(_state) do
Agent.start_link(&word_list/0, name: @me)
end
def random_word() do
Agent.get(@me, &Enum.random/1)
end
def word_list do
"../../assets/words.txt"
|> Path.expand(__DIR__)
|> File.read!()
|> String.split(~r/\n/)
end
end
| 16.380952 | 45 | 0.627907 |
1ce08e4005b65fed9bd43bd4170461e1a6fd4370 | 2,292 | ex | Elixir | clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1p2beta1__explicit_content_annotation.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1p2beta1__explicit_content_annotation.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1p2beta1__explicit_content_annotation.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.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation do
@moduledoc """
Explicit content annotation (based on per-frame visual signals only).
If no explicit content has been detected in a frame, no annotations are
present for that frame.
## Attributes
* `frames` (*type:* `list(GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame.t)`, *default:* `nil`) - All video frames where explicit content was detected.
* `version` (*type:* `String.t`, *default:* `nil`) - Feature version.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:frames =>
list(
GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame.t()
),
:version => String.t()
}
field(:frames,
as:
GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame,
type: :list
)
field(:version)
end
defimpl Poison.Decoder,
for:
GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation do
def decode(value, options) do
GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.208955 | 204 | 0.75 |
1ce0dab67cce5707b53de0b0e422119e9f2094fb | 1,612 | ex | Elixir | clients/games/lib/google_api/games/v1/model/games_achievement_set_steps_at_least.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/games_achievement_set_steps_at_least.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/games_achievement_set_steps_at_least.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.Games.V1.Model.GamesAchievementSetStepsAtLeast do
@moduledoc """
This is a JSON template for the payload to request to increment an achievement.
## Attributes
- kind (String): Uniquely identifies the type of this resource. Value is always the fixed string games#GamesAchievementSetStepsAtLeast. Defaults to: `null`.
- steps (Integer): The minimum number of steps for the achievement to be set to. Defaults to: `null`.
"""
defstruct [
:"kind",
:"steps"
]
end
defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.GamesAchievementSetStepsAtLeast do
def decode(value, _options) do
value
end
end
defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.GamesAchievementSetStepsAtLeast do
def encode(value, options) do
GoogleApi.Games.V1.Deserializer.serialize_non_nil(value, options)
end
end
| 33.583333 | 158 | 0.759305 |
1ce0ecd57ed82ada1cf279545775d7f980f5209f | 717 | ex | Elixir | apps/grenadier/lib/grenadier_web/gettext.ex | allen-garvey/phoenix-umbrella | 1d444bbd62a5e7b5f51d317ce2be71ee994125d5 | [
"MIT"
] | 4 | 2019-10-04T16:11:15.000Z | 2021-08-18T21:00:13.000Z | apps/grenadier/lib/grenadier_web/gettext.ex | allen-garvey/phoenix-umbrella | 1d444bbd62a5e7b5f51d317ce2be71ee994125d5 | [
"MIT"
] | 5 | 2020-03-16T23:52:25.000Z | 2021-09-03T16:52:17.000Z | apps/grenadier/lib/grenadier_web/gettext.ex | allen-garvey/phoenix-umbrella | 1d444bbd62a5e7b5f51d317ce2be71ee994125d5 | [
"MIT"
] | null | null | null | defmodule GrenadierWeb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import GrenadierWeb.Gettext
# Simple translation
gettext("Here is the string to translate")
# Plural translation
ngettext("Here is the string to translate",
"Here are the strings to translate",
3)
# Domain-based translation
dgettext("errors", "Here is the error message to translate")
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :grenadier
end
| 28.68 | 72 | 0.680614 |
1ce0f9db9840a067cc5e8d8386bf9c3c1d291eea | 5,082 | ex | Elixir | clients/games/lib/google_api/games/v1/api/pushtokens.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/api/pushtokens.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/api/pushtokens.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.Games.V1.Api.Pushtokens do
@moduledoc """
API calls for all endpoints tagged `Pushtokens`.
"""
alias GoogleApi.Games.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Removes a push token for the current user and application. Removing a non-existent push token will report success.
## Parameters
* `connection` (*type:* `GoogleApi.Games.V1.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.Games.V1.Model.PushTokenId.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %{}}` on success
* `{:error, info}` on failure
"""
@spec games_pushtokens_remove(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, nil} | {:ok, Tesla.Env.t()} | {:error, any()}
def games_pushtokens_remove(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("/pushtokens/remove", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [decode: false])
end
@doc """
Registers a push token for the current user and application.
## Parameters
* `connection` (*type:* `GoogleApi.Games.V1.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.Games.V1.Model.PushToken.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %{}}` on success
* `{:error, info}` on failure
"""
@spec games_pushtokens_update(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, nil} | {:ok, Tesla.Env.t()} | {:error, any()}
def games_pushtokens_update(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(:put)
|> Request.url("/pushtokens", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [decode: false])
end
end
| 40.983871 | 187 | 0.641086 |
1ce10230aa2cfb40103c03ed15b0e96bb141041d | 2,420 | exs | Elixir | apps/api_web/mix.exs | fjlanasa/api | c39bc393aea572bfb81754b2ea1adf9dda9ce24a | [
"MIT"
] | null | null | null | apps/api_web/mix.exs | fjlanasa/api | c39bc393aea572bfb81754b2ea1adf9dda9ce24a | [
"MIT"
] | null | null | null | apps/api_web/mix.exs | fjlanasa/api | c39bc393aea572bfb81754b2ea1adf9dda9ce24a | [
"MIT"
] | null | null | null | defmodule ApiWeb.Mixfile do
@moduledoc false
use Mix.Project
def project do
[
app: :api_web,
aliases: aliases(),
build_embedded: Mix.env() == :prod,
build_path: "../../_build",
compilers: [:phoenix] ++ Mix.compilers() ++ [:phoenix_swagger],
config_path: "../../config/config.exs",
deps: deps(),
deps_path: "../../deps",
elixir: "~> 1.10",
elixirc_paths: elixirc_paths(Mix.env()),
lockfile: "../../mix.lock",
start_permanent: Mix.env() == :prod,
test_coverage: [tool: ExCoveralls],
version: "0.1.0"
]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
extra_applications = [:logger, :phoenix_swagger | env_applications(Mix.env())]
[mod: {ApiWeb, []}, extra_applications: extra_applications]
end
defp aliases do
[compile: ["compile --warnings-as-errors"]]
end
defp env_applications(:prod) do
[:sasl, :diskusage_logger]
end
defp env_applications(_) do
[]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Dependencies can be Hex packages:
#
# {:mydep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
#
# To depend on another app inside the umbrella:
#
# {:myapp, in_umbrella: true}
#
# Type "mix help deps" for more examples and options
defp deps do
[
{:phoenix, "< 1.5.5"},
{:phoenix_html, "~> 2.11"},
{:ja_serializer, github: "mbta/ja_serializer", branch: "master"},
{:timex, "~> 3.2"},
{:corsica, "~> 1.1"},
{:state_mediator, in_umbrella: true},
{:health, in_umbrella: true},
{:api_accounts, in_umbrella: true},
{:memcachex, "~> 0.4"},
{:ehmon, github: "mbta/ehmon", branch: "master", only: :prod},
{:benchwarmer, "~> 0.0", only: [:dev, :test]},
{:dialyxir, "~> 1.0.0-rc", only: [:dev, :test], runtime: false},
{:logster, "~> 1.0"},
{:phoenix_swagger, github: "mbta/phoenix_swagger", branch: "master"},
{:ex_json_schema, "~> 0.6.2"},
{:diskusage_logger, "~> 0.2.0", only: :prod},
{:jason, "~> 1.0"},
{:stream_data, "~> 0.4", only: :test},
{:plug_cowboy, "~> 2.1"}
]
end
end
| 28.470588 | 82 | 0.577686 |
1ce124b16ddddd8cb10255e4e3aad1fa111e3d91 | 986 | exs | Elixir | lib/logger/test/test_helper.exs | jfornoff/elixir | 4ed5e8e66973ae7b0e52ead00f65117ab0d600e0 | [
"Apache-2.0"
] | null | null | null | lib/logger/test/test_helper.exs | jfornoff/elixir | 4ed5e8e66973ae7b0e52ead00f65117ab0d600e0 | [
"Apache-2.0"
] | null | null | null | lib/logger/test/test_helper.exs | jfornoff/elixir | 4ed5e8e66973ae7b0e52ead00f65117ab0d600e0 | [
"Apache-2.0"
] | 1 | 2021-09-30T01:21:02.000Z | 2021-09-30T01:21:02.000Z | Logger.configure_backend(:console, colors: [enabled: false])
exclude = if Process.whereis(:logger), do: [:error_logger], else: [:logger]
ExUnit.start(exclude: exclude)
defmodule Logger.Case do
use ExUnit.CaseTemplate
import ExUnit.CaptureIO
using _ do
quote do
import Logger.Case
end
end
def msg(msg) do
~r/\d\d\:\d\d\:\d\d\.\d\d\d #{Regex.escape(msg)}/
end
def wait_for_handler(manager, handler) do
unless handler in :gen_event.which_handlers(manager) do
Process.sleep(10)
wait_for_handler(manager, handler)
end
end
def wait_for_logger() do
try do
:gen_event.which_handlers(Logger)
catch
:exit, _ ->
Process.sleep(10)
wait_for_logger()
else
_ ->
:ok
end
end
def capture_log(level \\ :debug, fun) do
Logger.configure(level: level)
capture_io(:user, fn ->
fun.()
Logger.flush()
end)
after
Logger.configure(level: :debug)
end
end
| 19.333333 | 75 | 0.633874 |
1ce155ebbdde47303862e053310e1033a2eae74d | 141 | exs | Elixir | HackerRank/Functional Programming/Elixir/test/solution_test.exs | cjschneider2/practice_code | 5d9b793eccca39262fb452fa1f3f53e6b54bc7aa | [
"Unlicense"
] | null | null | null | HackerRank/Functional Programming/Elixir/test/solution_test.exs | cjschneider2/practice_code | 5d9b793eccca39262fb452fa1f3f53e6b54bc7aa | [
"Unlicense"
] | null | null | null | HackerRank/Functional Programming/Elixir/test/solution_test.exs | cjschneider2/practice_code | 5d9b793eccca39262fb452fa1f3f53e6b54bc7aa | [
"Unlicense"
] | null | null | null | defmodule SolutionTest do
use ExUnit.Case
doctest Solution
test "greets the world" do
assert Solution.hello() == :world
end
end
| 15.666667 | 37 | 0.716312 |
1ce16b3648556f709373b6fa8fdb1e6362a6b6e7 | 61 | ex | Elixir | lib/chirper_web/views/post_view.ex | PranavPuranik/project_twitter | 0b660e8749488a632d6f64212205757254caaec3 | [
"MIT"
] | 2 | 2019-10-10T11:57:29.000Z | 2019-12-17T18:04:10.000Z | lib/chirper_web/views/post_view.ex | PranavPuranik/project_twitter | 0b660e8749488a632d6f64212205757254caaec3 | [
"MIT"
] | 86 | 2019-04-27T16:18:58.000Z | 2021-05-28T23:13:36.000Z | lib/chirper_web/views/post_view.ex | PranavPuranik/project_twitter | 0b660e8749488a632d6f64212205757254caaec3 | [
"MIT"
] | 1 | 2020-07-16T04:52:47.000Z | 2020-07-16T04:52:47.000Z | defmodule ChirperWeb.PostView do
use ChirperWeb, :view
end
| 15.25 | 32 | 0.803279 |
1ce1846c37b4b98ac9772eca1a57ecfcdfae4261 | 740 | ex | Elixir | lib/plug/conn/wrapper_error.ex | gjaldon/plug | bfe88530b429c7b9b29b69b737772ef7c6aa2f6b | [
"Apache-2.0"
] | 1 | 2019-05-07T15:05:52.000Z | 2019-05-07T15:05:52.000Z | lib/plug/conn/wrapper_error.ex | gjaldon/plug | bfe88530b429c7b9b29b69b737772ef7c6aa2f6b | [
"Apache-2.0"
] | null | null | null | lib/plug/conn/wrapper_error.ex | gjaldon/plug | bfe88530b429c7b9b29b69b737772ef7c6aa2f6b | [
"Apache-2.0"
] | 1 | 2019-11-23T12:09:14.000Z | 2019-11-23T12:09:14.000Z | defmodule Plug.Conn.WrapperError do
@moduledoc """
Wraps the connection in an error which is meant
to be handled upper in the stack.
Used by both `Plug.Debugger` and `Plug.ErrorHandler`.
"""
defexception [:conn, :kind, :reason, :stack]
def message(%{kind: kind, reason: reason, stack: stack}) do
Exception.format_banner(kind, reason, stack)
end
@doc """
Reraises an error or a wrapped one.
"""
def reraise(_conn, :error, %__MODULE__{stack: stack} = reason) do
:erlang.raise(:error, reason, stack)
end
def reraise(conn, kind, reason) do
stack = System.stacktrace
wrapper = %__MODULE__{conn: conn, kind: kind, reason: reason, stack: stack}
:erlang.raise(:error, wrapper, stack)
end
end
| 27.407407 | 79 | 0.681081 |
1ce18fbc20e54b516b4984fd1bc69cf78d3bc61c | 3,559 | exs | Elixir | apps/discovery_api/mix.exs | msomji/smartcitiesdata | fc96abc1ef1306f7af6bd42bbcb4ed041a6d922c | [
"Apache-2.0"
] | null | null | null | apps/discovery_api/mix.exs | msomji/smartcitiesdata | fc96abc1ef1306f7af6bd42bbcb4ed041a6d922c | [
"Apache-2.0"
] | null | null | null | apps/discovery_api/mix.exs | msomji/smartcitiesdata | fc96abc1ef1306f7af6bd42bbcb4ed041a6d922c | [
"Apache-2.0"
] | null | null | null | defmodule DiscoveryApi.Mixfile do
use Mix.Project
def project do
[
app: :discovery_api,
compilers: [:phoenix, :gettext | Mix.compilers()],
version: "0.51.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.8",
start_permanent: Mix.env() == :prod,
deps: deps(),
test_paths: test_paths(Mix.env()),
elixirc_paths: elixirc_paths(Mix.env()),
aliases: aliases()
]
end
def application do
[
mod: {DiscoveryApi.Application, []},
extra_applications: [:logger, :runtime_tools, :corsica, :prestige, :ecto]
]
end
defp deps do
[
{:atomic_map, "~> 0.9"},
{:assertions, "~> 0.14.1", only: [:test, :integration], runtime: false},
{:auth, in_umbrella: true},
{:ex_aws, "~> 2.1"},
# This commit allows us to stream files off of S3 through memory. Release pending.
{
:ex_aws_s3,
"~> 2.0",
git: "https://github.com/ex-aws/ex_aws_s3", ref: "6b9fdac73b62dee14bffb939965742f2576f2a7b"
},
{:ibrowse, "~> 4.4"},
{:libvault, "~> 0.2"},
{:sweet_xml, "~> 0.6"},
{:brook, "~> 0.4"},
{:bypass, "~> 2.0", only: [:test, :integration]},
{:cachex, "~> 3.0"},
{:corsica, "~> 1.0"},
{:cowboy, "~> 2.7"},
{:cowlib, "~> 2.8", override: true},
{:csv, "~> 2.3"},
{:credo, "~> 1.0", only: [:dev, :test, :integration], runtime: false},
{:checkov, "~> 1.0", only: [:test, :integration]},
{:divo, "~> 1.1", only: [:dev, :test, :integration]},
{:ex_json_schema, "~> 0.7", only: [:test, :integration]},
{:ecto_sql, "~> 3.0"},
{:elastix, "~> 0.8.0"},
{:guardian, "~> 2.0"},
{:guardian_db, "~> 2.0.3"},
{:gettext, "~> 0.17"},
{:httpoison, "~> 1.5"},
{:faker, "~> 0.13"},
{:jason, "~> 1.2"},
{:mix_test_watch, "~> 1.0", only: :dev, runtime: false},
{:patiently, "~> 0.2"},
{:phoenix, "~> 1.4"},
{:phoenix_html, "~> 2.14.1"},
{:phoenix_pubsub, "~> 1.0"},
{:nanoid, "~> 2.0"},
{:placebo, "~> 2.0.0-rc2", only: [:dev, :test, :integration]},
{:plug_heartbeat, "~> 0.2.0"},
{:postgrex, "~> 0.15.1"},
{:prestige, "~> 1.0"},
{:quantum, "~>2.4"},
{:ranch, "~> 1.7.1", override: true},
{:redix, "~> 0.10"},
{:streaming_metrics, "~> 2.2"},
{:smart_city, "~> 3.0"},
{:smart_city_test, "~> 0.10.1", only: [:test, :integration]},
{:telemetry_event, in_umbrella: true},
{:temporary_env, "~> 2.0", only: :test, runtime: false},
{:timex, "~> 3.0"},
{:sobelow, "~> 0.8", only: :dev},
{:dialyxir, "~> 1.0.0-rc.6", only: :dev, runtime: false},
{:distillery, "~> 2.1"},
{:poison, "3.1.0", override: true},
# poison breaks @ 4.0.1 due to encode_to_iotdata missing from 4.0
# additionally, nearly no library that includes it as a dep is actually configured to use it
{:tasks, in_umbrella: true, only: :dev},
{:web, in_umbrella: true}
]
end
defp test_paths(:integration), do: ["test/integration"]
defp test_paths(_), do: ["test/unit"]
defp elixirc_paths(:test), do: ["test/utils", "test/unit/support", "lib"]
defp elixirc_paths(:integration), do: ["test/utils", "test/integration/support", "lib"]
defp elixirc_paths(_), do: ["lib"]
defp aliases() do
[
start: ["ecto.create --quiet", "ecto.migrate", "phx.server"]
]
end
end
| 33.575472 | 99 | 0.516437 |
1ce198dc795ae16cb0e114225b40ec56e50c2fb3 | 734 | exs | Elixir | binary/binary.exs | SLIB53/exercism-elixir-answers | 352e3b9b6c9e5f8025ccd462845f1682d115e1da | [
"MIT"
] | 2 | 2019-03-26T09:32:41.000Z | 2020-03-09T19:16:36.000Z | binary/binary.exs | SLIB53/exercism-elixir-answers | 352e3b9b6c9e5f8025ccd462845f1682d115e1da | [
"MIT"
] | null | null | null | binary/binary.exs | SLIB53/exercism-elixir-answers | 352e3b9b6c9e5f8025ccd462845f1682d115e1da | [
"MIT"
] | null | null | null | defmodule Binary do
@doc """
Convert a string containing a binary number to an integer.
On errors returns 0.
"""
@spec to_decimal(String.t()) :: non_neg_integer
def to_decimal(string) do
try do
string |> parse_tokens() |> tokens_to_integer()
rescue
_e in ArgumentError -> 0
end
end
@spec parse_tokens(String.t()) :: [integer]
defp parse_tokens(string) do
Enum.map(to_charlist(string), fn
?0 -> 0
?1 -> 1
_ -> raise ArgumentError
end)
end
@spec tokens_to_integer([integer]) :: integer
defp tokens_to_integer(tokens) do
Enum.zip(tokens, (length(tokens) - 1)..0)
|> Enum.map(fn {t, exp} -> t * round(:math.pow(2, exp)) end)
|> Enum.sum()
end
end
| 22.9375 | 64 | 0.622616 |
1ce1a5777045c06e0573c314e7a51d1870a43d4e | 838 | ex | Elixir | test/support/conn_case.ex | PandemicPlayers/pandemic-server | 39ce8c12b5f08be7dc66623a69423265f01d23e1 | [
"MIT"
] | null | null | null | test/support/conn_case.ex | PandemicPlayers/pandemic-server | 39ce8c12b5f08be7dc66623a69423265f01d23e1 | [
"MIT"
] | null | null | null | test/support/conn_case.ex | PandemicPlayers/pandemic-server | 39ce8c12b5f08be7dc66623a69423265f01d23e1 | [
"MIT"
] | null | null | null | defmodule Pandemic.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 and query models.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
use Phoenix.ConnTest
import Pandemic.Router.Helpers
# The default endpoint for testing
@endpoint Pandemic.Endpoint
end
end
setup tags do
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 23.942857 | 56 | 0.721957 |
1ce1bbfdc78cd5b645fdaefdf04fd28e08f7121a | 1,989 | exs | Elixir | test/phoenix/live_dashboard/pages/ecto_stats_test.exs | albertored/phoenix_live_dashboard | 2807be12795cff88661e6d430de12b960edf1bde | [
"MIT"
] | null | null | null | test/phoenix/live_dashboard/pages/ecto_stats_test.exs | albertored/phoenix_live_dashboard | 2807be12795cff88661e6d430de12b960edf1bde | [
"MIT"
] | null | null | null | test/phoenix/live_dashboard/pages/ecto_stats_test.exs | albertored/phoenix_live_dashboard | 2807be12795cff88661e6d430de12b960edf1bde | [
"MIT"
] | null | null | null | defmodule Phoenix.LiveDashboard.EctoStatsPageTest do
use ExUnit.Case, async: true
import Phoenix.ConnTest
import Phoenix.LiveViewTest
@endpoint Phoenix.LiveDashboardTest.Endpoint
alias Phoenix.LiveDashboard.EctoStatsPage
alias Phoenix.LiveDashboardTest.Repo
@link "https://hexdocs.pm/phoenix_live_dashboard/ecto_stats.html"
test "menu_link/2" do
assert {:disabled, "Ecto Stats", @link} = EctoStatsPage.menu_link(%{repo: nil}, %{})
assert :skip = EctoStatsPage.menu_link(%{repo: Repo}, %{processes: []})
assert {:ok, "Phoenix LiveDashboardTest Repo Stats"} =
EctoStatsPage.menu_link(%{repo: Repo}, %{processes: [Repo]})
end
test "renders" do
{:ok, live, _} = live(build_conn(), ecto_stats_path())
rendered = render(live)
assert rendered =~ "All locks"
assert rendered =~ "Extensions"
assert rendered =~ "Transactionid"
assert rendered =~ "Granted"
end
@forbidden_navs [:calls, :outliers, :kill_all, :mandelbrot]
test "navs" do
for {nav, _} <- EctoPSQLExtras.queries(), nav not in @forbidden_navs do
{:ok, _, _} = live(build_conn(), ecto_stats_path(nav))
end
end
test "search" do
{:ok, live, _} = live(build_conn(), ecto_stats_path(:extensions))
rendered = render(live)
assert rendered =~ "Default version"
assert rendered =~ "Installed version"
assert rendered =~ "fuzzystrmatch"
assert rendered =~ "hstore"
{:ok, live, _} = live(build_conn(), ecto_stats_path(:extensions, "hstore"))
rendered = render(live)
assert rendered =~ "Default version"
assert rendered =~ "Installed version"
refute rendered =~ "fuzzystrmatch"
assert rendered =~ "hstore"
end
defp ecto_stats_path() do
"/dashboard/nonode%40nohost/phoenix_live_dashboard_test_repo_info"
end
defp ecto_stats_path(nav) do
"#{ecto_stats_path()}?nav=#{nav}"
end
defp ecto_stats_path(nav, search) do
"#{ecto_stats_path()}?nav=#{nav}&search=#{search}"
end
end
| 30.6 | 88 | 0.684766 |
1ce1c439afc8f0e78afbf8e3e000a4f66729166e | 3,539 | ex | Elixir | lib/dion/lexers/rst/inline.ex | avoceteditors/dion | 33198da25f77647630aeeeaf78959906d3a08c9f | [
"BSD-3-Clause"
] | null | null | null | lib/dion/lexers/rst/inline.ex | avoceteditors/dion | 33198da25f77647630aeeeaf78959906d3a08c9f | [
"BSD-3-Clause"
] | 4 | 2021-12-06T01:44:47.000Z | 2021-12-12T21:45:21.000Z | lib/dion/lexers/rst/inline.ex | avoceteditors/dion | 33198da25f77647630aeeeaf78959906d3a08c9f | [
"BSD-3-Clause"
] | null | null | null | defmodule Dion.Lexers.RST.Inline do
@moduledoc """
Provides function used to perform lexical analysis, searching for
inline reStructuredText (RST) elements.
"""
@moduledoc since: "0.1.0"
@doc """
Performs inline lexical analysis on the provided text.
The `lineno` argument is set on the return elements for reference and
error reporting purposes.
"""
def lex(text, lineno) do
text
|> String.split(~r/ +/)
|> Enum.map(
fn word -> format(word, lineno) end
)
|> Stream.map(&Task.async(Dion.Lexers.RST.Inline, :analyze_init, [&1]))
|> Enum.map(&Task.await(&1))
|> List.flatten
|> Stream.map(&Task.async(Dion.Lexers.RST.Inline, :analyze_term, [&1]))
|> Enum.map(&Task.await(&1))
|> List.flatten
end
@doc """
Formats the given string, setting line number, type, text, observe and reverse
enumerated text, text, and raw text.
"""
@doc since: "0.1.0"
def format(text, lineno, type) do
graph = String.graphemes(text)
data = %{
lineno: lineno,
rawtext: text,
text: text,
chars: graph,
rchars: Enum.reverse(graph),
type: :string
}
if type == nil do
data
else
Map.put(data, :type, type)
end
end
def format(text, lineno) do
format(text, lineno, nil)
end
@doc """
Removes initial characters and reanalyzes the start of the string.
"""
@doc since: "0.1.0"
def strip_init(word, chars) do
format(
String.slice(word[:text], chars..-1),
word[:lineno]
)
|> analyze_init
end
@doc """
Removes terminal characters and reanalyzes the end of the string.
"""
@doc since: "0.1.0"
def strip_term(word, chars) do
format(
String.slice(word[:text], 0..chars),
word[:lineno]
)
|> analyze_term
end
@doc """
Performs lexical analysis on the start of the string.
"""
@doc since: "0.1.0"
def analyze_init(word) do
case word[:chars] do
# Bold
["*", "*" | _] -> [:open_bold, strip_init(word, 2)]
["*" | _] -> [:open_italic, strip_init(word, 1)]
["`", "`" | _] -> [:open_code, strip_init(word, 2)]
["`" | _] -> [:open_literal, strip_init(word, 1)]
["\"" | _] -> [:open_quote, strip_init(word, 2)]
[":" | _] -> [:open_colon, strip_init(word, 1)]
["_" | _] -> [:open_score, strip_init(word, 1)]
_ -> [word]
end
end
@doc """
Evaluates the given word, returns atoms without conideration and passes
maps on for lexical analysis of the end of the string.
"""
@doc since: "0.1.0"
def analyze_term(word) do
if is_atom(word) do
word
else
analyze_term_content(word)
end
end
@doc """
Performs lexical analysis on the end of the string.
"""
@doc since: "0.1.0"
def analyze_term_content(word) do
term = Enum.at(word[:rchars], 0)
cond do
# Punctation
term in [".", ",", ";", "'", "?", "-", "]", ")", "}"] ->
[strip_term(word, -2), format(term, word[:lineno], :punct)]
true ->
case word[:rchars] do
["*", "*" | _] -> [strip_term(word, -3), :close_bold]
["*" | _] -> [strip_term(word, -2), :close_italic]
["`", "`" | _] -> [strip_term(word, -3), :close_code]
["`" | _] -> [strip_term(word, -2), :close_literal]
["\"" | _] -> [strip_term(word, -2), :close_quote]
[":" | _] -> [strip_term(word, -2), :close_colon]
["_" | _] -> [strip_term(word, -2), :close_score]
_ -> [word]
end
end
end
end
| 26.410448 | 80 | 0.563436 |
1ce1c98bdd21e9f45a809e6b243f02da8a0fb950 | 1,466 | exs | Elixir | test/recurly/webhooks/closed_invoice_notification_test.exs | calibr/recurly-client-elixir | a1160a10f90e0919adacf39bd95df3784e11fdcc | [
"MIT"
] | 8 | 2016-08-11T00:45:46.000Z | 2020-05-04T18:55:48.000Z | test/recurly/webhooks/closed_invoice_notification_test.exs | calibr/recurly-client-elixir | a1160a10f90e0919adacf39bd95df3784e11fdcc | [
"MIT"
] | 10 | 2016-08-15T20:01:56.000Z | 2019-05-10T02:09:35.000Z | test/recurly/webhooks/closed_invoice_notification_test.exs | calibr/recurly-client-elixir | a1160a10f90e0919adacf39bd95df3784e11fdcc | [
"MIT"
] | 4 | 2017-10-16T14:29:58.000Z | 2019-05-09T23:20:56.000Z | defmodule Recurly.Webhooks.ClosedInvoiceNotificationTest do
use ExUnit.Case, async: true
alias Recurly.{Webhooks,Account,Invoice}
test "correctly parses payload" do
xml_doc = """
<closed_invoice_notification>
<account>
<account_code>1</account_code>
<username nil="true"></username>
<email>verena@example.com</email>
<first_name>Verana</first_name>
<last_name>Example</last_name>
<company_name nil="true"></company_name>
</account>
<invoice>
<uuid>ffc64d71d4b5404e93f13aac9c63b007</uuid>
<subscription_id nil="true"></subscription_id>
<state>collected</state>
<invoice_number_prefix></invoice_number_prefix>
<invoice_number type="integer">1000</invoice_number>
<po_number></po_number>
<vat_number></vat_number>
<total_in_cents type="integer">1100</total_in_cents>
<currency>USD</currency>
<date type="datetime">2014-01-01T20:20:29Z</date>
<closed_at type="datetime">2014-01-01T20:24:02Z</closed_at>
</invoice>
</closed_invoice_notification>
"""
notification = %Webhooks.ClosedInvoiceNotification{} = Webhooks.parse(xml_doc)
account = %Account{} = notification.account
invoice = %Invoice{} = notification.invoice
assert account.account_code == "1"
assert invoice.uuid == "ffc64d71d4b5404e93f13aac9c63b007"
end
end
| 36.65 | 82 | 0.654161 |
1ce1cbaba3193a48a16a984cdddfa5d5dcc657f7 | 288 | exs | Elixir | crawler_challenge/priv/repo/migrations/20191009195145_create_parties.exs | tuliostarling/crawler-challenge | 1b948769db200d09ac0481b9fd71a175d876d20f | [
"Apache-2.0"
] | null | null | null | crawler_challenge/priv/repo/migrations/20191009195145_create_parties.exs | tuliostarling/crawler-challenge | 1b948769db200d09ac0481b9fd71a175d876d20f | [
"Apache-2.0"
] | 3 | 2021-05-08T08:50:39.000Z | 2022-02-10T19:40:38.000Z | crawler_challenge/priv/repo/migrations/20191009195145_create_parties.exs | tuliostarling/elixir-crawler | 1b948769db200d09ac0481b9fd71a175d876d20f | [
"Apache-2.0"
] | null | null | null | defmodule CrawlerChallenge.Repo.Migrations.CreateParties do
use Ecto.Migration
def change do
create table(:parties) do
add :partie, :string
add :name, :string
add :position, :string
add :person_name_position, :string
timestamps()
end
end
end
| 19.2 | 59 | 0.673611 |
1ce1f8e8d864d2db40c2c4798d692aa0c099b663 | 429 | exs | Elixir | hacker_news/test/hacker_news_web/views/error_view_test.exs | suulcoder/ElixirStories | 6aaf8cdaf834b019d02f8c82461f0f7825540629 | [
"MIT"
] | null | null | null | hacker_news/test/hacker_news_web/views/error_view_test.exs | suulcoder/ElixirStories | 6aaf8cdaf834b019d02f8c82461f0f7825540629 | [
"MIT"
] | null | null | null | hacker_news/test/hacker_news_web/views/error_view_test.exs | suulcoder/ElixirStories | 6aaf8cdaf834b019d02f8c82461f0f7825540629 | [
"MIT"
] | null | null | null | defmodule HackerNewsWeb.ErrorViewTest do
use HackerNewsWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.html" do
assert render_to_string(HackerNewsWeb.ErrorView, "404.html", []) == "Not Found"
end
test "renders 500.html" do
assert render_to_string(HackerNewsWeb.ErrorView, "500.html", []) == "Internal Server Error"
end
end
| 28.6 | 95 | 0.741259 |
1ce1ff0555121f50e94351a6c667c52ce229ebaf | 744 | ex | Elixir | lib/media_server_web/live/live_helpers.ex | cgomesu/midarr-server | 02833567ceaedfff5549b90104ce7256b9e7472b | [
"MIT"
] | 1 | 2022-02-14T16:40:55.000Z | 2022-02-14T16:40:55.000Z | lib/media_server_web/live/live_helpers.ex | smilenkovski/midarr-server | ba1815f5ab12fbe5d5377aaee6709ea26c5459d4 | [
"MIT"
] | null | null | null | lib/media_server_web/live/live_helpers.ex | smilenkovski/midarr-server | ba1815f5ab12fbe5d5377aaee6709ea26c5459d4 | [
"MIT"
] | null | null | null | defmodule MediaServerWeb.LiveHelpers do
import Phoenix.LiveView.Helpers
@doc """
Renders a component inside the `MediaServerWeb.ModalComponent` component.
The rendered modal receives a `:return_to` option to properly update
the URL when the modal is closed.
## Examples
<%= live_modal MediaServerWeb.LibraryLive.FormComponent,
id: @library.id || :new,
action: @live_action,
library: @library,
return_to: Routes.library_index_path(@socket, :index) %>
"""
def live_modal(component, opts) do
path = Keyword.fetch!(opts, :return_to)
modal_opts = [id: :modal, return_to: path, component: component, opts: opts]
live_component(MediaServerWeb.ModalComponent, modal_opts)
end
end
| 31 | 80 | 0.709677 |
1ce20aebee82b0d4c57498b99a3d10ab6eff0953 | 48 | ex | Elixir | lib/ueberauth_vk.ex | asiniy/ueberauth_vk | 1dab73536e333f62bf7c72a5817b332a35c0d247 | [
"MIT"
] | 19 | 2016-04-03T18:10:58.000Z | 2020-01-12T04:29:46.000Z | lib/ueberauth_vk.ex | asiniy/ueberauth_vk | 1dab73536e333f62bf7c72a5817b332a35c0d247 | [
"MIT"
] | 94 | 2016-05-07T08:48:31.000Z | 2020-03-10T02:21:02.000Z | lib/ueberauth_vk.ex | asiniy/ueberauth_vk | 1dab73536e333f62bf7c72a5817b332a35c0d247 | [
"MIT"
] | 17 | 2016-05-07T10:12:10.000Z | 2018-03-23T11:36:45.000Z | defmodule UeberauthVK do
@moduledoc false
end
| 12 | 24 | 0.8125 |
1ce20dbd30ffd671057d4d862bf556832ea3fc91 | 883 | ex | Elixir | lib/photo_gallery_web/router.ex | rayrrr/fameliphotos | cc928abdc6d761d76113067432e9d6d0fcb2507b | [
"MIT"
] | 6 | 2019-10-08T01:30:08.000Z | 2020-10-01T04:49:33.000Z | lib/photo_gallery_web/router.ex | rayrrr/fameliphotos | cc928abdc6d761d76113067432e9d6d0fcb2507b | [
"MIT"
] | null | null | null | lib/photo_gallery_web/router.ex | rayrrr/fameliphotos | cc928abdc6d761d76113067432e9d6d0fcb2507b | [
"MIT"
] | 1 | 2019-11-08T22:58:31.000Z | 2019-11-08T22:58:31.000Z | defmodule PhotoGalleryWeb.Router do
use PhotoGalleryWeb, :router
use Pow.Phoenix.Router
use Pow.Extension.Phoenix.Router, otp_app: :photo_gallery
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
pipeline :protected do
plug Pow.Plug.RequireAuthenticated,
error_handler: Pow.Phoenix.PlugErrorHandler
end
scope "/" do
pipe_through :browser
pow_routes()
pow_extension_routes()
end
scope "/", PhotoGalleryWeb do
pipe_through [:browser, :protected]
# Add your protected routes here
resources "/photos", PhotoController, except: [:edit, :update]
end
scope "/", PhotoGalleryWeb do
pipe_through :browser
get "/", PageController, :index
end
end
| 20.534884 | 66 | 0.702152 |
1ce20f9db07955fb9baba3e0ddae8ffdd09d5710 | 256 | exs | Elixir | apps/web/config/prod.exs | bitwalker/aws-dist-test | 94d87e82b617da02d541f7b2744d20747d8ef21f | [
"Apache-2.0"
] | 4 | 2019-03-13T16:38:32.000Z | 2020-01-11T20:05:25.000Z | apps/web/config/prod.exs | bitwalker/aws-dist-test | 94d87e82b617da02d541f7b2744d20747d8ef21f | [
"Apache-2.0"
] | 1 | 2019-03-14T17:41:55.000Z | 2019-03-14T17:41:55.000Z | apps/web/config/prod.exs | bitwalker/aws-dist-test | 94d87e82b617da02d541f7b2744d20747d8ef21f | [
"Apache-2.0"
] | 1 | 2019-03-14T14:53:29.000Z | 2019-03-14T14:53:29.000Z | use Mix.Config
config :web, ExampleWeb.Endpoint,
server: true,
cache_static_manifest: "priv/static/cache_manifest.json",
version: Application.spec(:web, :vsn)
config :logger,
level: :info,
handle_sasl_reports: true,
handle_otp_reports: true
| 19.692308 | 59 | 0.75 |
1ce2162a51f3ffa235335838d8876442336d26f1 | 546 | ex | Elixir | lib/hl7/raw_message.ex | starbelly/elixir-hl7 | 677566200ac0da8bf84f7b7e62ffdf2386351469 | [
"Apache-2.0"
] | null | null | null | lib/hl7/raw_message.ex | starbelly/elixir-hl7 | 677566200ac0da8bf84f7b7e62ffdf2386351469 | [
"Apache-2.0"
] | null | null | null | lib/hl7/raw_message.ex | starbelly/elixir-hl7 | 677566200ac0da8bf84f7b7e62ffdf2386351469 | [
"Apache-2.0"
] | null | null | null | defmodule HL7.RawMessage do
require Logger
@moduledoc """
Contains the raw text of an HL7 message alongside parsed header metadata from the MSH segment.
Use `HL7.Message.raw/1` to generate the `HL7.RawMessage` struct.
"""
@type t :: %HL7.RawMessage{
raw: nil | binary(),
header: nil | HL7.Header.t()
}
defstruct raw: nil,
header: nil
defimpl String.Chars, for: HL7.RawMessage do
require Logger
def to_string(%HL7.RawMessage{raw: raw_text}) do
raw_text
end
end
end
| 21 | 96 | 0.641026 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.