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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e83231d9a6b8c330dbbdeddbb7fde25187d1eb17 | 768 | exs | Elixir | mix.exs | seanabrahams/elixir-bandsintown | 720d4926ffe0255d79b29991cb686e103919daa7 | [
"MIT"
] | 1 | 2017-06-02T00:11:14.000Z | 2017-06-02T00:11:14.000Z | mix.exs | seanabrahams/elixir-bandsintown | 720d4926ffe0255d79b29991cb686e103919daa7 | [
"MIT"
] | null | null | null | mix.exs | seanabrahams/elixir-bandsintown | 720d4926ffe0255d79b29991cb686e103919daa7 | [
"MIT"
] | null | null | null | defmodule Bandsintown.Mixfile do
use Mix.Project
def project do
[app: :bandsintown,
version: "0.1.0",
elixir: "~> 1.2",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
[applications: [:logger, :httpoison]]
end
# Dependencies can be Hex packages:
#
# {:mydep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
#
# Type "mix help deps" for more examples and options
defp deps do
[
{:httpoison, "~> 0.8"},
{:poison, "~> 1.5 or ~> 2.0 or ~> 3.0"}
]
end
end
| 21.333333 | 77 | 0.585938 |
e8325c156decbefd0ff86b75512ea53a7b39efbb | 1,896 | exs | Elixir | talks-articles/languages-n-runtimes/elixir/book--programming-elixir-ge-1.6/chapter-04.exs | abhishekkr/tutorials_as_code | f355dc62a5025b710ac6d4a6ac2f9610265fad54 | [
"MIT"
] | 37 | 2015-02-01T23:16:39.000Z | 2021-12-22T16:50:48.000Z | talks-articles/languages-n-runtimes/elixir/book--programming-elixir-ge-1.6/chapter-04.exs | abhishekkr/tutorials_as_code | f355dc62a5025b710ac6d4a6ac2f9610265fad54 | [
"MIT"
] | 1 | 2017-03-02T04:55:48.000Z | 2018-01-14T10:51:11.000Z | talks-articles/languages-n-runtimes/elixir/book--programming-elixir-ge-1.6/chapter-04.exs | abhishekkr/tutorials_as_code | f355dc62a5025b710ac6d4a6ac2f9610265fad54 | [
"MIT"
] | 15 | 2015-03-02T08:09:01.000Z | 2021-06-10T03:25:41.000Z | defmodule Shout do
def users() do
content = "some content to be not affected byuse of similar identifier in expression"
usr = with {:ok, file} = File.open("/etc/passwd"),
content = IO.read(file, :all),
:ok = File.close(file),
[_, uid, gid] = Regex.run(~r/^lp:.*?:(\d+):(\d+)/m, content)
do
"Group: #{gid}, User: #{uid}"
end
IO.puts usr
IO.puts content
end
def users_handled() do
with {:ok, file} = File.open("/etc/passwd"),
content = IO.read(file, :all),
:ok = File.close(file),
[_, uid, gid] <- Regex.run(~r/^lp:.*?:(\d+):(\d+)/m, content)
do
"Group: #{gid}, User: #{uid}"
end
end
def users_with_else() do
with {:ok, file} = File.open("/etc/passwd"),
content = IO.read(file, :all),
:ok = File.close(file),
[_, uid, gid] <- Regex.run(~r/^1xlp:.*?:(\d+):(\d+)/m, content)
do
"Group: #{gid}, User: #{uid}"
else
nil -> "no relevant user found"
:error -> :error
end
end
def users_handled_paren() do
with(
{:ok, file} = File.open("/etc/passwd"),
content = IO.read(file, :all),
:ok = File.close(file),
[_, uid, gid] <- Regex.run(~r/^lp:.*?:(\d+):(\d+)/m, content)
)do
"Group: #{gid}, User: #{uid}"
end
end
def users_do_colon() do
with {:ok, file} = File.open("/etc/passwd"),
content = IO.read(file, :all),
:ok = File.close(file),
[_, uid, gid] <- Regex.run(~r/^lp:.*?:(\d+):(\d+)/m, content),
do: "Group: #{gid}, User: #{uid}"
end
end
Shout.users
IO.puts Shout.users_handled
IO.puts Shout.users_with_else
IO.puts Shout.users_handled_paren
IO.puts Shout.users_do_colon
| 29.625 | 89 | 0.484705 |
e8325d88e85f0f324a8706672f0616c69f82a61a | 1,153 | exs | Elixir | spec/error_pipe/with_error_pipe_spec.exs | antonmi/flowex | 7597e2ae1bf53033679ba65e0be13a50ad6f1e5e | [
"Apache-2.0"
] | 422 | 2017-01-20T13:38:13.000Z | 2022-02-08T14:07:11.000Z | spec/error_pipe/with_error_pipe_spec.exs | antonmi/flowex | 7597e2ae1bf53033679ba65e0be13a50ad6f1e5e | [
"Apache-2.0"
] | 11 | 2017-01-26T15:40:36.000Z | 2020-07-02T21:02:18.000Z | spec/error_pipe/with_error_pipe_spec.exs | antonmi/flowex | 7597e2ae1bf53033679ba65e0be13a50ad6f1e5e | [
"Apache-2.0"
] | 20 | 2017-01-25T07:56:00.000Z | 2021-11-29T16:19:34.000Z | defmodule WithErrorPipeSpec do
use ESpec, async: true
defmodule Pipeline do
use Flowex.Pipeline
defstruct data: nil, error: nil
pipe :one
pipe :two
pipe :three
error_pipe :if_error
def one(_struct, _opts), do: raise(ArithmeticError, "error")
def two(struct, _opts), do: struct
def three(struct, _opts), do: struct
def if_error(error, struct, _opts) do
%{struct | error: error}
end
end
let :result do
pipeline = Pipeline.start
Pipeline.call(pipeline, %Pipeline{data: nil})
end
it "return struct with error" do
expect(result().__struct__) |> to(eq Pipeline)
expect(result().error.__struct__) |> to(eq Flowex.PipeError)
expect(result().error.error) |> to(eq %ArithmeticError{message: "error"})
end
context "checks error" do
let :error, do: result().error
it "has message" do
expect(error().message) |> to(eq "error")
end
it "has pipe info" do
expect(error().pipe) |> to(eq {WithErrorPipeSpec.Pipeline, :one, %{}})
end
it "has struct info" do
expect(error().struct) |> to(eq %{data: nil, error: nil})
end
end
end
| 23.530612 | 77 | 0.639202 |
e832756c350db8887c47fbf96523568370c94f2f | 2,344 | ex | Elixir | clients/service_control/lib/google_api/service_control/v1/model/status.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/service_control/lib/google_api/service_control/v1/model/status.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/service_control/lib/google_api/service_control/v1/model/status.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.ServiceControl.V1.Model.Status do
@moduledoc """
The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
## Attributes
* `code` (*type:* `integer()`, *default:* `nil`) - The status code, which should be an enum value of google.rpc.Code.
* `details` (*type:* `list(map())`, *default:* `nil`) - A list of messages that carry the error details. There is a common set of message types for APIs to use.
* `message` (*type:* `String.t`, *default:* `nil`) - A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:code => integer() | nil,
:details => list(map()) | nil,
:message => String.t() | nil
}
field(:code)
field(:details, type: :list)
field(:message)
end
defimpl Poison.Decoder, for: GoogleApi.ServiceControl.V1.Model.Status do
def decode(value, options) do
GoogleApi.ServiceControl.V1.Model.Status.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceControl.V1.Model.Status do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 44.226415 | 427 | 0.721416 |
e8327eb69b0f8582e7d94e0cd03922f6bd5619b0 | 4,334 | exs | Elixir | .credo.exs | twix14/elastic | 1e2c7a3fe7b28bfa6cc574b10fd7bc6dca3dadfa | [
"MIT"
] | 63 | 2016-10-19T15:48:22.000Z | 2021-12-21T02:55:39.000Z | .credo.exs | twix14/elastic | 1e2c7a3fe7b28bfa6cc574b10fd7bc6dca3dadfa | [
"MIT"
] | 33 | 2016-11-13T02:41:07.000Z | 2021-05-25T11:12:51.000Z | .credo.exs | twix14/elastic | 1e2c7a3fe7b28bfa6cc574b10fd7bc6dca3dadfa | [
"MIT"
] | 27 | 2016-11-13T02:47:29.000Z | 2022-01-25T02:16:39.000Z | # This file contains the configuration for Credo and you are probably reading
# this after creating it with `mix credo.gen.config`.
#
# If you find anything wrong or unclear in this file, please report an
# issue on GitHub: https://github.com/rrrene/credo/issues
#
%{
#
# You can have as many configs as you like in the `configs:` field.
configs: [
%{
#
# Run any config using `mix credo -C <name>`. If no config name is given
# "default" is used.
name: "default",
#
# these are the files included in the analysis
files: %{
#
# you can give explicit globs or simply directories
# in the latter case `**/*.{ex,exs}` will be used
included: ["lib/", "src/", "web/", "apps/"],
excluded: [~r"/_build/", ~r"/deps/"]
},
#
# If you create your own checks, you must specify the source files for
# them here, so they can be loaded by Credo before running the analysis.
requires: [],
#
# Credo automatically checks for updates, like e.g. Hex does.
# You can disable this behaviour below:
check_for_updates: true,
#
# You can customize the parameters of any check by adding a second element
# to the tuple.
#
# To disable a check put `false` as second element:
#
# {Credo.Check.Design.DuplicatedCode, false}
#
checks: [
{Credo.Check.Consistency.ExceptionNames},
{Credo.Check.Consistency.LineEndings},
{Credo.Check.Consistency.SpaceAroundOperators},
{Credo.Check.Consistency.SpaceInParentheses},
{Credo.Check.Consistency.TabsOrSpaces},
# For some checks, like AliasUsage, you can only customize the priority
# Priority values are: `low, normal, high, higher`
{Credo.Check.Design.AliasUsage, priority: :low},
# For others you can set parameters
# If you don't want the `setup` and `test` macro calls in ExUnit tests
# or the `schema` macro in Ecto schemas to trigger DuplicatedCode, just
# set the `excluded_macros` parameter to `[:schema, :setup, :test]`.
{Credo.Check.Design.DuplicatedCode, excluded_macros: []},
# You can also customize the exit_status of each check.
# If you don't want TODO comments to cause `mix credo` to fail, just
# set this value to 0 (zero).
{Credo.Check.Design.TagTODO, exit_status: 2},
{Credo.Check.Design.TagFIXME},
{Credo.Check.Readability.FunctionNames},
{Credo.Check.Readability.LargeNumbers},
{Credo.Check.Readability.MaxLineLength, false},
{Credo.Check.Readability.ModuleAttributeNames},
{Credo.Check.Readability.ModuleDoc},
{Credo.Check.Readability.ModuleNames},
{Credo.Check.Readability.ParenthesesInCondition},
{Credo.Check.Readability.PredicateFunctionNames},
{Credo.Check.Readability.TrailingBlankLine},
{Credo.Check.Readability.TrailingWhiteSpace},
{Credo.Check.Readability.VariableNames},
{Credo.Check.Refactor.ABCSize},
# {Credo.Check.Refactor.CaseTrivialMatches}, # deprecated in 0.4.0
{Credo.Check.Refactor.CondStatements},
{Credo.Check.Refactor.FunctionArity},
{Credo.Check.Refactor.MatchInCondition},
{Credo.Check.Refactor.PipeChainStart, false},
{Credo.Check.Refactor.CyclomaticComplexity},
{Credo.Check.Refactor.NegatedConditionsInUnless},
{Credo.Check.Refactor.NegatedConditionsWithElse},
{Credo.Check.Refactor.Nesting},
{Credo.Check.Refactor.UnlessWithElse},
{Credo.Check.Warning.IExPry},
{Credo.Check.Warning.IoInspect},
{Credo.Check.Warning.OperationOnSameValues},
{Credo.Check.Warning.BoolOperationOnSameValues},
{Credo.Check.Warning.UnusedEnumOperation},
{Credo.Check.Warning.UnusedKeywordOperation},
{Credo.Check.Warning.UnusedListOperation},
{Credo.Check.Warning.UnusedStringOperation},
{Credo.Check.Warning.UnusedTupleOperation},
{Credo.Check.Warning.OperationWithConstantResult},
{Credo.Check.Refactor.MapInto, false},
{Credo.Check.Warning.LazyLogging, false},
# Custom checks can be created using `mix credo.gen.check`.
#
]
}
]
}
| 39.761468 | 80 | 0.652746 |
e832a09001f00c00a21f9551eb8d60e277840043 | 69 | exs | Elixir | test/test_helper.exs | jeantsai/phoenix-admin | 3f954f0c452d385438b616f7e91bc5d66bcc1adc | [
"MIT"
] | null | null | null | test/test_helper.exs | jeantsai/phoenix-admin | 3f954f0c452d385438b616f7e91bc5d66bcc1adc | [
"MIT"
] | null | null | null | test/test_helper.exs | jeantsai/phoenix-admin | 3f954f0c452d385438b616f7e91bc5d66bcc1adc | [
"MIT"
] | null | null | null | ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(Admin.Repo, :manual)
| 13.8 | 51 | 0.753623 |
e8331b49112c28234d1532e882a18874e5cce24c | 5,581 | ex | Elixir | lib/mix.tasks/snoop.ex | ityonemo/ExDhcp | 9a7f47da61a93b4fb9efaa62bbdb362e3b467b2b | [
"MIT"
] | null | null | null | lib/mix.tasks/snoop.ex | ityonemo/ExDhcp | 9a7f47da61a93b4fb9efaa62bbdb362e3b467b2b | [
"MIT"
] | 16 | 2019-12-16T04:56:50.000Z | 2020-03-11T20:18:56.000Z | lib/mix.tasks/snoop.ex | ityonemo/ex_dhcp | 9a7f47da61a93b4fb9efaa62bbdb362e3b467b2b | [
"MIT"
] | null | null | null | defmodule Mix.Tasks.Snoop do
use Mix.Task
@moduledoc """
A tool for snooping on DHCP transactions that are passing by this particular
connected device.
## Usage
Run this mix task on a device on the same layer-2 network as the network
where you'd like to watch DHCP packets go by. It's probably a good idea to
*not* have this be the same machine that you're using to serve DHCP.
```bash
mix snoop
```
Defaults to listening to UDP ports 67 and 68. In order to use this feature
on most Linux machines, you'll need give your erlang virtual machine
permission to listen on (< 1024) port numbers. You can do this with the
following command as superuser:
```bash
setcap 'cap_net_bind_service,cap_net_raw=+ep' /usr/lib/erlang/erts-10.6.1/bin/beam.smp
```
Note that the path to your `beam.smp` might be different.
`Ctrl-c` will exit out of this mix task
### Using without `setcap`
You can use this program without changing the permissions on `beam.smp`.
Instead, supply the `--port` or `-p` parameter to the mix task, like so:
```bash
mix snoop -p 6767
```
And you'll want to forward UDP port activity from 67 and 68 to
the snoop port 6767, you may use `iptables` as superuser to achieve this.
Note that these changes may not persist on certain network activity
(such as (libvirt)[https://libvirt.org/] creating or destroying a network),
and certainly not on reboot. Instrumenting these settings as permanent is
beyond the scope of this guide.
```bash
iptables -t nat -I PREROUTING -p udp --dport 67 -j DNAT --to :6767
iptables -t nat -I PREROUTING -p udp --dport 68 -j DNAT --to :6767
```
This will cause DHCP packets streaming to be logged to the console.
## Options
- `--bind <device>` or `-b <device>` binds this mix task to a specific
network device.
- `--save <prefix>` or `-s <prefix>` saves packets (as erlang term binaries) to files
with the given prefix
"""
@shortdoc "snoop on DHCP packets as they go by"
defmodule DhcpSnooper do
@moduledoc false
defstruct [:save]
use ExDhcp
require Logger
def start_link(_init, opts \\ []) do
ExDhcp.start_link(__MODULE__, struct(__MODULE__, opts), opts)
end
@impl true
def init(config), do: {:ok, config}
@impl true
def handle_discover(packet, _, _, state) do
saveinfo = save(packet, state)
Logger.info(saveinfo <> inspect packet)
{:norespond, state}
end
@impl true
def handle_request(packet, _, _, state) do
saveinfo = save(packet, state)
Logger.info(saveinfo <> inspect packet)
{:norespond, state}
end
@impl true
def handle_decline(packet, _, _, state) do
saveinfo = save(packet, state)
Logger.info(saveinfo <> inspect packet)
{:norespond, state}
end
@impl true
def handle_inform(packet, _, _, state) do
saveinfo = save(packet, state)
Logger.info(saveinfo <> inspect packet)
{:norespond, state}
end
@impl true
def handle_release(packet, _, _, state) do
saveinfo = save(packet, state)
Logger.info(saveinfo <> inspect packet)
{:norespond, state}
end
@impl true
def handle_packet(packet, _, _, state) do
saveinfo = save(packet, state)
Logger.info(saveinfo <> inspect packet)
{:norespond, state}
end
@impl true
def handle_info({:udp, _, _, _, binary}, state) do
unrolled_binary = binary
|> :erlang.binary_to_list
|> Enum.chunk_every(16)
|> Enum.map(&Enum.join(&1, ", "))
|> Enum.join("\n")
Logger.warn("untrapped udp: \n <<#{unrolled_binary}>> ")
{:noreply, state}
end
def handle_info(info, state) do
Logger.warn(inspect info)
{:noreply, state}
end
defp save(_, %{save: nil}), do: ""
defp save(packet, %{save: prefix}) do
last_index = prefix
|> Path.expand
|> Path.dirname
|> File.ls!
|> Enum.filter(&String.starts_with?(&1, prefix))
|> Enum.map(fn filename ->
filename |> Path.basename(".pkt") |> String.split("-") |> List.last |> String.to_integer
end)
|> Enum.max(fn -> 0 end)
filename = "#{prefix}-#{last_index + 1}.pkt"
File.write!(filename, :erlang.term_to_binary(packet))
"(saved to #{filename}) "
end
end
@doc false
def run(params) do
params = parse_params(params)
case params[:port] do
[] ->
# the default should be start up on both standard DHCP port
DhcpSnooper.start_link(:ok, Keyword.put(params, :port, 67))
DhcpSnooper.start_link(:ok, Keyword.put(params, :port, 68))
lst ->
Enum.map(lst, fn port ->
DhcpSnooper.start_link(:ok, Keyword.put(params, :port, port))
end)
end
receive do after :infinity -> :ok end
end
@bind ~w(-b --bind)
@port ~w(-p --port)
@save ~w(-s --save)
defp parse_params(lst, params \\ [port: []])
defp parse_params([], params), do: params
defp parse_params([switch, dev | rest], params) when switch in @bind do
parse_params(rest, Keyword.put(params, :bind_to_device, dev))
end
defp parse_params([switch, n | rest], params) when switch in @port do
port = [String.to_integer(n) | params[:port]]
parse_params(rest, Keyword.put(params, :port, port))
end
defp parse_params([switch, file_prefix | rest], params) when switch in @save do
parse_params(rest, Keyword.put(params, :save, file_prefix))
end
defp parse_params([_ | rest], params), do: parse_params(rest, params)
end
| 28.620513 | 96 | 0.643971 |
e83321de89ca1b4485e0e7c4bcc2cc9016fd6921 | 110 | exs | Elixir | test/phoenix_react_playground_web/views/page_view_test.exs | vinej/tpr | 4377a6cbe2b1105731296ad7630a905c40acd2de | [
"Unlicense"
] | 88 | 2017-09-01T03:13:00.000Z | 2021-06-26T10:56:29.000Z | test/phoenix_react_playground_web/views/page_view_test.exs | vinej/tpr | 4377a6cbe2b1105731296ad7630a905c40acd2de | [
"Unlicense"
] | 4 | 2020-07-17T07:52:09.000Z | 2021-09-01T06:46:54.000Z | test/phoenix_react_playground_web/views/page_view_test.exs | vinej/tpr | 4377a6cbe2b1105731296ad7630a905c40acd2de | [
"Unlicense"
] | 21 | 2017-09-01T03:18:09.000Z | 2021-09-23T09:07:41.000Z | defmodule PhoenixReactPlaygroundWeb.PageViewTest do
use PhoenixReactPlaygroundWeb.ConnCase, async: true
end
| 27.5 | 53 | 0.872727 |
e8332ce69f958e3c893629f2d7bce18fd01184df | 8,463 | exs | Elixir | apps/admin_api/test/admin_api/v1/controllers/admin_auth/category_controller_test.exs | amadeobrands/ewallet | 505b7822721940a7b892a9b35c225e80cc8ac0b4 | [
"Apache-2.0"
] | 1 | 2018-12-07T06:21:21.000Z | 2018-12-07T06:21:21.000Z | apps/admin_api/test/admin_api/v1/controllers/admin_auth/category_controller_test.exs | amadeobrands/ewallet | 505b7822721940a7b892a9b35c225e80cc8ac0b4 | [
"Apache-2.0"
] | null | null | null | apps/admin_api/test/admin_api/v1/controllers/admin_auth/category_controller_test.exs | amadeobrands/ewallet | 505b7822721940a7b892a9b35c225e80cc8ac0b4 | [
"Apache-2.0"
] | null | null | null | defmodule AdminAPI.V1.AdminAuth.CategoryControllerTest do
use AdminAPI.ConnCase, async: true
alias EWalletDB.Category
alias EWalletDB.Helpers.Preloader
describe "/category.all" do
test "returns a list of categories and pagination data" do
response = admin_user_request("/category.all")
# Asserts return data
assert response["success"]
assert response["data"]["object"] == "list"
assert is_list(response["data"]["data"])
# Asserts pagination data
pagination = response["data"]["pagination"]
assert is_integer(pagination["per_page"])
assert is_integer(pagination["current_page"])
assert is_boolean(pagination["is_last_page"])
assert is_boolean(pagination["is_first_page"])
end
test "returns a list of categories according to search_term, sort_by and sort_direction" do
insert(:category, %{name: "Matched 2"})
insert(:category, %{name: "Matched 3"})
insert(:category, %{name: "Matched 1"})
insert(:category, %{name: "Missed 1"})
attrs = %{
# Search is case-insensitive
"search_term" => "MaTcHed",
"sort_by" => "name",
"sort_dir" => "desc"
}
response = admin_user_request("/category.all", attrs)
categories = response["data"]["data"]
assert response["success"]
assert Enum.count(categories) == 3
assert Enum.at(categories, 0)["name"] == "Matched 3"
assert Enum.at(categories, 1)["name"] == "Matched 2"
assert Enum.at(categories, 2)["name"] == "Matched 1"
end
test_supports_match_any("/category.all", :admin_auth, :category, :name)
test_supports_match_all("/category.all", :admin_auth, :category, :name)
end
describe "/category.get" do
test "returns an category by the given category's ID" do
categories = insert_list(3, :category)
# Pick the 2nd inserted category
target = Enum.at(categories, 1)
response = admin_user_request("/category.get", %{"id" => target.id})
assert response["success"]
assert response["data"]["object"] == "category"
assert response["data"]["name"] == target.name
end
test "returns 'category:id_not_found' if the given ID was not found" do
response = admin_user_request("/category.get", %{"id" => "cat_12345678901234567890123456"})
refute response["success"]
assert response["data"]["object"] == "error"
assert response["data"]["code"] == "category:id_not_found"
assert response["data"]["description"] ==
"There is no category corresponding to the provided id."
end
test "returns 'category:id_not_found' if the given ID format is invalid" do
response = admin_user_request("/category.get", %{"id" => "not_an_id"})
refute response["success"]
assert response["data"]["object"] == "error"
assert response["data"]["code"] == "category:id_not_found"
assert response["data"]["description"] ==
"There is no category corresponding to the provided id."
end
end
describe "/category.create" do
test "creates a new category and returns it" do
request_data = %{name: "A test category"}
response = admin_user_request("/category.create", request_data)
assert response["success"] == true
assert response["data"]["object"] == "category"
assert response["data"]["name"] == request_data.name
end
test "returns an error if the category name is not provided" do
request_data = %{name: ""}
response = admin_user_request("/category.create", request_data)
assert response["success"] == false
assert response["data"]["object"] == "error"
assert response["data"]["code"] == "client:invalid_parameter"
end
end
describe "/category.update" do
test "updates the given category" do
category = insert(:category)
# Prepare the update data while keeping only id the same
request_data =
params_for(:category, %{
id: category.id,
name: "updated_name",
description: "updated_description"
})
response = admin_user_request("/category.update", request_data)
assert response["success"] == true
assert response["data"]["object"] == "category"
assert response["data"]["name"] == "updated_name"
assert response["data"]["description"] == "updated_description"
end
test "updates the category's accounts" do
category = :category |> insert() |> Preloader.preload(:accounts)
account = :account |> insert()
assert Enum.empty?(category.accounts)
# Prepare the update data while keeping only id the same
request_data = %{
id: category.id,
account_ids: [account.id]
}
response = admin_user_request("/category.update", request_data)
assert response["success"] == true
assert response["data"]["object"] == "category"
assert response["data"]["account_ids"] == [account.id]
assert List.first(response["data"]["accounts"]["data"])["id"] == account.id
end
test "returns a 'client:invalid_parameter' error if id is not provided" do
request_data = params_for(:category, %{id: nil})
response = admin_user_request("/category.update", request_data)
assert response["success"] == false
assert response["data"]["object"] == "error"
assert response["data"]["code"] == "client:invalid_parameter"
assert response["data"]["description"] == "Invalid parameter provided."
end
test "returns an 'unauthorized' error if id is invalid" do
request_data = params_for(:category, %{id: "invalid_format"})
response = admin_user_request("/category.update", request_data)
assert response["success"] == false
assert response["data"]["object"] == "error"
assert response["data"]["code"] == "category:id_not_found"
assert response["data"]["description"] ==
"There is no category corresponding to the provided id."
end
end
describe "/category.delete" do
test "responds success with the deleted category" do
category = insert(:category)
response = admin_user_request("/category.delete", %{id: category.id})
assert response["success"] == true
assert response["data"]["object"] == "category"
assert response["data"]["id"] == category.id
end
test "responds with an error if the category has one or more associated accounts" do
account = insert(:account)
{:ok, category} =
:category
|> insert()
|> Category.update(%{account_ids: [account.id]})
response = admin_user_request("/category.delete", %{id: category.id})
assert response ==
%{
"version" => "1",
"success" => false,
"data" => %{
"code" => "category:not_empty",
"description" => "The category has one or more accounts associated.",
"messages" => nil,
"object" => "error"
}
}
end
test "responds with an error if the provided id is not found" do
response = admin_user_request("/category.delete", %{id: "wrong_id"})
assert response ==
%{
"version" => "1",
"success" => false,
"data" => %{
"code" => "category:id_not_found",
"description" => "There is no category corresponding to the provided id.",
"messages" => nil,
"object" => "error"
}
}
end
test "responds with an error if the user is not authorized to delete the category" do
category = insert(:category)
auth_token = insert(:auth_token, owner_app: "admin_api")
attrs = %{id: category.id}
opts = [user_id: auth_token.user.id, auth_token: auth_token.token]
response = admin_user_request("/category.delete", attrs, opts)
assert response ==
%{
"version" => "1",
"success" => false,
"data" => %{
"code" => "unauthorized",
"description" => "You are not allowed to perform the requested operation.",
"messages" => nil,
"object" => "error"
}
}
end
end
end
| 35.410042 | 97 | 0.600851 |
e83336f2179813afef1bf1b1ed1d03fdfbca89aa | 2,120 | exs | Elixir | test/combined_test.exs | robpark/elixir-roman-numerals | c69c27369a0fc28999f16cb9c0b0fdd4a8823f53 | [
"MIT"
] | 1 | 2015-11-23T17:11:59.000Z | 2015-11-23T17:11:59.000Z | test/combined_test.exs | robpark/elixir_roman_numerals | c69c27369a0fc28999f16cb9c0b0fdd4a8823f53 | [
"MIT"
] | null | null | null | test/combined_test.exs | robpark/elixir_roman_numerals | c69c27369a0fc28999f16cb9c0b0fdd4a8823f53 | [
"MIT"
] | null | null | null | defmodule CombinedTest do
use ExUnit.Case
Enum.each 1..2000, fn(arabic) ->
roman = Arabic.to_roman arabic
computed_arabic = Roman.to_arabic roman
test "#{arabic} -- #{roman} -- #{computed_arabic}" do
assert unquote(computed_arabic) == unquote(arabic)
end
test "at most 3: #{roman}" do
_assert_no_more_than_3(unquote(roman))
end
test "no repeats: #{roman}" do
_assert_no_repeats(unquote(roman))
end
test "only subract from 2 next highest: #{roman}" do
_assert_subtraction_from_2_next(unquote(roman))
end
test "only 1 subraction per numeral: #{roman}" do
_assert_1_subtraction_per(unquote(roman))
end
test "cannot subtract: #{roman}" do
_assert_cannot_subtract(unquote(roman))
end
end
defp _assert_no_more_than_3(roman) do
refute String.contains?(roman, "IIII"), "#{roman}: too many I"
refute String.contains?(roman, "XXXX"), "#{roman}: too many X"
refute String.contains?(roman, "CCCC"), "#{roman}: too many C"
refute String.contains?(roman, "MMMM"), "#{roman}: too many M"
end
defp _assert_no_repeats(roman) do
refute String.contains?(roman, "VV"), "#{roman}: repeated V"
refute String.contains?(roman, "LL"), "#{roman}: repeated L"
refute String.contains?(roman, "DD"), "#{roman}: repeated D"
end
defp _assert_subtraction_from_2_next(roman) do
refute String.contains?(roman, "IL")
refute String.contains?(roman, "IC")
refute String.contains?(roman, "ID")
refute String.contains?(roman, "IM")
refute String.contains?(roman, "XD")
refute String.contains?(roman, "XM")
end
defp _assert_1_subtraction_per(roman) do
refute String.contains?(roman, "IIV")
refute String.contains?(roman, "IIX")
refute String.contains?(roman, "XXL")
refute String.contains?(roman, "XXC")
refute String.contains?(roman, "CCD")
refute String.contains?(roman, "CCM")
end
defp _assert_cannot_subtract(roman) do
refute String.contains?(roman, "VX")
refute String.contains?(roman, "LC")
refute String.contains?(roman, "DM")
end
end
| 30.285714 | 66 | 0.669811 |
e8335cc28cf11ed4ea22ccb89f9fb000459f4706 | 2,586 | ex | Elixir | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/condition.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/condition.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/condition.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudRun.V1alpha1.Model.Condition do
@moduledoc """
Condition defines a generic condition for a Resource
## Attributes
* `lastTransitionTime` (*type:* `DateTime.t`, *default:* `nil`) - Optional. Last time the condition transitioned from one status to another.
* `message` (*type:* `String.t`, *default:* `nil`) - Optional. Human readable message indicating details about the current status.
* `reason` (*type:* `String.t`, *default:* `nil`) - Optional. One-word CamelCase reason for the condition's last transition.
* `severity` (*type:* `String.t`, *default:* `nil`) - Optional. How to interpret failures of this condition, one of Error, Warning, Info
* `status` (*type:* `String.t`, *default:* `nil`) - Status of the condition, one of True, False, Unknown.
* `type` (*type:* `String.t`, *default:* `nil`) - type is used to communicate the status of the reconciliation process. See also: https://github.com/knative/serving/blob/master/docs/spec/errors.md#error-conditions-and-reporting Types common to all resources include: * "Ready": True when the Resource is ready.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:lastTransitionTime => DateTime.t(),
:message => String.t(),
:reason => String.t(),
:severity => String.t(),
:status => String.t(),
:type => String.t()
}
field(:lastTransitionTime, as: DateTime)
field(:message)
field(:reason)
field(:severity)
field(:status)
field(:type)
end
defimpl Poison.Decoder, for: GoogleApi.CloudRun.V1alpha1.Model.Condition do
def decode(value, options) do
GoogleApi.CloudRun.V1alpha1.Model.Condition.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudRun.V1alpha1.Model.Condition do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 41.709677 | 314 | 0.704563 |
e8335d6c78a5760b0791cda205ae56afbb60d27f | 1,011 | exs | Elixir | mix.exs | tkschmidt/PushElixirOver | 34c9703f9863d65778fc97761359e5f013027c77 | [
"MIT"
] | null | null | null | mix.exs | tkschmidt/PushElixirOver | 34c9703f9863d65778fc97761359e5f013027c77 | [
"MIT"
] | null | null | null | mix.exs | tkschmidt/PushElixirOver | 34c9703f9863d65778fc97761359e5f013027c77 | [
"MIT"
] | null | null | null | defmodule PushElixirOver.Mixfile do
use Mix.Project
def project do
[app: :pushElixirOver,
version: "0.0.1",
elixir: "~> 1.0",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps]
end
# Configuration for the OTP application
#
# Type `mix help compile.app` for more information
def application do
[applications: [:logger, :httpoison],
mod: {PushElixirOver, []}]
end
# Dependencies can be Hex packages:
#
# {:mydep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
#
# Type `mix help deps` for more examples and options
defp deps do
[
{:httpoison, "~> 0.7.2"},
{:poison, "~> 1.5"}
]
end
defp package do
[ files: [ "lib", "mix.exs", "README.md", "LICENSE" ],
contributors: [ "Tobias Schmidt" ],
licenses: [ "MIT" ],
links: %{ "GitHub" => "https://github.com/tkschmidt/PushElixirOver" } ]
end
end
| 22.977273 | 77 | 0.588526 |
e83372098432b945c6214e407e466c8bb4f1ac74 | 422 | ex | Elixir | priv/templates/talon.new/web/controllers/page_controller.ex | talonframework/ex_admin | d164c065ac74c156c3abeca8437e184456db903c | [
"MIT"
] | 170 | 2017-05-25T15:09:53.000Z | 2021-07-09T04:04:14.000Z | priv/templates/talon.new/web/controllers/page_controller.ex | talonframework/ex_admin | d164c065ac74c156c3abeca8437e184456db903c | [
"MIT"
] | 78 | 2017-05-25T09:41:55.000Z | 2019-01-04T20:53:35.000Z | priv/templates/talon.new/web/controllers/page_controller.ex | talonframework/ex_admin | d164c065ac74c156c3abeca8437e184456db903c | [
"MIT"
] | 8 | 2017-06-24T12:28:06.000Z | 2018-09-17T16:11:56.000Z | defmodule <%= base %>.<%= web_namespace %><%= concern %>PageController do
use <%= base %>.Web, :controller
use Talon.PageController, concern: <%= base %>.<%= concern %>
plug Talon.Plug.LoadConcern, concern: <%= base %>.<%= concern %>, web_namespace: <%= web_module %>
plug Talon.Plug.Theme
plug Talon.Plug.Layout, layout: <%= layout %>
plug Talon.Plug.View
<%= if boilerplate do %>
# TODO
<% end %>
end
| 32.461538 | 100 | 0.627962 |
e833736bdeec97b01e802f82335c5d3bf43fa95d | 488 | ex | Elixir | gateway/lib/channel/supervisor.ex | xonnect/server-ce | 7ec2e689a19098a17dfc5eaf190d56f29fb45263 | [
"BSD-2-Clause"
] | null | null | null | gateway/lib/channel/supervisor.ex | xonnect/server-ce | 7ec2e689a19098a17dfc5eaf190d56f29fb45263 | [
"BSD-2-Clause"
] | null | null | null | gateway/lib/channel/supervisor.ex | xonnect/server-ce | 7ec2e689a19098a17dfc5eaf190d56f29fb45263 | [
"BSD-2-Clause"
] | null | null | null | defmodule Channel.Supervisor do
use Supervisor
# Supervisor api
def start_child(identifier) do
Supervisor.start_child __MODULE__, [identifier]
end
def start_link() do
Supervisor.start_link __MODULE__, [], name: __MODULE__
end
# Supervisor callback
def init([]) do
children = [
worker(Channel.Agent, [], restart: :temporary, shutdown: :brutal_kill)
]
supervise children, strategy: :simple_one_for_one, max_restarts: 0, max_seconds: 1
end
end
| 23.238095 | 86 | 0.713115 |
e83399fdabc4e58c2e2dc51ea9b9dc21a61d0d8e | 1,543 | ex | Elixir | lib/plexy/logger/simple_redactor.ex | heroku/plexy | bfdd4a539c2c0d8f80101cca8061a945a2cd6159 | [
"MIT"
] | 153 | 2016-11-07T15:11:52.000Z | 2021-11-16T23:20:52.000Z | lib/plexy/logger/simple_redactor.ex | heroku/plexy | bfdd4a539c2c0d8f80101cca8061a945a2cd6159 | [
"MIT"
] | 21 | 2016-11-07T14:55:09.000Z | 2022-03-30T18:31:31.000Z | lib/plexy/logger/simple_redactor.ex | heroku/plexy | bfdd4a539c2c0d8f80101cca8061a945a2cd6159 | [
"MIT"
] | 5 | 2018-07-09T05:02:53.000Z | 2019-11-01T01:08:09.000Z | defmodule Plexy.Logger.SimpleRedactor do
@moduledoc """
SimpleRedactor is able to filter and redact sensative data
"""
@doc """
Assuming line is in the format "key=value"
- redact the values for all "keys" under `opts` :redact
- filter out the entire line if it has a "key" under `opts` :filter
## Examples
iex> SimpleRedactor.run("username=bob age=21", redact: ["username"])
{:cont, "username=REDACTED age=21"}
iex> SimpleRedactor.run("password=mysecred", filter: ["password"])
{:cont, ""}
"""
def run("", _opts), do: {:halt, ""}
def run(line, opts) do
with {:cont, redacted} <- redact(line, Keyword.get(opts, :redact, [])),
{:cont, filtered} <- filter(redacted, Keyword.get(opts, :filter, [])),
do: {:cont, filtered}
end
defp redact(line, []), do: {:cont, line}
defp redact(line, keys) do
redacted =
Enum.reduce(keys, line, fn k, l ->
with {:ok, quoted} <- Regex.compile("#{k}=\"[^\"]+\"(\s?)"),
{:ok, nquoted} <- Regex.compile("#{k}=[^\s]+(\s?)") do
quoted_redacted = Regex.replace(quoted, l, "#{k}=REDACTED\\1")
Regex.replace(nquoted, quoted_redacted, "#{k}=REDACTED\\1")
end
end)
{:cont, redacted}
end
defp filter(line, []), do: {:cont, line}
defp filter(line, keys) do
line =
Enum.reduce_while(keys, line, fn k, l ->
if String.contains?(l, "#{k}=") do
{:halt, ""}
else
{:cont, l}
end
end)
{:cont, line}
end
end
| 27.070175 | 79 | 0.558652 |
e833bf58c08075811d5022938d4657b1ac677417 | 6,539 | ex | Elixir | lib/app/router.ex | wasi0013/tbud | 19b3931f758cd5c923296a7f64ffc74d320e2243 | [
"MIT"
] | null | null | null | lib/app/router.ex | wasi0013/tbud | 19b3931f758cd5c923296a7f64ffc74d320e2243 | [
"MIT"
] | 2 | 2021-11-12T14:34:12.000Z | 2021-11-12T14:40:30.000Z | lib/app/router.ex | wasi0013/tbud | 19b3931f758cd5c923296a7f64ffc74d320e2243 | [
"MIT"
] | null | null | null | defmodule App.Router do
@bot_name Application.compile_env(:app, :bot_name)
# Code injectors
defmacro __using__(_opts) do
quote do
require Logger
import App.Router
def match_message(message) do
try do
apply(__MODULE__, :do_match_message, [message])
rescue
err in FunctionClauseError ->
Logger.log(:warn, """
Errored when matching command. #{Poison.encode!(err)}
Message was: #{Poison.encode!(message)}
""")
end
end
end
end
def generate_message_matcher(handler) do
quote do
def do_match_message(var!(update)) do
handle_message(unquote(handler), [var!(update)])
end
end
end
defp generate_command(command, handler) do
quote do
def do_match_message(
%{
message: %{
text: "/" <> unquote(command)
}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
def do_match_message(
%{
message: %{
text: "/" <> unquote(command) <> " " <> _
}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
def do_match_message(
%{
message: %{
text: "/" <> unquote(command) <> "@" <> unquote(@bot_name)
}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
def do_match_message(
%{
message: %{
text: "/" <> unquote(command) <> "@" <> unquote(@bot_name) <> " " <> _
}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
end
end
def generate_inline_query_matcher(handler) do
quote do
def do_match_message(%{inline_query: inline_query} = var!(update))
when not is_nil(inline_query) do
handle_message(unquote(handler), [var!(update)])
end
end
end
def generate_inline_query_command(command, handler) do
quote do
def do_match_message(
%{
inline_query: %{query: "/" <> unquote(command)}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
def do_match_message(
%{
inline_query: %{query: "/" <> unquote(command) <> " " <> _}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
end
end
def generate_callback_query_matcher(handler) do
quote do
def do_match_message(%{callback_query: callback_query} = var!(update))
when not is_nil(callback_query) do
handle_message(unquote(handler), [var!(update)])
end
end
end
def generate_callback_query_command(command, handler) do
quote do
def do_match_message(
%{
callback_query: %{data: "/" <> unquote(command)}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
def do_match_message(
%{
callback_query: %{data: "/" <> unquote(command) <> " " <> _}
} = var!(update)
) do
handle_message(unquote(handler), [var!(update)])
end
end
end
# Receiver Macros
## Match All
defmacro message(do: function) do
generate_message_matcher(function)
end
defmacro message(module, function) do
generate_message_matcher({module, function})
end
## Command
defmacro command(commands, do: function)
when is_list(commands) do
Enum.map(commands, fn command ->
generate_command(command, function)
end)
end
defmacro command(command, do: function) do
generate_command(command, function)
end
defmacro command(commands, module, function)
when is_list(commands) do
Enum.map(commands, fn command ->
generate_command(command, {module, function})
end)
end
defmacro command(command, module, function) do
generate_command(command, {module, function})
end
## Inline query
defmacro inline_query(do: function) do
generate_inline_query_matcher(function)
end
defmacro inline_query(module, function) do
generate_inline_query_matcher({module, function})
end
defmacro inline_query_command(commands, do: function)
when is_list(commands) do
Enum.map(commands, fn item ->
generate_inline_query_command(item, function)
end)
end
defmacro inline_query_command(command, do: function) do
generate_inline_query_command(command, function)
end
defmacro inline_query_command(commands, module, function)
when is_list(commands) do
Enum.map(commands, fn item ->
generate_inline_query_command(item, {module, function})
end)
end
defmacro inline_query_command(command, module, function) do
generate_inline_query_command(command, {module, function})
end
## Callback query
defmacro callback_query(do: function) do
generate_callback_query_matcher(function)
end
defmacro callback_query(module, function) do
generate_callback_query_matcher({module, function})
end
defmacro callback_query_command(commands, do: function)
when is_list(commands) do
Enum.map(commands, fn item ->
generate_callback_query_command(item, function)
end)
end
defmacro callback_query_command(command, do: function) do
generate_callback_query_command(command, function)
end
defmacro callback_query_command(commands, module, function)
when is_list(commands) do
Enum.map(commands, fn item ->
generate_callback_query_command(item, {module, function})
end)
end
defmacro callback_query_command(command, module, function) do
generate_callback_query_command(command, {module, function})
end
# Helpers
def handle_message({module, function}, update)
when is_atom(function) and is_list(update) do
Task.start(fn ->
apply(module, function, [hd(update)])
end)
end
def handle_message({module, function}, update)
when is_atom(function) do
Task.start(fn ->
apply(module, function, [update])
end)
end
def handle_message(function, _update)
when is_function(function) do
Task.start(fn ->
function.()
end)
end
def handle_message(_, _), do: nil
end
| 25.15 | 86 | 0.609726 |
e833e2342b63938f996f97f4c088373a1e4ea036 | 425 | ex | Elixir | 12elixirtut_loop.ex | kamranhossain/elixir-by-derek-banas | 44c08cb73d6e528cd5ff3df5f8b1ce79fb155926 | [
"MIT"
] | null | null | null | 12elixirtut_loop.ex | kamranhossain/elixir-by-derek-banas | 44c08cb73d6e528cd5ff3df5f8b1ce79fb155926 | [
"MIT"
] | null | null | null | 12elixirtut_loop.ex | kamranhossain/elixir-by-derek-banas | 44c08cb73d6e528cd5ff3df5f8b1ce79fb155926 | [
"MIT"
] | null | null | null | defmodule M do
def main do
do_stuff()
end
def do_stuff do
IO.puts "Sum : #{sum([1,2,3])}"
loop(5, 1)
end
def sum([]), do: 0
def sum([h|t]), do: h + sum(t)
def loop(0,_), do: nil
def loop(max, min) do
if max < min do
loop(0, min)
else
IO.puts "Num : #{max}"
loop(max - 1, min)
end
end
end
| 16.346154 | 39 | 0.414118 |
e83445cf4f4f7c69cb5de3ea296f8028f563213f | 23,865 | ex | Elixir | lib/tortoise311/connection.ex | jsmestad/tortoise311 | 146b4e5bcf967d0c07b43d0d029790f9f0a7d6a9 | [
"Apache-2.0"
] | null | null | null | lib/tortoise311/connection.ex | jsmestad/tortoise311 | 146b4e5bcf967d0c07b43d0d029790f9f0a7d6a9 | [
"Apache-2.0"
] | null | null | null | lib/tortoise311/connection.ex | jsmestad/tortoise311 | 146b4e5bcf967d0c07b43d0d029790f9f0a7d6a9 | [
"Apache-2.0"
] | null | null | null | defmodule Tortoise311.Connection do
@moduledoc """
Establish a connection to a MQTT broker.
Todo.
"""
use GenServer
require Logger
defstruct [
:client_id,
:connect,
:server,
:status,
:backoff,
:subscriptions,
:keep_alive,
:opts,
:handler
]
alias __MODULE__, as: State
alias Tortoise311.{Transport, Connection, Package, Events, Handler}
alias Tortoise311.Connection.{Inflight, Controller, Receiver, Backoff}
alias Tortoise311.Package.{Connect, Connack}
@doc """
Start a connection process and link it to the current process.
Read the documentation on `child_spec/1` if you want... (todo!)
"""
@spec start_link(options, GenServer.options()) :: GenServer.on_start()
when option:
{:client_id, Tortoise311.client_id()}
| {:server, {atom(), term()}}
| {:user_name, String.t()}
| {:password, String.t()}
| {:keep_alive, non_neg_integer()}
| {:will, Tortoise311.Package.Publish.t()}
| {:subscriptions,
[{Tortoise311.topic_filter(), Tortoise311.qos()}]
| Tortoise311.Package.Subscribe.t()}
| {:clean_session, boolean()}
| {:handler, {atom(), term()}},
options: [option]
def start_link(connection_opts, opts \\ []) do
client_id = Keyword.fetch!(connection_opts, :client_id)
server = connection_opts |> Keyword.fetch!(:server) |> Transport.new()
connect = %Package.Connect{
client_id: client_id,
user_name: Keyword.get(connection_opts, :user_name),
password: Keyword.get(connection_opts, :password),
keep_alive: Keyword.get(connection_opts, :keep_alive, 60),
will: Keyword.get(connection_opts, :will),
# if we re-spawn from here it means our state is gone
clean_session: Keyword.get(connection_opts, :clean_session, true)
}
backoff = Keyword.get(connection_opts, :backoff, [])
# This allow us to either pass in a list of topics, or a
# subscription struct. Passing in a subscription struct is helpful
# in tests.
subscriptions =
case Keyword.get(connection_opts, :subscriptions, []) do
topics when is_list(topics) ->
Enum.into(topics, %Package.Subscribe{})
%Package.Subscribe{} = subscribe ->
subscribe
end
# @todo, validate that the handler is valid
connection_opts = Keyword.take(connection_opts, [:client_id, :handler])
initial = {server, connect, backoff, subscriptions, connection_opts}
opts = Keyword.merge(opts, name: via_name(client_id))
GenServer.start_link(__MODULE__, initial, opts)
end
@doc false
@spec via_name(Tortoise311.client_id()) ::
pid() | {:via, Registry, {Tortoise311.Registry, {atom(), Tortoise311.client_id()}}}
def via_name(client_id) do
Tortoise311.Registry.via_name(__MODULE__, client_id)
end
@spec child_spec(Keyword.t()) :: %{
id: term(),
start: {__MODULE__, :start_link, [Keyword.t()]},
restart: :transient | :permanent | :temporary,
type: :worker
}
def child_spec(opts) do
%{
id: Keyword.get(opts, :name, __MODULE__),
start: {__MODULE__, :start_link, [opts]},
restart: Keyword.get(opts, :restart, :transient),
type: :worker
}
end
@doc """
Close the connection to the broker.
Given the `client_id` of a running connection it will cancel the
inflight messages and send the proper disconnect message to the
broker. The session will get terminated on the server.
"""
@spec disconnect(Tortoise311.client_id()) :: :ok
def disconnect(client_id) do
GenServer.call(via_name(client_id), :disconnect)
end
@doc """
Return the list of subscribed topics.
Given the `client_id` of a running connection return its current
subscriptions. This is helpful in a debugging situation.
"""
@spec subscriptions(Tortoise311.client_id()) :: Tortoise311.Package.Subscribe.t()
def subscriptions(client_id) do
GenServer.call(via_name(client_id), :subscriptions)
end
@doc """
Subscribe to one or more topics using topic filters on `client_id`
The topic filter should be a 2-tuple, `{topic_filter, qos}`, where
the `topic_filter` is a valid MQTT topic filter, and `qos` an
integer value 0 through 2.
Multiple topics can be given as a list.
The subscribe function is asynchronous, so it will return `{:ok,
ref}`. Eventually a response will get delivered to the process
mailbox, tagged with the reference stored in `ref`. It will take the
form of:
{{Tortoise311, ^client_id}, ^ref, ^result}
Where the `result` can be one of `:ok`, or `{:error, reason}`.
Read the documentation for `Tortoise311.Connection.subscribe_sync/3`
for a blocking version of this call.
"""
@spec subscribe(Tortoise311.client_id(), topic | topics, [options]) :: {:ok, reference()}
when topics: [topic],
topic: {Tortoise311.topic_filter(), Tortoise311.qos()},
options:
{:timeout, timeout()}
| {:identifier, Tortoise311.package_identifier()}
def subscribe(client_id, topics, opts \\ [])
def subscribe(client_id, [{_, n} | _] = topics, opts) when is_number(n) do
caller = {_, ref} = {self(), make_ref()}
{identifier, opts} = Keyword.pop_first(opts, :identifier, nil)
subscribe = Enum.into(topics, %Package.Subscribe{identifier: identifier})
GenServer.cast(via_name(client_id), {:subscribe, caller, subscribe, opts})
{:ok, ref}
end
def subscribe(client_id, {_, n} = topic, opts) when is_number(n) do
subscribe(client_id, [topic], opts)
end
def subscribe(client_id, topic, opts) when is_binary(topic) do
case Keyword.pop_first(opts, :qos) do
{nil, _opts} ->
throw("Please specify a quality of service for the subscription")
{qos, opts} when qos in 0..2 ->
subscribe(client_id, [{topic, qos}], opts)
end
end
@doc """
Subscribe to topics and block until the server acknowledges.
This is a synchronous version of the
`Tortoise311.Connection.subscribe/3`. In fact it calls into
`Tortoise311.Connection.subscribe/3` but will handle the selective
receive loop, making it much easier to work with. Also, this
function can be used to block a process that cannot continue before
it has a subscription to the given topics.
See `Tortoise311.Connection.subscribe/3` for configuration options.
"""
@spec subscribe_sync(Tortoise311.client_id(), topic | topics, [options]) ::
:ok | {:error, :timeout}
when topics: [topic],
topic: {Tortoise311.topic_filter(), Tortoise311.qos()},
options:
{:timeout, timeout()}
| {:identifier, Tortoise311.package_identifier()}
def subscribe_sync(client_id, topics, opts \\ [])
def subscribe_sync(client_id, [{_, n} | _] = topics, opts) when is_number(n) do
timeout = Keyword.get(opts, :timeout, 5000)
{:ok, ref} = subscribe(client_id, topics, opts)
receive do
{{Tortoise311, ^client_id}, ^ref, result} -> result
after
timeout ->
{:error, :timeout}
end
end
def subscribe_sync(client_id, {_, n} = topic, opts) when is_number(n) do
subscribe_sync(client_id, [topic], opts)
end
def subscribe_sync(client_id, topic, opts) when is_binary(topic) do
case Keyword.pop_first(opts, :qos) do
{nil, _opts} ->
throw("Please specify a quality of service for the subscription")
{qos, opts} ->
subscribe_sync(client_id, [{topic, qos}], opts)
end
end
@doc """
Unsubscribe from one of more topic filters. The topic filters are
given as strings. Multiple topic filters can be given at once by
passing in a list of strings.
Tortoise311.Connection.unsubscribe(client_id, ["foo/bar", "quux"])
This operation is asynchronous. When the operation is done a message
will be received in mailbox of the originating process.
"""
@spec unsubscribe(Tortoise311.client_id(), topic | topics, [options]) :: {:ok, reference()}
when topics: [topic],
topic: Tortoise311.topic_filter(),
options:
{:timeout, timeout()}
| {:identifier, Tortoise311.package_identifier()}
def unsubscribe(client_id, topics, opts \\ [])
def unsubscribe(client_id, [topic | _] = topics, opts) when is_binary(topic) do
caller = {_, ref} = {self(), make_ref()}
{identifier, opts} = Keyword.pop_first(opts, :identifier, nil)
unsubscribe = %Package.Unsubscribe{identifier: identifier, topics: topics}
GenServer.cast(via_name(client_id), {:unsubscribe, caller, unsubscribe, opts})
{:ok, ref}
end
def unsubscribe(client_id, topic, opts) when is_binary(topic) do
unsubscribe(client_id, [topic], opts)
end
@doc """
Unsubscribe from topics and block until the server acknowledges.
This is a synchronous version of
`Tortoise311.Connection.unsubscribe/3`. It will block until the server
has send the acknowledge message.
See `Tortoise311.Connection.unsubscribe/3` for configuration options.
"""
@spec unsubscribe_sync(Tortoise311.client_id(), topic | topics, [options]) ::
:ok | {:error, :timeout}
when topics: [topic],
topic: Tortoise311.topic_filter(),
options:
{:timeout, timeout()}
| {:identifier, Tortoise311.package_identifier()}
def unsubscribe_sync(client_id, topics, opts \\ [])
def unsubscribe_sync(client_id, topics, opts) when is_list(topics) do
timeout = Keyword.get(opts, :timeout, 5000)
{:ok, ref} = unsubscribe(client_id, topics, opts)
receive do
{{Tortoise311, ^client_id}, ^ref, result} -> result
after
timeout ->
{:error, :timeout}
end
end
def unsubscribe_sync(client_id, topic, opts) when is_binary(topic) do
unsubscribe_sync(client_id, [topic], opts)
end
@doc """
Ping the broker.
When the round-trip is complete a message with the time taken in
milliseconds will be send to the process that invoked the ping
command.
The connection will automatically ping the broker at the interval
specified in the connection configuration, so there is no need to
setup a reoccurring ping. This ping function is exposed for
debugging purposes. If ping latency over time is desired it is
better to listen on `:ping_response` using the `Tortoise311.Events`
PubSub.
"""
@spec ping(Tortoise311.client_id()) :: {:ok, reference()}
defdelegate ping(client_id), to: Tortoise311.Connection.Controller
@doc """
Ping the server and await the ping latency reply.
Takes a `client_id` and an optional `timeout`.
Like `ping/1` but will block the caller process until a response is
received from the server. The response will contain the ping latency
in milliseconds. The `timeout` defaults to `:infinity`, so it is
advisable to specify a reasonable time one is willing to wait for a
response.
"""
@spec ping_sync(Tortoise311.client_id(), timeout()) :: {:ok, reference()} | {:error, :timeout}
defdelegate ping_sync(client_id, timeout \\ :infinity),
to: Tortoise311.Connection.Controller
@doc false
@spec connection(Tortoise311.client_id(), [opts]) ::
{:ok, {module(), term()}} | {:error, :unknown_connection} | {:error, :timeout}
when opts: {:timeout, timeout()} | {:active, boolean()}
def connection(client_id, opts \\ [active: false]) do
# register a connection subscription in the case we are currently
# in the connect phase; this solves a possible race condition
# where the connection is requested while the status is
# connecting, but will reach the receive block after the message
# has been dispatched from the pubsub; previously we registered
# for the connection message in this window.
{:ok, _} = Events.register(client_id, :connection)
case Tortoise311.Registry.meta(via_name(client_id)) do
{:ok, {_transport, _socket} = connection} ->
{:ok, connection}
{:ok, :connecting} ->
timeout = Keyword.get(opts, :timeout, :infinity)
receive do
{{Tortoise311, ^client_id}, :connection, {transport, socket}} ->
{:ok, {transport, socket}}
after
timeout ->
{:error, :timeout}
end
:error ->
{:error, :unknown_connection}
end
after
# if the connection subscription is non-active we should remove it
# from the registry, so the process will not receive connection
# messages when the connection is reestablished.
active? = Keyword.get(opts, :active, false)
unless active?, do: Events.unregister(client_id, :connection)
end
# Callbacks
@impl true
def init(
{transport, %Connect{client_id: client_id} = connect, backoff_opts, subscriptions, opts}
) do
Handler.new(Keyword.fetch!(opts, :handler))
{:ok, %Handler{} = handler} =
Handler.new(Keyword.fetch!(opts, :handler)) |> Handler.execute(:init)
state = %State{
client_id: client_id,
server: transport,
connect: connect,
backoff: Backoff.new(backoff_opts),
subscriptions: subscriptions,
opts: opts,
status: :down,
handler: handler
}
Tortoise311.Registry.put_meta(via_name(client_id), :connecting)
Tortoise311.Events.register(client_id, :status)
# eventually, switch to handle_continue
send(self(), :connect)
{:ok, state}
end
@impl true
def terminate(_reason, state) do
:ok = Tortoise311.Registry.delete_meta(via_name(state.connect.client_id))
:ok = Events.dispatch(state.client_id, :status, :terminated)
:ok
end
@impl true
def handle_info(:connect, state) do
# make sure we will not fall for a keep alive timeout while we reconnect
# check if the will needs to be updated for each connection
state = cancel_keep_alive(state) |> maybe_update_last_will()
with {%Connack{status: :accepted} = connack, socket} <-
do_connect(state.server, state.connect),
{:ok, state} = init_connection(socket, state) do
# we are connected; reset backoff state, etc
state =
%State{state | backoff: Backoff.reset(state.backoff)}
|> update_connection_status(:up)
|> reset_keep_alive()
case connack do
%Connack{session_present: true} ->
{:noreply, state}
%Connack{session_present: false} ->
:ok = Inflight.reset(state.client_id)
unless Enum.empty?(state.subscriptions), do: send(self(), :subscribe)
{:noreply, state}
end
else
%Connack{status: {:refused, reason}} ->
Logger.warn(
"[Tortoise311] Connection refused: #{inspect(reason)}, #{inspect(summarize_state(state))}"
)
{:stop, {:connection_failed, reason}, state}
{:error, reason} ->
Logger.warn(
"[Tortoise311] Connection failed: #{inspect(reason)}, #{inspect(summarize_state(state))}"
)
{timeout, state} = Map.get_and_update(state, :backoff, &Backoff.next/1)
case categorize_error(reason) do
:connectivity ->
Process.send_after(self(), :connect, timeout)
{:noreply, state}
:other ->
{:stop, reason, state}
end
end
end
def handle_info(:subscribe, %State{subscriptions: subscriptions} = state) do
client_id = state.connect.client_id
case Enum.empty?(subscriptions) do
true ->
# nothing to subscribe to, just continue
{:noreply, state}
false ->
# subscribe to the predefined topics
case Inflight.track_sync(client_id, {:outgoing, subscriptions}, 5000) do
{:error, :timeout} ->
{:stop, :subscription_timeout, state}
result ->
case handle_suback_result(result, state) do
{:ok, updated_state} ->
{:noreply, updated_state}
{:error, reasons} ->
error = {:unable_to_subscribe, reasons}
{:stop, error, state}
end
end
end
end
def handle_info(:ping, %State{} = state) do
case Controller.ping_sync(state.connect.client_id, 5000) do
{:ok, round_trip_time} ->
Events.dispatch(state.connect.client_id, :ping_response, round_trip_time)
state = reset_keep_alive(state)
{:noreply, state}
{:error, :timeout} ->
{:stop, :ping_timeout, state}
end
end
# dropping connection
def handle_info({transport, _socket}, state) when transport in [:tcp_closed, :ssl_closed] do
Logger.error("Socket closed before we handed it to the receiver")
# communicate that we are down
:ok = Events.dispatch(state.client_id, :status, :down)
{:noreply, state}
end
# react to connection status change events
def handle_info(
{{Tortoise311, client_id}, :status, status},
%{client_id: client_id, status: current} = state
) do
case status do
^current ->
{:noreply, state}
:up ->
{:noreply, %State{state | status: status}}
:down ->
send(self(), :connect)
{:noreply, %State{state | status: status}}
end
end
@impl true
def handle_call(:subscriptions, _from, state) do
{:reply, state.subscriptions, state}
end
def handle_call(:disconnect, from, state) do
:ok = Events.dispatch(state.client_id, :status, :terminating)
:ok = Inflight.drain(state.client_id)
:ok = Controller.stop(state.client_id)
:ok = GenServer.reply(from, :ok)
{:stop, :shutdown, state}
end
@impl true
def handle_cast({:subscribe, {caller_pid, ref}, subscribe, opts}, state) do
client_id = state.connect.client_id
timeout = Keyword.get(opts, :timeout, 5000)
case Inflight.track_sync(client_id, {:outgoing, subscribe}, timeout) do
{:error, :timeout} = error ->
send(caller_pid, {{Tortoise311, client_id}, ref, error})
{:noreply, state}
result ->
case handle_suback_result(result, state) do
{:ok, updated_state} ->
send(caller_pid, {{Tortoise311, client_id}, ref, :ok})
{:noreply, updated_state}
{:error, reasons} ->
error = {:unable_to_subscribe, reasons}
send(caller_pid, {{Tortoise311, client_id}, ref, {:error, reasons}})
{:stop, error, state}
end
end
end
def handle_cast({:unsubscribe, {caller_pid, ref}, unsubscribe, opts}, state) do
client_id = state.connect.client_id
timeout = Keyword.get(opts, :timeout, 5000)
case Inflight.track_sync(client_id, {:outgoing, unsubscribe}, timeout) do
{:error, :timeout} = error ->
send(caller_pid, {{Tortoise311, client_id}, ref, error})
{:noreply, state}
unsubbed ->
topics = Keyword.drop(state.subscriptions.topics, unsubbed)
subscriptions = %Package.Subscribe{state.subscriptions | topics: topics}
send(caller_pid, {{Tortoise311, client_id}, ref, :ok})
{:noreply, %State{state | subscriptions: subscriptions}}
end
end
# Helpers
defp handle_suback_result(%{:error => []} = results, %State{} = state) do
subscriptions = Enum.into(results[:ok], state.subscriptions)
{:ok, %State{state | subscriptions: subscriptions}}
end
defp handle_suback_result(%{:error => errors}, %State{}) do
{:error, errors}
end
defp reset_keep_alive(%State{keep_alive: nil} = state) do
ref = Process.send_after(self(), :ping, state.connect.keep_alive * 1000)
%State{state | keep_alive: ref}
end
defp reset_keep_alive(%State{keep_alive: previous_ref} = state) do
# Cancel the previous timer, just in case one was already set
_ = Process.cancel_timer(previous_ref)
ref = Process.send_after(self(), :ping, state.connect.keep_alive * 1000)
%State{state | keep_alive: ref}
end
defp cancel_keep_alive(%State{keep_alive: nil} = state) do
state
end
defp cancel_keep_alive(%State{keep_alive: keep_alive_ref} = state) do
_ = Process.cancel_timer(keep_alive_ref)
%State{state | keep_alive: nil}
end
defp maybe_update_last_will(%State{connect: connect, handler: handler} = state) do
if function_exported?(handler.module, :last_will, 1) do
{{:ok, last_will}, _updated_handler} = Handler.execute(handler, :last_will)
if last_will == nil do
state
else
updated_connect = %Connect{connect | will: last_will}
%State{state | connect: updated_connect}
end
else
state
end
end
# dispatch connection status if the connection status change
defp update_connection_status(%State{status: same} = state, same) do
state
end
defp update_connection_status(%State{} = state, status) do
:ok = Events.dispatch(state.connect.client_id, :status, status)
%State{state | status: status}
end
defp do_connect(server, %Connect{} = connect) do
%Transport{type: transport, host: host, port: port, opts: opts} = server
with {:ok, socket} <- transport.connect(host, port, opts, 10000),
:ok = transport.send(socket, Package.encode(connect)),
{:ok, packet} <- transport.recv(socket, 4, 5000) do
try do
case Package.decode(packet) do
%Connack{status: :accepted} = connack ->
{connack, socket}
%Connack{status: {:refused, _reason}} = connack ->
connack
end
catch
:error, {:badmatch, _unexpected} ->
violation = %{expected: Connect, got: packet}
{:error, {:protocol_violation, violation}}
end
else
{:error, :econnrefused} ->
{:error, {:connection_refused, host, port}}
{:error, :nxdomain} ->
{:error, {:nxdomain, host, port}}
{:error, {:options, {:cacertfile, []}}} ->
{:error, :no_cacertfile_specified}
{:error, :closed} ->
{:error, :server_closed_connection}
{:error, :timeout} ->
{:error, :connection_timeout}
{:error, other} ->
{:error, other}
end
end
defp init_connection(socket, %State{opts: opts, server: transport, connect: connect} = state) do
connection = {transport.type, socket}
:ok = start_connection_supervisor(opts)
:ok = Receiver.handle_socket(connect.client_id, connection)
:ok = Tortoise311.Registry.put_meta(via_name(connect.client_id), connection)
:ok = Events.dispatch(connect.client_id, :connection, connection)
# set clean session to false for future reconnect attempts
connect = %Connect{connect | clean_session: false}
{:ok, %State{state | connect: connect}}
end
defp start_connection_supervisor(opts) do
case Connection.Supervisor.start_link(opts) do
{:ok, _pid} ->
:ok
{:error, {:already_started, _pid}} ->
:ok
end
end
defp categorize_error({:nxdomain, _host, _port}) do
:connectivity
end
defp categorize_error({:connection_refused, _host, _port}) do
:connectivity
end
defp categorize_error(:server_closed_connection) do
:connectivity
end
defp categorize_error(:connection_timeout) do
:connectivity
end
defp categorize_error(:enetunreach) do
:connectivity
end
defp categorize_error(_other) do
:other
end
defp summarize_state(state) do
%{
client_id: state.client_id,
protocol: state.connect.protocol,
protocol_version: state.connect.protocol_version,
keep_alive: state.connect.keep_alive,
clean_session: state.connect.clean_session,
host: state.server.host,
port: state.server.port,
transport: state.server.type,
status: state.status,
subscriptions: state.subscriptions
}
end
end
| 32.917241 | 100 | 0.649445 |
e834628737617c8f82e3d068c6c808bc11351735 | 3,557 | ex | Elixir | lib/network/simple.ex | BradLyman/nergle | 7de7a8ea73b3f5aa038409d0eb0c29cbd06a8876 | [
"MIT"
] | null | null | null | lib/network/simple.ex | BradLyman/nergle | 7de7a8ea73b3f5aa038409d0eb0c29cbd06a8876 | [
"MIT"
] | null | null | null | lib/network/simple.ex | BradLyman/nergle | 7de7a8ea73b3f5aa038409d0eb0c29cbd06a8876 | [
"MIT"
] | null | null | null | require Logger
alias Network.Simple, as: Net
defmodule Network.Simple.Cortex do
use GenServer
@moduledoc """
The Cortex is the controller for the network.
It is responsible for synchronizing signals from sensors and waiting for
responses from actuators.
This Cortex implementation does not wait for actuator responses.
"""
@doc """
Start a Cortex instance.
"""
def start_link do
GenServer.start_link(__MODULE__, {})
end
@doc """
The Cortex will sync the sensors which triggers the network to begin
processing the sensor output.
## Examples
iex> {:ok, cortex} = Network.Simple.Cortex.start_link
iex> Network.Simple.Cortex.sense_think_act cortex
"""
def sense_think_act(cortex) do
GenServer.call(cortex, :sense_think_act)
end
# Callbacks
@impl true
def init(_) do
{:ok, actuator} = Net.Actuator.start_link()
{:ok, neuron} = Net.Neuron.start_link(actuator)
{:ok, sensor} = Net.Sensor.start_link(neuron)
{:ok, %{sensor: sensor, neuron: neuron, actuator: actuator}}
end
@impl true
def handle_call(:sense_think_act, _from, state) do
{:reply, Net.Sensor.sync(state.sensor), state}
end
end
defmodule Network.Simple.Sensor do
use GenServer
@moduledoc """
The Sensor is responsible for creating a vector input based on some state in
the environment.
This Sensor just generates a random vector each time it is sync'd.
"""
@doc """
Create a Sensor instance which signals the provided neuron.
"""
def start_link(neuron) do
GenServer.start_link(
__MODULE__,
neuron
)
end
@doc """
Trigger the sensor to send environmental information to the configured
neuron.
"""
def sync(sensor) do
GenServer.call(sensor, :sync)
end
# Callbacks
@impl true
def init(neuron) do
{:ok, neuron}
end
@impl true
def handle_call(:sync, _from, neuron) do
environment = [:rand.uniform(), :rand.uniform()]
{:reply, Net.Neuron.sense(neuron, environment), neuron}
end
end
defmodule Network.Simple.Actuator do
use GenServer
@moduledoc """
The Actuator is responsible for using a signal input to act upon the
environment.
"""
@doc """
Create an Actuator instance.
"""
def start_link do
GenServer.start_link(
__MODULE__,
{}
)
end
@doc """
Send a signal to the actuator.
"""
def sense(actuator, signal) do
GenServer.call(actuator, {:forward, signal})
end
# Callbacks
@impl true
def init(args) do
{:ok, args}
end
@impl true
def handle_call({:forward, output}, _from, state) do
{:reply, output, state}
end
end
defmodule Network.Simple.Neuron do
use GenServer
@moduledoc """
The neuron is responsible for the actual 'thinking' in the neural network.
"""
defmodule State do
@enforce_keys [:actuator, :weights]
defstruct [:actuator, :weights]
def create(actuator, size) do
weights = for _ <- 0..size, do: :rand.uniform()
%State{weights: weights, actuator: actuator}
end
end
def start_link(actuator) do
GenServer.start_link(
__MODULE__,
State.create(actuator, 2)
)
end
def sense(neuron, signal) when is_list(signal) do
GenServer.call(neuron, {:sense, signal})
end
# Callbacks
@impl true
def init(args) do
{:ok, args}
end
@impl true
def handle_call({:sense, signal}, _from, state) do
value =
Linalg.dot(signal ++ [1.0], state.weights)
|> :math.tanh()
{:reply, Net.Actuator.sense(state.actuator, value), state}
end
end
| 20.325714 | 78 | 0.669947 |
e83492e2bd238b11c92dae8f995165342093b78b | 8,474 | exs | Elixir | test/statham_logger_test.exs | prosapient/statham_logger | 0d58b333e714891676aed9b5a76dd535d4d2d074 | [
"Apache-2.0"
] | 2 | 2021-06-25T17:35:12.000Z | 2021-07-14T15:05:30.000Z | test/statham_logger_test.exs | prosapient/statham_logger | 0d58b333e714891676aed9b5a76dd535d4d2d074 | [
"Apache-2.0"
] | null | null | null | test/statham_logger_test.exs | prosapient/statham_logger | 0d58b333e714891676aed9b5a76dd535d4d2d074 | [
"Apache-2.0"
] | null | null | null | defmodule StathamLoggerTest do
use StathamLogger.LoggerCase, async: false
import ExUnit.CaptureIO
require Logger
defmodule IDStruct, do: defstruct(id: nil)
setup do
Logger.remove_backend(:console)
Logger.add_backend(StathamLogger)
:ok =
Logger.configure_backend(
StathamLogger,
device: :user,
level: nil,
metadata: []
)
:ok = Logger.reset_metadata([])
end
describe "@derive StathamLogger.Loggable" do
test "allows Structs to override sanitize options" do
Logger.configure_backend(StathamLogger,
metadata: :all,
sanitize_options: [
filter_keys: {:discard, [:password]},
max_string_size: 4
]
)
Logger.metadata(
user: %StathamLogger.LoggableStructWithDiscard{
name: "Long Name",
password: "123",
phone_number: "123"
}
)
log =
fn -> Logger.debug("") end
|> capture_log()
|> Jason.decode!()
assert %{
"user" => %{
"name" => "Long...",
"password" => "123",
"phone_number" => "[FILTERED]"
}
} = log
Logger.metadata(
user: %StathamLogger.LoggableStructWithKeep{
name: "Long Name",
password: "123",
phone_number: "123"
}
)
log =
fn -> Logger.debug("") end
|> capture_log()
|> Jason.decode!()
assert %{
"user" => %{
"name" => "Long...",
"password" => "[FILTERED]",
"phone_number" => "123"
}
} = log
end
end
test "logs empty binary messages" do
Logger.configure_backend(StathamLogger, metadata: :all)
log =
fn -> Logger.debug("") end
|> capture_log()
|> Jason.decode!()
assert %{"message" => ""} = log
end
test "logs binary messages" do
Logger.configure_backend(StathamLogger, metadata: :all)
log =
fn -> Logger.debug("hello") end
|> capture_log()
|> Jason.decode!()
assert %{"message" => "hello"} = log
end
test "logs empty iodata messages" do
Logger.configure_backend(StathamLogger, metadata: :all)
log =
fn -> Logger.debug([]) end
|> capture_log()
|> Jason.decode!()
assert %{"message" => ""} = log
end
test "logs iodata messages" do
Logger.configure_backend(StathamLogger, metadata: :all)
log =
fn -> Logger.debug([?h, ?e, ?l, ?l, ?o]) end
|> capture_log()
|> Jason.decode!()
assert %{"message" => "hello"} = log
end
test "logs chardata messages" do
Logger.configure_backend(StathamLogger, metadata: :all)
log =
fn -> Logger.debug([?π, ?α, ?β]) end
|> capture_log()
|> Jason.decode!()
assert %{"message" => "παβ"} = log
end
test "log message does not break escaping" do
Logger.configure_backend(StathamLogger, metadata: :all)
log =
fn -> Logger.debug([?", ?h]) end
|> capture_log()
|> Jason.decode!()
assert %{"message" => "\"h"} = log
log =
fn -> Logger.debug("\"h") end
|> capture_log()
|> Jason.decode!()
assert %{"message" => "\"h"} = log
end
test "does not start when there is no user" do
:ok = Logger.remove_backend(StathamLogger)
user = Process.whereis(:user)
try do
Process.unregister(:user)
assert {:error, :ignore} == :gen_event.add_handler(Logger, StathamLogger, StathamLogger)
after
Process.register(user, :user)
end
after
{:ok, _} = Logger.add_backend(StathamLogger)
end
test "may use another device" do
Logger.configure_backend(StathamLogger, device: :standard_error)
assert capture_io(:standard_error, fn ->
Logger.debug("hello")
Logger.flush()
end) =~ "hello"
end
describe "metadata" do
test "can be configured" do
Logger.configure_backend(StathamLogger, metadata: [:user_id])
assert capture_log(fn ->
Logger.debug("hello")
end) =~ "hello"
Logger.metadata(user_id: 13)
log =
fn -> Logger.debug("hello") end
|> capture_log()
|> Jason.decode!()
assert %{"user_id" => 13} = log
end
test "can be configured to :all" do
Logger.configure_backend(StathamLogger, metadata: :all)
Logger.metadata(user_id: 11)
Logger.metadata(dynamic_metadata: 5)
log =
fn -> Logger.debug("hello") end
|> capture_log()
|> Jason.decode!()
assert %{"user_id" => 11} = log
assert %{"dynamic_metadata" => 5} = log
end
test "can be empty" do
Logger.configure_backend(StathamLogger, metadata: [])
log =
fn -> Logger.debug("hello") end
|> capture_log()
|> Jason.decode!()
assert %{"message" => "hello"} = log
end
test "skip some otp metadata fields" do
Logger.configure_backend(StathamLogger, metadata: :all)
debug_fn = fn -> Logger.debug("hello") end
log =
debug_fn
|> capture_log()
|> Jason.decode!()
refute log["time"]
refute log["domain"]
refute log["erl_level"]
refute log["gl"]
assert log["file"]
assert log["function"]
assert log["mfa"]
assert log["module"]
assert log["pid"]
end
test "converts Struct metadata to maps" do
Logger.configure_backend(StathamLogger, metadata: :all)
Logger.metadata(id_struct: %IDStruct{id: "test"})
debug_fn = fn -> Logger.debug("hello") end
log =
debug_fn
|> capture_log()
|> Jason.decode!()
assert %{"id_struct" => %{"id" => "test"}} = log
end
end
test "contains source location" do
%{module: mod, function: {name, arity}, file: _file, line: _line} = __ENV__
log =
fn -> Logger.debug("hello") end
|> capture_log()
|> Jason.decode!()
function = "Elixir.#{inspect(mod)}.#{name}/#{arity}"
assert %{
"logger" => %{
"method_name" => ^function
}
} = log
end
test "may configure level" do
Logger.configure_backend(StathamLogger, level: :info)
assert capture_log(fn ->
Logger.debug("hello")
end) == ""
end
test "logs severity" do
log =
fn -> Logger.debug("hello") end
|> capture_log()
|> Jason.decode!()
assert %{"syslog" => %{"severity" => "debug"}} = log
log =
fn -> Logger.warn("hello") end
|> capture_log()
|> Jason.decode!()
assert %{"syslog" => %{"severity" => "warn"}} = log
end
test "logs crash reason when present" do
Logger.configure_backend(StathamLogger, metadata: [:crash_reason])
Logger.metadata(crash_reason: {%RuntimeError{message: "oops"}, []})
log =
capture_log(fn -> Logger.debug("hello") end)
|> Jason.decode!()
assert is_nil(log["error"]["initial_call"])
assert log["error"]["reason"] == "** (RuntimeError) oops"
end
test "logs erlang style crash reasons" do
Logger.configure_backend(StathamLogger, metadata: [:crash_reason])
Logger.metadata(crash_reason: {:socket_closed_unexpectedly, []})
log =
capture_log(fn -> Logger.debug("hello") end)
|> Jason.decode!()
assert is_nil(log["error"]["initial_call"])
assert log["error"]["reason"] == "{:socket_closed_unexpectedly, []}"
end
test "logs initial call when present" do
Logger.configure_backend(StathamLogger, metadata: [:initial_call])
Logger.metadata(crash_reason: {%RuntimeError{message: "oops"}, []}, initial_call: {Foo, :bar, 3})
log =
capture_log(fn -> Logger.debug("hello") end)
|> Jason.decode!()
assert log["error"]["initial_call"] == "Elixir.Foo.bar/3"
end
test "hides sensitive data" do
Logger.configure_backend(StathamLogger,
metadata: :all,
sanitize_options: [filter_keys: {:discard, [:password]}]
)
Logger.metadata(
request: %{
password: "secret",
name: "not a secret"
}
)
log =
fn -> Logger.debug("hello") end
|> capture_log()
|> Jason.decode!()
assert %{
"request" => %{
"name" => "not a secret",
"password" => "[FILTERED]"
}
} = log
end
end
| 23.736695 | 101 | 0.554992 |
e83498a021da0f500762c97ef999de3e6e0e79b2 | 640 | exs | Elixir | test/user_model_test.exs | elixir-extracts/passport | 2031d7b874e74746eea14ce1a83911be84ce8c2b | [
"Apache-2.0"
] | 1 | 2016-04-28T18:32:10.000Z | 2016-04-28T18:32:10.000Z | test/user_model_test.exs | elixir-extracts/passport | 2031d7b874e74746eea14ce1a83911be84ce8c2b | [
"Apache-2.0"
] | null | null | null | test/user_model_test.exs | elixir-extracts/passport | 2031d7b874e74746eea14ce1a83911be84ce8c2b | [
"Apache-2.0"
] | null | null | null | defmodule Models.UserTest do
use ExUnit.Case, async: false
alias Pass.Test.User
@valid_attrs %{email: "email", username: "uname", password: "some content", emailConfirmed: true, passwordResetToken: "pw token"}
@invalid_attrs %{}
setup tags do
unless tags[:async] do
Ecto.Adapters.SQL.restart_test_transaction(Pass.Test.Repo, [])
end
end
test "changeset with valid attributes" do
changeset = User.changeset(%User{}, @valid_attrs)
assert changeset.valid?
end
test "changeset with invalid attributes" do
changeset = User.changeset(%User{}, @invalid_attrs)
refute changeset.valid?
end
end
| 25.6 | 131 | 0.709375 |
e834d37b803f3ff21ea5f10e38d458f64c75eafc | 1,496 | exs | Elixir | mix.exs | hellogustav/elixir_email_reply_parser | e0cad1831cfaf1eb8db41fd8965eea2dd6e03c7d | [
"MIT"
] | 7 | 2017-04-15T13:49:45.000Z | 2022-02-15T08:06:33.000Z | mix.exs | hellogustav/elixir_email_reply_parser | e0cad1831cfaf1eb8db41fd8965eea2dd6e03c7d | [
"MIT"
] | 12 | 2017-03-28T16:56:23.000Z | 2019-10-16T13:41:12.000Z | mix.exs | hellogustav/elixir_email_reply_parser | e0cad1831cfaf1eb8db41fd8965eea2dd6e03c7d | [
"MIT"
] | 2 | 2017-11-11T19:14:29.000Z | 2020-10-19T17:41:44.000Z | defmodule ElixirEmailReplyParser.Mixfile do
use Mix.Project
def project do
[app: :elixir_email_reply_parser,
version: "0.1.2",
description: description(),
elixir: "~> 1.3",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
package: package(),
deps: deps(),
# Docs
name: "Elixir Email Reply Parser",
source_url: "https://github.com/hellogustav/elixir_email_reply_parser",
docs: [main: "readme",
extras: ["README.md", "LICENSE.md"]]]
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
"""
Email reply parser for retrieval of the last reply from email message.
Originally an Elixir port of https://github.com/github/email_reply_parser
as well as its port https://github.com/zapier/email-reply-parser
enhanced by e.g. an ability to handle emails with German.
"""
end
defp package do
[name: :elixir_email_reply_parser,
maintainers: ["elixir.email.reply.parser@gmail.com"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/hellogustav/elixir_email_reply_parser"}]
end
defp deps do
[
{:dialyxir, "~> 0.5", only: :dev, runtime: false},
{:earmark, "~> 1.2.0", only: :dev},
{:ex_doc, "~> 0.15", only: :dev}
]
end
end
| 28.226415 | 85 | 0.647727 |
e835047cdf10d75f97fbaccd80f125194d25e92b | 959 | exs | Elixir | demos/brella_demo_umbrella/config/prod.secret.exs | axelson/priv_check | ba4228881edbf16ac61b0e006537de517c7f6f06 | [
"MIT"
] | 8 | 2020-03-15T19:22:02.000Z | 2021-09-28T11:00:18.000Z | demos/brella_demo_umbrella/config/prod.secret.exs | axelson/priv_check | ba4228881edbf16ac61b0e006537de517c7f6f06 | [
"MIT"
] | 7 | 2020-03-11T06:21:57.000Z | 2020-11-15T19:48:54.000Z | demos/brella_demo_umbrella/config/prod.secret.exs | axelson/priv_check | ba4228881edbf16ac61b0e006537de517c7f6f06 | [
"MIT"
] | null | null | null | # In this file, we load production configuration and secrets
# from environment variables. You can also hardcode secrets,
# although such is generally not recommended and you have to
# remember to add this file to your .gitignore.
use Mix.Config
secret_key_base =
System.get_env("SECRET_KEY_BASE") ||
raise """
environment variable SECRET_KEY_BASE is missing.
You can generate one by calling: mix phx.gen.secret
"""
config :brella_demo_web, BrellaDemoWeb.Endpoint,
http: [
port: String.to_integer(System.get_env("PORT") || "4000"),
transport_options: [socket_opts: [:inet6]]
],
secret_key_base: secret_key_base
# ## Using releases (Elixir v1.9+)
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start each relevant endpoint:
#
# config :brella_demo_web, BrellaDemoWeb.Endpoint, server: true
#
# Then you can assemble a release by calling `mix release`.
# See `mix help release` for more information.
| 31.966667 | 67 | 0.736184 |
e83528efce04d7f25f051904d851beef506f79c3 | 45 | exs | Elixir | test/trash_test.exs | newaperio/trash | ad7f82dab736c8b4e926888f8f09fce078b289ac | [
"MIT"
] | 1 | 2022-03-18T15:26:07.000Z | 2022-03-18T15:26:07.000Z | test/trash_test.exs | newaperio/trash | ad7f82dab736c8b4e926888f8f09fce078b289ac | [
"MIT"
] | null | null | null | test/trash_test.exs | newaperio/trash | ad7f82dab736c8b4e926888f8f09fce078b289ac | [
"MIT"
] | null | null | null | defmodule TrashTest do
use ExUnit.Case
end
| 11.25 | 22 | 0.8 |
e8353c0009a0db43e90f288ae85025cb0e956ba8 | 1,106 | ex | Elixir | lib/elasticlunr/storage.ex | merchant-ly/ex_elasticlunr | b7d12f3e567f1ecad1bfb402a062edd4d58ef9fd | [
"MIT"
] | 129 | 2021-11-15T23:22:06.000Z | 2022-03-20T03:03:27.000Z | lib/elasticlunr/storage.ex | merchant-ly/ex_elasticlunr | b7d12f3e567f1ecad1bfb402a062edd4d58ef9fd | [
"MIT"
] | 9 | 2021-11-06T16:22:30.000Z | 2022-03-28T11:58:08.000Z | lib/elasticlunr/storage.ex | merchant-ly/ex_elasticlunr | b7d12f3e567f1ecad1bfb402a062edd4d58ef9fd | [
"MIT"
] | 5 | 2022-01-05T16:44:21.000Z | 2022-03-24T11:55:49.000Z | defmodule Elasticlunr.Storage do
@moduledoc """
This is the storage interface that's used by the index manager.
```elixir
config :elasticlunr,
storage: Elasticlunr.Storage.Blackhole # this is the default provider
```
"""
alias Elasticlunr.Index
alias Elasticlunr.Storage.Blackhole
@spec all() :: Enum.t()
def all do
provider().load_all()
end
@spec write(Index.t()) :: :ok | {:error, any()}
def write(%Index{} = index) do
provider().write(index)
end
@spec read(binary()) :: Index.t() | {:error, any()}
def read(index_name) do
provider().read(index_name)
end
@spec delete(binary()) :: :ok | {:error, any()}
def delete(index_name) do
provider().delete(index_name)
end
defp provider, do: Application.get_env(:elasticlunr, :storage, Blackhole)
defmacro __using__(_) do
quote location: :keep do
@behaviour Elasticlunr.Storage.Provider
defp config(key, default \\ nil) do
Keyword.get(config_all(), key, default)
end
defp config_all, do: Application.get_env(:elasticlunr, __MODULE__, [])
end
end
end
| 24.043478 | 76 | 0.659132 |
e8353e13e2feaf00e325a4310cd428c3a7e1dc71 | 3,212 | ex | Elixir | lib/codes/codes_r46.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_r46.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_r46.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_R46 do
alias IcdCode.ICDCode
def _R460 do
%ICDCode{full_code: "R460",
category_code: "R46",
short_code: "0",
full_name: "Very low level of personal hygiene",
short_name: "Very low level of personal hygiene",
category_name: "Very low level of personal hygiene"
}
end
def _R461 do
%ICDCode{full_code: "R461",
category_code: "R46",
short_code: "1",
full_name: "Bizarre personal appearance",
short_name: "Bizarre personal appearance",
category_name: "Bizarre personal appearance"
}
end
def _R462 do
%ICDCode{full_code: "R462",
category_code: "R46",
short_code: "2",
full_name: "Strange and inexplicable behavior",
short_name: "Strange and inexplicable behavior",
category_name: "Strange and inexplicable behavior"
}
end
def _R463 do
%ICDCode{full_code: "R463",
category_code: "R46",
short_code: "3",
full_name: "Overactivity",
short_name: "Overactivity",
category_name: "Overactivity"
}
end
def _R464 do
%ICDCode{full_code: "R464",
category_code: "R46",
short_code: "4",
full_name: "Slowness and poor responsiveness",
short_name: "Slowness and poor responsiveness",
category_name: "Slowness and poor responsiveness"
}
end
def _R465 do
%ICDCode{full_code: "R465",
category_code: "R46",
short_code: "5",
full_name: "Suspiciousness and marked evasiveness",
short_name: "Suspiciousness and marked evasiveness",
category_name: "Suspiciousness and marked evasiveness"
}
end
def _R466 do
%ICDCode{full_code: "R466",
category_code: "R46",
short_code: "6",
full_name: "Undue concern and preoccupation with stressful events",
short_name: "Undue concern and preoccupation with stressful events",
category_name: "Undue concern and preoccupation with stressful events"
}
end
def _R467 do
%ICDCode{full_code: "R467",
category_code: "R46",
short_code: "7",
full_name: "Verbosity and circumstantial detail obscuring reason for contact",
short_name: "Verbosity and circumstantial detail obscuring reason for contact",
category_name: "Verbosity and circumstantial detail obscuring reason for contact"
}
end
def _R4681 do
%ICDCode{full_code: "R4681",
category_code: "R46",
short_code: "81",
full_name: "Obsessive-compulsive behavior",
short_name: "Obsessive-compulsive behavior",
category_name: "Obsessive-compulsive behavior"
}
end
def _R4689 do
%ICDCode{full_code: "R4689",
category_code: "R46",
short_code: "89",
full_name: "Other symptoms and signs involving appearance and behavior",
short_name: "Other symptoms and signs involving appearance and behavior",
category_name: "Other symptoms and signs involving appearance and behavior"
}
end
end
| 33.113402 | 91 | 0.624222 |
e83575ed9639262c8a5cc51b72e971414ec724e8 | 2,050 | ex | Elixir | clients/artifact_registry/lib/google_api/artifact_registry/v1/model/import_yum_artifacts_response.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/artifact_registry/lib/google_api/artifact_registry/v1/model/import_yum_artifacts_response.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | clients/artifact_registry/lib/google_api/artifact_registry/v1/model/import_yum_artifacts_response.ex | yoshi-code-bot/elixir-google-api | cdb6032f01fac5ab704803113c39f2207e9e019d | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.ArtifactRegistry.V1.Model.ImportYumArtifactsResponse do
@moduledoc """
The response message from importing YUM artifacts.
## Attributes
* `errors` (*type:* `list(GoogleApi.ArtifactRegistry.V1.Model.ImportYumArtifactsErrorInfo.t)`, *default:* `nil`) - Detailed error info for packages that were not imported.
* `yumArtifacts` (*type:* `list(GoogleApi.ArtifactRegistry.V1.Model.YumArtifact.t)`, *default:* `nil`) - The yum artifacts imported.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:errors =>
list(GoogleApi.ArtifactRegistry.V1.Model.ImportYumArtifactsErrorInfo.t()) | nil,
:yumArtifacts => list(GoogleApi.ArtifactRegistry.V1.Model.YumArtifact.t()) | nil
}
field(:errors, as: GoogleApi.ArtifactRegistry.V1.Model.ImportYumArtifactsErrorInfo, type: :list)
field(:yumArtifacts, as: GoogleApi.ArtifactRegistry.V1.Model.YumArtifact, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.ArtifactRegistry.V1.Model.ImportYumArtifactsResponse do
def decode(value, options) do
GoogleApi.ArtifactRegistry.V1.Model.ImportYumArtifactsResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ArtifactRegistry.V1.Model.ImportYumArtifactsResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.196078 | 175 | 0.754634 |
e835a5b8ec6d902d1f6f03173b6a04b9ae7cbada | 1,389 | exs | Elixir | test/arrow_web/controllers/auth_controller_test.exs | mbta/arrow | abbac9c7f300790d452ecec027a6c609775b72d1 | [
"MIT"
] | null | null | null | test/arrow_web/controllers/auth_controller_test.exs | mbta/arrow | abbac9c7f300790d452ecec027a6c609775b72d1 | [
"MIT"
] | 775 | 2019-11-18T16:23:57.000Z | 2022-03-28T18:20:04.000Z | test/arrow_web/controllers/auth_controller_test.exs | mbta/arrow | abbac9c7f300790d452ecec027a6c609775b72d1 | [
"MIT"
] | 1 | 2019-12-23T13:52:25.000Z | 2019-12-23T13:52:25.000Z | defmodule ArrowWeb.Controllers.AuthControllerTest do
use ArrowWeb.ConnCase
describe "callback" do
test "redirects on success and saves refresh token", %{conn: conn} do
current_time = System.system_time(:second)
auth = %Ueberauth.Auth{
uid: "foo@mbta.com",
credentials: %Ueberauth.Auth.Credentials{
expires_at: current_time + 1_000,
other: %{groups: ["test1"]}
}
}
conn =
conn
|> assign(:ueberauth_auth, auth)
|> get(Routes.auth_path(conn, :callback, "cognito"))
response = html_response(conn, 302)
assert response =~ Routes.disruption_path(conn, :index)
assert Guardian.Plug.current_claims(conn)["groups"] == ["test1"]
assert get_session(conn, :arrow_username) == "foo@mbta.com"
end
test "handles generic failure", %{conn: conn} do
conn =
conn
|> assign(:ueberauth_failure, %Ueberauth.Failure{})
|> get(Routes.auth_path(conn, :callback, "cognito"))
response = response(conn, 401)
assert response =~ "unauthenticated"
end
end
describe "request" do
test "redirects to auth callback", %{conn: conn} do
conn = get(conn, Routes.auth_path(conn, :request, "cognito"))
response = response(conn, 302)
assert response =~ Routes.auth_path(conn, :callback, "cognito")
end
end
end
| 27.78 | 73 | 0.62707 |
e835c866816b340382188aa10cbbd88a6a59b3c8 | 1,482 | ex | Elixir | lib/tesla/middleware/follow_redirects.ex | brittlewis12/tesla | 6f0969733142fb59fbce16af6c13352a928b4783 | [
"MIT"
] | null | null | null | lib/tesla/middleware/follow_redirects.ex | brittlewis12/tesla | 6f0969733142fb59fbce16af6c13352a928b4783 | [
"MIT"
] | null | null | null | lib/tesla/middleware/follow_redirects.ex | brittlewis12/tesla | 6f0969733142fb59fbce16af6c13352a928b4783 | [
"MIT"
] | null | null | null | defmodule Tesla.Middleware.FollowRedirects do
@behaviour Tesla.Middleware
@moduledoc """
Follow 3xx redirects
### Example
```
defmodule MyClient do
use Tesla
plug Tesla.Middleware.FollowRedirects, max_redirects: 3 # defaults to 5
end
```
### Options
- `:max_redirects` - limit number of redirects (default: `5`)
"""
@max_redirects 5
@redirect_statuses [301, 302, 307, 308]
def call(env, next, opts \\ []) do
max = Keyword.get(opts || [], :max_redirects, @max_redirects)
redirect(env, next, max)
end
defp redirect(env, next, left) when left == 0 do
case Tesla.run(env, next) do
{:ok, %{status: status} = env} when not (status in @redirect_statuses) ->
{:ok, env}
{:ok, _env} ->
{:error, {__MODULE__, :too_many_redirects}}
error ->
error
end
end
defp redirect(env, next, left) do
case Tesla.run(env, next) do
{:ok, %{status: status} = env} when status in @redirect_statuses ->
case Tesla.get_header(env, "location") do
nil ->
{:ok, env}
location ->
location = parse_location(location, env)
redirect(%{env | url: location}, next, left - 1)
end
other ->
other
end
end
defp parse_location("/" <> _rest = location, env) do
env.url
|> URI.parse()
|> URI.merge(location)
|> URI.to_string()
end
defp parse_location(location, _env), do: location
end
| 21.478261 | 79 | 0.591093 |
e835d63fc6630ab61d6be5330fce544576ff2f76 | 20,984 | ex | Elixir | clients/compute/lib/google_api/compute/v1/api/interconnects.ex | kaaboaye/elixir-google-api | 1896784c4342151fd25becd089a5beb323eff567 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/interconnects.ex | kaaboaye/elixir-google-api | 1896784c4342151fd25becd089a5beb323eff567 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/interconnects.ex | kaaboaye/elixir-google-api | 1896784c4342151fd25becd089a5beb323eff567 | [
"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.Compute.V1.Api.Interconnects do
@moduledoc """
API calls for all endpoints tagged `Interconnects`.
"""
alias GoogleApi.Compute.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Deletes the specified interconnect.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `interconnect` (*type:* `String.t`) - Name of the interconnect to delete.
* `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.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_interconnects_delete(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def compute_interconnects_delete(
connection,
project,
interconnect,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/{project}/global/interconnects/{interconnect}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"interconnect" => URI.encode(interconnect, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Returns the specified interconnect. Get a list of available interconnects by making a list() request.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `interconnect` (*type:* `String.t`) - Name of the interconnect to return.
* `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.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Interconnect{}}` on success
* `{:error, info}` on failure
"""
@spec compute_interconnects_get(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Interconnect.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def compute_interconnects_get(
connection,
project,
interconnect,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/global/interconnects/{interconnect}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"interconnect" => URI.encode(interconnect, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Interconnect{}])
end
@doc """
Returns the interconnectDiagnostics for the specified interconnect.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `interconnect` (*type:* `String.t`) - Name of the interconnect resource to query.
* `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.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.InterconnectsGetDiagnosticsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec compute_interconnects_get_diagnostics(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.InterconnectsGetDiagnosticsResponse.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def compute_interconnects_get_diagnostics(
connection,
project,
interconnect,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/global/interconnects/{interconnect}/getDiagnostics", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"interconnect" => URI.encode(interconnect, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Compute.V1.Model.InterconnectsGetDiagnosticsResponse{}]
)
end
@doc """
Creates a Interconnect in the specified project using the data included in the request.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `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.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `:body` (*type:* `GoogleApi.Compute.V1.Model.Interconnect.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_interconnects_insert(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def compute_interconnects_insert(connection, project, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{project}/global/interconnects", %{
"project" => URI.encode(project, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Retrieves the list of interconnect available to the specified project.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `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.
* `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <.
For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance.
You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true).
* `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
* `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
Currently, only sorting by name or creationTimestamp desc is supported.
* `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.InterconnectList{}}` on success
* `{:error, info}` on failure
"""
@spec compute_interconnects_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.InterconnectList.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def compute_interconnects_list(connection, project, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/global/interconnects", %{
"project" => URI.encode(project, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.InterconnectList{}])
end
@doc """
Updates the specified interconnect with the data included in the request. This method supports PATCH semantics and uses the JSON merge patch format and processing rules.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `interconnect` (*type:* `String.t`) - Name of the interconnect to update.
* `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.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `:body` (*type:* `GoogleApi.Compute.V1.Model.Interconnect.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_interconnects_patch(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()}
| {:ok, Tesla.Env.t()}
| {:error, Tesla.Env.t()}
def compute_interconnects_patch(
connection,
project,
interconnect,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/{project}/global/interconnects/{interconnect}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"interconnect" => URI.encode(interconnect, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
end
| 48.574074 | 414 | 0.650448 |
e835e66bf8b1d237bb7e356534c7b369d7f03dff | 12,445 | ex | Elixir | data/web/deps/ecto/lib/ecto/changeset/relation.ex | lydiadwyer/trains_elixir | 16da18d4582307f4967b6cce7320e9aa08a849c3 | [
"Apache-2.0"
] | null | null | null | data/web/deps/ecto/lib/ecto/changeset/relation.ex | lydiadwyer/trains_elixir | 16da18d4582307f4967b6cce7320e9aa08a849c3 | [
"Apache-2.0"
] | null | null | null | data/web/deps/ecto/lib/ecto/changeset/relation.ex | lydiadwyer/trains_elixir | 16da18d4582307f4967b6cce7320e9aa08a849c3 | [
"Apache-2.0"
] | null | null | null | defmodule Ecto.Changeset.Relation do
@moduledoc false
alias Ecto.Changeset
alias Ecto.Association.NotLoaded
@type t :: %{cardinality: :one | :many,
on_replace: :raise | :mark_as_invalid | atom,
relationship: :parent | :child,
owner: atom,
related: atom,
field: atom}
@doc """
Builds the related data.
"""
@callback build(t) :: Ecto.Schema.t
@doc """
Returns empty container for relation.
"""
def empty(%{cardinality: cardinality}), do: do_empty(cardinality)
defp do_empty(:one), do: nil
defp do_empty(:many), do: []
@doc """
Checks if the container can be considered empty.
"""
def empty?(%{cardinality: _}, %NotLoaded{}), do: true
def empty?(%{cardinality: :many}, []), do: true
def empty?(%{cardinality: :one}, nil), do: true
def empty?(%{}, _), do: false
@doc """
Applies related changeset changes
"""
def apply_changes(%{cardinality: :one}, nil) do
nil
end
def apply_changes(%{cardinality: :one}, changeset) do
apply_changes(changeset)
end
def apply_changes(%{cardinality: :many}, changesets) do
for changeset <- changesets,
struct = apply_changes(changeset),
do: struct
end
defp apply_changes(%Changeset{action: :delete}), do: nil
defp apply_changes(%Changeset{action: :replace}), do: nil
defp apply_changes(changeset), do: Changeset.apply_changes(changeset)
@doc """
Loads the relation with the given struct.
Loading will fail if the association is not loaded but the struct is.
"""
def load!(%{__meta__: %{state: :built}}, %NotLoaded{__cardinality__: cardinality}) do
do_empty(cardinality)
end
def load!(struct, %NotLoaded{__field__: field}) do
raise "attempting to cast or change association `#{field}` " <>
"from `#{inspect struct.__struct__}` that was not loaded. Please preload your " <>
"associations before manipulating them through changesets"
end
def load!(_struct, loaded), do: loaded
@doc """
Casts related according to the `on_cast` function.
"""
def cast(%{cardinality: :one} = relation, nil, current, _on_cast) do
case current && on_replace(relation, current) do
:error -> :error
_ -> {:ok, nil, true, false}
end
end
def cast(%{cardinality: :many} = relation, params, current, on_cast) when is_map(params) do
params =
params
|> Enum.sort_by(&elem(&1, 0))
|> Enum.map(&elem(&1, 1))
cast(relation, params, current, on_cast)
end
def cast(%{related: mod} = relation, params, current, on_cast) do
pks = mod.__schema__(:primary_key)
cast_or_change(relation, params, current, struct_pk(mod, pks),
param_pk(mod, pks), &do_cast(relation, &1, &2, &3, on_cast))
end
defp do_cast(meta, params, nil, allowed_actions, on_cast) do
{:ok,
on_cast.(meta.__struct__.build(meta), params)
|> put_new_action(:insert)
|> check_action!(allowed_actions)}
end
defp do_cast(relation, nil, current, _allowed_actions, _on_cast) do
on_replace(relation, current)
end
defp do_cast(_meta, params, struct, allowed_actions, on_cast) do
{:ok,
on_cast.(struct, params)
|> put_new_action(:update)
|> check_action!(allowed_actions)}
end
@doc """
Wraps related structs in changesets.
"""
def change(%{cardinality: :one} = relation, nil, current) do
case current && on_replace(relation, current) do
:error -> :error
_ -> {:ok, nil, true, false}
end
end
def change(%{related: mod} = relation, value, current) do
get_pks = struct_pk(mod, mod.__schema__(:primary_key))
cast_or_change(relation, value, current, get_pks, get_pks,
&do_change(relation, &1, &2, &3))
end
# This may be an insert or an update, get all fields.
defp do_change(_relation, %{__struct__: _} = changeset_or_struct, nil, _allowed_actions) do
changeset = Changeset.change(changeset_or_struct)
{:ok, put_new_action(changeset, action_from_changeset(changeset))}
end
defp do_change(relation, nil, current, _allowed_actions) do
on_replace(relation, current)
end
defp do_change(_relation, %Changeset{} = changeset, _current, allowed_actions) do
{:ok, put_new_action(changeset, :update) |> check_action!(allowed_actions)}
end
defp do_change(_relation, %{__struct__: _} = struct, _current, allowed_actions) do
{:ok, struct |> Ecto.Changeset.change |> put_new_action(:update) |> check_action!(allowed_actions)}
end
defp do_change(%{related: mod} = relation, changes, current, allowed_actions)
when is_list(changes) or is_map(changes) do
changeset = Ecto.Changeset.change(current || mod.__struct__, changes)
changeset = put_new_action(changeset, action_from_changeset(changeset))
do_change(relation, changeset, current, allowed_actions)
end
defp action_from_changeset(%{data: %{__meta__: %{state: state}}}) do
case state do
:built -> :insert
:loaded -> :update
:deleted -> :delete
end
end
defp action_from_changeset(_) do
:insert # We don't care if it is insert/update for embeds (no meta)
end
@doc """
Handles the changeset or struct when being replaced.
"""
def on_replace(%{on_replace: :mark_as_invalid}, _changeset_or_struct) do
:error
end
def on_replace(%{on_replace: :raise, field: name, owner: owner}, _) do
raise """
you are attempting to change relation #{inspect name} of
#{inspect owner}, but there is missing data.
If you are attempting to update an existing entry, please make sure
you include the entry primary key (ID) alongside the data.
If you have a relationship with many children, at least the same N
children must be given on update. By default it is not possible to
orphan embed nor associated records, attempting to do so results in
this error message.
If you don't desire the current behavior or if you are using embeds
without a primary key, it is possible to change this behaviour by
setting `:on_replace` when defining the relation. See `Ecto.Changeset`'s
section on related data for more info.
"""
end
def on_replace(_relation, changeset_or_struct) do
{:ok, Changeset.change(changeset_or_struct) |> put_new_action(:replace)}
end
defp cast_or_change(%{cardinality: :one} = relation, value, current, current_pks,
new_pks, fun) when is_map(value) or is_list(value) or is_nil(value) do
single_change(relation, value, current_pks, new_pks, fun, current)
end
defp cast_or_change(%{cardinality: :many}, [], [], _current_pks, _new_pks, _fun) do
{:ok, [], true, false}
end
defp cast_or_change(%{cardinality: :many, unique: unique}, value, current, current_pks, new_pks, fun) when is_list(value) do
map_changes(value, new_pks, fun, process_current(current, current_pks), [], true, true, unique && %{})
end
defp cast_or_change(_, _, _, _, _, _), do: :error
# single change
defp single_change(_relation, nil, _current_pks, _new_pks, fun, current) do
single_change(nil, current, fun, [:update, :delete], false)
end
defp single_change(_relation, new, _current_pks, _new_pks, fun, nil) do
single_change(new, nil, fun, [:insert], false)
end
defp single_change(%{on_replace: on_replace} = relation, new, current_pks, new_pks, fun, current) do
pk_values = new_pks.(new)
if on_replace == :update or (pk_values == current_pks.(current) and pk_values != []) do
single_change(new, current, fun, allowed_actions(pk_values), true)
else
case on_replace(relation, current) do
{:ok, _changeset} -> single_change(new, nil, fun, [:insert], false)
:error -> :error
end
end
end
defp single_change(new, current, fun, allowed_actions, skippable?) do
case fun.(new, current, allowed_actions) do
{:ok, changeset} ->
{:ok, changeset, changeset.valid?, skippable? and skip?(changeset)}
:error ->
:error
end
end
# map changes
defp map_changes([changes | rest], new_pks, fun, current, acc, valid?, skip?, acc_pk_values)
when is_map(changes) or is_list(changes) do
pk_values = new_pks.(changes)
{struct, current, allowed_actions} = pop_current(current, pk_values)
case fun.(changes, struct, allowed_actions) do
{:ok, changeset} ->
changeset = maybe_add_error_on_pk(changeset, pk_values, acc_pk_values)
map_changes(rest, new_pks, fun, current, [changeset | acc],
valid? and changeset.valid?, (struct != nil) and skip? and skip?(changeset),
acc_pk_values && Map.put(acc_pk_values, pk_values, true))
:error ->
:error
end
end
defp map_changes([], _new_pks, fun, current, acc, valid?, skip?, _acc_pk_values) do
current_structs = Enum.map(current, &elem(&1, 1))
reduce_delete_changesets(current_structs, fun, Enum.reverse(acc), valid?, skip?)
end
defp map_changes(_params, _new_pks, _fun, _current, _acc, _valid?, _skip?, _acc_pk_values) do
:error
end
defp maybe_add_error_on_pk(%{data: %{__struct__: schema}} = changeset, pk_values, acc_pk_values) do
invalid? = pk_values == [] or Enum.any?(pk_values, &is_nil/1)
case acc_pk_values do
%{^pk_values => true} when not invalid? ->
Enum.reduce(schema.__schema__(:primary_key), changeset, fn pk, acc ->
Changeset.add_error(acc, pk, "has already been taken")
end)
_ ->
changeset
end
end
defp allowed_actions(pk_values) do
if Enum.all?(pk_values, &is_nil/1) do
[:insert, :update, :delete]
else
[:update, :delete]
end
end
defp reduce_delete_changesets([], _fun, acc, valid?, skip?) do
{:ok, acc, valid?, skip?}
end
defp reduce_delete_changesets([struct | rest], fun, acc, valid?, _skip?) do
case fun.(nil, struct, [:update, :delete]) do
{:ok, changeset} ->
reduce_delete_changesets(rest, fun, [changeset | acc],
valid? and changeset.valid?, false)
:error ->
:error
end
end
# helpers
defp check_action!(changeset, allowed_actions) do
action = changeset.action
cond do
action in allowed_actions ->
changeset
action == :insert ->
raise "cannot #{action} related #{inspect changeset.data} " <>
"because it is already associated with the given struct"
true ->
raise "cannot #{action} related #{inspect changeset.data} because " <>
"it already exists and it is not currently associated with the " <>
"given struct. Ecto forbids casting existing records through " <>
"the association field for security reasons. Instead, set " <>
"the foreign key value accordingly"
end
end
defp process_current(nil, _get_pks),
do: %{}
defp process_current(current, get_pks) do
Enum.reduce(current, {%{}, 0}, fn struct, {acc, index} ->
case get_pks.(struct) do
[] -> {Map.put(acc, index, struct), index + 1}
pks -> {Map.put(acc, pks, struct), index}
end
end) |> elem(0)
end
defp pop_current(current, pk_values) do
case Map.fetch(current, pk_values) do
{:ok, struct} ->
{struct, Map.delete(current, pk_values), allowed_actions(pk_values)}
:error ->
{nil, current, [:insert]}
end
end
defp struct_pk(_mod, pks) do
fn
%Changeset{data: struct} -> Enum.map(pks, &Map.get(struct, &1))
[_|_] = struct -> Enum.map(pks, &Keyword.get(struct, &1))
%{} = struct -> Enum.map(pks, &Map.get(struct, &1))
end
end
defp param_pk(mod, pks) do
pks = Enum.map(pks, &{&1, Atom.to_string(&1), mod.__schema__(:type, &1)})
fn params ->
Enum.map pks, fn {atom_key, string_key, type} ->
original = Map.get(params, string_key) || Map.get(params, atom_key)
case Ecto.Type.cast(type, original) do
{:ok, value} -> value
:error -> original
end
end
end
end
defp put_new_action(%{action: action} = changeset, new_action) when is_nil(action),
do: Map.put(changeset, :action, new_action)
defp put_new_action(changeset, _new_action),
do: changeset
defp skip?(%{valid?: true, changes: empty, action: :update}) when empty == %{},
do: true
defp skip?(_changeset),
do: false
end
| 33.186667 | 126 | 0.651828 |
e835ec6a6d4601bdbfba312f2f0e22b63a5a46fe | 403 | exs | Elixir | apps/bankingengine/priv/repo/migrations/20210414184116_create_user.exs | IgorFB00/bankingengine | b09eb44ee336869625a9afe38fcceef03d06a092 | [
"Apache-2.0"
] | null | null | null | apps/bankingengine/priv/repo/migrations/20210414184116_create_user.exs | IgorFB00/bankingengine | b09eb44ee336869625a9afe38fcceef03d06a092 | [
"Apache-2.0"
] | null | null | null | apps/bankingengine/priv/repo/migrations/20210414184116_create_user.exs | IgorFB00/bankingengine | b09eb44ee336869625a9afe38fcceef03d06a092 | [
"Apache-2.0"
] | null | null | null | defmodule Bankingengine.Repo.Migrations.CreateUser do
use Ecto.Migration
def change do
create table(:users, primary_key: false) do
add :id, :uuid, primary_key: true
add :cpf, :string
add :name, :string
add :email, :string
add :adress, :string
timestamps()
end
create unique_index(:users, [:email])
create unique_index(:users, [:cpf])
end
end
| 21.210526 | 53 | 0.645161 |
e83614f58f4e3c14aadcce92fa34bd70581b64fa | 274 | ex | Elixir | lib/drunkard/protobuf/recipeArray.pb.ex | shaddysignal/drunkard | 8365c75cd98414dfe38481956e90dda26a177bdd | [
"Unlicense"
] | 2 | 2020-07-05T21:27:33.000Z | 2021-12-12T22:56:00.000Z | lib/drunkard/protobuf/recipeArray.pb.ex | shaddysignal/drunkard | 8365c75cd98414dfe38481956e90dda26a177bdd | [
"Unlicense"
] | 1 | 2021-05-11T08:14:48.000Z | 2021-05-11T08:14:48.000Z | lib/drunkard/protobuf/recipeArray.pb.ex | shaddysignal/drunkard | 8365c75cd98414dfe38481956e90dda26a177bdd | [
"Unlicense"
] | 1 | 2020-07-05T21:27:46.000Z | 2020-07-05T21:27:46.000Z | defmodule Drunkard.Protobuf.RecipeArray do
@moduledoc false
use Protobuf, syntax: :proto3
@type t :: %__MODULE__{
recipe: [Drunkard.Protobuf.Recipe.t()]
}
defstruct [:recipe]
field :recipe, 1, repeated: true, type: Drunkard.Protobuf.Recipe
end
| 22.833333 | 66 | 0.682482 |
e83633d8d4aabbce11b3846eaebcb410e6901cd3 | 304 | ex | Elixir | lib/sanbase_web/live_view_utils.ex | sitedata/sanbase2 | 8da5e44a343288fbc41b68668c6c80ae8547d557 | [
"MIT"
] | 81 | 2017-11-20T01:20:22.000Z | 2022-03-05T12:04:25.000Z | lib/sanbase_web/live_view_utils.ex | rmoorman/sanbase2 | 226784ab43a24219e7332c49156b198d09a6dd85 | [
"MIT"
] | 359 | 2017-10-15T14:40:53.000Z | 2022-01-25T13:34:20.000Z | lib/sanbase_web/live_view_utils.ex | sitedata/sanbase2 | 8da5e44a343288fbc41b68668c6c80ae8547d557 | [
"MIT"
] | 16 | 2017-11-19T13:57:40.000Z | 2022-02-07T08:13:02.000Z | defmodule SanbaseWeb.LiveViewUtils do
require Sanbase.Utils.Config, as: Config
def session_options(opts) do
opts
|> Keyword.put(:domain, Config.module_get(SanbaseWeb.Plug.SessionPlug, :domain))
|> Keyword.put(:key, Config.module_get(SanbaseWeb.Plug.SessionPlug, :session_key))
end
end
| 30.4 | 86 | 0.753289 |
e8364086db690601e37553678f25a356ef1dcae3 | 1,513 | ex | Elixir | lib/locations_web/endpoint.ex | antp/locations | fe765fe78b896fe02e11b92e8d21e97f00744384 | [
"MIT"
] | 14 | 2020-09-16T14:10:35.000Z | 2021-10-30T22:05:48.000Z | lib/locations_web/endpoint.ex | antp/locations | fe765fe78b896fe02e11b92e8d21e97f00744384 | [
"MIT"
] | null | null | null | lib/locations_web/endpoint.ex | antp/locations | fe765fe78b896fe02e11b92e8d21e97f00744384 | [
"MIT"
] | null | null | null | defmodule LocationsWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :locations
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
@session_options [
store: :cookie,
key: "_locations_key",
signing_salt: "HDYqlCt8"
]
socket "/socket", LocationsWeb.UserSocket,
websocket: true,
longpoll: false
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phx.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/",
from: :locations,
gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
plug Phoenix.Ecto.CheckRepoStatus, otp_app: :locations
end
plug Plug.RequestId
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug LocationsWeb.Router
end
| 29.666667 | 97 | 0.71844 |
e8365b99ba13ea511b7af1c4f8d18490216fff8e | 1,170 | exs | Elixir | test/bitcoin_simulator/bitcoin_core/network_test.exs | sidharth-shridhar/Bitcoin-Miner-Simulation | 2789dc8fe5f65269789540f675fac682e431e518 | [
"MIT"
] | 1 | 2021-12-16T08:31:24.000Z | 2021-12-16T08:31:24.000Z | test/bitcoin_simulator/bitcoin_core/network_test.exs | hojason117/BitcoinSimulator | f85e623eec1923a2c0d418388f440cc06b6a5283 | [
"MIT"
] | null | null | null | test/bitcoin_simulator/bitcoin_core/network_test.exs | hojason117/BitcoinSimulator | f85e623eec1923a2c0d418388f440cc06b6a5283 | [
"MIT"
] | null | null | null | defmodule BitcoinSimulator.BitcoinCore.NetworkTest do
use ExUnit.Case, async: true
alias BitcoinSimulator.BitcoinCore.Network
test "message seen?" do
record =
%Network.MessageRecord{
transactions: Map.new([{:crypto.hash(:sha256, "exist"), Timex.now()}]),
blocks: Map.new([{:crypto.hash(:sha256, "exist"), Timex.now()}])
}
assert Network.message_seen?(record, :transaction, :crypto.hash(:sha256, "exist")) == true
assert Network.message_seen?(record, :block, :crypto.hash(:sha256, "not exist")) == false
end
test "saw message" do
record = %Network.MessageRecord{}
assert Network.message_seen?(record, :transaction, :crypto.hash(:sha256, "exist")) == false
assert Network.message_seen?(record, :block, :crypto.hash(:sha256, "exist")) == false
record = Network.saw_message(record, :transaction, :crypto.hash(:sha256, "exist"))
record = Network.saw_message(record, :block, :crypto.hash(:sha256, "exist"))
assert Network.message_seen?(record, :transaction, :crypto.hash(:sha256, "exist")) == true
assert Network.message_seen?(record, :block, :crypto.hash(:sha256, "exist")) == true
end
end
| 41.785714 | 95 | 0.683761 |
e836683b74f5ab7fbe0a65b1209ec8f386dbf6c9 | 460 | exs | Elixir | .workshop/exercises/my_enum/test/test_helper.exs | silesian-beamers/elixir-from-the-ground-up | 1ad8c2a4d429175461dc45e218849eb6a212c776 | [
"MIT"
] | 10 | 2015-12-13T07:29:08.000Z | 2016-09-22T03:47:35.000Z | .workshop/exercises/my_enum/test/test_helper.exs | silesian-beamers/elixir-from-the-ground-up | 1ad8c2a4d429175461dc45e218849eb6a212c776 | [
"MIT"
] | 4 | 2015-12-02T12:12:14.000Z | 2016-01-11T07:33:24.000Z | .workshop/exercises/my_enum/test/test_helper.exs | silesian-beamers/elixir-from-the-ground-up | 1ad8c2a4d429175461dc45e218849eb6a212c776 | [
"MIT"
] | null | null | null | defmodule Workshop.Exercise.MyEnumCheck.Helper do
def exec(solution_dir) do
# Locate and load and perhaps start the users solution.
# The following example assumes that the user solution is located
# in a file called *exercise.exs*:
"my_enum.ex"
|> Path.expand(solution_dir)
|> Code.require_file
# load and run the solution checker
Code.require_file("check.exs", __DIR__)
Workshop.Exercise.MyEnumCheck.run()
end
end
| 25.555556 | 69 | 0.715217 |
e83682b4a5ca25483b6aea32f9a4258db79e2399 | 738 | ex | Elixir | lib/glimesh_web/live/live_helpers.ex | YFG-Online/glimesh.tv | 5d9bb6f4ab383897c383bf33bbfac783b09e294e | [
"MIT"
] | null | null | null | lib/glimesh_web/live/live_helpers.ex | YFG-Online/glimesh.tv | 5d9bb6f4ab383897c383bf33bbfac783b09e294e | [
"MIT"
] | null | null | null | lib/glimesh_web/live/live_helpers.ex | YFG-Online/glimesh.tv | 5d9bb6f4ab383897c383bf33bbfac783b09e294e | [
"MIT"
] | null | null | null | defmodule GlimeshWeb.LiveHelpers do
import Phoenix.LiveView.Helpers
@doc """
Renders a component inside the `GlimeshWeb.ModalComponent` component.
The rendered modal receives a `:return_to` option to properly update
the URL when the modal is closed.
## Examples
<%= live_modal @socket, GlimeshWeb.PostLive.FormComponent,
id: @post.id || :new,
action: @live_action,
post: @post,
return_to: Routes.post_index_path(@socket, :index) %>
"""
def live_modal(socket, component, opts) do
path = Keyword.fetch!(opts, :return_to)
modal_opts = [id: :modal, return_to: path, component: component, opts: opts]
live_component(socket, GlimeshWeb.ModalComponent, modal_opts)
end
end
| 30.75 | 80 | 0.697832 |
e836a8168f6118c69dd212714635090e0ef817b9 | 106 | ex | Elixir | lib/journey/repo.ex | shipworthy/journey | 95674eb9ca3a1aa932d2ef36753deefe6ce9405e | [
"MIT"
] | 1 | 2021-10-04T15:49:53.000Z | 2021-10-04T15:49:53.000Z | lib/journey/repo.ex | shipworthy/journey | 95674eb9ca3a1aa932d2ef36753deefe6ce9405e | [
"MIT"
] | 1 | 2021-06-14T02:31:57.000Z | 2021-06-14T02:31:57.000Z | lib/journey/repo.ex | shipworthy/journey | 95674eb9ca3a1aa932d2ef36753deefe6ce9405e | [
"MIT"
] | null | null | null | defmodule Journey.Repo do
use Ecto.Repo,
otp_app: :journey,
adapter: Ecto.Adapters.Postgres
end
| 17.666667 | 35 | 0.726415 |
e836b541b0ac175ad3b0767dfda2a971a8dc16e8 | 123 | ex | Elixir | lib/google_fit/activity_type/hiking.ex | tsubery/google_fit | 7578b832c560b3b4a78059ac86af6e111812712e | [
"Apache-2.0"
] | 2 | 2017-02-01T13:51:26.000Z | 2019-04-12T11:37:25.000Z | lib/google_fit/activity_type/hiking.ex | tsubery/google_fit | 7578b832c560b3b4a78059ac86af6e111812712e | [
"Apache-2.0"
] | null | null | null | lib/google_fit/activity_type/hiking.ex | tsubery/google_fit | 7578b832c560b3b4a78059ac86af6e111812712e | [
"Apache-2.0"
] | null | null | null | defmodule GoogleFit.ActivityType.Hiking do
@moduledoc false
def code, do: GoogleFit.ActivityType.code(__MODULE__)
end
| 20.5 | 55 | 0.804878 |
e836b5be3a4baa8ba9f3fd71367464930d560116 | 111 | exs | Elixir | test/test_helper.exs | Thopiax/rummage_phoenix | 22c9a3f499abeaf61af29998c4164d177bfe6521 | [
"MIT"
] | 72 | 2017-03-20T02:33:30.000Z | 2018-08-11T14:51:15.000Z | test/test_helper.exs | Thopiax/rummage_phoenix | 22c9a3f499abeaf61af29998c4164d177bfe6521 | [
"MIT"
] | 46 | 2017-03-27T06:43:27.000Z | 2018-07-17T16:49:08.000Z | test/test_helper.exs | Thopiax/rummage_phoenix | 22c9a3f499abeaf61af29998c4164d177bfe6521 | [
"MIT"
] | 30 | 2017-03-14T07:10:26.000Z | 2018-07-19T10:14:14.000Z | ExUnit.start()
Rummage.Phoenix.Repo.start_link()
Ecto.Adapters.SQL.Sandbox.mode(Rummage.Phoenix.Repo, :manual)
| 27.75 | 61 | 0.801802 |
e836bf2412a753b2e156e34b1ce3687dabcfb69c | 1,522 | exs | Elixir | priv/repo/seeds.exs | supersimple/tilex | 8e0c2ae06fe007f2a9b6393532c415cf8c3135f0 | [
"MIT"
] | 460 | 2016-12-28T21:50:05.000Z | 2022-03-16T14:34:08.000Z | priv/repo/seeds.exs | supersimple/tilex | 8e0c2ae06fe007f2a9b6393532c415cf8c3135f0 | [
"MIT"
] | 412 | 2016-12-27T17:32:01.000Z | 2021-09-17T23:51:47.000Z | priv/repo/seeds.exs | supersimple/tilex | 8e0c2ae06fe007f2a9b6393532c415cf8c3135f0 | [
"MIT"
] | 140 | 2017-01-06T06:55:58.000Z | 2022-02-04T13:35:21.000Z | # Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# Tilex.Repo.insert!(%Tilex.SomeModel{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
alias Tilex.{Channel, Developer, Post, Repo}
Repo.delete_all(Post)
Repo.delete_all(Channel)
Repo.delete_all(Developer)
phoenix_channel = Repo.insert!(%Channel{name: "phoenix", twitter_hashtag: "phoenix"})
elixir_channel = Repo.insert!(%Channel{name: "elixir", twitter_hashtag: "myelixirstatus"})
erlang_channel = Repo.insert!(%Channel{name: "erlang", twitter_hashtag: "erlang"})
developer =
Repo.insert!(%Developer{email: "developer@hashrocket.com", username: "rickyrocketeer"})
1..100
|> Enum.each(fn _i ->
Repo.insert!(%Post{
title: "Observing Change",
body: "A Gold Master Test in Practice",
channel: phoenix_channel,
developer: developer,
slug: Post.generate_slug()
})
Repo.insert!(%Post{
title: "Controlling Your Test Environment",
body: "Slow browser integration tests are a hard problem",
channel: elixir_channel,
developer: developer,
slug: Post.generate_slug()
})
Repo.insert!(%Post{
title: "Testing Elixir",
body: "A Rubyist's Journey",
channel: erlang_channel,
developer: developer,
slug: Post.generate_slug()
})
end)
| 29.269231 | 90 | 0.672142 |
e836cb2c6dc2a9713f7eb7d35b81aba1235cc132 | 1,820 | ex | Elixir | web/controllers/game_controller.ex | functional-miners/interactive-tetris | 440bc821745cc7fd7ff8b59a4fc6c643eb2bf183 | [
"MIT"
] | 1 | 2020-01-19T03:29:22.000Z | 2020-01-19T03:29:22.000Z | web/controllers/game_controller.ex | functional-miners/interactive-tetris | 440bc821745cc7fd7ff8b59a4fc6c643eb2bf183 | [
"MIT"
] | null | null | null | web/controllers/game_controller.ex | functional-miners/interactive-tetris | 440bc821745cc7fd7ff8b59a4fc6c643eb2bf183 | [
"MIT"
] | null | null | null | defmodule InteractiveTetris.GameController do
use InteractiveTetris.Web, :controller
alias InteractiveTetris.Room
alias InteractiveTetris.ConnectedGame
alias InteractiveTetris.User
def game(conn, %{"id" => id}) do
room = Repo.get(Room, id)
room = Ecto.Changeset.change(room, active: true)
case Repo.update room do
{:ok, _model} ->
username = get_session(conn, :username)
user = Repo.get_by(User, username: username)
case Repo.get_by(ConnectedGame, user_id: user.id, room_id: id) do
nil ->
changeset = ConnectedGame.changeset(%ConnectedGame{ :user_id => user.id, :room_id => id })
case Repo.insert(changeset) do
{:ok, _model} ->
conn
|> put_flash(:info, "Game activated!")
|> render("game.html", room: room)
{:error, _changeset} ->
conn
|> render("game.html", room: room)
end
_ ->
conn
|> put_flash(:info, "Game already active!")
|> render("game.html", room: room)
end
{:error, _changeset} ->
conn
|> put_flash(:error, "Game is not activated.")
|> render("game.html", room: room)
end
end
def summary(conn, %{"id" => id}) do
room = Repo.get(Room, id)
room = Repo.preload(room, [:author, :connected_users])
changeset = Ecto.Changeset.change(room, active: false, finished: true)
case Repo.update(changeset) do
{:ok, _model} ->
conn
|> put_flash(:info, "Game finished!")
|> render("summary.html", room: room)
{:error, _changeset} ->
conn
|> put_flash(:error, "Game is not finished.")
|> render("summary.html", room: room)
end
end
end
| 28.888889 | 102 | 0.558791 |
e836d625906eba9d7160d4039512436cba0e3d76 | 1,298 | ex | Elixir | lib/oli_web/live/common/text_search.ex | chrislawson/oli-torus | 94165b211ab74fac3e7c8a14110a394fa9a6f320 | [
"MIT"
] | null | null | null | lib/oli_web/live/common/text_search.ex | chrislawson/oli-torus | 94165b211ab74fac3e7c8a14110a394fa9a6f320 | [
"MIT"
] | null | null | null | lib/oli_web/live/common/text_search.ex | chrislawson/oli-torus | 94165b211ab74fac3e7c8a14110a394fa9a6f320 | [
"MIT"
] | 1 | 2021-10-30T05:58:19.000Z | 2021-10-30T05:58:19.000Z | defmodule OliWeb.Common.TextSearch do
use Surface.LiveComponent
prop apply, :event, default: "text_search_apply"
prop reset, :event, default: "text_search_reset"
prop change, :event, default: "text_search_change"
prop text, :string, default: ""
def render(%{id: id} = assigns) do
~F"""
<div class="input-group" style="max-width: 350px;">
<input id={"#{id}-input"} type="text" class="form-control" placeholder="Search..." value={@text} phx-hook="TextInputListener" phx-value-change={@change}>
{#if @text != ""}
<div class="input-group-append">
<button class="btn btn-outline-secondary" :on-click={@reset, target: :live_view} phx-value-id={@id}><i class="las la-times"></i></button>
</div>
{/if}
</div>
"""
end
def handle_delegated(event, params, socket, patch_fn) do
delegate_handle_event(event, params, socket, patch_fn)
end
def delegate_handle_event("text_search_reset", %{"id" => _id}, socket, patch_fn) do
patch_fn.(socket, %{text_search: "", offset: 0})
end
def delegate_handle_event("text_search_change", %{"value" => value}, socket, patch_fn) do
patch_fn.(socket, %{text_search: value, offset: 0})
end
def delegate_handle_event(_, _, _, _) do
:not_handled
end
end
| 34.157895 | 161 | 0.649461 |
e836d6324be498c90a2e1798197831acb26dd546 | 106 | ex | Elixir | web/commands/variant_option_value.ex | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 356 | 2016-03-16T12:37:28.000Z | 2021-12-18T03:22:39.000Z | web/commands/variant_option_value.ex | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 30 | 2016-03-16T09:19:10.000Z | 2021-01-12T08:10:52.000Z | web/commands/variant_option_value.ex | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 72 | 2016-03-16T13:32:14.000Z | 2021-03-23T11:27:43.000Z | defmodule Nectar.Command.VariantOptionValue do
use Nectar.Command, model: Nectar.VariantOptionValue
end
| 26.5 | 54 | 0.849057 |
e83703115ad1d85af7b70f20d3b87cb58ae117a7 | 71 | ex | Elixir | lib/wiring_editor_web/views/page_view.ex | apre/wiring_editor | 54337f97c95594258038a34949ebca7b423cbf6e | [
"WTFPL",
"Unlicense"
] | null | null | null | lib/wiring_editor_web/views/page_view.ex | apre/wiring_editor | 54337f97c95594258038a34949ebca7b423cbf6e | [
"WTFPL",
"Unlicense"
] | null | null | null | lib/wiring_editor_web/views/page_view.ex | apre/wiring_editor | 54337f97c95594258038a34949ebca7b423cbf6e | [
"WTFPL",
"Unlicense"
] | null | null | null | defmodule WiringEditorWeb.PageView do
use WiringEditorWeb, :view
end
| 17.75 | 37 | 0.830986 |
e83704cd093b78886460cec63f68a3e0395e1691 | 1,767 | exs | Elixir | db_server/test/db_server_web/schema/participating_team_schema_test.exs | Graveyardillon/db_server | ce5a5884d7d1f0eacb3c5cc27066203424594cf4 | [
"MIT"
] | null | null | null | db_server/test/db_server_web/schema/participating_team_schema_test.exs | Graveyardillon/db_server | ce5a5884d7d1f0eacb3c5cc27066203424594cf4 | [
"MIT"
] | null | null | null | db_server/test/db_server_web/schema/participating_team_schema_test.exs | Graveyardillon/db_server | ce5a5884d7d1f0eacb3c5cc27066203424594cf4 | [
"MIT"
] | null | null | null | defmodule DbServerWeb.ParticipatingTeamSchemaTest do
use ExUnit.Case, async: true
use DbServer.DataCase
use DbServer.AroundRepo
describe "participating team schema test." do
@insert_tournament_params %{
name: "test_name",
duration: 120,
participation_deadline: DateTime.utc_now(),
team_number_limit: 2,
player_number_limit: 2
}
@insert_user_params %{
id: "test_id",
name: "test_name",
email: "email@gmail.com",
password: "Password123?",
gender: 0,
bio: "Howdy?",
birthday: DateTime.utc_now()
}
@update_user_params %{
name: "new_one"
}
test "team creation and adding member test." do
assert {_, tournament_struct} = Tournaments.create(@insert_tournament_params)
assert {_, participating_team_struct} = ParticipatingTeams.create(tournament_struct)
# get the tourney.
assert %ParticipatingTeam{} = participating_team = ParticipatingTeams.get(participating_team_struct.id)
assert {_, user_struct} = Users.create(@insert_user_params)
assert {:ok, %ParticipatingTeam{} = participating_team} = ParticipatingTeams.add_member_relation(participating_team, user_struct)
|> ParticipatingTeams.update()
participating_team.user
|> Enum.each(fn x ->
assert x.id == @insert_user_params.id
assert {:ok, %User{} = user} = Users.update(x, @update_user_params)
end)
assert %ParticipatingTeam{} = participating_team = ParticipatingTeams.get(participating_team_struct.id)
participating_team.user
|> Enum.each(fn x ->
assert x.name == @update_user_params.name
end)
end
end
end | 33.980769 | 135 | 0.650821 |
e837051e0a947afc58f0e7417eac9eefda5dee2f | 46 | ex | Elixir | lib/assoc.ex | jmhthethird/assoc | d73c556f398d01258cbc17b6de58a621a6bc4397 | [
"MIT"
] | 6 | 2019-01-31T23:31:42.000Z | 2020-10-06T20:05:34.000Z | lib/assoc.ex | jmhthethird/assoc | d73c556f398d01258cbc17b6de58a621a6bc4397 | [
"MIT"
] | 2 | 2021-11-09T14:35:51.000Z | 2021-11-09T18:04:15.000Z | lib/assoc.ex | jmhthethird/assoc | d73c556f398d01258cbc17b6de58a621a6bc4397 | [
"MIT"
] | 2 | 2019-01-31T23:53:33.000Z | 2021-11-05T21:47:26.000Z | defmodule Assoc do
@moduledoc """
"""
end
| 9.2 | 18 | 0.608696 |
e83716a1a3746b8b80e884518c22d4339739f115 | 4,927 | ex | Elixir | clients/deployment_manager/lib/google_api/deployment_manager/v2/model/deployment.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/deployment_manager/lib/google_api/deployment_manager/v2/model/deployment.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/deployment_manager/lib/google_api/deployment_manager/v2/model/deployment.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.DeploymentManager.V2.Model.Deployment do
@moduledoc """
## Attributes
- description (String.t): An optional user-provided description of the deployment. Defaults to: `null`.
- fingerprint (binary()): Provides a fingerprint to use in requests to modify a deployment, such as update(), stop(), and cancelPreview() requests. A fingerprint is a randomly generated value that must be provided with update(), stop(), and cancelPreview() requests to perform optimistic locking. This ensures optimistic concurrency so that only one request happens at a time. The fingerprint is initially generated by Deployment Manager and changes after every request to modify data. To get the latest fingerprint value, perform a get() request to a deployment. Defaults to: `null`.
- id (String.t): Defaults to: `null`.
- insertTime (String.t): Output only. Creation timestamp in RFC3339 text format. Defaults to: `null`.
- labels ([DeploymentLabelEntry]): Map of labels; provided by the client when the resource is created or updated. Specifically: Label keys must be between 1 and 63 characters long and must conform to the following regular expression: [a-z]([-a-z0-9]*[a-z0-9])? Label values must be between 0 and 63 characters long and must conform to the regular expression ([a-z]([-a-z0-9]*[a-z0-9])?)? Defaults to: `null`.
- manifest (String.t): Output only. URL of the manifest representing the last manifest that was successfully deployed. Defaults to: `null`.
- name (String.t): Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression [a-z]([-a-z0-9]*[a-z0-9])? which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. Defaults to: `null`.
- operation (Operation): Output only. The Operation that most recently ran, or is currently running, on this deployment. Defaults to: `null`.
- selfLink (String.t): Output only. Server defined URL for the resource. Defaults to: `null`.
- target (TargetConfiguration): [Input Only] The parameters that define your deployment, including the deployment configuration and relevant templates. Defaults to: `null`.
- update (DeploymentUpdate): Output only. If Deployment Manager is currently updating or previewing an update to this deployment, the updated configuration appears here. Defaults to: `null`.
- updateTime (String.t): Output only. Update timestamp in RFC3339 text format. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:description => any(),
:fingerprint => any(),
:id => any(),
:insertTime => any(),
:labels => list(GoogleApi.DeploymentManager.V2.Model.DeploymentLabelEntry.t()),
:manifest => any(),
:name => any(),
:operation => GoogleApi.DeploymentManager.V2.Model.Operation.t(),
:selfLink => any(),
:target => GoogleApi.DeploymentManager.V2.Model.TargetConfiguration.t(),
:update => GoogleApi.DeploymentManager.V2.Model.DeploymentUpdate.t(),
:updateTime => any()
}
field(:description)
field(:fingerprint)
field(:id)
field(:insertTime)
field(:labels, as: GoogleApi.DeploymentManager.V2.Model.DeploymentLabelEntry, type: :list)
field(:manifest)
field(:name)
field(:operation, as: GoogleApi.DeploymentManager.V2.Model.Operation)
field(:selfLink)
field(:target, as: GoogleApi.DeploymentManager.V2.Model.TargetConfiguration)
field(:update, as: GoogleApi.DeploymentManager.V2.Model.DeploymentUpdate)
field(:updateTime)
end
defimpl Poison.Decoder, for: GoogleApi.DeploymentManager.V2.Model.Deployment do
def decode(value, options) do
GoogleApi.DeploymentManager.V2.Model.Deployment.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DeploymentManager.V2.Model.Deployment do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 60.82716 | 587 | 0.737569 |
e8377a3ef81820529f50a5452ce8d50917fbb8a9 | 4,165 | ex | Elixir | lib/sphinx_rtm/messages.ex | esl/sphinx | 2b514a713035512d80ab5d63f6945b1e11357b28 | [
"Apache-2.0"
] | 1 | 2021-03-11T23:23:34.000Z | 2021-03-11T23:23:34.000Z | lib/sphinx_rtm/messages.ex | esl/sphinx | 2b514a713035512d80ab5d63f6945b1e11357b28 | [
"Apache-2.0"
] | 1 | 2019-12-19T12:25:58.000Z | 2019-12-19T12:25:58.000Z | lib/sphinx_rtm/messages.ex | esl/sphinx | 2b514a713035512d80ab5d63f6945b1e11357b28 | [
"Apache-2.0"
] | 2 | 2021-03-11T23:27:14.000Z | 2022-03-06T10:20:41.000Z | defmodule SphinxRtm.Messages do
alias SphinxRtm.Messages.Parser
alias Sphinx.Riddles
alias Sphinx.SlackUtils
alias Sphinx.Answers
import Ecto.Query
@help """
```
@sphinx help Print Sphinx commands \n
@sphinx [TEXT] Starts a thread with SphinxBot \n
@sphinx [SAVE] [TEXT] It saves the link to the thread without title \n
...
```
"""
## TODO: check if message is a question
## if yes then get the keywords and search for old questions
## else check if it is related to/ answering the recent question.
## If yes, save the answer
## Else discard (something like that?)
@spec process(map()) :: {:ok, Riddles.Riddle.t()} | {:error, Ecto.Changeset.t()}
def process(message = %{thread_ts: _ts}) do
save_reply(message)
:no_reply
end
def process(message) do
case Parser.mention_sphinx?(message.text) do
true ->
text = Parser.trim_mention(message.text)
case Parser.check_content(text) do
{:help, _} ->
{:ephemeral, @help}
{:save, content} ->
message
|> Map.put(:text, content)
|> save_question()
{:ephemeral, "Your question is saved!"}
{:search, content} ->
content = if content == "", do: text, else: content
search(content, message)
end
false ->
:no_reply
end
end
def search(content, message) do
case db_search(content) do
[] ->
search_history(content, message)
riddles ->
case get_most_upvote_answers(riddles) do
[] ->
case search_history(content, message) do
{:ephemeral, _} ->
{:reply,
"Someone has asked the same on #{hd(riddles).permalink} but there is no answer so far"}
{:reply, reply} ->
{:reply, reply}
end
reply ->
{:reply, "You asked for \"#{content}\", you might find these helpful: \n #{reply}"}
end
end
end
def search_history(content, message) do
case SlackUtils.search(content, message.channel) do
nil ->
{:ephemeral,
"You asked for \"#{content}\" but I have no answer! Invoke @sphinx [SAVE] [TEXT] to save the question for future use!"}
reply ->
{:reply, "You asked for \"#{content}\", you might find these helpful: \n #{reply}"}
end
end
def add_reaction(message) do
permalink = permalink(message.item.channel, message.item.ts)
case Answers.get(%{permalink: permalink}) do
nil ->
:ok
answer ->
upvote = answer.upvote
Answers.update(%{permalink: permalink, upvote: upvote + 1})
end
end
defp db_search(content) do
query =
Riddles.Riddle
|> where([r], like(r.title, ^"%#{String.replace(content, "%", "\\%")}%"))
Sphinx.Repo.all(query)
end
@spec save_question(map()) :: {:ok, Riddles.Riddle.t()} | {:error, Ecto.Changeset.t()}
defp save_question(message) do
%{}
|> Map.put(:enquirer, user(message.user))
|> Map.put(:title, message.text)
|> Map.put(:permalink, permalink(message.channel, message.ts))
|> Riddles.create()
end
@spec save_reply(map()) :: {:ok, Riddles.Riddle.t()} | {:error, Ecto.Changeset.t()} | :ok
defp save_reply(message) do
params = %{:permalink => get_thread_permalink(message.channel, message.thread_ts)}
case Riddles.get(params) do
# Ignore thread reply to not-saved messages
nil ->
:ok
question ->
%{}
|> Map.put(:solver, user(message.user))
|> Map.put(:permalink, permalink(message.channel, message.ts))
|> Answers.create(question)
end
end
defp user(user_id), do: SlackUtils.get_user_name(user_id)
defp permalink(channel_id, ts), do: SlackUtils.get_permalink(channel_id, ts)
defp get_thread_permalink(channel_id, ts) do
permalink(channel_id, ts)
|> String.replace(~r/[?](.)*/, "")
end
defp get_most_upvote_answers(riddles) do
case Answers.get_most_upvote_answers(riddles, []) do
[] -> []
answers -> Parser.build_text("", 1, answers)
end
end
end
| 27.766667 | 128 | 0.597119 |
e837b08fffaf94ce3921df67861d23be4451ac6a | 3,678 | exs | Elixir | test/siwapp_web/graphql/invoices_test.exs | jakon89/siwapp | b5f8fd43458deae72c76e434ed0c63b620cb97a4 | [
"MIT"
] | null | null | null | test/siwapp_web/graphql/invoices_test.exs | jakon89/siwapp | b5f8fd43458deae72c76e434ed0c63b620cb97a4 | [
"MIT"
] | null | null | null | test/siwapp_web/graphql/invoices_test.exs | jakon89/siwapp | b5f8fd43458deae72c76e434ed0c63b620cb97a4 | [
"MIT"
] | null | null | null | defmodule SiwappWeb.Graphql.InvoicesTest do
use SiwappWeb.ConnCase, async: true
import Siwapp.InvoicesFixtures
import Siwapp.CommonsFixtures
import Siwapp.SettingsFixtures
setup do
series = series_fixture(%{name: "A-Series", code: "A-"})
taxes_fixture(%{name: "VAT", value: 21, default: true})
taxes_fixture(%{name: "RETENTION", value: -15})
settings_fixture()
invoices =
Enum.map(1..11, fn _i ->
invoice_fixture(%{name: "test_name", identification: "test_id"})
end)
%{invoices: invoices, series: series}
end
test "list invoices by a customer_id and get its name", %{conn: conn, invoices: invoices} do
invoice = hd(invoices)
query = """
query {
invoices(customer_id: #{invoice.customer_id} ) {
name
customer_id
}
}
"""
data_result =
Enum.map(1..10, fn _i ->
%{"name" => invoice.name, "customer_id" => "#{invoice.customer_id}"}
end)
res =
conn
|> post("/graphql", %{query: query})
|> json_response(200)
assert res == %{"data" => %{"invoices" => data_result}}
end
test "Create an invoice", %{conn: conn, series: series} do
query = """
mutation {
create_invoice(name: "test_name", series_code: "#{series.code}", metaAttributes: [{key: "testkey"}]) {
name
series_id
metaAttributes {
key
value
}
}
}
"""
res =
conn
|> post("/graphql", %{query: query})
|> json_response(200)
assert res == %{
"data" => %{
"create_invoice" => %{
"name" => "test_name",
"series_id" => "#{series.id}",
"metaAttributes" => [
%{"key" => "testkey", "value" => nil}
]
}
}
}
end
test "Update an invoice", %{conn: conn, invoices: invoices} do
invoice = hd(invoices)
query = """
mutation {
update_invoice(id: #{invoice.id}, email: "info@example.com", metaAttributes: [{key: "testkey" value: "testvalue"}]) {
name
email
metaAttributes {
key
value
}
}
}
"""
res =
conn
|> post("/graphql", %{query: query})
|> json_response(200)
assert res == %{
"data" => %{
"update_invoice" => %{
"name" => invoice.name,
"email" => "info@example.com",
"metaAttributes" => [
%{"key" => "testkey", "value" => "testvalue"}
]
}
}
}
end
test "Updating an invoice with a value but not with a key inside meta_attributes will return an error",
%{conn: conn, invoices: invoices} do
invoice = hd(invoices)
query = """
mutation {
update_invoice(id: #{invoice.id}, metaAttributes: [{value: "testvalue"}]) {
metaAttributes {
key
value
}
}
}
"""
res =
conn
|> post("/graphql", %{query: query})
|> json_response(200)
error_map = hd(res["errors"])
assert res == %{"errors" => [error_map]}
end
test "Delete an invoice", %{conn: conn, invoices: invoices} do
invoice = hd(invoices)
query = """
mutation {
delete_invoice(id: #{invoice.id}) {
name
}
}
"""
res =
conn
|> post("/graphql", %{query: query})
|> json_response(200)
assert res == %{"data" => %{"delete_invoice" => %{"name" => invoice.name}}}
end
end
| 23.426752 | 123 | 0.494018 |
e837b4d0f136ce0beae8a38f6e600fe60d6e2584 | 1,732 | ex | Elixir | clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/import_context_csv_import_options.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/import_context_csv_import_options.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/import_context_csv_import_options.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.SQLAdmin.V1beta4.Model.ImportContextCsvImportOptions do
@moduledoc """
Options for importing data as CSV.
## Attributes
* `columns` (*type:* `list(String.t)`, *default:* `nil`) - The columns to which CSV data is imported. If not specified, all columns
of the database table are loaded with CSV data.
* `table` (*type:* `String.t`, *default:* `nil`) - The table to which CSV data is imported.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:columns => list(String.t()),
:table => String.t()
}
field(:columns, type: :list)
field(:table)
end
defimpl Poison.Decoder, for: GoogleApi.SQLAdmin.V1beta4.Model.ImportContextCsvImportOptions do
def decode(value, options) do
GoogleApi.SQLAdmin.V1beta4.Model.ImportContextCsvImportOptions.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.SQLAdmin.V1beta4.Model.ImportContextCsvImportOptions do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.960784 | 135 | 0.729792 |
e837c323e3b11fb73a16bc1e6a1f90191044ab67 | 1,670 | ex | Elixir | clients/games/lib/google_api/games/v1/model/push_token_id.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/push_token_id.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/push_token_id.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Games.V1.Model.PushTokenId do
@moduledoc """
This is a JSON template for a push token ID resource.
## Attributes
- ios (PushTokenIdIos): Defaults to: `null`.
- kind (String.t): Uniquely identifies the type of this resource. Value is always the fixed string games#pushTokenId. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:ios => GoogleApi.Games.V1.Model.PushTokenIdIos.t(),
:kind => any()
}
field(:ios, as: GoogleApi.Games.V1.Model.PushTokenIdIos)
field(:kind)
end
defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.PushTokenId do
def decode(value, options) do
GoogleApi.Games.V1.Model.PushTokenId.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.PushTokenId do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.745098 | 140 | 0.733533 |
e837f613aace91ed74df665d57b0ea9f66c4441f | 198 | exs | Elixir | broker/test/broker_web/controllers/page_controller_test.exs | mikehelmick/broker-prototype | 68082f753d3a7ea29399706504419e495287b35f | [
"Apache-2.0"
] | 1 | 2019-02-04T21:09:16.000Z | 2019-02-04T21:09:16.000Z | broker/test/broker_web/controllers/page_controller_test.exs | mikehelmick/broker-prototype | 68082f753d3a7ea29399706504419e495287b35f | [
"Apache-2.0"
] | null | null | null | broker/test/broker_web/controllers/page_controller_test.exs | mikehelmick/broker-prototype | 68082f753d3a7ea29399706504419e495287b35f | [
"Apache-2.0"
] | null | null | null | defmodule BrokerWeb.PageControllerTest do
use BrokerWeb.ConnCase
test "GET /", %{conn: conn} do
conn = get(conn, "/")
assert html_response(conn, 200) =~ "Welcome to Phoenix!"
end
end
| 22 | 60 | 0.676768 |
e83801a3c4f9646e78207b12ecf8a7189c5c2f53 | 6,957 | ex | Elixir | lib/unifex/specs.ex | wishdev/unifex | f16a65b73e2a482e784b1bf6816b73c0f7bdb2a7 | [
"Apache-2.0"
] | null | null | null | lib/unifex/specs.ex | wishdev/unifex | f16a65b73e2a482e784b1bf6816b73c0f7bdb2a7 | [
"Apache-2.0"
] | null | null | null | lib/unifex/specs.ex | wishdev/unifex | f16a65b73e2a482e784b1bf6816b73c0f7bdb2a7 | [
"Apache-2.0"
] | null | null | null | defmodule Unifex.Specs do
@moduledoc """
Module exporting macros that can be used to define Unifex specs.
Example of such specs is provided below:
module Membrane.Element.Mad.Decoder.Native
spec create() :: {:ok :: label, state}
spec decode_frame(payload, offset :: int, state) ::
{:ok :: label, {payload, bytes_used :: long, sample_rate :: long, channels :: int}}
| {:error :: label, :buflen :: label}
| {:error :: label, :malformed :: label}
| {:error :: label, {:recoverable :: label, bytes_to_skip :: int}}
dirty :cpu, decode_frame: 3
sends {:example_msg :: label, number :: int}
According to this specification, module `Membrane.Element.Mad.Decoder.Native` should contain 2 functions: `create/0`
and `decode_frame/3` (which is a cpu-bound dirty NIF). The module should use `Unifex.Loader` to provide access to
these functions. What is more, messages of the form `{:example_msg, integer}` can be sent from the native code to
erlang processes.
The generated boilerplate would require implementation of the following functions:
UNIFEX_TERM create(UnifexEnv* env);
UNIFEX_TERM decode_frame(UnifexEnv* env, UnifexPayload * payload, int offset, State* state);
Also the following functions that should be called to return results will be generated:
UNIFEX_TERM create_result_ok(UnifexEnv* env, State* state);
UNIFEX_TERM decode_frame_result_ok(UnifexEnv* env, UnifexPayload * payload,
long bytes_used, long sample_rate, int channels);
UNIFEX_TERM decode_frame_result_error_buflen(UnifexEnv* env);
UNIFEX_TERM decode_frame_result_error_malformed(UnifexEnv* env);
UNIFEX_TERM decode_frame_result_error_recoverable(UnifexEnv* env, int bytes_to_skip);
See docs for appropriate macros for more details.
"""
@doc """
Defines module that exports native functions to Elixir world.
The module needs to be defined manually, but it can `use` `Unifex.Loader` to
have functions declared with `spec/1` automatically defined.
"""
defmacro module(module) do
store_config(:module, module)
end
@doc """
Defines native function specification.
The specification should be in the form of
spec function_name(parameter1 :: parameter1_type, some_type, parameter3 :: parameter3_type, ...) ::
{:label1 :: label, {result_value1 :: result_value1_type, some_type2, ...}}
| {:label2 :: label, other_result_value2 :: other_result_value2_type}
## Parameters
Specs for parameters can either take the form of `parameter1 :: parameter1_type`
which will generate parameter with name `parameter1` of type `parameter1_type`
The other form - just a name, like `some_type` - will generate parameter `some_type`
of type `some_type`.
Custom types can be added by creating modules `Unifex.BaseType.Type` that implement
`Unifex.BaseType` behaviour. Then, they can by used in specs as `type`.
Each generated function gets additional `UnifexEnv* env` as the first parameter implicitly.
## Returned values
Specs for returned values contain a special type - `label`. An atom of type `label`
will be put literally in returned values by the special function generated for each
spec. Names of the generated functions start with Elixir function name
(e.g. `create`) followed by `_result_` part and then all the labels joined with `_`.
## Example
The example is provided in the moduledoc of this module.
"""
defmacro spec(spec) do
store_config(:fun_specs, spec |> parse_fun_spec() |> enquote())
end
@doc """
Macro used for marking functions as dirty, i.e. performing long cpu-bound or
io-bound operations.
The macro should be used the following way:
dirty type, function1: function1_arity, ...
when type is one of:
- `:cpu` - marks function as CPU-bound (maps to the `ERL_NIF_DIRTY_JOB_CPU_BOUND` erlang flag)
- `:io` - marks function as IO-bound (maps to the `ERL_NIF_DIRTY_JOB_IO_BOUND` erlang flag)
"""
defmacro dirty(type, funs) when type in [:cpu, :io] and is_list(funs) do
store_config(:dirty, funs |> Enum.map(&{&1, type}))
end
@doc """
Defines terms that can be sent from the native code to elixir processes.
Creates native function that can be invoked to send specified data. Name of the
function starts with `send_` and is constructed from `label`s.
"""
defmacro sends(spec) do
store_config(:sends, spec |> enquote())
end
@doc """
Defines names of callbacks invoked on specified hook.
The available hooks are:
* `:load` - invoked when the library is loaded. Callback must have the following typing:
`int on_load(UnifexEnv *env, void ** priv_data)`
The callback receives an `env` and a pointer to private data that is initialized
with NULL and can be set to whatever should be passed to other callbacks.
If callback returns anything else than 0, the library fails to load.
* `:upgrade` - called when the library is loaded while there is old code for this module
with a native library loaded. Compared to `:load`, it also receives `old_priv_data`:
`int on_upgrade(UnifexEnv* env, void** priv_data, void** old_priv_data)`
Both old and new private data can be modified
If this callback is not defined, the module code cannot be hot-swapped. Non-zero return
value also prevents code upgrade.
* `:unload` - called when the code for module is unloaded. It has the following declaration:
`void on_unload(UnifexEnv *env, void * priv_data)`
"""
defmacro callback(hook, fun \\ nil) when hook in [:load, :upgrade, :unload] and is_atom(fun) do
fun = fun || "handle_#{hook}" |> String.to_atom()
store_config(:callbacks, {hook, fun})
end
defp store_config(key, value) when is_atom(key) do
config_store = Macro.var(:unifex_config__, nil)
quote generated: true do
unquote(config_store) = [{unquote(key), unquote(value)} | unquote(config_store)]
end
end
defp parse_fun_spec({:::, _, [{fun_name, _, args}, results]}) do
args =
args
|> Enum.map(fn
{:::, _, [{name, _, _}, [{type, _, _}]]} -> {name, {:list, type}}
[{name, _, _}] -> {name, {:list, name}}
{:::, _, [{name, _, _}, {type, _, _}]} -> {name, type}
{name, _, _} -> {name, name}
end)
results =
results
|> parse_fun_spec_results_traverse_helper()
{fun_name, args, results}
end
defp parse_fun_spec_results_traverse_helper({:|, _, [left, right]}) do
parse_fun_spec_results_traverse_helper(left) ++ parse_fun_spec_results_traverse_helper(right)
end
defp parse_fun_spec_results_traverse_helper(value) do
[value]
end
# Embeds code in a `quote` block. Useful when willing to store the code and parse
# it in runtime instead of compile time.
defp enquote(value) do
{:quote, [], [[do: value]]}
end
end
| 37.203209 | 118 | 0.693115 |
e83802e49603ddfe8820cd32e3e02d4a2a9260b7 | 579 | exs | Elixir | exercises/practice/tournament/mix.exs | devtayls/elixir | 67824de8209ff1b6ed2f736deedfb5bd815130ca | [
"MIT"
] | 343 | 2017-06-22T16:28:28.000Z | 2022-03-25T21:33:32.000Z | exercises/practice/tournament/mix.exs | devtayls/elixir | 67824de8209ff1b6ed2f736deedfb5bd815130ca | [
"MIT"
] | 583 | 2017-06-19T10:48:40.000Z | 2022-03-28T21:43:12.000Z | exercises/practice/tournament/mix.exs | devtayls/elixir | 67824de8209ff1b6ed2f736deedfb5bd815130ca | [
"MIT"
] | 228 | 2017-07-05T07:09:32.000Z | 2022-03-27T08:59:08.000Z | defmodule Tournament.MixProject do
use Mix.Project
def project do
[
app: :tournament,
version: "0.1.0",
# elixir: "~> 1.8",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end
| 19.965517 | 87 | 0.578584 |
e838636d9f057109c5a65fa1a9bac3264cb27a41 | 2,536 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/security_policy_rule_matcher.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/security_policy_rule_matcher.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/security_policy_rule_matcher.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.SecurityPolicyRuleMatcher do
@moduledoc """
Represents a match condition that incoming traffic is evaluated against. Exactly one field must be specified.
## Attributes
* `config` (*type:* `GoogleApi.Compute.V1.Model.SecurityPolicyRuleMatcherConfig.t`, *default:* `nil`) - The configuration options available when specifying versioned_expr. This field must be specified if versioned_expr is specified and cannot be specified if versioned_expr is not specified.
* `expr` (*type:* `GoogleApi.Compute.V1.Model.Expr.t`, *default:* `nil`) - User defined CEVAL expression. A CEVAL expression is used to specify match criteria such as origin.ip, source.region_code and contents in the request header.
* `versionedExpr` (*type:* `String.t`, *default:* `nil`) - Preconfigured versioned expression. If this field is specified, config must also be specified. Available preconfigured expressions along with their requirements are: SRC_IPS_V1 - must specify the corresponding src_ip_range field in config.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:config => GoogleApi.Compute.V1.Model.SecurityPolicyRuleMatcherConfig.t(),
:expr => GoogleApi.Compute.V1.Model.Expr.t(),
:versionedExpr => String.t()
}
field(:config, as: GoogleApi.Compute.V1.Model.SecurityPolicyRuleMatcherConfig)
field(:expr, as: GoogleApi.Compute.V1.Model.Expr)
field(:versionedExpr)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.SecurityPolicyRuleMatcher do
def decode(value, options) do
GoogleApi.Compute.V1.Model.SecurityPolicyRuleMatcher.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.SecurityPolicyRuleMatcher do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 47.849057 | 302 | 0.759858 |
e8386a6f3920c69a0b8ba50da299bd6c4a29b591 | 498 | exs | Elixir | languages/elixir/exercises/concept/rpn-calculator/test/rpn_calculator_test.exs | AlexLeSang/v3 | 3d35961a961b5a2129b1d42f1d118972d9665357 | [
"MIT"
] | 3 | 2020-07-25T06:24:00.000Z | 2020-09-14T17:39:11.000Z | languages/elixir/exercises/concept/rpn-calculator/test/rpn_calculator_test.exs | AlexLeSang/v3 | 3d35961a961b5a2129b1d42f1d118972d9665357 | [
"MIT"
] | 45 | 2020-01-24T17:04:52.000Z | 2020-11-24T17:50:18.000Z | languages/elixir/exercises/concept/rpn-calculator/test/rpn_calculator_test.exs | AlexLeSang/v3 | 3d35961a961b5a2129b1d42f1d118972d9665357 | [
"MIT"
] | null | null | null | defmodule RPNCalculatorTest do
use ExUnit.Case
test "let it crash" do
assert_raise(RuntimeError, fn ->
RPNCalculator.calculate!([], fn _ -> raise "test error" end)
end)
end
test "rescue the crash, no message" do
assert RPNCalculator.calculate([], fn _ -> raise "test error" end) == :error
end
test "rescue the crash, get error tuple with message" do
assert RPNCalculator.calculate_verbose([], fn _ -> raise "test error" end) == {:error, "test error"}
end
end
| 27.666667 | 104 | 0.674699 |
e838be2e5a57b2b2d8b0fbc0070e593e8d64228c | 588 | exs | Elixir | config/test.exs | ExSemantica/exsemantica | c2d72513195f44b6b5f73c8cc07394de0a1fd273 | [
"Apache-2.0"
] | null | null | null | config/test.exs | ExSemantica/exsemantica | c2d72513195f44b6b5f73c8cc07394de0a1fd273 | [
"Apache-2.0"
] | 2 | 2020-07-21T20:53:13.000Z | 2020-07-21T20:54:15.000Z | config/test.exs | Chlorophytus/eactivitypub | 469346b4d5cd7ad2b575c245ac50fd71b00c4864 | [
"Apache-2.0"
] | null | null | null | import Config
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :exsemantica, ExsemanticaWeb.Endpoint,
http: [ip: {127, 0, 0, 1}, port: 4002],
secret_key_base: "Fo2ydQjwjyrHBX+pVq+GGxiQRVeZADAHfx9oTaxMXdc8NZyPqPx7vByTjCs7iFlp",
server: false
# In test we don't send emails.
config :exsemantica, Exsemantica.Mailer,
adapter: Swoosh.Adapters.Test
# Print only warnings and errors during test
config :logger, level: :warn
# Initialize plugs at runtime for faster test compilation
config :phoenix, :plug_init_mode, :runtime
| 30.947368 | 86 | 0.768707 |
e838ec1636a063ea843cec3dd32fcb8dfca9e5d9 | 1,528 | ex | Elixir | server/lib/fakers_api_web/endpoint.ex | bart-kosmala/fakers | aff49689c2507a5f8e6e81441bd922ec8887bbc9 | [
"MIT"
] | 5 | 2020-11-15T17:46:40.000Z | 2021-06-15T16:10:57.000Z | server/lib/fakers_api_web/endpoint.ex | bart-kosmala/fakers | aff49689c2507a5f8e6e81441bd922ec8887bbc9 | [
"MIT"
] | 5 | 2020-12-04T13:38:10.000Z | 2020-12-18T11:15:50.000Z | server/lib/fakers_api_web/endpoint.ex | bart-kosmala/fakers | aff49689c2507a5f8e6e81441bd922ec8887bbc9 | [
"MIT"
] | 2 | 2020-12-18T11:16:18.000Z | 2021-01-19T22:03:35.000Z | defmodule FakersApiWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :fakers_api
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
@session_options [
store: :cookie,
key: "_fakers_api_key",
signing_salt: "Tlcv7ArO"
]
socket "/socket", FakersApiWeb.UserSocket,
websocket: true,
longpoll: false
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phx.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/",
from: :fakers_api,
gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
plug Phoenix.CodeReloader
plug Phoenix.Ecto.CheckRepoStatus, otp_app: :fakers_api
end
plug Phoenix.LiveDashboard.RequestLogger,
param_key: "request_logger",
cookie_key: "request_logger"
plug Plug.RequestId
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug FakersApiWeb.Router
end
| 28.830189 | 97 | 0.717932 |
e838f4e5d7aae75b704a907e12e9729610ea5aa4 | 716 | ex | Elixir | lib/mix_test_interactive/test_files.ex | kianmeng/mix_test_interactive | 6ce4ea1a1cbe8c926089b5cbb55556a991f5b2e1 | [
"MIT"
] | 32 | 2021-02-19T17:48:55.000Z | 2022-03-28T21:52:01.000Z | lib/mix_test_interactive/test_files.ex | kianmeng/mix_test_interactive | 6ce4ea1a1cbe8c926089b5cbb55556a991f5b2e1 | [
"MIT"
] | 6 | 2021-03-02T08:48:58.000Z | 2021-11-19T16:58:42.000Z | lib/mix_test_interactive/test_files.ex | kianmeng/mix_test_interactive | 6ce4ea1a1cbe8c926089b5cbb55556a991f5b2e1 | [
"MIT"
] | 2 | 2021-11-19T16:32:07.000Z | 2022-03-25T10:32:22.000Z | defmodule MixTestInteractive.TestFiles do
@moduledoc false
@doc """
List available test files
Respects the configured `:test_paths` and `:test_pattern` settings.
Used internally to filter test files by pattern on each test run.
That way, any new files that match an existing pattern will be picked
up immediately.
"""
@spec list() :: [String.t()]
def list() do
config = Mix.Project.config()
paths = config[:test_paths] || default_test_paths()
pattern = config[:test_pattern] || "*_test.exs"
Mix.Utils.extract_files(paths, pattern)
end
def default_test_paths do
if Mix.Project.umbrella?() do
Path.wildcard("apps/*/test")
else
["test"]
end
end
end
| 24.689655 | 71 | 0.682961 |
e839185df508b2f6c727d1aca7f704353fe39084 | 15,212 | exs | Elixir | test/unit/typespec_test.exs | wojtekmach/zigler | b2102744bff212351abfeb4f6d87e57dd1ab232c | [
"MIT"
] | 1 | 2021-02-26T00:00:34.000Z | 2021-02-26T00:00:34.000Z | test/unit/typespec_test.exs | fhunleth/zigler | 037ff05087563d3255f58fb0abbaedeb12b97211 | [
"MIT"
] | null | null | null | test/unit/typespec_test.exs | fhunleth/zigler | 037ff05087563d3255f58fb0abbaedeb12b97211 | [
"MIT"
] | null | null | null | defmodule ZiglerTest.Unit.TypespecTest do
use ExUnit.Case, async: true
@moduletag :typespec
alias Zig.Parser.Nif
alias Zig.Typespec
describe "when asking for a typespec retval" do
test "a void function gives a sane result" do
result = quote context: Elixir do
@spec egress() :: :nil
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "void"}) == result
end
###########################################################################
## INTS
test "a u8-returning function gives appropriate bounds" do
result = quote context: Elixir do
@spec egress() :: 0..255
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "u8"}) == result
end
test "a u16-returning function gives appropriate bounds" do
result = quote context: Elixir do
@spec egress() :: 0..0xFFFF
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "u16"}) == result
end
test "a u32-returning function gives appropriate bounds" do
result = quote context: Elixir do
@spec egress() :: 0..0xFFFF_FFFF
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "u32"}) == result
end
test "a u64-returning function gives non_neg_integer" do
result = quote context: Elixir do
@spec egress() :: non_neg_integer
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "u64"}) == result
end
test "an i32-returning function gives appropriate bounds" do
result = quote context: Elixir do
@spec egress() :: -2_147_483_648..2_147_483_647
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "i32"}) == result
end
test "an i64-returning function gives integer" do
result = quote context: Elixir do
@spec egress() :: integer
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "i64"}) == result
end
test "a c_uint-returning function gives non_neg_integer" do
result = quote context: Elixir do
@spec egress() :: non_neg_integer
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "c_uint"}) == result
end
test "a c_int-returning function gives integer" do
result = quote context: Elixir do
@spec egress() :: integer
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "c_int"}) == result
end
test "a c_ulong-returning function gives non_neg_integer" do
result = quote context: Elixir do
@spec egress() :: non_neg_integer
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "c_ulong"}) == result
end
test "a c_long-returning function gives integer" do
result = quote context: Elixir do
@spec egress() :: integer
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "c_long"}) == result
end
test "a usize-returning function gives non_neg_integer" do
result = quote context: Elixir do
@spec egress() :: non_neg_integer
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "usize"}) == result
end
test "an isize-returning function gives integer" do
result = quote context: Elixir do
@spec egress() :: integer
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "isize"}) == result
end
###########################################################################
## FLOATS
test "an f16-returning function gives float" do
result = quote context: Elixir do
@spec egress() :: float
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "f16"}) == result
end
test "an f32-returning function gives float" do
result = quote context: Elixir do
@spec egress() :: float
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "f32"}) == result
end
test "an f64-returning function gives float" do
result = quote context: Elixir do
@spec egress() :: float
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "f64"}) == result
end
###########################################################################
## BOOL
test "a bool returning function is boolean" do
result = quote context: Elixir do
@spec egress() :: boolean
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "bool"}) == result
end
###########################################################################
## BEAM
test "a beam.term returning function is term" do
result = quote context: Elixir do
@spec egress() :: term
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "beam.term"}) == result
end
test "a e.ErlNifTerm returning function is term" do
result = quote context: Elixir do
@spec egress() :: term
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "e.ErlNifTerm"}) == result
end
test "a beam.pid returning function is pid" do
result = quote context: Elixir do
@spec egress() :: pid
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "beam.pid"}) == result
end
test "a e.ErlNifPid returning function is pid" do
result = quote context: Elixir do
@spec egress() :: pid
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "e.ErlNifPid"}) == result
end
test "a beam.atom returning function is atom" do
result = quote context: Elixir do
@spec egress() :: atom
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "beam.atom"}) == result
end
###########################################################################
## COLLECTIONS
test "a u8-slice returning function is special and turns to binary" do
result = quote context: Elixir do
@spec egress() :: binary
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "[]u8"}) == result
end
test "a int-slice returning function is list of integer" do
result = quote context: Elixir do
@spec egress() :: [integer]
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "[]i64"}) == result
end
test "a float-slice returning function is list of integer" do
result = quote context: Elixir do
@spec egress() :: [float]
end
assert Typespec.from_nif(%Nif{name: :egress, arity: 0, args: [], retval: "[]f64"}) == result
end
end
describe "when asking for a typed input" do
test "?*e.ErlNifEnv is ignored for zero arity" do
result = quote context: Elixir do
@spec ingress() :: nil
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 0, args: ["?*e.ErlNifEnv"], retval: "void"}) == result
end
test "beam.env is ignored for zero arity" do
result = quote context: Elixir do
@spec ingress() :: nil
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 0, args: ["beam.env"], retval: "void"}) == result
end
test "?*e.ErlNifEnv is ignored for one arity" do
result = quote context: Elixir do
@spec ingress(integer) :: integer
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["?*e.ErlNifEnv", "i64"], retval: "i64"}) == result
end
test "beam.env is ignored for one arity" do
result = quote context: Elixir do
@spec ingress(integer) :: integer
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["beam.env", "i64"], retval: "i64"}) == result
end
###########################################################################
## INTS
test "a u8-input function gives appropriate bounds" do
result = quote context: Elixir do
@spec ingress(0..255) :: 0..255
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["u8"], retval: "u8"}) == result
end
test "a u16-input function gives appropriate bounds" do
result = quote context: Elixir do
@spec ingress(0..0xFFFF) :: 0..0xFFFF
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["u16"], retval: "u16"}) == result
end
test "a u32-input function gives appropriate bounds" do
result = quote context: Elixir do
@spec ingress(0..0xFFFF_FFFF) :: 0..0xFFFF_FFFF
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["u32"], retval: "u32"}) == result
end
test "a u64-input function gives non_neg_integer" do
result = quote context: Elixir do
@spec ingress(non_neg_integer) :: non_neg_integer
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["u64"], retval: "u64"}) == result
end
test "an i32-input function gives appropriate bounds" do
result = quote context: Elixir do
@spec ingress(-2_147_483_648..2_147_483_647) :: -2_147_483_648..2_147_483_647
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["i32"], retval: "i32"}) == result
end
test "an i64-input function gives integer" do
result = quote context: Elixir do
@spec ingress(integer) :: integer
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["i64"], retval: "i64"}) == result
end
test "a c_uint-input function gives non_neg_integer" do
result = quote context: Elixir do
@spec ingress(non_neg_integer) :: non_neg_integer
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["c_uint"], retval: "c_uint"}) == result
end
test "a c_int-input function gives integer" do
result = quote context: Elixir do
@spec ingress(integer) :: integer
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["c_int"], retval: "c_int"}) == result
end
test "a c_ulong-input function gives non_neg_integer" do
result = quote context: Elixir do
@spec ingress(non_neg_integer) :: non_neg_integer
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["c_ulong"], retval: "c_ulong"}) == result
end
test "a c_long-input function gives integer" do
result = quote context: Elixir do
@spec ingress(integer) :: integer
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["c_long"], retval: "c_long"}) == result
end
test "a usize-input function gives non_neg_integer" do
result = quote context: Elixir do
@spec ingress(non_neg_integer) :: non_neg_integer
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["usize"], retval: "usize"}) == result
end
test "an isize-input function gives integer" do
result = quote context: Elixir do
@spec ingress(integer) :: integer
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["isize"], retval: "isize"}) == result
end
###########################################################################
## FLOATS
test "an f16-input function gives float" do
result = quote context: Elixir do
@spec ingress(float) :: float
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["f16"], retval: "f16"}) == result
end
test "an f32-input function gives float" do
result = quote context: Elixir do
@spec ingress(float) :: float
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["f32"], retval: "f32"}) == result
end
test "an f64-input function gives float" do
result = quote context: Elixir do
@spec ingress(float) :: float
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["f64"], retval: "f64"}) == result
end
###########################################################################
## BOOL
test "a bool input function is boolean" do
result = quote context: Elixir do
@spec ingress(boolean) :: boolean
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["bool"], retval: "bool"}) == result
end
###########################################################################
## BEAM
test "a beam.term input function is term" do
result = quote context: Elixir do
@spec ingress(term) :: term
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["beam.term"], retval: "beam.term"}) == result
end
test "a e.ErlNifTerm input function is term" do
result = quote context: Elixir do
@spec ingress(term) :: term
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["e.ErlNifTerm"], retval: "e.ErlNifTerm"}) == result
end
test "a beam.pid input function is pid" do
result = quote context: Elixir do
@spec ingress(pid) :: pid
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["beam.pid"], retval: "beam.pid"}) == result
end
test "a e.ErlNifPid input function is pid" do
result = quote context: Elixir do
@spec ingress(pid) :: pid
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["e.ErlNifPid"], retval: "e.ErlNifPid"}) == result
end
test "a beam.atom input function is atom" do
result = quote context: Elixir do
@spec ingress(atom) :: atom
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["beam.atom"], retval: "beam.atom"}) == result
end
###########################################################################
## COLLECTIONS
test "a u8-slice returning function is special and turns to binary" do
result = quote context: Elixir do
@spec ingress(binary) :: binary
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["[]u8"], retval: "[]u8"}) == result
end
test "a int-slice returning function is list of integer" do
result = quote context: Elixir do
@spec ingress([integer]) :: [integer]
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["[]i64"], retval: "[]i64"}) == result
end
test "a float-slice returning function is list of integer" do
result = quote context: Elixir do
@spec ingress([float]) :: [float]
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["[]f64"], retval: "[]f64"}) == result
end
test "multi-speccing works" do
result = quote context: Elixir do
@spec ingress(float, integer) :: float
end
assert Typespec.from_nif(%Nif{name: :ingress, arity: 1, args: ["f64", "i64"], retval: "f64"}) == result
end
end
end
| 35.962175 | 120 | 0.586839 |
e8393a0d5e2cf7f09d276c6cf7720b27cc0ee5f0 | 639 | ex | Elixir | lib/lib_ten_web/controllers/admin/settings_controller.ex | 10clouds/10Books | 622360ea190421e07d4b207700867be105894218 | [
"MIT"
] | 11 | 2018-08-29T15:59:09.000Z | 2021-08-25T16:35:13.000Z | lib/lib_ten_web/controllers/admin/settings_controller.ex | fram74/10Books | 9e4e280032c7f7b9625c831efa9850d999327e53 | [
"MIT"
] | 16 | 2018-08-29T15:43:52.000Z | 2021-05-09T00:53:56.000Z | lib/lib_ten_web/controllers/admin/settings_controller.ex | fram74/10Books | 9e4e280032c7f7b9625c831efa9850d999327e53 | [
"MIT"
] | 3 | 2019-05-29T14:22:59.000Z | 2020-06-06T12:30:54.000Z | defmodule LibTenWeb.Admin.SettingsController do
use LibTenWeb, :controller
alias LibTen.Admin
def index(conn, _params) do
changeset = Admin.change_settings(conn.assigns.settings)
render(conn, "index.html", changeset: changeset)
end
def update(conn, %{"settings" => params}) do
case Admin.update_settings(conn.assigns.settings, params) do
{:ok, _} ->
conn
|> put_flash(:info, "Settings updated successfully.")
|> redirect(to: admin_settings_path(conn, :index))
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "index.html", changeset: changeset)
end
end
end
| 29.045455 | 64 | 0.669797 |
e839531bbae5b822e38dfe00cd05e4494fdc4732 | 523 | exs | Elixir | mix.exs | corka149/burrito | fa7d9af37b83e59a6429c19c6645ca8da170a86f | [
"MIT"
] | null | null | null | mix.exs | corka149/burrito | fa7d9af37b83e59a6429c19c6645ca8da170a86f | [
"MIT"
] | null | null | null | mix.exs | corka149/burrito | fa7d9af37b83e59a6429c19c6645ca8da170a86f | [
"MIT"
] | null | null | null | defmodule Burrito.MixProject do
use Mix.Project
def project do
[
app: :burrito,
version: String.trim(File.read!("VERSION")),
elixir: "~> 1.12",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:req, "~> 0.1.0"},
{:jason, "~> 1.2"}
]
end
end
| 18.034483 | 59 | 0.562141 |
e83968cd7b49952f157077abd994dec5f351ee67 | 11,896 | ex | Elixir | lib/mimic.ex | dylan-chong/mimic | 4ed364823f75285039af80af549dbe0ea646ebf0 | [
"Apache-2.0"
] | null | null | null | lib/mimic.ex | dylan-chong/mimic | 4ed364823f75285039af80af549dbe0ea646ebf0 | [
"Apache-2.0"
] | null | null | null | lib/mimic.ex | dylan-chong/mimic | 4ed364823f75285039af80af549dbe0ea646ebf0 | [
"Apache-2.0"
] | null | null | null | defmodule Mimic do
@moduledoc """
Mimic is a library that simplifies the usage of mocks in Elixir.
Mimic is mostly API compatible with [mox](https://hex.pm/packages/mox) but
doesn't require explicit contract checking with behaviours. It's also faster.
You're welcome.
Mimic works by copying your module out of the way and replacing it with one of
it's own which can delegate calls back to the original or to a mock function
as required.
In order to prepare a module for mocking you must call `copy/1` with the
module as an argument. We suggest that you do this in your
`test/test_helper.exs`:
```elixir
Mimic.copy(Calculator)
ExUnit.start()
```
Importantly calling `copy/1` will not change the behaviour of the module. When
writing tests you can then use `stub/3` or `expect/3` to add mocks and
assertions.
## Multi-process collaboration
Mimic supports multi-process collaboration via two mechanisms:
1. Explicit allows.
2. Global mode.
Using explicit allows is generally preferred as these stubs can be run
concurrently, whereas global mode tests must be run exclusively.
## Explicit allows
Using `allow/3` you can give other processes permission to use stubs and
expectations from where they were not defined.
```elixir
test "invokes add from a task" do
Caculator
|> expect(:add, fn x, y -> x + y end)
parent_pid = self()
Task.async(fn ->
Calculator |> allow(parent_pid, self())
assert Calculator.add(2, 3) == 5
end)
|> Task.await
end
```
## Global mode
When set in global mode any process is able to call the stubs and expectations
defined in your tests.
**Warning: If using global mode you should remove `async: true` from your tests**
Enable global mode using `set_mimic_global/1`.
```elixir
setup :set_mimic_global
setup :verify_on_exit!
test "invokes add from a task" do
Calculator
|> expect(:add, fn x, y -> x + y end)
Task.async(fn ->
assert Calculator.add(2, 3) == 5
end)
|> Task.await
end
```
"""
alias ExUnit.Callbacks
alias Mimic.{Server, VerificationError}
@doc false
defmacro __using__(_opts \\ []) do
quote do
import Mimic
setup :verify_on_exit!
end
end
@doc """
Define a stub function for a copied module.
## Arguments:
* `module` - the name of the module in which we're adding the stub.
* `function_name` - the name of the function we're stubbing.
* `function` - the function to use as a replacement.
## Raises:
* If `module` is not copied.
* If `function_name` is not publicly exported from `module` with the same arity.
## Example
iex> Calculator.add(2, 4)
6
iex> Mimic.stub(Calculator, :add, fn x, y -> x * y end)
...> Calculator.add(2, 4)
8
"""
@spec stub(module(), atom(), function()) :: module
def stub(module, function_name, function) do
arity = :erlang.fun_info(function)[:arity]
raise_if_not_copied!(module)
raise_if_not_exported_function!(module, function_name, arity)
module
|> Server.stub(function_name, arity, function)
|> validate_server_response(
"Stub cannot be called by the current process. Only the global owner is allowed."
)
end
@doc """
Replace all public functions in `module` with stubs.
The stubbed functions will raise if they are called.
## Arguments:
* `module` - The name of the module to stub.
## Raises:
* If `module` is not copied.
* If `function` is not called by the stubbing process.
## Example
iex> Mimic.stub(Calculator)
...> Calculator.add(2, 4)
** (ArgumentError) Module Calculator has not been copied. See docs for Mimic.copy/1
"""
@spec stub(module()) :: module()
def stub(module) do
raise_if_not_copied!(module)
module
|> Server.stub()
|> validate_server_response(
"Stub cannot be called by the current process. Only the global owner is allowed."
)
end
@doc """
Define a stub which must be called within an example.
This function is almost identical to `stub/3` except that the replacement
function must be called within the lifetime of the calling `pid` (i.e. the
test example).
## Arguments:
* `module` - the name of the module in which we're adding the stub.
* `function_name` - the name of the function we're stubbing.
* `function` - the function to use as a replacement.
## Raises:
* If `module` is not copied.
* If `function_name` is not publicly exported from `module` with the same
arity.
* If `function` is not called by the stubbing process.
## Example
iex> Calculator.add(2, 4)
6
iex> Mimic.expect(Calculator, :add, fn x, y -> x * y end)
...> Calculator.add(2, 4)
8
"""
@spec expect(atom, atom, non_neg_integer, function) :: module
def expect(module, fn_name, num_calls \\ 1, func)
def expect(_module, _fn_name, 0, _func) do
raise ArgumentError, "Expecting 0 calls should be done through Mimic.reject/1"
end
def expect(module, fn_name, num_calls, func)
when is_atom(module) and is_atom(fn_name) and is_integer(num_calls) and num_calls >= 1 and
is_function(func) do
arity = :erlang.fun_info(func)[:arity]
raise_if_not_copied!(module)
raise_if_not_exported_function!(module, fn_name, arity)
module
|> Server.expect(fn_name, arity, num_calls, func)
|> validate_server_response(
"Expect cannot be called by the current process. Only the global owner is allowed."
)
end
@doc """
Define a stub which must not be called.
This function allows you do define a stub which must not be called during the
course of this test. If it is called then the verification step will raise.
## Arguments:
* `function` - A capture of the function which must not be called.
## Raises:
* If `function` is not called by the stubbing process while calling `verify!/1`.
## Example:
iex> Mimic.reject(&Calculator.add/2)
Calculator
"""
@spec reject(function) :: module
def reject(function) when is_function(function) do
fun_info = :erlang.fun_info(function)
arity = fun_info[:arity]
module = fun_info[:module]
fn_name = fun_info[:name]
raise_if_not_copied!(module)
raise_if_not_exported_function!(module, fn_name, arity)
module
|> Server.expect(fn_name, arity, 0, function)
|> validate_server_response(
"Reject cannot be called by the current process. Only the global owner is allowed."
)
end
@doc """
Define a stub which must not be called.
This function allows you do define a stub which must not be called during the
course of this test. If it is called then the verification step will raise.
## Arguments:
* `module` - the name of the module in which we're adding the stub.
* `function_name` - the name of the function we're stubbing.
* `arity` - the arity of the function we're stubbing.
## Raises:
* If `function` is not called by the stubbing process while calling `verify!/1`.
## Example:
iex> Mimic.reject(Calculator, :add, 2)
Calculator
"""
@spec reject(module, atom, non_neg_integer) :: module
def reject(module, function_name, arity) do
raise_if_not_copied!(module)
raise_if_not_exported_function!(module, function_name, arity)
func = :erlang.make_fun(module, function_name, arity)
module
|> Server.expect(function_name, arity, 0, func)
|> validate_server_response(
"Reject cannot be called by the current process. Only the global owner is allowed."
)
end
@doc """
Allow other processes to share expectations and stubs defined by another
process.
## Arguments:
* `module` - the copied module.
* `owner_pid` - the process ID of the process which created the stub.
* `allowed_pid` - the process ID of the process which should also be allowed
to use this stub.
## Raises:
* If Mimic is running in global mode.
Allows other processes to share expectations and stubs defined by another
process.
## Example
```elixir
test "invokes add from a task" do
Caculator
|> expect(:add, fn x, y -> x + y end)
parent_pid = self()
Task.async(fn ->
Calculator |> allow(parent_pid, self())
assert Calculator.add(2, 3) == 5
end)
|> Task.await
end
```
"""
@spec allow(module(), pid(), pid()) :: module() | {:error, atom()}
def allow(module, owner_pid, allowed_pid) do
module
|> Server.allow(owner_pid, allowed_pid)
|> validate_server_response("Allow must not be called when mode is global.")
end
@doc """
Prepare `module` for mocking.
## Arguments:
* `module` - the name of the module to copy.
"""
@spec copy(module()) :: :ok
def copy(module) do
if not Code.ensure_compiled?(module) do
raise ArgumentError,
"Module #{inspect(module)} is not available"
end
Mimic.Module.replace!(module)
ExUnit.after_suite(fn _ -> Server.reset(module) end)
:ok
end
@doc """
Verifies the current process after it exits.
If you want to verify expectations for all tests, you can use
`verify_on_exit!/1` as a setup callback:
```elixir
setup :verify_on_exit!
```
"""
@spec verify_on_exit!(map()) :: :ok | no_return()
def verify_on_exit!(_context \\ %{}) do
pid = self()
Server.verify_on_exit(pid)
Callbacks.on_exit(Mimic, fn ->
verify!(pid)
Server.exit(pid)
end)
end
@doc """
Sets the mode to private. Mocks can be set and used by the process
```elixir
setup :set_mimic_private
```
"""
@spec set_mimic_private(map()) :: :ok
def set_mimic_private(_context \\ %{}), do: Server.set_private_mode()
@doc """
Sets the mode to global. Mocks can be set and used by all processes
```elixir
setup :set_mimic_global
```
"""
@spec set_mimic_global(map()) :: :ok
def set_mimic_global(_context \\ %{}), do: Server.set_global_mode(self())
@doc """
Chooses the mode based on ExUnit context. If `async` is `true` then
the mode is private, otherwise global.
```elixir
setup :set_mimic_from_context
```
"""
@spec set_mimic_from_context(map()) :: :ok
def set_mimic_from_context(%{async: true}), do: set_mimic_private()
def set_mimic_from_context(_context), do: set_mimic_global()
@doc """
Verify if expectations were fulfilled for a process `pid`
"""
@spec verify!(pid()) :: :ok
def verify!(pid \\ self()) do
pending = Server.verify(pid)
messages =
for {{module, name, arity}, num_calls, num_applied_calls} <- pending do
mfa = Exception.format_mfa(module, name, arity)
" * expected #{mfa} to be invoked #{num_calls} time(s) " <>
"but it has been called #{num_applied_calls} time(s)"
end
if messages != [] do
raise VerificationError,
"error while verifying mocks for #{inspect(pid)}:\n\n" <> Enum.join(messages, "\n")
end
:ok
end
@doc "Returns the current mode (`:global` or `:private`)"
@spec mode() :: :private | :global
def mode do
Server.get_mode()
|> validate_server_response("Couldn't get the current mode.")
end
defp raise_if_not_copied!(module) do
unless function_exported?(module, :__mimic_info__, 0) do
raise ArgumentError,
"Module #{inspect(module)} has not been copied. See docs for Mimic.copy/1"
end
end
defp raise_if_not_exported_function!(module, fn_name, arity) do
unless function_exported?(module, fn_name, arity) do
raise ArgumentError, "Function #{fn_name}/#{arity} not defined for #{inspect(module)}"
end
end
defp validate_server_response({:ok, module}, _), do: module
defp validate_server_response({:error, _}, error_message),
do: raise(ArgumentError, error_message)
end
| 26.672646 | 96 | 0.665098 |
e839940f029fede8e9b770ebdaef90f0bc7c49bb | 472 | ex | Elixir | lib/perkle/blockchain.ex | esprezzo/elixir-perkle | 42666bcb5b56322c9685068971b19029b00a17e3 | [
"MIT"
] | null | null | null | lib/perkle/blockchain.ex | esprezzo/elixir-perkle | 42666bcb5b56322c9685068971b19029b00a17e3 | [
"MIT"
] | null | null | null | lib/perkle/blockchain.ex | esprezzo/elixir-perkle | 42666bcb5b56322c9685068971b19029b00a17e3 | [
"MIT"
] | null | null | null | defmodule Perkle.Blockchain do
@doc """
iex> all_blocks = Perkle.Blockchain.get_all_blocks()
"""
@spec get_all_blocks :: {:ok, List.t} | {:error, String.t}
def get_all_blocks() do
{:ok, highest_block_num} = Perkle.Eth.block_number()
range_floor = 0
range = highest_block_num..range_floor
blocks = Enum.map(range, fn blocknum ->
{:ok, block} = blocknum |> Perkle.to_hex() |> Perkle.get_block_by_number()
block
end)
end
end | 27.764706 | 80 | 0.652542 |
e839ae4dc9f789358af753ead03373c13b1c2ee2 | 678 | ex | Elixir | learning/adopting_elixir/chapter_9/demo/lib/demo_web/views/error_helpers.ex | Mdlkxzmcp/various_elixir | c87527b7118a0c74a042073c04d2228025888ddf | [
"MIT"
] | 2 | 2020-01-20T20:15:20.000Z | 2020-02-27T11:08:42.000Z | learning/adopting_elixir/chapter_9/demo/lib/demo_web/views/error_helpers.ex | Mdlkxzmcp/various_elixir | c87527b7118a0c74a042073c04d2228025888ddf | [
"MIT"
] | null | null | null | learning/adopting_elixir/chapter_9/demo/lib/demo_web/views/error_helpers.ex | Mdlkxzmcp/various_elixir | c87527b7118a0c74a042073c04d2228025888ddf | [
"MIT"
] | null | null | null | defmodule DemoWeb.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
use Phoenix.HTML
@doc """
Generates tag for inlined form input errors.
"""
def error_tag(form, field) do
Enum.map(Keyword.get_values(form.errors, field), fn error ->
content_tag(:span, translate_error(error), class: "help-block")
end)
end
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
if count = opts[:count] do
Gettext.dngettext(DemoWeb.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(DemoWeb.Gettext, "errors", msg, opts)
end
end
end
| 24.214286 | 73 | 0.674041 |
e839ce187af0a47b5d2619c5f7de24d58d9d7215 | 2,209 | ex | Elixir | clients/drive/lib/google_api/drive/v3/model/permission_list.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/drive/lib/google_api/drive/v3/model/permission_list.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/drive/lib/google_api/drive/v3/model/permission_list.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Drive.V3.Model.PermissionList do
@moduledoc """
A list of permissions for a file.
## Attributes
- kind (String.t): Identifies what kind of resource this is. Value: the fixed string \"drive#permissionList\". Defaults to: `null`.
- nextPageToken (String.t): The page token for the next page of permissions. This field will be absent if the end of the permissions list has been reached. If the token is rejected for any reason, it should be discarded, and pagination should be restarted from the first page of results. Defaults to: `null`.
- permissions ([Permission]): The list of permissions. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kind => any(),
:nextPageToken => any(),
:permissions => list(GoogleApi.Drive.V3.Model.Permission.t())
}
field(:kind)
field(:nextPageToken)
field(:permissions, as: GoogleApi.Drive.V3.Model.Permission, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.Drive.V3.Model.PermissionList do
def decode(value, options) do
GoogleApi.Drive.V3.Model.PermissionList.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Drive.V3.Model.PermissionList do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.907407 | 310 | 0.740154 |
e839e9faaf8c40c0d6eaef34835415773ac9ee11 | 66 | ex | Elixir | lib/eecrit/old_repo.ex | marick/eecrit | 50b1ebeadc5cf21ea9f9df6add65e4d7037e2482 | [
"MIT"
] | 10 | 2016-07-15T15:57:33.000Z | 2018-06-09T00:40:46.000Z | lib/eecrit/old_repo.ex | marick/eecrit | 50b1ebeadc5cf21ea9f9df6add65e4d7037e2482 | [
"MIT"
] | null | null | null | lib/eecrit/old_repo.ex | marick/eecrit | 50b1ebeadc5cf21ea9f9df6add65e4d7037e2482 | [
"MIT"
] | 6 | 2016-07-15T15:57:41.000Z | 2018-03-22T16:38:00.000Z | defmodule Eecrit.OldRepo do
use Ecto.Repo, otp_app: :eecrit
end
| 16.5 | 33 | 0.772727 |
e839f625379404b56850424a8172e005d0362f6b | 1,298 | exs | Elixir | test/paginate_test.exs | devonestes/ex_admin | e135ae7c28de78fc87baf519ff8a32da12e8bf66 | [
"MIT"
] | 1,347 | 2015-10-05T18:23:49.000Z | 2022-01-09T18:38:36.000Z | test/paginate_test.exs | fanduel/ex_admin | 05806a718859a0e155d3447c3ffde8a536fd676a | [
"MIT"
] | 402 | 2015-10-03T13:53:32.000Z | 2021-07-08T09:52:22.000Z | test/paginate_test.exs | fanduel/ex_admin | 05806a718859a0e155d3447c3ffde8a536fd676a | [
"MIT"
] | 333 | 2015-10-12T22:56:57.000Z | 2021-05-26T18:40:24.000Z | defmodule ExAdmin.PaginateTest do
use ExUnit.Case
alias ExAdmin.Paginate
test "pagination_information name total" do
assert Paginate.pagination_information("Contacts", 10) == "Displaying <b>all 10</b> Contacts"
end
test "pagination_information/4" do
assert Paginate.pagination_information("Contacts", 1, 1, 10) ==
"Displaying Contact <b>1</b> of <b>10</b> in total"
end
test "pagination_information last" do
assert Paginate.pagination_information("Contacts", 1, 10, 100) ==
"Displaying Contacts <b>1 - 10</b> of <b>100</b> in total"
end
@link "/admin/contacts?order="
test "paginate fist page links" do
html = Paginate.paginate(@link, 1, 10, 11, 103, "Contacts")
items = Floki.find(html, "ul.pagination li")
assert Enum.count(items) == 7
assert Floki.find(hd(items), "li a") |> Floki.text() == "1"
items = Enum.reverse(items)
assert Floki.find(hd(items), "li a") |> Floki.attribute("href") ==
["/admin/contacts?order=&page=11"]
end
test "paginate fist page information" do
html = Paginate.paginate(@link, 1, 10, 11, 103, "Contacts")
text = Floki.find(html, "div") |> Floki.text()
assert text =~ "Displaying Contacts"
assert text =~ "1 - 10 of 103 in total"
end
end
| 34.157895 | 97 | 0.651772 |
e83a1fe9c7f8a0dacb471a37014434f0c18553ca | 1,644 | exs | Elixir | mix.exs | membraneframework/elixir_libnice | 5db244055282855aeaa520a6e4ae65cad34a084a | [
"Apache-2.0"
] | null | null | null | mix.exs | membraneframework/elixir_libnice | 5db244055282855aeaa520a6e4ae65cad34a084a | [
"Apache-2.0"
] | 1 | 2020-09-30T13:59:37.000Z | 2020-09-30T13:59:37.000Z | mix.exs | membraneframework/elixir_libnice | 5db244055282855aeaa520a6e4ae65cad34a084a | [
"Apache-2.0"
] | null | null | null | defmodule ExLibnice.MixProject do
use Mix.Project
@version "0.8.0"
@github_url "https://github.com/membraneframework/ex_libnice"
def project do
[
app: :ex_libnice,
version: @version,
elixir: "~> 1.10",
compilers: [:unifex, :bundlex] ++ Mix.compilers(),
elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod,
deps: deps(),
# hex
description: "Elixir wrapper over libnice",
package: package(),
# docs
name: "ExLibnice",
source_url: @github_url,
homepage_url: "https://membraneframework.org",
docs: docs()
]
end
def application do
[
mod: {ExLibnice.App, []},
extra_applications: [:logger]
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_env), do: ["lib"]
defp deps do
[
{:unifex, "~> 1.0"},
{:bunch, "~> 1.3.0"},
{:mdns, "~> 1.0.12"},
{:ex_doc, "~> 0.23", only: :dev, runtime: false},
{:dialyxir, "~> 1.0", only: :dev, runtime: false},
{:credo, "~> 1.5", only: :dev, runtime: false}
]
end
defp package do
[
maintainers: ["Membrane Team"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => @github_url,
"Membrane Framework Homepage" => "https://membraneframework.org"
},
files: ["lib", "mix.exs", "README*", "LICENSE*", ".formatter.exs", "bundlex.exs", "c_src"]
]
end
defp docs do
[
main: "readme",
extras: ["README.md", "LICENSE"],
source_ref: "v#{@version}",
nest_modules_by_prefix: [ExLibnice]
]
end
end
| 23.15493 | 96 | 0.550487 |
e83a7e0bf7cfb2db0cb013c459f4400f4292c0ae | 291 | ex | Elixir | test/support/conn_case.ex | uavaustin/flight-status | 8ccc3c21f7135aa2a2d600a4e66fc8f2995ac241 | [
"MIT"
] | null | null | null | test/support/conn_case.ex | uavaustin/flight-status | 8ccc3c21f7135aa2a2d600a4e66fc8f2995ac241 | [
"MIT"
] | null | null | null | test/support/conn_case.ex | uavaustin/flight-status | 8ccc3c21f7135aa2a2d600a4e66fc8f2995ac241 | [
"MIT"
] | null | null | null | defmodule FlightStatusWeb.ConnCase do
use ExUnit.CaseTemplate
using do
quote do
use Phoenix.ConnTest
import FlightStatusWeb.Router.Helpers
@endpoint FlightStatusWeb.Endpoint
end
end
setup _tags do
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 17.117647 | 46 | 0.71134 |
e83af906cd1556f55dd364aaef054d360a70de37 | 2,971 | ex | Elixir | clients/deployment_manager/lib/google_api/deployment_manager/v2/model/binding.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/deployment_manager/lib/google_api/deployment_manager/v2/model/binding.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/deployment_manager/lib/google_api/deployment_manager/v2/model/binding.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.DeploymentManager.V2.Model.Binding do
@moduledoc """
Associates `members` with a `role`.
## Attributes
* `condition` (*type:* `GoogleApi.DeploymentManager.V2.Model.Expr.t`, *default:* `nil`) - Unimplemented. The condition that is associated with this binding. NOTE: an unsatisfied condition will not allow user access via current binding. Different bindings, including their conditions, are examined independently.
* `members` (*type:* `list(String.t)`, *default:* `nil`) - Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following values:
* `allUsers`: A special identifier that represents anyone who is on the internet; with or without a Google account.
* `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated with a Google account or a service account.
* `user:{emailid}`: An email address that represents a specific Google account. For example, `alice@gmail.com` .
* `serviceAccount:{emailid}`: An email address that represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`.
* `group:{emailid}`: An email address that represents a Google group. For example, `admins@example.com`.
* `domain:{domain}`: A Google Apps domain name that represents all the users of that domain. For example, `google.com` or `example.com`.
* `role` (*type:* `String.t`, *default:* `nil`) - Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:condition => GoogleApi.DeploymentManager.V2.Model.Expr.t(),
:members => list(String.t()),
:role => String.t()
}
field(:condition, as: GoogleApi.DeploymentManager.V2.Model.Expr)
field(:members, type: :list)
field(:role)
end
defimpl Poison.Decoder, for: GoogleApi.DeploymentManager.V2.Model.Binding do
def decode(value, options) do
GoogleApi.DeploymentManager.V2.Model.Binding.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DeploymentManager.V2.Model.Binding do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 43.057971 | 315 | 0.728374 |
e83b03bcbd8f23af34678f5da9e3a063048f49cb | 1,629 | ex | Elixir | clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_byte_content_item.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_byte_content_item.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_byte_content_item.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.DLP.V2.Model.GooglePrivacyDlpV2ByteContentItem do
@moduledoc """
Container for bytes to inspect or redact.
## Attributes
* `data` (*type:* `String.t`, *default:* `nil`) - Content data to inspect or redact.
* `type` (*type:* `String.t`, *default:* `nil`) - The type of data stored in the bytes string. Default will be TEXT_UTF8.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:data => String.t() | nil,
:type => String.t() | nil
}
field(:data)
field(:type)
end
defimpl Poison.Decoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2ByteContentItem do
def decode(value, options) do
GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2ByteContentItem.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2ByteContentItem do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.58 | 125 | 0.724985 |
e83b1252fb2107bffae279957bec3dd339bba3bb | 3,364 | exs | Elixir | priv/templates/phx.gen.context/test_cases.exs | zoosky/phoenix | 8c90262009652390286dd6150bed513f6a3e6150 | [
"MIT"
] | null | null | null | priv/templates/phx.gen.context/test_cases.exs | zoosky/phoenix | 8c90262009652390286dd6150bed513f6a3e6150 | [
"MIT"
] | null | null | null | priv/templates/phx.gen.context/test_cases.exs | zoosky/phoenix | 8c90262009652390286dd6150bed513f6a3e6150 | [
"MIT"
] | null | null | null |
describe "<%= schema.plural %>" do
alias <%= inspect schema.module %>
@valid_attrs <%= inspect schema.params.create %>
@update_attrs <%= inspect schema.params.update %>
@invalid_attrs <%= inspect for {key, _} <- schema.params.create, into: %{}, do: {key, nil} %>
def <%= schema.singular %>_fixture(attrs \\ %{}) do
{:ok, <%= schema.singular %>} =
attrs
|> Enum.into(@valid_attrs)
|> <%= inspect context.alias %>.create_<%= schema.singular %>()
<%= schema.singular %>
end
test "list_<%= schema.plural %>/0 returns all <%= schema.plural %>" do
<%= schema.singular %> = <%= schema.singular %>_fixture()
assert <%= inspect context.alias %>.list_<%= schema.plural %>() == [<%= schema.singular %>]
end
test "get_<%= schema.singular %>!/1 returns the <%= schema.singular %> with given id" do
<%= schema.singular %> = <%= schema.singular %>_fixture()
assert <%= inspect context.alias %>.get_<%= schema.singular %>!(<%= schema.singular %>.id) == <%= schema.singular %>
end
test "create_<%= schema.singular %>/1 with valid data creates a <%= schema.singular %>" do
assert {:ok, %<%= inspect schema.alias %>{} = <%= schema.singular %>} = <%= inspect context.alias %>.create_<%= schema.singular %>(@valid_attrs)<%= for {field, value} <- schema.params.create do %>
assert <%= schema.singular %>.<%= field %> == <%= Mix.Phoenix.Schema.value(schema, field, value) %><% end %>
end
test "create_<%= schema.singular %>/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} = <%= inspect context.alias %>.create_<%= schema.singular %>(@invalid_attrs)
end
test "update_<%= schema.singular %>/2 with valid data updates the <%= schema.singular %>" do
<%= schema.singular %> = <%= schema.singular %>_fixture()
assert {:ok, %<%= inspect schema.alias %>{} = <%= schema.singular %>} = <%= inspect context.alias %>.update_<%= schema.singular %>(<%= schema.singular %>, @update_attrs)
<%= for {field, value} <- schema.params.update do %>
assert <%= schema.singular %>.<%= field %> == <%= Mix.Phoenix.Schema.value(schema, field, value) %><% end %>
end
test "update_<%= schema.singular %>/2 with invalid data returns error changeset" do
<%= schema.singular %> = <%= schema.singular %>_fixture()
assert {:error, %Ecto.Changeset{}} = <%= inspect context.alias %>.update_<%= schema.singular %>(<%= schema.singular %>, @invalid_attrs)
assert <%= schema.singular %> == <%= inspect context.alias %>.get_<%= schema.singular %>!(<%= schema.singular %>.id)
end
test "delete_<%= schema.singular %>/1 deletes the <%= schema.singular %>" do
<%= schema.singular %> = <%= schema.singular %>_fixture()
assert {:ok, %<%= inspect schema.alias %>{}} = <%= inspect context.alias %>.delete_<%= schema.singular %>(<%= schema.singular %>)
assert_raise Ecto.NoResultsError, fn -> <%= inspect context.alias %>.get_<%= schema.singular %>!(<%= schema.singular %>.id) end
end
test "change_<%= schema.singular %>/1 returns a <%= schema.singular %> changeset" do
<%= schema.singular %> = <%= schema.singular %>_fixture()
assert %Ecto.Changeset{} = <%= inspect context.alias %>.change_<%= schema.singular %>(<%= schema.singular %>)
end
end
| 54.258065 | 202 | 0.601962 |
e83b1629fd0736a7b19b9ef5cc495100d1751821 | 4,244 | ex | Elixir | lib/platform/video/video_processing.ex | lucab85/audioslides.io | cb502ccf6ed0b2db42d9fb20bb4c963bcca3cfa9 | [
"MIT"
] | 17 | 2017-11-14T14:03:18.000Z | 2021-12-10T04:18:48.000Z | lib/platform/video/video_processing.ex | lucab85/audioslides.io | cb502ccf6ed0b2db42d9fb20bb4c963bcca3cfa9 | [
"MIT"
] | 21 | 2017-11-19T13:38:07.000Z | 2022-02-10T00:11:14.000Z | lib/platform/video/video_processing.ex | lucab85/audioslides.io | cb502ccf6ed0b2db42d9fb20bb4c963bcca3cfa9 | [
"MIT"
] | 2 | 2019-09-03T03:32:13.000Z | 2021-02-23T21:52:57.000Z | defmodule Platform.VideoProcessing do
@moduledoc """
Context for the video converter
"""
require Logger
alias Filename
alias FileHelper
alias Platform.Speech
alias VideoConverter
alias Platform.VideoHelper
alias Platform.Core
alias Platform.Core.Schema.Lesson
alias Platform.Core.Schema.Slide
def merge_videos(lesson) do
Logger.info("Videos for Lesson ##{lesson.id} will be merged ...")
generated_video_filenames = Enum.map(lesson.slides, fn slide -> Filename.get_relative_filename_for_slide_video(lesson, slide) end)
final_output_filename = Filename.get_filename_for_lesson_video(lesson)
VideoConverter.merge_videos(
video_filename_list: generated_video_filenames,
output_filename: final_output_filename
)
duration_in_seconds =
final_output_filename
|> VideoConverter.get_duration()
|> parse_duration()
Core.update_lesson(lesson, %{duration: duration_in_seconds, video_hash: VideoHelper.generate_video_hash(lesson)})
Logger.info("Lesson ##{lesson.id} merge complete")
end
def parse_duration(<<minutes_as_string::bytes-size(2)>> <> ":" <> <<seconds_as_string::bytes-size(2)>> <> "." <> miliseconds_as_string), do: parse_duration("00:#{minutes_as_string}:#{seconds_as_string}.#{miliseconds_as_string}")
def parse_duration(<<hours_as_string::bytes-size(2)>> <> ":" <> <<minutes_as_string::bytes-size(2)>> <> ":" <> <<seconds_as_string::bytes-size(2)>> <> "." <> _miliseconds_as_string) do
hours = String.to_integer(hours_as_string)
minutes = String.to_integer(minutes_as_string)
seconds = String.to_integer(seconds_as_string)
seconds + (minutes * 60) + (hours * 3600)
end
def parse_duration(_), do: 0
def generate_video_for_slide(%Lesson{} = lesson, %Slide{} = slide) do
image_filename = create_or_update_image_for_slide(lesson, slide)
audio_filename = create_or_update_audio_for_slide(lesson, slide)
# Get current slide-data to check for newest hash
slide = Core.get_slide!(slide.id)
# Only generate video of audio or video changed
if VideoHelper.generate_video_hash(slide) != slide.video_hash do
Logger.info("Slide #{slide.id} Video: need update")
video_filename = Filename.get_filename_for_slide_video(lesson, slide)
Core.update_slide(slide, %{video_sync_pid: self()})
VideoConverter.generate_video(
image_filename: image_filename,
audio_filename: audio_filename,
output_filename: video_filename
)
Core.update_slide_video_hash(slide, VideoHelper.generate_video_hash(slide))
Core.update_slide(slide, %{video_sync_pid: nil})
Logger.info("Slide #{slide.id} Video: generated")
else
Logger.info("Slide #{slide.id} Video: skipped")
end
end
def create_or_update_image_for_slide(lesson, slide) do
if slide.page_elements_hash != slide.image_hash do
Logger.info("Slide #{slide.id} Image: need update")
Core.update_slide(slide, %{image_sync_pid: self()})
Core.download_thumb!(lesson, slide)
Core.update_slide_image_hash(slide, slide.page_elements_hash)
Core.update_slide(slide, %{image_sync_pid: nil})
Logger.info("Slide #{slide.id} Image: generated")
else
Logger.info("Slide #{slide.id} Image: skipped")
end
Filename.get_filename_for_slide_image(lesson, slide)
end
def create_or_update_audio_for_slide(lesson, slide) do
audio_filename = Filename.get_filename_for_slide_audio(lesson, slide)
if slide.speaker_notes_hash != slide.audio_hash do
Logger.info("Slide #{slide.id} Audio: need update")
Core.update_slide(slide, %{audio_sync_pid: self()})
speech_binary =
Speech.run(%{
"language_key" => lesson.voice_language,
"voice_gender" => lesson.voice_gender,
"text" => slide.speaker_notes || "<break time=\"800ms\"/>"
})
FileHelper.write_to_file(audio_filename, speech_binary)
Core.update_slide_audio_hash(slide, slide.speaker_notes_hash)
Core.update_slide(slide, %{audio_sync_pid: nil})
Logger.info("Slide #{slide.id} Audio: generated")
else
Logger.info("Slide #{slide.id} Audio: skipped")
end
audio_filename
end
end
| 34.225806 | 230 | 0.711357 |
e83b1a7ffc0b57f22c82b3742871f06055ffd7d6 | 1,182 | exs | Elixir | mix.exs | simonmcconnell/msgpax_serializer | 985980a016a08f7ad80cef1d90272624843aebd1 | [
"MIT"
] | null | null | null | mix.exs | simonmcconnell/msgpax_serializer | 985980a016a08f7ad80cef1d90272624843aebd1 | [
"MIT"
] | 1 | 2022-02-01T08:00:00.000Z | 2022-02-01T08:00:00.000Z | mix.exs | simonmcconnell/msgpax_serializer | 985980a016a08f7ad80cef1d90272624843aebd1 | [
"MIT"
] | null | null | null | defmodule MsgpaxSerializer.MixProject do
use Mix.Project
@version "0.1.0"
@github_url "https://github.com/simonmcconnell/msgpax_serializer"
def project do
[
app: :msgpax_serializer,
version: @version,
elixir: "~> 1.9",
start_permanent: Mix.env() == :prod,
deps: deps(),
package: package(),
docs: [
source_url: @github_url,
source_ref: "v#{@version}",
main: "readme",
extras: ["README.md"]
]
]
end
def application do
[extra_applications: [:logger]]
end
defp deps do
[
{:msgpax, "~> 2.0", optional: true},
{:phoenix, "~> 1.3", only: [:dev, :test]},
{:jason, "~> 1.0", only: [:dev, :test]},
{:phoenix_gen_socket_client, "~> 4.0", only: [:dev, :test]},
{:websocket_client, "~> 1.2", only: [:dev, :test]},
{:ex_doc, "~> 0.28", only: :dev, runtime: false}
]
end
defp package do
[
links: %{
"GitHub" => @github_url,
"Msgpax" => "https://github.com/lexmag/msgpax",
"phoenix_gen_socket_client" => "https://github.com/J0/phoenix_gen_socket_client"
},
licenses: ["MIT"]
]
end
end
| 23.64 | 88 | 0.543993 |
e83b2227a6a799ae3160eacdebe4330e233e6715 | 12,728 | ex | Elixir | lib/votr/stv.ex | wjanssens/votr | 4fdd2a6e5ac9178a7fa90578f75a248e2bf161b6 | [
"MIT"
] | 1 | 2018-04-27T09:43:27.000Z | 2018-04-27T09:43:27.000Z | lib/votr/stv.ex | wjanssens/votr | 4fdd2a6e5ac9178a7fa90578f75a248e2bf161b6 | [
"MIT"
] | null | null | null | lib/votr/stv.ex | wjanssens/votr | 4fdd2a6e5ac9178a7fa90578f75a248e2bf161b6 | [
"MIT"
] | null | null | null | # TODO implement Borda method
# TODO implement Condorcet method
# TODO implement Block Plurality (multiple seats, unranked votes)
# TODO implement dynamic vs static threshold option
# TODO implement STV tie breaking options (backwards, random)
# TODO implement overvote and undervote handling options and reporting
# TODO implement Meek STV
# TODO implement Baas STV
# TODO implement weighted votes
defmodule Votr.Stv do
@moduledoc """
Provides Ranked (STV, IRV), and Unranked (FPTP) ballot evaluation.
* STV uses a quota to determine when a candidate is elected in rounds.
Droop, Hare, Impirali, and Hagenbach Bischoff quotas are available.
* IRV is a degenerate case of STV where only one seat is elected,
* FPTP is a degenerate case of IRV where ballots have no rankings and thus
no distribution can be performed.
"""
@doc """
Evaluates an election.
* `ballots` a list of ballots;
with ranked votes for STV and IRV, or unranked votes for FPTP.
* `seats` the number of seats to elect; 1 for AV and FPTP, or > 1 for STV
* Undervoting is handled by always choosing the candidate with least rank
(i.e. absolute rank isn't important, only relative rank is)
* Overvoting is handled by choosing one of the candidates (in ballot order)
and deferring the other(s) into the next round
## Ballots
Ballots are in the form of a list of maps where each map key is the
candidate and each map value is the ranking.
A ballot for FPTP should have only one key and a rank of 1.
The key should may be either a string or a number.
```
[ %{weight: 1.5, vote: %{"a" => 1, "b" => 2, ...} },
%{weight: 1.0, vote: %{"c" => 1, "d" => 2, ...} },
...
]
```
## Results
Results are in the form of a map with an entry for each candidate.
Each candidate is represented with a map of the following values:
* `round` is the round that a candidate was :elected or :excluded in,
or not present for candidates that weren't considered in any round
* `votes` is the number of they obtained
(which may not be an integer if there was fractional distrution)
* `surplus` is the number of votes that they obtained beyond the quota which
may be transferred to next choice candidates. There will not be a surplus
for excluded candidates
* `exhausted` is the number of votes that could not be transferred because
there were no next choice candidates to choose from.
* `status` is `:elected`, `:excluded`,
or not present for candidates that weren't considered in any round
```
%{
"a" => %{round: 1, status: :elected, votes: 40.0, surplus: 20.0, exhausted: 0},
"b" => %{round: 2, status: :excluded, votes: 8.0, exhausted: 0},
"c" => %{round: 3, status: :elected, votes: 20.0, surplus: 0.0, exhausted: 0},
"d" => %{votes: 17.0}
}
```
## Options
* `:quota` - the quota will be calculated according to
`:imperali`, `:hare`, `:hagenbach_bischoff`, or `:droop` formulas; defaults to `:droop`
* `:threshold` - the quota will be a `:whole` number or a `:fractional` number
"""
def eval(ballots, seats, options \\ []) do
# find the unique list of candidates from all the ballots
candidates =
ballots
|> Stream.map(fn b -> b.candidates end)
|> Stream.flat_map(fn v -> Map.keys(v) end)
|> Stream.uniq()
# create a result that has an empty entry for every candidate
# and perform the initial vote distribution
this_round =
candidates
|> Enum.reduce(%{}, fn c, acc -> Map.put(acc, c, %{votes: 0}) end)
|> distribute(ranked_votes(ballots))
|> Map.put(:exhausted, %{votes: 0})
sum = ballots
|> Enum.map(fn b -> b.weight end)
|> Enum.sum()
Enum.count(ballots)
quota =
case seats do
1 ->
# make the quota a pure majority (equivalent to hagenbach_bischoff)
sum / 2
_ ->
# calculate the number of votes it takes to be elected
case Keyword.get(options, :quota, :droop) do
:imperali -> sum / (seats + 2)
:hare -> sum / seats
:hagenbach_bischoff -> Float.floor(sum / (seats + 1))
_ -> sum / (seats + 1) + 1
end
end
quota =
case Keyword.get(options, :threshold, :whole) do
:fractional -> quota
_ -> Float.floor(quota)
end
eval([this_round], ballots, 1, 0, seats, quota, options)
end
# Recursively evaluate the subsequent rounds of the ranked election.
# Returns updated results.
defp eval(result, ballots, round, elected, seats, quota, options \\ []) do
[last_round | _] = result
remaining = last_round
|> Stream.filter(fn {k, _} -> k != :exhausted end)
|> Enum.count(fn {_, v} -> !Map.has_key?(v, :status) end)
cond do
seats == elected ->
# all the seats are filled so end the recursion
result
remaining == 1 ->
# only one canditate left standing, so they are elected regardless of meeting quota
{elected_candidate, elected_result} =
last_round
|> Stream.filter(fn {k, _} -> k != :exhausted end)
|> Enum.find(fn {_, v} -> !Map.has_key?(v, :status) end)
elected_result =
elected_result
|> Map.delete(:received)
|> Map.put(:surplus, elected_result.votes - quota)
|> Map.put(:status, :elected)
|> Map.put(:votes, quota)
this_round = last_round
|> Map.put(elected_candidate, elected_result)
|> Map.put(:exhausted, Map.delete(Map.get(last_round, :exhausted), :received))
[this_round | result]
true ->
# find the candidate with the most votes
{elected_candidate, elected_result} =
last_round
|> Stream.filter(fn {k, _} -> k != :exhausted end)
|> Stream.filter(fn {_, v} -> !Map.has_key?(v, :status) end)
|> Enum.max_by(fn {_, v} -> v.votes end)
if elected_result.votes >= quota do
# candidate has enough votes to be elected
surplus = elected_result.votes - quota
# update the result for the elected candidate
elected_result =
elected_result
|> Map.delete(:received)
|> Map.put(:status, :elected)
|> Map.put(:surplus, surplus)
|> Map.put(:votes, quota)
this_round = last_round
|> Map.put(elected_candidate, elected_result)
|> distribute(ballots, elected_candidate, surplus)
# perform the next round using ballots that exclude the elected candidate
eval([this_round | result], ballots, round + 1, elected + 1, seats, quota, options)
else
# a candidate must be excluded
# find the candidate with the least votes
{excluded_candidate, excluded_result} =
last_round
|> Stream.filter(fn {k, _} -> k != :exhausted end)
|> Stream.filter(fn {_, v} -> !Map.has_key?(v, :status) end)
|> Enum.min_by(fn {_, v} -> v.votes end)
surplus = excluded_result.votes;
# update the result for the excluded candidate
excluded_result =
excluded_result
|> Map.delete(:received)
|> Map.put(:status, :excluded)
|> Map.put(:surplus, surplus)
|> Map.put(:votes, 0)
this_round = last_round
|> Map.put(excluded_candidate, excluded_result)
|> distribute(ballots, excluded_candidate, surplus)
# perform the next round using ballots that exclude the elected candidate
eval([this_round | result], ballots, round + 1, elected, seats, quota, options)
end
end
end
@doc """
Converts ranked ballots into unranked ballots.
This is useful for conducting a simulated plurality election from ranked ballots.
"""
def unranked(ballots) do
ballots
|> Stream.map(
fn b ->
{candidate, _} = Enum.min_by(b, fn {_, v} -> v end, {:nobody, 0})
%{candidate => 1}
end
)
end
# Returns a map of how many votes a candidates has obtained
defp ranked_votes(ballots) do
# count the number of "first" choice votes for each candidate
ballots
|> Stream.map(
fn b ->
# vote(s) with the lowest rank
# candidate from the vote
c = b.candidates
|> Enum.filter(fn {k, _} -> k != :exhausted end)
|> Enum.min_by(fn {_, v} -> v end, fn -> {:exhausted, 0} end)
|> Tuple.to_list()
|> List.first()
%{w: b.weight, c: c}
end
)
|> Enum.reduce(%{}, fn %{c: c, w: w}, a -> Map.update(a, c, 1 * w, &(&1 + (1 * w))) end)
end
# Applies initial vote distribution to result for all candidates.
# Returns updated results.
defp distribute(result, counts) do
Enum.reduce(
result,
%{},
fn {rk, rv}, a ->
# vote count for the current candidate
cv = Map.get(counts, rk, 0)
# update result row for candidate
Map.put(a, rk, Map.update(rv, :votes, 0, &(&1 + cv)))
end
)
end
# Applies subsequent vote distribution to result for the elected or excluded candidate
# Returns updated results.
defp distribute(result, ballots, candidate, surplus) do
# ignore all previously elected and excluded candidates during distribution
ineligible = result
|> Enum.reduce(
[],
fn {c, v}, acc ->
if Map.has_key?(v, :status) do
[c | acc]
else
acc
end
end
)
|> List.delete(candidate)
# find the ballots that were used to elect / exclude this candidate
ballots_to_distribute = ballots
|> Stream.map(
fn ballot ->
Map.update!(
ballot,
:candidates,
fn candidates ->
candidates
|> Map.drop([:exhausted | ineligible])
end
)
end
)
|> Stream.filter(
fn ballot ->
ballot.candidates
|> Enum.min_by(fn {_, rank} -> rank end, fn -> {:exhausted, 0} end)
|> Tuple.to_list()
|> Enum.member?(candidate)
end
)
|> Enum.map(
fn ballot ->
Map.update!(
ballot,
:candidates,
fn candidates ->
candidates
|> Map.drop([candidate])
end
)
end
)
# the weight of the distribution, not the voter's weight
weight = ballots_to_distribute
|> Enum.map(fn ballot -> ballot.weight end)
|> Enum.sum
counts = ranked_votes(ballots_to_distribute)
result
|> Enum.reduce(
%{},
fn {rk, rv}, a ->
if Map.has_key?(rv, :status) do
Map.put(a, rk, rv)
else
# vote count for the current candidate
count = Map.get(counts, rk, 0)
# update result row for candidate
# TODO implement configurable precision
received = Float.round(surplus / weight * count, 5)
if received > 0 do
rv = rv
|> Map.delete(:surplus)
|> Map.put(:received, received)
|> Map.update(:votes, received, &(&1 + received))
Map.put(a, rk, rv)
else
rv = rv
|> Map.delete(:received)
|> Map.delete(:surplus)
Map.put(a, rk, rv)
end
end
end
)
end
end
| 37.216374 | 102 | 0.529777 |
e83b307db922174a210193c9548fa294f701367f | 586 | exs | Elixir | mix.exs | IanLuites/kvasir_pub_sub | 2059f18bbf88612f66e4292625b81edf3d970ba0 | [
"MIT"
] | null | null | null | mix.exs | IanLuites/kvasir_pub_sub | 2059f18bbf88612f66e4292625b81edf3d970ba0 | [
"MIT"
] | null | null | null | mix.exs | IanLuites/kvasir_pub_sub | 2059f18bbf88612f66e4292625b81edf3d970ba0 | [
"MIT"
] | null | null | null | defmodule Kvasir.PubSub.MixProject do
use Mix.Project
def project do
[
app: :kvasir_pub_sub,
version: "0.1.0",
elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {Kvasir.PubSub.Application, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:common_x, ">= 0.0.0"},
{:jason, ">= 1.2.0"},
{:ranch, "~> 2.0"}
]
end
end
| 18.903226 | 59 | 0.551195 |
e83b46c5cca351814e2623ff9be9deaf9859dabc | 2,310 | exs | Elixir | mix.exs | riosvictor/rockelivery | d34c8ccd76f95bb5bc8131f8ef1fb9111f554ebb | [
"MIT"
] | 1 | 2022-03-16T20:41:29.000Z | 2022-03-16T20:41:29.000Z | mix.exs | riosvictor/rockelivery | d34c8ccd76f95bb5bc8131f8ef1fb9111f554ebb | [
"MIT"
] | null | null | null | mix.exs | riosvictor/rockelivery | d34c8ccd76f95bb5bc8131f8ef1fb9111f554ebb | [
"MIT"
] | null | null | null | defmodule Rockelivery.MixProject do
use Mix.Project
def project do
[
app: :rockelivery,
version: "0.1.0",
elixir: "~> 1.12",
elixirc_paths: elixirc_paths(Mix.env()),
compilers: [:gettext] ++ Mix.compilers(),
start_permanent: Mix.env() == :prod,
aliases: aliases(),
deps: deps(),
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
]
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {Rockelivery.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.6.2"},
{:phoenix_ecto, "~> 4.4"},
{:ecto_sql, "~> 3.6"},
{:postgrex, ">= 0.0.0"},
{:phoenix_live_dashboard, "~> 0.5"},
{:swoosh, "~> 1.3"},
{:telemetry_metrics, "~> 0.6"},
{:telemetry_poller, "~> 1.0"},
{:gettext, "~> 0.18"},
{:jason, "~> 1.2"},
{:plug_cowboy, "~> 2.5"},
{:pbkdf2_elixir, "~> 1.4"},
{:ex_machina, "~> 2.7.0"},
{:tesla, "~> 1.4"},
{:hackney, "~> 1.17"},
{:guardian, "~> 2.0"},
# DEV TEST
{:credo, "~> 1.6", only: [:dev, :test], runtime: false},
# TEST
{:excoveralls, "~> 0.10", only: :test},
{:bypass, "~> 2.1", only: :test},
{:mox, "~> 1.0", only: :test}
]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, to install project dependencies and perform other setup tasks, run:
#
# $ mix setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
[
setup: ["deps.get", "ecto.setup"],
"ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
"ecto.reset": ["ecto.drop", "ecto.setup"],
test: ["ecto.create --quiet", "ecto.migrate --quiet", "test"]
]
end
end
| 27.176471 | 84 | 0.547186 |
e83b4a326188442b15511a489c8bfa404967001f | 682 | ex | Elixir | lib/brando_admin/live/pages/page_fragment_create_live.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 4 | 2020-10-30T08:40:38.000Z | 2022-01-07T22:21:37.000Z | lib/brando_admin/live/pages/page_fragment_create_live.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 1,162 | 2020-07-05T11:20:15.000Z | 2022-03-31T06:01:49.000Z | lib/brando_admin/live/pages/page_fragment_create_live.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | null | null | null | defmodule BrandoAdmin.Pages.PageFragmentCreateLive do
use BrandoAdmin.LiveView.Form, schema: Brando.Pages.Fragment
alias BrandoAdmin.Components.Content
alias BrandoAdmin.Components.Form
import Brando.Gettext
def mount(%{"page_id" => page_id, "language" => language}, assigns, socket) do
{:ok,
socket
|> assign(assigns)
|> assign(:initial_params, %{page_id: page_id, language: language})}
end
def render(assigns) do
~F"""
<Content.Header
title={gettext("Create fragment")} />
<Form
id="fragment_form"
current_user={@current_user}
schema={@schema}
initial_params={@initial_params}
/>
"""
end
end
| 24.357143 | 80 | 0.668622 |
e83b4f2c7ca864edf66194600ecd356ad0f63280 | 4,949 | ex | Elixir | lib/majudge.ex | coltonw/majudge | 4f81a66abe6a2e82f42131982e7a9b26951b9124 | [
"MIT"
] | null | null | null | lib/majudge.ex | coltonw/majudge | 4f81a66abe6a2e82f42131982e7a9b26951b9124 | [
"MIT"
] | 1 | 2021-05-10T04:23:56.000Z | 2021-05-10T04:23:56.000Z | lib/majudge.ex | coltonw/majudge | 4f81a66abe6a2e82f42131982e7a9b26951b9124 | [
"MIT"
] | null | null | null | defmodule Majudge do
@moduledoc """
Majudge keeps the contexts that define your domain
and business logic.
Contexts are also responsible for managing your data, regardless
if it comes from the database, an external API or others.
"""
@default_ratings [:excellent, :verygood, :good, :average, :fair, :poor]
defmodule Candidate do
@derive {Jason.Encoder, only: [:name, :id, :thumbnail, :value]}
defstruct name: "Unknown", id: nil, thumbnail: nil, value: [], distance: []
end
# to simplify readability, I will be using the symbols:
# excellent, verygood, good, average, fair, poor
# Find the number of median votes that must be removed
# before the rating would change to the given rating.
# above_cur is the total number of ratings that are
# higher than the current rating.
# This function assumes that the median value is equal
# to or lower than the given rating.
def _distance_above(rating_votes, total, above_cur) do
rating_and_above = rating_votes + above_cur
cond do
rating_and_above >= total / 2 ->
{0, rating_and_above}
true ->
{total - rating_and_above * 2, rating_and_above}
end
end
# Find the number of median votes that must be removed
# before the rating would change to the given rating.
# above_cur is the total number of ratings that are
# higher than the current rating.
# This function assumes that the median value is equal
# to or lower than the given rating.
def _distance_below(rating_votes, total, below_cur) do
rating_and_below = rating_votes + below_cur
cond do
rating_and_below > total / 2 ->
{0, rating_and_below}
true ->
{total - rating_and_below * 2 + 1, rating_and_below}
end
end
def _distance(
ratings,
tallies,
total,
distance_helper \\ &_distance_above/3,
accum_votes \\ 0,
accum_result \\ []
)
def _distance([rating | rest], tallies, total, distance_helper, accum_votes, accum_result) do
case tallies do
%{^rating => rating_votes} ->
{dist, accum_votes} = distance_helper.(rating_votes, total, accum_votes)
accum_result = accum_result ++ [{rating, dist}]
if dist == 0 do
distance_helper = &_distance_below/3
accum_votes = 0
ratings_rev = Enum.reverse(rest)
_distance(ratings_rev, tallies, total, distance_helper, accum_votes, accum_result)
else
_distance(rest, tallies, total, distance_helper, accum_votes, accum_result)
end
_ ->
_distance(rest, tallies, total, distance_helper, accum_votes, accum_result)
end
end
def _distance(_, _, _, _, _, accum_result) do
accum_result
end
# find the number of median votes that must be removed for each rating
def distance(tallies, ratings \\ @default_ratings) do
total = Enum.sum(Map.values(tallies))
result = _distance(ratings, tallies, total)
Enum.sort(result, fn a, b -> elem(a, 1) <= elem(b, 1) end)
end
# could easily be converted to a function which creates a compare function from a given list of ratings
def _compare_rating(a, b) do
Enum.find_index(@default_ratings, &(&1 == a)) <= Enum.find_index(@default_ratings, &(&1 == b))
end
def _compare([], []) do
true
end
def _compare(_, []) do
true
end
def _compare([], _) do
false
end
def _compare([{a_rating, _}], [{b_rating, _}]) do
_compare_rating(a_rating, b_rating)
end
def _compare([{same_rating, _} | a_tail], [{same_rating, _}] = b) do
_compare(a_tail, b)
end
def _compare([{same_rating, _}] = a, [{same_rating, _} | b_tail]) do
_compare(a, b_tail)
end
def _compare([{same_rating, _}, a_next | a_tail] = a, [{same_rating, _}, b_next | b_tail] = b) do
a_dist = elem(a_next, 1)
b_dist = elem(b_next, 1)
cond do
a_dist < b_dist ->
_compare([a_next | a_tail], b)
a_dist > b_dist ->
_compare(a, [b_next | b_tail])
a_dist == b_dist ->
_compare([a_next | a_tail], [b_next | b_tail])
end
end
def _compare([{a_rating, _} | _], [{b_rating, _} | _]) do
_compare_rating(a_rating, b_rating)
end
def sort(distances) do
Enum.sort(distances, &_compare/2)
end
def _compare_candidates(%Candidate{distance: a}, %Candidate{distance: b}) do
_compare(a, b)
end
def sort_candidates(candidates) do
Enum.sort(candidates, &_compare_candidates/2)
end
def count_one(vote, outer_acc) do
Enum.reduce(vote, outer_acc, fn {candId, rating}, acc ->
candMap = Map.get(acc, candId, %{})
curCount = Map.get(candMap, rating, 0)
Map.put(acc, candId, Map.put(candMap, rating, curCount + 1))
end)
end
def count(votes, acc \\ %{})
def count(nil, acc) do
acc
end
def count([], acc) do
acc
end
def count([vote | tail], acc) do
count(tail, count_one(vote, acc))
end
end
| 27.494444 | 105 | 0.650232 |
e83b4feaed4c105df1885bd08dc06e01c3a9a9af | 967 | ex | Elixir | clients/line_social_api/lib/line/social_api/profile.ex | wingyplus/elixir-line-sdk | e2e9518747237aac1f6edee0d4b9c546277a1dd0 | [
"MIT"
] | null | null | null | clients/line_social_api/lib/line/social_api/profile.ex | wingyplus/elixir-line-sdk | e2e9518747237aac1f6edee0d4b9c546277a1dd0 | [
"MIT"
] | null | null | null | clients/line_social_api/lib/line/social_api/profile.ex | wingyplus/elixir-line-sdk | e2e9518747237aac1f6edee0d4b9c546277a1dd0 | [
"MIT"
] | null | null | null | defmodule LINE.SocialAPI.Profile.UserProfile do
defstruct [:display_name, :user_id, :picture_url, :status_message]
def from_map(user_profile) when is_map(user_profile) do
%__MODULE__{
display_name: user_profile["displayName"],
user_id: user_profile["userId"],
picture_url: user_profile["pictureUrl"],
status_message: user_profile["statusMessage"]
}
end
end
defmodule LINE.SocialAPI.Profile do
alias LINE.SocialAPI.Profile.UserProfile
use Tesla
adapter Tesla.Adapter.Mint
plug Tesla.Middleware.BaseUrl, "https://api.line.me"
plug Tesla.Middleware.DecodeJson
def get_user_profile(access_token) do
get("/v2/profile", headers: [{"authorization", "Bearer #{access_token}"}])
|> case do
{:ok, %Tesla.Env{status: 200, body: body}} ->
{:ok, body |> UserProfile.from_map()}
{:ok, %Tesla.Env{body: body}} ->
{:error, body}
{:error, _} = error ->
error
end
end
end
| 26.135135 | 78 | 0.672182 |
e83b9fbc087eb35e0d208a91ca9411639dfcc47b | 3,601 | ex | Elixir | lib/singyeong/gateway/encoding.ex | queer/singyeong | 3d2f5c1052100ed70bb3a4dddd8e22e3ef0df15a | [
"BSD-3-Clause"
] | 70 | 2018-10-25T06:06:37.000Z | 2022-03-14T19:51:56.000Z | lib/singyeong/gateway/encoding.ex | queer/singyeong | 3d2f5c1052100ed70bb3a4dddd8e22e3ef0df15a | [
"BSD-3-Clause"
] | 140 | 2019-02-19T06:52:59.000Z | 2022-03-01T11:13:41.000Z | lib/singyeong/gateway/encoding.ex | queer/singyeong | 3d2f5c1052100ed70bb3a4dddd8e22e3ef0df15a | [
"BSD-3-Clause"
] | 9 | 2019-03-20T12:17:28.000Z | 2021-03-11T18:51:00.000Z | defmodule Singyeong.Gateway.Encoding do
@moduledoc false
alias Phoenix.Socket
alias Singyeong.Gateway.Payload
alias Singyeong.Utils
require Logger
@valid_encodings [
"json",
"msgpack",
"etf",
]
@spec validate_encoding(binary()) :: boolean()
def validate_encoding(encoding) when is_binary(encoding), do: encoding in @valid_encodings
@spec encode(Socket.t(), {any(), any()} | Payload.t()) :: {:binary, any()} | {:text, binary()}
def encode(socket, data) do
encoding = socket.assigns[:encoding] || "json"
case data do
{_, payload} ->
encode_real encoding, payload
_ ->
encode_real encoding, data
end
end
@spec encode_real(binary(), any()) :: {:binary, binary()} | {:text, binary()}
def encode_real(encoding, payload) do
payload = to_outgoing payload
case encoding do
"json" ->
{:ok, term} = Jason.encode payload
{:text, term}
"msgpack" ->
{:ok, term} = Msgpax.pack payload
# msgpax returns iodata, so we convert it to binary for consistency
{:binary, IO.iodata_to_binary(term)}
"etf" ->
term =
payload
|> Utils.destructify
|> :erlang.term_to_binary
{:binary, term}
end
end
@spec decode_payload(Phoenix.Socket.t(), :text | :binary, binary(), String.t(), boolean())
:: {:ok, Payload.t()} | {:error, term()}
def decode_payload(socket, opcode, payload, encoding, restricted) do
case {opcode, encoding} do
{:text, "json"} ->
# JSON has to be error-checked for error conversion properly
{status, data} = Jason.decode payload
case status do
:ok ->
{:ok, Payload.from_map(data, socket)}
:error ->
{:error, Exception.message(data)}
end
{:binary, "msgpack"} ->
# MessagePack has to be unpacked and error-checked
{status, data} = Msgpax.unpack payload
case status do
:ok ->
{:ok, Payload.from_map(data, socket)}
:error ->
# We convert the exception into smth more useful
{:error, Exception.message(data)}
end
{:binary, "etf"} ->
decode_etf socket, payload, restricted
_ ->
{:error, "decode: payload: invalid websocket opcode/encoding combo: {#{opcode}, #{encoding}}"}
end
rescue
err ->
Logger.error "[GATEWAY] [DECODE] #{inspect err, pretty: true}\n#{inspect __STACKTRACE__, pretty: true}"
{:error, "decode: payload: unrecoverable"}
end
defp decode_etf(socket, payload, restricted) do
case restricted do
true ->
# If the client is restricted, but is sending us ETF, make it go
# away
{:error, "restricted clients may not use ETF"}
false ->
# If the client is NOT restricted and sends ETF, decode it.
# In this particular case, we trust that the client isn't stupid
# about the ETF it's sending
term =
payload
|> :erlang.binary_to_term
|> Utils.stringify_keys
|> Payload.from_map(socket)
{:ok, term}
nil ->
# If we don't yet know if the client will be restricted, decode
# it in safe mode
term =
payload
|> :erlang.binary_to_term([:safe])
|> Utils.stringify_keys
|> Payload.from_map(socket)
{:ok, term}
end
end
defp to_outgoing(%{__struct__: _} = payload) do
Map.from_struct payload
end
defp to_outgoing(payload) do
payload
end
end
| 27.280303 | 109 | 0.585115 |
e83bb4c66186f225c5802e2dd225e2806522344d | 292 | exs | Elixir | priv/repo/migrations/20170921014405_loosen_markdown_restrictions.exs | fikape/code-corps-api | c21674b0b2a19fa26945c94268db8894420ca181 | [
"MIT"
] | 275 | 2015-06-23T00:20:51.000Z | 2021-08-19T16:17:37.000Z | priv/repo/migrations/20170921014405_loosen_markdown_restrictions.exs | fikape/code-corps-api | c21674b0b2a19fa26945c94268db8894420ca181 | [
"MIT"
] | 1,304 | 2015-06-26T02:11:54.000Z | 2019-12-12T21:08:00.000Z | priv/repo/migrations/20170921014405_loosen_markdown_restrictions.exs | fikape/code-corps-api | c21674b0b2a19fa26945c94268db8894420ca181 | [
"MIT"
] | 140 | 2016-01-01T18:19:47.000Z | 2020-11-22T06:24:47.000Z | defmodule CodeCorps.Repo.Migrations.LoosenMarkdownRestrictions do
use Ecto.Migration
def up do
alter table(:comments) do
modify :markdown, :text, null: true
end
end
def down do
alter table(:comments) do
modify :markdown, :text, null: false
end
end
end
| 18.25 | 65 | 0.684932 |
e83bc8e8384c054e9c4ee25478faf1c6aa3aa9d5 | 2,065 | ex | Elixir | lib/execution.ex | dnlserrano/firefighter | dca8a8f199dc4a30c19a55abf29f3a8e17209c5b | [
"MIT"
] | 5 | 2020-11-26T11:47:21.000Z | 2021-03-26T23:18:49.000Z | lib/execution.ex | dnlserrano/firefighter | dca8a8f199dc4a30c19a55abf29f3a8e17209c5b | [
"MIT"
] | 8 | 2021-03-09T18:38:40.000Z | 2022-03-20T18:08:04.000Z | lib/execution.ex | dnlserrano/firefighter | dca8a8f199dc4a30c19a55abf29f3a8e17209c5b | [
"MIT"
] | 1 | 2021-03-09T18:08:16.000Z | 2021-03-09T18:08:16.000Z | defmodule Firefighter.Execution do
@type execution :: %__MODULE__{}
@callback start(data :: map) :: execution
@callback record(exec :: execution, data :: map) :: execution
@callback record_many(exec :: execution, name :: binary, data :: list | map) :: execution
@callback push(exec :: execution, pid :: any) :: execution
@callback hose(pid :: any, data :: map) :: execution
defstruct [
:event_uuid,
:event_time,
:elapsed,
data: %{}
]
def start(ids) do
%__MODULE__{
event_uuid: uuid(),
event_time: current_time(),
data: ids
}
end
def record(%__MODULE__{data: data} = execution, ids) do
%{execution | data: Map.merge(data, ids)}
end
def record_many(%__MODULE__{} = execution, name, list_of_ids) when is_list(list_of_ids) do
list_of_ids
|> Enum.reduce(execution, fn ids, end_execution ->
record_many(end_execution, name, ids)
end)
end
def record_many(%__MODULE__{data: data} = execution, name, ids) when is_map(ids) do
many = data[name] || []
data = Map.put(data, name, [ids | many])
%{execution | data: data}
end
def push(%__MODULE__{} = execution, id) when not is_pid(id) do
case Process.whereis(id) do
nil -> raise ArgumentError, "No process found for id #{id}"
pid -> push(execution, pid)
end
end
def push(execution, pid) when is_pid(pid) do
record = to_record(execution)
firefighter().push(pid, record)
execution
end
def hose(id, ids) do
start(ids) |> push(id)
end
defp to_record(%__MODULE__{event_uuid: event_uuid, event_time: event_time, data: data}) do
%{
event_uuid: event_uuid,
event_time: event_time |> DateTime.to_iso8601(),
elapsed: DateTime.diff(current_time(), event_time)
}
|> Map.merge(data)
|> json().encode!()
end
defp uuid, do: UUID.uuid4()
defp current_time, do: DateTime.utc_now()
defp firefighter, do: Application.get_env(:firefighter, :firefighter, Firefighter)
defp json, do: Application.get_env(:firefighter, :json, Jason)
end
| 27.171053 | 92 | 0.6523 |
e83c0ab9eaa8ab053740ad2c2beaccb6f66edca9 | 7,156 | ex | Elixir | lib/ayesql/ast/context.ex | iautom8things/ayesql | c6f6a21fde52f44bcfb59a5b51e170df33a5117d | [
"MIT"
] | null | null | null | lib/ayesql/ast/context.ex | iautom8things/ayesql | c6f6a21fde52f44bcfb59a5b51e170df33a5117d | [
"MIT"
] | null | null | null | lib/ayesql/ast/context.ex | iautom8things/ayesql | c6f6a21fde52f44bcfb59a5b51e170df33a5117d | [
"MIT"
] | null | null | null | defmodule AyeSQL.AST.Context do
@moduledoc """
This module defines an AST context.
"""
alias __MODULE__, as: Context
alias AyeSQL.Core
alias AyeSQL.Error
alias AyeSQL.Query
@doc """
AST context struct.
"""
defstruct index: 1, statement: [], arguments: [], errors: []
@typedoc """
Current context index.
"""
@type index :: non_neg_integer()
@typedoc """
Accumulated statement.
"""
@type statement :: [binary()]
@typedoc """
Argument list.
"""
@type arguments :: [term()]
@typedoc """
Error type.
"""
@type error_type :: :not_found
@typedoc """
Error.
"""
@type error :: {Core.parameter_name(), error_type()}
@typedoc """
AST context.
"""
@type t :: %__MODULE__{
index: index :: index(),
statement: statement :: statement(),
arguments: arguments :: arguments(),
errors: errors :: [error()]
}
############
# Public API
@doc """
Creates a new context given some `options`.
"""
@spec new(keyword()) :: t() | no_return()
def new(options) do
%Context{}
|> set_optional(:index, options[:index])
|> set_optional(:statement, options[:statement])
|> set_optional(:arguments, options[:arguments])
|> set_optional(:errors, options[:errors])
end
@doc """
Context id function.
"""
@spec id(t()) :: t()
def id(context)
def id(%Context{} = context), do: context
@doc """
Adds statement in a `context` given a new `value`.
"""
@spec put_statement(t()) :: t()
@spec put_statement(t(), nil | binary()) :: t()
def put_statement(context, value \\ nil)
def put_statement(context, nil) do
variable = binding_placeholder(context)
put_statement(context, variable)
end
def put_statement(%Context{statement: stmt} = context, value)
when is_binary(value) do
%Context{context | statement: [value | stmt]}
end
@doc """
Adds arguments in a `context` given a new `value`.
"""
@spec put_argument(t(), term()) :: t()
def put_argument(context, value)
def put_argument(%Context{arguments: args} = context, value) do
%Context{context | arguments: [value | args]}
end
@doc """
Adds a `value` to the `context` index.
"""
@spec add_index(t(), non_neg_integer()) :: t()
def add_index(context, value \\ 1)
def add_index(%Context{index: index} = context, value)
when is_integer(value) and value > 0 do
%Context{context | index: index + value}
end
@doc """
Puts a new variable `value` in the `context`.
"""
@spec put_variable(t(), term()) :: t()
def put_variable(context, value)
def put_variable(%Context{} = context, value) do
context
|> put_statement()
|> put_argument(value)
|> add_index()
end
@doc """
Puts several variable `value` in the `context` as an SQL list.
"""
@spec put_variables(t(), [term()]) :: t()
def put_variables(%Context{index: index} = context, values) do
inner_context =
values
|> Enum.reduce(new(index: index), &put_variable(&2, &1))
|> Map.update(:statement, [], &Enum.reverse/1)
|> Map.update(:statement, [], &Enum.join(&1, ","))
merge(context, inner_context)
end
@doc """
Merges two contexts.
"""
@spec merge(t(), t()) :: t()
def merge(old, new)
def merge(%Context{} = old, %Context{} = new) do
new(
index: new.index,
statement: List.flatten([new.statement | old.statement]),
arguments: new.arguments ++ old.arguments,
errors: new.errors ++ old.errors
)
end
@doc """
Merges a `context` with a `query`.
"""
@spec merge_query(t(), Query.t()) :: t()
def merge_query(context, query)
def merge_query(%Context{} = context, %Query{} = query) do
new(
index: context.index + length(query.arguments),
statement: [query.statement | context.statement],
arguments: Enum.reverse(query.arguments) ++ context.arguments,
errors: context.errors
)
end
@doc """
Merges a `context` with an `error`
"""
@spec merge_error(t(), Error.t()) :: t()
def merge_error(context, error)
def merge_error(%Context{} = context, %Error{} = error) do
new(
index: context.index + length(error.arguments),
statement: [error.statement | context.statement],
arguments: Enum.reverse(error.arguments) ++ context.arguments,
errors: context.errors ++ error.errors
)
end
@doc """
Transforms a context to a query.
"""
@spec to_query(t()) :: {:ok, Query.t()} | {:error, Error.t()}
def to_query(context)
def to_query(%Context{errors: []} = context) do
stmt = join_statement(context.statement)
args = Enum.reverse(context.arguments)
query = Query.new(statement: stmt, arguments: args)
{:ok, query}
end
def to_query(%Context{} = context) do
stmt = join_statement(context.statement)
args = Enum.reverse(context.arguments)
errors = Enum.reverse(context.errors)
error = Error.new(statement: stmt, arguments: args, errors: errors)
{:error, error}
end
@doc """
Updates `context` with the error not found for a `key`.
"""
@spec not_found(t(), Core.parameter_name()) :: t()
def not_found(context, key)
def not_found(%Context{statement: statement, errors: errors} = context, key) do
%Context{
context
| statement: ["<missing #{key}>" | statement],
errors: Keyword.put(errors, key, :not_found)
}
end
#########
# Helpers
@doc false
@spec set_optional(t(), atom(), term()) :: t() | no_return()
def set_optional(context, key, value)
def set_optional(%Context{} = context, :index, index)
when is_integer(index) do
%Context{context | index: index}
end
def set_optional(%Context{} = context, :statement, stmt) when is_list(stmt) do
if Enum.all?(stmt, &is_binary/1) do
%Context{context | statement: stmt}
else
raise ArgumentError, message: "statement should be a binary list"
end
end
def set_optional(%Context{} = context, :arguments, args) when is_list(args) do
%Context{context | arguments: args}
end
def set_optional(%Context{} = context, :errors, errors)
when is_list(errors) do
is_error = fn e ->
is_tuple(e) and is_atom(elem(e, 0)) and tuple_size(e) == 2
end
if Enum.all?(errors, is_error) do
%Context{context | errors: errors}
else
raise ArgumentError, message: "errors should be a keyword list"
end
end
def set_optional(context, _, _) do
context
end
# Joins a statement into a binary.
@spec join_statement(statement()) :: binary()
defp join_statement(statement) when is_list(statement) do
statement
|> Enum.reverse()
|> Enum.join()
|> String.replace(~r/\s+/, " ")
|> String.trim()
|> String.trim(";")
end
defp binding_placeholder(%Context{index: index}) do
if use_question_marks?() do
"?"
else
"$#{inspect(index)}"
end
end
@spec use_question_marks?() :: boolean()
defp use_question_marks? do
default = false
value = Application.get_env(:ayesql, :use_question_mark_bindings?, default)
if is_boolean(value), do: value, else: default
end
end
| 24.847222 | 81 | 0.621716 |
e83c256676d0f4ac6a5960db17c5154c8d3d38c7 | 59,657 | ex | Elixir | plugins/one_chat/lib/one_chat_web/channels/user_channel.ex | smpallen99/ucx_ucc | 47225f205a6ac4aacdb9bb4f7512dcf4092576ad | [
"MIT"
] | 11 | 2017-05-15T18:35:05.000Z | 2018-02-05T18:27:40.000Z | plugins/one_chat/lib/one_chat_web/channels/user_channel.ex | anndream/infinity_one | 47225f205a6ac4aacdb9bb4f7512dcf4092576ad | [
"MIT"
] | 15 | 2017-11-27T10:38:05.000Z | 2018-02-09T20:42:08.000Z | plugins/one_chat/lib/one_chat_web/channels/user_channel.ex | anndream/infinity_one | 47225f205a6ac4aacdb9bb4f7512dcf4092576ad | [
"MIT"
] | 4 | 2017-09-13T11:34:16.000Z | 2018-02-26T13:37:06.000Z | defmodule OneChatWeb.UserChannel do
@moduledoc """
A channel responsible for handling most of the user based chat interactions.
Much of the communications between the client and the server is done with
this channel. When new messages are broadcast to users, they much be
individually rendered for the user so that timezone information and other
user based settings can be applied.
Interactions with features like opening panels, saving settings, editing
messages are all done for the user only. So, this is the channel that
handles those communications.
Unlike traditional AJAX based applications, OneChat uses the `Phoenix.Channel`
to handle asynchronous messaging instead of AJAX requests. After the
initial page load, almost all content is pushed from the Server to the
client over channels.
InfinityOne takes this one step further by handling client events on the server
and pushing out javascript over the channel for execution in the client. This
is accomplished with the `Rebel` library.
"""
use OneLogger
use OneChatWeb, :channel
use InfinityOne
use InfinityOne.OnePubSub
use Rebel.Channel, name: "user", controllers: [
OneChatWeb.ChannelController,
], intercepts: [
"room:join",
"room:leave",
"user:state",
"direct:new",
"update:room-icon",
"update:room-visibility",
"get:subscribed",
"js:execjs",
"webrtc:incoming_video_call",
"webrtc:confirmed_video_call",
"webrtc:declined_video_call",
"webrtc:leave",
"get",
"get:assigns",
"put:assigns"
]
use OneChatWeb.RebelChannel.Macros
import Rebel.Core, warn: false
import Rebel.Query, warn: false
import Rebel.Browser, warn: false
import Ecto.Query, except: [update: 3]
alias Phoenix.Socket.Broadcast
alias InfinityOne.{Repo, Accounts, Hooks, TabBar}
# alias InfinityOne.TabBar.Ftab
alias Accounts.{Account, User}
alias OneAdmin.AdminService
alias InfinityOneWeb.Endpoint
alias OneChat.ServiceHelpers, as: Helpers
alias OneChat.Schema.Subscription, as: SubscriptionSchema
alias OneUiFlexTab.FlexTabChannel
alias OneChatWeb.FlexBar.Form
alias OneChat.{
Subscription, ChannelService, Channel, Web.RoomChannel, Message,
SideNavService, ChannelService, InvitationService,
UserService, EmojiService, PresenceAgent
}
alias OneChatWeb.{RoomChannel, AccountView, MasterView, FlexBarView}
alias Rebel.SweetAlert
alias OneWebrtcWeb.WebrtcChannel
alias OneChatWeb.RebelChannel.Client
alias OneChatWeb.RoomChannel.Channel, as: WebChannel
alias OneChatWeb.RoomChannel.Message, as: WebMessage
alias InfinityOne.OnePubSub
alias InfinityOneWeb.Query
alias OneChatWeb.UserChannel.Notifier
alias OneChatWeb.UserChannel.SideNav.Channels
require OneChat.ChatConstants, as: CC
onconnect :on_connect
onload :page_loaded
def on_connect(socket) do
broadcast_js socket, "window.OneChat.run()"
WebrtcChannel.on_connect(socket)
end
def page_loaded(socket) do
# Logger.info "page_loaded, assigns: #{inspect socket.assigns}"
socket
end
def join_room(user_id, room) do
Endpoint.broadcast!(CC.chan_user() <> "#{user_id}", "room:join",
%{room: room, user_id: user_id})
end
def leave_room(user_id, room) do
Endpoint.broadcast!(CC.chan_user() <> "#{user_id}", "room:leave",
%{room: room, user_id: user_id})
end
def user_state(user_id, state) do
Endpoint.broadcast(CC.chan_user() <> "#{user_id}", "user:state",
%{state: state})
end
def get_assigns(username) do
user = Accounts.get_by_username username
Endpoint.broadcast(CC.chan_user() <> user.id, "get:assigns", %{pid: self()})
receive do
message -> message
end
end
def put_assign(user_id, key) do
put_assign(user_id, key, nil)
end
def put_assign(user_id, key, value) do
Endpoint.broadcast(CC.chan_user() <> user_id, "put:assigns", %{key: key, value: value})
end
@doc """
API to get internal state from a channel.
Used for debugging purposes.
"""
@spec get(any, String.t) :: any
def get(item, user_id) do
Endpoint.broadcast(CC.chan_user() <> "#{user_id}", "get", %{item: item, caller: self()})
receive do
{:get_response, response} -> {:ok, response}
after
1_500 -> {:error, :timeout}
end
end
def join(CC.chan_user() <> _user_id = event, payload, socket) do
trace(event, payload)
send(self(), {:after_join, payload})
super event, payload, FlexTabChannel.do_join(socket, event, payload)
end
def join(other, params, socket) do
# Logger.error "another join #{other}"
super other, params, socket
end
def topic(_broadcasting, _controller, _request_path, conn_assigns) do
conn_assigns[:current_user] |> Map.get(:id)
end
def handle_out("put:assigns", %{key: key, value: value}, socket) do
{:noreply, assign(socket, key, value)}
end
def handle_out("get:assigns", %{pid: pid}, socket) do
send pid, socket.assigns
{:noreply, socket}
end
def handle_out("webrtc:leave" = ev, payload, socket) do
trace ev, payload
broadcast_js socket, ~s/$('.webrtc-video button.stop-call').click()/
{:noreply, socket}
end
def handle_out("webrtc:" <> event, payload, socket) do
apply WebrtcChannel, String.to_atom(event), [payload, socket]
end
# Generic handler for retrieving internal information from a channel.
# This is only for debugging purposes.
def handle_out("get", payload, socket) do
response =
case payload[:item] do
:assigns -> socket.assigns
:socket -> socket
:pid -> self()
{:assigns, field} -> Map.get(socket.assigns, field)
_ -> :invalid
end
send payload[:caller], {:get_response, response}
{:noreply, socket}
end
def handle_out("js:execjs" = ev, payload, socket) do
trace ev, payload
case exec_js socket, payload[:js] do
{:ok, result} ->
send payload[:sender], {:response, result}
{:error, error} ->
send payload[:sender], {:error, error}
end
{:noreply, socket}
end
def handle_out("get:subscribed" = ev, msg, socket) do
trace ev, msg
Kernel.send msg.pid, {:subscribed, socket.assigns[:subscribed]}
{:noreply, socket}
end
def handle_out("room:join", %{room: room} = msg, socket) do
trace "room:join", msg
channel = Channel.get_by(name: room)
socket
|> update_rooms_list()
|> Client.push_message_box(channel.id, socket.assigns.user_id)
# clear_unreads(room, socket)
{:noreply, subscribe([room], socket)}
end
def handle_out("room:leave" = ev, msg, socket) do
%{room: room} = msg
trace ev, msg, "assigns: #{inspect socket.assigns}"
# UserSocket.push_message_box(socket, socket.assigns.channel_id, socket.assigns.user_id)
socket.endpoint.unsubscribe(CC.chan_room <> room)
update_rooms_list(socket)
{:noreply, assign(socket, :subscribed,
List.delete(socket.assigns[:subscribed], room))}
end
def handle_out("user:state", msg, socket) do
{:noreply, handle_user_state(msg, socket)}
end
def handle_out("direct:new", msg, socket) do
%{room: room} = msg
update_rooms_list(socket)
{:noreply, subscribe([room], socket)}
end
def handle_out("update:room-icon", payload, socket) do
icon = String.replace(payload.icon_name, ~r/^icon-/, "")
Client.broadcast_room_icon(socket, payload.room_name, icon)
{:noreply, socket}
end
def handle_out("update:room-visibility", payload, socket) do
Client.broadcast_room_visibility(socket, payload, payload.visible)
{:noreply, socket}
end
def handle_user_state(%{state: "blur"}, socket) do
trace "blur", ""
assign socket, :user_state, "blur"
end
def handle_user_state(%{state: "idle"}, socket) do
trace "idle", ""
push socket, "focus:change", %{state: false, msg: "idle"}
assign socket, :user_state, "idle"
end
def handle_user_state(%{state: "active"}, socket) do
trace "active", ""
push socket, "focus:change", %{state: true, msg: "active"}
clear_unreads(socket)
assign socket, :user_state, "active"
end
def more_channels(socket, _sender, client \\ Client) do
client.more_channels socket, SideNavService.render_more_channels(socket.assigns.user_id)
socket
end
def push_update_direct_message(msg, socket) do
Process.send_after self(),
{:update_direct_message, msg, socket.assigns.user_id}, 250
socket
end
###############
# Incoming Messages
def handle_in("unread:clear", _params, socket) do
clear_unreads(socket)
{:noreply, socket}
end
def handle_in("notification:click", params, socket) do
message = Message.get params["message_id"]
if params["channel_id"] == socket.assigns.channel_id do
broadcast_js socket, ~s/OneChat.roomHistoryManager.scroll_to_message('#{message.timestamp}')/
else
room = params["channel_name"]
broadcast_js socket, ~s/$('aside.side-nav a.open-room[data-room="#{room}"]').click()/
# TODO: This is a hack. We should have a notification when the room is loaded and then run the JS below.
spawn fn ->
Process.sleep 3500
broadcast_js socket, ~s/OneChat.roomHistoryManager.scroll_to_message('#{message.timestamp}')/
end
end
{:noreply, socket}
end
def handle_in(ev = "reaction:" <> action, params, socket) do
trace ev, params
_ = ev
_ = params
case OneChat.ReactionService.select(action, params, socket) do
nil -> {:noreply, socket}
res -> {:reply, res, socket}
end
end
def handle_in("emoji:" <> emoji, params, socket) do
EmojiService.handle_in(emoji, params, socket)
end
def handle_in("subscribe" = ev, params, socket) do
trace ev, params, "assigns: #{inspect socket.assigns}"
_ = ev
_ = params
{:noreply, socket}
end
def handle_in("side_nav:open" = ev, %{"page" => "account"} = params,
socket) do
trace ev, params
_ = ev
_ = params
user = Helpers.get_user!(socket)
account_cs = Account.changeset(user.account, %{})
Client.update_main_content_html socket, AccountView,
"account_preferences.html",
user: user, account_changeset: account_cs
html = Helpers.render(AccountView, "account_flex.html")
{:reply, {:ok, %{html: html}}, socket}
end
def handle_in("side_nav:more_channels" = ev, params, socket) do
trace ev, params
html = SideNavService.render_more_channels(socket.assigns.user_id)
{:reply, {:ok, %{html: html}}, socket}
end
def handle_in("side_nav:more_users" = ev, params, socket) do
trace ev, params
html = SideNavService.render_more_users(socket.assigns.user_id)
{:reply, {:ok, %{html: html}}, socket}
end
def handle_in("side_nav:close" = ev, params, socket) do
trace ev, params
assigns = socket.assigns
OneUiFlexTab.FlexTabChannel.flex_close socket, %{}
assigns.user_id
|> InfinityOne.TabBar.get_ftabs
|> Enum.find(fn {tab_name, _} -> String.starts_with?(tab_name, "admin_") end)
|> case do
{tab_name, _} ->
Logger.warn "found open admin tab: " <> tab_name
module =
"admin_user_info"
|> TabBar.get_button
|> Map.get(:module)
module.close socket, %{}
TabBar.close_ftab assigns.user_id, assigns.channel_id
_ ->
:ok
end
{:noreply, socket}
end
def handle_in("account:preferences:save" = ev, params, socket) do
trace ev, params, "assigns: #{inspect socket.assigns}"
params =
params
|> Helpers.normalize_form_params
|> Map.get("account")
resp =
socket
|> Helpers.get_user!
|> Map.get(:account)
|> Account.changeset(params)
|> Repo.update
|> case do
{:ok, _account} ->
{:ok, %{success: ~g"Account updated successfully"}}
{:error, _cs} ->
{:ok, %{error: ~g"There a problem updating your account."}}
end
{:reply, resp, socket}
end
def handle_in("account:profile:save" = ev, params, socket) do
trace ev, params, "assigns: #{inspect socket.assigns}"
params =
params
|> Helpers.normalize_form_params
|> Map.get("user")
resp =
socket
|> Helpers.get_user!
|> User.changeset(params)
|> Repo.update
|> case do
{:ok, _account} ->
{:ok, %{success: ~g"Profile updated successfully"}}
{:error, cs} ->
Logger.error "cs.errors: #{inspect cs.errors}"
{:ok, %{error: ~g"There a problem updating your profile."}}
end
{:reply, resp, socket}
end
def handle_in("account:phone:save" = ev, params, socket) do
trace ev, params, "assigns: #{inspect socket.assigns}"
# TODO: Need to validate parameters to ensure they were not changed on
# the way from the client to the server. This includes the user_id
# and the phone number id.
{id, phone_number_params} =
params
|> Helpers.normalize_form_params
|> Map.get("phone_number")
|> Map.pop("id")
resp =
case id do
nil ->
phone_number_params
|> Map.put("user_id", socket.assigns.user_id)
|> Map.put("primary", true)
|> Map.put("extension", %{user_id: socket.assigns.user_id, default: true})
|> Accounts.create_phone_number
|> case do
{:ok, phone_number} ->
if phone_number.primary do
OnePubSub.broadcast "phone_number", "create", %{
number: phone_number.number,
user_id: socket.assigns.user_id,
username: socket.assigns.username
}
end
# Logger.warn inspect(socket.assigns)
{:ok, %{success: ~g"Phone Number created successfully"}}
{:error, cs} ->
Logger.error "cs.errors: #{inspect cs.errors}"
{:ok, %{error: ~g"There a problem creating your phone number."}}
end
id ->
id
|> Accounts.get_phone_number!
|> Accounts.update_phone_number(phone_number_params)
|> case do
{:ok, phone_number} ->
if phone_number.primary do
OnePubSub.broadcast "phone_number", "update", %{
number: phone_number.number,
user_id: socket.assigns.user_id,
username: socket.assigns.username
}
end
# Logger.warn inspect(socket.assigns)
{:ok, %{success: ~g"Phone Number updated successfully"}}
{:error, cs} ->
Logger.error "cs.errors: #{inspect cs.errors}"
{:ok, %{error: ~g"There a problem updating your phone number."}}
end
end
{:reply, resp, socket}
end
def handle_in("account:phone:delete", params, socket) do
user_id = socket.assigns.user_id
phone_number =
params
|> Helpers.normalize_form_params()
|> Map.get("phone_number")
|> Map.get("id")
|> Accounts.get_phone_number!
resp =
case phone_number.user_id do
^user_id ->
case Accounts.delete_phone_number(phone_number) do
{:ok, _} ->
if phone_number.primary do
OnePubSub.broadcast "phone_number", "delete", %{
number: phone_number.number,
user_id: socket.assigns.user_id,
username: socket.assigns.username
}
end
{:ok, %{success: ~g"Phone Number deleted successfully."}}
{:error, _} ->
{:ok, %{error: ~g"There was a problem deleting the phone number!"}}
end
_ ->
{:ok, %{error: ~g"You don't have permission to delete that phone number!"}}
end
{:reply, resp, socket}
end
@links ~w(preferences profile)
def handle_in(ev = "account_link:click:" <> link, params, socket) when link in @links do
trace ev, params
user = Accounts.get_user(socket.assigns.user_id,
preload: Hooks.user_preload([:account, :roles, user_roles: :role, phone_numbers: :label]))
user_cs = User.changeset(user, %{})
account_cs = Account.changeset(user.account, %{})
Client.update_main_content_html socket, AccountView, "account_#{link}.html",
user: user, account_changeset: account_cs, user_changeset: user_cs
{:noreply, socket}
end
def handle_in(ev = "account_link:click:phone", params, socket) do
trace ev, params
user = Accounts.get_user(socket.assigns.user_id,
preload: Hooks.user_preload([:account, :roles, user_roles: :role, phone_numbers: :label]))
labels = Enum.map Accounts.list_phone_number_labels, & {String.to_atom(&1.name), &1.id}
phone_cs =
case user.phone_numbers do
[] ->
work = Enum.find labels |> IO.inspect(label: "labels"), & elem(&1, 0) == :Work
Accounts.change_phone_number(%{primary: true, label_id: elem(work, 1)})
[pn | _] ->
Accounts.change_phone_number(pn, %{})
end
user_cs = Accounts.change_user(user)
Client.update_main_content_html socket, AccountView, "account_phone.html",
user: user, phone_number_changeset: phone_cs, labels: labels, user_changeset: user_cs
{:noreply, socket}
end
def handle_in(ev = "mode:set:" <> mode, params, socket) do
trace ev, params
mode = if mode == "im", do: true, else: false
user = Helpers.get_user!(socket)
resp =
user
|> Map.get(:account)
|> Account.changeset(%{chat_mode: mode})
|> Repo.update
|> case do
{:ok, _} ->
push socket, "window:reload", %{mode: mode}
{:ok, %{}}
{:error, _} ->
{:error, %{error: ~g"There was a problem switching modes"}}
end
{:reply, resp, socket}
end
@links ~w(info general chat_general message permissions layout users rooms file_upload)
def handle_in(ev = "admin_link:click:" <> link, params, socket) when link in @links do
trace ev, params
user = Helpers.get_user! socket
html = AdminService.render user, link, "#{link}.html"
push socket, "code:update", %{html: html, selector: ".main-content", action: "html"}
broadcast_js socket, "Rebel.set_event_handlers('.main-content')"
{:noreply, socket}
end
def handle_in(ev = "admin_link:click:webrtc" , params, socket) do
link = "webrtc"
trace ev, params
user = Helpers.get_user! socket
update socket, :html,
set: AdminService.render(user, link, "#{link}.html"),
on: ".main-content"
{:noreply, socket}
end
def handle_in(ev = "admin:" <> link, params, socket) do
trace ev, params
AdminService.handle_in(link, params, socket)
end
# def handle_in(ev = "flex:member-list:" <> action, params, socket) do
# debug ev, params
# FlexBarService.handle_in action, params, socket
# end
def handle_in(ev = "update:currentMessage", params, socket) do
trace ev, params
value = params["value"] || "0"
assigns = socket.assigns
last_read = Subscription.get(assigns.channel_id, assigns.user_id,
:last_read) || ""
cond do
last_read == "" or String.to_integer(last_read) < String.to_integer(value) ->
Subscription.update(assigns.channel_id, assigns.user_id, %{last_read: value})
true ->
nil
end
Subscription.update(assigns.channel_id, assigns.user_id,
%{current_message: value})
{:noreply, socket}
end
def handle_in(ev = "get:currentMessage", params,
%{assigns: assigns} = socket) do
trace ev, params
channel = Channel.get_by name: params["room"]
if channel do
res =
case Subscription.get channel.id, assigns.user_id, :current_message do
:error -> {:error, %{}}
value -> {:ok, %{value: value}}
end
{:reply, res, socket}
else
{:noreply, socket}
end
end
def handle_in(ev = "last_read", params, %{assigns: assigns} = socket) do
trace ev, params
Subscription.update assigns.channel_id, assigns.user_id, %{last_read: params["last_read"]}
{:noreply, socket}
end
def handle_in("invitation:resend", %{"email" => _email, "id" => id},
socket) do
case InvitationService.resend(id) do
{:ok, message} ->
{:reply, {:ok, %{success: message}}, socket}
{:error, error} ->
{:reply, {:error, %{error: error}}, socket}
end
end
def handle_in("webrtc:device_manager_init", payload, socket) do
WebrtcChannel.device_manager_init(socket, payload)
end
def handle_in(ev = "webrtc:incoming_video_call", payload, socket) do
trace ev, payload
{:noreply, socket}
end
# default unknown handler
def handle_in(event, params, socket) do
Logger.warn "UserChannel.handle_in unknown event: #{inspect event}, " <>
"params: #{inspect params}"
{:noreply, socket}
end
###############
# Info messages
def handle_info({"webrtc:incoming_video_call" = ev, payload}, socket) do
trace ev, payload
trace ev, socket.assigns
title = "Direct video call from #{payload[:username]}"
icon = "videocam"
# SweetAlert.swal_modal socket, "<i class='icon-#{icon} alert-icon success-color'></i>#{title}", "Do you want to accept?", "warning",
# SweetAlert.swal_modal socket, title, "Do you want to accept?", "warning",
SweetAlert.swal_modal socket, ~s(<i class="icon-#{icon} alert-icon success-color"></i>#{title}), "Do you want to accept?", nil,
[html: true, showCancelButton: true, closeOnConfirm: true, closeOnCancel: true],
confirm: fn _result ->
# Logger.warn "sweet confirmed! #{inspect result}"
# SweetAlert.swal socket, "Confirmed!", "Your action was confirmed", "success",
# timer: 2000, showConfirmButton: false
true
end,
cancel: fn _result ->
# Logger.warn "sweet canceled! result: #{inspect result}"
# SweetAlert.swal socket, "Canceled!", "Your action was canceled", "error",
# timer: 2000, showConfirmButton: false
# Logger.warn "sweet notice complete!"
true
end
{:noreply, socket}
end
def handle_info({:after_join, params}, socket) do
:erlang.process_flag(:trap_exit, true)
trace "after_join", socket.assigns, inspect(params)
user_id = socket.assigns.user_id
channel_name =
case params["channel_id"] do
id when id in ["", nil] ->
"lobby"
channel_id ->
channel_id
|> Channel.get
|> Map.get(:name)
end
new_assigns =
params
|> Enum.map(fn {k,v} ->
{String.to_atom(k), v}
end)
|> Enum.into(%{})
socket =
socket
|> struct(assigns: Map.merge(new_assigns, socket.assigns))
|> assign(:subscribed, socket.assigns[:subscribed] || [])
|> assign(:user_state, "active")
|> assign(:room, channel_name)
|> assign(:self, self())
socket =
Repo.all(from s in SubscriptionSchema, where: s.user_id == ^user_id,
preload: [:channel, {:user, :roles}])
|> Enum.map(&(&1.channel.name))
|> subscribe(socket)
subscribe_callback "user:" <> user_id, "room:join",
{FlexTabChannel, :room_join}
subscribe_callback "user:" <> user_id, "new:subscription",
:new_subscription
subscribe_callback "user:" <> user_id, "delete:subscription",
:delete_subscription
subscribe_callback "user:" <> user_id, "room:update",
:room_update
subscribe_callback "user:" <> user_id, "logout", :logout
subscribe_callback "user:" <> user_id, "webrtc:offer", :webrtc_offer
subscribe_callback "user:" <> user_id, "webrtc:answer", {WebrtcChannel, :webrtc_answer}
subscribe_callback "user:" <> user_id, "webrtc:leave", {WebrtcChannel, :webrtc_leave}
subscribe_callback "user:" <> user_id, "unread:update", :unread_update
OnePubSub.subscribe "message:new", "*"
# TODO: add Hooks for this
subscribe_callback "user:all", "callback", :user_all_event
# TODO: Add hooks for this
OnePubSub.subscribe "user:all", "channel:deleted"
OnePubSub.subscribe "user:all", "channel:change:key"
OnePubSub.subscribe "user:all", "status:refresh"
subscribe_callback "user:all", "callback", :user_all_event
subscribe_callback "user:all", "avatar:change", :user_all_event
subscribe_callback "user:all", "account:change", :user_all_event
subscribe_callback "user:all", "status_message:update", :status_message_update
OnePubSub.subscribe "user:all", "status:refresh-user"
{:noreply, socket}
end
def handle_info(%Broadcast{topic: _, event: "get:subscribed",
payload: payload}, socket) do
trace "get:subscribed", payload
send payload["pid"], {:subscribed, socket.assigns[:subscribed]}
{:noreply, socket}
end
def handle_info(%Broadcast{topic: _, event: "room:update:name" = event,
payload: payload}, socket) do
trace event, payload
Logger.warn "deprecated room:update:name assigns: " <> inspect(socket.assigns)
push socket, event, payload
# socket.endpoint.unsubscribe(CC.chan_room <> payload[:old_name])
{:noreply, assign(socket, :subscribed,
[payload[:new_name] | List.delete(socket.assigns[:subscribed],
payload[:old_name])])}
end
def handle_info(%Broadcast{topic: _, event: "room:update:list" = event,
payload: payload}, socket) do
trace event, payload
{:noreply, update_rooms_list(socket)}
end
def handle_info(%Broadcast{topic: "room:" <> room,
event: "message:new" = event, payload: payload}, socket) do
Logger.warn "deprecated!!!"
trace event, "" #socket.assigns
assigns = socket.assigns
if room in assigns.subscribed do
channel = Channel.get_by(name: room)
# Logger.debug "in the room ... #{assigns.user_id}, room: #{inspect room}"
if channel.id != assigns.channel_id or assigns.user_state == "idle" do
if channel.type == 2 do
msg =
if payload[:body] do
%{body: payload[:body], username: assigns.username, message: payload[:message]}
else
nil
end
push_update_direct_message(%{channel_id: channel.id, msg: msg},
socket)
end
update_has_unread(channel, socket)
end
end
{:noreply, socket}
end
def handle_info(%Broadcast{event: "user:action" = event,
payload: %{action: "unhide"} = payload}, %{assigns: assigns} = socket) do
trace event, payload, "assigns: #{inspect assigns}"
update_rooms_list(socket, socket.assigns.user_id, payload.channel_id)
{:noreply, socket}
end
def handle_info(%Broadcast{event: "user:entered" = event,
payload: %{user_id: user_id} = payload},
%{assigns: %{user_id: user_id} = assigns} = socket) do
trace event, payload, "assigns: #{inspect assigns}"
channel_id = payload[:channel_id]
new_channel = Channel.get(channel_id)
socket = %{assigns: _assigns} =
socket
|> assign(:channel_id, channel_id)
|> assign(:last_channel_id, assigns[:channel_id])
|> assign(:room, new_channel.name)
OnePubSub.broadcast "user:" <> assigns.user_id, "room:join",
%{resource_id: channel_id, last_resoure_key: :last_channel_id}
{:noreply, socket}
end
def handle_info(%Broadcast{event: "user:entered"}, socket) do
{:noreply, socket}
end
def handle_info(%Broadcast{event: "room:delete" = event,
payload: payload}, socket) do
trace event, payload
room = payload.room
if Enum.any?(socket.assigns[:subscribed], &(&1 == room)) do
update_rooms_list(socket)
{:noreply, assign(socket, :subscribed,
List.delete(socket.assigns[:subscribed], room))}
else
{:noreply, socket}
end
end
# def handle_info(%Broadcast{topic: "room:" <> room, event: "broadcastjs",
# payload: %{js: js} = payload}, socket) do
# trace "broadcast room:" <> room <> ", event: broadcastjs", payload
# # next, update sidebar if subscribed
# if room in socket.assigns.subscribed do
# exec_js socket, js
# end
# {:noreply, socket}
# end
# Default broadcast case to ignore messages we are not interested in
def handle_info(%Broadcast{}, socket) do
# Logger.warn "broadcast: " <> inspect(broadcast)
# Logger.warn "assigns: " <> inspect(socket.assigns)
{:noreply, socket}
end
def handle_info({"message:new", _, payload}, socket) do
assigns = socket.assigns
room = payload.channel_name
socket =
if room in assigns.subscribed do
channel = Channel.get_by(name: room)
new_payload = %{
message: payload.message,
channel: channel,
user_id: assigns.user_id,
user_state: assigns.user_state,
open: Subscription.open?(channel.id, assigns.user_id),
}
if channel.id != assigns.channel_id or assigns.user_state != "active" do
update_has_unread(channel, socket)
end
Notifier.new_message(new_payload, socket)
else
socket
end
{:noreply, socket}
end
def handle_info({_, "channel:deleted", payload}, socket) do
socket =
if payload.room_name in socket.assigns.subscribed do
room = payload.room_name
socket = unsubscribe(socket, room)
if socket.assigns.room == room do
next_room =
socket.assigns.subscribed
|> Enum.reject(& &1 == room)
|> hd
socket
|> OneChatWeb.Client.close_flex_bar()
|> Channels.open_room(nil, next_room, next_room)
else
update_rooms_list(socket)
end
else
socket
end
{:noreply, socket}
end
def handle_info({_, "channel:change:key", %{key: :name} = payload}, socket) do
Logger.debug fn -> inspect(payload) end
assigns = socket.assigns
socket =
if payload.old_value in assigns.subscribed do
new_room = payload.new_value
if assigns.room == payload.old_value && assigns[:channel_id] do
socket
|> Client.set_room_title(assigns.channel_id, new_room)
|> Client.update_flex_channel_name(new_room)
|> Client.replace_history(new_room, new_room)
|> assign(:room, new_room)
else
socket
end
|> unsubscribe(payload.old_value)
|> subscribe(new_room)
|> update_rooms_list()
else
socket
end
{:noreply, socket}
end
def handle_info({_, "channel:change:key", payload}, socket) do
Logger.debug fn -> "unhandled channel:change:key payload: " <>
inspect(payload)
end
{:noreply, socket}
end
def handle_info({"user:all", "status:refresh", %{user_id: id}},
%{assigns: %{user_id: id}} = socket) do
user =
id
|> Accounts.get_user()
|> InfinityOne.Hooks.preload_user(Accounts.default_user_preloads())
push_account_header(socket, user)
{:noreply, socket}
end
def handle_info({"user:all", "status:refresh", payload}, socket) do
subscribed = socket.assigns.subscribed
case Enum.find(payload.friend_channel_names, & elem(&1, 0) in subscribed) do
{_, channel_id} ->
current_user =
socket.assigns.user_id
|> Accounts.get_user()
|> InfinityOne.Hooks.preload_user(Accounts.default_user_preloads())
room = ChannelService.get_side_nav_room current_user, channel_id
socket
|> update_side_nav_item(current_user, room)
|> update_messages_header_icons(room, socket.assigns[:channel_id] == channel_id)
_ ->
nil
end
{:noreply, socket}
end
def handle_info({"user:all", "status:refresh-user", payload}, socket) do
status = PresenceAgent.get(payload[:user_id])
user = Accounts.get_user(payload[:user_id], preload: [:account])
Client.refresh_users_status(socket, payload[:username], status, user.account.status_message)
{:noreply, socket}
end
handle_callback("user:" <> _user_id)
handle_callback("user:all")
def handle_info({:EXIT, _, :normal}, socket) do
{:noreply, socket}
end
# A generic timer handler that was introduced for the message search
# feature. The message is provide with a module, function, arity tuple
# as means of a callback.
def handle_info({:forward_timeout, {m, f, a}}, socket) do
case apply(m, f, [socket | a]) do
tuple when is_tuple(tuple) ->
tuple
_ ->
{:noreply, socket}
end
end
def handle_info(payload, socket) do
Logger.warn "default handle info payload: #{inspect payload}"
{:noreply, socket}
end
def terminate(_reason, socket) do
OnePubSub.unsubscribe "user:" <> socket.assigns[:user_id]
OnePubSub.unsubscribe "message:new"
Subscription.close_opens(socket.assigns[:user_id])
:ok
end
###############
# Helpers
defp subscribe(channels, %Phoenix.Socket{} = socket) when is_list(channels) do
# trace inspect(channels), ""
Enum.reduce channels, socket, fn channel, acc ->
subscribed = acc.assigns[:subscribed]
if channel in subscribed do
acc
else
socket.endpoint.subscribe(CC.chan_room <> channel)
assign(acc, :subscribed, [channel | subscribed])
end
end
end
defp subscribe(%Phoenix.Socket{} = socket, room) do
assign(socket, :subscribed, [room | socket.assigns.subscribed])
end
defp update_rooms_list(%{assigns: assigns} = socket) do
trace "", inspect(assigns)
html = SideNavService.render_rooms_list(assigns[:channel_id],
assigns[:user_id])
Rebel.Query.update! socket, :html, set: html, on: ".rooms-list"
end
defp clear_unreads(%{assigns: %{channel_id: ""}} = socket) do
socket
end
defp clear_unreads(%{assigns: %{channel_id: channel_id}} = socket) do
channel_id
|> Channel.get
|> Map.get(:name)
|> clear_unreads(socket)
end
defp clear_unreads(socket) do
Logger.debug "clear_unreads/1: default"
socket
end
defp clear_unreads(room, %{assigns: assigns} = socket) do
Subscription.set_has_unread(assigns.channel_id, assigns.user_id, false)
async_js socket, """
$('link-room-#{room}').removeClass('has-unread')
.removeClass('has-alert');
""" |> String.replace("\n", "")
push socket, "update:alerts", %{}
end
defp update_has_unread(%{id: channel_id, name: room},
%{assigns: assigns} = socket) do
has_unread = ChannelService.get_has_unread(channel_id, assigns.user_id)
Logger.debug fn -> "has_unread: #{inspect has_unread}, channel_id: " <>
"#{inspect channel_id}, assigns: #{inspect assigns}" end
unless has_unread do
Subscription.set_has_unread(channel_id, assigns.user_id, true)
broadcast_js socket,
"$('.link-room-#{room}').addClass('has-unread').addClass('has-alert');"
push socket, "update:alerts", %{}
end
end
def drop_notify_click(socket, sender) do
OnePubSub.broadcast "drop_notify", "click", sender
socket
end
def drop_notify_cancel(socket, sender) do
OnePubSub.broadcast "drop_notify", "cancel", sender
broadcast_js socket, """
var elem = $('#{this(sender)}').closest('.notice');
elem.animate({
height: "0px",
'font-size': "0px"
}, 500, function() {
elem.remove();
});
""" |> String.replace("\n", " ")
socket
end
#################################
# Status Messages Implementation
#
def change_status_message(socket, sender) do
Logger.debug fn -> inspect(sender) end
user = Accounts.get_user(socket.assigns.user_id, preload: [:account])
account = user.account
case sender["value"] do
"__edit__" ->
account
|> push_status_message_edit(socket)
"__new__" ->
account
|> push_status_message_select(socket)
|> show_status_message_input()
|> async_js(~s/$('.status-message-input input').val('').focus();/)
"__clear__" ->
case InfinityOne.Accounts.update_account(account, %{status_message: ""}) do
{:ok, account} ->
Client.toastr(socket, :success, ~g(Your status message as been cleared))
account
{:error, _} ->
Client.toastr socket, :error, ~g(Problem updating clearing your status message)
account
end
|> push_status_message_select(socket)
|> Rebel.Query.execute(:click, on: ".account-box.active")
|> broadcast_status_message(user.username, "")
"" ->
if sender["event"]["type"] == "click" do
async_js socket, "$('.status-message-input input').change();"
else
socket
|> Rebel.Query.execute(:click, on: ".account-box.active")
|> show_status_message_select()
end
message ->
message = String.trim(message)
user = Accounts.get_user socket.assigns.user_id, preload: [:account]
case OneChat.Accounts.update_status_message(user.account, message) do
{:ok, account} ->
account
|> push_status_message_select(socket)
|> Client.toastr(:success, ~g(Your status message was updated))
|> broadcast_status_message(user.username, message)
{:error, _} ->
Client.toastr socket, :error, ~g(Problem updating your status message)
end
socket
|> Rebel.Query.execute(:click, on: ".account-box.active")
|> show_status_message_select()
end
socket
end
def cancel_status_message(socket, sender) do
Logger.debug fn -> inspect(sender) end
async_js socket, "$('.status-message-input').hide(); $('.status-message-select').show();"
socket
end
def edit_status_message_close(socket, _sender) do
# Logger.warn inspect(sender)
user = Accounts.get_user(socket.assigns.user_id, preload: [:account])
push_status_message_select user.account,
async_js(socket, "$('.status-message-edit').hide();")
end
def edit_status_message(socket, %{"value" => ""} = sender) do
# Logger.warn inspect(sender)
user = Accounts.get_user(socket.assigns.user_id, preload: [:account])
index = String.to_integer(sender["dataset"]["index"])
case exec_js socket, ~s/$('.status-message-edit-ctrl input[data-index="#{index}"]').val()/ do
{:ok, ""} -> socket
{:error, _} -> socket
{:ok, message} ->
edit_status_message(socket, sender, user, index, message)
end
end
defp edit_status_message(socket, _sender, user, index, message) do
# Logger.warn inspect(sender)
case OneChat.Accounts.replace_status_message(user.account, index, message) do
{:ok, _account} ->
socket
|> async_js(disable_edit_status_control_buttons_js(index))
|> SweetAlert.swal(~g"Updated!", ~g"Your message has been Updated!", "success",
timer: 2000, showConfirmButton: false)
{:error, _} ->
socket
|> async_js(~s/.status-message-edit-ctrl .cancel[data-index="#{index}"]').click()/)
|> SweetAlert.swal(~g"Error!", ~g"There was a problem updating your message!", "error",
timer: 2000, showConfirmButton: false)
end
end
def delete_status_message(socket, sender) do
# Logger.warn inspect(sender)
user = Accounts.get_user(socket.assigns.user_id, preload: [:account])
index = String.to_integer(sender["dataset"]["index"])
current_message? =
user.account
|> OneChat.Accounts.get_status_message_history()
|> Enum.at(index)
|> Kernel.==(user.account.status_message)
success = fn _ ->
case OneChat.Accounts.delete_status_message(user.account, index) do
{:ok, _account} ->
if current_message? do
broadcast_status_message(socket, user.username, "")
end
socket
|> Query.delete(~s(.status-message-edit-ctrl[data-index="#{index}"]))
|> update_message_ids()
|> SweetAlert.swal(~g"Deleted!", ~g"Your message was Deleted!", "success",
timer: 2000, showConfirmButton: false)
{:error, changeset} ->
Logger.warn inspect(changeset.errors)
SweetAlert.swal(socket, ~g"Error!", ~g"Something went wrong", "error",
timer: 2000, showConfirmButton: false)
end
end
SweetAlert.swal_modal socket, ~g(Are you sure?),
~g(The message will be permanently deleted), "warning",
[
showCancelButton: true, closeOnConfirm: false, closeOnCancel: true,
confirmButtonColor: "#DD6B55", confirmButtonText: ~g(Yes, delete it)
],
confirm: success
end
defp update_message_ids(socket) do
js = """
items = $('.status-message-edit-ctrl');
for(var i = 0; i < items.length; i++) {
$(items[i]).attr('data-index', i).find('[data-index]')
.attr('data-index', i);
}
""" |> String.replace("\n", "")
async_js socket, js
end
def cancel_edit_status_message(socket, sender) do
# Logger.warn inspect(sender)
user = Accounts.get_user(socket.assigns.user_id, preload: [:account])
index = String.to_integer(sender["dataset"]["index"])
current_message =
user.account
|> OneChat.Accounts.get_status_message_history()
|> Enum.at(index)
js = ~s/$('.status-message-edit-ctrl input[data-index="#{index}"]').val('#{current_message}');/ <>
disable_edit_status_control_buttons_js(index)
async_js socket, js
end
def disable_edit_status_control_buttons_js(index) do
"""
$('.status-message-edit-ctrl button.save[data-index="#{index}"]').attr('disabled', true);
$('.status-message-edit-ctrl button.cancel[data-index="#{index}"]').attr('disabled', true);
$('.status-message-edit-ctrl input[data-index="#{index}"]').blur();
""" |> String.replace("\n", "")
end
defp push_status_message_select(account, socket) do
html =
Phoenix.View.render_to_string(OneChatWeb.SideNavView,
"account_box_status_select.html", account: account)
Query.update(socket, :replaceWith, set: html, on: ".status-message-select")
end
defp push_status_message_edit(account, socket) do
html =
Phoenix.View.render_to_string(OneChatWeb.SideNavView,
"account_box_status_edit.html", account: account)
socket
|> Query.update(:html, set: html, on: ".status-message-edit")
|> async_js("$('.status-message-edit').show(); $('.status-message-select').hide()")
end
defp show_status_message_select(socket) do
async_js(socket, "$('.status-message-select').show(); $('.status-message-input').hide();")
socket
end
defp show_status_message_input(socket) do
async_js(socket, "$('.status-message-select').hide(); $('.status-message-input').show();")
socket
end
defp broadcast_status_message(socket, username, message) do
OnePubSub.broadcast "user:all", "status_message:update", %{username: username, message: message}
socket
end
@doc """
The user callback used to update status messages.
This is a OnePubSub Callback.
Note: This is run for all users in the system. It does not check to see if a user is
subscribed or not. It should really to that.
TBD: Implement a filter to only push out if the user is subscribed to this person.
"""
def status_message_update("status_message:update", %{username: username, message: message}, socket) do
Query.update socket, :text, set: message, on: ~s(.status-message[data-username="#{username}"])
end
# End of States messages implementation
# TOOD: this needs to be moved like the video stuff
def start_audio_call(socket, sender) do
current_user_id = socket.assigns.user_id
user_id = sender["dataset"]["id"]
Logger.debug fn -> "start audio curr_id: #{current_user_id}, user_id: #{user_id}" end
socket
end
def new_subscription(_event, payload, socket) do
trace "new_subscription", payload
socket
|> update_rooms_list()
# |> update_rooms_list(user_id, channel_id)
# |> update_messages_header(true)
end
def delete_subscription(_event, payload, socket) do
channel_id = payload.channel_id
user_id = socket.assigns.user_id
socket
|> OneChatWeb.Client.close_flex_bar()
|> update_rooms_list(user_id, channel_id)
|> update_message_box(user_id, channel_id)
|> update_messages_header(false)
end
def unread_update(_, payload, socket) do
subscription = payload.subscription
unread = payload.unread
broadcast_js socket, """
$('.link-room-#{subscription.channel.name}')
.addClass('has-unread')
.addClass('has-alert')
.find('.unread').remove();
$('.link-room-#{subscription.channel.name} a.open-room')
.prepend('<span class="unread">#{unread}</span>');
"""
push socket, "update:alerts", %{}
end
def logout(_event, payload, socket) do
key = Rebel.Core.exec_js!(socket, ~s/window.ucxchat.key/)
if key == payload.creds do
Client.toastr(socket, :warning,
~g(Logging you out. Someone logged into your account from another device.))
spawn fn ->
Process.sleep(3_000)
Rebel.Core.async_js(socket, ~s(window.location.href="/logout"))
end
end
socket
end
def room_update(_event, payload, socket) do
trace "room_update", payload
channel_id = payload.channel_id
user_id = socket.assigns.user_id
do_room_update(socket, payload[:field], user_id, channel_id)
end
defp do_room_update(socket, {:name, new_room}, user_id, channel_id) do
room = socket.assigns.room
RoomChannel.broadcast_name_change(room, new_room, user_id, channel_id)
# broadcast message header on room channel
# broadcast room entry on user channel
socket
end
defp do_room_update(socket, {:topic, data}, _user_id, _channel_id) do
trace "do_room_update", {:topic, data}
RoomChannel.broadcast_room_field(socket.assigns.room, "topic", data)
socket
end
defp do_room_update(socket, {:description, data}, _user_id, _channel_id) do
trace "do_room_update", {:description, data}
RoomChannel.broadcast_room_field(socket.assigns.room, "description", data)
socket
end
defp do_room_update(socket, {:type, type}, user_id, channel_id) do
trace "do_room_update", {:type, type}
# Logger.error "room: #{socket.assigns.room}, type: #{inspect type}"
icon_name = ChannelService.get_icon(type)
room_name = socket.assigns.room
RoomChannel.broadcast_room_field room_name, "room-icon", icon_name
RoomChannel.broadcast_message_box(socket.assigns.room, channel_id, user_id)
set_room_icon(socket, room_name, icon_name)
end
defp do_room_update(socket, {:read_only, data}, user_id, channel_id) do
trace "do_room_update", {:read_only, data}
RoomChannel.broadcast_message_box(socket.assigns.room, channel_id, user_id)
end
defp do_room_update(socket, {:archived, value}, user_id, channel_id) do
trace "do_room_update", {:archive, value}
value = to_atom(value)
room_name = socket.assigns.room
RoomChannel.broadcast_message_box(room_name, channel_id, user_id)
update_room_visibility socket, channel_id, room_name, not value
end
defp do_room_update(socket, field, _user_id, _channel_id) do
Logger.warn fn -> "Default case. Should not be called. field: " <>
"#{inspect field}, assigns: #{inspect socket.assigns}" end
socket
end
defp update_room_visibility(socket, channel_id, room_name, visible?) do
[channel_id: channel_id]
|> Subscription.list_by
|> Enum.each(fn %{user_id: user_id} ->
Logger.debug fn -> "broadcast update room room-visibility to user_id: #{inspect user_id}" end
socket.endpoint.broadcast CC.chan_user <> user_id, "update:room-visibility",
%{visible: visible?, room_name: room_name, user_id: user_id, channel_id: channel_id}
end)
socket
end
defp update_rooms_list(socket, user_id, channel_id) do
trace "update_room_visibility", {user_id, channel_id}
update socket, :html,
set: SideNavService.render_rooms_list(channel_id, user_id),
on: "aside.side-nav .rooms-list"
socket
end
def webrtc_offer(event, payload, socket) do
trace event, payload, inspect(socket.assigns)
socket
end
# defp broadcast_rooms_list(socket, user_id, channel_id) do
# socket
# end
defp update_message_box(%{assigns: %{channel_id: channel_id}} = socket, user_id, channel_id) do
update socket, :html,
set: WebMessage.render_message_box(channel_id, user_id),
on: ".room-container footer.footer"
socket
end
defp update_message_box(socket, _user_id, _channel_id) do
socket
end
defp update_messages_header(socket, show) do
html = Phoenix.View.render_to_string MasterView, "favorite_icon.html",
show: show, favorite: false
async_js socket,
~s/$('section.messages-container .toggle-favorite').replaceWith('#{html}')/
socket
end
def video_stop(socket, sender) do
trace "video_stop", sender
broadcast_js(socket, "window.WebRTC.hangup()")
execute(socket, :click, on: ".tab-button.active")
end
@doc """
Handle and event targeted to all users on the system.
The event handles for a "user:all" event generated by the OnePubSub system.
This is a generic handler that simply runs the callback provided in the
payload map. The socket is provided to the callback so it can use Rebel
perform updates on the client side.
This event handler allows decoupled access to the client from any plugin.
"""
def user_all_event("callback" = evt, %{callback: callback, payload: payload}, socket) do
callback.(evt, payload, socket)
end
def user_all_event("avatar:change", payload, socket) do
if payload.user_id == socket.assigns.user_id do
Client.toastr socket, :success, ~g(Your Avatar had been updated!)
end
Client.update_user_avatar(socket, payload.username, payload.url)
end
def user_all_event("account:change", %{user_id: id} = payload, %{assigns: %{user_id: id}} = socket) do
Client.update_client_account_setting(socket, payload.field, payload.value)
socket
end
def user_all_event("account:change", _payload, socket) do
socket
end
def click_status(socket, sender) do
user_id = socket.assigns.user_id
status = sender["dataset"]["status"] || ""
OnePubSub.broadcast "status:" <> user_id, "set:" <> status, sender["dataset"]
execute socket, :click, on: ".account-box.active"
end
def phone_call(socket, sender) do
# Logger.warn "click to call... #{inspect sender}"
username = sender["dataset"]["phoneStatus"]
# TODO: Need to use a unique Id here instead of the userkame
OnePubSub.broadcast "user:" <> socket.assigns.user_id, "phone:call",
%{username: username}
socket
end
def remove_user(socket, %{} = sender) do
remove_user socket, sender["dataset"]["id"]
end
def remove_user(socket, user_id) do
current_user = Accounts.get_user socket.assigns.user_id, preload: [:roles, user_roles: :role]
user = Accounts.get_user user_id
channel = Channel.get socket.assigns.channel_id
case WebChannel.remove_user channel, user.id, current_user do
{:ok, _message} ->
js = """
var user_view = $('.user-view[data-username="#{user.username}"]');
if (!user_view.hasClass('animated-hidden')) {
user_view.find('.button.back').click();
}
"""
|> String.replace("\n", "")
socket.endpoint.broadcast CC.chan_room <> channel.name,
"update:remove_user", %{username: user.username, js: js}
Client.toastr! socket, :success, ~g(User removed)
{:error, message} ->
Client.toastr! socket, :error, message
end
end
def mousedown(socket, _sender) do
# Logger.debug "mousedown sender: #{inspect sender}"
socket
end
def delegate(socket, sender) do
# Logger.warn "delegate sender: #{inspect sender}"
dataset = sender["dataset"]
mod = Module.concat(dataset["module"], nil)
fun = String.to_existing_atom dataset["fun"]
apply mod, fun, [socket, sender]
end
def phone_number(socket, sender, client \\ OneChatWeb.Client) do
# Logger.warn "phone_number sender: #{inspect sender}"
unless sender["html"] =~ "phone-cog" do
html = Phoenix.View.render_to_string FlexBarView, "phone_cog.html",
phone: sender["dataset"]["phone"]
# Logger.warn "phone_number html: #{inspect html}"
client.append(socket, this(sender), html)
end
socket
end
# def toggle_webrtc_enabled(socket, sender) do
# user = Accounts.get_user socket.assigns.user_id
# # form = sender["form"]
# id = "#" <> sender["dataset"]["id"]
# start_loading_animation(socket, id)
# val = !Rebel.Query.select(socket, prop: "checked", from: id)
# with {:ok, user} <- Accounts.update_user(user, %{webrtc_enabled: val}),
# client <- Mscs.Client.get(user.id),
# true <- is_nil(client.mac) and val,
# {:ok, _client} <- Mscs.Client.add_mac_address!(client) do
# handle_webrtc_enabled_success(socket, val, id)
# else
# false ->
# handle_webrtc_enabled_success(socket, val, id)
# {:error, _} ->
# Client.toastr! socket, :error, ~g(Problem updating WebRTC mode)
# end
# |> stop_loading_animation()
# end
# # TODO: Don't think we need this
# def toggle_webrtc_enabled_change(socket, sender) do
# Logger.warn inspect(sender)
# socket
# end
# defp handle_webrtc_enabled_success(socket, val, id) do
# Rebel.Query.update socket, prop: "checked", set: val, on: id
# msg =
# if val do
# # InfinityOne.TabBar.show_button("mscs")
# ~g(WebRTC Enabled!)
# else
# # InfinityOne.TabBar.hide_button("mscs")
# ~g(WebRTC Disabled!)
# end
# socket
# |> OneUiFlexTab.FlexTabChannel.refresh_tab_bar
# |> Client.toastr!(:success, msg)
# end
def close_phone_cog(socket, sender, client \\ OneChatWeb.Client) do
# Logger.warn "close_phone_cog sender: #{inspect sender}"
client.remove_closest socket, this(sender), "a.phone-number", ".phone-cog"
end
def add_phone_number(socket, sender, client \\ OneChatWeb.Client) do
user_id = sender["dataset"]["userId"]
html = Phoenix.View.render_to_string FlexBarView, "new_phone_number.html", user: %{id: user_id}
client.html socket, "fieldset.phone-numbers", html
socket
end
def delete_phone_number(socket, sender, client \\ OneChatWeb.Client) do
user_id = sender["form"]["user[id]"]
html = Phoenix.View.render_to_string FlexBarView, "add_phone_number_button.html", user: %{id: user_id}
client.html socket, "fieldset.phone-numbers", html
socket
end
defp update_side_nav_item(socket, user, room) do
push_side_nav_item_link socket, user, room
end
defp update_messages_header_icons(socket, room, true) do
push_messages_header_icons(socket, %{active_room: room})
end
defp update_messages_header_icons(socket, _room, _) do
socket
end
def audit_open_rooms(socket) do
assigns = socket.assigns
if UserService.open_channel_count(assigns.user_id) > 1 do
opens = UserService.open_channels(assigns.user_id)
|> Enum.map(& &1.name)
user = Accounts.get_user(assigns.user_id)
Logger.error "found more than one open, room: " <>
"username: #{user.username}, #{inspect assigns.room}, opens: #{inspect opens}"
end
socket
end
defp unsubscribe(socket, room) do
assign(socket, :subscribed, List.delete(socket.assigns.subscribed, room))
end
defp to_atom(value) when is_atom(value), do: value
defp to_atom(value) when is_binary(value), do: String.to_existing_atom(value)
defdelegate flex_tab_click(socket, sender), to: FlexTabChannel
defdelegate flex_tab_open(socket, sender), to: FlexTabChannel
defdelegate flex_call(socket, sender), to: FlexTabChannel
defdelegate flex_close(socket, sender), to: FlexTabChannel
defdelegate flex_form(socket, sender), to: Form
defdelegate flex_form_change(socket, sender), to: Form
defdelegate flex_form_save(socket, sender), to: Form
defdelegate flex_form_submit(socket, sender), to: Form
defdelegate flex_form_cancel(socket, sender), to: Form
defdelegate flex_form_toggle(socket, sender), to: Form
defdelegate flex_form_select_change(socket, sender), to: Form
defdelegate flex_form_delete(socket, sender), to: Form
defdelegate side_nav_search_click(socket, sender), to: __MODULE__.SideNav.Search, as: :search_click
defdelegate side_nav_search_keydown(socket, sender), to: __MODULE__.SideNav.Search, as: :search_keydown
defdelegate side_nav_search_blur(socket, sender), to: __MODULE__.SideNav.Search, as: :search_blur
defdelegate side_nav_channels_select(socket, sender), to: __MODULE__.SideNav.Channels, as: :channels_select
defdelegate side_nav_channels_search(socket, sender), to: __MODULE__.SideNav.Channels, as: :channels_search
defdelegate side_nav_create_channel(socket, sender), to: __MODULE__.SideNav.Channels, as: :create_channel
defdelegate side_nav_create_channel_search_members(socket, sender), to: __MODULE__.SideNav.Channels, as: :create_channel_search_members
defdelegate side_nav_create_channel_save(socket, sender), to: __MODULE__.SideNav.Channels, as: :create_channel_save
defdelegate side_nav_create_channel_cancel(socket, sender), to: __MODULE__.SideNav.Channels, as: :create_channel_cancel
defdelegate side_nav_create_channel_select_member(socket, sender), to: __MODULE__.SideNav.Channels, as: :create_channel_select_member
defdelegate side_nav_create_channel_remove_member(socket, sender), to: __MODULE__.SideNav.Channels, as: :create_channel_remove_member
defdelegate side_nav_open_direct(socket, sender), to: __MODULE__.SideNav.Directs, as: :open_direct
defdelegate add_private(socket, sender), to: OneChatWeb.RoomChannel.MessageInput.Channels
defdelegate admin_restart_server(socket, sender), to: OneAdminWeb.AdminChannel
defdelegate admin_delete_backup(socket, sender), to: OneBackupRestoreWeb.Admin.Page.BackupRestore
defdelegate admin_backup_batch_delete(socket, sender), to: OneBackupRestoreWeb.Admin.Page.BackupRestore
defdelegate admin_restore_backup(socket, sender), to: OneBackupRestoreWeb.Admin.Page.BackupRestore
defdelegate admin_download_cert(socket, sender), to: OneBackupRestoreWeb.FlexBar.Tab.GenCert
defdelegate admin_regen_cert(socket, sender), to: OneBackupRestoreWeb.FlexBar.Tab.GenCert
defdelegate admin_delete_invition(socket, sender), to: OneAdminWeb.FlexBar.Tab.InviteUsers, as: :delete_invitation
# TODO: Figure out a way to inject this from the Dialer module
defdelegate dial(socket, sender), to: OneDialerWeb.Channel.Dialer
# defdelegate click_admin(socket, sender), to: OneAdminWeb.AdminChannel
defdelegateadmin :click_admin
defdelegateadmin :admin_link
defdelegateadmin :admin_flex
defdelegateadmin :admin_user_roles
defdelegateadmin :admin_add_user_role
defdelegateadmin :admin_user_role_remove
defdelegateadmin :admin_click_user_role_member
defdelegateadmin :admin_user_role_search_channel
# defdelegateadmin :admin_user_role_search_rooms
# defdelegateadmin :admin_user_role_search_pages
defdelegateadmin :admin_click_scoped_room
defdelegateadmin :admin_autocomplete_mouseenter
defdelegateadmin :admin_reset_setting_click
defdelegateadmin :admin_new_pattern
end
| 32.90513 | 137 | 0.659302 |
e83c39a26bdb8b2e14fd1ef2ec49089ee70be303 | 4,491 | exs | Elixir | test/glimesh_web/live/category_live_test.exs | itsUnsmart/glimesh.tv | 22c532184bb5046f6c6d8232e8bd66ba534c01c1 | [
"MIT"
] | 1 | 2020-08-02T00:12:28.000Z | 2020-08-02T00:12:28.000Z | test/glimesh_web/live/category_live_test.exs | itsUnsmart/glimesh.tv | 22c532184bb5046f6c6d8232e8bd66ba534c01c1 | [
"MIT"
] | null | null | null | test/glimesh_web/live/category_live_test.exs | itsUnsmart/glimesh.tv | 22c532184bb5046f6c6d8232e8bd66ba534c01c1 | [
"MIT"
] | null | null | null | defmodule GlimeshWeb.CategoryLiveTest do
use GlimeshWeb.ConnCase
import Phoenix.LiveViewTest
alias Glimesh.Streams
@create_attrs %{
name: "some name"
}
@update_attrs %{
name: "some updated name"
}
@invalid_attrs %{name: nil}
defp fixture(:category, parent_category) do
{:ok, category} =
Streams.create_category(@create_attrs |> Enum.into(%{parent_id: parent_category.id}))
category
end
defp fixture(:parent_category) do
{:ok, category} =
Streams.create_category(%{
name: "some parent",
parent_id: nil
})
category
end
defp create_category(_) do
parent_category = fixture(:parent_category)
category = fixture(:category, parent_category)
%{parent_category: parent_category, category: category}
end
describe "Category Normal User Functionality" do
test "lists all categories", %{conn: conn} do
{:error, {:redirect, param}} = live(conn, Routes.category_index_path(conn, :index))
assert param.to =~ "/users/log_in"
end
end
describe "Category Admin Functionality" do
setup [:register_and_log_in_admin_user, :create_category]
test "lists all categories", %{conn: conn, category: category} do
{:ok, _index_live, html} = live(conn, Routes.category_index_path(conn, :index))
assert html =~ "Listing Categories"
assert html =~ category.name
end
test "saves new category", %{conn: conn, parent_category: parent_category} do
{:ok, index_live, _html} = live(conn, Routes.category_index_path(conn, :index))
assert index_live |> element("a", "New Category") |> render_click() =~
"New Category"
assert_patch(index_live, Routes.category_index_path(conn, :new))
assert index_live
|> form("#category-form", category: @invalid_attrs)
|> render_change() =~ "Cannot be blank"
new_input = %{name: "some new category", parent_id: parent_category.id}
{:ok, _, html} =
index_live
|> form("#category-form", category: new_input)
|> render_submit()
|> follow_redirect(conn, Routes.category_index_path(conn, :index))
assert html =~ "Category created successfully"
assert html =~ "some new category"
end
test "updates category in listing", %{conn: conn, category: category} do
{:ok, index_live, _html} = live(conn, Routes.category_index_path(conn, :index))
assert index_live |> element("#category-#{category.id} a", "Edit") |> render_click() =~
"Edit Category"
assert_patch(index_live, Routes.category_index_path(conn, :edit, category))
assert index_live
|> form("#category-form", category: @invalid_attrs)
|> render_change() =~ "Cannot be blank"
{:ok, _, html} =
index_live
|> form("#category-form", category: @update_attrs)
|> render_submit()
|> follow_redirect(conn, Routes.category_index_path(conn, :index))
assert html =~ "Category updated successfully"
assert html =~ "some updated name"
end
test "deletes category in listing", %{conn: conn, category: category} do
{:ok, index_live, _html} = live(conn, Routes.category_index_path(conn, :index))
assert index_live |> element("#category-#{category.id} a", "Delete") |> render_click()
refute has_element?(index_live, "#category-#{category.id}")
end
test "displays category", %{conn: conn, category: category} do
{:ok, _show_live, html} = live(conn, Routes.category_show_path(conn, :show, category))
assert html =~ "Show Category"
assert html =~ category.name
end
test "updates category within modal", %{conn: conn, category: category} do
{:ok, show_live, _html} = live(conn, Routes.category_show_path(conn, :show, category))
assert show_live |> element("a", "Edit") |> render_click() =~
"Edit Category"
assert_patch(show_live, Routes.category_show_path(conn, :edit, category))
assert show_live
|> form("#category-form", category: @invalid_attrs)
|> render_change() =~ "Cannot be blank"
{:ok, _, html} =
show_live
|> form("#category-form", category: @update_attrs)
|> render_submit()
|> follow_redirect(conn, Routes.category_show_path(conn, :show, category))
assert html =~ "Category updated successfully"
assert html =~ "some updated name"
end
end
end
| 32.078571 | 93 | 0.643509 |
e83c451ed0799332a3f0d335bcb99d93003ce72a | 338 | ex | Elixir | lib/sobelow/misc.ex | rahiparikh/sobelow | ed2ff5ea2648a1decb8d43b35100f833a1aa6c95 | [
"Apache-2.0"
] | null | null | null | lib/sobelow/misc.ex | rahiparikh/sobelow | ed2ff5ea2648a1decb8d43b35100f833a1aa6c95 | [
"Apache-2.0"
] | null | null | null | lib/sobelow/misc.ex | rahiparikh/sobelow | ed2ff5ea2648a1decb8d43b35100f833a1aa6c95 | [
"Apache-2.0"
] | null | null | null | defmodule Sobelow.Misc do
@submodules [Sobelow.Misc.BinToTerm, Sobelow.Misc.FilePath]
use Sobelow.FindingType
def get_vulns(fun, meta_file, _web_root, skip_mods \\ []) do
allowed = @submodules -- (Sobelow.get_ignored() ++ skip_mods)
Enum.each(allowed, fn mod ->
apply(mod, :run, [fun, meta_file])
end)
end
end
| 26 | 65 | 0.686391 |
e83c45936f044fffd504880e0a147d1936175597 | 9,803 | ex | Elixir | lib/ex_unit/lib/ex_unit/runner.ex | evalphobia/elixir | a07a2362e5827b09d8b27be2c1ad2980d25b9768 | [
"Apache-2.0"
] | null | null | null | lib/ex_unit/lib/ex_unit/runner.ex | evalphobia/elixir | a07a2362e5827b09d8b27be2c1ad2980d25b9768 | [
"Apache-2.0"
] | null | null | null | lib/ex_unit/lib/ex_unit/runner.ex | evalphobia/elixir | a07a2362e5827b09d8b27be2c1ad2980d25b9768 | [
"Apache-2.0"
] | null | null | null | defmodule ExUnit.Runner do
@moduledoc false
alias ExUnit.EventManager, as: EM
def run(opts, load_us) do
{opts, config} = configure(opts)
:erlang.system_flag(:backtrace_depth,
Keyword.fetch!(opts, :stacktrace_depth))
{run_us, _} =
:timer.tc fn ->
EM.suite_started(config.manager, opts)
loop(config, 0)
end
EM.suite_finished(config.manager, run_us, load_us)
result = ExUnit.RunnerStats.stats(config.stats)
EM.stop(config.manager)
result
end
defp configure(opts) do
opts = normalize_opts(opts)
{:ok, manager} = EM.start_link
{:ok, stats} = EM.add_handler(manager, ExUnit.RunnerStats, opts)
Enum.each opts[:formatters], &EM.add_handler(manager, &1, opts)
config = %{
capture_log: opts[:capture_log],
exclude: opts[:exclude],
include: opts[:include],
manager: manager,
stats: stats,
max_cases: opts[:max_cases],
seed: opts[:seed],
cases: :async,
timeout: opts[:timeout],
trace: opts[:trace]
}
{opts, config}
end
defp normalize_opts(opts) do
{include, exclude} = ExUnit.Filters.normalize(opts[:include], opts[:exclude])
opts
|> Keyword.put(:exclude, exclude)
|> Keyword.put(:include, include)
end
defp loop(%{cases: :async} = config, taken) do
available = config.max_cases - taken
cond do
# No cases available, wait for one
available <= 0 ->
wait_until_available(config, taken)
# Slots are available, start with async cases
cases = ExUnit.Server.take_async_cases(available) ->
spawn_cases(config, cases, taken)
true ->
cases = ExUnit.Server.take_sync_cases()
loop(%{config | cases: cases}, taken)
end
end
defp loop(%{cases: cases} = config, taken) do
case cases do
_ when taken > 0 ->
wait_until_available(config, taken)
# So we can start all sync cases
[h | t] ->
spawn_cases(%{config | cases: t}, [h], taken)
# No more cases, we are done!
[] ->
config
end
end
# Loop expecting messages from the spawned cases. Whenever
# a test case has finished executing, decrease the taken
# cases counter and attempt to spawn new ones.
defp wait_until_available(config, taken) do
receive do
{_pid, :case_finished, _test_case} ->
loop(config, taken - 1)
end
end
defp spawn_cases(config, cases, taken) do
pid = self()
Enum.each cases, fn case_name ->
spawn_link fn ->
run_case(config, pid, case_name)
end
end
loop(config, taken + length(cases))
end
defp run_case(config, pid, case_name) do
test_case = case_name.__ex_unit__(:case)
EM.case_started(config.manager, test_case)
# Prepare tests, selecting which ones should
# run and which ones were skipped.
tests = prepare_tests(config, test_case.tests)
{test_case, pending} =
if Enum.all?(tests, &(&1.state)) do
{test_case, tests}
else
spawn_case(config, test_case, tests)
end
# Run the pending tests. We don't actually spawn those
# tests but we do send the notifications to formatter.
Enum.each pending, &run_test(config, &1, [])
EM.case_finished(config.manager, test_case)
send pid, {self(), :case_finished, test_case}
end
defp prepare_tests(config, tests) do
tests = shuffle(config, tests)
include = config.include
exclude = config.exclude
for test <- tests do
tags = Map.merge(test.tags, %{test: test.name, case: test.case})
case ExUnit.Filters.eval(include, exclude, tags, tests) do
:ok -> %{test | tags: tags}
{:error, msg} -> %{test | state: {:skip, msg}}
end
end
end
defp spawn_case(config, test_case, tests) do
parent = self()
{case_pid, case_ref} =
spawn_monitor(fn ->
ExUnit.OnExitHandler.register(self())
case exec_case_setup(test_case) do
{:ok, test_case, context} ->
Enum.each tests, &run_test(config, &1, context)
send parent, {self(), :case_finished, test_case, []}
{:error, test_case} ->
failed_tests = Enum.map tests, & %{&1 | state: {:invalid, test_case}}
send parent, {self(), :case_finished, test_case, failed_tests}
end
exit(:shutdown)
end)
{test_case, pending} =
receive do
{^case_pid, :case_finished, test_case, tests} ->
receive do
{:DOWN, ^case_ref, :process, ^case_pid, _} -> :ok
end
{test_case, tests}
{:DOWN, ^case_ref, :process, ^case_pid, error} ->
test_case = %{test_case | state: failed({:EXIT, case_pid}, error, [])}
{test_case, []}
end
timeout = get_timeout(%{}, config)
{exec_on_exit(test_case, case_pid, timeout), pending}
end
defp exec_case_setup(%ExUnit.TestCase{name: case_name} = test_case) do
{:ok, test_case, case_name.__ex_unit__(:setup_all, %{case: case_name})}
catch
kind, error ->
failed = failed(kind, error, pruned_stacktrace())
{:error, %{test_case | state: failed}}
end
defp run_test(true, config, test, context) do
run_test([], config, test, context)
end
defp run_test(false, config, test, context) do
spawn_test(config, test, context)
end
defp run_test(opts, config, test, context) do
ref = make_ref()
try do
ExUnit.CaptureLog.capture_log(opts, fn ->
send self(), {ref, spawn_test(config, test, context)}
end)
catch
:exit, :noproc ->
message =
"could not run test, it uses @tag :capture_log" <>
" but the :logger application is not running"
%{test | state: failed(:error, RuntimeError.exception(message), [])}
else
logged ->
receive do
{^ref, test} -> %{test | logs: logged}
end
end
end
defp run_test(config, %{tags: tags} = test, context) do
EM.test_started(config.manager, test)
test =
if is_nil(test.state) do
capture_log? = Map.get(tags, :capture_log, config.capture_log)
run_test(capture_log?, config, test, Map.merge(tags, context))
else
test
end
EM.test_finished(config.manager, test)
end
defp spawn_test(config, test, context) do
parent = self()
{test_pid, test_ref} =
spawn_monitor(fn ->
ExUnit.OnExitHandler.register(self())
{us, test} =
:timer.tc(fn ->
case exec_test_setup(test, context) do
{:ok, test} ->
exec_test(test)
{:error, test} ->
test
end
end)
send parent, {self(), :test_finished, %{test | time: us}}
exit(:shutdown)
end)
timeout = get_timeout(test.tags, config)
test = receive_test_reply(test, test_pid, test_ref, timeout)
exec_on_exit(test, test_pid, timeout)
end
defp receive_test_reply(test, test_pid, test_ref, timeout) do
receive do
{^test_pid, :test_finished, test} ->
receive do
{:DOWN, ^test_ref, :process, ^test_pid, _} -> :ok
end
test
{:DOWN, ^test_ref, :process, ^test_pid, error} ->
%{test | state: failed({:EXIT, test_pid}, error, [])}
after
timeout ->
case Process.info(test_pid, :current_stacktrace) do
{:current_stacktrace, stacktrace} ->
Process.exit(test_pid, :kill)
receive do
{:DOWN, ^test_ref, :process, ^test_pid, _} -> :ok
end
exception = ExUnit.TimeoutError.exception(timeout: timeout, type: test.tags.type)
%{test | state: failed(:error, exception, stacktrace)}
nil ->
receive_test_reply(test, test_pid, test_ref, timeout)
end
end
end
defp exec_test_setup(%ExUnit.Test{case: case} = test, context) do
{:ok, %{test | tags: case.__ex_unit__(:setup, context)}}
catch
kind, error ->
{:error, %{test | state: failed(kind, error, pruned_stacktrace())}}
end
defp exec_test(%ExUnit.Test{case: case, name: name, tags: context} = test) do
apply(case, name, [context])
test
catch
kind, error ->
%{test | state: failed(kind, error, pruned_stacktrace())}
end
defp exec_on_exit(test_or_case, pid, timeout) do
case ExUnit.OnExitHandler.run(pid, timeout) do
:ok ->
test_or_case
{kind, reason, stack} ->
state = test_or_case.state || failed(kind, reason, prune_stacktrace(stack))
%{test_or_case | state: state}
end
end
## Helpers
defp get_timeout(tags, config) do
if config.trace do
:infinity
else
Map.get(tags, :timeout, config.timeout)
end
end
defp shuffle(%{seed: 0}, list) do
Enum.reverse(list)
end
defp shuffle(%{seed: seed}, list) do
_ = :rand.seed(:exsplus, {3172, 9814, seed})
Enum.shuffle(list)
end
defp failed(:error, %ExUnit.MultiError{errors: errors}, _stack) do
{:failed,
Enum.map(errors, fn {kind, reason, stack} ->
{kind, Exception.normalize(kind, reason), prune_stacktrace(stack)}
end)}
end
defp failed(kind, reason, stack) do
{:failed, [{kind, Exception.normalize(kind, reason), stack}]}
end
defp pruned_stacktrace, do: prune_stacktrace(System.stacktrace)
# Assertions can pop-up in the middle of the stack
defp prune_stacktrace([{ExUnit.Assertions, _, _, _} | t]), do: prune_stacktrace(t)
# As soon as we see a Runner, it is time to ignore the stacktrace
defp prune_stacktrace([{ExUnit.Runner, _, _, _} | _]), do: []
# All other cases
defp prune_stacktrace([h | t]), do: [h | prune_stacktrace(t)]
defp prune_stacktrace([]), do: []
end
| 27.928775 | 93 | 0.608385 |
e83c53d64c4ee72b0ec1cd0adacbe0f517697ad7 | 14,158 | ex | Elixir | lib/eml/html/parser.ex | clemensm/eml | e2dc3dc605d2a61ccbdca1901a444a123abd8e94 | [
"Apache-2.0"
] | null | null | null | lib/eml/html/parser.ex | clemensm/eml | e2dc3dc605d2a61ccbdca1901a444a123abd8e94 | [
"Apache-2.0"
] | null | null | null | lib/eml/html/parser.ex | clemensm/eml | e2dc3dc605d2a61ccbdca1901a444a123abd8e94 | [
"Apache-2.0"
] | null | null | null | defmodule Eml.HTML.Parser do
@moduledoc false
# API
@spec parse(binary, Keyword.t) :: [Eml.t]
def parse(html, opts \\ []) do
res = tokenize(html, { :blank, [] }, [], :blank, opts) |> parse_content(opts)
case res do
{ content, [] } ->
content
{ content, rest }->
raise Eml.ParseError, message: "Unparsable content, parsed: #{inspect content}, rest: #{inspect rest}"
end
end
# Tokenize
# Skip comments
defp tokenize("<!--" <> rest, buf, acc, state, opts)
when state != :comment do
tokenize(rest, buf, acc, :comment, opts)
end
defp tokenize("-->" <> rest, buf, acc, :comment, opts) do
{ state, _ } = buf
tokenize(rest, buf, acc, state, opts)
end
defp tokenize(<<_>> <> rest, buf, acc, :comment, opts) do
tokenize(rest, buf, acc, :comment, opts)
end
# Skip doctype
defp tokenize("<!DOCTYPE" <> rest, buf, acc, :blank, opts) do
tokenize(rest, buf, acc, :doctype, opts)
end
defp tokenize("<!doctype" <> rest, buf, acc, :blank, opts) do
tokenize(rest, buf, acc, :doctype, opts)
end
defp tokenize(">" <> rest, buf, acc, :doctype, opts) do
tokenize(rest, buf, acc, :blank, opts)
end
defp tokenize(<<_>> <> rest, buf, acc, :doctype, opts) do
tokenize(rest, buf, acc, :doctype, opts)
end
# CDATA
defp tokenize("<![CDATA[" <> rest, buf, acc, state, opts)
when state in [:content, :blank, :start_close, :end_close, :close] do
next(rest, buf, "", acc, :cdata, opts)
end
defp tokenize("]]>" <> rest, buf, acc, :cdata, opts) do
next(rest, buf, "", acc, :content, opts)
end
defp tokenize(<<char>> <> rest, buf, acc, :cdata, opts) do
consume(char, rest, buf, acc, :cdata, opts)
end
# Makes it possible for elements to treat its contents as if cdata
defp tokenize(chars, buf, acc, { :cdata, end_tag } = state, opts) do
end_token = "</" <> end_tag <> ">"
n = byte_size(end_token)
case chars do
<<^end_token::binary-size(n), rest::binary>> ->
acc = change(buf, acc, :cdata)
acc = change({ :open, "<" }, acc)
acc = change({ :slash, "/" }, acc)
acc = change({ :end_tag, end_tag }, acc)
tokenize(rest, { :end_close, ">" }, acc, :end_close, opts)
<<char>> <> rest ->
consume(char, rest, buf, acc, state, opts)
"" ->
:lists.reverse([buf | acc])
end
end
# Attribute quotes
defp tokenize("'" <> rest, buf, acc, :attr_sep, opts) do
next(rest, buf, "'", acc, :attr_single_open, opts)
end
defp tokenize("\"" <> rest, buf, acc, :attr_sep, opts) do
next(rest, buf, "\"", acc, :attr_double_open, opts)
end
defp tokenize(<<char>> <> rest, buf, acc, :attr_value, opts) when char in [?\", ?\'] do
case { char, previous_state(acc, [:attr_value]) } do
t when t in [{ ?\', :attr_single_open }, { ?\", :attr_double_open }] ->
next(rest, buf, char, acc, :attr_close, opts)
_else ->
consume(char, rest, buf, acc, :attr_value, opts)
end
end
defp tokenize(<<char>> <> rest, buf, acc, state, opts)
when { char, state } in [{ ?\', :attr_single_open }, { ?\", :attr_double_open }] do
next(rest, buf, char, acc, :attr_close, opts)
end
# Attributes values accept any character
defp tokenize(<<char>> <> rest, buf, acc, state, opts)
when state in [:attr_single_open, :attr_double_open] do
next(rest, buf, char, acc, :attr_value, opts)
end
defp tokenize(<<char>> <> rest, buf, acc, :attr_value, opts) do
consume(char, rest, buf, acc, :attr_value, opts)
end
# Attribute field/value seperator
defp tokenize("=" <> rest, buf, acc, :attr_field, opts) do
next(rest, buf, "=", acc, :attr_sep, opts)
end
# Allow boolean attributes, ie. attributes with only a field name
defp tokenize(<<char>> <> rest, buf, acc, :attr_field, opts)
when char in [?\>, ?\s, ?\n, ?\r, ?\t] do
next(<<char, rest::binary>>, buf, "\"", acc, :attr_close, opts)
end
# Whitespace handling
defp tokenize(<<char>> <> rest, buf, acc, state, opts)
when char in [?\s, ?\n, ?\r, ?\t] do
case state do
:start_tag ->
next(rest, buf, "", acc, :start_tag_close, opts)
s when s in [:close, :start_close, :end_close] ->
if char in [?\n, ?\r] do
next(rest, buf, "", acc, :content, opts)
else
next(rest, buf, char, acc, :content, opts)
end
:content ->
consume(char, rest, buf, acc, state, opts)
_ ->
tokenize(rest, buf, acc, state, opts)
end
end
# Open tag
defp tokenize("<" <> rest, buf, acc, state, opts) do
case state do
s when s in [:blank, :start_close, :end_close, :close, :content] ->
next(rest, buf, "<", acc, :open, opts)
_ ->
error("<", rest, buf, acc, state)
end
end
# Close tag
defp tokenize(">" <> rest, buf, acc, state, opts) do
case state do
s when s in [:attr_close, :start_tag] ->
# The html tokenizer doesn't support elements without proper closing.
# However, it does makes exceptions for tags specified in is_void_element?/1
# and assume they never have children.
tag = get_last_tag(acc, buf)
if is_void_element?(tag) do
next(rest, buf, ">", acc, :close, opts)
else
# check if the content of the element should be interpreted as cdata
case element_type([buf | acc], List.wrap(opts[:treat_as_cdata])) do
:content ->
next(rest, buf, ">", acc, :start_close, opts)
{ :cdata, tag } ->
acc = change(buf, acc)
next(rest, { :start_close, ">" }, "", acc, { :cdata, tag }, opts)
end
end
:slash ->
next(rest, buf, ">", acc, :close, opts)
:end_tag ->
next(rest, buf, ">", acc, :end_close, opts)
_ ->
def_tokenize(">" <> rest, buf, acc, state, opts)
end
end
# Slash
defp tokenize("/" <> rest, buf, acc, state, opts)
when state in [:open, :attr_field, :attr_close, :start_tag, :start_tag_close] do
next(rest, buf, "/", acc, :slash, opts)
end
defp tokenize("", buf, acc, _, _opts) do
:lists.reverse([buf | acc])
end
# Default parsing
defp tokenize(chars, buf, acc, state, opts), do: def_tokenize(chars, buf, acc, state, opts)
# Either start or consume content or tag.
defp def_tokenize(<<char>> <> rest, buf, acc, state, opts) do
case state do
s when s in [:start_tag, :end_tag, :attr_field, :content] ->
consume(char, rest, buf, acc, state, opts)
s when s in [:blank, :start_close, :end_close, :close] ->
next(rest, buf, char, acc, :content, opts)
s when s in [:attr_close, :start_tag_close] ->
next(rest, buf, char, acc, :attr_field, opts)
:open ->
next(rest, buf, char, acc, :start_tag, opts)
:slash ->
next(rest, buf, char, acc, :end_tag, opts)
_ ->
error(char, rest, buf, acc, state)
end
end
# Stops tokenizing and dumps all info in a tuple
defp error(char, rest, buf, acc, state) do
char = if is_integer(char), do: <<char>>, else: char
state = [state: state,
char: char,
buf: buf,
last_token: List.first(acc),
next_char: String.first(rest)]
raise Eml.ParseError, message: "Illegal token, parse state is: #{inspect state}"
end
# Consumes character and put it in the buffer
defp consume(char, rest, { type, buf }, acc, state, opts) do
char = if is_integer(char), do: <<char>>, else: char
tokenize(rest, { type, buf <> char }, acc, state, opts)
end
# Add the old buffer to the accumulator and start a new buffer
defp next(rest, old_buf, new_buf, acc, new_state, opts) do
acc = change(old_buf, acc)
new_buf = if is_integer(new_buf), do: <<new_buf>>, else: new_buf
tokenize(rest, { new_state, new_buf }, acc, new_state, opts)
end
# Add buffer to the accumulator if its content is not empty.
defp change({ type, buf }, acc, type_modifier \\ nil) do
type = if is_nil(type_modifier), do: type, else: type_modifier
token = { type, buf }
if empty?(token) do
acc
else
[token | acc]
end
end
# Checks for empty content
defp empty?({ :blank, _ }), do: true
defp empty?({ :content, content }) do
String.trim(content) === ""
end
defp empty?(_), do: false
# Checks if last tokenized tag is a tag that should always close.
defp get_last_tag(tokens, { type, buf }) do
get_last_tag([{ type, buf } | tokens])
end
defp get_last_tag([{ :start_tag, tag } | _]), do: tag
defp get_last_tag([_ | ts]), do: get_last_tag(ts)
defp get_last_tag([]), do: nil
defp is_void_element?(tag) do
tag in ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]
end
defp previous_state([{ state, _ } | rest], skip_states) do
if state in skip_states do
previous_state(rest, skip_states)
else
state
end
end
defp previous_state([], _), do: :blank
# CDATA element helper
@cdata_elements ["script", "style"]
defp element_type(acc, extra_cdata_elements) do
cdata_elements = @cdata_elements ++ extra_cdata_elements
case get_last_tag(acc) do
nil ->
:content
tag ->
if tag in cdata_elements do
{ :cdata, tag }
else
:content
end
end
end
# Parse the genrated tokens
defp parse_content(tokens, opts) do
parse_content(tokens, [], opts)
end
defp parse_content([{ type, token } | ts], acc, opts) do
case preparse(type, token) do
:skip ->
parse_content(ts, acc, opts)
{ :tag, tag } ->
{ element, tokens } = parse_element(ts, [tag: tag, attrs: [], content: []], opts)
parse_content(tokens, [element | acc], opts)
{ :content, content } ->
parse_content(ts, [content | acc], opts)
{ :cdata, content } ->
# tag cdata in order to skip whitespace trimming
parse_content(ts, [{ :cdata, content } | acc], opts)
:end_el ->
{ :lists.reverse(acc), ts }
end
end
defp parse_content([], acc, _opts) do
{ :lists.reverse(acc), [] }
end
defp parse_element([{ type, token } | ts], acc, opts) do
case preparse(type, token) do
:skip ->
parse_element(ts, acc, opts)
{ :attr_field, field } ->
attrs = [{ field, "" } | acc[:attrs]]
parse_element(ts, Keyword.put(acc, :attrs, attrs), opts)
{ :attr_value, value } ->
[{ field, current } | rest] = acc[:attrs]
attrs = if is_binary(current) && is_binary(value) do
[{ field, current <> value } | rest]
else
[{ field, List.wrap(current) ++ [value] } | rest]
end
parse_element(ts, Keyword.put(acc, :attrs, attrs), opts)
:start_content ->
{ content, tokens } = parse_content(ts, [], opts)
{ make_element(Keyword.put(acc, :content, content), opts), tokens }
:end_el ->
{ make_element(acc, opts), ts }
end
end
defp parse_element([], acc, opts) do
{ make_element(acc, opts), [] }
end
defp make_element(acc, opts) do
attrs = acc[:attrs]
%Eml.Element{tag: acc[:tag], attrs: Enum.into(attrs, %{}), content: finalize_content(acc[:content], acc[:tag], opts)}
end
defp preparse(:blank, _), do: :skip
defp preparse(:open, _), do: :skip
defp preparse(:slash, _), do: :skip
defp preparse(:attr_single_open, _), do: :skip
defp preparse(:attr_double_open, _), do: :skip
defp preparse(:attr_close, _), do: :skip
defp preparse(:attr_sep, _), do: :skip
defp preparse(:end_tag, _), do: :skip
defp preparse(:start_tag_close, _), do: :skip
defp preparse(:attr_field, token) do
{ :attr_field, String.to_atom(token) }
end
defp preparse(:attr_value, token), do: { :attr_value, token }
defp preparse(:start_tag, token), do: { :tag, String.to_atom(token) }
defp preparse(:start_close, _), do: :start_content
defp preparse(:content, token), do: { :content, token }
defp preparse(:end_close, _), do: :end_el
defp preparse(:close, _), do: :end_el
defp preparse(:cdata, token), do: { :cdata, token }
defp finalize_content(content, tag, _opts)
when tag in [:textarea, :pre] do
case content do
[content] when is_binary(content) ->
content
[] ->
nil
content ->
content
end
end
defp finalize_content(content, _, opts) do
app_default = Application.get_env(:eml, :trim_whitespace, true)
trim_whitespace = Keyword.get(opts, :trim_whitespace, app_default)
case content do
[content] when is_binary(content) ->
if trim_whitespace, do: trim_whitespace(content, :only), else: content
[] ->
nil
[first | rest] ->
if trim_whitespace do
first = trim_whitespace(first, :first)
[first | trim_whitespace_loop(rest, [])]
else
[first | rest]
end
end
end
defp trim_whitespace_loop([last], acc) do
last = trim_whitespace(last, :last)
:lists.reverse([last | acc])
end
defp trim_whitespace_loop([h | t], acc) do
trim_whitespace_loop(t, [trim_whitespace(h, :other) | acc])
end
defp trim_whitespace_loop([], acc) do
acc
end
defp trim_whitespace(content, position) do
trim_whitespace(content, "", false, position)
end
defp trim_whitespace(<<char>> <> rest, acc, in_whitespace?, pos) do
if char in [?\s, ?\n, ?\r, ?\t] do
if in_whitespace? do
trim_whitespace(rest, acc, true, pos)
else
trim_whitespace(rest, acc <> " ", true, pos)
end
else
trim_whitespace(rest, acc <> <<char>>, false, pos)
end
end
defp trim_whitespace("", acc, _, pos) do
case pos do
:first -> String.trim_leading(acc)
:last -> String.trim_trailing(acc)
:only -> String.trim(acc)
:other -> acc
end
end
defp trim_whitespace({ :cdata, noop }, _, _, _), do: noop
defp trim_whitespace(noop, _, _, _), do: noop
end
| 32.69746 | 132 | 0.588713 |
e83c66ed7c0c5557ceec24b0af7f0e359eb37b5d | 13,044 | ex | Elixir | apps/api_web/lib/api_web/router.ex | pacebus/mbta-api-fork | 6bf1d3a16e8917c9cfac0001b184c443be1f3abd | [
"MIT"
] | null | null | null | apps/api_web/lib/api_web/router.ex | pacebus/mbta-api-fork | 6bf1d3a16e8917c9cfac0001b184c443be1f3abd | [
"MIT"
] | null | null | null | apps/api_web/lib/api_web/router.ex | pacebus/mbta-api-fork | 6bf1d3a16e8917c9cfac0001b184c443be1f3abd | [
"MIT"
] | 1 | 2019-09-09T20:40:13.000Z | 2019-09-09T20:40:13.000Z | defmodule ApiWeb.Router do
use ApiWeb.Web, :router
defdelegate set_content_type(conn, opts), to: JaSerializer.ContentTypeNegotiation
@rate_limit_headers """
The HTTP headers returned in any API response show your rate limit status:
| Header | Description |
| ------ | ----------- |
| `x-ratelimit-limit` | The maximum number of requests you're allowed to make per time window. |
| `x-ratelimit-remaining` | The number of requests remaining in the current time window. |
| `x-ratelimit-reset` | The time at which the current rate limit time window ends in UTC epoch seconds. |
"""
pipeline :secure do
if force_ssl = Application.get_env(:site, :secure_pipeline)[:force_ssl] do
plug(Plug.SSL, force_ssl)
end
end
pipeline :browser do
plug(
Plug.Session,
store: :cookie,
key: "_api_key",
signing_salt: Application.get_env(:api_web, :signing_salt)
)
plug(:accepts, ["html"])
plug(:fetch_session)
plug(:fetch_flash)
plug(:protect_from_forgery)
plug(:put_secure_browser_headers)
plug(ApiWeb.Plugs.FetchUser)
end
pipeline :admin_view do
plug(:put_layout, {ApiWeb.Admin.LayoutView, :app})
end
pipeline :admin do
plug(ApiWeb.Plugs.RequireAdmin)
end
pipeline :portal_view do
plug(:put_layout, {ApiWeb.ClientPortal.LayoutView, :app})
end
pipeline :portal do
plug(ApiWeb.Plugs.RequireUser)
end
pipeline :api do
plug(:accepts_runtime)
plug(:set_content_type)
plug(ApiWeb.Plugs.Version)
plug(:authenticated_accepts, ApiWeb.config(:api_pipeline, :authenticated_accepts))
end
scope "/", ApiWeb do
pipe_through(:api)
get("/_health", HealthController, :index)
end
scope "/", ApiWeb do
pipe_through([:secure, :api])
get("/status", StatusController, :index)
resources("/stops", StopController, only: [:index, :show])
resources("/routes", RouteController, only: [:index, :show])
resources("/route_patterns", RoutePatternController, only: [:index, :show])
resources("/route-patterns", RoutePatternController, only: [:index, :show])
resources("/lines", LineController, only: [:index, :show])
resources("/shapes", ShapeController, only: [:index, :show])
get("/predictions", PredictionController, :index)
get("/schedules", ScheduleController, :index)
resources("/vehicles", VehicleController, only: [:index, :show])
resources("/trips", TripController, only: [:index, :show])
resources("/alerts", AlertController, only: [:index, :show])
resources("/facilities", FacilityController, only: [:index, :show])
resources("/live_facilities", LiveFacilityController, only: [:index, :show])
resources("/live-facilities", LiveFacilityController, only: [:index, :show])
resources("/services", ServiceController, only: [:index, :show])
end
scope "/docs/swagger" do
pipe_through(:secure)
forward("/", PhoenixSwagger.Plug.SwaggerUI, otp_app: :api_web, swagger_file: "swagger.json")
end
# Admin Portal routes
scope "/admin", ApiWeb.Admin, as: :admin do
pipe_through([:secure, :browser, :admin_view])
get("/login", SessionController, :new)
post("/login", SessionController, :create)
delete("/logout", SessionController, :delete)
end
scope "/admin/users", ApiWeb.Admin.Accounts, as: :admin do
pipe_through([:secure, :browser, :admin_view, :admin])
resources("/", UserController)
end
scope "/admin/users/:user_id/keys", ApiWeb.Admin.Accounts, as: :admin do
pipe_through([:secure, :browser, :admin_view, :admin])
resources("/", KeyController, only: [:create, :edit, :update, :delete])
put("/:id/approve", KeyController, :approve)
end
scope "/admin/keys", ApiWeb.Admin.Accounts, as: :admin do
pipe_through([:secure, :browser, :admin_view, :admin])
get("/", KeyController, :index)
get("/:key", KeyController, :redirect_to_user_by_id)
post("/search", KeyController, :find_user_by_key)
end
# Client Portal routes
scope "/", ApiWeb.ClientPortal do
pipe_through([:secure, :browser, :portal_view])
get("/", PortalController, :landing)
get("/login", SessionController, :new)
post("/login", SessionController, :create)
get("/register", UserController, :new)
post("/register", UserController, :create)
get("/forgot-password", UserController, :forgot_password)
post("/forgot-password", UserController, :forgot_password_submit)
get("/reset-password", UserController, :reset_password)
post("/reset-password", UserController, :reset_password_submit)
end
scope "/portal", ApiWeb.ClientPortal do
pipe_through([:secure, :browser, :portal_view, :portal])
get("/", PortalController, :index)
resources("/keys", KeyController, only: [:create, :edit, :update])
get("/keys/:id/request_increase", KeyController, :request_increase)
post("/keys/:id/request_increase", KeyController, :do_request_increase)
delete("/logout", SessionController, :delete)
resources(
"/account",
UserController,
only: [:show, :edit, :update],
singleton: true
)
get("/account/edit-password", UserController, :edit_password)
end
if Mix.env() == :dev do
scope "/sent_emails" do
forward("/", Bamboo.SentEmailViewerPlug)
end
end
def swagger_info do
%{
info: %{
title: "MBTA",
description:
"MBTA service API. https://www.mbta.com Source code: https://github.com/mbta/api",
termsOfService: "http://www.massdot.state.ma.us/DevelopersData.aspx",
contact: %{
name: "MBTA Developer",
url: "https://groups.google.com/forum/#!forum/massdotdevelopers",
email: "developer@mbta.com"
},
license: %{
name: "MassDOT Developer's License Agreement",
url:
"http://www.massdot.state.ma.us/Portals/0/docs/developers/develop_license_agree.pdf"
},
version: "3.0"
},
definitions: %{
NotFound: %{
type: :object,
description: "A JSON-API error document when a resource is not found",
required: [:errors],
properties: %{
errors: %{
type: :array,
items: %{
type: :object,
description: "A JSON-API error when a resource is not found",
properties: %{
code: %{
type: :string,
description: "An application-specific error code",
example: "not_found"
},
source: %{
type: :object,
description: "A JSON-API error source",
properties: %{
parameter: %{
type: :string,
description:
"The name of parameter that was used to lookup up the resource that was not found",
example: "id"
}
}
},
status: %{
type: :string,
description: "The HTTP status code applicable to the problem",
example: "404"
},
title: %{
type: :string,
description: "A short, human-readable summary of the problem",
example: "Resource Not Found"
}
}
},
maxItems: 1,
minItems: 1
}
}
},
BadRequest: %{
type: :object,
description: """
A JSON-API error document when the server cannot or will not process \
the request due to something that is perceived to be a client error.
""",
required: [:errors],
properties: %{
errors: %{
type: :array,
items: %{
type: :object,
description: "A JSON-API error when a bad request is received",
properties: %{
code: %{
type: :string,
description: "An application-specific error code",
example: "bad_request"
},
source: %{
type: :object,
description: "A JSON-API error source",
properties: %{
parameter: %{
type: :string,
description: "The name of parameter that caused the error",
example: "sort"
}
}
},
status: %{
type: :string,
description: "The HTTP status code applicable to the problem",
example: "400"
},
detail: %{
type: :string,
description: "A short, human-readable summary of the problem",
example: "Invalid sort key"
}
}
},
maxItems: 1,
minItems: 1
}
}
},
Forbidden: %{
type: :object,
description: "A JSON-API error document when the API key is invalid",
required: [:errors],
properties: %{
errors: %{
type: :array,
items: %{
type: :object,
description: "A JSON-API error when an invalid API key is received",
properties: %{
code: %{
type: :string,
description: "An application-specific error code",
example: "forbidden"
},
status: %{
type: :string,
description: "The HTTP status code applicable to the problem",
example: "403"
}
}
},
maxItems: 1,
minItems: 1
}
}
},
TooManyRequests: %{
type: :object,
description: "A JSON-API error document when rate limited",
required: [:errors],
properties: %{
errors: %{
type: :array,
items: %{
type: :object,
description: "A JSON-API error when rate limited",
properties: %{
code: %{
type: :string,
description: "An application-specific error code",
example: "rate_limited"
},
status: %{
type: :string,
description: "The HTTP status code applicable to the problem",
example: "429"
},
detail: %{
type: :string,
description: "Human-readable summary of the problem",
example: "You have exceeded your allowed usage rate."
}
}
},
maxItems: 1,
minItems: 1
}
}
}
},
securityDefinitions: %{
api_key_in_query: %{
type: "apiKey",
name: "api_key",
in: "query",
description: """
##### Query Parameter
Without an api key in the query string or as a request header, requests will be tracked by IP address and have stricter rate limit. \
[Register for a key](/register)
#{@rate_limit_headers}
"""
},
api_key_in_header: %{
type: "apiKey",
name: "x-api-key",
in: "header",
description: """
##### Header
Without an api key as a request header or in the query string, requests will be tracked by IP address and have stricter rate limit. \
[Register for a key](/register)
#{@rate_limit_headers}
"""
}
},
security: [
%{api_key_in_query: []},
%{api_key_in_header: []}
]
}
end
@doc """
Like `accepts/2` but fetches the acceptable types at runtime instead of compile time.
"""
def accepts_runtime(conn, []) do
runtime_accepts = ApiWeb.config(:api_pipeline, :accepts)
accepts(conn, runtime_accepts)
end
@doc """
With an anonymous user, also require that the format is allowed for anonymous users.
"""
def authenticated_accepts(%{assigns: %{api_user: %{type: :anon}}} = conn, [_ | _] = accepts) do
if Phoenix.Controller.get_format(conn) in accepts do
anon_accepts = ApiWeb.config(:api_pipeline, :accepts) -- accepts
accepts(conn, anon_accepts)
else
conn
end
end
def authenticated_accepts(conn, _) do
conn
end
end
| 32.856423 | 143 | 0.536875 |
e83c73fc829e8b26862cd0db5b019a419a5d70ad | 754 | exs | Elixir | test/bank_account_test.exs | laurocaetano/bank_account | 5d14aeee50d4e6020631126ded6ebbbf3fada5e8 | [
"MIT"
] | 1 | 2015-04-05T16:36:02.000Z | 2015-04-05T16:36:02.000Z | test/bank_account_test.exs | laurocaetano/bank_account | 5d14aeee50d4e6020631126ded6ebbbf3fada5e8 | [
"MIT"
] | null | null | null | test/bank_account_test.exs | laurocaetano/bank_account | 5d14aeee50d4e6020631126ded6ebbbf3fada5e8 | [
"MIT"
] | null | null | null | defmodule BankAccountTest do
use ExUnit.Case
test "starts off with a balance of 0" do
account = spawn_link(BankAccount, :start, [])
verify_balance_is 0, account
end
test "has balance incremented by the amount of the deposit" do
account = spawn_link(BankAccount, :start, [])
send(account, {:deposit, 10})
verify_balance_is 10, account
end
test "has balance decremented by the amount of a withdrawal" do
account = spawn_link(BankAccount, :start, [])
send(account, {:deposit, 20})
send(account, {:withdraw, 15})
verify_balance_is 5, account
end
def verify_balance_is(expected_balance, account) do
send(account, {:check_balance, self})
assert_receive {:balance, ^expected_balance}
end
end
| 25.133333 | 65 | 0.704244 |
e83c8c340f0cc5accaa6ef41eb2cc2f182158588 | 603 | ex | Elixir | apps/dockup_ui/lib/dockup_ui/metrics.ex | rudydydy/dockup | 0d05d1ef65cc5523800bd852178361521cd3e7d8 | [
"MIT"
] | null | null | null | apps/dockup_ui/lib/dockup_ui/metrics.ex | rudydydy/dockup | 0d05d1ef65cc5523800bd852178361521cd3e7d8 | [
"MIT"
] | null | null | null | apps/dockup_ui/lib/dockup_ui/metrics.ex | rudydydy/dockup | 0d05d1ef65cc5523800bd852178361521cd3e7d8 | [
"MIT"
] | null | null | null | defmodule DockupUi.Metrics do
def send(container_count, metrics_url) do
has_customer_name = not is_nil(get_customer_name())
if(has_customer_name) do
route = "/containers/" <> get_customer_name() <> ".json"
url = metrics_url <> route
body = Poison.encode!(%{count: container_count, timeStamp: DateTime.utc_now()})
spawn(fn ->
HTTPotion.post(
url,
body: body,
headers: ["Content-Type": "application/json"]
)
end)
end
end
def get_customer_name do
Application.get_env(:dockup_ui, :customer_name)
end
end
| 25.125 | 85 | 0.631841 |
e83cbf7997b5c4a655a91d4595b47671b42a32f1 | 1,679 | ex | Elixir | apps/bank_web/web/web.ex | devnacho/acme_bank | cee19a490d2b3c04465273b7a6212d7e6a81f736 | [
"MIT"
] | 776 | 2016-07-16T14:24:37.000Z | 2022-03-07T17:05:11.000Z | apps/bank_web/web/web.ex | fercho1224/devops | 81a352d857e190963d9f045d73c91f3c36a12064 | [
"MIT"
] | 19 | 2016-09-03T15:06:57.000Z | 2021-12-10T10:04:05.000Z | apps/bank_web/web/web.ex | fercho1224/devops | 81a352d857e190963d9f045d73c91f3c36a12064 | [
"MIT"
] | 130 | 2016-09-03T19:44:27.000Z | 2022-01-16T12:27:54.000Z | defmodule BankWeb.Web do
@moduledoc """
A module that keeps using definitions for controllers,
views and so on.
This can be used in your application as:
use BankWeb.Web, :controller
use BankWeb.Web, :view
The definitions below will be executed for every view,
controller, etc, so keep them short and clean, focused
on imports, uses and aliases.
Do NOT define functions inside the quoted expressions
below.
"""
def model do
quote do
use Ecto.Schema
import Ecto
import Ecto.Changeset
import Ecto.Query
end
end
def controller do
quote do
use Phoenix.Controller
alias Bank.Repo
import Ecto
import Ecto.Query
import BankWeb.Router.Helpers
import BankWeb.Gettext
import BankWeb.Authentication, only: [require_authenticated: 2]
end
end
def view do
quote do
use Phoenix.View, root: "web/templates"
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1]
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
import BankWeb.Router.Helpers
import BankWeb.ErrorHelpers
import BankWeb.Gettext
end
end
def router do
quote do
use Phoenix.Router
end
end
def channel do
quote do
use Phoenix.Channel
alias Bank.Repo
import Ecto
import Ecto.Query
import BankWeb.Gettext
end
end
@doc """
When used, dispatch to the appropriate controller/view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
| 19.988095 | 88 | 0.668255 |
e83cd4f30c84602a9eb9cc88369c46fb66bcfe02 | 388 | exs | Elixir | day16/test/day16_test.exs | bjorng/advent-of-code-2016 | fb3e40ae2fd52d761f6c0bf55e7634277917ba25 | [
"Apache-2.0"
] | 1 | 2021-05-12T11:30:15.000Z | 2021-05-12T11:30:15.000Z | day16/test/day16_test.exs | bjorng/advent-of-code-2016 | fb3e40ae2fd52d761f6c0bf55e7634277917ba25 | [
"Apache-2.0"
] | null | null | null | day16/test/day16_test.exs | bjorng/advent-of-code-2016 | fb3e40ae2fd52d761f6c0bf55e7634277917ba25 | [
"Apache-2.0"
] | null | null | null | defmodule Day16Test do
use ExUnit.Case
doctest Day16
test "part 1 with example" do
assert Day16.part1("10000", 20) == "01100"
end
test "part 1 with my input data" do
assert Day16.part1(input()) == "11100111011101111"
end
test "part 2 with my input data" do
assert Day16.part2(input()) == "10001110010000110"
end
defp input(), do: "01110110101001000"
end
| 20.421053 | 54 | 0.677835 |
e83ceb559e4a3ae8f9456bcd73159e441dd8aa5c | 3,551 | ex | Elixir | lib/bsv/address.ex | afomi/bsv-ex | a31db1e9d223aa4ac9cc00e86b1e6344a0037805 | [
"Apache-2.0"
] | null | null | null | lib/bsv/address.ex | afomi/bsv-ex | a31db1e9d223aa4ac9cc00e86b1e6344a0037805 | [
"Apache-2.0"
] | null | null | null | lib/bsv/address.ex | afomi/bsv-ex | a31db1e9d223aa4ac9cc00e86b1e6344a0037805 | [
"Apache-2.0"
] | null | null | null | defmodule BSV.Address do
@moduledoc """
Module for calculating any Bitcoin public or private key's address.
A Bitcoin address is calculated by hashing the public key with both the
SHA-256 and then RIPEMD alogrithms. The hash is then Base58Check encoded,
resulting in the Bitcoin address.
"""
alias BSV.Crypto.Hash
alias BSV.KeyPair
alias BSV.Extended.{PublicKey, PrivateKey}
defstruct network: :main, version_number: nil, hash: nil
@typedoc "Extended Private Key"
@type t :: %__MODULE__{
network: atom,
hash: binary
}
@version_bytes %{
main: <<0x00>>,
test: <<0x6F>>
}
@doc """
Returns a Bitcoin address from the given public key.
## Examples
iex> address = BSV.Crypto.ECDSA.PrivateKey.from_sequence(BSV.Test.ecdsa_key)
...> |> BSV.KeyPair.from_ecdsa_key
...> |> BSV.Address.from_public_key
iex> address.__struct__ == BSV.Address
true
"""
@spec from_public_key(
KeyPair.t | PublicKey.t | PrivateKey.t | {binary, binary} | binary,
keyword
) :: __MODULE__.t
def from_public_key(public_key, options \\ [])
def from_public_key(%KeyPair{} = key, options) do
network = Keyword.get(options, :network, key.network)
from_public_key(key.public_key, network: network)
end
def from_public_key(%PublicKey{} = key, options) do
network = Keyword.get(options, :network, key.network)
from_public_key(key.key, network: network)
end
def from_public_key(%PrivateKey{} = key, options) do
PrivateKey.get_public_key(key)
|> from_public_key(options)
end
def from_public_key({public_key, _}, options),
do: from_public_key(public_key, options)
def from_public_key(public_key, options) when is_binary(public_key) do
network = Keyword.get(options, :network, :main)
hash = Hash.sha256_ripemd160(public_key)
struct(__MODULE__, [
network: network,
version_number: @version_bytes[network],
hash: hash
])
end
@doc """
Returns a Bitcoin address struct from the given address string.
## Examples
iex> BSV.Address.from_string("15KgnG69mTbtkx73vNDNUdrWuDhnmfCxsf")
%BSV.Address{
network: :main,
hash: <<47, 105, 50, 137, 102, 179, 60, 141, 131, 76, 2, 71, 24, 254, 231, 1, 101, 139, 55, 71>>
}
"""
@spec from_string(binary) :: __MODULE__.t
def from_string(address) when is_binary(address) do
{hash, version_byte} = B58.decode58_check!(address)
network = @version_bytes
|> Enum.find(fn {_k, v} -> v == version_byte end)
|> elem(0)
struct(__MODULE__, [
network: network,
hash: hash
])
end
@doc """
Returns a Base58Check encoded string from the given Bitcoin address struct.
## Examples
iex> BSV.Test.bsv_keys
...> |> BSV.KeyPair.from_ecdsa_key
...> |> BSV.Address.from_public_key
...> |> BSV.Address.to_string
"15KgnG69mTbtkx73vNDNUdrWuDhnmfCxsf"
iex> BSV.Test.bsv_keys
...> |> BSV.KeyPair.from_ecdsa_key(compressed: false)
...> |> BSV.Address.from_public_key
...> |> BSV.Address.to_string
"13qKCNCBSgcis1TGBgCr2D9qz9iywiYrYd"
iex> BSV.Test.bsv_keys
...> |> BSV.KeyPair.from_ecdsa_key
...> |> BSV.Address.from_public_key(network: :test)
...> |> BSV.Address.to_string
"mjqe5KB8aV39Y4afdwBkJZ4qmDJViTNDLQ"
"""
@spec to_string(__MODULE__.t) :: String.t
def to_string(%__MODULE__{} = address) do
version = @version_bytes[address.network]
B58.encode58_check!(address.hash, version)
end
end | 27.742188 | 104 | 0.665728 |
e83d135e54d4379faab09b20c20c89d708cfaf53 | 1,736 | ex | Elixir | clients/firestore/lib/google_api/firestore/v1beta1/model/map_value.ex | CertifiedrLi/elixir-google-api | 4e0e261dd06ee7753c356cca413783f3facd5f03 | [
"Apache-2.0"
] | null | null | null | clients/firestore/lib/google_api/firestore/v1beta1/model/map_value.ex | CertifiedrLi/elixir-google-api | 4e0e261dd06ee7753c356cca413783f3facd5f03 | [
"Apache-2.0"
] | null | null | null | clients/firestore/lib/google_api/firestore/v1beta1/model/map_value.ex | CertifiedrLi/elixir-google-api | 4e0e261dd06ee7753c356cca413783f3facd5f03 | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2018 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.Firestore.V1beta1.Model.MapValue do
@moduledoc """
A map value.
## Attributes
- fields (%{optional(String.t) => Value}): The map's fields. The map keys represent field names. Field names matching the regular expression `__.*__` are reserved. Reserved field names are forbidden except in certain documented contexts. The map keys, represented as UTF-8, must not exceed 1,500 bytes and cannot be empty. Defaults to: `null`.
"""
defstruct [
:fields
]
end
defimpl Poison.Decoder, for: GoogleApi.Firestore.V1beta1.Model.MapValue do
import GoogleApi.Firestore.V1beta1.Deserializer
def decode(value, options) do
value
|> deserialize(:fields, :map, GoogleApi.Firestore.V1beta1.Model.Value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Firestore.V1beta1.Model.MapValue do
def encode(value, options) do
GoogleApi.Firestore.V1beta1.Deserializer.serialize_non_nil(value, options)
end
end
| 36.93617 | 368 | 0.755184 |
e83d31b16bc1e6191580d589765f71c0481d9795 | 958 | ex | Elixir | clients/books/lib/google_api/books/v1/request_builder.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/books/lib/google_api/books/v1/request_builder.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | null | null | null | clients/books/lib/google_api/books/v1/request_builder.ex | nuxlli/elixir-google-api | ecb8679ac7282b7dd314c3e20c250710ec6a7870 | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Books.V1.RequestBuilder do
@moduledoc """
Helper functions for building Tesla requests.
This module is no longer used. Please use GoogleApi.Gax.Request instead.
"""
end
| 36.846154 | 77 | 0.763048 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.