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
037367a50b61835e6f9d83abcb8f4ff59a7133ed
431
ex
Elixir
services/interop-proxy/lib/interop_proxy_web/views/error_view.ex
RemusW/orchestra
688c0d2a25d8f73c9c5a6e27d4fe4b2460c2c198
[ "MIT" ]
1
2020-10-08T14:37:36.000Z
2020-10-08T14:37:36.000Z
services/interop-proxy/lib/interop_proxy_web/views/error_view.ex
RemusW/orchestra
688c0d2a25d8f73c9c5a6e27d4fe4b2460c2c198
[ "MIT" ]
33
2017-10-31T22:36:42.000Z
2021-01-10T22:15:54.000Z
services/interop-proxy/lib/interop_proxy_web/views/error_view.ex
RemusW/orchestra
688c0d2a25d8f73c9c5a6e27d4fe4b2460c2c198
[ "MIT" ]
3
2018-10-07T21:36:02.000Z
2020-02-07T01:13:53.000Z
defmodule InteropProxyWeb.ErrorView do use InteropProxyWeb, :view def render("404.json", _assigns) do %{errors: %{detail: "Page not found"}} end def render("500.json", _assigns) do %{errors: %{detail: "Internal server error"}} end # In case no render clause matches or no template is found, we'll # render it as 500. def template_not_found(_template, assigns) do render "500.json", assigns end end
23.944444
67
0.691415
0373da8eedc074adf37f6cf76f0bbbcb062dfa3f
3,328
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/node_group.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/node_group.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/node_group.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.Compute.V1.Model.NodeGroup do @moduledoc """ A NodeGroup resource. ## Attributes - creationTimestamp (String.t): [Output Only] Creation timestamp in RFC3339 text format. Defaults to: `null`. - description (String.t): An optional description of this resource. Provide this property when you create the resource. Defaults to: `null`. - id (String.t): [Output Only] The unique identifier for the resource. This identifier is defined by the server. Defaults to: `null`. - kind (String.t): [Output Only] The type of the resource. Always compute#nodeGroup for node group. Defaults to: `null`. - name (String.t): The name of the resource, provided by the client when initially creating the resource. The resource 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`. - nodeTemplate (String.t): The URL of the node template to which this node group belongs. Defaults to: `null`. - selfLink (String.t): [Output Only] Server-defined URL for the resource. Defaults to: `null`. - size (integer()): [Output Only] The total number of nodes in the node group. Defaults to: `null`. - status (String.t): Defaults to: `null`. - Enum - one of [CREATING, DELETING, INVALID, READY] - zone (String.t): [Output Only] The name of the zone where the node group resides, such as us-central1-a. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :creationTimestamp => any(), :description => any(), :id => any(), :kind => any(), :name => any(), :nodeTemplate => any(), :selfLink => any(), :size => any(), :status => any(), :zone => any() } field(:creationTimestamp) field(:description) field(:id) field(:kind) field(:name) field(:nodeTemplate) field(:selfLink) field(:size) field(:status) field(:zone) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.NodeGroup do def decode(value, options) do GoogleApi.Compute.V1.Model.NodeGroup.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.NodeGroup do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
43.789474
509
0.701623
0374513ee3fccff8af98d827db5a2249743d14b1
1,297
exs
Elixir
apps/phx_web/mix.exs
harmon25/roygbiv_cntrl
77b056e26c3b3a1d2e49babb94ea6edefc5587f5
[ "MIT" ]
null
null
null
apps/phx_web/mix.exs
harmon25/roygbiv_cntrl
77b056e26c3b3a1d2e49babb94ea6edefc5587f5
[ "MIT" ]
null
null
null
apps/phx_web/mix.exs
harmon25/roygbiv_cntrl
77b056e26c3b3a1d2e49babb94ea6edefc5587f5
[ "MIT" ]
null
null
null
defmodule PhxWeb.Mixfile do use Mix.Project def project do [app: :phx_web, version: "0.0.1", build_path: "../../_build", config_path: "../../config/config.exs", deps_path: "../../deps", lockfile: "../../mix.lock", elixir: "~> 1.2", elixirc_paths: elixirc_paths(Mix.env), compilers: [:phoenix, :gettext] ++ Mix.compilers, build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, deps: deps()] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [mod: {PhxWeb, []}, applications: [:phoenix, :phoenix_pubsub, :phoenix_html, :cowboy, :logger, :gettext, :absinthe, :absinthe_plug]] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "web", "test/support"] defp elixirc_paths(_), do: ["lib", "web"] # Specifies your project dependencies. # # Type `mix help deps` for examples and options. defp deps do [{:phoenix, "~> 1.2.1"}, {:phoenix_pubsub, "~> 1.0"}, {:phoenix_html, "~> 2.6"}, {:phoenix_live_reload, "~> 1.0", only: :dev}, {:gettext, "~> 0.11"}, {:cowboy, "~> 1.0"}, {:absinthe, "~> 1.2"}, {:absinthe_plug, "~> 1.2.0"}] end end
28.822222
117
0.588281
03748a80a663ae5370d054874e625536545c2adf
6,062
exs
Elixir
test/service/disk_service_test.exs
kieraneglin/activestorage_ex
3cc00c212f2e87f9e04651e16e6701af8893cc7b
[ "MIT" ]
null
null
null
test/service/disk_service_test.exs
kieraneglin/activestorage_ex
3cc00c212f2e87f9e04651e16e6701af8893cc7b
[ "MIT" ]
null
null
null
test/service/disk_service_test.exs
kieraneglin/activestorage_ex
3cc00c212f2e87f9e04651e16e6701af8893cc7b
[ "MIT" ]
2
2019-05-30T18:29:37.000Z
2020-06-27T18:40:03.000Z
defmodule ActivestorageExTest.DiskServiceTest do use ExUnit.Case doctest ActivestorageEx.DiskService alias ActivestorageEx.DiskService @rails_storage_directory "external/activestorage_ex_rails/storage/" @local_key TestHelper.get_local_upload_key() setup do Application.put_env(:activestorage_ex, :root_path, @rails_storage_directory) Application.put_env(:activestorage_ex, :asset_host, "http://localhost.test") end describe "DiskService.download/1" do test "Returns a file from a given key as binary" do downloaded_file = DiskService.download(@local_key) assert is_binary(downloaded_file) end test "Returns an error if the file cannot be found" do Application.put_env(:activestorage_ex, :root_path, "/fake/directory") missing_file = DiskService.download(@local_key) assert {:error, :enoent} == missing_file end end describe "DiskService.stream_download/2" do test "An image is downloaded to the given filepath" do filepath = "test/files/streamed.jpg" DiskService.stream_download(@local_key, filepath) assert File.exists?(filepath) File.rm(filepath) end test "The filepath is returned upon success" do filepath = "test/files/streamed.jpg" download = DiskService.stream_download(@local_key, filepath) assert {:ok, ^filepath} = download File.rm(filepath) end end describe "DiskService.upload/2" do test "An image is sucessfully saved to disk" do Application.put_env(:activestorage_ex, :root_path, "test/files") image = Mogrify.open("test/files/image.jpg") key = "test_key" DiskService.upload(image, key) assert File.exists?(DiskService.path_for(key)) File.rm(DiskService.path_for(key)) end test "Image directory is created if it doesn't exist" do Application.put_env(:activestorage_ex, :root_path, "test/files") image = Mogrify.open("test/files/image.jpg") key = "non_existant_key" refute File.exists?(Path.dirname(DiskService.path_for(key))) DiskService.upload(image, key) assert File.exists?(Path.dirname(DiskService.path_for(key))) File.rm_rf(Path.dirname(DiskService.path_for(key))) end end describe "DiskService.delete/1" do test "File is deleted if it exists" do key = "test_key" save_image(key) assert File.exists?(DiskService.path_for(key)) :ok = DiskService.delete(key) refute File.exists?(DiskService.path_for(key)) end test "No error is thrown if a file doesn't exist" do key = "super_fake_test_key" refute File.exists?(DiskService.path_for(key)) :ok = DiskService.delete(key) end defp save_image(key) do Application.put_env(:activestorage_ex, :root_path, "test/files") image = Mogrify.open("test/files/image.jpg") DiskService.upload(image, key) end end describe "DiskService.path_for/1" do test "Directories of returned path are based off key name" do path = DiskService.path_for("asdf") assert String.contains?(path, "as/df") end test "Directories of variants are represented correctly" do path = DiskService.path_for("variant/blob_key/variant_key") assert String.contains?(path, "/va/ri/variant/blob_key/variant_key") end test "Filename of returned path is the key name" do key = "asdf" path = DiskService.path_for(key) assert String.ends_with?(path, key) end test "Returned path is built based off of key name" do Application.put_env(:activestorage_ex, :root_path, "/") path = DiskService.path_for("asdf") assert "/as/df/asdf" == path end test "Custom root paths are built into returned path" do Application.put_env(:activestorage_ex, :root_path, "/root/path") path = DiskService.path_for("asdf") assert "/root/path/as/df/asdf" == path end end describe "DiskService.url/2" do test "The JWT contains disposition + filename, key, and content_type" do {:ok, claims} = jwt_from_url("test_key", %{ filename: "test.png", disposition: "inline", content_type: "image/png" }) |> ActivestorageEx.verify_message() assert claims["key"] == "test_key" assert claims["disposition"] == "inline; filename=\"test.png\"" assert claims["content_type"] == "image/png" end test "A custom host can be specified" do Application.put_env(:activestorage_ex, :asset_host, "http://custom.host") url = DiskService.url("", %{filename: ""}) assert String.starts_with?(url, "http://custom.host/") end test "The filename is present in the final URL" do url = DiskService.url("", %{filename: "test.png"}) assert String.contains?(url, "/test.png") end test "The full disposition is present in the final URL" do url = DiskService.url("", %{ filename: "test.png", disposition: "inline" }) assert String.contains?(url, "disposition=inline%3B+filename%3D%22test.png%22") end test "The content_type is present in the final URL" do url = DiskService.url("", %{ filename: "", content_type: "image/png" }) assert String.contains?(url, "content_type=image%2Fpng") end test "Extra opts are discarded" do url = DiskService.url("", %{ filename: "", custom_opt: "something_bad" }) refute String.contains?(url, "something_bad") end defp jwt_from_url(key, opts) do {:ok, jwt} = DiskService.url(key, opts) |> String.split("/") |> Enum.fetch(5) jwt end end describe "DiskService.exist?/1" do test "Returns true if a file with a given key exists" do assert DiskService.exist?(@local_key) end test "Returns false if a file with a given key doesn't exist" do refute DiskService.exist?("not-a-real-key") end end end
27.680365
85
0.654899
0374bfa1cb70b2d29b2b75c3ad50783142e0aaa9
1,738
exs
Elixir
test/clients/config_test.exs
MatthewNielsen27/memo_generator
d11f6a7d6c2da3bbc21895c7ee8849f089b05492
[ "MIT" ]
null
null
null
test/clients/config_test.exs
MatthewNielsen27/memo_generator
d11f6a7d6c2da3bbc21895c7ee8849f089b05492
[ "MIT" ]
null
null
null
test/clients/config_test.exs
MatthewNielsen27/memo_generator
d11f6a7d6c2da3bbc21895c7ee8849f089b05492
[ "MIT" ]
null
null
null
defmodule MemoGenerator.Clients.ConfigTest do use ExUnit.Case alias MemoGenerator.Clients.Config test "Config start_link/2 handles valid map" do data = %{ "token" => "12dahbd31jdn31i23=2s", "base_url" => "www.example.com" } assert {:ok, pid} = Config.start_link(data, Client) end test "Config start_link/2 handles invalid map" do data = [] assert {:ok, pid} = Config.start_link(data, Client) end test "Get data using Config get/2" do data = %{ "token" => "12dahbd31jdn31i23=2s", "base_url" => "www.example.com" } assert {:ok, pid} = Config.start_link(data, Client) assert Config.get(Client, "token") == "12dahbd31jdn31i23=2s" assert Config.get(Client, "base_url") == "www.example.com" assert Config.get(Client, "headers") == nil end test "Reset data using Config reset/1" do data = %{ "token" => "12dahbd31jdn31i23=2s", "base_url" => "www.example.com" } assert {:ok, pid} = Config.start_link(data, Client) assert Config.get(Client, "token") == "12dahbd31jdn31i23=2s" assert Config.reset(Client) == :ok assert Config.get(Client, "token") == nil end test "Update data with valid map using Config update/2" do data_1 = %{ "token" => "12dahbd31jdn31i23=2s" } data_2 = %{ "base_url" => "www.example.com" } assert {:ok, pid} = Config.start_link(data_1, Client) assert Config.get(Client, "token") == "12dahbd31jdn31i23=2s" refute Config.get(Client, "base_url") == "www.example.com" assert Config.update(Client, data_2) == :ok assert Config.get(Client, "token") == "12dahbd31jdn31i23=2s" assert Config.get(Client, "base_url") == "www.example.com" end end
28.491803
64
0.635788
0374c84f7381a66b49152693caa1a0c1dfcb83d3
6,331
ex
Elixir
lib/changelog_web/helpers/shared_helpers.ex
axelson/changelog.com
bad9f461aabbde0faa938f7b2ae643ed47d1df9b
[ "MIT" ]
1
2021-01-06T18:21:45.000Z
2021-01-06T18:21:45.000Z
lib/changelog_web/helpers/shared_helpers.ex
codexn/changelog.com
25ce501ee62eef76731c38d590667e8132096ba8
[ "MIT" ]
null
null
null
lib/changelog_web/helpers/shared_helpers.ex
codexn/changelog.com
25ce501ee62eef76731c38d590667e8132096ba8
[ "MIT" ]
null
null
null
defmodule ChangelogWeb.Helpers.SharedHelpers do use Phoenix.HTML alias Changelog.{ListKit, Regexp} alias Phoenix.{Controller, Naming} @doc """ Returns `class_name` for a given connection if it matches any of the provided 'matchers'. A 'matcher' could be a string representation of a controller/ action combo, or it could be a regular expression. """ def active_class(conn, matchers, class_name \\ "is-active") def active_class(conn, matchers, class_name) when is_binary(matchers), do: active_class(conn, [matchers], class_name) def active_class(conn, matchers, class_name) when is_list(matchers) do active_id = controller_action_combo(conn) if Enum.any?(matchers, fn x -> matcher = if Regex.regex?(x), do: x, else: ~r/#{x}/ String.match?(active_id, matcher) end) do class_name end end def action_name(conn), do: Controller.action_name(conn) def comma_separated(number) do number |> Integer.to_charlist() |> Enum.reverse() |> Enum.chunk_every(3, 3, []) |> Enum.join(",") |> String.reverse() end def comma_separated_names(list) def comma_separated_names([first]), do: first.name def comma_separated_names([first, second]), do: "#{first.name} and #{second.name}" def comma_separated_names([first, second, third]), do: "#{first.name}, #{second.name}, and #{third.name}" def comma_separated_names([first | rest]), do: "#{first.name}, #{comma_separated_names(rest)}" def comma_separated_names(_unhandled), do: "" def controller_name(conn), do: Controller.controller_module(conn) |> Naming.resource_name("Controller") def controller_action_combo(conn), do: [controller_name(conn), action_name(conn)] |> Enum.join("-") def controller_action_combo_matches?(conn, list) when is_list(list) do combo = controller_action_combo(conn) Enum.any?(list, &(&1 == combo)) end def ctr(%{impression_count: 0}), do: 0 def ctr(%{click_count: 0}), do: 0 def ctr(trackable) do Float.round(trackable.click_count / trackable.impression_count * 100, 1) end def current_path(conn), do: Controller.current_path(conn) def current_path(conn, params), do: Controller.current_path(conn, params) def dev_relative(url) do if Mix.env() == :dev do parsed = URI.parse(url) [parsed.path, parsed.fragment] |> ListKit.compact_join("#") else url end end def domain_name(url) do url |> URI.parse() |> Map.get(:host) |> String.replace(~r/\Awww\./, "") end def domain_url(url) do uri = URI.parse(url) "#{uri.scheme}://#{uri.host}" end def external_link(text, opts), do: link(text, opts ++ [rel: "external"]) def get_param(assigns, param, default \\ nil), do: Map.get(assigns.conn.params, param, default) def get_assigns_or_param(assigns, param, default \\ nil) do Map.get(assigns, String.to_atom(param)) || get_param(assigns, param, default) end def github_url(nil), do: "" def github_url(%{github_handle: nil}), do: "" def github_url(%{github_handle: handle}), do: github_url(handle) def github_url(handle), do: "https://github.com/#{handle}" def github_link(model) do if model.github_handle do external_link(model.github_handle, to: github_url(model.github_handle)) end end def linkedin_url(nil), do: "" def linkedin_url(%{linkedin_handle: nil}), do: "" def linkedin_url(%{linkedin_handle: handle}), do: linkedin_url(handle) def linkedin_url(handle), do: "https://www.linkedin.com/in/#{handle}" def is_future?(time = %DateTime{}, as_of \\ Timex.now()), do: Timex.compare(time, as_of) == 1 def is_past?(time = %DateTime{}, as_of \\ Timex.now()), do: Timex.compare(time, as_of) == -1 def lazy_image(src, alt, attrs \\ []) do attrs = Keyword.merge(attrs, data: [src: src], alt: alt, src: transparent_gif()) attrs = Keyword.update(attrs, :class, "lazy", &"#{&1} lazy") tag(:img, attrs) end def maybe_lazy_image(conn, src, alt, attrs \\ []) do case controller_name(conn) do "news_issue" -> tag(:img, Keyword.merge([src: src, alt: alt], attrs)) _else -> lazy_image(src, alt, attrs) end end def md_to_safe_html(nil), do: "" def md_to_safe_html(md) when is_binary(md), do: Cmark.to_html(md, [:smart, :hardbreaks]) def md_to_html(nil), do: "" def md_to_html(md) when is_binary(md) do # special case for years stated on their own, which are technically parsed as ordered list items # but we don't want them to be. eg - "1997." or "98." if String.match?(md, ~r/^\d{2,4}\.$/) do "<p>#{md}</p>" else Cmark.to_html(md, [:unsafe, :smart, :hardbreaks]) end end def md_to_text(nil), do: "" def md_to_text(md) when is_binary(md), do: md |> md_to_html() |> HtmlSanitizeEx.strip_tags() |> sans_new_lines() def percent(numerator, divisor), do: (numerator / divisor * 100) |> round() def pluralize(list, singular, plural) when is_list(list), do: pluralize(length(list), singular, plural) def pluralize(1, singular, _plural), do: "1 #{singular}" def pluralize(count, _singular, plural), do: "#{count} #{plural}" def sans_p_tags(html), do: String.replace(html, Regexp.tag("p"), "") def sans_new_lines(string), do: String.replace(string, "\n", " ") def transparent_gif, do: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" def truncate(string, length) when is_binary(string) do if String.length(string) > length do String.slice(string, 0, length) <> "..." else string end end def truncate(_string, _length), do: "" def twitter_url(nil), do: "" def twitter_url(%{twitter_handle: nil}), do: "" def twitter_url(%{twitter_handle: handle}), do: twitter_url(handle) def twitter_url(handle) when is_binary(handle), do: "https://twitter.com/#{handle}" def twitter_link(model, string \\ nil) do if model.twitter_handle do external_link(string || model.twitter_handle, to: twitter_url(model.twitter_handle)) end end def website_link(model) do if model.website do external_link(domain_name(model.website), to: model.website) end end def word_count(nil), do: 0 def word_count(text) when is_binary(text) do text |> md_to_text() |> String.split() |> length() end end
31.655
100
0.670668
0374d63ba26f331b777871f32ca9f09a180b6c2b
3,247
exs
Elixir
test/tesla/middleware/timeout_test.exs
moosecodebv/tesla
eb919a534aa115e7d1555d0c833fa2ebecbe5b9e
[ "MIT" ]
1
2019-06-25T07:01:01.000Z
2019-06-25T07:01:01.000Z
test/tesla/middleware/timeout_test.exs
moosecodebv/tesla
eb919a534aa115e7d1555d0c833fa2ebecbe5b9e
[ "MIT" ]
null
null
null
test/tesla/middleware/timeout_test.exs
moosecodebv/tesla
eb919a534aa115e7d1555d0c833fa2ebecbe5b9e
[ "MIT" ]
1
2020-05-25T10:18:54.000Z
2020-05-25T10:18:54.000Z
defmodule Tesla.Middleware.TimeoutTest do use ExUnit.Case, async: false defmodule Client do use Tesla plug Tesla.Middleware.Timeout, timeout: 100 adapter fn env -> case env.url do "/sleep_50ms" -> Process.sleep(50) {:ok, %{env | status: 200}} "/sleep_150ms" -> Process.sleep(150) {:ok, %{env | status: 200}} "/error" -> {:error, :adapter_error} "/raise" -> raise "custom_exception" "/throw" -> throw(:throw_value) "/exit" -> exit(:exit_value) end end end defmodule DefaultTimeoutClient do use Tesla plug Tesla.Middleware.Timeout adapter fn env -> case env.url do "/sleep_950ms" -> Process.sleep(950) {:ok, %{env | status: 200}} "/sleep_1050ms" -> Process.sleep(1_050) {:ok, %{env | status: 200}} end end end describe "using custom timeout (100ms)" do test "should return timeout error when the stack timeout" do assert {:error, :timeout} = Client.get("/sleep_150ms") end test "should return the response when not timeout" do assert {:ok, %Tesla.Env{status: 200}} = Client.get("/sleep_50ms") end test "should not kill calling process" do Process.flag(:trap_exit, true) pid = spawn_link(fn -> assert {:error, :timeout} = Client.get("/sleep_150ms") end) assert_receive {:EXIT, ^pid, :normal}, 200 end end describe "using default timeout (1_000ms)" do test "should raise a Tesla.Error when the stack timeout" do assert {:error, :timeout} = DefaultTimeoutClient.get("/sleep_1050ms") end test "should return the response when not timeout" do assert {:ok, %Tesla.Env{status: 200}} = DefaultTimeoutClient.get("/sleep_950ms") end end describe "repassing errors and exit" do test "should repass rescued errors" do assert_raise RuntimeError, "custom_exception", fn -> Client.get("/raise") end end test "should keep original stacktrace information" do try do Client.get("/raise") rescue _ in RuntimeError -> [{last_module, _, _, file_info} | _] = System.stacktrace() assert Tesla.Middleware.TimeoutTest.Client == last_module assert [file: 'lib/tesla/builder.ex', line: 23] == file_info else _ -> flunk("Expected exception to be thrown") end end test "should add timeout module info to stacktrace" do try do Client.get("/raise") rescue _ in RuntimeError -> [_, {timeout_module, _, _, module_file_info} | _] = System.stacktrace() assert Tesla.Middleware.Timeout == timeout_module assert module_file_info == [file: 'lib/tesla/middleware/timeout.ex', line: 45] else _ -> flunk("Expected exception to be thrown") end end test "should repass thrown value" do assert catch_throw(Client.get("/throw")) == :throw_value end test "should repass exit value" do assert catch_exit(Client.get("/exit")) == :exit_value end end end
25.170543
88
0.591315
0374e39f9b4a1d27de11a646e9bde502c553e708
1,579
ex
Elixir
clients/web_security_scanner/lib/google_api/web_security_scanner/v1/model/empty.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/web_security_scanner/lib/google_api/web_security_scanner/v1/model/empty.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/web_security_scanner/lib/google_api/web_security_scanner/v1/model/empty.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.WebSecurityScanner.V1.Model.Empty do @moduledoc """ A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`. ## Attributes """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{} end defimpl Poison.Decoder, for: GoogleApi.WebSecurityScanner.V1.Model.Empty do def decode(value, options) do GoogleApi.WebSecurityScanner.V1.Model.Empty.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.WebSecurityScanner.V1.Model.Empty do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
31.58
76
0.747942
0374f316ece08c5cb0df1d8d51e595c4fb606d9f
461
ex
Elixir
lib/portmidi/nifs/input.ex
bwanab/ex-portmidi
9e10a5ff007ebef81c5212dbfb65b4bd90e49daa
[ "MIT" ]
36
2016-03-28T15:01:18.000Z
2021-09-11T02:41:31.000Z
lib/portmidi/nifs/input.ex
bwanab/ex-portmidi
9e10a5ff007ebef81c5212dbfb65b4bd90e49daa
[ "MIT" ]
15
2016-05-29T13:01:33.000Z
2021-11-18T18:24:23.000Z
lib/portmidi/nifs/input.ex
bwanab/ex-portmidi
9e10a5ff007ebef81c5212dbfb65b4bd90e49daa
[ "MIT" ]
11
2016-05-19T15:37:49.000Z
2020-12-13T21:34:07.000Z
defmodule PortMidi.Nifs.Input do @on_load {:init, 0} def init do :ok = :portmidi |> :code.priv_dir |> :filename.join("portmidi_in") |> :erlang.load_nif(0) end def do_poll(_stream), do: raise "NIF library not loaded" def do_read(_stream, _buffer_size), do: raise "NIF library not loaded" def do_open(_device_name), do: raise "NIF library not loaded" def do_close(_stream), do: raise "NIF library not loaded" end
20.954545
41
0.661605
0374f375a703e07eef99051c72b90b3d0781a827
706
ex
Elixir
lib/nomad_client/model/namespace.ex
mrmstn/nomad_client
a586022e5eb4d166acba08b55b198ec079d4b118
[ "Apache-2.0" ]
8
2021-09-04T21:22:53.000Z
2022-02-22T22:48:38.000Z
lib/nomad_client/model/namespace.ex
mrmstn/nomad_client
a586022e5eb4d166acba08b55b198ec079d4b118
[ "Apache-2.0" ]
null
null
null
lib/nomad_client/model/namespace.ex
mrmstn/nomad_client
a586022e5eb4d166acba08b55b198ec079d4b118
[ "Apache-2.0" ]
null
null
null
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). # https://openapi-generator.tech # Do not edit the class manually. defmodule NomadClient.Model.Namespace do @moduledoc """ """ @derive [Poison.Encoder] defstruct [ :Name, :Description, :Quota, :CreateIndex, :ModifyIndex ] @type t :: %__MODULE__{ :Name => String.t() | nil, :Description => String.t() | nil, :Quota => String.t() | nil, :CreateIndex => integer() | nil, :ModifyIndex => integer() | nil } end defimpl Poison.Decoder, for: NomadClient.Model.Namespace do def decode(value, _options) do value end end
21.393939
91
0.610482
0375164edc4b5c6f99576c79d095e5aae622be86
2,055
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/ssl_certificate_aggregated_list_warning_data.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/compute/lib/google_api/compute/v1/model/ssl_certificate_aggregated_list_warning_data.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/compute/lib/google_api/compute/v1/model/ssl_certificate_aggregated_list_warning_data.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.Compute.V1.Model.SslCertificateAggregatedListWarningData do @moduledoc """ ## Attributes * `key` (*type:* `String.t`, *default:* `nil`) - [Output Only] A key that provides more detail on the warning being returned. For example, for warnings where there are no results in a list request for a particular zone, this key might be scope and the key value might be the zone name. Other examples might be a key indicating a deprecated resource and a suggested replacement, or a warning about invalid network settings (for example, if an instance attempts to perform IP forwarding but is not enabled for IP forwarding). * `value` (*type:* `String.t`, *default:* `nil`) - [Output Only] A warning data value corresponding to the key. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :key => String.t() | nil, :value => String.t() | nil } field(:key) field(:value) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.SslCertificateAggregatedListWarningData do def decode(value, options) do GoogleApi.Compute.V1.Model.SslCertificateAggregatedListWarningData.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.SslCertificateAggregatedListWarningData do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
41.1
527
0.745499
0375616b4c27ba7314af2bf92c9395c9f28940f7
209
exs
Elixir
test/fixtures/parser/safety_assured_create_indexes.exs
maximemenager/strong_migrations
b7e091d2cfed73098d3bf683c7ce5c8ceee3159b
[ "MIT" ]
23
2021-10-29T19:58:35.000Z
2021-11-13T21:42:45.000Z
test/fixtures/parser/safety_assured_create_indexes.exs
maximemenager/strong_migrations
b7e091d2cfed73098d3bf683c7ce5c8ceee3159b
[ "MIT" ]
1
2021-10-31T03:57:47.000Z
2021-10-31T14:33:45.000Z
test/fixtures/parser/safety_assured_create_indexes.exs
surgeventures/strong_migrations
3c82e34a6e7a372c6de17ba7a0b07da7664baa26
[ "MIT" ]
3
2021-10-31T02:14:10.000Z
2021-11-09T08:07:22.000Z
defmodule SafetyAssuredCreateIndex do @moduledoc false use StrongMigrations def change do safety_assured do create(index(:users, :name)) create(index(:users, :email)) end end end
16.076923
37
0.69378
0375729dac986284304dd54a38ab85446010df5a
876
ex
Elixir
clients/games/lib/google_api/games/v1/metadata.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/games/lib/google_api/games/v1/metadata.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/games/lib/google_api/games/v1/metadata.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Games.V1 do @moduledoc """ API client metadata for GoogleApi.Games.V1. """ @discovery_revision "20200416" def discovery_revision(), do: @discovery_revision end
32.444444
74
0.756849
03758a30a2669556266675ce6add9eedbab844b9
1,136
ex
Elixir
lib/triton/supervisor.ex
sewinter/triton
7a821929dddee0d8ffc802ac36c044921bb49871
[ "MIT" ]
71
2017-11-29T03:40:54.000Z
2022-01-10T22:11:48.000Z
lib/triton/supervisor.ex
sewinter/triton
7a821929dddee0d8ffc802ac36c044921bb49871
[ "MIT" ]
19
2018-04-13T18:25:05.000Z
2020-12-24T05:22:41.000Z
lib/triton/supervisor.ex
sewinter/triton
7a821929dddee0d8ffc802ac36c044921bb49871
[ "MIT" ]
23
2017-11-02T21:34:54.000Z
2021-08-24T08:29:34.000Z
defmodule Triton.Supervisor do @moduledoc """ There is one supervisor per cluster, which is composed of a Xandra worker + Triton monitor. The Supervisor uses a one_for_all strategy to ensure that clusters are restarted when the monitor fails. This design is necessary because when Xandra / DBConnection receives a disconnection error it cannot be restarted without terminating & restarting Xandra. Separation of clusters ensure that one cluster going down doesn't affect the other. """ use Supervisor def start_link(config), do: Supervisor.start_link(__MODULE__, config, name: Module.concat([__MODULE__, config[:conn]])) def init(config) do children = [ worker(Xandra.Cluster, [[ {:name, config[:conn]}, {:after_connect, fn(conn) -> Xandra.execute(conn, "USE #{config[:keyspace]}") end} | config ]], [id: config[:conn]]), worker(Triton.Monitor, [ config[:conn], config[:keyspace], config[:health_check_delay], config[:health_check_interval] ], [id: make_ref()]) ] supervise(children, strategy: :one_for_all) end end
33.411765
121
0.684859
0375ad04c9d6554bb14cb1401474af68086c1a31
110
exs
Elixir
episode20/sort/test/sort_test.exs
paulfioravanti/learn_elixir
8424b1a7a89cb9fd1dacb85bcca487601958b8fa
[ "MIT" ]
null
null
null
episode20/sort/test/sort_test.exs
paulfioravanti/learn_elixir
8424b1a7a89cb9fd1dacb85bcca487601958b8fa
[ "MIT" ]
null
null
null
episode20/sort/test/sort_test.exs
paulfioravanti/learn_elixir
8424b1a7a89cb9fd1dacb85bcca487601958b8fa
[ "MIT" ]
null
null
null
defmodule SortTest do use ExUnit.Case doctest Sort test "the truth" do assert 1 + 1 == 2 end end
12.222222
21
0.654545
0375ec57a2c8690c9bdff32adc6fd08f42ba4b4d
595
exs
Elixir
mix.exs
ngarbezza/unq-sd-sube
48481dd3e6d9e23b6271c313c4fe1a081e5365ca
[ "MIT" ]
null
null
null
mix.exs
ngarbezza/unq-sd-sube
48481dd3e6d9e23b6271c313c4fe1a081e5365ca
[ "MIT" ]
null
null
null
mix.exs
ngarbezza/unq-sd-sube
48481dd3e6d9e23b6271c313c4fe1a081e5365ca
[ "MIT" ]
null
null
null
defmodule Sube.MixProject do use Mix.Project def project do [ app: :sube, version: "0.1.0", elixir: "~> 1.6", 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 [ {:credo, "~> 0.8.8", only: :dev, runtime: false}, {:uuid, "~> 1.1"}, {:ex_matchers, "~> 0.1.3", only: :test}, {:amnesia, "~> 0.2.0"} ] end end
19.193548
59
0.532773
03762992caeb759cbd4c7461c85c6c28b635283c
1,669
ex
Elixir
lib/mango_web/endpoint.ex
jacruzca/mango
9978dc609ed1fc86aa40386e35fae06cb95f80fc
[ "MIT" ]
null
null
null
lib/mango_web/endpoint.ex
jacruzca/mango
9978dc609ed1fc86aa40386e35fae06cb95f80fc
[ "MIT" ]
null
null
null
lib/mango_web/endpoint.ex
jacruzca/mango
9978dc609ed1fc86aa40386e35fae06cb95f80fc
[ "MIT" ]
null
null
null
defmodule MangoWeb.Endpoint do use Phoenix.Endpoint, otp_app: :mango socket "/socket", MangoWeb.UserSocket # Serve at "/" the static files from "priv/static" directory. # # You should set gzip to true if you are running phoenix.digest # when deploying your static files in production. plug Plug.Static, at: "/", from: :mango, gzip: false, only: ~w(css fonts images product_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 end plug Plug.RequestId plug Plug.Logger plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Poison plug Plug.MethodOverride plug Plug.Head # 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. plug Plug.Session, store: :cookie, key: "_mango_key", signing_salt: "oTlKXK1P" plug MangoWeb.Router @doc """ Callback invoked for dynamically configuring the endpoint. It receives the endpoint configuration and checks if configuration should be loaded from the system environment. """ def init(_key, config) do if config[:load_from_system_env] do port = System.get_env("PORT") || raise "expected the PORT environment variable to be set" {:ok, Keyword.put(config, :http, [:inet6, port: port])} else {:ok, config} end end end
28.775862
95
0.707609
0376336328fc27b20144c33967b405931481f5ea
1,615
ex
Elixir
lib/glimesh_web/channels/user_socket.ex
Cykotiq/glimesh.tv
6b998fa0b170b04916378df7246b6c64dd9f401e
[ "MIT" ]
null
null
null
lib/glimesh_web/channels/user_socket.ex
Cykotiq/glimesh.tv
6b998fa0b170b04916378df7246b6c64dd9f401e
[ "MIT" ]
null
null
null
lib/glimesh_web/channels/user_socket.ex
Cykotiq/glimesh.tv
6b998fa0b170b04916378df7246b6c64dd9f401e
[ "MIT" ]
null
null
null
defmodule GlimeshWeb.UserSocket do use Phoenix.Socket use Absinthe.Phoenix.Socket, schema: Glimesh.Schema alias Glimesh.Accounts.User ## Channels # channel "room:*", GlimeshWeb.RoomChannel # Socket params are passed from the client and can # be used to verify and authenticate a user. After # verification, you can put default assigns into # the socket that will be set for all channels, ie # # {:ok, assign(socket, :user_id, verified_user_id)} # # To deny connection, return `:error`. # # See `Phoenix.Token` documentation for examples in # performing token verification on connect. @impl true def connect(%{"token" => token}, socket, _connect_info) do case Glimesh.Oauth.TokenResolver.resolve_user(token) do {:ok, %User{} = user} -> {:ok, socket |> assign(:user_id, user.id) |> Absinthe.Phoenix.Socket.put_options( context: %{ is_admin: user.is_admin, current_user: user } )} _ -> :error end end def connect(_, _, _) do :error end # Socket id's are topics that allow you to identify all sockets for a given user: # # def id(socket), do: "user_socket:#{socket.assigns.user_id}" # # Would allow you to broadcast a "disconnect" event and terminate # all active sockets and channels for a given user: # # GlimeshWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) # # Returning `nil` makes this socket anonymous. @impl true def id(socket), do: "user_socket:#{socket.assigns.user_id}" end
27.372881
83
0.643344
0376377e662e0942da93e681c871907ba549322c
3,042
exs
Elixir
test/chat_api/messages_test.exs
xprazak2/papercups
925e7c20ab868648e078a129e832856026c50424
[ "MIT" ]
1
2021-01-18T09:57:23.000Z
2021-01-18T09:57:23.000Z
test/chat_api/messages_test.exs
xprazak2/papercups
925e7c20ab868648e078a129e832856026c50424
[ "MIT" ]
null
null
null
test/chat_api/messages_test.exs
xprazak2/papercups
925e7c20ab868648e078a129e832856026c50424
[ "MIT" ]
null
null
null
defmodule ChatApi.MessagesTest do use ChatApi.DataCase, async: true import ChatApi.Factory alias ChatApi.Messages describe "messages" do alias ChatApi.Messages.Message @update_attrs %{body: "some updated body"} @invalid_attrs %{body: nil} setup do {:ok, message: insert(:message)} end test "list_messages/1 returns all messages", %{message: message} do account_id = message.account_id message_ids = Messages.list_messages(account_id) |> Enum.map(& &1.id) assert message_ids == [message.id] end test "get_message!/1 returns the message with given id", %{message: message} do assert Map.take(message, [:account_id, :conversation_id]) == Messages.get_message!(message.id) |> Map.take([:account_id, :conversation_id]) end test "create_message/1 with valid data creates a message" do attrs = params_with_assocs(:message, body: "valid message body") assert {:ok, %Message{} = message} = Messages.create_message(attrs) assert message.body == "valid message body" end test "create_message/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Messages.create_message(@invalid_attrs) end test "update_message/2 with valid data updates the message", %{message: message} do assert {:ok, %Message{} = message} = Messages.update_message(message, @update_attrs) assert message.body == @update_attrs.body end test "update_message/2 with invalid data returns error changeset", %{message: message} do assert {:error, %Ecto.Changeset{}} = Messages.update_message(message, @invalid_attrs) end test "delete_message/1 deletes the message", %{message: message} do assert {:ok, %Message{}} = Messages.delete_message(message) assert_raise Ecto.NoResultsError, fn -> Messages.get_message!(message.id) end end test "change_message/1 returns a message changeset", %{message: message} do assert %Ecto.Changeset{} = Messages.change_message(message) end test "get_message_type/1 returns the message sender type" do customer_message = insert(:message, user: nil) user_message = insert(:message, customer: nil) assert :customer = Messages.Helpers.get_message_type(customer_message) assert :agent = Messages.Helpers.get_message_type(user_message) end test "get_conversation_topic/1 returns the conversation event topic", %{message: message} do %{conversation_id: conversation_id} = message topic = Messages.Helpers.get_conversation_topic(message) assert "conversation:" <> ^conversation_id = topic end test "format/1 returns the formatted message" do customer = insert(:customer) message = insert(:message, customer: customer) assert %{body: body, customer: c} = Messages.Helpers.format(message) assert body == message.body assert customer.email == c.email end end end
34.179775
91
0.682774
037639ceb5219635b27713bed1fce3b81a784ead
1,444
ex
Elixir
lib/one_dhcpd.ex
fhunleth/one_dhcpd
d1a4a6c7e8c86e7ae33c67231984b3665fa7382a
[ "Apache-2.0" ]
6
2018-08-27T16:32:28.000Z
2020-10-07T09:47:53.000Z
lib/one_dhcpd.ex
fhunleth/one_dhcpd
d1a4a6c7e8c86e7ae33c67231984b3665fa7382a
[ "Apache-2.0" ]
null
null
null
lib/one_dhcpd.ex
fhunleth/one_dhcpd
d1a4a6c7e8c86e7ae33c67231984b3665fa7382a
[ "Apache-2.0" ]
1
2019-03-28T23:48:26.000Z
2019-03-28T23:48:26.000Z
defmodule OneDHCPD do alias OneDHCPD.IPCalculator @moduledoc """ The One Address DHCP Server! This is a simple DHCP server for supplying IP addresses on point-to-point Ethernet links. To use it, specify a static IPv4 address on the Ethernet interface and then start the server up. OneDHCPD can supply an IPv4 address for you by calling `OneDHCPD.default_ip_address/1` that should minimize IP conflicts with the user's network and other OneDHCPD servers. This is the recommended approach. OneDHCPD is mostly used behinds the scenes with VintageNet. Here's an example for using it with a virtual USB ethernet interface: ```elixir iex> VintageNet.configure("usb0", %{type: VintageNetDirect}) :ok ``` The Nerves new project generator adds this configuration by default. If you'd like more information, see the [VintageNetDirect[(https://hexdocs.pm/vintage_net_direct/VintageNetDirect.html) documentation. """ @doc """ Return the default server IP address that would be used for the specified interface. """ @spec default_ip_address(String.t()) :: :inet.ip4_address() def default_ip_address(ifname) do IPCalculator.default_subnet(ifname) |> IPCalculator.our_ip_address() end @doc """ Return the subnet mask that goes along with default_ip_address/1. """ @spec default_subnet_mask() :: :inet.ip4_address() def default_subnet_mask() do IPCalculator.mask() end end
31.391304
81
0.745152
0376449211e3b32bd870e22732e62a5c2b794000
1,485
exs
Elixir
mix.exs
sticksnleaves/me
a63478c4eb82f586da706c9394156018f35ca686
[ "MIT" ]
5
2017-04-07T19:27:27.000Z
2020-10-30T23:24:16.000Z
mix.exs
sticksnleaves/me
a63478c4eb82f586da706c9394156018f35ca686
[ "MIT" ]
null
null
null
mix.exs
sticksnleaves/me
a63478c4eb82f586da706c9394156018f35ca686
[ "MIT" ]
null
null
null
defmodule Me.Mixfile do use Mix.Project @version "1.0.0" def project do [app: :hora, name: "Hora", description: "Extensible password management", version: @version, elixir: "~> 1.3", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, deps: deps(), package: package(), preferred_cli_env: [ "coveralls": :test, "coveralls.html": :test, "coveralls.travis": :test ], test_coverage: [tool: ExCoveralls] ] 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 [applications: [:logger]] end # Dependencies can be Hex packages: # # {:my_dep, "~> 0.3.0"} # # Or git/path repositories: # # {:my_dep, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} # # Type "mix help deps" for more examples and options defp deps do [ {:comeonin, "~> 3.0", optional: true}, {:ecto, "~> 2.1", optional: true}, # dev {:credo, "~> 0.7", only: :dev, runtime: false}, {:ex_doc, ">= 0.0.0", only: :dev, runtime: false}, # test {:excoveralls, "~> 0.7.0", only: :test, runtime: false} ] end defp package do [ maintainers: ["Anthony Smith"], licenses: ["MIT"], links: %{ GitHub: "https://github.com/sticksnleaves/hora" } ] end end
23.203125
79
0.569024
03765461dc699a6f49f8ab4dbfb38906193057e9
769
exs
Elixir
test/til/posts/post_test.exs
kw7oe/til
5ecaa3d199c06d535d1bbbfa05e2dc88e86ad815
[ "MIT" ]
null
null
null
test/til/posts/post_test.exs
kw7oe/til
5ecaa3d199c06d535d1bbbfa05e2dc88e86ad815
[ "MIT" ]
2
2020-04-26T14:03:27.000Z
2020-12-12T17:14:02.000Z
test/til/posts/post_test.exs
kw7oe/til
5ecaa3d199c06d535d1bbbfa05e2dc88e86ad815
[ "MIT" ]
null
null
null
defmodule Til.PostTest do use Til.DataCase alias Til.Posts.Post describe "group_by_date/1" do test "return date" do today = Timex.now() yesterday = Timex.shift(today, days: -1) _post = insert(:post, inserted_at: today) _yesterday_post = insert(:post, inserted_at: yesterday) _yesterday_post_2 = insert(:post, inserted_at: yesterday) [date1, date2] = Post.group_by_date() |> Repo.all() |> List.flatten() |> Enum.sort() assert to_naive_datetime_and_truncate(yesterday) == date1 assert to_naive_datetime_and_truncate(today) == date2 end end defp to_naive_datetime_and_truncate(date) do date |> Timex.beginning_of_day() |> Timex.to_naive_datetime() end end
25.633333
63
0.657997
03766a840b13891b68ebcc2e97d42e1268f402b4
463
ex
Elixir
lib/brando_admin/live/navigation/menu_update_live.ex
univers-agency/brando
69c3c52498a3f64518da3522cd9f27294a52cc68
[ "Apache-2.0" ]
1
2020-04-26T09:53:02.000Z
2020-04-26T09:53:02.000Z
lib/brando_admin/live/navigation/menu_update_live.ex
univers-agency/brando
69c3c52498a3f64518da3522cd9f27294a52cc68
[ "Apache-2.0" ]
198
2019-08-20T16:16:07.000Z
2020-07-03T15:42:07.000Z
lib/brando_admin/live/navigation/menu_update_live.ex
univers-agency/brando
69c3c52498a3f64518da3522cd9f27294a52cc68
[ "Apache-2.0" ]
null
null
null
defmodule BrandoAdmin.Navigation.MenuUpdateLive do use BrandoAdmin.LiveView.Form, schema: Brando.Navigation.Menu alias BrandoAdmin.Components.Form import Brando.Gettext def render(assigns) do ~H""" <.live_component module={Form} id="menu_form" entry_id={@entry_id} current_user={@current_user} schema={@schema}> <:header> <%= gettext("Edit menu") %> </:header> </.live_component> """ end end
23.15
63
0.647948
0376e69795d122bd1f31f38312a0dd82005e05ad
3,485
exs
Elixir
test/firebirdex_test.exs
nakagami/firebirdex
a9b64e52daf81566f6325987e750ec878db113b3
[ "Apache-2.0" ]
22
2019-02-09T14:48:13.000Z
2022-03-20T14:23:54.000Z
test/firebirdex_test.exs
nakagami/firebirdex
a9b64e52daf81566f6325987e750ec878db113b3
[ "Apache-2.0" ]
null
null
null
test/firebirdex_test.exs
nakagami/firebirdex
a9b64e52daf81566f6325987e750ec878db113b3
[ "Apache-2.0" ]
null
null
null
defmodule FirebirdexTest do use ExUnit.Case, async: true @opts TestHelpers.opts() describe "connect_test" do opts = @opts {:ok, conn} = Firebirdex.start_link(opts) {:ok, %Firebirdex.Result{} = result} = Firebirdex.query(conn, "SELECT 1 AS a, CAST('Str' AS VARCHAR(3)) AS b, 1.23 AS c, CAST(1.23 AS DOUBLE PRECISION) AS d, NULL AS E FROM RDB$DATABASE", []) assert result.columns == ["A", "B", "C", "D", "E"] assert result.rows == [[1, "Str", Decimal.new("1.23"), 1.23, :nil]] {:ok, %Firebirdex.Result{} = result} = Firebirdex.query(conn, "SELECT CAST('1967-08-11' AS date) AS d, CAST('12:23:34.4567' AS time) AS t, CAST('1967-08-11 23:34:56.1234' AS timestamp) AS TS FROM RDB$DATABASE", []) assert result.columns == ["D", "T", "TS"] assert result.rows == [[~D[1967-08-11], ~T[12:23:34.456700], ~N[1967-08-11 23:34:56.123400]]] {:ok, %Firebirdex.Result{} = result} = Firebirdex.query(conn, "SELECT count(*) from rdb$relations where rdb$system_flag = ?", [0]) assert result.rows == [[0]] {:error, %Firebirdex.Error{}} = Firebirdex.query(conn, "bad query", []) {:error, %Firebirdex.Error{}} = Firebirdex.query(conn, "SELECT * from rdb$relations where rdb$system_flag = ?", [<<"bad arg">>]) {:ok, %Firebirdex.Result{} = result} = Firebirdex.query(conn, ["SELECT 'a'", ?,, "'b' FROM RDB$DATABASE"], []) assert result.rows == [["a", "b"]] {:ok, _} = Firebirdex.query(conn, "CREATE TABLE foo ( a INTEGER NOT NULL, b VARCHAR(30) NOT NULL UNIQUE, c VARCHAR(1024), d DECIMAL(16,3) DEFAULT -0.123, e DATE DEFAULT '1967-08-11', f TIMESTAMP DEFAULT '1967-08-11 23:45:01', g TIME DEFAULT '23:45:01', h BLOB SUB_TYPE 1, i DOUBLE PRECISION DEFAULT 0.0, j FLOAT DEFAULT 0.0, PRIMARY KEY (a), CONSTRAINT CHECK_A CHECK (a <> 0) )", []) {:ok, %Firebirdex.Result{} = result} = Firebirdex.query(conn, "SELECT * from foo", []) assert result.rows == [] firebird_major_version = TestHelpers.get_firebird_major_version(conn) if firebird_major_version > 3 do # timezone test {:ok, _} = Firebirdex.query(conn, "CREATE TABLE tz_test ( id INTEGER NOT NULL, t TIME WITH TIME ZONE DEFAULT '12:34:56', ts TIMESTAMP WITH TIME ZONE DEFAULT '1967-08-11 23:45:01', PRIMARY KEY (id) )", []) {:ok, _} = Firebirdex.query(conn, "insert into tz_test (id) values (1)", []) {:ok, _} = Firebirdex.query(conn, "insert into tz_test (id, t, ts) values (2, '12:34:56 Asia/Seoul', '1967-08-11 23:45:01.0000 Asia/Seoul')", []) {:ok, _} = Firebirdex.query(conn, "insert into tz_test (id, t, ts) values (3, '03:34:56 UTC', '1967-08-11 14:45:01.0000 UTC')", []) {:ok, %Firebirdex.Result{} = result} = Firebirdex.query(conn, "SELECT * from tz_test", []) assert result.columns == ["ID", "T", "TS"] assert result.rows == [ [1, {~T[12:34:56.000000], "Asia/Tokyo"}, DateTime.from_naive!(~N[1967-08-11 23:45:01.000000], "Asia/Tokyo")], [2, {~T[12:34:56.000000], "Asia/Seoul"}, DateTime.from_naive!(~N[1967-08-11 23:45:01.000000], "Asia/Seoul")], [3, {~T[03:34:56.000000], "UTC"}, DateTime.from_naive!(~N[1967-08-11 14:45:01.000000], "UTC")] ] end end end
39.602273
151
0.568723
037736c336b0c20721bd9348fcb43f2701b11335
12,164
ex
Elixir
lib/ecto/query/builder/select.ex
matteing/ecto
beabc36931222ac574bb0047fef90d84cb138459
[ "Apache-2.0" ]
3,931
2016-06-16T11:38:48.000Z
2022-03-31T21:24:19.000Z
lib/ecto/query/builder/select.ex
matteing/ecto
beabc36931222ac574bb0047fef90d84cb138459
[ "Apache-2.0" ]
2,343
2016-06-16T11:18:09.000Z
2022-03-27T23:44:43.000Z
deps/ecto/lib/ecto/query/builder/select.ex
adrianomota/blog
ef3b2d2ed54f038368ead8234d76c18983caa75b
[ "MIT" ]
1,300
2016-06-17T13:56:59.000Z
2022-03-31T01:46:20.000Z
import Kernel, except: [apply: 2] defmodule Ecto.Query.Builder.Select do @moduledoc false alias Ecto.Query.Builder @doc """ Escapes a select. It allows tuples, lists and variables at the top level. Inside the tuples and lists query expressions are allowed. ## Examples iex> escape({1, 2}, [], __ENV__) {{:{}, [], [:{}, [], [1, 2]]}, {[], %{}}} iex> escape([1, 2], [], __ENV__) {[1, 2], {[], %{}}} iex> escape(quote(do: x), [x: 0], __ENV__) {{:{}, [], [:&, [], [0]]}, {[], %{}}} """ @spec escape(Macro.t, Keyword.t, Macro.Env.t) :: {Macro.t, {list, %{}}} def escape(atom, _vars, _env) when is_atom(atom) and not is_boolean(atom) and atom != nil do Builder.error! """ #{inspect(atom)} is not a valid query expression, :select expects a query expression or a list of fields """ end def escape(other, vars, env) do cond do take?(other) -> {{:{}, [], [:&, [], [0]]}, {[], %{0 => {:any, other}}}} maybe_take?(other) -> Builder.error! """ Cannot mix fields with interpolations, such as: `select: [:foo, ^:bar, :baz]`. \ Instead interpolate all fields at once, such as: `select: ^[:foo, :bar, :baz]`. \ Got: #{Macro.to_string(other)}. """ true -> escape(other, {[], %{}}, vars, env) end end # Tuple defp escape({left, right}, params_take, vars, env) do escape({:{}, [], [left, right]}, params_take, vars, env) end # Tuple defp escape({:{}, _, list}, params_take, vars, env) do {list, params_take} = Enum.map_reduce(list, params_take, &escape(&1, &2, vars, env)) expr = {:{}, [], [:{}, [], list]} {expr, params_take} end # Struct defp escape({:%, _, [name, map]}, params_take, vars, env) do name = Macro.expand(name, env) {escaped_map, params_take} = escape(map, params_take, vars, env) {{:{}, [], [:%, [], [name, escaped_map]]}, params_take} end # Map defp escape({:%{}, _, [{:|, _, [data, pairs]}]}, params_take, vars, env) do {data, params_take} = escape(data, params_take, vars, env) {pairs, params_take} = escape_pairs(pairs, params_take, vars, env) {{:{}, [], [:%{}, [], [{:{}, [], [:|, [], [data, pairs]]}]]}, params_take} end # Merge defp escape({:merge, _, [left, {kind, _, _} = right]}, params_take, vars, env) when kind in [:%{}, :map] do {left, params_take} = escape(left, params_take, vars, env) {right, params_take} = escape(right, params_take, vars, env) {{:{}, [], [:merge, [], [left, right]]}, params_take} end defp escape({:merge, _, [_left, right]}, _params_take, _vars, _env) do Builder.error! "expected the second argument of merge/2 in select to be a map, got: `#{Macro.to_string(right)}`" end # Map defp escape({:%{}, _, pairs}, params_take, vars, env) do {pairs, params_take} = escape_pairs(pairs, params_take, vars, env) {{:{}, [], [:%{}, [], pairs]}, params_take} end # List defp escape(list, params_take, vars, env) when is_list(list) do Enum.map_reduce(list, params_take, &escape(&1, &2, vars, env)) end # map/struct(var, [:foo, :bar]) defp escape({tag, _, [{var, _, context}, fields]}, {params, take}, vars, env) when tag in [:map, :struct] and is_atom(var) and is_atom(context) do taken = escape_fields(fields, tag, env) expr = Builder.escape_var!(var, vars) take = add_take(take, Builder.find_var!(var, vars), {tag, taken}) {expr, {params, take}} end defp escape(expr, params_take, vars, env) do Builder.escape(expr, :any, params_take, vars, {env, &escape_expansion/5}) end defp escape_expansion(expr, _type, params_take, vars, env) do escape(expr, params_take, vars, env) end defp escape_pairs(pairs, params_take, vars, env) do Enum.map_reduce pairs, params_take, fn({k, v}, acc) -> {k, acc} = escape_key(k, acc, vars, env) {v, acc} = escape(v, acc, vars, env) {{k, v}, acc} end end defp escape_key(k, params_take, _vars, _env) when is_atom(k) do {k, params_take} end defp escape_key(k, params_take, vars, env) do escape(k, params_take, vars, env) end defp escape_fields({:^, _, [interpolated]}, tag, _env) do quote do Ecto.Query.Builder.Select.fields!(unquote(tag), unquote(interpolated)) end end defp escape_fields(expr, tag, env) do case Macro.expand(expr, env) do fields when is_list(fields) -> fields _ -> Builder.error! "`#{tag}/2` in `select` expects either a literal or " <> "an interpolated list of atom fields" end end @doc """ Called at runtime to verify a field. """ def fields!(tag, fields) do if take?(fields) do fields else raise ArgumentError, "expected a list of fields in `#{tag}/2` inside `select`, got: `#{inspect fields}`" end end defp take?(fields) do is_list(fields) and Enum.all?(fields, fn {k, v} when is_atom(k) -> take?(List.wrap(v)) k when is_atom(k) -> true _ -> false end) end defp maybe_take?(fields) do is_list(fields) and Enum.any?(fields, fn {k, v} when is_atom(k) -> maybe_take?(List.wrap(v)) k when is_atom(k) -> true _ -> false end) end @doc """ Called at runtime for interpolated/dynamic selects. """ def select!(kind, query, fields, file, line) do take = %{0 => {:any, fields!(:select, fields)}} expr = %Ecto.Query.SelectExpr{expr: {:&, [], [0]}, take: take, file: file, line: line} if kind == :select do apply(query, expr) else merge(query, expr) end end @doc """ Builds a quoted expression. The quoted expression should evaluate to a query at runtime. If possible, it does all calculations at compile time to avoid runtime work. """ @spec build(:select | :merge, Macro.t, [Macro.t], Macro.t, Macro.Env.t) :: Macro.t def build(kind, query, _binding, {:^, _, [var]}, env) do quote do Ecto.Query.Builder.Select.select!(unquote(kind), unquote(query), unquote(var), unquote(env.file), unquote(env.line)) end end def build(kind, query, binding, expr, env) do {query, binding} = Builder.escape_binding(query, binding, env) {expr, {params, take}} = escape(expr, binding, env) params = Builder.escape_params(params) take = {:%{}, [], Map.to_list(take)} select = quote do: %Ecto.Query.SelectExpr{ expr: unquote(expr), params: unquote(params), file: unquote(env.file), line: unquote(env.line), take: unquote(take)} if kind == :select do Builder.apply_query(query, __MODULE__, [select], env) else quote do query = unquote(query) Builder.Select.merge(query, unquote(select)) end end end @doc """ The callback applied by `build/5` to build the query. """ @spec apply(Ecto.Queryable.t, term) :: Ecto.Query.t def apply(%Ecto.Query{select: nil} = query, expr) do %{query | select: expr} end def apply(%Ecto.Query{}, _expr) do Builder.error! "only one select expression is allowed in query" end def apply(query, expr) do apply(Ecto.Queryable.to_query(query), expr) end @doc """ The callback applied by `build/5` when merging. """ def merge(%Ecto.Query{select: nil} = query, new_select) do merge(query, new_select, {:&, [], [0]}, [], %{}, new_select) end def merge(%Ecto.Query{select: old_select} = query, new_select) do %{expr: old_expr, params: old_params, take: old_take} = old_select merge(query, old_select, old_expr, old_params, old_take, new_select) end def merge(query, expr) do merge(Ecto.Queryable.to_query(query), expr) end defp merge(query, select, old_expr, old_params, old_take, new_select) do %{expr: new_expr, params: new_params, take: new_take} = new_select new_expr = Ecto.Query.Builder.bump_interpolations(new_expr, old_params) expr = case {classify_merge(old_expr, old_take), classify_merge(new_expr, new_take)} do {_, _} when old_expr == new_expr -> new_expr {{:source, meta, ix}, {:source, _, ix}} -> {:&, meta, [ix]} {{:struct, meta, name, old_fields}, {:map, _, new_fields}} when old_params == [] -> cond do new_fields == [] -> old_expr Keyword.keyword?(old_fields) and Keyword.keyword?(new_fields) -> {:%, meta, [name, {:%{}, meta, Keyword.merge(old_fields, new_fields)}]} true -> {:merge, [], [old_expr, new_expr]} end {{:map, meta, old_fields}, {:map, _, new_fields}} when old_params == [] -> cond do old_fields == [] -> new_expr new_fields == [] -> old_expr Keyword.keyword?(old_fields) and Keyword.keyword?(new_fields) -> {:%{}, meta, Keyword.merge(old_fields, new_fields)} true -> {:merge, [], [old_expr, new_expr]} end {_, {:map, _, _}} -> {:merge, [], [old_expr, new_expr]} {_, _} -> message = """ cannot select_merge #{merge_argument_to_error(new_expr, query)} into \ #{merge_argument_to_error(old_expr, query)}, those select expressions \ are incompatible. You can only select_merge: * a source (such as post) with another source (of the same type) * a source (such as post) with a map * a struct with a map * a map with a map Incompatible merge found """ raise Ecto.QueryError, query: query, message: message end select = %{ select | expr: expr, params: old_params ++ new_params, take: merge_take(old_expr, old_take, new_take) } %{query | select: select} end defp classify_merge({:&, meta, [ix]}, take) when is_integer(ix) do case take do %{^ix => {:map, _}} -> {:map, meta, :runtime} _ -> {:source, meta, ix} end end defp classify_merge({:%, meta, [name, {:%{}, _, fields}]}, _take) when fields == [] or tuple_size(hd(fields)) == 2 do {:struct, meta, name, fields} end defp classify_merge({:%{}, meta, fields}, _take) when fields == [] or tuple_size(hd(fields)) == 2 do {:map, meta, fields} end defp classify_merge({:%{}, meta, _}, _take) do {:map, meta, :runtime} end defp classify_merge(_, _take) do :error end defp merge_argument_to_error({:&, _, [0]}, %{from: %{source: {source, alias}}}) do "source #{inspect(source || alias)}" end defp merge_argument_to_error({:&, _, [ix]}, _query) do "join (at position #{ix})" end defp merge_argument_to_error(other, _query) do Macro.to_string(other) end defp add_take(take, key, value) do Map.update(take, key, value, &merge_take_kind_and_fields(key, &1, value)) end defp merge_take(old_expr, %{} = old_take, %{} = new_take) do Enum.reduce(new_take, old_take, fn {binding, new_value}, acc -> case acc do %{^binding => old_value} -> Map.put(acc, binding, merge_take_kind_and_fields(binding, old_value, new_value)) %{} -> # If the binding is a not filtered source, merge shouldn't restrict it case old_expr do {:&, _, [^binding]} -> acc _ -> Map.put(acc, binding, new_value) end end end) end defp merge_take_kind_and_fields(binding, {old_kind, old_fields}, {new_kind, new_fields}) do {merge_take_kind(binding, old_kind, new_kind), Enum.uniq(old_fields ++ new_fields)} end defp merge_take_kind(_, kind, kind), do: kind defp merge_take_kind(_, :any, kind), do: kind defp merge_take_kind(_, kind, :any), do: kind defp merge_take_kind(binding, old, new) do Builder.error! "cannot select_merge because the binding at position #{binding} " <> "was previously specified as a `#{old}` and later as `#{new}`" end end
31.030612
116
0.584265
03775d819f389675c84543ef85c2375b6a25c495
1,815
ex
Elixir
lib/person.ex
vinceurag/kups
456d4e1e030721e70ffe616bc1fbb81c85a98c76
[ "MIT" ]
3
2018-02-19T05:22:59.000Z
2018-02-19T05:37:45.000Z
lib/person.ex
vinceurag/kups
456d4e1e030721e70ffe616bc1fbb81c85a98c76
[ "MIT" ]
null
null
null
lib/person.ex
vinceurag/kups
456d4e1e030721e70ffe616bc1fbb81c85a98c76
[ "MIT" ]
null
null
null
defmodule Kups.Person do @moduledoc """ Functions for generating fake data related to a person (any gender). """ alias Kups.Collection @doc """ Generates a full name of a person. Accepts a boolean parameter. Defaults to `false`. ## Examples iex(1)> Kups.Person.full_name(true) "Maria R. Dela Cruz" iex(2)> Kups.Person.full_name "Maria Dela Cruz" """ @spec full_name() :: String.t def full_name(with_middle_initial \\ false) do case with_middle_initial do true -> middle_initial = String.split("abcdefghijklmnopqrstuvwxyz", "", trim: true) first_name() <> " #{String.capitalize(Enum.random(middle_initial))}. " <> last_name() false -> "#{first_name()} #{last_name()}" end end @doc """ Generates first name of a person. ## Example iex> Kups.Person.first_name "Maria" """ @spec first_name() :: String.t def first_name do Enum.random(Collection.Person.female_first_name ++ Collection.Person.male_first_name) end @doc """ Generates last name of a person. ## Example iex> Kups.Person.last_name "Dela Cruz" """ @spec last_name() :: String.t def last_name do Enum.random(Collection.Person.last_name) end @doc """ Generates gender of a person. ## Example iex> Kups.Person.gender "male" """ @spec gender() :: String.t def gender do Enum.random(Collection.Person.gender) end @doc """ Generates salutation of a person. ## Example iex> Kups.Person.prefix "Gng." """ @spec prefix() :: String.t def prefix do Enum.random(Collection.Person.prefix) end end
20.862069
95
0.581267
037769934a37d9124c8b89778586b02676fe33ca
1,948
ex
Elixir
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/model/restore_default.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/model/restore_default.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/cloud_resource_manager/lib/google_api/cloud_resource_manager/v1/model/restore_default.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.CloudResourceManager.V1.Model.RestoreDefault do @moduledoc """ Ignores policies set above this resource and restores the `constraint_default` enforcement behavior of the specific `Constraint` at this resource. Suppose that `constraint_default` is set to `ALLOW` for the `Constraint` `constraints/serviceuser.services`. Suppose that organization foo.com sets a `Policy` at their Organization resource node that restricts the allowed service activations to deny all service activations. They could then set a `Policy` with the `policy_type` `restore_default` on several experimental projects, restoring the `constraint_default` enforcement of the `Constraint` for only those projects, allowing those projects to have all services activated. ## Attributes """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{} end defimpl Poison.Decoder, for: GoogleApi.CloudResourceManager.V1.Model.RestoreDefault do def decode(value, options) do GoogleApi.CloudResourceManager.V1.Model.RestoreDefault.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudResourceManager.V1.Model.RestoreDefault do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.754717
86
0.777721
03777fed05d813d1f2863e768f127982fd7ee229
5,628
exs
Elixir
test/utility_test.exs
wuhkuh/Talib
41b6bb684a87bb3dd60e73fdbf4c0aa6207ba2e0
[ "MIT" ]
18
2017-12-27T22:23:24.000Z
2021-09-10T14:08:19.000Z
test/utility_test.exs
wuhkuh/Talib
41b6bb684a87bb3dd60e73fdbf4c0aa6207ba2e0
[ "MIT" ]
6
2017-07-29T13:06:52.000Z
2021-04-11T10:58:36.000Z
test/utility_test.exs
wuhkuh/Talib
41b6bb684a87bb3dd60e73fdbf4c0aa6207ba2e0
[ "MIT" ]
11
2018-01-01T16:04:48.000Z
2021-08-17T02:26:40.000Z
defmodule Talib.UtilityTest do use ExUnit.Case alias Talib.Utility doctest Talib.Utility defmodule Fixtures do def numbers do [ 89, 77, 53, 64, 78, 67, 30, 6, 24, 53, 46, 30, 100, 48, 34, 69, 40, 44, 66, 89 ] end def numbers_change do [ nil, -12, -24, 11, 14, -11, -37, -24, 18, 29, -7, -16, 70, -52, -14, 35, -29, 4, 22, 23 ] end def numbers_gain do [ nil, 0, 0, 11, 14, 0, 0, 0, 18, 29, 0, 0, 70, 0, 0, 35, 0, 4, 22, 23 ] end def numbers_loss do [ nil, 12, 24, 0, 0, 11, 37, 24, 0, 0, 7, 16, 0, 52, 14, 0, 29, 0, 0, 0 ] end def numbers_high, do: 100 def numbers_low, do: 6 def numbers_occur do %{ 89 => 2, 77 => 1, 53 => 2, 64 => 1, 78 => 1, 67 => 1, 30 => 2, 6 => 1, 24 => 1, 46 => 1, 100 => 1, 48 => 1, 34 => 1, 69 => 1, 40 => 1, 44 => 1, 66 => 1 } end end test "change/2" do assert Utility.change(Fixtures.numbers) === {:ok, Fixtures.numbers_change} assert Utility.change([nil, 3, nil]) === {:ok, [nil, nil, nil]} assert Utility.change([nil, 3]) === {:ok, [nil, nil]} assert Utility.change([nil]) === {:ok, [nil]} assert Utility.change([3]) === {:ok, [nil]} assert Utility.change([]) === {:error, :no_data} end test "gain/1" do assert Utility.gain(Fixtures.numbers) === {:ok, Fixtures.numbers_gain} assert Utility.gain([nil, 3, nil]) === {:ok, [nil, nil, nil]} assert Utility.gain([nil, 3]) === {:ok, [nil, nil]} assert Utility.gain([nil]) === {:ok, [nil]} assert Utility.gain([3]) === {:ok, [nil]} assert Utility.gain([]) === {:error, :no_data} end test "high/1" do assert Utility.high(Fixtures.numbers) === {:ok, Fixtures.numbers_high} assert Utility.high([nil, 3, nil]) === {:ok, 3} assert Utility.high([nil, 3]) === {:ok, 3} assert Utility.high([nil]) === {:ok, nil} assert Utility.high([3]) === {:ok, 3} assert Utility.high([]) === {:error, :no_data} end test "loss/1" do assert Utility.loss(Fixtures.numbers) === {:ok, Fixtures.numbers_loss} assert Utility.loss([nil, 3, nil]) === {:ok, [nil, nil, nil]} assert Utility.loss([nil, 3]) === {:ok, [nil, nil]} assert Utility.loss([nil]) === {:ok, [nil]} assert Utility.loss([3]) === {:ok, [nil]} assert Utility.loss([]) === {:error, :no_data} end test "low/1" do assert Utility.low(Fixtures.numbers) === {:ok, Fixtures.numbers_low} assert Utility.low([nil, 3, nil]) === {:ok, 3} assert Utility.low([nil, 3]) === {:ok, 3} assert Utility.low([nil]) === {:ok, nil} assert Utility.low([3]) === {:ok, 3} assert Utility.low([]) === {:error, :no_data} end test "occur/1" do assert Utility.occur(Fixtures.numbers) === {:ok, Fixtures.numbers_occur} assert Utility.occur([nil, 3, nil]) === {:ok, %{3 => 1, nil => 2}} assert Utility.occur([3]) === {:ok, %{3 => 1}} assert Utility.occur([]) === {:error, :no_data} end test "change!/2" do assert Utility.change!(Fixtures.numbers) === Fixtures.numbers_change assert Utility.change!([nil, 3, nil]) === [nil, nil, nil] assert Utility.change!([nil, 3]) === [nil, nil] assert Utility.change!([nil]) === [nil] assert Utility.change!([3]) === [nil] assert_raise NoDataError, fn -> Utility.change!([]) end end test "gain!/1" do assert Utility.gain!(Fixtures.numbers) === Fixtures.numbers_gain assert Utility.gain!([nil, 3, nil]) === [nil, nil, nil] assert Utility.gain!([nil, 3]) === [nil, nil] assert Utility.gain!([nil]) === [nil] assert Utility.gain!([3]) === [nil] assert_raise NoDataError, fn -> Utility.gain!([]) end end test "high!/1" do assert Utility.high!(Fixtures.numbers) === Fixtures.numbers_high assert Utility.high!([nil, 3, nil]) === 3 assert Utility.high!([nil, 3]) === 3 assert Utility.high!([nil]) === nil assert Utility.high!([3]) === 3 assert_raise NoDataError, fn -> Utility.high!([]) end end test "loss!/1" do assert Utility.loss!(Fixtures.numbers) === Fixtures.numbers_loss assert Utility.loss!([nil, 3, nil]) === [nil, nil, nil] assert Utility.loss!([nil, 3]) === [nil, nil] assert Utility.loss!([nil]) === [nil] assert Utility.loss!([3]) === [nil] assert_raise NoDataError, fn -> Utility.loss!([]) end end test "low!/1" do assert Utility.low!(Fixtures.numbers) === Fixtures.numbers_low assert Utility.low!([nil, 3, nil]) === 3 assert Utility.low!([nil, 3]) === 3 assert Utility.low!([nil]) === nil assert Utility.low!([3]) === 3 assert_raise NoDataError, fn -> Utility.low!([]) end end test "occur!/1" do assert Utility.occur!(Fixtures.numbers) === Fixtures.numbers_occur assert Utility.occur!([nil, 3, nil]) === %{3 => 1, nil => 2} assert Utility.occur!([3]) === %{3 => 1} assert_raise NoDataError, fn -> Utility.occur!([]) end end test "filter_nil/1" do assert Utility.filter_nil(Fixtures.numbers) === Fixtures.numbers assert Utility.filter_nil([nil, 3, nil]) === [3] assert Utility.filter_nil([nil, 3]) === [3] assert Utility.filter_nil([nil]) === [] assert Utility.filter_nil([3]) === [3] end test "to_bang_function/1" do assert Talib.Utility.to_bang_function({:ok, [1, nil, 5]}) === [1, nil, 5] assert_raise BadPeriodError, fn -> Talib.Utility.to_bang_function({:error, :bad_period}) end assert_raise NoDataError, fn -> Talib.Utility.to_bang_function({:error, :no_data}) end end end
32.912281
78
0.566453
037788c187cda344e2ddf5960c485238213a6a9e
453
exs
Elixir
priv/repo/migrations/20210626223101_create_sponsorship_histories.exs
WOCyo/policr-mini
23e5e9f927d083cba5993f39e9f122e3a0ad1be2
[ "MIT" ]
487
2020-06-08T03:04:21.000Z
2022-03-31T14:51:36.000Z
priv/repo/migrations/20210626223101_create_sponsorship_histories.exs
WOCyo/policr-mini
23e5e9f927d083cba5993f39e9f122e3a0ad1be2
[ "MIT" ]
141
2020-06-11T01:03:29.000Z
2022-03-30T20:23:32.000Z
priv/repo/migrations/20210626223101_create_sponsorship_histories.exs
WOCyo/policr-mini
23e5e9f927d083cba5993f39e9f122e3a0ad1be2
[ "MIT" ]
61
2020-06-10T05:25:03.000Z
2022-03-23T15:54:26.000Z
defmodule PolicrMini.Repo.Migrations.CreateSponsorshipHistories do use PolicrMini.Migration def change do create table(:sponsorship_histories) do add :sponsor_id, references(:sponsors), comment: "赞助者编号" add :expected_to, :string, comment: "期望用于" add :amount, :integer, comment: "金额" add :has_reached, :boolean, comment: "是否已达成" add :reached_at, :utc_datetime, comment: "达成时间" timestamps() end end end
28.3125
66
0.695364
0377e3ed8c2e3c75891749dda748f92dca5e6029
543
ex
Elixir
lib/chess_app/web/views/layout_view.ex
leobessa/exchess
289819d183f3001dddf56810c36298fa669c3a06
[ "MIT" ]
3
2017-06-02T20:47:07.000Z
2018-05-25T11:17:12.000Z
lib/chess_app/web/views/layout_view.ex
leobessa/exchess
289819d183f3001dddf56810c36298fa669c3a06
[ "MIT" ]
null
null
null
lib/chess_app/web/views/layout_view.ex
leobessa/exchess
289819d183f3001dddf56810c36298fa669c3a06
[ "MIT" ]
null
null
null
defmodule ChessApp.Web.LayoutView do use ChessApp.Web, :view def js_script_tag do if Mix.env == :prod do ~s(<script src="/js/app.js"></script>) else ~s(<script src="http://localhost:8080/js/app.js"></script>) end end def css_link_tag do if Mix.env == :prod do ~s(<link rel="stylesheet" type="text/css" href="/css/app.css" media="screen,projection" />) else ~s(<link rel="stylesheet" type="text/css" href="http://localhost:8080/css/app.css" media="screen,projection" />) end end end
25.857143
118
0.629834
0377ffed63c391249d06885da771c22bea00ff8c
487
ex
Elixir
algorithms/medium/continuous_subarray_sum.ex
stackcats/leetcode
8d50cd92ced2ca991ea9f1e5311f5fda5707d81d
[ "MIT" ]
1
2021-05-30T05:06:06.000Z
2021-05-30T05:06:06.000Z
algorithms/medium/continuous_subarray_sum.ex
stackcats/leetcode
8d50cd92ced2ca991ea9f1e5311f5fda5707d81d
[ "MIT" ]
null
null
null
algorithms/medium/continuous_subarray_sum.ex
stackcats/leetcode
8d50cd92ced2ca991ea9f1e5311f5fda5707d81d
[ "MIT" ]
null
null
null
defmodule Solution do @spec check_subarray_sum(nums :: [integer], k :: integer) :: boolean def check_subarray_sum(nums, k) do nums |> Enum.with_index() |> helper(k, 0, %{0 => -1}) end def helper([], _, _, _), do: false def helper([{n, i} | rest], k, sum, m) do sum = sum + n r = rem(sum, k) case Map.fetch(m, r) do {:ok, j} -> if i - m[r] > 1, do: true, else: helper(rest, k, sum, m) _ -> helper(rest, k, sum, Map.put(m, r, i)) end end end
25.631579
74
0.544148
03781adbc354b665399b93235d1cf7cca8244f40
842
ex
Elixir
lib/stl.ex
alanrobson/hull_stl
5fc7d8ca8a1645264a9eaf2212935df4258b27b1
[ "MIT" ]
null
null
null
lib/stl.ex
alanrobson/hull_stl
5fc7d8ca8a1645264a9eaf2212935df4258b27b1
[ "MIT" ]
null
null
null
lib/stl.ex
alanrobson/hull_stl
5fc7d8ca8a1645264a9eaf2212935df4258b27b1
[ "MIT" ]
null
null
null
defmodule HullSTL.STL do def render_stl([last, triangles]) do IO.puts("solid hull") triangles |> Enum.map(fn t -> _render_triangle(t) end) IO.puts("endsolid hull") end defp _render_triangle(t) do IO.puts(" facet normal #{_point_to_string(t.normal)}") IO.puts(" outer loop") {p1, p2, p3} = t.triangle IO.puts(" vertex #{_point_to_string(p1)}") IO.puts(" vertex #{_point_to_string(p2)}") IO.puts(" vertex #{_point_to_string(p3)}") IO.puts(" endloop") IO.puts(" endfacet") end defp _point_to_string({x,y,z}) do "#{String.trim(to_string(:io_lib.format('~e ~n',[x])))} " <> "#{String.trim(to_string(:io_lib.format('~e ~n',[y])))} " <> "#{String.trim(to_string(:io_lib.format('~e ~n',[z])))}" end end
30.071429
64
0.558195
037821820bbb2a727c1eb7076487fa8e98856020
3,271
ex
Elixir
lib/cforum_web/controllers/moderation_controller.ex
MatthiasApsel/cforum_ex
52c621a583182d82692b74694b0b2792ac23b8ff
[ "MIT" ]
null
null
null
lib/cforum_web/controllers/moderation_controller.ex
MatthiasApsel/cforum_ex
52c621a583182d82692b74694b0b2792ac23b8ff
[ "MIT" ]
null
null
null
lib/cforum_web/controllers/moderation_controller.ex
MatthiasApsel/cforum_ex
52c621a583182d82692b74694b0b2792ac23b8ff
[ "MIT" ]
null
null
null
defmodule CforumWeb.ModerationController do use CforumWeb, :controller use Cforum.Constants alias Cforum.Threads.Thread alias Cforum.Messages.Message alias Cforum.ModerationQueue alias Cforum.ModerationQueue.ModerationQueueEntry alias Cforum.Abilities alias Cforum.Helpers def index(conn, params) do forums = Cforum.Forums.list_forums_by_permission(conn.assigns.current_user, @permission_moderate) count = ModerationQueue.count_entries(forums) paging = CforumWeb.Paginator.paginate(count, page: params["p"]) entries = forums |> ModerationQueue.list_entries(limit: paging.params) |> Enum.map(fn entry -> %ModerationQueueEntry{ entry | message: %Message{entry.message | thread: %Thread{entry.message.thread | message: entry.message}} } end) render(conn, "index.html", page: paging, moderation_queue_entries: entries) end def index_open(conn, params) do forums = Cforum.Forums.list_forums_by_permission(conn.assigns.current_user, @permission_moderate) count = ModerationQueue.count_entries(forums, true) paging = CforumWeb.Paginator.paginate(count, page: params["p"]) entries = forums |> ModerationQueue.list_entries(limit: paging.params, only_open: true) |> Enum.map(fn entry -> %ModerationQueueEntry{ entry | message: %Message{entry.message | thread: %Thread{entry.message.thread | message: entry.message}} } end) render(conn, "index.html", page: paging, moderation_queue_entries: entries) end def show(conn, _params) do render(conn, "show.html") end def edit(conn, _params) do changeset = ModerationQueue.change_resolve_entry(conn.assigns.current_user, conn.assigns.entry) render(conn, "edit.html", changeset: changeset) end def update(conn, %{"moderation_queue_entry" => entry_params}) do case ModerationQueue.resolve_entry(conn.assigns.current_user, conn.assigns.entry, entry_params) do {:ok, _entry} -> conn |> put_flash(:info, gettext("Moderation case successfully solved.")) |> redirect(to: Path.moderation_path(conn, :index)) {:error, %Ecto.Changeset{} = changeset} -> render(conn, "edit.html", changeset: changeset) end end def load_resource(conn) do if Helpers.present?(conn.params["id"]) do entry = ModerationQueue.get_entry!(conn.params["id"]) Plug.Conn.assign(conn, :entry, %ModerationQueueEntry{ entry | message: %Message{entry.message | thread: %Thread{entry.message.thread | message: entry.message}} }) else conn end end def allowed?(conn, :index, _), do: conn.assigns[:is_moderator] def allowed?(conn, :index_open, _), do: conn.assigns[:is_moderator] def allowed?(conn, action, entry) when action in [:edit, :update] do entry = entry || conn.assigns[:entry] Abilities.access_forum?(conn.assigns.current_user, entry.message.thread.forum, :moderate) && entry.cleared == false end def allowed?(conn, :show, entry) do entry = entry || conn.assigns[:entry] Abilities.access_forum?(conn.assigns.current_user, entry.message.thread.forum, :moderate) end def allowed?(_, _, _), do: false end
32.068627
109
0.689392
03786a4701337202fa217e583c4a7e4a81a6f509
3,126
exs
Elixir
config/config.exs
Oliv4945/console
fd7b85c8ff3b0702c8a524eb888104612946934c
[ "Apache-2.0" ]
null
null
null
config/config.exs
Oliv4945/console
fd7b85c8ff3b0702c8a524eb888104612946934c
[ "Apache-2.0" ]
null
null
null
config/config.exs
Oliv4945/console
fd7b85c8ff3b0702c8a524eb888104612946934c
[ "Apache-2.0" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. # # This configuration file is loaded before any dependency and # is restricted to this project. use Mix.Config config :phoenix, :json_library, Jason # General application configuration config :console, ecto_repos: [Console.Repo] config :console, Console.Repo, migration_primary_key: [id: :uuid, type: :binary_id] # Configures the endpoint config :console, ConsoleWeb.Endpoint, url: [host: "localhost"], secret_key_base: "qmS/z+jc4ZZNfmBN31tGhJbQ88aa0gD+NO8H/B5x+SCXC5XpXBAUsES7E4ubnxkJ", render_errors: [view: ConsoleWeb.ErrorView, accepts: ~w(html json)], pubsub_server: Console.PubSub config :console, :generators, migration: true, binary_id: true, sample_binary_id: "11111111-1111-1111-1111-111111111111" config :console, ConsoleWeb.Guardian, issuer: "console", secret_key: "SIc3vGaukN3p6I+o/r2SEmguIhCuSRVCR3RX4w+yLDDpDpJinc7m4SsahlgmsmwK" config :console, ConsoleWeb.AuthApiPipeline, module: ConsoleWeb.Guardian, error_handler: ConsoleWeb.AuthErrorHandler config :hammer, backend: {Hammer.Backend.ETS, [expiry_ms: 60_000 * 60 * 4, cleanup_interval_ms: 60_000 * 10]} # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:user_id] config :console, auth0_baseurl: "https://dev-j03rcvdv.auth0.com" config :console, auth0_management_id: System.get_env("AUTH0_MANAGEMENT_ID") config :console, auth0_secret: System.get_env("AUTH0_SECRET") config :console, auth0_management_aud: System.get_env("AUTH0_MANAGEMENT_AUDIENCE") config :console, :access_token_decoder, ConsoleWeb.AccessTokenDecoder.Auth0 config :console, self_hosted: System.get_env("SELF_HOSTED") config :console, Console.Scheduler, jobs: [ send_survey_tokens: [ schedule: "*/5 * * * *", # every 5th min task: {Console.Jobs, :send_survey_tokens, []} ], refresh_materialized_views: [ schedule: "0 * * * *", # every hour @ 0 mins task: {Console.Jobs, :refresh_materialized_views, []} ], trigger_device_stops_transmitting: [ schedule: "*/15 * * * *", # every 15th min task: {Console.Jobs, :trigger_device_stops_transmitting, []} ], send_alerts: [ schedule: "*/5 * * * *", # every 5th min task: {Console.Jobs, :send_alerts, []} ], delete_sent_alerts: [ schedule: "0 0 * * *", # every day @ 00:00 task: {Console.Jobs, :delete_sent_alerts, []} ], sync_hotspots_1: [ schedule: "0 2 * * *", # every day at 2am utc task: {Console.Jobs, :sync_hotspots, []} ], sync_hotspots_2: [ schedule: "0 6 * * *", # every day at 6am utc task: {Console.Jobs, :sync_hotspots, []} ], sync_hotspots_3: [ schedule: "0 10 * * *", # every day at 10am utc task: {Console.Jobs, :sync_hotspots, []} ], ] # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. import_config "#{Mix.env}.exs"
30.349515
86
0.690979
03786fa16085878c1319c4862edf719d7e15987e
2,925
ex
Elixir
apps/admin_app/lib/admin_app_web/controllers/permission_controller.ex
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
456
2018-09-20T02:40:59.000Z
2022-03-07T08:53:48.000Z
apps/admin_app/lib/admin_app_web/controllers/permission_controller.ex
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
273
2018-09-19T06:43:43.000Z
2021-08-07T12:58:26.000Z
apps/admin_app/lib/admin_app_web/controllers/permission_controller.ex
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
122
2018-09-26T16:32:46.000Z
2022-03-13T11:44:19.000Z
defmodule AdminAppWeb.PermissionController do use AdminAppWeb, :controller alias Snitch.Data.Model.Permission alias Snitch.Data.Schema.Permission, as: PermissionSchema alias AdminAppWeb.Helpers def index(conn, _params) do permissions = Permission.get_all() render(conn, "index.html", permissions: permissions) end def create(conn, %{"permission" => permission}) do params = parse_permission_params(permission) case Permission.create(params) do {:ok, _} -> conn |> put_flash(:info, "Permission created!") |> redirect(to: permission_path(conn, :index)) {:error, changeset} -> conn |> put_flash(:error, "Sorry there were some errors !") |> render("new.html", changeset: %{changeset | action: :insert}) end end def new(conn, _params) do changeset = PermissionSchema.create_changeset(%PermissionSchema{}, %{}) render(conn, "new.html", changeset: changeset) end def edit(conn, %{"id" => id}) do case Permission.get(String.to_integer(id)) do {:error, msg} -> conn |> put_flash(:error, "Sorry not found") |> redirect(to: permission_path(conn, :index)) {:ok, permission} -> changeset = PermissionSchema.update_changeset(permission, %{}) render(conn, "edit.html", changeset: changeset, permission: permission) end end def update(conn, %{"id" => id, "permission" => permission}) do id = String.to_integer(id) params = parse_permission_params(permission) {:ok, permission} = Permission.get(id) case Permission.update(params, permission) do {:ok, _} -> conn |> put_flash(:info, "permission updated successfully!") |> redirect(to: permission_path(conn, :index)) {:error, changeset} -> conn |> put_flash(:error, "Sorry some error occured!") |> render("edit.html", changeset: %{changeset | action: :update}, permission: permission) end end def delete(conn, %{"id" => id}) do id = String.to_integer(id) conn = case Permission.delete(id) do {:ok, _} -> put_flash(conn, :info, "Permission deleted successfully!") {:error, :not_found} -> put_flash(conn, :error, "Permission not found!") {:error, changeset} -> errors = Helpers.extract_changeset_errors(changeset) error = stringify_error(errors) put_flash(conn, :error, "Error! #{error}") end redirect(conn, to: permission_path(conn, :index)) end ################ Private Functions ############### defp parse_permission_params(permission) do %{ code: permission["code"], description: permission["description"] } end defp stringify_error(error_map) do Enum.reduce(error_map, "", fn {key, value}, acc -> value = Enum.join(value, ",") "#{acc} #{key}: #{value}" end) end end
29.545455
97
0.617436
037875647f38624d07a0b6521d84563ea149593c
4,460
ex
Elixir
apps/gitgud/lib/gitgud/user.ex
chulkilee/gitgud
7a9b1023ff986ca08fb821a5e7658904a6061ba3
[ "MIT" ]
null
null
null
apps/gitgud/lib/gitgud/user.ex
chulkilee/gitgud
7a9b1023ff986ca08fb821a5e7658904a6061ba3
[ "MIT" ]
null
null
null
apps/gitgud/lib/gitgud/user.ex
chulkilee/gitgud
7a9b1023ff986ca08fb821a5e7658904a6061ba3
[ "MIT" ]
null
null
null
defmodule GitGud.User do @moduledoc """ User account schema and helper functions. """ use Ecto.Schema import Ecto, only: [build_assoc: 2] import Ecto.Changeset import Ecto.Query, only: [from: 2] import Comeonin.Argon2, only: [add_hash: 1, check_pass: 2] alias GitGud.DB alias GitGud.Repo alias GitGud.SSHAuthenticationKey schema "users" do field :username, :string field :name, :string field :email, :string has_many :repositories, Repo, foreign_key: :owner_id has_many :ssh_keys, SSHAuthenticationKey, on_delete: :delete_all field :password, :string, virtual: true field :password_hash, :string timestamps() end @type t :: %__MODULE__{ id: pos_integer, username: binary, name: binary, email: binary, repositories: [Repo.t], ssh_keys: [SSHAuthenticationKey.t], password: binary, password_hash: binary, inserted_at: NaiveDateTime.t, updated_at: NaiveDateTime.t } @doc """ Creates a new user with the given `params`. """ @spec create(map|keyword) :: {:ok, t} | {:error, Ecto.Changeset.t} def create(params) do changeset = registration_changeset(Map.new(params)) DB.insert(changeset) end @doc """ Similar to `create/1`, but raises an `Ecto.InvalidChangesetError` if an error occurs. """ @spec create!(map|keyword) :: t def create!(params) do case create(params) do {:ok, user} -> user {:error, changeset} -> raise Ecto.InvalidChangesetError, action: changeset.action, changeset: changeset end end @doc """ Updates the given `user` with the given `params`. """ @spec update(t, atom, map|keyword) :: {:ok, t} | {:error, Ecto.Changeset.t | :file.posix} def update(%__MODULE__{} = user, changeset_type, params) do DB.update(update_changeset(user, changeset_type, params)) end defp update_changeset(user, :profile, params), do: profile_changeset(user, params) @doc """ Similar to `update/2`, but raises an `Ecto.InvalidChangesetError` if an error occurs. """ @spec update!(t, atom, map|keyword) :: t def update!(%__MODULE__{} = user, changeset_type, params) do DB.update!(update_changeset(user, changeset_type, params)) end @doc """ Deletes the given `user`. """ @spec delete(t) :: {:ok, t} | {:error, Ecto.Changeset.t} def delete(%__MODULE__{} = user) do DB.delete(user) end @doc """ Similar to `delete!/1`, but raises an `Ecto.InvalidChangesetError` if an error occurs. """ @spec delete!(t) :: t def delete!(%__MODULE__{} = user) do DB.delete(user) end @doc """ Returns a registration changeset for the given `params`. """ @spec registration_changeset(map) :: Ecto.Changeset.t def registration_changeset(params \\ %{}) do %__MODULE__{} |> cast(params, [:username, :name, :email, :password]) |> validate_required([:username, :name, :email, :password]) |> validate_username() |> validate_email() |> validate_password() end @doc """ Returns a profile changeset for the given `params`. """ @spec profile_changeset(map) :: Ecto.Changeset.t def profile_changeset(%__MODULE__{} = user, params \\ %{}) do user |> cast(params, [:name, :email]) |> validate_required([:name, :email]) |> validate_email() end @doc """ Returns the matching user for the given credentials; elsewhise returns `nil`. """ @spec check_credentials(binary, binary) :: t | nil def check_credentials(email_or_username, password) do user = DB.one(from u in __MODULE__, where: u.email == ^email_or_username or u.username == ^email_or_username) case check_pass(user, password) do {:ok, user} -> user {:error, _reason} -> nil end end # # Helpers # defp validate_username(changeset) do changeset |> validate_length(:username, min: 3, max: 20) |> validate_format(:username, ~r/^[a-zA-Z0-9_-]+$/) |> unique_constraint(:username) end defp validate_email(changeset) do changeset |> validate_format(:email, ~r/@/) |> unique_constraint(:email) end defp validate_password(changeset) do changeset |> validate_length(:password, min: 6) |> put_password_hash(:password) end defp put_password_hash(changeset, field) do if password = changeset.valid? && get_field(changeset, field), do: change(changeset, add_hash(password)), else: changeset end end
27.530864
113
0.65426
037877440f293bf3948c9d97411bfab6c57f7967
4,159
exs
Elixir
spec/message_template_spec.exs
mspanc/dbux
294ee5a62f1d1b3fafe97dd85b80829289be55ae
[ "MIT" ]
8
2016-09-18T23:43:30.000Z
2021-05-04T04:23:07.000Z
spec/message_template_spec.exs
mspanc/dbux
294ee5a62f1d1b3fafe97dd85b80829289be55ae
[ "MIT" ]
10
2016-05-31T22:22:01.000Z
2016-09-28T20:11:25.000Z
spec/message_template_spec.exs
mspanc/dbux
294ee5a62f1d1b3fafe97dd85b80829289be55ae
[ "MIT" ]
4
2016-09-14T12:50:26.000Z
2019-11-18T19:48:42.000Z
defmodule DBux.MessageTemplateSpec do use ESpec describe ".hello/1" do context "if no serial is given" do it "returns a valid Hello message with serial set to 0" do expect(described_module.hello()).to eq %DBux.Message{ body: [], destination: "org.freedesktop.DBus", error_name: nil, flags: 0, interface: "org.freedesktop.DBus", member: "Hello", message_type: :method_call, path: "/org/freedesktop/DBus", reply_serial: nil, sender: nil, serial: 0, signature: "", unix_fds: nil} end end context "if serial is given" do it "returns a valid Hello message with serial set to given serial" do expect(described_module.hello(123)).to eq %DBux.Message{ body: [], destination: "org.freedesktop.DBus", error_name: nil, flags: 0, interface: "org.freedesktop.DBus", member: "Hello", message_type: :method_call, path: "/org/freedesktop/DBus", reply_serial: nil, sender: nil, serial: 123, signature: "", unix_fds: nil} end end end describe ".request_name/3" do let :name, do: "org.something.dbux" context "if no serial and flags are given" do it "returns a valid RequestName message with serial and flags set to 0" do expect(described_module.request_name(name)).to eq %DBux.Message{ body: [ %DBux.Value{type: :string, value: name}, %DBux.Value{type: :uint32, value: 0} ], destination: "org.freedesktop.DBus", error_name: nil, flags: 0, interface: "org.freedesktop.DBus", member: "RequestName", message_type: :method_call, path: "/org/freedesktop/DBus", reply_serial: nil, sender: nil, serial: 0, signature: "su", unix_fds: nil} end end context "if no serial is given but flags are given" do it "returns a valid RequestName message with serial set to 0 and given flags" do expect(described_module.request_name(name, 1)).to eq %DBux.Message{ body: [ %DBux.Value{type: :string, value: name}, %DBux.Value{type: :uint32, value: 1} ], destination: "org.freedesktop.DBus", error_name: nil, flags: 0, interface: "org.freedesktop.DBus", member: "RequestName", message_type: :method_call, path: "/org/freedesktop/DBus", reply_serial: nil, sender: nil, serial: 0, signature: "su", unix_fds: nil} end end context "if both serial and flags are given" do it "returns a valid RequestName message with serial and flags given set to given values" do expect(described_module.request_name(name, 1, 123)).to eq %DBux.Message{ body: [ %DBux.Value{type: :string, value: name}, %DBux.Value{type: :uint32, value: 1} ], destination: "org.freedesktop.DBus", error_name: nil, flags: 0, interface: "org.freedesktop.DBus", member: "RequestName", message_type: :method_call, path: "/org/freedesktop/DBus", reply_serial: nil, sender: nil, serial: 123, signature: "su", unix_fds: nil} end end end describe ".list_names/1" do context "if no serial is given" do it "returns a valid ListNames message with serial set to 0" do expect(described_module.list_names()).to eq %DBux.Message{ body: [], destination: "org.freedesktop.DBus", error_name: nil, flags: 0, interface: "org.freedesktop.DBus", member: "ListNames", message_type: :method_call, path: "/org/freedesktop/DBus", reply_serial: nil, sender: nil, serial: 0, signature: "", unix_fds: nil} end end context "if serial is given" do it "returns a valid ListNames message with serial set to given serial" do expect(described_module.list_names(123)).to eq %DBux.Message{ body: [], destination: "org.freedesktop.DBus", error_name: nil, flags: 0, interface: "org.freedesktop.DBus", member: "ListNames", message_type: :method_call, path: "/org/freedesktop/DBus", reply_serial: nil, sender: nil, serial: 123, signature: "", unix_fds: nil} end end end end
44.72043
97
0.636451
0378bc1b2e6938ed0d209cce09fdb4302e6d6cb9
1,223
ex
Elixir
Microsoft.Azure.Management.Database.CosmosDb/lib/microsoft/azure/management/database/cosmos_db/model/partition_metric.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
4
2018-09-29T03:43:15.000Z
2021-04-01T18:30:46.000Z
Microsoft.Azure.Management.Database.CosmosDb/lib/microsoft/azure/management/database/cosmos_db/model/partition_metric.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
Microsoft.Azure.Management.Database.CosmosDb/lib/microsoft/azure/management/database/cosmos_db/model/partition_metric.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
# NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule Microsoft.Azure.Management.Database.CosmosDb.Model.PartitionMetric do @moduledoc """ The metric values for a single partition. """ @derive [Poison.Encoder] defstruct [ :"startTime", :"endTime", :"timeGrain", :"unit", :"name", :"metricValues" ] @type t :: %__MODULE__{ :"startTime" => DateTime.t, :"endTime" => DateTime.t, :"timeGrain" => String.t, :"unit" => UnitType, :"name" => MetricName, :"metricValues" => [MetricValue] } end defimpl Poison.Decoder, for: Microsoft.Azure.Management.Database.CosmosDb.Model.PartitionMetric do import Microsoft.Azure.Management.Database.CosmosDb.Deserializer def decode(value, options) do value |> deserialize(:"unit", :struct, Microsoft.Azure.Management.Database.CosmosDb.Model.UnitType, options) |> deserialize(:"name", :struct, Microsoft.Azure.Management.Database.CosmosDb.Model.MetricName, options) |> deserialize(:"metricValues", :list, Microsoft.Azure.Management.Database.CosmosDb.Model.MetricValue, options) end end
30.575
115
0.704007
0378c7adcd6b6c9755d1eeddb4640f5e5b2da7a1
894
ex
Elixir
apps/website/lib/website/application.ex
gregredhead/belethor
255925396b18ba4a6950f386abf8a9e17a7e5e7c
[ "Apache-2.0" ]
3
2018-07-20T22:14:36.000Z
2018-12-21T19:54:48.000Z
apps/website/lib/website/application.ex
gregredhead/belethor
255925396b18ba4a6950f386abf8a9e17a7e5e7c
[ "Apache-2.0" ]
36
2018-09-15T21:46:54.000Z
2020-03-28T16:10:18.000Z
apps/website/lib/website/application.ex
gregredhead/belethor
255925396b18ba4a6950f386abf8a9e17a7e5e7c
[ "Apache-2.0" ]
2
2018-07-22T08:47:07.000Z
2021-12-11T01:39:19.000Z
defmodule Website.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false alias WebsiteWeb.Endpoint use Application def start(_type, _args) do # List all child processes to be supervised children = [ # Start the endpoint when the application starts WebsiteWeb.Endpoint # Starts a worker by calling: Website.Worker.start_link(arg) # {Website.Worker, arg}, ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Website.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do Endpoint.config_change(changed, removed) :ok end end
27.9375
66
0.720358
0378cbc4d059f955c3e9316a2f694f329e07cd1a
73
exs
Elixir
test/file_watcher_test.exs
ColdOrange/file_watcher
3cd9fd29c21d990e5d2518b6ffda6114ba1ecab1
[ "MIT" ]
null
null
null
test/file_watcher_test.exs
ColdOrange/file_watcher
3cd9fd29c21d990e5d2518b6ffda6114ba1ecab1
[ "MIT" ]
null
null
null
test/file_watcher_test.exs
ColdOrange/file_watcher
3cd9fd29c21d990e5d2518b6ffda6114ba1ecab1
[ "MIT" ]
1
2019-11-28T14:02:05.000Z
2019-11-28T14:02:05.000Z
defmodule FileWatcherTest do use ExUnit.Case doctest FileWatcher end
14.6
28
0.821918
0378f2e8f81b8e90d129fed626240872be3bf3cc
820
ex
Elixir
lib/cowguest/repo.ex
cedretaber/cowguest
dd41ca95f19820de3707e4b1afa04f901a9e9670
[ "MIT" ]
null
null
null
lib/cowguest/repo.ex
cedretaber/cowguest
dd41ca95f19820de3707e4b1afa04f901a9e9670
[ "MIT" ]
null
null
null
lib/cowguest/repo.ex
cedretaber/cowguest
dd41ca95f19820de3707e4b1afa04f901a9e9670
[ "MIT" ]
null
null
null
defmodule Cowguest.Repo do @moduledoc false def keys(pattern \\ "*") do Redix.command(:redix, ["keys", pattern]) end def get(key, hkey) when is_binary(key) and is_binary(hkey) do Redix.command(:redix, ["hget", key, hkey]) end def get(key, hkey) when is_binary(key), do: get(key, to_string(hkey)) def get(key, hkey), do: get(to_string(key), hkey) def put(key, kvs) when is_binary(key) do cmds = kvs |> Enum.reduce([key, "hset"], fn {k, v}, list when is_atom(k) -> [v, Atom.to_string(k) | list] {k, v}, list when is_binary(k) -> [v, k | list] e, list when is_binary(e) -> [e | list] e, list -> [to_string(e) | list] end) |> Enum.reverse() Redix.command(:redix, cmds) end def put(key, kvs), do: put(to_string(key), kvs) end
25.625
71
0.586585
037926aac113c5171134e5ecd29054335ca8b37f
4,072
exs
Elixir
test/awesome_list_test.exs
sprql/awesome_elixir
ae1a372bf3060142a546aaf6cb28ffda491d9fa0
[ "MIT" ]
1
2017-04-13T05:37:08.000Z
2017-04-13T05:37:08.000Z
test/awesome_list_test.exs
sprql/awesome_elixir
ae1a372bf3060142a546aaf6cb28ffda491d9fa0
[ "MIT" ]
null
null
null
test/awesome_list_test.exs
sprql/awesome_elixir
ae1a372bf3060142a546aaf6cb28ffda491d9fa0
[ "MIT" ]
null
null
null
defmodule AwesomeElixir.AwesomeListTest do use AwesomeElixir.DataCase alias AwesomeElixir.AwesomeList alias AwesomeElixir.AwesomeList.{Section, Repository} @create_attrs %{description: "some description", name: "some name"} @update_attrs %{description: "some updated description", name: "some updated name"} @invalid_attrs %{description: nil, name: nil} def fixture(:section, attrs \\ @create_attrs) do {:ok, section} = AwesomeList.create_section(attrs) section end test "list_sections/1 returns all sections" do section = fixture(:section) assert AwesomeList.list_sections() == [section] end test "get_section! returns the section with given id" do section = fixture(:section) assert AwesomeList.get_section!(section.id) == section end test "create_or_update_section/1 creates and updates a section" do assert {:ok, %Section{} = section} = AwesomeList.create_or_update_section(@create_attrs) assert section.description == "some description" assert section.name == "some name" assert {:ok, %Section{} = updated_section} = %{section | description: "new description"} |> Map.from_struct |> AwesomeList.create_or_update_section assert updated_section.description == "new description" assert updated_section.name == "some name" end test "create_or_update_section/1 with invalid data returns error changeset" do section = fixture(:section) invalid_attrs = %{name: section.name, description: ""} assert {:error, %Ecto.Changeset{}} = AwesomeList.create_or_update_section(invalid_attrs) end test "create_section/1 with valid data creates a section" do assert {:ok, %Section{} = section} = AwesomeList.create_section(@create_attrs) assert section.description == "some description" assert section.name == "some name" end test "create_section/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = AwesomeList.create_section(@invalid_attrs) end test "update_section/2 with valid data updates the section" do section = fixture(:section) assert {:ok, section} = AwesomeList.update_section(section, @update_attrs) assert %Section{} = section assert section.description == "some updated description" assert section.name == "some updated name" end test "update_section/2 with invalid data returns error changeset" do section = fixture(:section) assert {:error, %Ecto.Changeset{}} = AwesomeList.update_section(section, @invalid_attrs) assert section == AwesomeList.get_section!(section.id) end test "delete_section/1 deletes the section" do section = fixture(:section) assert {:ok, %Section{}} = AwesomeList.delete_section(section) assert_raise Ecto.NoResultsError, fn -> AwesomeList.get_section!(section.id) end end test "change_section/1 returns a section changeset" do section = fixture(:section) assert %Ecto.Changeset{} = AwesomeList.change_section(section) end test "create_or_update_repository/1 creates and updates a repository" do section = fixture(:section) repository_attrs = %{ url: "https://test.url/", description: "some description", name: "some name", section_id: section.id } assert {:ok, %Repository{} = repository} = AwesomeList.create_or_update_repository(repository_attrs) assert repository.description == "some description" assert repository.name == "some name" assert repository.section_id == section.id new_section = fixture(:section, %{name: "new_name", description: "new description"}) new_repository_attrs = repository |> Map.from_struct |> Map.put(:section_id, new_section.id) |> Map.put(:description, "new description") assert {:ok, %Repository{} = updated_repository} = AwesomeList.create_or_update_repository(new_repository_attrs) assert updated_repository.description == "new description" assert updated_repository.name == "some name" assert updated_repository.section_id == new_section.id end end
36.357143
116
0.72225
037941e25a0445d138d9ce06826436ac011ffbc2
4,926
ex
Elixir
clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/google_devtools_remotebuildexecution_admin_v1alpha_worker_config.ex
myskoach/elixir-google-api
4f8cbc2fc38f70ffc120fd7ec48e27e46807b563
[ "Apache-2.0" ]
null
null
null
clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/google_devtools_remotebuildexecution_admin_v1alpha_worker_config.ex
myskoach/elixir-google-api
4f8cbc2fc38f70ffc120fd7ec48e27e46807b563
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/google_devtools_remotebuildexecution_admin_v1alpha_worker_config.ex
myskoach/elixir-google-api
4f8cbc2fc38f70ffc120fd7ec48e27e46807b563
[ "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.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerConfig do @moduledoc """ Defines the configuration to be used for creating workers in the worker pool. ## Attributes * `accelerator` (*type:* `GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemotebuildexecutionAdminV1alphaAcceleratorConfig.t`, *default:* `nil`) - The accelerator card attached to each VM. * `diskSizeGb` (*type:* `String.t`, *default:* `nil`) - Required. Size of the disk attached to the worker, in GB. See https://cloud.google.com/compute/docs/disks/ * `diskType` (*type:* `String.t`, *default:* `nil`) - Required. Disk Type to use for the worker. See [Storage options](https://cloud.google.com/compute/docs/disks/#introduction). Currently only `pd-standard` and `pd-ssd` are supported. * `labels` (*type:* `map()`, *default:* `nil`) - Labels associated with the workers. Label keys and values can be no longer than 63 characters, can only contain lowercase letters, numeric characters, underscores and dashes. International letters are permitted. Label keys must start with a letter. Label values are optional. There can not be more than 64 labels per resource. * `machineType` (*type:* `String.t`, *default:* `nil`) - Required. Machine type of the worker, such as `n1-standard-2`. See https://cloud.google.com/compute/docs/machine-types for a list of supported machine types. Note that `f1-micro` and `g1-small` are not yet supported. * `maxConcurrentActions` (*type:* `String.t`, *default:* `nil`) - The maximum number of actions a worker can execute concurrently. * `minCpuPlatform` (*type:* `String.t`, *default:* `nil`) - Minimum CPU platform to use when creating the worker. See [CPU Platforms](https://cloud.google.com/compute/docs/cpu-platforms). * `networkAccess` (*type:* `String.t`, *default:* `nil`) - Determines the type of network access granted to workers. Possible values: - "public": Workers can connect to the public internet. - "private": Workers can only connect to Google APIs and services. - "restricted-private": Workers can only connect to Google APIs that are reachable through `restricted.googleapis.com` (`199.36.153.4/30`). * `reserved` (*type:* `boolean()`, *default:* `nil`) - Determines whether the worker is reserved (equivalent to a Compute Engine on-demand VM and therefore won't be preempted). See [Preemptible VMs](https://cloud.google.com/preemptible-vms/) for more details. * `soleTenantNodeType` (*type:* `String.t`, *default:* `nil`) - The node type name to be used for sole-tenant nodes. * `vmImage` (*type:* `String.t`, *default:* `nil`) - The name of the image used by each VM. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :accelerator => GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemotebuildexecutionAdminV1alphaAcceleratorConfig.t(), :diskSizeGb => String.t(), :diskType => String.t(), :labels => map(), :machineType => String.t(), :maxConcurrentActions => String.t(), :minCpuPlatform => String.t(), :networkAccess => String.t(), :reserved => boolean(), :soleTenantNodeType => String.t(), :vmImage => String.t() } field(:accelerator, as: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemotebuildexecutionAdminV1alphaAcceleratorConfig ) field(:diskSizeGb) field(:diskType) field(:labels, type: :map) field(:machineType) field(:maxConcurrentActions) field(:minCpuPlatform) field(:networkAccess) field(:reserved) field(:soleTenantNodeType) field(:vmImage) end defimpl Poison.Decoder, for: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerConfig do def decode(value, options) do GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerConfig.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.RemoteBuildExecution.V2.Model.GoogleDevtoolsRemotebuildexecutionAdminV1alphaWorkerConfig do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
55.348315
400
0.723508
0379448c1fc639f675ef7939183568c144210200
1,099
exs
Elixir
clients/dataflow/mix.exs
MechimCook/elixir-google-api
0240ede69ec77115076724d223f9d1f849ff1d6b
[ "Apache-2.0" ]
null
null
null
clients/dataflow/mix.exs
MechimCook/elixir-google-api
0240ede69ec77115076724d223f9d1f849ff1d6b
[ "Apache-2.0" ]
null
null
null
clients/dataflow/mix.exs
MechimCook/elixir-google-api
0240ede69ec77115076724d223f9d1f849ff1d6b
[ "Apache-2.0" ]
null
null
null
defmodule GoogleApi.Dataflow.V1b3.Mixfile do use Mix.Project @version "0.8.0" def project do [app: :google_api_dataflow, version: @version, elixir: "~> 1.4", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/dataflow" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.1.0"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Manages Google Cloud Dataflow projects on Google Cloud Platform. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/GoogleCloudPlatform/elixir-google-api/tree/master/clients/dataflow", "Homepage" => "https://cloud.google.com/dataflow" } ] end end
22.895833
108
0.598726
03794bd132bebef2e131b635666fecf6aefd0327
786
ex
Elixir
lib/cgrates_web_jsonapi/csv_import_job.ex
zombalo/cgrates_web_jsonapi
47845be4311839fe180cc9f2c7c6795649da4430
[ "MIT" ]
null
null
null
lib/cgrates_web_jsonapi/csv_import_job.ex
zombalo/cgrates_web_jsonapi
47845be4311839fe180cc9f2c7c6795649da4430
[ "MIT" ]
null
null
null
lib/cgrates_web_jsonapi/csv_import_job.ex
zombalo/cgrates_web_jsonapi
47845be4311839fe180cc9f2c7c6795649da4430
[ "MIT" ]
null
null
null
defmodule CgratesWebJsonapi.CsvImportJob do defmacro __using__(opts) do module = Keyword.get(opts, :module) quote do require Logger use Phoenix.Controller def create(conn, %{"data" => %{"attributes" => %{"tpid" => tpid, "csv" => csv}}}) do id = DateTime.utc_now() |> DateTime.to_unix() Task.async fn -> start_time = Time.utc_now() Logger.info "Start Import Task" unquote(module).from_csv(csv.path, tpid) |> Enum.into([]) |> length() |> Logger.info() end_time = Time.utc_now() Logger.info "End Import Task. Duration - #{ Time.diff end_time, start_time } sec" end conn |> put_status(202) |> render("show.json-api", data: %{id: id}) end end end end
31.44
96
0.576336
03798339d2394136239ba893e8a73b5efa3a5f00
339
ex
Elixir
lib/phoenix_elm_web/router.ex
ejpcmac/phoenix_elm
cc43a2253610728fbf2db9bd87b5341e82a27e5e
[ "BSD-3-Clause" ]
null
null
null
lib/phoenix_elm_web/router.ex
ejpcmac/phoenix_elm
cc43a2253610728fbf2db9bd87b5341e82a27e5e
[ "BSD-3-Clause" ]
null
null
null
lib/phoenix_elm_web/router.ex
ejpcmac/phoenix_elm
cc43a2253610728fbf2db9bd87b5341e82a27e5e
[ "BSD-3-Clause" ]
null
null
null
defmodule PhoenixElmWeb.Router do use PhoenixElmWeb, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers end scope "/", PhoenixElmWeb do pipe_through :browser get "/", PageController, :index end end
18.833333
36
0.707965
037988521533d00d157efe495b504027e6cd8813
2,694
ex
Elixir
test/elixir/lib/setup.ex
mtenrero/couchdb-vetcontrol
b7ede3ededdf0072c73f08d8f1217cb723b03f7a
[ "Apache-2.0" ]
1
2022-01-14T20:52:55.000Z
2022-01-14T20:52:55.000Z
test/elixir/lib/setup.ex
mtenrero/couchdb-vetcontrol
b7ede3ededdf0072c73f08d8f1217cb723b03f7a
[ "Apache-2.0" ]
1
2021-07-28T02:13:39.000Z
2021-07-28T02:13:39.000Z
test/elixir/lib/setup.ex
mtenrero/couchdb-vetcontrol
b7ede3ededdf0072c73f08d8f1217cb723b03f7a
[ "Apache-2.0" ]
null
null
null
defmodule Couch.Test.Setup do @moduledoc """ Allows to chain setup functions. Example of using: ``` alias Couch,Test.Utils def with_db_name(context, setup) do setup = setup |> Step.Start.new(:start, extra_apps: [:chttpd]) |> Step.User.new(:admin, roles: [:server_admin]) |> Setup.run() context = Map.merge(context, %{ db_name: Utils.random_name("db") base_url: setup |> Setup.get(:start) |> Step.Start.clustered_url(), user: setup |> Setup.get(:admin) |> Step.User.name() }) {context, setup} end @tag setup: &__MODULE__.with_db_name/2 test "Create", %{db_name: db_name, user: user} do ... end ``` """ import ExUnit.Callbacks, only: [on_exit: 1] import ExUnit.Assertions, only: [assert: 2] require Logger alias Couch.Test.Setup alias Couch.Test.Setup.Step defstruct stages: [], by_type: %{}, state: %{} def step(%Setup{stages: stages} = setup, id, step) do %{setup | stages: [{id, step} | stages]} end defp setup_step({id, step}, %Setup{state: state, by_type: by_type} = setup) do %module{} = step # credo:disable-for-next-line Credo.Check.Warning.LazyLogging Logger.debug("Calling 'setup/2' for '#{module}'") step = module.setup(setup, step) state = Map.put(state, id, step) by_type = Map.update(by_type, module, [id], fn ids -> [id | ids] end) on_exit(fn -> # credo:disable-for-next-line Credo.Check.Warning.LazyLogging Logger.debug("Calling 'teardown/3' for '#{module}'") try do module.teardown(setup, step) :ok catch _ -> :ok _, _ -> :ok end end) {{id, step}, %{setup | state: state, by_type: by_type}} end def run(%Setup{stages: stages} = setup) do {stages, setup} = stages |> Enum.reverse |> Enum.map_reduce(setup, &setup_step/2) %{setup | stages: stages} end def setup(ctx) do Map.get(ctx, :__setup) end def setup(ctx, setup_fun) do setup = %Setup{} |> Step.Config.new(:test_config, config_file: nil) {ctx, setup} = setup_fun.(ctx, setup) assert not Map.has_key?(ctx, :__setup), "Key `__setup` is reserved for internal purposes" Map.put(ctx, :__setup, setup) end def completed?(%Setup{by_type: by_type}, step) do Map.has_key?(by_type, step) end def all_for(%Setup{by_type: by_type, state: state}, step_module) do Map.take(state, by_type[step_module] || []) end def reduce_for(setup, step_module, acc, fun) do Enum.reduce(all_for(setup, step_module), acc, fun) end def get(%Setup{state: state}, id) do state[id] end end
27.773196
93
0.609503
0379adb3a292681fbef96a06b1e1841371519ec4
1,403
ex
Elixir
lib/chat_api_web/views/slack_authorization_view.ex
aboutphilippe/papercups
30364cc562f41cd9d5a7ca5357b16ab8484bd5c9
[ "MIT" ]
1
2021-06-17T03:17:24.000Z
2021-06-17T03:17:24.000Z
lib/chat_api_web/views/slack_authorization_view.ex
aboutphilippe/papercups
30364cc562f41cd9d5a7ca5357b16ab8484bd5c9
[ "MIT" ]
null
null
null
lib/chat_api_web/views/slack_authorization_view.ex
aboutphilippe/papercups
30364cc562f41cd9d5a7ca5357b16ab8484bd5c9
[ "MIT" ]
null
null
null
defmodule ChatApiWeb.SlackAuthorizationView do use ChatApiWeb, :view alias ChatApiWeb.SlackAuthorizationView alias ChatApi.SlackAuthorizations def render("show.json", %{slack_authorization: slack_authorization}) do %{ data: render_one( slack_authorization, SlackAuthorizationView, "slack_authorization.json" ) } end def render("slack_authorization.json", %{ slack_authorization: slack_authorization }) do %{ id: slack_authorization.id, object: "slack_authorization", account_id: slack_authorization.account_id, channel: slack_authorization.channel, configuration_url: slack_authorization.configuration_url, team_name: slack_authorization.team_name, created_at: slack_authorization.inserted_at, updated_at: slack_authorization.updated_at, settings: render("settings.json", %{ settings: SlackAuthorizations.get_authorization_settings(slack_authorization) }) } end def render("settings.json", %{settings: settings}) do %{ sync_all_incoming_threads: settings.sync_all_incoming_threads, sync_by_emoji_tagging: settings.sync_by_emoji_tagging, sync_trigger_emoji: settings.sync_trigger_emoji, forward_synced_messages_to_reply_channel: settings.forward_synced_messages_to_reply_channel } end end
31.177778
97
0.722024
0379ce29f659c2f2320b841124e9bc359417fcc9
2,120
exs
Elixir
mix.exs
pojiro/vintage_net_wifi
1033585be6c4a8a65e6085e99b9f470711ceec1c
[ "Apache-2.0" ]
null
null
null
mix.exs
pojiro/vintage_net_wifi
1033585be6c4a8a65e6085e99b9f470711ceec1c
[ "Apache-2.0" ]
null
null
null
mix.exs
pojiro/vintage_net_wifi
1033585be6c4a8a65e6085e99b9f470711ceec1c
[ "Apache-2.0" ]
null
null
null
defmodule VintageNetWiFi.MixProject do use Mix.Project @version "0.10.4" @source_url "https://github.com/nerves-networking/vintage_net_wifi" def project do [ app: :vintage_net_wifi, version: @version, elixir: "~> 1.9", elixirc_paths: elixirc_paths(Mix.env()), test_coverage: [tool: ExCoveralls], start_permanent: Mix.env() == :prod, build_embedded: true, compilers: [:elixir_make | Mix.compilers()], make_targets: ["all"], make_clean: ["mix_clean"], make_error_message: "", deps: deps(), dialyzer: dialyzer(), docs: docs(), package: package(), description: description(), preferred_cli_env: %{ docs: :docs, "hex.publish": :docs, "hex.build": :docs, credo: :test, "coveralls.circle": :test } ] end def application do [ extra_applications: [:crypto, :logger] ] end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] defp description do "WiFi networking for VintageNet" end defp package do %{ files: [ "CHANGELOG.md", "lib", "mix.exs", "Makefile", "README.md", "src/*.[ch]", "src/test-c99.sh", "LICENSE" ], licenses: ["Apache-2.0"], links: %{"GitHub" => @source_url} } end defp deps do [ {:vintage_net, "~> 0.10.0"}, {:credo, "~> 1.2", only: :test, runtime: false}, {:dialyxir, "~> 1.1", only: [:dev, :test], runtime: false}, {:elixir_make, "~> 0.6", runtime: false}, {:ex_doc, "~> 0.22", only: :docs, runtime: false}, {:excoveralls, "~> 0.13", only: :test, runtime: false} ] end defp dialyzer() do [ flags: [:race_conditions, :unmatched_returns, :error_handling, :underspecs] ] end defp docs do [ extras: ["README.md", "CHANGELOG.md"], main: "readme", source_ref: "v#{@version}", source_url: @source_url, skip_undefined_reference_warnings_on: ["CHANGELOG.md"] ] end end
23.043478
81
0.551415
037a2e991a8b124c461b5bb2967e8f4e3b7b2ec3
1,652
ex
Elixir
lib/rql/tokens/update.ex
YgorCastor/ravix
ad3d191e2682b87d533a2d41899ed10e00b4dc55
[ "Apache-2.0" ]
9
2022-01-11T10:01:54.000Z
2022-03-31T06:50:59.000Z
lib/rql/tokens/update.ex
YgorCastor/ravix
ad3d191e2682b87d533a2d41899ed10e00b4dc55
[ "Apache-2.0" ]
2
2022-03-21T20:13:13.000Z
2022-03-28T21:07:47.000Z
lib/rql/tokens/update.ex
YgorCastor/ravix
ad3d191e2682b87d533a2d41899ed10e00b4dc55
[ "Apache-2.0" ]
null
null
null
defmodule Ravix.RQL.Tokens.Update do @moduledoc """ RQL Update tokens """ defstruct token: :update, fields: [] alias Ravix.RQL.Tokens.Update @type t :: %Update{ token: atom(), fields: list(map()) } @doc """ Creates a new "set" update operation Returns a `Ravix.RQL.Tokens.Update` ## Examples iex> import alias Ravix.RQL.Tokens.Update iex> set("field1", 10) |> set("field2", "a") """ @spec set(Update.t(), atom() | String.t(), any) :: Ravix.RQL.Tokens.Update.t() def set(update \\ %Update{}, field, value) do %Update{ update | fields: update.fields ++ [%{name: field, value: value, operation: :set}] } end @doc """ Creates a new "increment" update operation Returns a `Ravix.RQL.Tokens.Update` ## Examples iex> import alias Ravix.RQL.Tokens.Update iex> inc("field1", 10) """ @spec inc(Update.t(), atom() | String.t(), number()) :: Ravix.RQL.Tokens.Update.t() def inc(update \\ %Update{}, field, value) when is_number(value) do %Update{ update | fields: update.fields ++ [%{name: field, value: value, operation: :inc}] } end @doc """ Creates a new "decrement" update operation Returns a `Ravix.RQL.Tokens.Update` ## Examples iex> import alias Ravix.RQL.Tokens.Update iex> dec("field1", 10) """ @spec dec(Update.t(), atom() | String.t(), number()) :: Ravix.RQL.Tokens.Update.t() def dec(update \\ %Update{}, field, value) when is_number(value) do %Update{ update | fields: update.fields ++ [%{name: field, value: value, operation: :dec}] } end end
25.030303
85
0.595036
037a490703b0ce2810a35dd268ed40f0f01a486b
104
exs
Elixir
config/config.exs
kaashyapan/cognitex
ae2cdbd9b07ef1bfb138e71b1c6a85f6e8adea53
[ "MIT" ]
29
2018-08-12T19:32:59.000Z
2021-07-14T16:45:20.000Z
config/config.exs
kaashyapan/cognitex
ae2cdbd9b07ef1bfb138e71b1c6a85f6e8adea53
[ "MIT" ]
1
2018-11-27T11:11:15.000Z
2018-11-27T11:11:15.000Z
config/config.exs
kaashyapan/cognitex
ae2cdbd9b07ef1bfb138e71b1c6a85f6e8adea53
[ "MIT" ]
9
2018-08-12T19:06:01.000Z
2021-08-12T14:22:35.000Z
use Mix.Config config :aws, key: "", secret: "", region: "", client_id: "", user_pool_id: ""
11.555556
18
0.548077
037a4a8f5b8e08ff29a24ceba1c7dda96845ea86
9,675
ex
Elixir
lib/codes/codes_o46.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_o46.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
lib/codes/codes_o46.ex
badubizzle/icd_code
4c625733f92b7b1d616e272abc3009bb8b916c0c
[ "Apache-2.0" ]
null
null
null
defmodule IcdCode.ICDCode.Codes_O46 do alias IcdCode.ICDCode def _O46001 do %ICDCode{full_code: "O46001", category_code: "O46", short_code: "001", full_name: "Antepartum hemorrhage with coagulation defect, unspecified, first trimester", short_name: "Antepartum hemorrhage with coagulation defect, unspecified, first trimester", category_name: "Antepartum hemorrhage with coagulation defect, unspecified, first trimester" } end def _O46002 do %ICDCode{full_code: "O46002", category_code: "O46", short_code: "002", full_name: "Antepartum hemorrhage with coagulation defect, unspecified, second trimester", short_name: "Antepartum hemorrhage with coagulation defect, unspecified, second trimester", category_name: "Antepartum hemorrhage with coagulation defect, unspecified, second trimester" } end def _O46003 do %ICDCode{full_code: "O46003", category_code: "O46", short_code: "003", full_name: "Antepartum hemorrhage with coagulation defect, unspecified, third trimester", short_name: "Antepartum hemorrhage with coagulation defect, unspecified, third trimester", category_name: "Antepartum hemorrhage with coagulation defect, unspecified, third trimester" } end def _O46009 do %ICDCode{full_code: "O46009", category_code: "O46", short_code: "009", full_name: "Antepartum hemorrhage with coagulation defect, unspecified, unspecified trimester", short_name: "Antepartum hemorrhage with coagulation defect, unspecified, unspecified trimester", category_name: "Antepartum hemorrhage with coagulation defect, unspecified, unspecified trimester" } end def _O46011 do %ICDCode{full_code: "O46011", category_code: "O46", short_code: "011", full_name: "Antepartum hemorrhage with afibrinogenemia, first trimester", short_name: "Antepartum hemorrhage with afibrinogenemia, first trimester", category_name: "Antepartum hemorrhage with afibrinogenemia, first trimester" } end def _O46012 do %ICDCode{full_code: "O46012", category_code: "O46", short_code: "012", full_name: "Antepartum hemorrhage with afibrinogenemia, second trimester", short_name: "Antepartum hemorrhage with afibrinogenemia, second trimester", category_name: "Antepartum hemorrhage with afibrinogenemia, second trimester" } end def _O46013 do %ICDCode{full_code: "O46013", category_code: "O46", short_code: "013", full_name: "Antepartum hemorrhage with afibrinogenemia, third trimester", short_name: "Antepartum hemorrhage with afibrinogenemia, third trimester", category_name: "Antepartum hemorrhage with afibrinogenemia, third trimester" } end def _O46019 do %ICDCode{full_code: "O46019", category_code: "O46", short_code: "019", full_name: "Antepartum hemorrhage with afibrinogenemia, unspecified trimester", short_name: "Antepartum hemorrhage with afibrinogenemia, unspecified trimester", category_name: "Antepartum hemorrhage with afibrinogenemia, unspecified trimester" } end def _O46021 do %ICDCode{full_code: "O46021", category_code: "O46", short_code: "021", full_name: "Antepartum hemorrhage with disseminated intravascular coagulation, first trimester", short_name: "Antepartum hemorrhage with disseminated intravascular coagulation, first trimester", category_name: "Antepartum hemorrhage with disseminated intravascular coagulation, first trimester" } end def _O46022 do %ICDCode{full_code: "O46022", category_code: "O46", short_code: "022", full_name: "Antepartum hemorrhage with disseminated intravascular coagulation, second trimester", short_name: "Antepartum hemorrhage with disseminated intravascular coagulation, second trimester", category_name: "Antepartum hemorrhage with disseminated intravascular coagulation, second trimester" } end def _O46023 do %ICDCode{full_code: "O46023", category_code: "O46", short_code: "023", full_name: "Antepartum hemorrhage with disseminated intravascular coagulation, third trimester", short_name: "Antepartum hemorrhage with disseminated intravascular coagulation, third trimester", category_name: "Antepartum hemorrhage with disseminated intravascular coagulation, third trimester" } end def _O46029 do %ICDCode{full_code: "O46029", category_code: "O46", short_code: "029", full_name: "Antepartum hemorrhage with disseminated intravascular coagulation, unspecified trimester", short_name: "Antepartum hemorrhage with disseminated intravascular coagulation, unspecified trimester", category_name: "Antepartum hemorrhage with disseminated intravascular coagulation, unspecified trimester" } end def _O46091 do %ICDCode{full_code: "O46091", category_code: "O46", short_code: "091", full_name: "Antepartum hemorrhage with other coagulation defect, first trimester", short_name: "Antepartum hemorrhage with other coagulation defect, first trimester", category_name: "Antepartum hemorrhage with other coagulation defect, first trimester" } end def _O46092 do %ICDCode{full_code: "O46092", category_code: "O46", short_code: "092", full_name: "Antepartum hemorrhage with other coagulation defect, second trimester", short_name: "Antepartum hemorrhage with other coagulation defect, second trimester", category_name: "Antepartum hemorrhage with other coagulation defect, second trimester" } end def _O46093 do %ICDCode{full_code: "O46093", category_code: "O46", short_code: "093", full_name: "Antepartum hemorrhage with other coagulation defect, third trimester", short_name: "Antepartum hemorrhage with other coagulation defect, third trimester", category_name: "Antepartum hemorrhage with other coagulation defect, third trimester" } end def _O46099 do %ICDCode{full_code: "O46099", category_code: "O46", short_code: "099", full_name: "Antepartum hemorrhage with other coagulation defect, unspecified trimester", short_name: "Antepartum hemorrhage with other coagulation defect, unspecified trimester", category_name: "Antepartum hemorrhage with other coagulation defect, unspecified trimester" } end def _O468X1 do %ICDCode{full_code: "O468X1", category_code: "O46", short_code: "8X1", full_name: "Other antepartum hemorrhage, first trimester", short_name: "Other antepartum hemorrhage, first trimester", category_name: "Other antepartum hemorrhage, first trimester" } end def _O468X2 do %ICDCode{full_code: "O468X2", category_code: "O46", short_code: "8X2", full_name: "Other antepartum hemorrhage, second trimester", short_name: "Other antepartum hemorrhage, second trimester", category_name: "Other antepartum hemorrhage, second trimester" } end def _O468X3 do %ICDCode{full_code: "O468X3", category_code: "O46", short_code: "8X3", full_name: "Other antepartum hemorrhage, third trimester", short_name: "Other antepartum hemorrhage, third trimester", category_name: "Other antepartum hemorrhage, third trimester" } end def _O468X9 do %ICDCode{full_code: "O468X9", category_code: "O46", short_code: "8X9", full_name: "Other antepartum hemorrhage, unspecified trimester", short_name: "Other antepartum hemorrhage, unspecified trimester", category_name: "Other antepartum hemorrhage, unspecified trimester" } end def _O4690 do %ICDCode{full_code: "O4690", category_code: "O46", short_code: "90", full_name: "Antepartum hemorrhage, unspecified, unspecified trimester", short_name: "Antepartum hemorrhage, unspecified, unspecified trimester", category_name: "Antepartum hemorrhage, unspecified, unspecified trimester" } end def _O4691 do %ICDCode{full_code: "O4691", category_code: "O46", short_code: "91", full_name: "Antepartum hemorrhage, unspecified, first trimester", short_name: "Antepartum hemorrhage, unspecified, first trimester", category_name: "Antepartum hemorrhage, unspecified, first trimester" } end def _O4692 do %ICDCode{full_code: "O4692", category_code: "O46", short_code: "92", full_name: "Antepartum hemorrhage, unspecified, second trimester", short_name: "Antepartum hemorrhage, unspecified, second trimester", category_name: "Antepartum hemorrhage, unspecified, second trimester" } end def _O4693 do %ICDCode{full_code: "O4693", category_code: "O46", short_code: "93", full_name: "Antepartum hemorrhage, unspecified, third trimester", short_name: "Antepartum hemorrhage, unspecified, third trimester", category_name: "Antepartum hemorrhage, unspecified, third trimester" } end end
43.38565
115
0.678656
037a52756cc42a165ac412e0a4d4c4299466cac3
54,322
ex
Elixir
clients/content/lib/google_api/content/v2/api/orders.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/api/orders.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/api/orders.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Content.V2.Api.Orders do @moduledoc """ API calls for all endpoints tagged `Orders`. """ alias GoogleApi.Content.V2.Connection alias GoogleApi.Gax.{Request, Response} @doc """ Marks an order as acknowledged. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the order. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersAcknowledgeRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersAcknowledgeResponse{}} on success {:error, info} on failure """ @spec content_orders_acknowledge(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersAcknowledgeResponse.t()} | {:error, Tesla.Env.t()} def content_orders_acknowledge( connection, merchant_id, order_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/orders/{orderId}/acknowledge", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersAcknowledgeResponse{}]) end @doc """ Sandbox only. Moves a test order from state \&quot;inProgress\&quot; to state \&quot;pendingShipment\&quot;. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the test order to modify. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersAdvanceTestOrderResponse{}} on success {:error, info} on failure """ @spec content_orders_advancetestorder(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersAdvanceTestOrderResponse.t()} | {:error, Tesla.Env.t()} def content_orders_advancetestorder( connection, merchant_id, order_id, 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(:post) |> Request.url("/{merchantId}/testorders/{orderId}/advance", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersAdvanceTestOrderResponse{}] ) end @doc """ Cancels all line items in an order, making a full refund. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the order to cancel. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersCancelRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersCancelResponse{}} on success {:error, info} on failure """ @spec content_orders_cancel(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersCancelResponse.t()} | {:error, Tesla.Env.t()} def content_orders_cancel(connection, merchant_id, order_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/orders/{orderId}/cancel", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersCancelResponse{}]) end @doc """ Cancels a line item, making a full refund. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the order. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersCancelLineItemRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersCancelLineItemResponse{}} on success {:error, info} on failure """ @spec content_orders_cancellineitem(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersCancelLineItemResponse.t()} | {:error, Tesla.Env.t()} def content_orders_cancellineitem( connection, merchant_id, order_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/orders/{orderId}/cancelLineItem", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersCancelLineItemResponse{}] ) end @doc """ Sandbox only. Cancels a test order for customer-initiated cancellation. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the test order to cancel. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersCancelTestOrderByCustomerRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersCancelTestOrderByCustomerResponse{}} on success {:error, info} on failure """ @spec content_orders_canceltestorderbycustomer( Tesla.Env.client(), String.t(), String.t(), keyword() ) :: {:ok, GoogleApi.Content.V2.Model.OrdersCancelTestOrderByCustomerResponse.t()} | {:error, Tesla.Env.t()} def content_orders_canceltestorderbycustomer( connection, merchant_id, order_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/testorders/{orderId}/cancelByCustomer", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersCancelTestOrderByCustomerResponse{}] ) end @doc """ Sandbox only. Creates a test order. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that should manage the order. This cannot be a multi-client account. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersCreateTestOrderRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersCreateTestOrderResponse{}} on success {:error, info} on failure """ @spec content_orders_createtestorder(Tesla.Env.client(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersCreateTestOrderResponse.t()} | {:error, Tesla.Env.t()} def content_orders_createtestorder(connection, merchant_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/testorders", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersCreateTestOrderResponse{}] ) end @doc """ Sandbox only. Creates a test return. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the order. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersCreateTestReturnRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersCreateTestReturnResponse{}} on success {:error, info} on failure """ @spec content_orders_createtestreturn(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersCreateTestReturnResponse.t()} | {:error, Tesla.Env.t()} def content_orders_createtestreturn( connection, merchant_id, order_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/orders/{orderId}/testreturn", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersCreateTestReturnResponse{}] ) end @doc """ Retrieves or modifies multiple orders in a single request. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersCustomBatchRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersCustomBatchResponse{}} on success {:error, info} on failure """ @spec content_orders_custombatch(Tesla.Env.client(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersCustomBatchResponse.t()} | {:error, Tesla.Env.t()} def content_orders_custombatch(connection, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/orders/batch") |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersCustomBatchResponse{}]) end @doc """ Retrieves an order from your Merchant Center account. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the order. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. ## Returns {:ok, %GoogleApi.Content.V2.Model.Order{}} on success {:error, info} on failure """ @spec content_orders_get(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.Order.t()} | {:error, Tesla.Env.t()} def content_orders_get(connection, merchant_id, order_id, 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("/{merchantId}/orders/{orderId}", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.Order{}]) end @doc """ Retrieves an order using merchant order ID. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - merchant_order_id (String.t): The merchant order ID to be looked for. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersGetByMerchantOrderIdResponse{}} on success {:error, info} on failure """ @spec content_orders_getbymerchantorderid(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersGetByMerchantOrderIdResponse.t()} | {:error, Tesla.Env.t()} def content_orders_getbymerchantorderid( connection, merchant_id, merchant_order_id, 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("/{merchantId}/ordersbymerchantid/{merchantOrderId}", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "merchantOrderId" => URI.encode(merchant_order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersGetByMerchantOrderIdResponse{}] ) end @doc """ Sandbox only. Retrieves an order template that can be used to quickly create a new order in sandbox. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that should manage the order. This cannot be a multi-client account. - template_name (String.t): The name of the template to retrieve. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :country (String.t): The country of the template to retrieve. Defaults to US. ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersGetTestOrderTemplateResponse{}} on success {:error, info} on failure """ @spec content_orders_gettestordertemplate(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersGetTestOrderTemplateResponse.t()} | {:error, Tesla.Env.t()} def content_orders_gettestordertemplate( connection, merchant_id, template_name, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :country => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{merchantId}/testordertemplates/{templateName}", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "templateName" => URI.encode(template_name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersGetTestOrderTemplateResponse{}] ) end @doc """ Notifies that item return and refund was handled directly by merchant outside of Google payments processing (e.g. cash refund done in store). Note: We recommend calling the returnrefundlineitem method to refund in-store returns. We will issue the refund directly to the customer. This helps to prevent possible differences arising between merchant and Google transaction records. We also recommend having the point of sale system communicate with Google to ensure that customers do not receive a double refund by first refunding via Google then via an in-store return. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the order. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersInStoreRefundLineItemRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersInStoreRefundLineItemResponse{}} on success {:error, info} on failure """ @spec content_orders_instorerefundlineitem( Tesla.Env.client(), String.t(), String.t(), keyword() ) :: {:ok, GoogleApi.Content.V2.Model.OrdersInStoreRefundLineItemResponse.t()} | {:error, Tesla.Env.t()} def content_orders_instorerefundlineitem( connection, merchant_id, order_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/orders/{orderId}/inStoreRefundLineItem", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersInStoreRefundLineItemResponse{}] ) end @doc """ Lists the orders in your Merchant Center account. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :acknowledged (boolean()): Obtains orders that match the acknowledgement status. When set to true, obtains orders that have been acknowledged. When false, obtains orders that have not been acknowledged. We recommend using this filter set to false, in conjunction with the acknowledge call, such that only un-acknowledged orders are returned. - :maxResults (integer()): The maximum number of orders to return in the response, used for paging. The default value is 25 orders per page, and the maximum allowed value is 250 orders per page. - :orderBy (String.t): Order results by placement date in descending or ascending order. Acceptable values are: - placedDateAsc - placedDateDesc - :pageToken (String.t): The token returned by the previous request. - :placedDateEnd (String.t): Obtains orders placed before this date (exclusively), in ISO 8601 format. - :placedDateStart (String.t): Obtains orders placed after this date (inclusively), in ISO 8601 format. - :statuses ([String.t]): Obtains orders that match any of the specified statuses. Multiple values can be specified with comma separation. Additionally, please note that active is a shortcut for pendingShipment and partiallyShipped, and completed is a shortcut for shipped, partiallyDelivered, delivered, partiallyReturned, returned, and canceled. ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersListResponse{}} on success {:error, info} on failure """ @spec content_orders_list(Tesla.Env.client(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersListResponse.t()} | {:error, Tesla.Env.t()} def content_orders_list(connection, merchant_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :acknowledged => :query, :maxResults => :query, :orderBy => :query, :pageToken => :query, :placedDateEnd => :query, :placedDateStart => :query, :statuses => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{merchantId}/orders", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersListResponse{}]) end @doc """ Deprecated, please use returnRefundLineItem instead. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the order to refund. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersRefundRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersRefundResponse{}} on success {:error, info} on failure """ @spec content_orders_refund(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersRefundResponse.t()} | {:error, Tesla.Env.t()} def content_orders_refund(connection, merchant_id, order_id, optional_params \\ [], opts \\ []) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/orders/{orderId}/refund", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersRefundResponse{}]) end @doc """ Rejects return on an line item. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the order. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersRejectReturnLineItemRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersRejectReturnLineItemResponse{}} on success {:error, info} on failure """ @spec content_orders_rejectreturnlineitem(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersRejectReturnLineItemResponse.t()} | {:error, Tesla.Env.t()} def content_orders_rejectreturnlineitem( connection, merchant_id, order_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/orders/{orderId}/rejectReturnLineItem", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersRejectReturnLineItemResponse{}] ) end @doc """ Returns a line item. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the order. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersReturnLineItemRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersReturnLineItemResponse{}} on success {:error, info} on failure """ @spec content_orders_returnlineitem(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersReturnLineItemResponse.t()} | {:error, Tesla.Env.t()} def content_orders_returnlineitem( connection, merchant_id, order_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/orders/{orderId}/returnLineItem", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersReturnLineItemResponse{}] ) end @doc """ Returns and refunds a line item. Note that this method can only be called on fully shipped orders. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the order. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersReturnRefundLineItemRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersReturnRefundLineItemResponse{}} on success {:error, info} on failure """ @spec content_orders_returnrefundlineitem(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersReturnRefundLineItemResponse.t()} | {:error, Tesla.Env.t()} def content_orders_returnrefundlineitem( connection, merchant_id, order_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/orders/{orderId}/returnRefundLineItem", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersReturnRefundLineItemResponse{}] ) end @doc """ Sets (or overrides if it already exists) merchant provided annotations in the form of key-value pairs. A common use case would be to supply us with additional structured information about a line item that cannot be provided via other methods. Submitted key-value pairs can be retrieved as part of the orders resource. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the order. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersSetLineItemMetadataRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersSetLineItemMetadataResponse{}} on success {:error, info} on failure """ @spec content_orders_setlineitemmetadata(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersSetLineItemMetadataResponse.t()} | {:error, Tesla.Env.t()} def content_orders_setlineitemmetadata( connection, merchant_id, order_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/orders/{orderId}/setLineItemMetadata", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersSetLineItemMetadataResponse{}] ) end @doc """ Marks line item(s) as shipped. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the order. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersShipLineItemsRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersShipLineItemsResponse{}} on success {:error, info} on failure """ @spec content_orders_shiplineitems(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersShipLineItemsResponse.t()} | {:error, Tesla.Env.t()} def content_orders_shiplineitems( connection, merchant_id, order_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/orders/{orderId}/shipLineItems", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersShipLineItemsResponse{}] ) end @doc """ Updates ship by and delivery by dates for a line item. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the order. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersUpdateLineItemShippingDetailsRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersUpdateLineItemShippingDetailsResponse{}} on success {:error, info} on failure """ @spec content_orders_updatelineitemshippingdetails( Tesla.Env.client(), String.t(), String.t(), keyword() ) :: {:ok, GoogleApi.Content.V2.Model.OrdersUpdateLineItemShippingDetailsResponse.t()} | {:error, Tesla.Env.t()} def content_orders_updatelineitemshippingdetails( connection, merchant_id, order_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/orders/{orderId}/updateLineItemShippingDetails", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersUpdateLineItemShippingDetailsResponse{}] ) end @doc """ Updates the merchant order ID for a given order. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the order. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersUpdateMerchantOrderIdRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersUpdateMerchantOrderIdResponse{}} on success {:error, info} on failure """ @spec content_orders_updatemerchantorderid( Tesla.Env.client(), String.t(), String.t(), keyword() ) :: {:ok, GoogleApi.Content.V2.Model.OrdersUpdateMerchantOrderIdResponse.t()} | {:error, Tesla.Env.t()} def content_orders_updatemerchantorderid( connection, merchant_id, order_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/orders/{orderId}/updateMerchantOrderId", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersUpdateMerchantOrderIdResponse{}] ) end @doc """ Updates a shipment&#39;s status, carrier, and/or tracking ID. ## Parameters - connection (GoogleApi.Content.V2.Connection): Connection to server - merchant_id (String.t): The ID of the account that manages the order. This cannot be a multi-client account. - order_id (String.t): The ID of the order. - optional_params (KeywordList): [optional] Optional parameters - :alt (String.t): Data format for the response. - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (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 (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters. - :userIp (String.t): Deprecated. Please use quotaUser instead. - :body (OrdersUpdateShipmentRequest): ## Returns {:ok, %GoogleApi.Content.V2.Model.OrdersUpdateShipmentResponse{}} on success {:error, info} on failure """ @spec content_orders_updateshipment(Tesla.Env.client(), String.t(), String.t(), keyword()) :: {:ok, GoogleApi.Content.V2.Model.OrdersUpdateShipmentResponse.t()} | {:error, Tesla.Env.t()} def content_orders_updateshipment( connection, merchant_id, order_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{merchantId}/orders/{orderId}/updateShipment", %{ "merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1), "orderId" => URI.encode(order_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode( opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersUpdateShipmentResponse{}] ) end end
41.403963
570
0.670483
037a67ad60f9e2b598d220699a1dcca980613ecc
1,185
ex
Elixir
coherence_demo_no_confirm/lib/coherence_demo_web/coherence_web.ex
hotpyn/coherence-setup
fc10bb15d993ae0dd13a19fd178bdfb4ee13d6b6
[ "MIT" ]
null
null
null
coherence_demo_no_confirm/lib/coherence_demo_web/coherence_web.ex
hotpyn/coherence-setup
fc10bb15d993ae0dd13a19fd178bdfb4ee13d6b6
[ "MIT" ]
null
null
null
coherence_demo_no_confirm/lib/coherence_demo_web/coherence_web.ex
hotpyn/coherence-setup
fc10bb15d993ae0dd13a19fd178bdfb4ee13d6b6
[ "MIT" ]
null
null
null
defmodule CoherenceDemoWeb.Coherence do @moduledoc false def view do quote do use Phoenix.View, root: "lib/coherence_demo_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 CoherenceDemoWeb.Router.Helpers import CoherenceDemoWeb.ErrorHelpers import CoherenceDemoWeb.Gettext import CoherenceDemoWeb.Coherence.ViewHelpers end end def controller do quote do use Phoenix.Controller, except: [layout_view: 2] use Coherence.Config use Timex import Ecto import Ecto.Query import Plug.Conn import CoherenceDemoWeb.Router.Helpers import CoherenceDemoWeb.Gettext import Coherence.ControllerHelpers alias Coherence.Config alias Coherence.ControllerHelpers, as: Helpers require Redirects 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
24.6875
88
0.704641
037ac12ebcef1d5f525a31b176c3a49265bddf30
1,265
ex
Elixir
lib/platform_web/controllers/gameplay_controller.ex
LKlemens/platform
837d70503c71e603c2830df9b6c1f8e77cdfe620
[ "MIT" ]
1
2020-02-20T21:57:02.000Z
2020-02-20T21:57:02.000Z
lib/platform_web/controllers/gameplay_controller.ex
LKlemens/platform
837d70503c71e603c2830df9b6c1f8e77cdfe620
[ "MIT" ]
1
2020-03-23T19:22:48.000Z
2020-03-23T19:22:48.000Z
lib/platform_web/controllers/gameplay_controller.ex
LKlemens/platform
837d70503c71e603c2830df9b6c1f8e77cdfe620
[ "MIT" ]
null
null
null
defmodule PlatformWeb.GameplayController do use PlatformWeb, :controller alias Platform.Products alias Platform.Products.Gameplay action_fallback PlatformWeb.FallbackController def index(conn, _params) do gameplays = Products.list_gameplays() render(conn, "index.json", gameplays: gameplays) end def create(conn, %{"gameplay" => gameplay_params}) do with {:ok, %Gameplay{} = gameplay} <- Products.create_gameplay(gameplay_params) do conn |> put_status(:created) |> put_resp_header("location", Routes.gameplay_path(conn, :show, gameplay)) |> render("show.json", gameplay: gameplay) end end def show(conn, %{"id" => id}) do gameplay = Products.get_gameplay!(id) render(conn, "show.json", gameplay: gameplay) end def update(conn, %{"id" => id, "gameplay" => gameplay_params}) do gameplay = Products.get_gameplay!(id) with {:ok, %Gameplay{} = gameplay} <- Products.update_gameplay(gameplay, gameplay_params) do render(conn, "show.json", gameplay: gameplay) end end def delete(conn, %{"id" => id}) do gameplay = Products.get_gameplay!(id) with {:ok, %Gameplay{}} <- Products.delete_gameplay(gameplay) do send_resp(conn, :no_content, "") end end end
28.75
96
0.679051
037b1387237e1fa281997453915433c64170664d
419
exs
Elixir
priv/repo/migrations/2016032505124126_create_batch_histories.exs
simwms/apiv4
c3da7407eaf3580b759f49726028439b4b8ea9d0
[ "MIT" ]
2
2016-02-25T20:12:35.000Z
2018-01-03T00:03:12.000Z
priv/repo/migrations/2016032505124126_create_batch_histories.exs
simwms/apiv4
c3da7407eaf3580b759f49726028439b4b8ea9d0
[ "MIT" ]
1
2016-01-11T04:50:39.000Z
2016-01-12T05:00:08.000Z
priv/repo/migrations/2016032505124126_create_batch_histories.exs
simwms/apiv4
c3da7407eaf3580b759f49726028439b4b8ea9d0
[ "MIT" ]
null
null
null
defmodule Apiv4.Repo.Migrations.CreateBatchHistories do use Ecto.Migration def change do create table(:batch_histories) do add :recordable_id, :integer add :type, :string add :name, :string add :message, :string add :scheduled_at, :datetime add :happened_at, :datetime add :mentioned_type, :string add :mentioned_id, :integer timestamps end end end
22.052632
55
0.665871
037b14c2b1725e6e64ededfd462f1d04f17257b8
2,595
ex
Elixir
clients/identity_toolkit/lib/google_api/identity_toolkit/v3/model/user_info_provider_user_info.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/identity_toolkit/lib/google_api/identity_toolkit/v3/model/user_info_provider_user_info.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/identity_toolkit/lib/google_api/identity_toolkit/v3/model/user_info_provider_user_info.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.IdentityToolkit.V3.Model.UserInfoProviderUserInfo do @moduledoc """ ## Attributes * `displayName` (*type:* `String.t`, *default:* `nil`) - The user's display name at the IDP. * `email` (*type:* `String.t`, *default:* `nil`) - User's email at IDP. * `federatedId` (*type:* `String.t`, *default:* `nil`) - User's identifier at IDP. * `phoneNumber` (*type:* `String.t`, *default:* `nil`) - User's phone number. * `photoUrl` (*type:* `String.t`, *default:* `nil`) - The user's photo url at the IDP. * `providerId` (*type:* `String.t`, *default:* `nil`) - The IdP ID. For white listed IdPs it's a short domain name, e.g., google.com, aol.com, live.net and yahoo.com. For other OpenID IdPs it's the OP identifier. * `rawId` (*type:* `String.t`, *default:* `nil`) - User's raw identifier directly returned from IDP. * `screenName` (*type:* `String.t`, *default:* `nil`) - User's screen name at Twitter or login name at Github. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :displayName => String.t(), :email => String.t(), :federatedId => String.t(), :phoneNumber => String.t(), :photoUrl => String.t(), :providerId => String.t(), :rawId => String.t(), :screenName => String.t() } field(:displayName) field(:email) field(:federatedId) field(:phoneNumber) field(:photoUrl) field(:providerId) field(:rawId) field(:screenName) end defimpl Poison.Decoder, for: GoogleApi.IdentityToolkit.V3.Model.UserInfoProviderUserInfo do def decode(value, options) do GoogleApi.IdentityToolkit.V3.Model.UserInfoProviderUserInfo.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.IdentityToolkit.V3.Model.UserInfoProviderUserInfo do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
38.161765
216
0.677071
037b874e23f1a3b6f0d2825f68ebfd8d5adfe2ed
1,982
exs
Elixir
clients/container_analysis/mix.exs
Contractbook/elixir-google-api
342751041aaf8c2e7f76f9922cf24b9c5895802b
[ "Apache-2.0" ]
null
null
null
clients/container_analysis/mix.exs
Contractbook/elixir-google-api
342751041aaf8c2e7f76f9922cf24b9c5895802b
[ "Apache-2.0" ]
null
null
null
clients/container_analysis/mix.exs
Contractbook/elixir-google-api
342751041aaf8c2e7f76f9922cf24b9c5895802b
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.ContainerAnalysis.Mixfile do use Mix.Project @version "0.14.0" def project() do [ app: :google_api_container_analysis, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/container_analysis" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.4"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Container Analysis API client library. An implementation of the Grafeas API, which stores, and enables querying and retrieval of critical metadata about all of your software artifacts. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/container_analysis", "Homepage" => "https://cloud.google.com/container-analysis/api/reference/rest/" } ] end end
29.58209
188
0.671544
037b9854e58a67c035f33b34e40be34230919a69
420
exs
Elixir
config/test.exs
eeng/blaine
d91d94034925d64632789925ef90a198c0a1d8ea
[ "MIT" ]
null
null
null
config/test.exs
eeng/blaine
d91d94034925d64632789925ef90a198c0a1d8ea
[ "MIT" ]
null
null
null
config/test.exs
eeng/blaine
d91d94034925d64632789925ef90a198c0a1d8ea
[ "MIT" ]
null
null
null
import Config config :blaine, :components, accounts_manager: Blaine.Services.MockAccountsManager, uploads_service: Blaine.Services.MockUploadsService, google_auth_api: Blaine.Google.MockAuthAPI, google_people_api: Blaine.Google.MockPeopleAPI, google_youtube_api: Blaine.Google.MockYouTubeAPI, http_client: Blaine.Util.MockHTTP, repository: Blaine.Persistance.MockRepository config :logger, level: :error
32.307692
56
0.82381
037bc25b5b99a846695f003b1ba64dfa2945ee5e
15,529
ex
Elixir
lib/elixir/lib/application.ex
hamiltop/elixir
3b601660d4d4eb0c69f824fcebbbe93a3f2ba463
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/application.ex
hamiltop/elixir
3b601660d4d4eb0c69f824fcebbbe93a3f2ba463
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/application.ex
hamiltop/elixir
3b601660d4d4eb0c69f824fcebbbe93a3f2ba463
[ "Apache-2.0" ]
null
null
null
defmodule Application do @moduledoc """ A module for working with applications and defining application callbacks. In Elixir (actually, in Erlang/OTP), an application is a component implementing some specific functionality, that can be started and stopped as a unit, and which can be re-used in other systems. Applications are defined with an application file named `APP.app` where `APP` is the application name, usually in `underscore_case`. The application file must reside in the same `ebin` directory as the compiled modules of the application. In Elixir, Mix is responsible for compiling your source code and generating your application `.app` file. Furthermore, Mix is also responsible for configuring, starting and stopping your application and its dependencies. For this reason, this documentation will focus on the remaining aspects of your application: the application environment and the application callback module. You can learn more about Mix generation of `.app` files by typing `mix help compile.app`. ## Application environment Once an application is started, OTP provides an application environment that can be used to configure the application. Assuming you are inside a Mix project, you can edit the `application` function in the `mix.exs` file to the following: def application do [env: [hello: :world]] end In the application function, we can define the default environment values for our application. By starting your application with `iex -S mix`, you can access the default value: Application.get_env(:APP_NAME, :hello) #=> :world It is also possible to put and delete values from the application value, including new values that are not defined in the environment file (although this should be avoided). Keep in mind that each application is responsible for its environment. Do not use the functions in this module for directly accessing or modifying the environment of other applications (as it may lead to inconsistent data in the application environment). ## Application module callback Often times, an application defines a supervision tree that must be started and stopped when the application starts and stops. For such, we need to define an application module callback. The first step is to define the module callback in the application definition in the `mix.exs` file: def application do [mod: {MyApp, []}] end Our application now requires the `MyApp` module to provide an application callback. This can be done by invoking `use Application` in that module and defining a `start/2` callback, for example: defmodule MyApp do use Application def start(_type, _args) do MyApp.Supervisor.start_link() end end `start/2` typically returns `{:ok, pid}` or `{:ok, pid, state}` where `pid` identifies the supervision tree and `state` is the application state. `args` is the second element of the tuple given to the `:mod` option. The `type` argument passed to `start/2` is usually `:normal` unless in a distributed setup where application takeovers and failovers are configured. This particular aspect of applications is explained in more detail in the OTP documentation: * [`:application` module](http://www.erlang.org/doc/man/application.html) * [Applications – OTP Design Principles](http://www.erlang.org/doc/design_principles/applications.html) A developer may also implement the `stop/1` callback (automatically defined by `use Application`) which does any application cleanup. It receives the application state and can return any value. Note that shutting down the supervisor is automatically handled by the VM. """ @doc false defmacro __using__(_) do quote location: :keep do @behaviour :application @doc false def stop(_state) do :ok end defoverridable [stop: 1] end end @type app :: atom @type key :: atom @type value :: term @type start_type :: :permanent | :transient | :temporary @application_keys [:description, :id, :vsn, :modules, :maxP, :maxT, :registered, :included_applications, :applications, :mod, :start_phases] @doc """ Returns the spec for `app`. The following keys are returned: * #{Enum.map_join @application_keys, "\n * ", &inspect/1} Note the environment is not returned as it can be accessed via `fetch_env/2`. Returns `nil` if the application is not loaded. """ @spec spec(app) :: [{key, value}] | nil def spec(app) do case :application.get_all_key(app) do {:ok, info} -> :lists.keydelete(:env, 1, info) :undefined -> nil end end @doc """ Returns the value for `key` in `app`'s specification. See `spec/1` for the supporte keys. If the given specification parameter does not exist, this function will raise. """ @spec spec(app, key) :: value def spec(app, key) when key in @application_keys do {:ok, value} = :application.get_key(app, key) value end @doc """ Get the application for the given module. The application is located by analyzing the spec of all loaded applications. Returns `nil` if the module is not listed in any application spec. """ @spec get_application(atom) :: atom | nil def get_application(module) when is_atom(module) do case :application.get_application(module) do {:ok, app} -> app :undefined -> nil end end @doc """ Returns all key-value pairs for `app`. """ @spec get_all_env(app) :: [{key, value}] def get_all_env(app) do :application.get_all_env(app) end @doc """ Returns the value for `key` in `app`'s environment. If the configuration parameter does not exist, the function returns the `default` value. """ @spec get_env(app, key, value) :: value def get_env(app, key, default \\ nil) do :application.get_env(app, key, default) end @doc """ Returns the value for `key` in `app`'s environment in a tuple. If the configuration parameter does not exist, the function returns `:error`. """ @spec fetch_env(app, key) :: {:ok, value} | :error def fetch_env(app, key) do case :application.get_env(app, key) do {:ok, value} -> {:ok, value} :undefined -> :error end end @doc """ Returns the value for `key` in `app`'s environment. If the configuration parameter does not exist, raises `ArgumentError`. """ @spec fetch_env!(app, key) :: value | no_return def fetch_env!(app, key) do case fetch_env(app, key) do {:ok, value} -> value :error -> raise ArgumentError, "application #{inspect app} is not loaded, " <> "or the configuration parameter #{inspect key} is not set" end end @doc """ Puts the `value` in `key` for the given `app`. ## Options * `:timeout` - the timeout for the change (defaults to 5000ms) * `:persistent` - persists the given value on application load and reloads If `put_env/4` is called before the application is loaded, the application environment values specified in the `.app` file will override the ones previously set. The persistent option can be set to `true` when there is a need to guarantee parameters set with this function will not be overridden by the ones defined in the application resource file on load. This means persistent values will stick after the application is loaded and also on application reload. """ @spec put_env(app, key, value, [timeout: timeout, persistent: boolean]) :: :ok def put_env(app, key, value, opts \\ []) do :application.set_env(app, key, value, opts) end @doc """ Deletes the `key` from the given `app` environment. See `put_env/4` for a description of the options. """ @spec delete_env(app, key, [timeout: timeout, persistent: boolean]) :: :ok def delete_env(app, key, opts \\ []) do :application.unset_env(app, key, opts) end @doc """ Ensures the given `app` is started. Same as `start/2` but returns `:ok` if the application was already started. This is useful in scripts and in test setup, where test applications need to be explicitly started: :ok = Application.ensure_started(:my_test_dep) """ @spec ensure_started(app, start_type) :: :ok | {:error, term} def ensure_started(app, type \\ :temporary) when is_atom(app) do :application.ensure_started(app, type) end @doc """ Ensures the given `app` and its applications are started. Same as `start/2` but also starts the applications listed under `:applications` in the `.app` file in case they were not previously started. """ @spec ensure_all_started(app, start_type) :: {:ok, [app]} | {:error, {app, term}} def ensure_all_started(app, type \\ :temporary) when is_atom(app) do :application.ensure_all_started(app, type) end @doc """ Starts the given `app`. If the `app` is not loaded, the application will first be loaded using `load/1`. Any included application, defined in the `:included_applications` key of the `.app` file will also be loaded, but they won't be started. Furthermore, all applications listed in the `:applications` key must be explicitly started before this application is. If not, `{:error, {:not_started, app}}` is returned, where `app` is the name of the missing application. In case you want to automatically load **and start** all of `app`'s dependencies, see `ensure_all_started/2`. The `type` argument specifies the type of the application: * `:permanent` - if `app` terminates, all other applications and the entire node are also terminated. * `:transient` - if `app` terminates with `:normal` reason, it is reported but no other applications are terminated. If a transient application terminates abnormally, all other applications and the entire node are also terminated. * `:temporary` - if `app` terminates, it is reported but no other applications are terminated (the default). Note that it is always possible to stop an application explicitly by calling `stop/1`. Regardless of the type of the application, no other applications will be affected. Note also that the `:transient` type is of little practical use, since when a supervision tree terminates, the reason is set to `:shutdown`, not `:normal`. """ @spec start(app, start_type) :: :ok | {:error, term} def start(app, type \\ :temporary) when is_atom(app) do :application.start(app, type) end @doc """ Stops the given `app`. When stopped, the application is still loaded. """ @spec stop(app) :: :ok | {:error, term} def stop(app) do :application.stop(app) end @doc """ Loads the given `app`. In order to be loaded, an `.app` file must be in the load paths. All `:included_applications` will also be loaded. Loading the application does not start it nor load its modules, but it does load its environment. """ @spec load(app) :: :ok | {:error, term} def load(app) when is_atom(app) do :application.load(app) end @doc """ Unloads the given `app`. It will also unload all `:included_applications`. Note that the function does not purge the application modules. """ @spec unload(app) :: :ok | {:error, term} def unload(app) when is_atom(app) do :application.unload(app) end @doc """ Gets the directory for app. This information is returned based on the code path. Here is an example: File.mkdir_p!("foo/ebin") Code.prepend_path("foo/ebin") Application.app_dir(:foo) #=> "foo" Even though the directory is empty and there is no `.app` file it is considered the application directory based on the name "foo/ebin". The name may contain a dash `-` which is considered to be the app version and it is removed for the lookup purposes: File.mkdir_p!("bar-123/ebin") Code.prepend_path("bar-123/ebin") Application.app_dir(:bar) #=> "bar-123" For more information on code paths, check the `Code` module in Elixir and also Erlang's `:code` module. """ @spec app_dir(app) :: String.t def app_dir(app) when is_atom(app) do case :code.lib_dir(app) do lib when is_list(lib) -> IO.chardata_to_string(lib) {:error, :bad_name} -> raise ArgumentError, "unknown application: #{inspect app}" end end @doc """ Returns the given path inside `app_dir/1`. """ @spec app_dir(app, String.t) :: String.t def app_dir(app, path) when is_binary(path) do Path.join(app_dir(app), path) end @doc """ Returns a list with information about the applications which are currently running. """ @spec started_applications(timeout) :: [tuple] def started_applications(timeout \\ 5000) do :application.which_applications(timeout) end @doc """ Returns a list with information about the applications which have been loaded. """ @spec loaded_applications :: [tuple] def loaded_applications do :application.loaded_applications end @doc """ Formats the error reason returned by `start/2`, `ensure_started/2`, `stop/1`, `load/1` and `unload/1`, returns a string. """ @spec format_error(any) :: String.t def format_error(reason) do try do impl_format_error(reason) catch # A user could create an error that looks like a builtin one # causing an error. :error, _ -> inspect(reason) end end # exit(:normal) call is special cased, undo the special case. defp impl_format_error({{:EXIT, :normal}, {mod, :start, args}}) do Exception.format_exit({:normal, {mod, :start, args}}) end # {:error, reason} return value defp impl_format_error({reason, {mod, :start, args}}) do Exception.format_mfa(mod, :start, args) <> " returned an error: " <> Exception.format_exit(reason) end # error or exit(reason) call, use exit reason as reason. defp impl_format_error({:bad_return, {{mod, :start, args}, {:EXIT, reason}}}) do Exception.format_exit({reason, {mod, :start, args}}) end # bad return value defp impl_format_error({:bad_return, {{mod, :start, args}, return}}) do Exception.format_mfa(mod, :start, args) <> " returned a bad value: " <> inspect(return) end defp impl_format_error({:already_started, app}) when is_atom(app) do "already started application #{app}" end defp impl_format_error({:not_started, app}) when is_atom(app) do "not started application #{app}" end defp impl_format_error({:bad_application, app}) do "bad application: #{inspect(app)}" end defp impl_format_error({:already_loaded, app}) when is_atom(app) do "already loaded application #{app}" end defp impl_format_error({:not_loaded, app}) when is_atom(app) do "not loaded application #{app}" end defp impl_format_error({:invalid_restart_type, restart}) do "invalid application restart type: #{inspect(restart)}" end defp impl_format_error({:invalid_name, name}) do "invalid application name: #{inspect(name)}" end defp impl_format_error({:invalid_options, opts}) do "invalid application options: #{inspect(opts)}" end defp impl_format_error({:badstartspec, spec}) do "bad application start specs: #{inspect(spec)}" end defp impl_format_error({'no such file or directory', file}) do "could not find application file: #{file}" end defp impl_format_error(reason) do Exception.format_exit(reason) end end
32.284823
107
0.69309
037c199baf1d968c0335b29da168696c30a024df
429
exs
Elixir
apps/core/priv/prm_repo/migrations/20170922121046_create_medical_program.exs
ehealth-ua/ehealth.api
4ffe26a464fe40c95fb841a4aa2e147068f65ca2
[ "Apache-2.0" ]
8
2019-06-14T11:34:49.000Z
2021-08-05T19:14:24.000Z
apps/core/priv/prm_repo/migrations/20170922121046_create_medical_program.exs
edenlabllc/ehealth.api.public
4ffe26a464fe40c95fb841a4aa2e147068f65ca2
[ "Apache-2.0" ]
1
2019-07-08T15:20:22.000Z
2019-07-08T15:20:22.000Z
apps/core/priv/prm_repo/migrations/20170922121046_create_medical_program.exs
ehealth-ua/ehealth.api
4ffe26a464fe40c95fb841a4aa2e147068f65ca2
[ "Apache-2.0" ]
6
2018-05-11T13:59:32.000Z
2022-01-19T20:15:22.000Z
defmodule Core.PRMRepo.Migrations.CreateMedicalProgram do use Ecto.Migration def change do create table(:medical_programs, primary_key: false) do add(:id, :uuid, primary_key: true) add(:name, :string, null: false) add(:is_active, :boolean, null: false) add(:inserted_by, :uuid, null: false) add(:updated_by, :uuid, null: false) timestamps(type: :utc_datetime_usec) end end end
26.8125
58
0.678322
037c4346b23b0929f50ba5799921a5e661b4406f
1,002
exs
Elixir
test/tailwind_test.exs
skunkwerks/tailwind
73b220315e4cce5dd3716e978389b41aa9314614
[ "MIT" ]
null
null
null
test/tailwind_test.exs
skunkwerks/tailwind
73b220315e4cce5dd3716e978389b41aa9314614
[ "MIT" ]
null
null
null
test/tailwind_test.exs
skunkwerks/tailwind
73b220315e4cce5dd3716e978389b41aa9314614
[ "MIT" ]
null
null
null
defmodule TailwindTest do use ExUnit.Case, async: true @version Tailwind.latest_version() test "run on default" do assert ExUnit.CaptureIO.capture_io(fn -> assert Tailwind.run(:default, ["--help"]) == 0 end) =~ @version assert File.exists?("assets/tailwind.config.js") end test "run on profile" do assert ExUnit.CaptureIO.capture_io(fn -> assert Tailwind.run(:another, []) == 0 end) =~ @version end test "updates on install" do Application.put_env(:tailwind, :version, "3.0.8") Mix.Task.rerun("tailwind.install", ["--if-missing"]) assert ExUnit.CaptureIO.capture_io(fn -> assert Tailwind.run(:default, ["--help"]) == 0 end) =~ "3.0.8" Application.delete_env(:tailwind, :version) Mix.Task.rerun("tailwind.install", ["--if-missing"]) assert ExUnit.CaptureIO.capture_io(fn -> assert Tailwind.run(:default, ["--help"]) == 0 end) =~ @version end end
27.081081
59
0.60479
037c68b59c2f866cb952e2e527eea2de0b1bc807
347
exs
Elixir
priv/repo/seeds.exs
harmon25/phonix_react
390d2663d1d796224588d94c5073b3bac600bb7f
[ "MIT" ]
null
null
null
priv/repo/seeds.exs
harmon25/phonix_react
390d2663d1d796224588d94c5073b3bac600bb7f
[ "MIT" ]
null
null
null
priv/repo/seeds.exs
harmon25/phonix_react
390d2663d1d796224588d94c5073b3bac600bb7f
[ "MIT" ]
null
null
null
# Script for populating the database. You can run it as: # # mix run priv/repo/seeds.exs # # Inside the script, you can read and write to any of your # repositories directly: # # PhoenixReact.Repo.insert!(%SomeModel{}) # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong.
28.916667
61
0.706052
037c75a26a60e965c8b66c99bb66d743c87268ea
631
ex
Elixir
testData/org/elixir_lang/parser_definition/matched_call_operation/matched_expression_parsing_test_case/BinaryWholeNumber.ex
ArtemGordinsky/intellij-elixir
e2d9b4dfc65651b293d499043edeaad606cf5652
[ "Apache-2.0" ]
null
null
null
testData/org/elixir_lang/parser_definition/matched_call_operation/matched_expression_parsing_test_case/BinaryWholeNumber.ex
ArtemGordinsky/intellij-elixir
e2d9b4dfc65651b293d499043edeaad606cf5652
[ "Apache-2.0" ]
null
null
null
testData/org/elixir_lang/parser_definition/matched_call_operation/matched_expression_parsing_test_case/BinaryWholeNumber.ex
ArtemGordinsky/intellij-elixir
e2d9b4dfc65651b293d499043edeaad606cf5652
[ "Apache-2.0" ]
null
null
null
0b10 &one 0b10 one \\ default 0b10 one when guard 0b10 one :: type 0b10 one | new 0b10 one = two 0b10 one or two 0b10 one || two 0b10 one and two 0b10 one && two 0b10 one != two 0b10 one < two 0b10 one |> two 0b10 one + two 0b10 one / two 0b10 one * two 0b10 one ^^^ two 0b10 !one 0b10 One.Two 0b10 One.two 0b10 @one 0b10 One Two 0b10 one 0b10 @1 0b10 &1 0b10 !1 0b10 not 1 0b10 (;) 0b10 ?1 0b10 0b10 0b10 1.2e-3 0b10 1 0b10 0xFF 0b10 0o7 0b10 0zZ 0b10 [] 0b10 "StringLine" 0b10 """ String Heredoc """ 0b10 'CharListLine' 0b10 ''' CharListLine ''' 0b10 ~x{sigil}modifiers 0b10 0b10 0b10 0b10 0b10 One
12.62
23
0.662441
037c8f16ed1f0727c3e6125e05e832d2edcb3b4f
424
ex
Elixir
lib/hacker_news_aggregator_web/controllers/fallback_controller.ex
rhnonose/hacker_news_aggregator
2dbcf9db4fb08c9cdc716959e0283c5e98312586
[ "MIT" ]
null
null
null
lib/hacker_news_aggregator_web/controllers/fallback_controller.ex
rhnonose/hacker_news_aggregator
2dbcf9db4fb08c9cdc716959e0283c5e98312586
[ "MIT" ]
null
null
null
lib/hacker_news_aggregator_web/controllers/fallback_controller.ex
rhnonose/hacker_news_aggregator
2dbcf9db4fb08c9cdc716959e0283c5e98312586
[ "MIT" ]
null
null
null
defmodule HackerNewsAggregatorWeb.FallbackController do @moduledoc """ Translates controller action results into valid `Plug.Conn` responses. See `Phoenix.Controller.action_fallback/1` for more details. """ use HackerNewsAggregatorWeb, :controller def call(conn, {:error, :not_found}) do conn |> put_status(:not_found) |> put_view(HackerNewsAggregatorWeb.ErrorView) |> render(:"404") end end
26.5
72
0.733491
037c9214adbef37da7aeedb1cb4d71030d849771
1,544
ex
Elixir
test/support/data_case.ex
jennifertakagi/chewiepay
15b5eca89f56e2933610f3edda7412889dc08137
[ "MIT" ]
4
2021-02-22T18:27:51.000Z
2021-02-28T21:54:12.000Z
test/support/data_case.ex
jennifertakagi/chewiepay
15b5eca89f56e2933610f3edda7412889dc08137
[ "MIT" ]
null
null
null
test/support/data_case.ex
jennifertakagi/chewiepay
15b5eca89f56e2933610f3edda7412889dc08137
[ "MIT" ]
null
null
null
defmodule Chewiepay.DataCase do @moduledoc """ This module defines the setup for tests requiring access to the application's data layer. You may define functions here to be used as helpers in your tests. Finally, if the test case interacts with the database, we enable the SQL sandbox, so changes done to the database are reverted at the end of every test. If you are using PostgreSQL, you can even run database tests asynchronously by setting `use Chewiepay.DataCase, async: true`, although this option is not recommended for other databases. """ use ExUnit.CaseTemplate using do quote do alias Chewiepay.Repo import Ecto import Ecto.Changeset import Ecto.Query import Chewiepay.DataCase end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Chewiepay.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(Chewiepay.Repo, {:shared, self()}) end :ok end @doc """ A helper that transforms changeset errors into a map of messages. assert {:error, changeset} = Accounts.create_user(%{password: "short"}) assert "password is too short" in errors_on(changeset).password assert %{password: ["password is too short"]} = errors_on(changeset) """ def errors_on(changeset) do Ecto.Changeset.traverse_errors(changeset, fn {message, opts} -> Regex.replace(~r"%{(\w+)}", message, fn _, key -> opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string() end) end) end end
27.571429
77
0.691062
037cefd87454bf3d2407878af481af68a1f2d6a3
858
exs
Elixir
elixir/06_Retirement_Calculator/retirement_calculator.exs
lucifer1004/EFP
3be9f22ef76957c0f3ebdc0dbb415cea1ede8da9
[ "MIT" ]
1
2021-11-04T11:49:46.000Z
2021-11-04T11:49:46.000Z
elixir/06_Retirement_Calculator/retirement_calculator.exs
lucifer1004/EFP
3be9f22ef76957c0f3ebdc0dbb415cea1ede8da9
[ "MIT" ]
8
2019-12-16T09:37:36.000Z
2020-07-02T06:00:30.000Z
elixir/06_Retirement_Calculator/retirement_calculator.exs
lucifer1004/EFP
3be9f22ef76957c0f3ebdc0dbb415cea1ede8da9
[ "MIT" ]
null
null
null
handle = &case &1 do :error -> IO.puts("Invalid input.") exit(:shutdown) {int, rest} -> if rest != "" do IO.puts("#{rest} has been truncated.") end if int < 0 do IO.puts("Negative values are not allowed.") exit(:shutdown) end int end input = &(IO.gets(&1) |> String.trim() |> Integer.parse() |> handle.()) current = input.("What is your current age? ") retire = input.("At what age would you like to retire? ") {:ok, now} = DateTime.now("Etc/UTC") if retire > current do IO.puts("It's #{now.year}, so you can retire in #{now.year + retire - current}.") else if retire == current do IO.puts("It's #{now.year}, the same year in which you can retire.") else IO.puts("It's #{now.year}, and you retired in #{now.year + retire - current}.") end end
21.45
83
0.565268
037d0a72ce14f4a52527d88c47b9d5bacb2cf26a
1,628
exs
Elixir
apps/omg_eth/test/omg_eth/release_tasks/set_ethereum_stalled_sync_threshold_test.exs
omisego/elixir-omg
2c68973d8f29033d137f63a6e060f12e2a7dcd59
[ "Apache-2.0" ]
177
2018-08-24T03:51:02.000Z
2020-05-30T13:29:25.000Z
apps/omg_eth/test/omg_eth/release_tasks/set_ethereum_stalled_sync_threshold_test.exs
omisego/elixir-omg
2c68973d8f29033d137f63a6e060f12e2a7dcd59
[ "Apache-2.0" ]
1,042
2018-08-25T00:52:39.000Z
2020-06-01T05:15:17.000Z
apps/omg_eth/test/omg_eth/release_tasks/set_ethereum_stalled_sync_threshold_test.exs
omisego/elixir-omg
2c68973d8f29033d137f63a6e060f12e2a7dcd59
[ "Apache-2.0" ]
47
2018-08-24T12:06:33.000Z
2020-04-28T11:49:25.000Z
# Copyright 2019-2020 OMG Network Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule OMG.Eth.ReleaseTasks.SetEthereumStalledSyncThresholdTest do use ExUnit.Case, async: true alias OMG.Eth.ReleaseTasks.SetEthereumStalledSyncThreshold @app :omg_eth @env_key "ETHEREUM_STALLED_SYNC_THRESHOLD_MS" @config_key :ethereum_stalled_sync_threshold_ms test "that interval is set when the env var is present" do :ok = System.put_env(@env_key, "9999") config = SetEthereumStalledSyncThreshold.load([], []) ethereum_stalled_sync_threshold_ms = config |> Keyword.fetch!(@app) |> Keyword.fetch!(@config_key) assert ethereum_stalled_sync_threshold_ms == 9999 :ok = System.delete_env(@env_key) end test "that the default config is used when the env var is not set" do old_config = Application.get_env(@app, @config_key) :ok = System.delete_env(@env_key) config = SetEthereumStalledSyncThreshold.load([], []) ethereum_stalled_sync_threshold_ms = config |> Keyword.fetch!(@app) |> Keyword.fetch!(@config_key) assert ethereum_stalled_sync_threshold_ms == old_config end end
41.74359
102
0.760442
037d128483bbc399a1ea6453ef5b496419e6ebab
2,741
ex
Elixir
lib/ecto/repo/supervisor.ex
tokafish/ecto
45d23da6faf660303484d0c993930af674685631
[ "Apache-2.0" ]
null
null
null
lib/ecto/repo/supervisor.ex
tokafish/ecto
45d23da6faf660303484d0c993930af674685631
[ "Apache-2.0" ]
null
null
null
lib/ecto/repo/supervisor.ex
tokafish/ecto
45d23da6faf660303484d0c993930af674685631
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.Repo.Supervisor do @moduledoc false use Supervisor @doc """ Starts the repo supervisor. """ def start_link(repo, otp_app, adapter, opts) do opts = config(repo, otp_app, opts) Supervisor.start_link(__MODULE__, {repo, otp_app, adapter, opts}, [name: repo]) end @doc """ Retrieves and normalizes the configuration for `repo` in `otp_app`. """ def config(repo, otp_app, custom) do if config = Application.get_env(otp_app, repo) do config = Keyword.merge(config, custom) {url, config} = Keyword.pop(config, :url) [otp_app: otp_app, repo: repo] ++ Keyword.merge(config, parse_url(url || "")) else raise ArgumentError, "configuration for #{inspect repo} not specified in #{inspect otp_app} environment" end end @doc """ Parses the OTP configuration for compile time. """ def parse_config(repo, opts) do otp_app = Keyword.fetch!(opts, :otp_app) config = Application.get_env(otp_app, repo, []) adapter = opts[:adapter] || config[:adapter] unless adapter do raise ArgumentError, "missing :adapter configuration in " <> "config #{inspect otp_app}, #{inspect repo}" end unless Code.ensure_loaded?(adapter) do raise ArgumentError, "adapter #{inspect adapter} was not compiled, " <> "ensure it is correct and it is included as a project dependency" end {otp_app, adapter, config} end @doc """ Parses an Ecto URL allowed in configuration. The format must be: "ecto://username:password@hostname:port/database" or {:system, "DATABASE_URL"} """ def parse_url(""), do: [] def parse_url({:system, env}) when is_binary(env) do parse_url(System.get_env(env) || "") end def parse_url(url) when is_binary(url) do info = url |> URI.decode() |> URI.parse() if is_nil(info.host) do raise Ecto.InvalidURLError, url: url, message: "host is not present" end if is_nil(info.path) or not (info.path =~ ~r"^/([^/])+$") do raise Ecto.InvalidURLError, url: url, message: "path should be a database name" end destructure [username, password], info.userinfo && String.split(info.userinfo, ":") "/" <> database = info.path opts = [username: username, password: password, database: database, hostname: info.host, port: info.port] Enum.reject(opts, fn {_k, v} -> is_nil(v) end) end ## Callbacks def init({repo, _otp_app, adapter, opts}) do children = [adapter.child_spec(repo, opts)] :ets.new(repo, [:set, :public, :named_table, read_concurrency: true]) supervise(children, strategy: :one_for_one) end end
28.257732
92
0.63371
037d2e0d9f3194b7409f5b07816b7b20e00f58cf
449
exs
Elixir
test/documents_design_web/views/error_view_test.exs
documents-org/documents.design-el
6976254e175232afe5e913c29b04c13a86d2e9a2
[ "MIT" ]
null
null
null
test/documents_design_web/views/error_view_test.exs
documents-org/documents.design-el
6976254e175232afe5e913c29b04c13a86d2e9a2
[ "MIT" ]
null
null
null
test/documents_design_web/views/error_view_test.exs
documents-org/documents.design-el
6976254e175232afe5e913c29b04c13a86d2e9a2
[ "MIT" ]
null
null
null
defmodule DocumentsDesignWeb.ErrorViewTest do use DocumentsDesignWeb.ConnCase, async: true # Bring render/3 and render_to_string/3 for testing custom views import Phoenix.View test "renders 404.html" do assert render_to_string(DocumentsDesignWeb.ErrorView, "404.html", []) == "Not Found" end test "renders 500.html" do assert render_to_string(DocumentsDesignWeb.ErrorView, "500.html", []) == "Internal Server Error" end end
29.933333
100
0.752784
037d46070c02f00140d78b5e03c6ae2d4af3f3d3
1,827
exs
Elixir
clients/calendar/mix.exs
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "Apache-2.0" ]
null
null
null
clients/calendar/mix.exs
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "Apache-2.0" ]
null
null
null
clients/calendar/mix.exs
ukrbublik/elixir-google-api
364cec36bc76f60bec94cbcad34844367a29d174
[ "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.Calendar.Mixfile do use Mix.Project @version "0.19.1" def project() do [ app: :google_api_calendar, version: @version, elixir: "~> 1.6", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/calendar" ] end def application() do [extra_applications: [:logger]] end defp deps() do [ {:google_gax, "~> 0.4"}, {:ex_doc, "~> 0.16", only: :dev} ] end defp description() do """ Calendar API client library. Manipulates events and other calendar data. """ end defp package() do [ files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jeff Ching", "Daniel Azuma"], licenses: ["Apache 2.0"], links: %{ "GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/calendar", "Homepage" => "https://developers.google.com/google-apps/calendar/firstapp" } ] end end
27.268657
99
0.655172
037d588250d11cb0e16a2762f98eb646e7ec1a72
86
exs
Elixir
test/iex_line_bot_web/views/page_view_test.exs
pastleo/iex_line_bot
73d02b45adc05bc7331fa5f88859861d04a2e71f
[ "MIT" ]
1
2019-06-24T23:55:26.000Z
2019-06-24T23:55:26.000Z
test/iex_line_bot_web/views/page_view_test.exs
pastleo/iex_line_bot
73d02b45adc05bc7331fa5f88859861d04a2e71f
[ "MIT" ]
null
null
null
test/iex_line_bot_web/views/page_view_test.exs
pastleo/iex_line_bot
73d02b45adc05bc7331fa5f88859861d04a2e71f
[ "MIT" ]
null
null
null
defmodule IexLineBotWeb.PageViewTest do use IexLineBotWeb.ConnCase, async: true end
21.5
41
0.837209
037d61c56a0de8d99f514598e96b2fb0884e0aa4
1,657
ex
Elixir
clients/content/lib/google_api/content/v2/model/liasettings_request_inventory_verification_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/liasettings_request_inventory_verification_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/liasettings_request_inventory_verification_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Content.V2.Model.LiasettingsRequestInventoryVerificationResponse do @moduledoc """ ## Attributes - kind (String.t): Identifies what kind of resource this is. Value: the fixed string \&quot;content#liasettingsRequestInventoryVerificationResponse\&quot;. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :kind => any() } field(:kind) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.LiasettingsRequestInventoryVerificationResponse do def decode(value, options) do GoogleApi.Content.V2.Model.LiasettingsRequestInventoryVerificationResponse.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.LiasettingsRequestInventoryVerificationResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
31.264151
178
0.756186
037d6fbc6ee4f07fa8ad2ace5aac57bb899c6f13
201
ex
Elixir
programming/elixir/hello-world-elixir-web-app-in-3-variants/variant-2-plug/lib/hello_world.ex
NomikOS/learning
268f94605214f6861ef476ca7573e68c068ccbe5
[ "Unlicense" ]
null
null
null
programming/elixir/hello-world-elixir-web-app-in-3-variants/variant-2-plug/lib/hello_world.ex
NomikOS/learning
268f94605214f6861ef476ca7573e68c068ccbe5
[ "Unlicense" ]
null
null
null
programming/elixir/hello-world-elixir-web-app-in-3-variants/variant-2-plug/lib/hello_world.ex
NomikOS/learning
268f94605214f6861ef476ca7573e68c068ccbe5
[ "Unlicense" ]
null
null
null
defmodule HelloWorld do use Application def start(_type, _args) do port = Application.get_env(:hello_world, :port) Plug.Adapters.Cowboy.http(HelloWorld.Router, [], [port: port]) end end
22.333333
66
0.716418
037d91d85073f1a99c8d78b0984bf0708f3b3dac
449
ex
Elixir
lib/membrane_fake_plugin/sink_buffers.ex
membraneframework/membrane_fake_plugin
5afab04f0f5f4691ab1ff4e2edf2b265796d3e25
[ "Apache-2.0" ]
1
2018-07-27T14:16:12.000Z
2018-07-27T14:16:12.000Z
lib/membrane_fake_plugin/sink_buffers.ex
membraneframework/membrane_fake_plugin
5afab04f0f5f4691ab1ff4e2edf2b265796d3e25
[ "Apache-2.0" ]
3
2018-10-15T08:04:11.000Z
2020-06-09T09:47:34.000Z
lib/membrane_fake_plugin/sink_buffers.ex
membraneframework/membrane_fake_plugin
5afab04f0f5f4691ab1ff4e2edf2b265796d3e25
[ "Apache-2.0" ]
null
null
null
defmodule Membrane.Fake.Sink.Buffers do @moduledoc """ Fake sink that ignores coming data. It makes demands in buffers. """ use Membrane.Sink def_input_pad :input, demand_unit: :buffers, caps: :any @impl true def handle_prepared_to_playing(_ctx, state) do {{:ok, demand: :input}, state} end @impl true def handle_write_list(:input, buffers, _ctx, state) do {{:ok, demand: {:input, length(buffers)}}, state} end end
22.45
66
0.690423
037dc3fda42b8ed011636ab49b88cbaee825edad
7,327
exs
Elixir
test/mix/tasks/nbx.gen.cache_test.exs
RudolfMan/nebulex
9cf2a1b66d538ba66e8d0fd195485a32772fdf04
[ "MIT" ]
null
null
null
test/mix/tasks/nbx.gen.cache_test.exs
RudolfMan/nebulex
9cf2a1b66d538ba66e8d0fd195485a32772fdf04
[ "MIT" ]
1
2021-08-02T18:06:24.000Z
2021-08-02T18:06:24.000Z
test/mix/tasks/nbx.gen.cache_test.exs
RudolfMan/nebulex
9cf2a1b66d538ba66e8d0fd195485a32772fdf04
[ "MIT" ]
null
null
null
defmodule Mix.Tasks.Nbx.Gen.CacheTest do use ExUnit.Case import Mix.Tasks.Nbx.Gen.Cache, only: [run: 1] describe "nbx.gen.cache" do test "generates a new cache" do in_tmp("new_cache", fn -> run(["-c", "Cache"]) assert_file("lib/cache.ex", """ defmodule Cache do use Nebulex.Cache, otp_app: :nebulex, adapter: Nebulex.Adapters.Local end """) first_line = if Code.ensure_loaded?(Config), do: "import Config", else: "use Mix.Config" assert_file("config/config.exs", """ #{first_line} config :nebulex, Cache, # When using :shards as backend # backend: :shards, # GC interval for pushing new generation: 12 hrs gc_interval: :timer.hours(12), # Max 1 million entries in cache max_size: 1_00_000, # Max 2 GB of memory allocated_memory: 2_000_000_000, # GC min timeout: 10 sec gc_cleanup_min_timeout: :timer.seconds(10), # GC min timeout: 10 min gc_cleanup_max_timeout: :timer.minutes(10) """) end) end test "generates a new cache with existing config file" do in_tmp("existing_config", fn -> File.mkdir_p!("config") File.write!("config/config.exs", """ # Hello use Mix.Config # World """) run(["-c", "Cache", "-a", "ABC"]) assert_file("config/config.exs", """ # Hello use Mix.Config # See the adapter's documentation for configuration options # config :nebulex, Cache, # key: :value # World """) end) end test "generates a new namespaced cache" do in_tmp("namespaced", fn -> run(["-c", "MyApp.Cache"]) assert_file("lib/my_app/cache.ex", "defmodule MyApp.Cache do") end) end test "raises exception because missing option -c" do msg = "nbx.gen.cache expects the cache to be given as -c MyApp.Cache" assert_raise Mix.Error, msg, fn -> run(["-a", "ABC"]) end end test "raises exception because multiple options -c" do msg = "nbx.gen.cache expects a single cache to be given" assert_raise Mix.Error, msg, fn -> run(["-c", "Cache1", "-c", "Cache2"]) end end test "raises exception because multiple options -a" do msg = "nbx.gen.cache expects a single adapter to be given" assert_raise Mix.Error, msg, fn -> run(["-c", "Cache", "-a", "A", "-a", "B"]) end end end describe "nbx.gen.cache with -a option" do test "generates a partitioned cache" do in_tmp("partitioned_cache", fn -> run(["-c", "PartitionedCache", "-a", "Nebulex.Adapters.Partitioned"]) assert_file("lib/partitioned_cache.ex", """ defmodule PartitionedCache do use Nebulex.Cache, otp_app: :nebulex, adapter: Nebulex.Adapters.Partitioned, primary_storage_adapter: Nebulex.Adapters.Local end """) first_line = if Code.ensure_loaded?(Config), do: "import Config", else: "use Mix.Config" assert_file("config/config.exs", """ #{first_line} config :nebulex, PartitionedCache, primary: [ # When using :shards as backend # backend: :shards, # GC interval for pushing new generation: 12 hrs gc_interval: :timer.hours(12), # Max 1 million entries in cache max_size: 1_00_000, # Max 2 GB of memory allocated_memory: 2_000_000_000, # GC min timeout: 10 sec gc_cleanup_min_timeout: :timer.seconds(10), # GC min timeout: 10 min gc_cleanup_max_timeout: :timer.minutes(10) ] """) end) end test "generates a replicated cache" do in_tmp("replicated_cache", fn -> run(["-c", "ReplicatedCache", "-a", "Nebulex.Adapters.Replicated"]) assert_file("lib/replicated_cache.ex", """ defmodule ReplicatedCache do use Nebulex.Cache, otp_app: :nebulex, adapter: Nebulex.Adapters.Replicated, primary_storage_adapter: Nebulex.Adapters.Local end """) first_line = if Code.ensure_loaded?(Config), do: "import Config", else: "use Mix.Config" assert_file("config/config.exs", """ #{first_line} config :nebulex, ReplicatedCache, primary: [ # When using :shards as backend # backend: :shards, # GC interval for pushing new generation: 12 hrs gc_interval: :timer.hours(12), # Max 1 million entries in cache max_size: 1_00_000, # Max 2 GB of memory allocated_memory: 2_000_000_000, # GC min timeout: 10 sec gc_cleanup_min_timeout: :timer.seconds(10), # GC min timeout: 10 min gc_cleanup_max_timeout: :timer.minutes(10) ] """) end) end test "generates a multilevel cache" do in_tmp("multilevel_cache", fn -> run(["-c", "MultilevelCache", "-a", "Nebulex.Adapters.Multilevel"]) assert_file("lib/multilevel_cache.ex", """ defmodule MultilevelCache do use Nebulex.Cache, otp_app: :nebulex, adapter: Nebulex.Adapters.Multilevel ## Cache Levels # Default auto-generated L1 cache (local) defmodule L1 do use Nebulex.Cache, otp_app: :nebulex, adapter: Nebulex.Adapters.Local end # Default auto-generated L2 cache (partitioned cache) defmodule L2 do use Nebulex.Cache, otp_app: :nebulex, adapter: Nebulex.Adapters.Partitioned end ## TODO: Add, remove or modify the auto-generated cache levels above end """) first_line = if Code.ensure_loaded?(Config), do: "import Config", else: "use Mix.Config" assert_file("config/config.exs", """ #{first_line} config :nebulex, MultilevelCache, model: :inclusive, levels: [ # Default auto-generated L1 cache (local) { MultilevelCache.L1, # GC interval for pushing new generation: 12 hrs gc_interval: :timer.hours(12), # Max 1 million entries in cache max_size: 1_00_000 }, # Default auto-generated L2 cache (partitioned cache) { MultilevelCache.L2, primary: [ # GC interval for pushing new generation: 12 hrs gc_interval: :timer.hours(12), # Max 1 million entries in cache max_size: 1_00_000 ] } ] """) end) end end ## Private Functions @tmp_path Path.expand("../../../tmp", __DIR__) defp in_tmp(path, fun) do path = Path.join(@tmp_path, path) File.rm_rf!(path) File.mkdir_p!(path) File.cd!(path, fun) end defp assert_file(file, match) do assert File.read!(file) =~ match end end
29.425703
96
0.554115
037e1634f5e710f740eae45c8669379e4f4acc25
69
ex
Elixir
web/views/page_view.ex
albertchan/phoenix_admin
74a9bbb01d7574db887b19a13f2934b7372f7d20
[ "MIT" ]
1
2018-03-07T17:21:58.000Z
2018-03-07T17:21:58.000Z
web/views/page_view.ex
albertchan/phoenix_admin
74a9bbb01d7574db887b19a13f2934b7372f7d20
[ "MIT" ]
null
null
null
web/views/page_view.ex
albertchan/phoenix_admin
74a9bbb01d7574db887b19a13f2934b7372f7d20
[ "MIT" ]
null
null
null
defmodule PhoenixAdmin.PageView do use PhoenixAdmin.Web, :view end
17.25
34
0.811594
037e1682ef75d95070beb32952217c64d2a2212a
3,017
ex
Elixir
lib/ex_aws/s3/upload.ex
kianmeng/ex_aws_s3
38ff1381c45118eb73230b55f95a4d2ade8f5c8b
[ "MIT", "Unlicense" ]
null
null
null
lib/ex_aws/s3/upload.ex
kianmeng/ex_aws_s3
38ff1381c45118eb73230b55f95a4d2ade8f5c8b
[ "MIT", "Unlicense" ]
null
null
null
lib/ex_aws/s3/upload.ex
kianmeng/ex_aws_s3
38ff1381c45118eb73230b55f95a4d2ade8f5c8b
[ "MIT", "Unlicense" ]
null
null
null
defmodule ExAws.S3.Upload do @moduledoc """ Represents an AWS S3 Multipart Upload operation. Implements `ExAws.Operation.perform/2` ## Examples ``` "path/to/big/file" |> S3.Upload.stream_file |> S3.upload("my-bucket", "path/on/s3") |> ExAws.request! #=> :done ``` See `ExAws.S3.upload/4` for options """ @enforce_keys ~w(bucket path src)a defstruct [ :src, :bucket, :path, :upload_id, opts: [], service: :s3, ] @type t :: %__MODULE__{ src: Enumerable.t, bucket: binary, path: binary, upload_id: binary, opts: Keyword.t, service: :s3 } def complete([], op, config) do # We must upload at least one "part", otherwise the # CompleteMultipartUpload request will fail. So if there were no # parts (because we're uploading an empty file), upload an empty part. part = upload_chunk!({"", 1}, op, config) complete([part], op, config) end def complete(parts, op, config) do ExAws.S3.complete_multipart_upload(op.bucket, op.path, op.upload_id, Enum.sort_by(parts, &elem(&1, 0))) |> ExAws.request(config) end def initialize(op, config) do init_op = ExAws.S3.initiate_multipart_upload(op.bucket, op.path, op.opts) with {:ok, %{body: %{upload_id: upload_id}}} <- ExAws.request(init_op, config) do {:ok, %{op | upload_id: upload_id}} end end @doc """ Open a file stream for use in an upload. Chunk size must be at least 5 MiB. Defaults to 5 MiB """ @spec stream_file(path :: binary) :: File.Stream.t @spec stream_file(path :: binary, opts :: [chunk_size: pos_integer]) :: File.Stream.t def stream_file(path, opts \\ []) do File.stream!(path, [], opts[:chunk_size] || 5 * 1024 * 1024) end @doc """ Upload a chunk for an operation. The first argument is a tuple with the binary contents of the chunk, and a positive integer index indicating which chunk it is. It will return this index along with the `etag` response from AWS necessary to complete the multipart upload. """ @spec upload_chunk!({binary, pos_integer}, t, ExAws.Config.t) :: {pos_integer, binary} def upload_chunk!({chunk, i}, op, config) do %{headers: headers} = ExAws.S3.upload_part(op.bucket, op.path, op.upload_id, i, chunk, op.opts) |> ExAws.request!(config) {_, etag} = Enum.find(headers, fn {k, _v} -> String.downcase(k) == "etag" end) {i, etag} end end defimpl ExAws.Operation, for: ExAws.S3.Upload do alias ExAws.S3.Upload def perform(op, config) do with {:ok, op} <- Upload.initialize(op, config) do op.src |> Stream.with_index(1) |> Task.async_stream(Upload, :upload_chunk!, [Map.delete(op, :src), config], max_concurrency: Keyword.get(op.opts, :max_concurrency, 4), timeout: Keyword.get(op.opts, :timeout, 30_000) ) |> Enum.to_list |> Enum.map(fn {:ok, val} -> val end) |> Upload.complete(op, config) end end def stream!(_, _), do: raise "not implemented" end
27.935185
107
0.641034
037ec4b1a92e379fb0d0035a383cd012e819fb48
2,874
ex
Elixir
clients/big_query/lib/google_api/big_query/v2/model/arima_model_info.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/big_query/lib/google_api/big_query/v2/model/arima_model_info.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/big_query/lib/google_api/big_query/v2/model/arima_model_info.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.BigQuery.V2.Model.ArimaModelInfo do @moduledoc """ Arima model information. ## Attributes * `arimaCoefficients` (*type:* `GoogleApi.BigQuery.V2.Model.ArimaCoefficients.t`, *default:* `nil`) - Arima coefficients. * `arimaFittingMetrics` (*type:* `GoogleApi.BigQuery.V2.Model.ArimaFittingMetrics.t`, *default:* `nil`) - Arima fitting metrics. * `hasDrift` (*type:* `boolean()`, *default:* `nil`) - Whether Arima model fitted with drift or not. It is always false when d is not 1. * `nonSeasonalOrder` (*type:* `GoogleApi.BigQuery.V2.Model.ArimaOrder.t`, *default:* `nil`) - Non-seasonal order. * `seasonalPeriods` (*type:* `list(String.t)`, *default:* `nil`) - Seasonal periods. Repeated because multiple periods are supported for one time series. * `timeSeriesId` (*type:* `String.t`, *default:* `nil`) - The time_series_id value for this time series. It will be one of the unique values from the time_series_id_column specified during ARIMA model training. Only present when time_series_id_column training option was used. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :arimaCoefficients => GoogleApi.BigQuery.V2.Model.ArimaCoefficients.t(), :arimaFittingMetrics => GoogleApi.BigQuery.V2.Model.ArimaFittingMetrics.t(), :hasDrift => boolean(), :nonSeasonalOrder => GoogleApi.BigQuery.V2.Model.ArimaOrder.t(), :seasonalPeriods => list(String.t()), :timeSeriesId => String.t() } field(:arimaCoefficients, as: GoogleApi.BigQuery.V2.Model.ArimaCoefficients) field(:arimaFittingMetrics, as: GoogleApi.BigQuery.V2.Model.ArimaFittingMetrics) field(:hasDrift) field(:nonSeasonalOrder, as: GoogleApi.BigQuery.V2.Model.ArimaOrder) field(:seasonalPeriods, type: :list) field(:timeSeriesId) end defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.ArimaModelInfo do def decode(value, options) do GoogleApi.BigQuery.V2.Model.ArimaModelInfo.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.ArimaModelInfo do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
46.354839
280
0.731733
037edda6eb6e21b2a506d45cf8d234b816f1a26b
98
exs
Elixir
test/ueberauth_example_web/views/page_view_test.exs
rerb/ueberauth_example
1a08d578dfeaca5b77d213b1abbc53913f2a3b37
[ "MIT" ]
210
2015-11-19T01:54:04.000Z
2021-11-14T18:14:57.000Z
test/ueberauth_example_web/views/page_view_test.exs
rerb/ueberauth_example
1a08d578dfeaca5b77d213b1abbc53913f2a3b37
[ "MIT" ]
63
2015-11-19T00:08:29.000Z
2021-09-07T03:04:36.000Z
test/ueberauth_example_web/views/page_view_test.exs
rerb/ueberauth_example
1a08d578dfeaca5b77d213b1abbc53913f2a3b37
[ "MIT" ]
102
2015-11-20T11:47:12.000Z
2022-03-23T11:10:38.000Z
defmodule UeberauthExampleWeb.PageViewTest do use UeberauthExampleWeb.ConnCase, async: true end
24.5
47
0.857143
037ee73e6bbb133c06dc682806e35fe26bdd8ecf
1,682
ex
Elixir
clients/logging/lib/google_api/logging/v2/model/label_descriptor.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/logging/lib/google_api/logging/v2/model/label_descriptor.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/logging/lib/google_api/logging/v2/model/label_descriptor.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.Logging.V2.Model.LabelDescriptor do @moduledoc """ A description of a label. ## Attributes * `description` (*type:* `String.t`, *default:* `nil`) - A human-readable description for the label. * `key` (*type:* `String.t`, *default:* `nil`) - The label key. * `valueType` (*type:* `String.t`, *default:* `nil`) - The type of data that can be assigned to the label. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :description => String.t(), :key => String.t(), :valueType => String.t() } field(:description) field(:key) field(:valueType) end defimpl Poison.Decoder, for: GoogleApi.Logging.V2.Model.LabelDescriptor do def decode(value, options) do GoogleApi.Logging.V2.Model.LabelDescriptor.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Logging.V2.Model.LabelDescriptor do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
31.735849
110
0.704518
037ee924afbebe4dcf62318aa43d600de5196a72
2,224
exs
Elixir
examples/demo/mix.exs
fhunleth/nerves_initramfs
3f24e4a98cd1b37a69e86eea39a9b05f839d43da
[ "Apache-2.0" ]
4
2020-01-16T10:17:53.000Z
2021-11-14T22:06:53.000Z
examples/demo/mix.exs
fhunleth/nerves_initramfs
3f24e4a98cd1b37a69e86eea39a9b05f839d43da
[ "Apache-2.0" ]
8
2019-11-26T14:42:59.000Z
2020-01-08T20:17:57.000Z
examples/demo/mix.exs
fhunleth/nerves_initramfs
3f24e4a98cd1b37a69e86eea39a9b05f839d43da
[ "Apache-2.0" ]
2
2019-11-22T17:24:07.000Z
2019-11-25T19:38:40.000Z
defmodule Demo.MixProject do use Mix.Project @app :demo @version "0.1.0" @all_targets [:rpi, :rpi0, :rpi2, :rpi3, :rpi3a, :rpi4, :bbb, :x86_64] def project do [ app: @app, version: @version, elixir: "~> 1.9", archives: [nerves_bootstrap: "~> 1.6"], start_permanent: Mix.env() == :prod, build_embedded: true, aliases: [loadconfig: [&bootstrap/1]], deps: deps(), releases: [{@app, release()}], preferred_cli_target: [run: :host, test: :host] ] end # Starting nerves_bootstrap adds the required aliases to Mix.Project.config() # Aliases are only added if MIX_TARGET is set. def bootstrap(args) do Application.start(:nerves_bootstrap) Mix.Task.run("loadconfig", args) end # Run "mix help compile.app" to learn about applications. def application do [ mod: {Demo.Application, []}, extra_applications: [:logger, :runtime_tools] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ # Dependencies for all targets {:nerves, "~> 1.7.0", runtime: false}, {:shoehorn, "~> 0.6"}, {:ring_logger, "~> 0.6"}, {:toolshed, "~> 0.2"}, # Dependencies for all targets except :host {:nerves_runtime, "~> 0.6", targets: @all_targets}, {:nerves_pack, "~> 0.2", targets: @all_targets}, # Dependencies for specific targets {:nerves_system_rpi, "~> 1.10", runtime: false, targets: :rpi}, {:nerves_system_rpi0, "~> 1.10", runtime: false, targets: :rpi0}, {:nerves_system_rpi2, "~> 1.10", runtime: false, targets: :rpi2}, {:nerves_system_rpi3, "~> 1.10", runtime: false, targets: :rpi3}, {:nerves_system_rpi3a, "~> 1.10", runtime: false, targets: :rpi3a}, {:nerves_system_rpi4, "~> 1.10", runtime: false, targets: :rpi4}, {:nerves_system_bbb, "~> 2.5", runtime: false, targets: :bbb}, {:nerves_system_x86_64, "~> 1.10", runtime: false, targets: :x86_64}, ] end def release do [ overwrite: true, cookie: "#{@app}_cookie", include_erts: &Nerves.Release.erts/0, steps: [&Nerves.Release.init/1, :assemble], strip_beams: Mix.env() == :prod ] end end
30.465753
79
0.600719
037f0547eb813be09845b9d81b59e817d2fe02c7
33,824
ex
Elixir
lib/surface/compiler/eex_engine.ex
kianmeng/surface
9fe00d3d1c5411f9763f0add96dc84cb8375e54c
[ "MIT" ]
null
null
null
lib/surface/compiler/eex_engine.ex
kianmeng/surface
9fe00d3d1c5411f9763f0add96dc84cb8375e54c
[ "MIT" ]
null
null
null
lib/surface/compiler/eex_engine.ex
kianmeng/surface
9fe00d3d1c5411f9763f0add96dc84cb8375e54c
[ "MIT" ]
null
null
null
defmodule Surface.Compiler.EExEngine do @moduledoc """ This module glues together surface's AST and Phoenix.LiveView.Engine to actually render an AST. It takes a list of Surface AST nodes, and processes them into a sequence of static raw html items and dynamic pieces. It then converts these into tokens which an EEx engine can understand (see EEx.Tokenizer for information on this). Finally, it passes these tokens into the engine sequentially in the same manner as EEx.Compiler.compile/2 """ alias Surface.AST alias Surface.IOHelper alias Surface.Components.Context # while this should technically work with other engines, the main use case is integration with Phoenix.LiveView.Engine @default_engine Phoenix.LiveView.Engine @string_types [:string, :css_class] @spec translate( [Surface.AST.t()], nil | maybe_improper_list | map ) :: any def translate(nodes, opts \\ []) do state = %{ engine: opts[:engine] || @default_engine, depth: 0, context_vars: %{count: 0, changed: []}, scope: [] } nodes |> to_token_sequence() |> generate_buffer(state.engine.init(opts), state) |> maybe_print_expression( opts[:debug], opts[:file] || "nofile", opts[:line] || 1 ) end defp to_token_sequence(nodes) do nodes |> to_dynamic_nested_html() |> List.flatten() |> combine_static_portions() end defp generate_buffer([], buffer, state) do state.engine.handle_body(buffer, root: true) end defp generate_buffer([{:text, chars} | tail], buffer, state) do buffer = state.engine.handle_text(buffer, chars) generate_buffer(tail, buffer, state) end defp generate_buffer([%AST.Expr{} = expr | tail], buffer, state) do buffer = state.engine.handle_expr(buffer, "", to_expression(expr, buffer, state)) generate_buffer(tail, buffer, state) end defp generate_buffer([expr | tail], buffer, state) do buffer = state.engine.handle_expr(buffer, "=", to_expression(expr, buffer, state)) generate_buffer(tail, buffer, state) end defp to_expression(nodes, buffer, state) defp to_expression([node], buffer, state), do: to_expression(node, buffer, state) defp to_expression(nodes, buffer, state) when is_list(nodes) do children = for node <- nodes do to_expression(node, buffer, state) end {:__block__, [], children} end defp to_expression({:safe, value}, _buffer, _state), do: {:safe, value} defp to_expression({:text, value}, _buffer, _state), do: {:safe, value} defp to_expression(%AST.AttributeExpr{value: expr}, _buffer, _state), do: expr defp to_expression(%AST.Interpolation{value: expr}, _buffer, _state), do: expr defp to_expression(%AST.Expr{value: expr}, _buffer, _state) when is_list(expr), do: {:__block__, [], expr} defp to_expression(%AST.Expr{value: expr}, _buffer, _state), do: {:__block__, [], [expr]} defp to_expression( %AST.For{generator: %AST.AttributeExpr{value: generator}, children: children} = comprehension, buffer, state ) do buffer = handle_nested_block(children, buffer, %{ state | depth: state.depth + 1, scope: [:for | state.scope] }) generator_expr = generator ++ [[do: buffer]] {:for, [generated: true], generator_expr} |> maybe_print_expression(comprehension) end defp to_expression( %AST.If{ condition: %AST.AttributeExpr{value: condition}, children: if_children, else: else_children } = conditional, buffer, state ) do if_buffer = handle_nested_block(if_children, buffer, %{ state | depth: state.depth + 1, scope: [:if | state.scope] }) else_buffer = handle_nested_block(else_children, buffer, %{ state | depth: state.depth + 1, scope: [:if | state.scope] }) {:if, [generated: true], [condition, [do: if_buffer, else: else_buffer]]} |> maybe_print_expression(conditional) end defp to_expression(%AST.Block{name: "case"} = block, buffer, state) do %AST.Block{expression: case_expr, sub_blocks: sub_blocks} = block state = %{state | depth: state.depth + 1, scope: [:case | state.scope]} match_blocks = Enum.flat_map(sub_blocks, fn %AST.SubBlock{children: children, expression: expr} -> match_body = handle_nested_block(children, buffer, state) quote do unquote(expr) -> unquote(match_body) end end) quote do case unquote(case_expr) do unquote(match_blocks) end end |> maybe_print_expression(block) end defp to_expression( %AST.Slot{ name: provided_name, as: slot_as, index: index_ast, for: slot_for_ast, args: args_expr, default: default, meta: meta }, buffer, state ) do slot_index = case index_ast do %AST.AttributeExpr{value: expr} -> expr %AST.Literal{value: value} -> value end slot_for = case slot_for_ast do %AST.AttributeExpr{value: expr} -> expr %AST.Literal{value: value} -> value _ -> nil end parent_context_var = context_name(state.context_vars.count - 1, meta.caller) context_expr = if is_child_component?(state) do quote generated: true do unquote(parent_context_var) end else quote do %{} end end slot_value = if slot_for do quote do unquote(slot_for) end else slot_name = slot_as || provided_name slot_assign = {:@, [], [{slot_name, [], nil}]} quote do Enum.at(List.wrap(unquote(slot_assign)), unquote(slot_index)) end end # TODO: map names somehow? slot_content_expr = quote generated: true do Phoenix.LiveView.Helpers.render_slot( unquote(slot_value), { Map.new(unquote(args_expr)), unquote(context_expr) } ) end fallback_value = handle_nested_block(default, buffer, %{ state | depth: state.depth + 1, scope: [:slot | state.scope] }) quote generated: true do if unquote(slot_value) do unquote(slot_content_expr) else unquote(fallback_value) end end end # Dynamic component defp to_expression(%AST.FunctionComponent{type: :dynamic} = component, buffer, state) do %AST.FunctionComponent{ module: %AST.AttributeExpr{value: module_expr}, fun: fun, props: props, meta: meta } = component fun_expr = case fun do nil -> :render %AST.AttributeExpr{value: expr} -> expr end {props_expr, dynamic_props_expr} = build_props_expressions(nil, component) {context_expr, context_var, state} = process_context(nil, nil, props, meta.caller, state) slot_props = build_slot_props(component, buffer, state, context_var) slot_props_map = {:%{}, [generated: true], slot_props} ctx = Surface.AST.Meta.quoted_caller_context(meta) quote generated: true do Phoenix.LiveView.Helpers.component( &apply(unquote(module_expr), unquote(fun_expr), [&1]), Map.merge( Surface.build_dynamic_assigns( unquote(context_expr), unquote(props_expr), unquote(dynamic_props_expr), unquote(module_expr), unquote(meta.node_alias), unquote(ctx) ), unquote(slot_props_map) ) ) end |> maybe_print_expression(component) end # Local function component defp to_expression(%AST.FunctionComponent{type: :local} = component, buffer, state) do %AST.FunctionComponent{module: module, fun: fun, props: props, meta: meta} = component {props_expr, dynamic_props_expr} = build_props_expressions(nil, component) {context_expr, context_var, state} = process_context(module, fun, props, meta.caller, state) slot_props = build_slot_props(component, buffer, state, context_var) slot_props_map = {:%{}, [generated: true], slot_props} ctx = Surface.AST.Meta.quoted_caller_context(meta) quote generated: true do Phoenix.LiveView.Helpers.component( &(unquote(Macro.var(fun, __MODULE__)) / 1), Map.merge( Surface.build_assigns( unquote(context_expr), unquote(props_expr), unquote(dynamic_props_expr), nil, unquote(meta.node_alias), unquote(ctx) ), unquote(slot_props_map) ) ) end |> maybe_print_expression(component) end # Remote function component defp to_expression(%AST.FunctionComponent{type: :remote} = component, buffer, state) do %AST.FunctionComponent{module: module, fun: fun, props: props, meta: meta} = component {props_expr, dynamic_props_expr} = build_props_expressions(nil, component) {context_expr, context_var, state} = process_context(module, fun, props, meta.caller, state) slot_props = build_slot_props(component, buffer, state, context_var) slot_props_map = {:%{}, [generated: true], slot_props} ctx = Surface.AST.Meta.quoted_caller_context(meta) # For now, we can only retrieve props and slots informaton from module components, # not function components, so if we're dealing with dynamic or recursive module components, # we pass the module, otherwise, we pass `nil`. module_for_build_assigns = if fun == :render, do: module quote generated: true do Phoenix.LiveView.Helpers.component( &(unquote(module).unquote(fun) / 1), Map.merge( Surface.build_assigns( unquote(context_expr), unquote(props_expr), unquote(dynamic_props_expr), unquote(module_for_build_assigns), unquote(meta.node_alias), unquote(ctx) ), unquote(slot_props_map) ) ) end |> maybe_print_expression(component) end # Module stateless component defp to_expression(%AST.Component{type: Surface.Component} = component, buffer, state) do %AST.Component{module: module, props: props, meta: meta} = component {props_expr, dynamic_props_expr} = build_props_expressions(module, component) {context_expr, context_var, state} = process_context(module, :render, props, meta.caller, state) slot_props = build_slot_props(component, buffer, state, context_var) slot_props_map = {:%{}, [generated: true], slot_props} ctx = Surface.AST.Meta.quoted_caller_context(meta) quote generated: true do Phoenix.LiveView.Helpers.component( &unquote(module).render/1, Map.merge( Surface.build_assigns( unquote(context_expr), unquote(props_expr), unquote(dynamic_props_expr), unquote(module), unquote(meta.node_alias), unquote(ctx) ), unquote(slot_props_map) ) ) end |> maybe_print_expression(component) end # Slotable component defp to_expression(%AST.SlotableComponent{} = component, buffer, state) do %AST.SlotableComponent{module: module, props: props, meta: meta} = component {props_expr, dynamic_props_expr} = build_props_expressions(module, component) {context_expr, context_var, state} = process_context(module, :render, props, meta.caller, state) slot_props = build_slot_props(component, buffer, state, context_var) slot_props_map = {:%{}, [generated: true], slot_props} ctx = Surface.AST.Meta.quoted_caller_context(meta) quote generated: true do Phoenix.LiveView.Helpers.component( &unquote(module).render/1, Map.merge( Surface.build_assigns( unquote(context_expr), unquote(props_expr), unquote(dynamic_props_expr), unquote(module), unquote(meta.node_alias), unquote(ctx) ), unquote(slot_props_map) ) ) end |> maybe_print_expression(component) end # Live component defp to_expression(%AST.Component{type: Surface.LiveComponent} = component, buffer, state) do %AST.Component{module: module, props: props, meta: meta} = component {props_expr, dynamic_props_expr} = build_props_expressions(module, component) {context_expr, context_var, state} = process_context(module, :render, props, meta.caller, state) slot_props = build_slot_props(component, buffer, state, context_var) slot_props_map = {:%{}, [generated: true], [{:module, module} | slot_props]} ctx = Surface.AST.Meta.quoted_caller_context(meta) quote generated: true do Phoenix.LiveView.Helpers.component( &Phoenix.LiveView.Helpers.live_component/1, Map.merge( Surface.build_assigns( unquote(context_expr), unquote(props_expr), unquote(dynamic_props_expr), unquote(module), unquote(meta.node_alias), unquote(ctx) ), unquote(slot_props_map) ) ) end |> maybe_print_expression(component) end # Dynamic live component defp to_expression(%AST.Component{type: :dynamic_live} = component, buffer, state) do %AST.Component{ module: %AST.AttributeExpr{value: module_expr}, props: props, meta: meta } = component {props_expr, dynamic_props_expr} = build_props_expressions(nil, component) {context_expr, context_var, state} = process_context(nil, :render, props, meta.caller, state) slot_props = build_slot_props(component, buffer, state, context_var) slot_props_map = {:%{}, [generated: true], [{:module, module_expr} | slot_props]} ctx = Surface.AST.Meta.quoted_caller_context(meta) quote generated: true do Phoenix.LiveView.Helpers.component( &Phoenix.LiveView.Helpers.live_component/1, Map.merge( Surface.build_dynamic_assigns( unquote(context_expr), unquote(props_expr), unquote(dynamic_props_expr), unquote(module_expr), unquote(meta.node_alias), unquote(ctx) ), unquote(slot_props_map) ) ) end |> maybe_print_expression(component) end # LiveView defp to_expression(%AST.Component{type: Surface.LiveView} = component, _buffer, _state) do %AST.Component{module: module, props: props} = component props_expr = collect_component_props(module, props) |> Enum.reject(fn {_, value} -> is_nil(value) end) quote generated: true do live_render(@socket, unquote(module), unquote(props_expr)) end |> maybe_print_expression(component) end defp handle_dynamic_props(nil), do: [] defp handle_dynamic_props(%AST.DynamicAttribute{expr: %AST.AttributeExpr{value: expr}}) do expr end defp collect_component_props(module, attrs) do {props, props_acc} = Enum.reduce(attrs, {[], %{}}, fn attr, {props, props_acc} -> %AST.Attribute{name: prop_name, type: type, type_opts: type_opts, value: expr} = attr cond do module && !module.__validate_prop__(prop_name) -> {props, props_acc} type_opts[:accumulate] -> current_value = props_acc[prop_name] || [] updated_value = [to_prop_expr(expr, type) | current_value] {props, Map.put(props_acc, prop_name, updated_value)} true -> {[{prop_name, to_prop_expr(expr, type)} | props], props_acc} end end) Enum.reverse(props) ++ Enum.map(props_acc, fn {k, v} -> {k, Enum.reverse(v)} end) end # Function component defp build_slot_props(%AST.FunctionComponent{fun: fun} = component, buffer, state, _context_var) when fun != nil do slot_info = component.templates |> Enum.map(fn {name, templates_for_slot} -> state = %{state | scope: [:template | state.scope]} nested_templates = handle_templates(component, templates_for_slot, buffer, state) {name, nested_templates} end) case slot_info do [{:default, [{let, _, body}]}] -> block = if let == [] do quote generated: true do _ -> unquote(body) end else quote generated: true do unquote(let) -> unquote(body) end end ast = quote do Phoenix.LiveView.Helpers.inner_block(:inner_block, do: unquote(block)) end props = [__slot__: :inner_block, inner_block: ast] [inner_block: {:%{}, [generated: true], props}] _ -> [] end end defp build_slot_props(component, buffer, state, context_var) do component_slots = if component.type in [Surface.Component, Surface.LiveComponent] && function_exported?(component.module, :__slots__, 0), do: component.module.__slots__(), else: [] slot_info = component.templates |> Enum.map(fn {name, templates_for_slot} -> state = %{state | scope: [:template | state.scope]} nested_templates = handle_templates(component, templates_for_slot, buffer, state) slot_name = Enum.find_value(component_slots, name, fn slot -> if slot.name == name do slot.opts[:as] || slot.name end end) {slot_name, nested_templates} end) for {name, infos} <- slot_info, not Enum.empty?(infos) do entries = Enum.map(infos, fn {let, props, body} -> block = quote generated: true do { unquote({:%{}, [generated: true], let}), unquote(context_var) } -> unquote(body) end ast = quote do Phoenix.LiveView.Helpers.inner_block(unquote(name), do: unquote(block)) end props = [__slot__: name, inner_block: ast] ++ props {:%{}, [generated: true], props} end) {name, entries} end end defp handle_nested_block(block, buffer, state) when is_list(block) do buffer = state.engine.handle_begin(buffer) buffer = Enum.reduce(block, buffer, fn {:text, chars}, buffer -> state.engine.handle_text(buffer, chars) %AST.Expr{} = expr, buffer -> state.engine.handle_expr(buffer, "", to_expression(expr, buffer, state)) expr, buffer -> state.engine.handle_expr(buffer, "=", to_expression(expr, buffer, state)) end) state.engine.handle_end(buffer) end defp handle_nested_block(block, buffer, state) do buffer = state.engine.handle_begin(buffer) buffer = state.engine.handle_expr(buffer, "=", to_expression(block, buffer, state)) state.engine.handle_end(buffer) end defp handle_templates(_component, [], _, _), do: [] defp handle_templates( component, [ %AST.Template{ name: name, props: props, let: let, children: children } | tail ], buffer, state ) do nested_block_state = %{ state | depth: state.depth + 1, context_vars: %{state.context_vars | count: state.context_vars.count + 1} } props = collect_component_props(nil, props) [ {add_default_bindings(component, name, let), props, handle_nested_block(children, buffer, nested_block_state)} | handle_templates(component, tail, buffer, state) ] end defp handle_templates(component, [slotable | tail], buffer, state) do %AST.SlotableComponent{ slot: name, module: module, let: let, props: props, templates: %{default: default} } = slotable template = cond do !module.__renderless__?() -> [ %AST.Component{ module: module, type: slotable.type, props: props, dynamic_props: nil, directives: [], templates: slotable.templates, meta: slotable.meta, debug: slotable.debug } ] Enum.empty?(default) -> [] true -> %AST.Template{children: children} = List.first(default) children end props = collect_component_props(module, props) default_props = Surface.default_props(module) nested_block_state = %{ state | depth: state.depth + 1, context_vars: %{state.context_vars | count: state.context_vars.count + 1} } [ {add_default_bindings(component, name, let), Keyword.merge(default_props, props), handle_nested_block(template, buffer, nested_block_state)} | handle_templates(component, tail, buffer, state) ] end defp add_default_bindings(%AST.FunctionComponent{}, _name, let) do let end defp add_default_bindings(%{module: %Surface.AST.AttributeExpr{}}, _name, let) do let end defp add_default_bindings(%{module: module, props: props}, name, let) do (module.__get_slot__(name)[:opts][:args] || []) |> Enum.reject(fn %{generator: nil} -> true %{name: name} -> Keyword.has_key?(let, name) end) |> Enum.map(fn %{generator: gen, name: name} -> case find_attribute_value(props, gen, nil) do %AST.AttributeExpr{value: {binding, _}} -> {name, binding} _ -> nil end end) |> Enum.reject(fn value -> value == nil end) |> Keyword.merge(let) end defp find_attribute_value(attrs, name, default) defp find_attribute_value([], _, default), do: default defp find_attribute_value([%AST.Attribute{name: attr_name, value: value} | _], name, _) when attr_name == name, do: value defp find_attribute_value([_ | tail], name, default), do: find_attribute_value(tail, name, default) defp to_prop_expr(%AST.AttributeExpr{value: value, meta: meta}, type) do Surface.TypeHandler.update_prop_expr(type, value, meta) end defp to_prop_expr(%AST.Literal{value: value}, _) do value end defp combine_static_portions(nodes, accumulators \\ {[], []}) defp combine_static_portions([], {[], node_acc}), do: Enum.reverse(node_acc) defp combine_static_portions([], {static_acc, node_acc}), do: combine_static_portions( [], {[], [{:text, join_string_list(static_acc)} | node_acc]} ) defp combine_static_portions([str | values], {static_acc, node_acc}) when is_binary(str), do: combine_static_portions(values, {[str | static_acc], node_acc}) defp combine_static_portions([node | values], {static_acc, node_acc}) do node_acc = case static_acc do [] -> node_acc list -> [{:text, join_string_list(list)} | node_acc] end combine_static_portions(values, {[], [node | node_acc]}) end defp join_string_list(list) do list |> Enum.reverse() |> IO.iodata_to_binary() end defp to_dynamic_nested_html([]), do: [] defp to_dynamic_nested_html([%AST.Literal{value: text} | nodes]) do [text | to_dynamic_nested_html(nodes)] end defp to_dynamic_nested_html([ %AST.Container{ children: children, meta: %AST.Meta{ module: mod, line: line } = meta } | nodes ]) when not is_nil(mod) do put_injected_component(meta.caller.module, mod, line) [to_dynamic_nested_html(children) | to_dynamic_nested_html(nodes)] end defp to_dynamic_nested_html([%AST.Container{children: children} | nodes]) do [to_dynamic_nested_html(children) | to_dynamic_nested_html(nodes)] end defp to_dynamic_nested_html([%AST.Slot{default: default} = slot | nodes]) do [%{slot | default: to_token_sequence(default)} | to_dynamic_nested_html(nodes)] end defp to_dynamic_nested_html([ %AST.If{children: if_children, else: else_children} = conditional | nodes ]) do [ %{ conditional | children: to_token_sequence(if_children), else: to_token_sequence(else_children) }, to_dynamic_nested_html(nodes) ] end defp to_dynamic_nested_html([%AST.For{children: children} = comprehension | nodes]) do [%{comprehension | children: to_token_sequence(children)}, to_dynamic_nested_html(nodes)] end defp to_dynamic_nested_html([%AST.Block{sub_blocks: sub_blocks} = block | nodes]) do [%{block | sub_blocks: to_token_sequence(sub_blocks)} | to_dynamic_nested_html(nodes)] end defp to_dynamic_nested_html([%AST.SubBlock{children: children} = sub_block | nodes]) do [%{sub_block | children: to_token_sequence(children)} | to_dynamic_nested_html(nodes)] end defp to_dynamic_nested_html([%AST.VoidTag{element: element, attributes: attributes} | nodes]) do [ "<", element, to_html_attributes(attributes), ">", to_dynamic_nested_html(nodes) ] end defp to_dynamic_nested_html([%AST.Tag{element: element, attributes: attributes, children: children} | nodes]) do [ "<", element, to_html_attributes(attributes), ">", to_dynamic_nested_html(children), "</", element, ">", to_dynamic_nested_html(nodes) ] end defp to_dynamic_nested_html([%type{module: mod, templates: templates_by_name} = component | nodes]) when type in [AST.Component, AST.FunctionComponent, AST.SlotableComponent] do {requires, templates_by_name} = Enum.reduce(templates_by_name, {[], %{}}, fn {name, templates}, {requires_acc, by_name} -> {requires, templates} = Enum.reduce(templates, {requires_acc, []}, fn %AST.Template{children: children} = template, {requires, templates} -> {requires, [%{template | children: to_token_sequence(children)} | templates]} %AST.SlotableComponent{} = template, {requires, templates} -> [nested, translated] = to_dynamic_nested_html([template]) {[nested | requires], [translated | templates]} end) {requires, Map.put(by_name, name, Enum.reverse(templates))} end) put_injected_component(component.meta.caller.module, mod, component.meta.line) [requires, %{component | templates: templates_by_name} | to_dynamic_nested_html(nodes)] end defp to_dynamic_nested_html([%AST.Error{message: message, meta: %AST.Meta{module: module} = meta} | nodes]) when not is_nil(module) do put_injected_component(meta.caller.module, module, meta.line) [ ~S(<span style="color: red; border: 2px solid red; padding: 3px"> Error: ), escape_message(message), ~S(</span>) | to_dynamic_nested_html(nodes) ] end defp to_dynamic_nested_html([%AST.Error{message: message} | nodes]), do: [ ~S(<span style="color: red; border: 2px solid red; padding: 3px"> Error: ), escape_message(message), ~S(</span>) | to_dynamic_nested_html(nodes) ] defp to_dynamic_nested_html([%AST.Interpolation{} = value | nodes]), do: [value | to_dynamic_nested_html(nodes)] defp to_dynamic_nested_html([%AST.Expr{} = value | nodes]), do: [value | to_dynamic_nested_html(nodes)] defp to_html_attributes([]), do: [] defp to_html_attributes([ %AST.Attribute{name: name, type: type, value: %AST.Literal{value: value}} | attributes ]) when type in @string_types and is_binary(value) do [[" ", to_string(name), "=", ~S("), value, ~S(")], to_html_attributes(attributes)] end defp to_html_attributes([ %AST.Attribute{name: name, type: type, value: %AST.Literal{value: value}} | attributes ]) do runtime_value = Surface.TypeHandler.expr_to_value!(type, name, [value], [], nil, value, _ctx = %{}) [Surface.TypeHandler.attr_to_html!(type, to_string(name), runtime_value), to_html_attributes(attributes)] end defp to_html_attributes([ %AST.DynamicAttribute{ expr: %AST.AttributeExpr{constant?: true} = expr } | attributes ]) do try do {expr_value, _} = Code.eval_quoted(expr.value) new_attrs = Enum.map(expr_value, fn {name, {type, value}} -> evaluate_literal_attribute(name, type, value, expr.meta) end) [new_attrs | to_html_attributes(attributes)] rescue e in RuntimeError -> IOHelper.compile_error(e.message, expr.meta.file, expr.meta.line) end end defp to_html_attributes([ %AST.DynamicAttribute{expr: %AST.AttributeExpr{value: expr_value} = expr} | attributes ]) do value = quote generated: true do for {name, {type, value}} <- unquote(expr_value) do Phoenix.HTML.raw(Surface.TypeHandler.attr_to_html!(type, name, value)) end end [%{expr | value: value} | to_html_attributes(attributes)] end defp to_html_attributes([ %AST.Attribute{value: %AST.AttributeExpr{constant?: true} = expr} = attr | attributes ]) do try do {expr_value, _} = Code.eval_quoted(expr.value) value = evaluate_literal_attribute(to_string(attr.name), attr.type, expr_value, attr.meta) [value | to_html_attributes(attributes)] rescue e in RuntimeError -> IOHelper.compile_error(e.message, expr.meta.file, expr.meta.line) end end defp to_html_attributes([ %AST.Attribute{ name: name, type: type, value: %AST.AttributeExpr{value: expr_value} = expr } | attributes ]) do value = quote generated: true do Phoenix.HTML.raw( Surface.TypeHandler.attr_to_html!(unquote(type), unquote(to_string(name)), unquote(expr_value)) ) end [%{expr | value: value} | to_html_attributes(attributes)] end defp maybe_print_expression(expr, node) do maybe_print_expression( expr, Map.has_key?(node, :debug) and Enum.member?(node.debug, :code), node.meta.file, node.meta.line ) end defp maybe_print_expression(expr, print?, file, line) do if print? do IO.puts(">>> DEBUG(EXPRESSION): #{file}:#{line}") expr |> Macro.to_string() |> Code.format_string!(line_length: 120) |> IO.puts() IO.puts("<<<") end expr end defp evaluate_literal_attribute(name, type, value, meta) do case Surface.TypeHandler.attr_to_html(type, name, value) do {:ok, attr} -> attr {:error, message} -> IOHelper.compile_error(message, meta.file, meta.line) end end defp require_expr(module, line) do %AST.Expr{ value: quote generated: true, line: line do require(unquote(module)).__info__(:module) end, meta: %AST.Meta{} } end defp is_child_component?(state) do state.depth > 0 and Enum.member?(state.scope, :template) end defp escape_message(message) do {:safe, message_iodata} = Phoenix.HTML.html_escape(message) IO.iodata_to_binary(message_iodata) end defp context_name(count, caller) do "context_#{count}" |> String.to_atom() |> Macro.var(caller.module) end defp put_injected_component(caller_module, component_module, line) do # No need to store dynamic modules if !match?(%Surface.AST.AttributeExpr{}, component_module) do Module.put_attribute(caller_module, :__injected_components__, {component_module, line}) end end defp process_context(module, fun, props, caller, state) do caller_is_module_component? = Module.get_attribute(caller.module, :component_type) && caller.function == {:render, 1} gets_context? = (function_exported?(module, :__gets_context__?, 1) and module.__gets_context__?({fun, 1})) or (module == Context and AST.has_attribute?(props, :get)) changes_context? = (function_exported?(module, :__changes_context__?, 1) and module.__changes_context__?({fun, 1}) and module.__slots__() != []) or (module == Context and AST.has_attribute?(props, :put)) if gets_context? do Module.put_attribute(caller.module, :gets_context?, caller.function) end if changes_context? do Module.put_attribute(caller.module, :changes_context?, caller.function) end initial_context = if caller_is_module_component? do quote do: @__context__ else quote do: %{} end context_expr = cond do function_exported?(module, :__slots__?, 0) and module.__slots__() == [] and not gets_context? -> quote do: %{} state.context_vars.changed != [] && gets_context? -> quote do: Enum.reduce([unquote_splicing(state.context_vars.changed ++ [initial_context])], &Map.merge/2) true -> initial_context end context_var = context_name(state.context_vars.count, caller) state = if changes_context? do %{state | context_vars: %{state.context_vars | changed: [context_var | state.context_vars.changed]}} else state end {context_expr, context_var, state} end defp build_props_expressions(module, %{props: props, dynamic_props: dynamic_props}) do props_expr = collect_component_props(module, props) dynamic_props_expr = handle_dynamic_props(dynamic_props) {props_expr, dynamic_props_expr} end end
30.665458
120
0.628311
037f0cab573da6f77fa4195e4fcdc98bbfb3e440
1,667
exs
Elixir
implements/bank-account/account.exs
MickeyOoh/Exercises
3b34e7fdab4a09e0269d20c68531b4fb75bb7f16
[ "MIT" ]
null
null
null
implements/bank-account/account.exs
MickeyOoh/Exercises
3b34e7fdab4a09e0269d20c68531b4fb75bb7f16
[ "MIT" ]
1
2018-06-19T18:59:41.000Z
2018-06-19T18:59:41.000Z
implements/bank-account/account.exs
MickeyOoh/Exercises
3b34e7fdab4a09e0269d20c68531b4fb75bb7f16
[ "MIT" ]
null
null
null
defmodule BankAccount do @moduledoc """ A bank account that supports access from multiple processes. """ use GenServer #defstruct name: "", balance: 0, last_updated: "" #def start_link() do # GenServer.start_link(__MODULE__, [],[]) #end def init(_args) do {:ok, 0} end def handle_call(:balance, _from, balance) do {:reply, balance, balance} end def handle_call({:update, amount}, _from, balance) do {:reply, :ok, balance + amount} end def handle_call(:close, _from, balance) do # We stop normally and return :stopped to the caller. {:stop, :normal, :stopped, balance} end @typedoc """ An account handle. """ @opaque account :: pid @doc """ Open the bank. Makes the account available. """ @spec open_bank() :: account def open_bank() do {:ok, pid} = GenServer.start_link(__MODULE__, [],[]) #IO.inspect pid pid end @doc """ Close the bank. Makes the account unavailable. """ #@spec close_bank(account) :: none @spec close_bank(account) :: any def close_bank(account) do GenServer.stop(account) end @doc """ Get the account's balance. """ @spec balance(account) :: integer def balance(account) do if Process.alive?(account) do GenServer.call(account, :balance) else {:error, :account_closed} end end @doc """ Update the account's balance by adding the given amount which may be negative. """ @spec update(account, integer) :: any def update(account, amount) do if Process.alive?(account) do GenServer.call(account, {:update, amount}) else {:error, :account_closed} end end end
23.152778
80
0.638272
037f2894b42c9c576231c7589389d50ec6a49159
1,327
exs
Elixir
config/config.exs
temp/opencov
0fc7d5af8d4d88162f9f74f371ed5799a0c8808e
[ "MIT" ]
189
2018-09-25T09:02:41.000Z
2022-03-09T13:52:06.000Z
config/config.exs
temp/opencov
0fc7d5af8d4d88162f9f74f371ed5799a0c8808e
[ "MIT" ]
29
2018-09-26T05:51:18.000Z
2021-11-05T08:55:03.000Z
config/config.exs
temp/opencov
0fc7d5af8d4d88162f9f74f371ed5799a0c8808e
[ "MIT" ]
32
2018-10-21T12:28:11.000Z
2022-03-28T02:20:19.000Z
use Mix.Config config :opencov, Opencov.Endpoint, url: [host: "localhost"], root: Path.dirname(__DIR__), secret_key_base: "tfYGCfFfu10pV8G5gtUJ1do3LDwnu+eWBfL1sNtK8+bEwo6gNzFQZtWkdNQVlt+V", render_errors: [accepts: ~w(html json)], pubsub_server: Opencov.PubSub config :opencov, badge_format: "svg", base_url: nil, ecto_repos: [Opencov.Repo] config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:request_id] config :phoenix, :generators, migration: true, binary_id: false config :phoenix, :json_library, Jason config :scrivener_html, routes_helper: Opencov.Router.Helpers config :opencov, PlugBasicAuth, enable: false config :seedex, repo: Opencov.Repo config :opencov, :email, sender: "OpenCov <info@opencov.com>", smtp: [ relay: "smtp.mailgun.org", username: System.get_env("SMTP_USER") || "info@opencov.com", password: System.get_env("SMTP_PASSWORD") || "I wouldn't share this", port: 587, ssl: false, tls: :always, auth: :always ] config :opencov, :demo, enabled: System.get_env("OPENCOV_DEMO") == "true", email: "user@opencov.com", password: "password123" import_config "#{Mix.env}.exs" local_config_path = Path.expand("local.exs", __DIR__) if File.exists?(local_config_path), do: import_config local_config_path
24.574074
86
0.71364
037f2b5f3b98e5aa4fd729e40ef136e9bfd761ba
3,490
ex
Elixir
lib/spear/grpc/response.ex
NFIBrokerage/spear
611223d2cdba97daa63f2ddd81a08b4f55e72198
[ "Apache-2.0" ]
34
2021-04-15T22:16:38.000Z
2022-03-11T10:20:11.000Z
lib/spear/grpc/response.ex
NFIBrokerage/spear
611223d2cdba97daa63f2ddd81a08b4f55e72198
[ "Apache-2.0" ]
32
2021-04-05T18:07:35.000Z
2021-11-04T19:32:58.000Z
lib/spear/grpc/response.ex
NFIBrokerage/spear
611223d2cdba97daa63f2ddd81a08b4f55e72198
[ "Apache-2.0" ]
1
2021-10-11T15:53:42.000Z
2021-10-11T15:53:42.000Z
alias Spear.{Connection.Response, Grpc, Rpc} defmodule Grpc.Response do @moduledoc false # a structure and functions for turning a `Spear.Connection.Response` into # a more friendly and usable data structure defstruct [:status, :status_code, :message, :data] # status code information and usages from # https://grpc.github.io/grpc/core/md_doc_statuscodes.html @status_code_mapping %{ 0 => :ok, 1 => :cancelled, 2 => :unknown, 3 => :invalid_argument, 4 => :deadline_exceeded, 5 => :not_found, 6 => :already_exists, 7 => :permission_denied, 8 => :resource_exhausted, 9 => :failed_precondition, 10 => :aborted, 11 => :out_of_range, 12 => :unimplemented, 13 => :internal, 14 => :unavailable, 15 => :data_loss, 16 => :unauthenticated } @reverse_capitalized_status_code_mapping Map.new(@status_code_mapping, fn {status_code, status} -> {status |> Atom.to_string() |> String.upcase() |> String.to_atom(), status_code} end) def from_connection_response(%Response{status: status}, _request, _raw?) when status != 200 do %__MODULE__{ status_code: 2, status: :unknown, message: "Bad HTTP status code: #{inspect(status)}, should be 200" } end def from_connection_response(%Response{headers: headers, data: data, status: 200}, rpc, raw?) do with {"grpc-status", "0"} <- List.keyfind(headers, "grpc-status", 0), {:ok, parsed_data} <- parse_data(data, rpc, raw?) do %__MODULE__{ status_code: 0, status: :ok, message: "", data: parsed_data } else {"grpc-status", other_status} -> status_code = String.to_integer(other_status) %__MODULE__{ status_code: status_code, status: map_status(status_code), message: Enum.find_value(headers, fn {k, v} -> k == "grpc-message" && v end), data: data } _ -> %__MODULE__{ status_code: 13, status: :internal, message: "Error parsing response proto" } end end defp parse_data(data, rpc, raw?) defp parse_data(data, _rpc, true), do: {:ok, data} defp parse_data(data, %Rpc{response_stream?: false} = rpc, _raw?) do case Grpc.decode_next_message(data, {rpc.service_module, rpc.response_type}) do {parsed, <<>>} -> {:ok, parsed} _ -> :error end end defp parse_data(data, %Rpc{response_stream?: true} = rpc, _raw?) do import Spear.Records.Streams, only: [read_resp: 1, read_resp_stream_not_found: 0] parse_chunk = &Spear.Grpc.decode_next_message(&1, {rpc.service_module, rpc.response_type}) case parse_chunk.(data) do {read_resp(content: {:stream_not_found, read_resp_stream_not_found()}), _rest} -> {:ok, []} {_message, _rest} -> {:ok, Stream.unfold(data, parse_chunk)} _ -> :error end end for {code, status} <- @status_code_mapping do def map_status(unquote(code)), do: unquote(status) end def map_status(_), do: :unknown for {status, code} <- @reverse_capitalized_status_code_mapping do def status_code(unquote(status)), do: unquote(code) end def status_code(_), do: 2 end
29.083333
100
0.583954
037f32990a189ccc39acfb228df13934b1602841
1,132
exs
Elixir
elixir-phoenix/mix.exs
duijf/boilerplates
a0aecb0de2c2a3f77ae8eeab1a030f4abc38959f
[ "MIT" ]
null
null
null
elixir-phoenix/mix.exs
duijf/boilerplates
a0aecb0de2c2a3f77ae8eeab1a030f4abc38959f
[ "MIT" ]
null
null
null
elixir-phoenix/mix.exs
duijf/boilerplates
a0aecb0de2c2a3f77ae8eeab1a030f4abc38959f
[ "MIT" ]
null
null
null
defmodule App.Umbrella.MixProject do use Mix.Project def project do [ apps_path: "apps", version: "0.1.0", start_permanent: Mix.env() == :prod, deps: deps(), aliases: aliases() ] 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. # # Dependencies listed here are available only for this project # and cannot be accessed from applications inside the apps/ folder. defp deps do [] 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. # # Aliases listed here are available only for this project # and cannot be accessed from applications inside the apps/ folder. defp aliases do [ # run `mix setup` in all child apps setup: ["cmd mix setup"] ] end end
24.608696
84
0.640459
037f99470cdeb62a9f3614d712d24c59681c406d
2,277
exs
Elixir
test/blog/web/controllers/tag_controller_test.exs
ench0/blog
04f7df2357b13dddee9d82cd1c35bbd0ce9618a9
[ "MIT" ]
2
2017-06-08T23:28:13.000Z
2017-06-08T23:28:16.000Z
test/blog/web/controllers/tag_controller_test.exs
ench0/blog
04f7df2357b13dddee9d82cd1c35bbd0ce9618a9
[ "MIT" ]
null
null
null
test/blog/web/controllers/tag_controller_test.exs
ench0/blog
04f7df2357b13dddee9d82cd1c35bbd0ce9618a9
[ "MIT" ]
null
null
null
defmodule Blog.Web.TagControllerTest do use Blog.Web.ConnCase alias Blog.Org @create_attrs %{active: true, list: [], slug: "some slug"} @update_attrs %{active: false, list: [], slug: "some updated slug"} @invalid_attrs %{active: nil, list: nil, slug: nil} def fixture(:tag) do {:ok, tag} = Org.create_tag(@create_attrs) tag end test "lists all entries on index", %{conn: conn} do conn = get conn, tag_path(conn, :index) assert html_response(conn, 200) =~ "Listing Tags" end test "renders form for new tags", %{conn: conn} do conn = get conn, tag_path(conn, :new) assert html_response(conn, 200) =~ "New Tag" end test "creates tag and redirects to show when data is valid", %{conn: conn} do conn = post conn, tag_path(conn, :create), tag: @create_attrs assert %{id: id} = redirected_params(conn) assert redirected_to(conn) == tag_path(conn, :show, id) conn = get conn, tag_path(conn, :show, id) assert html_response(conn, 200) =~ "Show Tag" end test "does not create tag and renders errors when data is invalid", %{conn: conn} do conn = post conn, tag_path(conn, :create), tag: @invalid_attrs assert html_response(conn, 200) =~ "New Tag" end test "renders form for editing chosen tag", %{conn: conn} do tag = fixture(:tag) conn = get conn, tag_path(conn, :edit, tag) assert html_response(conn, 200) =~ "Edit Tag" end test "updates chosen tag and redirects when data is valid", %{conn: conn} do tag = fixture(:tag) conn = put conn, tag_path(conn, :update, tag), tag: @update_attrs assert redirected_to(conn) == tag_path(conn, :show, tag) conn = get conn, tag_path(conn, :show, tag) assert html_response(conn, 200) =~ "" end test "does not update chosen tag and renders errors when data is invalid", %{conn: conn} do tag = fixture(:tag) conn = put conn, tag_path(conn, :update, tag), tag: @invalid_attrs assert html_response(conn, 200) =~ "Edit Tag" end test "deletes chosen tag", %{conn: conn} do tag = fixture(:tag) conn = delete conn, tag_path(conn, :delete, tag) assert redirected_to(conn) == tag_path(conn, :index) assert_error_sent 404, fn -> get conn, tag_path(conn, :show, tag) end end end
32.528571
93
0.659201
037f9ab40c45f3cfc23d6c9e9e981ac9270c5535
9,689
exs
Elixir
test/mustachex_test.exs
jui/mustachex
7686ab64c0177f6342150c881b08922afce8b42f
[ "MIT" ]
20
2015-01-29T22:14:55.000Z
2020-10-02T23:40:40.000Z
test/mustachex_test.exs
jui/mustachex
7686ab64c0177f6342150c881b08922afce8b42f
[ "MIT" ]
2
2015-04-23T14:27:48.000Z
2017-07-23T12:41:27.000Z
test/mustachex_test.exs
jui/mustachex
7686ab64c0177f6342150c881b08922afce8b42f
[ "MIT" ]
8
2015-08-06T00:16:22.000Z
2021-08-20T09:40:31.000Z
Code.require_file "test_helper.exs", __DIR__ defmodule MustachexTest do use ExUnit.Case test "render simple using lists" do assert Mustachex.render("Hello, {{name}}", [name: "Mustache"]) == "Hello, Mustache" end test "render multi line using lists" do assert Mustachex.render("Hello\n{{name}}", [name: "Mustache"]) == "Hello\nMustache" end test "render with nested context using lists" do assert Mustachex.render("{{#a}}{{#b}}Mustache{{/b}}{{/a}}", [a: true, b: true]) == "Mustache" end test "render nil using lists" do assert Mustachex.render("Hello, {{name}}", [name: nil]) == "Hello, " end test "render missing variable using lists" do assert Mustachex.render("Hello, {{name}}", []) == "Hello, " end test "render unescaped using lists" do assert Mustachex.render("{{{string}}}", [string: "&\'\"<>"]) == "&\'\"<>" end test "render unescaped ampersand using lists" do assert Mustachex.render("{{{string}}}", [string: "&\'\"<>"]) == "&\'\"<>" end test "render escaped using lists" do assert Mustachex.render("{{string}}", [string: "&\'\"<>"]) == "&amp;&#39;&quot;&lt;&gt;" end test "render list using lists" do assert Mustachex.render("Hello{{#names}}, {{name}}{{/names}}", [names: [[name: "Mustache"], [name: "Elixir"]]]) == "Hello, Mustache, Elixir" end test "render list twice using lists" do assert Mustachex.render("Hello{{#names}}, {{name}}{{/names}}! Hello{{#names}}, {{name}}{{/names}}!", [names: [[name: "Mustache"], [name: "Elixir"]]]) == "Hello, Mustache, Elixir! Hello, Mustache, Elixir!" end test "render single value using lists" do assert Mustachex.render("Hello{{#person}}, {{name}}{{/person}}!", [person: [name: "Mustache"]]) == "Hello, Mustache!" end test "render empty list using lists" do assert Mustachex.render("{{#things}}something{{/things}}", [things: []]) == "" end test "render nested list using lists" do assert Mustachex.render("{{#x}}{{#y}}{{z}}{{/y}}{{/x}}", [x: [y: [z: "z"]]]) == "z" end test "render comment using lists" do assert Mustachex.render("Hello, {{! comment }}{{name}}", [name: "Mustache"]) == "Hello, Mustache" end test "render tags with whitespace using lists" do assert Mustachex.render("Hello, {{# names }}{{ name }}{{/ names }}", [names: [[name: "Mustache"]]]) == "Hello, Mustache" end test "render true section using lists" do assert Mustachex.render("Hello, {{#bool}}Mustache{{/bool}}", [bool: true]) == "Hello, Mustache" end test "render false section using lists" do assert Mustachex.render("Hello, {{#bool}}Mustache{{/bool}}", [bool: false]) == "Hello, " end test "render inverted empty list using lists" do assert Mustachex.render("{{^things}}Empty{{/things}}", [thins: []]) == "Empty" end test "render inverted list using lists" do assert Mustachex.render("{{^things}}Empty{{/things}}", [things: ["yeah"]]) == "" end test "render inverted true section using lists" do assert Mustachex.render("Hello, {{^bool}}Mustache{{/bool}}", [bool: true]) == "Hello, " end test "render inverted false section using lists" do assert Mustachex.render("Hello, {{^bool}}Mustache{{/bool}}", [bool: false]) == "Hello, Mustache" end test "render dotted name using lists" do assert Mustachex.render("Hello, {{cool.mustache.name}}", [cool: [mustache: [name: "Mustache"]]]) == "Hello, Mustache" end test "render dotted name section using lists" do assert Mustachex.render("Hello, {{#person.name}}Mustache{{/person.name}}", [person: [name: true]]) == "Hello, Mustache" end test "render dotted name inverted section using lists" do assert Mustachex.render("Hello, {{#person.name}}Mustache{{/person.name}}", [people: [names: true]]) == "Hello, " end test "render implicit iterator using lists" do assert Mustachex.render("Hello{{#names}}, {{.}}{{/names}}!", [names: ["Mustache", "Elixir"]]) == "Hello, Mustache, Elixir!" end test "render lambda using lists" do assert Mustachex.render("Hello, {{name}}", [name: fn -> "Mustache" end]) == "Hello, Mustache" end test "render partial using lists" do assert Mustachex.render("Hello, {{>name}}", [n: "Mustache"], partials: [name: "{{n}}"]) == "Hello, Mustache" end test "render looooong using lists" do template = """ {{! ignore this line! }} Hello {{name}} {{! ignore this line! }} You have just won {{value}} dollars! {{#in_ca}} Well, {{taxed_value}} dollars, after taxes. {{/in_ca}} a{{! dont ignore this line! }} """ expected = """ Hello mururu You have just won 1000 dollars! Well, 50 dollars, after taxes. Well, 40 dollars, after taxes. a """ assert Mustachex.render(template, [name: "mururu", value: 1000, in_ca: [[taxed_value: 50], [taxed_value: 40]]]) == expected end test "render simple using maps" do assert Mustachex.render("Hello, {{name}}", %{name: "Mustache"}) == "Hello, Mustache" end test "render multi line using maps" do assert Mustachex.render("Hello\n{{name}}", %{name: "Mustache"}) == "Hello\nMustache" end test "render with nested context using maps" do assert Mustachex.render("{{#a}}{{#b}}Mustache{{/b}}{{/a}}", %{a: true, b: true}) == "Mustache" end test "render nil using maps" do assert Mustachex.render("Hello, {{name}}", %{name: nil}) == "Hello, " end test "render missing variable using maps" do assert Mustachex.render("Hello, {{name}}", %{}) == "Hello, " end test "render unescaped using maps" do assert Mustachex.render("{{{string}}}", %{string: "&\'\"<>"}) == "&\'\"<>" end test "render unescaped ampersand using maps" do assert Mustachex.render("{{{string}}}", %{string: "&\'\"<>"}) == "&\'\"<>" end test "render escaped using maps" do assert Mustachex.render("{{string}}", %{string: "&\'\"<>"}) == "&amp;&#39;&quot;&lt;&gt;" end test "render list using maps" do assert Mustachex.render("Hello{{#names}}, {{name}}{{/names}}", %{names: [%{name: "Mustache"}, %{name: "Elixir"}]}) == "Hello, Mustache, Elixir" end test "render list twice using maps" do assert Mustachex.render("Hello{{#names}}, {{name}}{{/names}}! Hello{{#names}}, {{name}}{{/names}}!", %{names: [%{name: "Mustache"}, %{name: "Elixir"}]}) == "Hello, Mustache, Elixir! Hello, Mustache, Elixir!" end test "render single value using maps" do assert Mustachex.render("Hello{{#person}}, {{name}}{{/person}}!", %{person: %{name: "Mustache"}}) == "Hello, Mustache!" end test "render empty list using maps" do assert Mustachex.render("{{#things}}something{{/things}}", %{things: []}) == "" end test "render nested list using maps" do assert Mustachex.render("{{#x}}{{#y}}{{z}}{{/y}}{{/x}}", %{x: %{y: %{z: "z"}}}) == "z" end test "render comment using maps" do assert Mustachex.render("Hello, {{! comment }}{{name}}", %{name: "Mustache"}) == "Hello, Mustache" end test "render tags with whitespace using maps" do assert Mustachex.render("Hello, {{# names }}{{ name }}{{/ names }}", %{names: [%{name: "Mustache"}]}) == "Hello, Mustache" end test "render true section using maps" do assert Mustachex.render("Hello, {{#bool}}Mustache{{/bool}}", %{bool: true}) == "Hello, Mustache" end test "render false section using maps" do assert Mustachex.render("Hello, {{#bool}}Mustache{{/bool}}", %{bool: false}) == "Hello, " end test "render inverted empty list using maps" do assert Mustachex.render("{{^things}}Empty{{/things}}", %{thins: []}) == "Empty" end test "render inverted list using maps" do assert Mustachex.render("{{^things}}Empty{{/things}}", %{things: ["yeah"]}) == "" end test "render inverted true section using maps" do assert Mustachex.render("Hello, {{^bool}}Mustache{{/bool}}", %{bool: true}) == "Hello, " end test "render inverted false section using maps" do assert Mustachex.render("Hello, {{^bool}}Mustache{{/bool}}", %{bool: false}) == "Hello, Mustache" end test "render dotted name using maps" do assert Mustachex.render("Hello, {{cool.mustache.name}}", %{cool: %{mustache: %{name: "Mustache"}}}) == "Hello, Mustache" end test "render dotted name section using maps" do assert Mustachex.render("Hello, {{#person.name}}Mustache{{/person.name}}", %{person: %{name: true}}) == "Hello, Mustache" end test "render dotted name inverted section using maps" do assert Mustachex.render("Hello, {{#person.name}}Mustache{{/person.name}}", %{people: %{names: true}}) == "Hello, " end test "render implicit iterator using maps" do assert Mustachex.render("Hello{{#names}}, {{.}}{{/names}}!", %{names: ["Mustache", "Elixir"]}) == "Hello, Mustache, Elixir!" end test "render lambda using maps" do assert Mustachex.render("Hello, {{name}}", %{name: fn -> "Mustache" end}) == "Hello, Mustache" end test "render partial using maps" do assert Mustachex.render("Hello, {{>name}}", %{n: "Mustache"}, partials: %{name: "{{n}}"}) == "Hello, Mustache" end test "render looooong using maps" do template = """ {{! ignore this line! }} Hello {{name}} {{! ignore this line! }} You have just won {{value}} dollars! {{#in_ca}} Well, {{taxed_value}} dollars, after taxes. {{/in_ca}} a{{! dont ignore this line! }} """ expected = """ Hello mururu You have just won 1000 dollars! Well, 50 dollars, after taxes. Well, 40 dollars, after taxes. a """ assert Mustachex.render(template, %{name: "mururu", value: 1000, in_ca: [%{taxed_value: 50}, %{taxed_value: 40}]}) == expected end end
34.978339
211
0.615027
037fb873e28330537f492c5eadd7d0b60027becc
1,657
ex
Elixir
lib/emq_event_store.ex
127labs/emq-event-store
0ce4aaed691f09e0e8cb19a8971919ce8fd5a056
[ "Apache-2.0" ]
1
2017-06-15T09:34:10.000Z
2017-06-15T09:34:10.000Z
lib/emq_event_store.ex
127labs/emq-event-store
0ce4aaed691f09e0e8cb19a8971919ce8fd5a056
[ "Apache-2.0" ]
2
2017-06-23T15:52:58.000Z
2017-06-23T15:54:14.000Z
lib/emq_event_store.ex
127labs/emq-event-store
0ce4aaed691f09e0e8cb19a8971919ce8fd5a056
[ "Apache-2.0" ]
null
null
null
##-------------------------------------------------------------------- ## Copyright (c) 2016-2017 EMQ Enterprise, Inc. (http://emqtt.io) ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ##-------------------------------------------------------------------- defmodule EmqEventStore do require Logger alias EmqEventStore.{ Event, Repo } def load(env) do register_hook(:"message.publish", &on_message_publish/2, [env]) end def unload do deregister_hook(:"message.publish", &on_message_publish/2) end def on_message_publish({:mqtt_message, _, _, _, topic, _, _, _, _, false, _, payload, _} = message, _) do Logger.debug("[emq_event_store] Topic: #{topic} Received: \n#{payload}") with {:ok, decoded} <- Poison.decode(payload) do decoded |> Map.put("type", topic) |> Event.new() |> Repo.insert!() end {:ok, message} end def on_message_publish(message, _), do: {:ok, message} defp register_hook(topic, callback, args) do :emqttd_hooks.add(topic, callback, args) end defp deregister_hook(topic, callback) do :emqttd_hooks.delete(topic, callback) end end
30.127273
107
0.629451
038000cc3ec28df4c54f329ee9dcb8c4237fcf96
1,525
ex
Elixir
lib/parsers/integer_parser.ex
heyorbit/elixir-server-utils
32643ecf4042a110495ffb2eaee3016aa5276d5a
[ "MIT" ]
null
null
null
lib/parsers/integer_parser.ex
heyorbit/elixir-server-utils
32643ecf4042a110495ffb2eaee3016aa5276d5a
[ "MIT" ]
null
null
null
lib/parsers/integer_parser.ex
heyorbit/elixir-server-utils
32643ecf4042a110495ffb2eaee3016aa5276d5a
[ "MIT" ]
null
null
null
defmodule ServerUtils.Parsers.IntegerParser do @moduledoc """ Module to simplify the parsing of an Integer value. It provides a bang! function that will raise an error if the parsing failed. """ @doc """ Parses an integer value. It returns the integer value or throws an error if something failed. ## Examples iex> ServerUtils.Parsers.IntegerParser.parse_integer!("23") 23 iex> ServerUtils.Parsers.IntegerParser.parse_integer!(23) 23 iex> ServerUtils.Parsers.IntegerParser.parse_integer!("abc") ** (RuntimeError) "Invalid integer: abc" """ @spec parse_integer!(String.t()) :: integer() def parse_integer!(value) when is_integer(value), do: value def parse_integer!(value) do case Integer.parse(value) do :error -> raise "Invalid integer: #{inspect(value)}" {value, _} -> value end end @doc """ Parses an integer value. It returns the integer value if succeed or the default value if something failed. ## Examples iex> ServerUtils.Parsers.IntegerParser.parse_integer("23", 15) 23 iex> ServerUtils.Parsers.IntegerParser.parse_integer(23, 7) 23 iex> ServerUtils.Parsers.IntegerParser.parse_integer("abc", 5) 5 """ @spec parse_integer(String.t(), integer()) :: integer() def parse_integer(value, _default) when is_integer(value), do: value def parse_integer(value, default) do case Integer.parse(value) do :error -> default {value, _} -> value end end end
24.596774
83
0.676721
0380036ef2c70904d326d0b9d384d08af75f6cc9
2,177
exs
Elixir
config/dev.exs
oiax/nano_planner
9a0081582ea82519b8166f49ac8c5bcbcadaefbd
[ "MIT" ]
4
2019-04-21T05:46:19.000Z
2021-09-13T01:56:33.000Z
config/dev.exs
oiax/nano_planner
9a0081582ea82519b8166f49ac8c5bcbcadaefbd
[ "MIT" ]
1
2020-09-24T00:13:40.000Z
2020-09-24T00:13:40.000Z
config/dev.exs
oiax/nano_planner
9a0081582ea82519b8166f49ac8c5bcbcadaefbd
[ "MIT" ]
3
2019-10-26T01:41:53.000Z
2020-09-21T01:13:02.000Z
use Mix.Config # Configure your database config :nano_planner, NanoPlanner.Repo, username: "postgres", password: "postgres", database: "nano_planner_dev", hostname: "postgres", show_sensitive_data_on_connection_error: true, pool_size: 10 # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with webpack to recompile .js and .css sources. config :nano_planner, NanoPlannerWeb.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [ node: [ "node_modules/webpack/bin/webpack.js", "--mode", "development", "--watch-stdin", cd: Path.expand("../assets", __DIR__) ] ] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # Mix task: # # mix phx.gen.cert # # Note that this task requires Erlang/OTP 20 or later. # Run `mix help phx.gen.cert` for more information. # # The `http:` config above can be replaced with: # # https: [ # port: 4001, # cipher_suite: :strong, # keyfile: "priv/cert/selfsigned_key.pem", # certfile: "priv/cert/selfsigned.pem" # ], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Watch static and templates for browser reloading. config :nano_planner, NanoPlannerWeb.Endpoint, live_reload: [ patterns: [ ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", ~r"priv/gettext/.*(po)$", ~r"lib/nano_planner_web/(live|views)/.*(ex)$", ~r"lib/nano_planner_web/templates/.*(eex)$" ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Initialize plugs at runtime for faster development compilation config :phoenix, :plug_init_mode, :runtime
28.272727
68
0.696371
03800c49d1450d343c5ac0a8e82d8724c6d7b494
1,360
exs
Elixir
hello_naked/mix.exs
playgd/learning-elixir
3909b540ccd7f54b174de9c6c6f258e94865ba6b
[ "MIT" ]
16
2021-11-08T12:15:27.000Z
2022-02-11T01:00:20.000Z
hello_naked/mix.exs
playgd/learning-elixir
3909b540ccd7f54b174de9c6c6f258e94865ba6b
[ "MIT" ]
null
null
null
hello_naked/mix.exs
playgd/learning-elixir
3909b540ccd7f54b174de9c6c6f258e94865ba6b
[ "MIT" ]
2
2021-11-19T11:32:58.000Z
2022-01-16T00:36:32.000Z
defmodule HelloNaked.MixProject do use Mix.Project def project do [ app: :hello_naked, version: "0.1.0", elixir: "~> 1.12", elixirc_paths: elixirc_paths(Mix.env()), compilers: Mix.compilers(), start_permanent: Mix.env() == :prod, aliases: aliases(), deps: deps() ] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [ mod: {HelloNaked.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_live_dashboard, "~> 0.5"}, {:telemetry_metrics, "~> 0.6"}, {:telemetry_poller, "~> 1.0"}, {:jason, "~> 1.2"}, {:plug_cowboy, "~> 2.5"} ] 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"] ] end end
23.859649
84
0.603676
03801fd1597e74506a3fe3563aca3c2cbb80779e
962
ex
Elixir
clients/elixir/generated/lib/cloud_manager_api/model/environment_logs.ex
shinesolutions/cloudmanager-api-clients
d73a25878f6cc57af954362ba8dccc90d54e6131
[ "Apache-2.0" ]
3
2020-06-23T05:31:52.000Z
2020-11-26T05:34:57.000Z
clients/elixir/generated/lib/cloud_manager_api/model/environment_logs.ex
shinesolutions/cloudmanager-api-clients
d73a25878f6cc57af954362ba8dccc90d54e6131
[ "Apache-2.0" ]
2
2021-01-21T01:19:54.000Z
2021-12-09T22:30:22.000Z
clients/elixir/generated/lib/cloud_manager_api/model/environment_logs.ex
shinesolutions/cloudmanager-api-clients
d73a25878f6cc57af954362ba8dccc90d54e6131
[ "Apache-2.0" ]
1
2020-11-18T11:48:13.000Z
2020-11-18T11:48:13.000Z
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). # https://openapi-generator.tech # Do not edit the class manually. defmodule CloudManagerAPI.Model.EnvironmentLogs do @moduledoc """ Logs of an Environment """ @derive [Poison.Encoder] defstruct [ :"service", :"name", :"days", :"_links", :"_embedded" ] @type t :: %__MODULE__{ :"service" => [String.t] | nil, :"name" => [String.t] | nil, :"days" => integer() | nil, :"_links" => EnvironmentLogsLinks | nil, :"_embedded" => EnvironmentLogsEmbedded | nil } end defimpl Poison.Decoder, for: CloudManagerAPI.Model.EnvironmentLogs do import CloudManagerAPI.Deserializer def decode(value, options) do value |> deserialize(:"_links", :struct, CloudManagerAPI.Model.EnvironmentLogsLinks, options) |> deserialize(:"_embedded", :struct, CloudManagerAPI.Model.EnvironmentLogsEmbedded, options) end end
26
97
0.678794
038030bbf966a3fd5ac701be5c2aef46eda60e9d
1,387
exs
Elixir
nucleotide-count/nucleotide_count.exs
Pompeu/exercism
29afcee4fbf48f5e7d91359bea871585438c8245
[ "MIT" ]
null
null
null
nucleotide-count/nucleotide_count.exs
Pompeu/exercism
29afcee4fbf48f5e7d91359bea871585438c8245
[ "MIT" ]
null
null
null
nucleotide-count/nucleotide_count.exs
Pompeu/exercism
29afcee4fbf48f5e7d91359bea871585438c8245
[ "MIT" ]
null
null
null
defmodule DNA do @nucleotides [?A, ?C, ?G, ?T] @doc """ Counts individual nucleotides in a DNA strand. ## Examples iex> DNA.count('AATAA', ?A) 4 iex> DNA.count('AATAA', ?T) 1 """ @spec count([char], char) :: non_neg_integer def count(strand, nucleotide) do len = Enum.concat(@nucleotides, strand) |> Enum.uniq |> Enum.count if len > 4 or not Enum.any?(@nucleotides, fn(x) -> x == nucleotide end) do raise ArgumentError end Enum.count(strand, fn(x) -> x == nucleotide end) end @doc """ Returns a summary of counts by nucleotide. ## Examples iex> DNA.histogram('AATAA') %{?A => 4, ?T => 1, ?C => 0, ?G => 0} """ @spec histogram([char]) :: map def histogram(strand) do Enum.reduce(strand, %{?A => 0, ?T => 0, ?C => 0, ?G => 0}, fn(x, acc) -> acc = case x do ?G -> Map.get_and_update(acc, x, fn current -> {current, DNA.count(strand, x)} end) ?A -> Map.get_and_update(acc, x, fn current -> {current, DNA.count(strand, x)} end) ?C -> Map.get_and_update(acc, x, fn current -> {current, DNA.count(strand, x)} end) ?T -> Map.get_and_update(acc, x, fn current -> {current, DNA.count(strand, x)} end) _ -> raise ArgumentError end if is_tuple acc do Tuple.to_list(acc) |> List.last else acc end end) end end
25.685185
92
0.563086
03807ba32935e71eb9bfa0fdfab898f9fd736e6d
142
exs
Elixir
chapter_12/todo_distributed/test/test_helper.exs
librity/elixir_in_action
d2df441ceb7e6a0d3f18bc3ab3c59570125fcdec
[ "MIT" ]
3
2021-04-22T11:55:58.000Z
2021-08-22T13:19:56.000Z
chapter_13/todo_release/test/test_helper.exs
librity/elixir_in_action
d2df441ceb7e6a0d3f18bc3ab3c59570125fcdec
[ "MIT" ]
null
null
null
chapter_13/todo_release/test/test_helper.exs
librity/elixir_in_action
d2df441ceb7e6a0d3f18bc3ab3c59570125fcdec
[ "MIT" ]
3
2021-04-22T21:19:45.000Z
2021-08-22T13:20:03.000Z
ExUnit.start() ExUnit.after_suite(fn _ -> Application.fetch_env!(:todo, :database) |> Keyword.fetch!(:db_folder) |> File.rm_rf!() end)
17.75
42
0.676056
0380a5d9209c8663ab883baeccb87aec75883754
1,504
exs
Elixir
test/controllers/comment_controller_test.exs
mwindholtz/has_many_blog
521f13c8b91620713a305f44040581276d162abc
[ "Apache-2.0" ]
7
2016-12-15T00:33:22.000Z
2019-04-24T20:42:17.000Z
test/controllers/comment_controller_test.exs
mwindholtz/has_many_blog
521f13c8b91620713a305f44040581276d162abc
[ "Apache-2.0" ]
1
2017-07-19T16:41:35.000Z
2017-07-19T16:41:35.000Z
test/controllers/comment_controller_test.exs
mwindholtz/has_many_blog
521f13c8b91620713a305f44040581276d162abc
[ "Apache-2.0" ]
2
2017-04-28T21:52:38.000Z
2020-04-24T14:41:31.000Z
defmodule Blog.CommentControllerTest do use Blog.ConnCase alias Blog.Post alias Blog.Comment @valid_attrs %{body: "some content"} @invalid_attrs %{} setup do post_attrs = %{body: "some content", title: "some content"} changeset = Post.changeset(%Post{}, post_attrs) {:ok, post} = Repo.insert(changeset) conn = build_conn() conn = assign(conn, :post, post) {:ok, conn: conn} end test "renders form for new resources", %{conn: conn} do post = conn.assigns.post conn = get conn, post_comment_path(conn, :new, post) assert html_response(conn, 200) =~ "New comment" end test "creates resource and redirects when data is valid", %{conn: conn} do post = conn.assigns.post conn = post conn, post_comment_path(conn, :create, post), comment: @valid_attrs assert redirected_to(conn) == post_path(conn, :show, post) assert Repo.get_by(Comment, @valid_attrs) end test "does not create resource and renders errors when data is invalid", %{conn: conn} do post = conn.assigns.post conn = post conn, post_comment_path(conn, :create, post), comment: @invalid_attrs assert html_response(conn, 200) =~ "New comment" end test "deletes chosen resource", %{conn: conn} do post = conn.assigns.post comment = Repo.insert! %Comment{} conn = delete conn, post_comment_path(conn, :delete, post, comment) assert redirected_to(conn) == post_path(conn, :show, post) refute Repo.get(Comment, comment.id) end end
32.695652
91
0.684176
0380aa4e5c136a486b382c5434c9e93ed2f2c201
2,226
exs
Elixir
config/dev.exs
parikshitgupta1/k8
1df84e3f0c37c59c27061c75408b2909e7e44ff9
[ "MIT" ]
null
null
null
config/dev.exs
parikshitgupta1/k8
1df84e3f0c37c59c27061c75408b2909e7e44ff9
[ "MIT" ]
null
null
null
config/dev.exs
parikshitgupta1/k8
1df84e3f0c37c59c27061c75408b2909e7e44ff9
[ "MIT" ]
null
null
null
use Mix.Config # Configure your database config :petal, Petal.Repo, username: System.get_env("POSTGRES_USER") || "postgres", password: System.get_env("POSTGRERS_PASSWORD") || "postgres", hostname: System.get_env("POSTGRES_HOST") || "postgres", database: "petal_dev", show_sensitive_data_on_connection_error: true, pool_size: 10 # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with webpack to recompile .js and .css sources. config :petal, PetalWeb.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [ node: [ "node_modules/webpack/bin/webpack.js", "--mode", "development", "--watch-stdin", cd: Path.expand("../assets", __DIR__) ] ] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # Mix task: # # mix phx.gen.cert # # Note that this task requires Erlang/OTP 20 or later. # Run `mix help phx.gen.cert` for more information. # # The `http:` config above can be replaced with: # # https: [ # port: 4001, # cipher_suite: :strong, # keyfile: "priv/cert/selfsigned_key.pem", # certfile: "priv/cert/selfsigned.pem" # ], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Watch static and templates for browser reloading. config :petal, PetalWeb.Endpoint, live_reload: [ patterns: [ ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", ~r"priv/gettext/.*(po)$", ~r"lib/petal_web/(live|views)/.*(ex)$", ~r"lib/petal_web/templates/.*(eex)$" ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Initialize plugs at runtime for faster development compilation config :phoenix, :plug_init_mode, :runtime
29.289474
68
0.691375
0380aabaeffa32198bdae0a06b90b84efa1fc6ce
1,709
ex
Elixir
clients/content/lib/google_api/content/v21/model/orders_create_test_return_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v21/model/orders_create_test_return_request.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/content/lib/google_api/content/v21/model/orders_create_test_return_request.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.Content.V21.Model.OrdersCreateTestReturnRequest do @moduledoc """ ## Attributes * `items` (*type:* `list(GoogleApi.Content.V21.Model.OrdersCustomBatchRequestEntryCreateTestReturnReturnItem.t)`, *default:* `nil`) - Returned items. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :items => list( GoogleApi.Content.V21.Model.OrdersCustomBatchRequestEntryCreateTestReturnReturnItem.t() ) } field(:items, as: GoogleApi.Content.V21.Model.OrdersCustomBatchRequestEntryCreateTestReturnReturnItem, type: :list ) end defimpl Poison.Decoder, for: GoogleApi.Content.V21.Model.OrdersCreateTestReturnRequest do def decode(value, options) do GoogleApi.Content.V21.Model.OrdersCreateTestReturnRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V21.Model.OrdersCreateTestReturnRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
32.245283
153
0.745465
0380af7de7a3c3aaa2278d07de7a9fddece9d8c1
99
ex
Elixir
web/admin/user.ex
xelcer/phoenix_demo
84dc516441dd715db7e24b1384c2fea3adffe0f7
[ "MIT" ]
null
null
null
web/admin/user.ex
xelcer/phoenix_demo
84dc516441dd715db7e24b1384c2fea3adffe0f7
[ "MIT" ]
null
null
null
web/admin/user.ex
xelcer/phoenix_demo
84dc516441dd715db7e24b1384c2fea3adffe0f7
[ "MIT" ]
null
null
null
defmodule Demo.ExAdmin.User do use ExAdmin.Register register_resource Demo.User do end end
12.375
32
0.777778