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
sequence
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
sequence
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
sequence
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
9ecda00c3a37d2f37fa8db8664af1be729a4303b
13,725
ex
Elixir
clients/vision/lib/google_api/vision/v1/api/operations.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/vision/lib/google_api/vision/v1/api/operations.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/vision/lib/google_api/vision/v1/api/operations.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.Vision.V1.Api.Operations do @moduledoc """ API calls for all endpoints tagged `Operations`. """ alias GoogleApi.Vision.V1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`. ## Parameters * `connection` (*type:* `GoogleApi.Vision.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource to be cancelled. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:body` (*type:* `GoogleApi.Vision.V1.Model.CancelOperationRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Vision.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec vision_operations_cancel(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Vision.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def vision_operations_cancel(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/v1/{+name}:cancel", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Vision.V1.Model.Empty{}]) end @doc """ Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. ## Parameters * `connection` (*type:* `GoogleApi.Vision.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource to be deleted. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Vision.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec vision_operations_delete(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Vision.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def vision_operations_delete(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Vision.V1.Model.Empty{}]) end @doc """ Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. ## Parameters * `connection` (*type:* `GoogleApi.Vision.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Vision.V1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec vision_operations_get(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Vision.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def vision_operations_get(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Vision.V1.Model.Operation{}]) end @doc """ Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. To override the binding, API services can add a binding such as `"/v1/{name=users/*}/operations"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id. ## Parameters * `connection` (*type:* `GoogleApi.Vision.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation's parent resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `:filter` (*type:* `String.t`) - The standard list filter. * `:pageSize` (*type:* `integer()`) - The standard list page size. * `:pageToken` (*type:* `String.t`) - The standard list page token. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Vision.V1.Model.ListOperationsResponse{}}` on success * `{:error, info}` on failure """ @spec vision_operations_list(Tesla.Env.client(), String.t(), keyword(), keyword()) :: {:ok, GoogleApi.Vision.V1.Model.ListOperationsResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def vision_operations_list(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query, :filter => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Vision.V1.Model.ListOperationsResponse{}]) end end
49.728261
607
0.633807
9ecdb285dd6f79e8becae2fa8a98b0a6acb5b15f
1,663
ex
Elixir
clients/big_query_connection/lib/google_api/big_query_connection/v1beta1/model/connection_credential.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/big_query_connection/lib/google_api/big_query_connection/v1beta1/model/connection_credential.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/big_query_connection/lib/google_api/big_query_connection/v1beta1/model/connection_credential.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.BigQueryConnection.V1beta1.Model.ConnectionCredential do @moduledoc """ Credential to use with a connection. ## Attributes * `cloudSql` (*type:* `GoogleApi.BigQueryConnection.V1beta1.Model.CloudSqlCredential.t`, *default:* `nil`) - Credential for Cloud SQL database. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :cloudSql => GoogleApi.BigQueryConnection.V1beta1.Model.CloudSqlCredential.t() | nil } field(:cloudSql, as: GoogleApi.BigQueryConnection.V1beta1.Model.CloudSqlCredential) end defimpl Poison.Decoder, for: GoogleApi.BigQueryConnection.V1beta1.Model.ConnectionCredential do def decode(value, options) do GoogleApi.BigQueryConnection.V1beta1.Model.ConnectionCredential.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.BigQueryConnection.V1beta1.Model.ConnectionCredential do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.382979
147
0.766085
9ecdb678637435924da2c1ca41724b2bf42844c4
5,945
ex
Elixir
lib/cforum_web/views/view_helpers/feeds.ex
MatthiasApsel/cforum_ex
52c621a583182d82692b74694b0b2792ac23b8ff
[ "MIT" ]
null
null
null
lib/cforum_web/views/view_helpers/feeds.ex
MatthiasApsel/cforum_ex
52c621a583182d82692b74694b0b2792ac23b8ff
[ "MIT" ]
null
null
null
lib/cforum_web/views/view_helpers/feeds.ex
MatthiasApsel/cforum_ex
52c621a583182d82692b74694b0b2792ac23b8ff
[ "MIT" ]
null
null
null
defmodule CforumWeb.Views.ViewHelpers.Feeds do alias CforumWeb.Views.ViewHelpers.Path alias Cforum.Messages.Message import CforumWeb.Gettext def atom_feed_head_for_thread(conn, thread, messages) do forum = conn.assigns[:current_forum] message = List.first(thread.sorted_messages) {:feed, %{"xml:lang" => Gettext.get_locale(CforumWeb.Gettext), "xmlns" => "http://www.w3.org/2005/Atom"}, [ {:id, nil, "tag:forum.selfhtml.org,2005:/self"}, {:link, %{"rel" => "alternate", "type" => "text/html", "href" => Path.message_url(conn, :show, thread, message)}, []}, {:link, %{"rel" => "self", "type" => "application/atom+xml", "href" => Path.thread_url(conn, :atom, thread)}, []}, {:title, nil, "#{message.subject} – #{CforumWeb.LayoutView.forum_name(forum)}"}, {:updated, nil, Timex.lformat!(thread.latest_message, "{RFC3339z}", "en")}, messages ]} end def atom_feed_head(conn, threads, last_updated) do forum = conn.assigns[:current_forum] {:feed, %{"xml:lang" => Gettext.get_locale(CforumWeb.Gettext), "xmlns" => "http://www.w3.org/2005/Atom"}, [ {:id, nil, "tag:forum.selfhtml.org,2005:/self"}, {:link, %{"rel" => "alternate", "type" => "text/html", "href" => Path.forum_url(conn, :index, forum)}, []}, {:link, %{"rel" => "self", "type" => "application/atom+xml", "href" => Path.forum_url(conn, :atom, forum)}, []}, {:title, nil, CforumWeb.LayoutView.forum_name(forum)}, {:updated, nil, Timex.lformat!(last_updated, "{RFC3339z}", "en")}, threads ]} end def atom_feed_message(conn, thread, message) do {:safe, html} = Cforum.MarkdownRenderer.to_html(message, conn) {:entry, nil, [ {:id, nil, Path.message_url(conn, :show, thread, message)}, atom_author(message), {:published, nil, Timex.lformat!(message.created_at, "{RFC3339z}", "en")}, {:updated, nil, Timex.lformat!(message.updated_at, "{RFC3339z}", "en")}, {:link, %{ "rel" => "alternate", "type" => "text/html", "href" => Path.message_url(conn, :show, thread, message) }, []}, {:title, nil, message.subject}, {:content, %{"type" => "html"}, html} ]} end def atom_feed_thread(conn, thread) do {:safe, html} = Cforum.MarkdownRenderer.to_html(thread.message, conn) {:entry, nil, [ {:id, nil, Path.thread_url(conn, :show, thread)}, atom_author(thread.message), {:published, nil, Timex.lformat!(thread.created_at, "{RFC3339z}", "en")}, {:updated, nil, Timex.lformat!(thread.updated_at, "{RFC3339z}", "en")}, {:link, %{ "rel" => "alternate", "type" => "text/html", "href" => Path.message_url(conn, :show, thread, thread.message) }, []}, {:title, nil, thread.message.subject}, {:content, %{"type" => "html"}, html} ]} end def atom_author(msg) do infos = [{:name, nil, msg.author}] |> atom_maybe_add_email(msg) |> atom_maybe_add_url(msg) {:author, nil, infos} end defp atom_maybe_add_email(children, %Message{email: email}) when not is_nil(email) and email != "", do: [children | [{:email, nil, email}]] defp atom_maybe_add_email(children, _), do: children defp atom_maybe_add_url(children, %Message{homepage: hp}) when not is_nil(hp) and hp != "", do: [children | [{:uri, nil, hp}]] defp atom_maybe_add_url(children, _), do: children def rss_feed_head(conn, threads) do forum = conn.assigns[:current_forum] desc = if forum && forum.description, do: forum.description, else: gettext("A forum as a completion to the wiki and the weblog") {:rss, %{"version" => "2.0", "xmlns:atom" => "http://www.w3.org/2005/Atom"}, [ {:channel, nil, [ {:title, nil, CforumWeb.LayoutView.forum_name(forum)}, {:description, nil, desc}, {:link, nil, Path.forum_url(conn, :index, forum)}, {"atom:link", %{"rel" => "self", "type" => "application/rss+xml", "href" => Path.forum_url(conn, :rss, forum)}, []}, threads ]} ]} end def rss_feed_head_for_thread(conn, thread, messages) do forum = conn.assigns[:current_forum] message = List.first(thread.sorted_messages) desc = if forum && forum.description, do: forum.description, else: gettext("A forum as a completion to the wiki and the weblog") {:rss, %{"version" => "2.0", "xmlns:atom" => "http://www.w3.org/2005/Atom"}, [ {:channel, nil, [ {:title, nil, "#{message.subject} – #{CforumWeb.LayoutView.forum_name(forum)}"}, {:description, nil, desc}, {:link, nil, Path.forum_url(conn, :index, forum)}, {"atom:link", %{"rel" => "self", "type" => "application/rss+xml", "href" => Path.thread_url(conn, :rss, thread)}, []}, messages ]} ]} end def rss_feed_thread(conn, thread) do {:safe, html} = Cforum.MarkdownRenderer.to_html(thread.message, conn) {:item, nil, [ {:title, nil, thread.message.subject}, {:pubDate, nil, Timex.lformat!(thread.message.created_at, "{RFC822z}", "en")}, {:link, nil, Path.message_url(conn, :show, thread, thread.message)}, {:guid, nil, Path.message_url(conn, :show, thread, thread.message)}, {:description, nil, html} ]} end def rss_feed_message(conn, thread, message) do {:safe, html} = Cforum.MarkdownRenderer.to_html(message, conn) {:item, nil, [ {:title, nil, message.subject}, {:pubDate, nil, Timex.lformat!(message.created_at, "{RFC822z}", "en")}, {:link, nil, Path.message_url(conn, :show, thread, message)}, {:guid, nil, Path.message_url(conn, :show, thread, message)}, {:description, nil, html} ]} end end
35.386905
120
0.583852
9ecdca3c94dc502053eebd560fdc32d796f58dd4
2,009
exs
Elixir
source/backend/api_app/config/prod.exs
edwinvautier/aio-group3-proj01
2ca3d834f358a38692e8ae4d6266bbea130a6cb5
[ "MIT" ]
3
2020-04-05T15:26:55.000Z
2020-06-17T15:01:33.000Z
source/backend/api_app/config/prod.exs
edwinvautier/aio-group3-proj01
2ca3d834f358a38692e8ae4d6266bbea130a6cb5
[ "MIT" ]
48
2020-04-01T16:00:47.000Z
2020-04-28T16:22:12.000Z
source/backend/api_app/config/prod.exs
edwinvautier/aio-group3-proj01
2ca3d834f358a38692e8ae4d6266bbea130a6cb5
[ "MIT" ]
4
2020-03-30T15:36:55.000Z
2020-06-17T15:01:36.000Z
use Mix.Config # For production, don't forget to configure the url host # to something meaningful, Phoenix uses this information # when generating URLs. # # Note we also include the path to a cache manifest # containing the digested version of static files. This # manifest is generated by the `mix phx.digest` task, # which you should run after static files are built and # before starting your production server. config :api_app, ApiAppWeb.Endpoint, url: [host: "example.com", port: 80], cache_static_manifest: "priv/static/cache_manifest.json" # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :api_app, ApiAppWeb.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [ # port: 443, # cipher_suite: :strong, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH"), # transport_options: [socket_opts: [:inet6]] # ] # # The `cipher_suite` is set to `:strong` to support only the # latest and more secure SSL ciphers. This means old browsers # and clients may not be supported. You can set it to # `:compatible` for wider support. # # `:keyfile` and `:certfile` expect an absolute path to the key # and cert in disk or a relative path inside priv, for example # "priv/ssl/server.key". For all supported SSL configuration # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 # # We also recommend setting `force_ssl` in your endpoint, ensuring # no data is ever sent via http, always redirecting to https: # # config :api_app, ApiAppWeb.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # Finally import the config/prod.secret.exs which loads secrets # and configuration from environment variables. import_config "prod.secret.exs"
35.875
66
0.714286
9ecdcd08156fac82e60d1a63c224b76bfeb1a24e
526
ex
Elixir
lib/ebnf_parser/interpreter_terms/minus.ex
langens-jonathan/mu-authorization
3b411460b81b87581af7c7f302b1d3bec4610608
[ "MIT" ]
1
2019-09-05T23:00:48.000Z
2019-09-05T23:00:48.000Z
lib/ebnf_parser/interpreter_terms/minus.ex
langens-jonathan/mu-authorization
3b411460b81b87581af7c7f302b1d3bec4610608
[ "MIT" ]
7
2020-10-27T20:42:06.000Z
2021-11-15T07:41:15.000Z
lib/ebnf_parser/interpreter_terms/minus.ex
langens-jonathan/mu-authorization
3b411460b81b87581af7c7f302b1d3bec4610608
[ "MIT" ]
6
2016-04-06T09:28:43.000Z
2021-08-09T12:29:16.000Z
defmodule InterpreterTerms.Minus do alias Generator.State, as: State defstruct [:left, :right, {:state, %State{}}] defimpl EbnfParser.GeneratorProtocol do def make_generator(%InterpreterTerms.Minus{left: left, right: right, state: state}) do %InterpreterTerms.Minus.Interpreter{ state: state, left_generator: EbnfParser.GeneratorConstructor.dispatch_generation(left, state), right_generator: EbnfParser.GeneratorConstructor.dispatch_generation(right, state) } end end end
32.875
90
0.735741
9ecdd1f8b09e0646311574c3c9efdb1cbdfbacf3
617
ex
Elixir
lib/mouth/adapters/local_adapter.ex
ZipBooks/mouth
50bd0949960d7d6149b7f56cb3c11357ea3ebad2
[ "MIT" ]
27
2017-06-21T13:31:13.000Z
2020-12-30T06:14:28.000Z
lib/mouth/adapters/local_adapter.ex
adolfosilva/mouth
95f605cc1044262f71995cb0a5bf951f3721cae1
[ "MIT" ]
12
2017-11-08T14:47:34.000Z
2019-04-02T07:40:28.000Z
lib/mouth/adapters/local_adapter.ex
adolfosilva/mouth
95f605cc1044262f71995cb0a5bf951f3721cae1
[ "MIT" ]
6
2017-11-08T14:43:27.000Z
2019-06-07T14:50:32.000Z
defmodule Mouth.LocalAdapter do @moduledoc """ Delivers messages locally to an in-memory store. """ @behaviour Mouth.Adapter def deliver(message, config) do driver = storage_driver(config) message = driver.push(message) {:ok, [status: "Accepted", id: message.meta[:id], datetime: to_string(DateTime.utc_now())]} end def status(id, _config) do {:ok, [status: "Accepted", id: id, datetime: to_string(DateTime.utc_now())]} end def handle_config(config) do config end defp storage_driver(config) do config[:storage_driver] || Mouth.LocalAdapter.Storage.Memory end end
23.730769
95
0.6953
9ecdd8e3461e893a96708f6b255bbe6edd5d8795
1,028
ex
Elixir
lib/cookbook_web/live/flash_live.ex
joerichsen/live_view_cookbook
a211e6bcfaa872df120f186b3d65e0672f410365
[ "MIT" ]
null
null
null
lib/cookbook_web/live/flash_live.ex
joerichsen/live_view_cookbook
a211e6bcfaa872df120f186b3d65e0672f410365
[ "MIT" ]
11
2021-12-19T09:07:30.000Z
2022-01-01T17:54:43.000Z
lib/cookbook_web/live/flash_live.ex
joerichsen/live_view_cookbook
a211e6bcfaa872df120f186b3d65e0672f410365
[ "MIT" ]
null
null
null
defmodule CookbookWeb.FlashLive do use CookbookWeb, :live_view def render(assigns) do ~H""" <div class="row"> <div class="col"> <button phx-click="show-flash-success" class="btn btn-success">Try me!</button> </div> <div class="col-8"> <button phx-click="show-flash-fail" class="btn btn-danger"> Press this dangerous button </button> </div> </div> <%= if @flash != %{} do %> <div class="row mt-3"> <div class="col"> <button phx-click="clear-flash" class="btn btn-primary">Clear the flash messages</button> </div> </div> <% end %> """ end def handle_event("show-flash-success", _params, socket) do {:noreply, socket |> put_flash(:info, "It worked")} end def handle_event("show-flash-fail", _params, socket) do {:noreply, socket |> put_flash(:error, "Uh oh, it didn't work")} end def handle_event("clear-flash", _params, socket) do {:noreply, socket |> clear_flash()} end end
26.358974
99
0.588521
9ecdf145c8e11decadf7460def97195f1f28f29d
2,832
ex
Elixir
test/support/attentive/http/mock.ex
malomohq/attentive-elixir
0bb550b482a1da6e344779aa0d077eacc790f021
[ "MIT" ]
null
null
null
test/support/attentive/http/mock.ex
malomohq/attentive-elixir
0bb550b482a1da6e344779aa0d077eacc790f021
[ "MIT" ]
3
2021-08-06T16:50:58.000Z
2022-02-21T17:18:12.000Z
test/support/attentive/http/mock.ex
malomohq/attentive-elixir
0bb550b482a1da6e344779aa0d077eacc790f021
[ "MIT" ]
null
null
null
defmodule Attentive.Http.Mock do @behaviour Attentive.Http use GenServer @proc_key :__attentive_http_mock__ # # client # def start_link do { :ok, pid } = GenServer.start_link(__MODULE__, :ok) Process.put(@proc_key, pid) { :ok, pid } end def get_request_body do pid = Process.get(@proc_key) GenServer.call(pid, :get_request_body) end def get_request_headers do pid = Process.get(@proc_key) GenServer.call(pid, :get_request_headers) end def get_request_method do pid = Process.get(@proc_key) GenServer.call(pid, :get_request_method) end def get_request_url do pid = Process.get(@proc_key) GenServer.call(pid, :get_request_url) end def put_response(response) do pid = Process.get(@proc_key) GenServer.call(pid, { :put_response, response }) end @impl true def send(request, _opts) do pid = Process.get(@proc_key) :ok = GenServer.call(pid, { :put_request_method, request.method }) :ok = GenServer.call(pid, { :put_request_url, request.url }) :ok = GenServer.call(pid, { :put_request_headers, request.headers }) :ok = GenServer.call(pid, { :put_request_body, request.body }) GenServer.call(pid, :get_response) end # # callbacks # @impl true def init(:ok) do { :ok, %{} } end @impl true def handle_call(:get_request_body, _from, state) do { :reply, Map.fetch!(state, :request_body), state } end @impl true def handle_call(:get_request_headers, _from, state) do { :reply, Map.fetch!(state, :request_headers), state } end @impl true def handle_call(:get_request_method, _from, state) do { :reply, Map.fetch!(state, :request_method), state } end @impl true def handle_call(:get_request_url, _from, state) do { :reply, Map.fetch!(state, :request_url), state } end @impl true def handle_call(:get_response, _from, state) do [h | t] = Map.get(state, :responses, []) { :reply, h, Map.put(state, :responses, t) } end @impl true def handle_call({ :put_request_body, body }, _from, state) do { :reply, :ok, Map.put(state, :request_body, body) } end @impl true def handle_call({ :put_request_headers, headers }, _from, state) do { :reply, :ok, Map.put(state, :request_headers, headers) } end @impl true def handle_call({ :put_request_method, method }, _from, state) do { :reply, :ok, Map.put(state, :request_method, method) } end @impl true def handle_call({ :put_request_url, url }, _from, state) do { :reply, :ok, Map.put(state, :request_url, url) } end @impl true def handle_call({ :put_response, response }, _from, state) do responses = Map.get(state, :responses, []) responses = responses ++ [response] { :reply, :ok, Map.put(state, :responses, responses) } end end
22.47619
72
0.660664
9ece0e90eba7cd57ed5d2bcc5cb08f5ad7ebed22
2,553
ex
Elixir
lib/cotoami_web/controllers/controller_helpers.ex
fmorita/cotoami
e3eb92ad15829f99cf3e8974077f135e789924cf
[ "Apache-2.0" ]
null
null
null
lib/cotoami_web/controllers/controller_helpers.ex
fmorita/cotoami
e3eb92ad15829f99cf3e8974077f135e789924cf
[ "Apache-2.0" ]
null
null
null
lib/cotoami_web/controllers/controller_helpers.ex
fmorita/cotoami
e3eb92ad15829f99cf3e8974077f135e789924cf
[ "Apache-2.0" ]
null
null
null
defmodule CotoamiWeb.ControllerHelpers do @moduledoc """ Utility functions for controllers. """ import Plug.Conn, only: [send_resp: 3] alias Cotoami.{Amishi, Coto, Cotonoma} def send_resp_by_constraint_error(conn, %Ecto.ConstraintError{} = e, content \\ nil) do case e.constraint do "cotonomas_name_owner_id_index" -> send_resp(conn, :conflict, content || "") constraint -> send_resp(conn, :bad_request, content || constraint) end end defp payload_base(%Amishi{} = amishi, client_id) do %{ clientId: client_id, amishi: Phoenix.View.render_one(amishi, CotoamiWeb.AmishiView, "amishi.json") } end defp broadcast(body, topic, event, %Amishi{} = amishi, client_id) do CotoamiWeb.Endpoint.broadcast( topic, event, payload_base(amishi, client_id) |> Map.put(:body, body)) end # # Channel: 'cotonomas:*' # def broadcast_post(%Coto{} = coto, cotonoma_key, %Amishi{} = amishi, client_id) do coto |> Phoenix.View.render_one(CotoamiWeb.CotoView, "coto.json") |> broadcast("cotonomas:#{cotonoma_key}", "post", amishi, client_id) end # # Channel: 'coto:*' # def broadcast_delete(coto_id, %Amishi{} = amishi, client_id) do coto_id |> broadcast("cotos:#{coto_id}", "delete", amishi, client_id) end def broadcast_update(%Coto{} = coto, %Amishi{} = amishi, client_id) do coto |> Phoenix.View.render_one(CotoamiWeb.CotoView, "coto.json") |> broadcast("cotos:#{coto.id}", "update", amishi, client_id) end def broadcast_cotonomatize(%Cotonoma{} = cotonoma, %Amishi{} = amishi, client_id) do cotonoma |> Phoenix.View.render_one(CotoamiWeb.CotonomaView, "cotonoma.json") |> broadcast("cotos:#{cotonoma.coto_id}", "cotonomatize", amishi, client_id) end def broadcast_connect(%Coto{} = start_coto, %Coto{} = end_coto, %Amishi{} = amishi, client_id) do %{ start: Phoenix.View.render_one(start_coto, CotoamiWeb.CotoView, "coto.json"), end: Phoenix.View.render_one(end_coto, CotoamiWeb.CotoView, "coto.json") } |> broadcast("cotos:#{start_coto.id}", "connect", amishi, client_id) end def broadcast_disconnect(start_id, end_id, %Amishi{} = amishi, client_id) do %{startId: start_id, endId: end_id} |> broadcast("cotos:#{start_id}", "disconnect", amishi, client_id) end def broadcast_reorder(start_id, end_ids, %Amishi{} = amishi, client_id) do %{startId: start_id, endIds: end_ids} |> broadcast("cotos:#{start_id}", "reorder", amishi, client_id) end end
32.316456
99
0.674109
9ece4fa5578a1d824fee7d5ecf47c32fa64a3592
35,679
ex
Elixir
lib/zaryn/crypto.ex
ambareesha7/node-zaryn
136e542801bf9b6fa4a015d3464609fdf3dacee8
[ "Apache-2.0" ]
1
2021-07-06T19:47:14.000Z
2021-07-06T19:47:14.000Z
lib/zaryn/crypto.ex
ambareesha7/node-zaryn
136e542801bf9b6fa4a015d3464609fdf3dacee8
[ "Apache-2.0" ]
null
null
null
lib/zaryn/crypto.ex
ambareesha7/node-zaryn
136e542801bf9b6fa4a015d3464609fdf3dacee8
[ "Apache-2.0" ]
null
null
null
defmodule Zaryn.Crypto do @moduledoc ~S""" Provide cryptographic operations for Zaryn network. An algorithm identification is produced by prepending keys and hashes. This identification helps to determine which algorithm/implementation to use in key generation and hashing. Ed25519 Software Public key | / | | | |-------| | | | <<0, 0, 106, 58, 193, 73, 144, 121, 104, 101, 53, 140, 125, 240, 52, 222, 35, 181, 13, 81, 241, 114, 227, 205, 51, 167, 139, 100, 176, 111, 68, 234, 206, 72>> NIST P-256 Software Public key | |-------| | | | |--------------| | | | <<1, 0, 4, 7, 161, 46, 148, 183, 43, 175, 150, 13, 39, 6, 158, 100, 2, 46, 167, 101, 222, 82, 108, 56, 71, 28, 192, 188, 104, 154, 182, 87, 11, 218, 58, 107, 222, 154, 48, 222, 193, 176, 88, 174, 1, 6, 154, 72, 28, 217, 222, 147, 106, 73, 150, 128, 209, 93, 99, 115, 17, 39, 96, 47, 203, 104, 34>> Some functions rely on software implementations such as hashing, signature verification. Other can rely on hardware or software as a configuration choice to generate keys, sign or decrypt data. According to the implementation, keys can be stored and regenerated on the fly """ alias __MODULE__.ECDSA alias __MODULE__.Ed25519 alias __MODULE__.ID alias __MODULE__.NodeKeystore alias __MODULE__.SharedSecretsKeystore alias Zaryn.SharedSecrets alias Zaryn.TransactionChain alias Zaryn.TransactionChain.Transaction alias Zaryn.TransactionChain.Transaction.ValidationStamp alias Zaryn.TransactionChain.TransactionData alias Zaryn.TransactionChain.TransactionData.Keys alias Zaryn.Utils require Logger @typedoc """ List of the supported hash algorithms """ @type supported_hash :: :sha256 | :sha512 | :sha3_256 | :sha3_512 | :blake2b @typedoc """ List of the supported elliptic curves """ @type supported_curve :: :ed25519 | ECDSA.curve() @typedoc """ List of the supported key origins """ @type supported_origin :: :software | :tpm @typedoc """ Binary representing a hash prepend by a single byte to identify the algorithm of the generated hash """ @type versioned_hash :: <<_::8, _::_*8>> @typedoc """ Binary representing a key prepend by two bytes: - to identify the elliptic curve for a key - to identify the origin of the key derivation (software, TPM) """ @type key :: <<_::16, _::_*8>> @typedoc """ Binary representing a AES key on 32 bytes """ @type aes_key :: <<_::256>> @typedoc """ Binary representing an encrypted data using AES authenticated encryption. The binary is split following this rule: - 12 bytes for the IV (Initialization Vector) - 16 bytes for the Authentication tag - The rest for the ciphertext """ @type aes_cipher :: <<_::384, _::_*8>> @certification_public_keys Application.compile_env( :zaryn, [__MODULE__, :root_ca_public_keys], [] ) @doc """ Derive a new keypair from a seed (retrieved from the local keystore and an index representing the number of previous generate keypair. The seed generates a master key and an entropy used in the child keys generation. / (256 bytes) Next private key (256 bytes) Master key --> HMAC-512 / Key: Master entropy, seed --> HASH-512 Data: Master key + index) \ (256 bytes) Master entropy ## Examples iex> {pub, _} = Crypto.derive_keypair("myseed", 1) iex> {pub10, _} = Crypto.derive_keypair("myseed", 10) iex> {pub_bis, _} = Crypto.derive_keypair("myseed", 1) iex> pub != pub10 and pub == pub_bis true """ @spec derive_keypair( seed :: binary(), additional_data :: non_neg_integer() | binary(), curve :: __MODULE__.supported_curve() ) :: {public_key :: key(), private_key :: key()} def derive_keypair( seed, additional_data, curve \\ Application.get_env(:zaryn, __MODULE__)[:default_curve] ) def derive_keypair( seed, index, curve ) when is_binary(seed) and is_integer(index) do seed |> get_extended_seed(<<index::32>>) |> generate_deterministic_keypair(curve) end def derive_keypair( seed, additional_data, curve ) when is_binary(seed) and is_binary(additional_data) do seed |> get_extended_seed(additional_data) |> generate_deterministic_keypair(curve) end @doc """ Retrieve the storage nonce """ @spec storage_nonce() :: binary() def storage_nonce, do: :persistent_term.get(:storage_nonce) @doc """ Generate the address for the beacon chain for a given transaction subset (two first digit of the address) and a date represented as timestamp using the storage nonce The date can be either a specific datetime or a specific day """ @spec derive_beacon_chain_address(subset :: binary(), date :: DateTime.t(), boolean()) :: binary() def derive_beacon_chain_address(subset, date = %DateTime{}, summary? \\ false) when is_binary(subset) do subset |> derive_beacon_keypair(date, summary?) |> elem(0) |> hash() end @doc """ Derive a keypair for beacon transaction based on the subset and the date """ @spec derive_beacon_keypair(binary(), DateTime.t(), boolean()) :: {key(), key()} def derive_beacon_keypair(subset, date = %DateTime{}, summary? \\ false) do summary_byte = if summary?, do: 1, else: 0 derive_keypair( :persistent_term.get(:storage_nonce), hash([subset, <<DateTime.to_unix(date)::32, summary_byte::8>>]) ) end @doc """ Derive a keypair for oracle transactions based on a name and a datetime """ @spec derive_oracle_keypair(DateTime.t()) :: {key(), key()} def derive_oracle_keypair(datetime = %DateTime{}) do derive_keypair( :persistent_term.get(:storage_nonce), hash([<<DateTime.to_unix(datetime)::32>>]) ) end @doc """ Store the encrypted secrets in the keystore by decrypting them with the given secret key """ @spec unwrap_secrets( encrypted_secrets :: binary(), encrypted_secret_key :: binary(), date :: DateTime.t() ) :: :ok | :error def unwrap_secrets(encrypted_secrets, encrypted_key, timestamp = %DateTime{}) when is_binary(encrypted_secrets) and is_binary(encrypted_key) do SharedSecretsKeystore.unwrap_secrets(encrypted_secrets, encrypted_key, timestamp) end @doc """ Store the storage nonce in memory by decrypting it using the last node private key """ @spec decrypt_and_set_storage_nonce(encrypted_nonce :: binary()) :: :ok def decrypt_and_set_storage_nonce(encrypted_nonce) when is_binary(encrypted_nonce) do storage_nonce = ec_decrypt_with_node_key!(encrypted_nonce) storage_nonce_path = storage_nonce_filepath() :ok = File.mkdir_p!(Path.dirname(storage_nonce_path)) :ok = File.write(storage_nonce_path, storage_nonce, [:write]) :ok = :persistent_term.put(:storage_nonce, storage_nonce) Logger.info("Storage nonce stored") end @doc """ Encrypt the storage nonce from memory using the given public key """ @spec encrypt_storage_nonce(key()) :: binary() def encrypt_storage_nonce(public_key) when is_binary(public_key) do ec_encrypt(:persistent_term.get(:storage_nonce), public_key) end @doc """ Encrypt the node shared secrets transaction seed located in the keystore using the given secret key """ @spec wrap_secrets(key :: binary()) :: {enc_transaction_seed :: binary(), enc_network_pool_seed :: binary()} defdelegate wrap_secrets(aes_key), to: SharedSecretsKeystore defp get_extended_seed(seed, additional_data) do <<master_key::binary-32, master_entropy::binary-32>> = :crypto.hash(:sha512, seed) <<extended_pv::binary-32, _::binary-32>> = :crypto.mac(:hmac, :sha512, master_entropy, <<master_key::binary, additional_data::binary>>) extended_pv end @doc """ Return the last node public key """ @spec last_node_public_key() :: key() defdelegate last_node_public_key, to: NodeKeystore, as: :last_public_key @doc """ Return the previous node public key """ defdelegate previous_node_public_key, to: NodeKeystore, as: :previous_public_key @doc """ Return the first node public key """ @spec first_node_public_key() :: key() defdelegate first_node_public_key, to: NodeKeystore, as: :first_public_key @doc """ Return the next node public key """ @spec next_node_public_key() :: key() defdelegate next_node_public_key, to: NodeKeystore, as: :next_public_key @doc """ Return the the node shared secrets public key using the node shared secret transaction seed """ @spec node_shared_secrets_public_key(index :: number()) :: key() defdelegate node_shared_secrets_public_key(index), to: SharedSecretsKeystore @doc """ Return the the network pool public key using the network pool transaction seed """ @spec network_pool_public_key(index :: number()) :: key() defdelegate network_pool_public_key(index), to: SharedSecretsKeystore @doc """ Return the storage nonce public key """ @spec storage_nonce_public_key() :: binary() def storage_nonce_public_key do {pub, _} = derive_keypair(:persistent_term.get(:storage_nonce), 0) pub end @doc """ Decrypt a cipher using the storage nonce public key using an authenticated encryption (ECIES). More details at `ec_decrypt/2` """ @spec ec_decrypt_with_storage_nonce(iodata()) :: {:ok, binary()} | {:error, :decryption_failed} def ec_decrypt_with_storage_nonce(data) when is_bitstring(data) or is_list(data) do {_, pv} = derive_keypair(:persistent_term.get(:storage_nonce), 0) ec_decrypt(data, pv) end @doc """ Return the number of node shared secrets keys after incrementation """ @spec number_of_node_shared_secrets_keys() :: non_neg_integer() defdelegate number_of_node_shared_secrets_keys, to: SharedSecretsKeystore, as: :get_node_shared_key_index @doc """ Return the number of network pool keys after incrementation """ @spec number_of_network_pool_keys() :: non_neg_integer() defdelegate number_of_network_pool_keys, to: SharedSecretsKeystore, as: :get_network_pool_key_index @doc """ Generate a keypair in a deterministic way using a seed ## Examples iex> {pub, _} = Crypto.generate_deterministic_keypair("myseed") iex> pub <<0, 0, 91, 43, 89, 132, 233, 51, 190, 190, 189, 73, 102, 74, 55, 126, 44, 117, 50, 36, 220, 249, 242, 73, 105, 55, 83, 190, 3, 75, 113, 199, 247, 165>> iex> {pub, _} = Crypto.generate_deterministic_keypair("myseed", :secp256r1) iex> pub <<1, 0, 4, 140, 235, 188, 198, 146, 160, 92, 132, 81, 177, 113, 230, 39, 220, 122, 112, 231, 18, 90, 66, 156, 47, 54, 192, 141, 44, 45, 223, 115, 28, 30, 48, 105, 253, 171, 105, 87, 148, 108, 150, 86, 128, 28, 102, 163, 51, 28, 57, 33, 133, 109, 49, 202, 92, 184, 138, 187, 26, 123, 45, 5, 94, 180, 250>> """ @spec generate_deterministic_keypair( seed :: binary(), curve :: supported_curve() ) :: {public_key :: key(), private_key :: key()} def generate_deterministic_keypair( seed, curve \\ Application.get_env(:zaryn, __MODULE__)[:default_curve] ) when is_binary(seed) do do_generate_deterministic_keypair(curve, seed) end defp do_generate_deterministic_keypair(:ed25519, seed) do seed |> Ed25519.generate_keypair() |> ID.prepend_keypair(:ed25519) end defp do_generate_deterministic_keypair(curve, seed) do curve |> ECDSA.generate_keypair(seed) |> ID.prepend_keypair(curve) end @doc """ Generate random keypair """ @spec generate_random_keypair(supported_curve()) :: {public_key :: key(), private_key :: key()} def generate_random_keypair(curve \\ Application.get_env(:zaryn, __MODULE__)[:default_curve]) do generate_deterministic_keypair(:crypto.strong_rand_bytes(32), curve) end @doc """ Sign data. The first byte of the private key identifies the curve and the signature algorithm to use ## Examples iex> {_pub, pv} = Crypto.generate_deterministic_keypair("myseed") iex> Crypto.sign("myfakedata", pv) <<220, 110, 7, 254, 119, 249, 124, 5, 24, 45, 224, 214, 60, 49, 223, 238, 47, 58, 91, 108, 33, 18, 230, 144, 178, 191, 236, 235, 188, 32, 224, 129, 47, 18, 216, 220, 32, 82, 252, 20, 55, 2, 204, 94, 73, 37, 44, 220, 33, 26, 44, 124, 20, 44, 255, 249, 77, 201, 97, 108, 213, 107, 134, 9>> """ @spec sign(data :: iodata(), private_key :: binary()) :: signature :: binary() def sign(data, _private_key = <<curve_id::8, _::8, key::binary>>) when is_bitstring(data) or is_list(data) do curve_id |> ID.to_curve() |> do_sign(Utils.wrap_binary(data), key) end defp do_sign(:ed25519, data, key), do: Ed25519.sign(key, data) defp do_sign(curve, data, key), do: ECDSA.sign(curve, key, data) @doc """ Sign the data with the last node private key """ @spec sign_with_last_node_key(data :: iodata() | bitstring() | [bitstring]) :: binary() def sign_with_last_node_key(data) when is_bitstring(data) or is_list(data) do data |> Utils.wrap_binary() |> NodeKeystore.sign_with_last_key() end @doc """ Sign with the previous node key """ @spec sign_with_previous_node_key(data :: iodata() | bitstring() | [bitstring]) :: binary() def sign_with_previous_node_key(data) when is_bitstring(data) or is_list(data) do data |> Utils.wrap_binary() |> NodeKeystore.sign_with_previous_key() end @doc """ Sign the data with the first node private key """ def sign_with_first_node_key(data) do data |> Utils.wrap_binary() |> NodeKeystore.sign_with_first_key() end @doc """ Sign the data with the node shared secrets transaction seed """ @spec sign_with_node_shared_secrets_key(data :: iodata()) :: binary() def sign_with_node_shared_secrets_key(data) when is_bitstring(data) or is_list(data) do data |> Utils.wrap_binary() |> SharedSecretsKeystore.sign_with_node_shared_secrets_key() end @doc """ Sign the data with the node shared secrets transaction seed """ @spec sign_with_node_shared_secrets_key(data :: iodata(), index :: non_neg_integer()) :: binary() def sign_with_node_shared_secrets_key(data, index) when (is_bitstring(data) or is_list(data)) and is_integer(index) and index >= 0 do data |> Utils.wrap_binary() |> SharedSecretsKeystore.sign_with_node_shared_secrets_key(index) end @doc """ Sign the data with the network pool transaction seed """ @spec sign_with_network_pool_key(data :: iodata()) :: binary() def sign_with_network_pool_key(data) when is_bitstring(data) or is_list(data) do data |> Utils.wrap_binary() |> SharedSecretsKeystore.sign_with_network_pool_key() end @doc """ Sign the data with the network pool transaction seed """ @spec sign_with_network_pool_key(data :: iodata(), index :: non_neg_integer()) :: binary() def sign_with_network_pool_key(data, index) when (is_bitstring(data) or is_list(data)) and is_integer(index) and index >= 0 do data |> Utils.wrap_binary() |> SharedSecretsKeystore.sign_with_network_pool_key(index) end @doc """ Sign data with the daily nonce stored in the keystore """ @spec sign_with_daily_nonce_key(data :: iodata(), DateTime.t()) :: binary() defdelegate sign_with_daily_nonce_key(data, timestamp), to: SharedSecretsKeystore @doc """ Verify a signature. The first byte of the public key identifies the curve and the verification algorithm to use. ## Examples iex> {pub, pv} = Crypto.generate_deterministic_keypair("myseed") iex> sig = Crypto.sign("myfakedata", pv) iex> Crypto.verify?(sig, "myfakedata", pub) true Returns false when the signature is invalid iex> {pub, _} = Crypto.generate_deterministic_keypair("myseed") iex> sig = <<1, 48, 69, 2, 33, 0, 185, 231, 7, 86, 207, 253, 8, 230, 199, 94, 251, 33, 42, 172, 95, 93, 7, 209, 175, 69, 216, 121, 239, 24, 17, 21, 41, 129, 255, 49, 153, 116, 2, 32, 85, 1, 212, 69, 182, 98, 174, 213, 79, 154, 69, 84, 149, 126, 169, 44, 98, 64, 21, 211, 20, 235, 165, 97, 61, 8, 239, 194, 196, 177, 46, 199>> iex> Crypto.verify?(sig, "myfakedata", pub) false """ @spec verify?( signature :: binary(), data :: iodata() | bitstring() | [bitstring], public_key :: key() ) :: boolean() def verify?( sig, data, <<curve_id::8, _::8, key::binary>> = _public_key ) when is_bitstring(data) or is_list(data) do curve_id |> ID.to_curve() |> do_verify?(key, Utils.wrap_binary(data), sig) end defp do_verify?(:ed25519, key, data, sig), do: Ed25519.verify?(key, data, sig) defp do_verify?(curve, key, data, sig), do: ECDSA.verify?(curve, key, data, sig) @doc """ Encrypts data using public key authenticated encryption (ECIES). Ephemeral and random ECDH key pair is generated which is used to generate shared secret with the given public key(transformed to ECDH public key). Based on this secret, KDF derive keys are used to create an authenticated symmetric encryption. ## Examples ``` {pub, _} = Crypto.generate_deterministic_keypair("myseed") Crypto.ec_encrypt("myfakedata", pub) <<20, 95, 27, 87, 71, 195, 100, 164, 225, 201, 163, 220, 15, 111, 201, 224, 41, 34, 143, 78, 201, 109, 157, 196, 108, 109, 155, 91, 239, 118, 23, 100, 161, 195, 39, 117, 148, 223, 182, 23, 1, 197, 205, 93, 239, 19, 27, 248, 168, 107, 40, 0, 68, 224, 177, 110, 180, 24>> ``` """ @spec ec_encrypt(message :: binary(), public_key :: key()) :: binary() def ec_encrypt(message, <<curve_id::8, _::8, public_key::binary>> = _public_key) when is_binary(message) do curve = ID.to_curve(curve_id) {ephemeral_public_key, ephemeral_private_key} = generate_ephemeral_encryption_keys(curve) # Derivate secret using ECDH with the given public key and the ephemeral private key shared_key = case curve do :ed25519 -> x25519_pk = Ed25519.convert_to_x25519_public_key(public_key) :crypto.compute_key(:ecdh, x25519_pk, ephemeral_private_key, :x25519) _ -> :crypto.compute_key(:ecdh, public_key, ephemeral_private_key, curve) end # Generate keys for the AES authenticated encryption {iv, aes_key} = derivate_secrets(shared_key) {cipher, tag} = aes_auth_encrypt(iv, aes_key, message) # Encode the cipher within the ephemeral public key, the authentication tag <<ephemeral_public_key::binary, tag::binary, cipher::binary>> end defp generate_ephemeral_encryption_keys(:ed25519), do: :crypto.generate_key(:ecdh, :x25519) defp generate_ephemeral_encryption_keys(curve), do: :crypto.generate_key(:ecdh, curve) defp derivate_secrets(dh_key) do pseudorandom_key = :crypto.hash(:sha256, dh_key) iv = binary_part(:crypto.mac(:hmac, :sha256, pseudorandom_key, "0"), 0, 32) aes_key = binary_part(:crypto.mac(:hmac, :sha256, iv, "1"), 0, 32) {iv, aes_key} end defp aes_auth_encrypt(iv, key, data), do: :crypto.crypto_one_time_aead(:aes_256_gcm, key, iv, data, "", true) defp aes_auth_decrypt(iv, key, cipher, tag), do: :crypto.crypto_one_time_aead(:aes_256_gcm, key, iv, cipher, "", tag, false) @doc """ Decrypt a cipher using public key authenticated encryption (ECIES). A cipher contains a generated ephemeral random public key coupled with an authentication tag. Private key is transformed to ECDH to compute a shared secret with this random public key. Based on this secret, KDF derive keys are used to create an authenticated symmetric decryption. Before the decryption, the authentication will be checked to ensure the given private key has the right to decrypt this data. ## Examples iex> cipher = <<20, 95, 27, 87, 71, 195, 100, 164, 225, 201, 163, 220, 15, 111, 201, 224, 41, ...> 34, 143, 78, 201, 109, 157, 196, 108, 109, 155, 91, 239, 118, 23, 100, 161, ...> 195, 39, 117, 148, 223, 182, 23, 1, 197, 205, 93, 239, 19, 27, 248, 168, 107, ...> 40, 0, 68, 224, 177, 110, 180, 24>> iex> {_pub, pv} = Crypto.generate_deterministic_keypair("myseed") iex> Zaryn.Crypto.ec_decrypt!(cipher, pv) "myfakedata" Invalid message to decrypt or key return an error: ``` iex> cipher = <<20, 95, 27, 87, 71, 195, 100, 164, 225, 201, 163, 220, 15, 111, 201, 224, 41, ...> 34, 143, 78, 201, 109, 157, 196, 108, 109, 155, 91, 239, 118, 23, 100, 161, ...> 195, 39, 117, 148, 223, 182, 23, 1, 197, 205, 93, 239, 19, 27, 248, 168, 107, ...> 40, 0, 68, 224, 177, 110, 180, 24>> iex> {_, pv} = Crypto.generate_deterministic_keypair("otherseed") iex> Crypto.ec_decrypt!(cipher, pv) ** (RuntimeError) Decryption failed ``` """ @spec ec_decrypt!(encoded_cipher :: binary(), private_key :: key()) :: binary() def ec_decrypt!(encoded_cipher, private_key) when is_binary(encoded_cipher) and is_binary(private_key) do case ec_decrypt(encoded_cipher, private_key) do {:error, :decryption_failed} -> raise "Decryption failed" {:ok, data} -> data end end @doc """ ## Examples iex> cipher = <<20, 95, 27, 87, 71, 195, 100, 164, 225, 201, 163, 220, 15, 111, 201, 224, 41, ...> 34, 143, 78, 201, 109, 157, 196, 108, 109, 155, 91, 239, 118, 23, 100, 161, ...> 195, 39, 117, 148, 223, 182, 23, 1, 197, 205, 93, 239, 19, 27, 248, 168, 107, ...> 40, 0, 68, 224, 177, 110, 180, 24>> iex> {_pub, pv} = Crypto.generate_deterministic_keypair("myseed") iex> {:ok, "myfakedata"} = Crypto.ec_decrypt(cipher, pv) Invalid message to decrypt return an error: iex> cipher = <<20, 95, 27, 87, 71, 195, 100, 164, 225, 201, 163, 220, 15, 111, 201, 224, 41, ...> 34, 143, 78, 201, 109, 157, 196, 108, 109, 155, 91, 239, 118, 23, 100, 161, ...> 195, 39, 117, 148, 223, 182, 23, 1, 197, 205, 93, 239, 19, 27, 248, 168, 107, ...> 40, 0, 68, 224, 177, 110, 180, 24>> iex> {_, pv} = Crypto.generate_deterministic_keypair("otherseed") iex> Crypto.ec_decrypt(cipher, pv) {:error, :decryption_failed} """ @spec ec_decrypt(cipher :: binary(), private_key :: key()) :: {:ok, binary()} | {:error, :decryption_failed} def ec_decrypt( encoded_cipher, _private_key = <<curve_id::8, _::8, private_key::binary>> ) when is_binary(encoded_cipher) do key_size = key_size(curve_id) <<ephemeral_public_key::binary-size(key_size), tag::binary-16, cipher::binary>> = encoded_cipher # Derivate shared key using ECDH with the given ephermal public key and the private key shared_key = case ID.to_curve(curve_id) do :ed25519 -> x25519_sk = Ed25519.convert_to_x25519_private_key(private_key) :crypto.compute_key(:ecdh, ephemeral_public_key, x25519_sk, :x25519) curve -> :crypto.compute_key(:ecdh, ephemeral_public_key, private_key, curve) end # Generate keys for the AES authenticated decryption {iv, aes_key} = derivate_secrets(shared_key) case aes_auth_decrypt(iv, aes_key, cipher, tag) do :error -> {:error, :decryption_failed} data -> {:ok, data} end end @doc """ Decrypt the cipher using last node private key """ @spec ec_decrypt_with_node_key!(cipher :: binary()) :: term() def ec_decrypt_with_node_key!(cipher) do case ec_decrypt_with_node_key(cipher) do {:ok, data} -> data _ -> raise "Decrypted failed" end end @doc """ Decrypt the cipher using last node private key """ @spec ec_decrypt_with_node_key(cipher :: binary()) :: {:ok, term()} | {:error, :decryption_failed} def ec_decrypt_with_node_key(encoded_cipher) when is_binary(encoded_cipher) do <<curve_id::8, _::8, _::binary>> = NodeKeystore.last_public_key() key_size = key_size(curve_id) <<ephemeral_public_key::binary-size(key_size), tag::binary-16, cipher::binary>> = encoded_cipher # Derivate shared key using ECDH with the given ephermal public key and the node's private key shared_key = NodeKeystore.diffie_hellman(ephemeral_public_key) # Generate keys for the AES authenticated decryption {iv, aes_key} = derivate_secrets(shared_key) case aes_auth_decrypt(iv, aes_key, cipher, tag) do :error -> {:error, :decryption_failed} data -> {:ok, data} end end @doc """ Encrypt a data using AES authenticated encryption. """ @spec aes_encrypt(data :: iodata(), key :: iodata()) :: aes_cipher def aes_encrypt(data, _key = <<key::binary-32>>) when is_binary(data) do iv = :crypto.strong_rand_bytes(12) {cipher, tag} = :crypto.crypto_one_time_aead(:aes_256_gcm, key, iv, data, "", true) <<iv::binary-size(12), tag::binary-size(16), cipher::binary>> end @doc """ Decrypt a ciphertext using the AES authenticated decryption. ## Examples iex> key = <<234, 210, 202, 129, 91, 76, 68, 14, 17, 212, 197, 49, 66, 168, 52, 111, 176, ...> 182, 227, 156, 5, 32, 24, 105, 41, 152, 67, 191, 187, 209, 101, 36>> iex> ciphertext = Crypto.aes_encrypt("sensitive data", key) iex> Crypto.aes_decrypt(ciphertext, key) {:ok, "sensitive data"} Return an error when the key is invalid iex> ciphertext = Crypto.aes_encrypt("sensitive data", :crypto.strong_rand_bytes(32)) iex> Crypto.aes_decrypt(ciphertext, :crypto.strong_rand_bytes(32)) {:error, :decryption_failed} """ @spec aes_decrypt(_encoded_cipher :: aes_cipher, key :: binary) :: {:ok, term()} | {:error, :decryption_failed} def aes_decrypt( _encoded_cipher = <<iv::binary-12, tag::binary-16, cipher::binary>>, <<key::binary-32>> ) do case :crypto.crypto_one_time_aead( :aes_256_gcm, key, iv, cipher, "", tag, false ) do :error -> {:error, :decryption_failed} data -> {:ok, data} end end @doc """ Decrypt a ciphertext using the AES authenticated decryption. ## Examples iex> key = <<234, 210, 202, 129, 91, 76, 68, 14, 17, 212, 197, 49, 66, 168, 52, 111, 176, ...> 182, 227, 156, 5, 32, 24, 105, 41, 152, 67, 191, 187, 209, 101, 36>> iex> ciphertext = Crypto.aes_encrypt("sensitive data", key) iex> Crypto.aes_decrypt!(ciphertext, key) "sensitive data" Return an error when the key is invalid ``` ciphertext = Crypto.aes_encrypt("sensitive data", :crypto.strong_rand_bytes(32)) Crypto.aes_decrypt!(ciphertext, :crypto.strong_rand_bytes(32)) ** (RuntimeError) Decryption failed ``` """ @spec aes_decrypt!(encoded_cipher :: aes_cipher, key :: binary) :: term() def aes_decrypt!(encoded_cipher, key) when is_binary(encoded_cipher) and is_binary(key) do case aes_decrypt(encoded_cipher, key) do {:ok, data} -> data {:error, :decryption_failed} -> raise "Decryption failed" end end @doc """ Hash a data. A first-byte prepends each hash to indicate the algorithm used. ## Examples iex> Crypto.hash("myfakedata", :sha256) <<0, 78, 137, 232, 16, 150, 235, 9, 199, 74, 41, 189, 246, 110, 65, 252, 17, 139, 109, 23, 172, 84, 114, 35, 202, 102, 41, 167, 23, 36, 230, 159, 35>> iex> Crypto.hash("myfakedata", :blake2b) <<4, 244, 16, 24, 144, 16, 67, 113, 164, 214, 115, 237, 113, 126, 130, 76, 128, 99, 78, 223, 60, 179, 158, 62, 239, 245, 85, 4, 156, 10, 2, 94, 95, 19, 166, 170, 147, 140, 117, 1, 169, 132, 113, 202, 217, 193, 56, 112, 193, 62, 134, 145, 233, 114, 41, 228, 164, 180, 225, 147, 2, 33, 192, 42, 184>> iex> Crypto.hash("myfakedata", :sha3_256) <<2, 157, 219, 54, 234, 186, 251, 4, 122, 216, 105, 185, 228, 211, 94, 44, 94, 104, 147, 182, 189, 45, 28, 219, 218, 236, 19, 66, 87, 121, 240, 249, 218>> """ @spec hash(data :: iodata(), algo :: supported_hash()) :: versioned_hash() def hash(data, algo \\ Application.get_env(:zaryn, __MODULE__)[:default_hash]) def hash(data, algo) when is_bitstring(data) or is_list(data) do data |> Utils.wrap_binary() |> do_hash(algo) |> ID.prepend_hash(algo) end defp do_hash(data, :sha256), do: :crypto.hash(:sha256, data) defp do_hash(data, :sha512), do: :crypto.hash(:sha512, data) defp do_hash(data, :sha3_256), do: :crypto.hash(:sha3_256, data) defp do_hash(data, :sha3_512), do: :crypto.hash(:sha3_512, data) defp do_hash(data, :blake2b), do: :crypto.hash(:blake2b, data) @doc """ Hash the data using the storage nonce stored in memory """ @spec hash_with_storage_nonce(data :: iodata()) :: binary() def hash_with_storage_nonce(data) when is_binary(data) or is_list(data) do hash([:persistent_term.get(:storage_nonce), data]) end @doc """ Return the size of key using the curve id ## Examples iex> Crypto.key_size(ID.from_curve(:ed25519)) 32 iex> Crypto.key_size(ID.from_curve(:secp256r1)) 65 iex> Crypto.key_size(ID.from_curve(:secp256k1)) 65 """ @spec key_size(curve_id :: 0 | 1 | 2) :: 32 | 65 def key_size(0), do: 32 def key_size(1), do: 65 def key_size(2), do: 65 @doc """ Determine if a public key is valid """ @spec valid_public_key?(binary()) :: boolean() def valid_public_key?(<<0::8, _::8, _::binary-size(32)>>), do: true def valid_public_key?(<<1::8, _::8, _::binary-size(65)>>), do: true def valid_public_key?(<<2::8, _::8, _::binary-size(65)>>), do: true def valid_public_key?(_), do: false @doc """ Return the size of hash using the algorithm id ## Examples iex> Crypto.hash_size(ID.from_hash(:sha256)) 32 iex> Crypto.hash_size(ID.from_hash(:sha512)) 64 iex> Crypto.hash_size(ID.from_hash(:sha3_256)) 32 iex> Crypto.hash_size(ID.from_hash(:sha3_512)) 64 iex> Crypto.hash_size(ID.from_hash(:blake2b)) 64 """ @spec hash_size(hash_algo_id :: 0 | 1 | 2 | 3 | 4) :: 32 | 64 def hash_size(0), do: 32 def hash_size(1), do: 64 def hash_size(2), do: 32 def hash_size(3), do: 64 def hash_size(4), do: 64 @doc """ Determine if a hash is valid """ @spec valid_hash?(binary()) :: boolean() def valid_hash?(<<0::8, _::binary-size(32)>>), do: true def valid_hash?(<<1::8, _::binary-size(64)>>), do: true def valid_hash?(<<2::8, _::binary-size(32)>>), do: true def valid_hash?(<<3::8, _::binary-size(64)>>), do: true def valid_hash?(<<4::8, _::binary-size(64)>>), do: true def valid_hash?(_), do: false @doc """ Load the transaction for the Keystore indexing """ @spec load_transaction(Transaction.t()) :: :ok def load_transaction(%Transaction{ address: address, type: :node_shared_secrets, data: %TransactionData{keys: keys = %Keys{secret: secret}}, validation_stamp: %ValidationStamp{ timestamp: timestamp } }) do nb_transactions = TransactionChain.size(address) SharedSecretsKeystore.set_node_shared_secrets_key_index(nb_transactions) if Keys.authorized_key?(keys, last_node_public_key()) do encrypted_secret_key = Keys.get_encrypted_key(keys, last_node_public_key()) daily_nonce_date = SharedSecrets.next_application_date(timestamp) unwrap_secrets(secret, encrypted_secret_key, daily_nonce_date) else :ok end end def load_transaction(%Transaction{type: :node_rewards, address: address}) do nb_transactions = TransactionChain.size(address) SharedSecretsKeystore.set_network_pool_key_index(nb_transactions) end def load_transaction(%Transaction{type: :node, address: address}) do if NodeKeystore.next_public_key() |> hash() == address do NodeKeystore.persist_next_keypair() else :ok end end def load_transaction(_), do: :ok @doc """ Return the storage nonce filepath """ @spec storage_nonce_filepath() :: binary() def storage_nonce_filepath do rel_filepath = Application.get_env(:zaryn, __MODULE__) |> Keyword.fetch!(:storage_nonce_file) Utils.mut_dir(rel_filepath) end @doc """ Determine the origin of the key from an ID """ @spec key_origin(non_neg_integer()) :: supported_origin() defdelegate key_origin(origin), to: ID, as: :to_origin @spec get_key_certificate(key()) :: binary() def get_key_certificate(<<_::8, origin_id::8, key::binary>>) do origin_id |> ID.to_origin() |> do_get_key_certificate(key) end defp do_get_key_certificate(:software, _) do "" end defp do_get_key_certificate(:tpm, key) do key_digest = :crypto.hash(:sha256, key) |> Base.encode16(case: :lower) cert_path = [ Application.get_env(:zaryn, __MODULE__) |> Keyword.fetch!(:key_certificates_dir), "#{key_digest}.bin" ] |> Path.join() |> Path.expand() case File.read(cert_path) do {:ok, data} -> data _ -> "" end end @doc """ Return the Root CA public key for the given versioned public key """ @spec get_root_ca_public_key(key()) :: binary() def get_root_ca_public_key(<<_::8, origin_id::8, _::binary>>) do origin = ID.to_origin(origin_id) case Keyword.get(@certification_public_keys, origin) do nil -> "" "" -> "" <<_::binary-size(26), public_key::binary>> -> public_key end end @doc """ Determine if the public key if authorized from the given certificate ## Examples iex> Crypto.verify_key_certificate?( ...> <<0, 0, 241, 101, 225, 229, 247, 194, 144, 229, 47, 46, 222, 243, 251, 171, 96, ...> 203, 174, 116, 191, 211, 39, 79, 142, 94, 225, 222, 51, 69, 201, 84, 161, 102>>, ...> <<48, 68, 2, 32, 90, 47, 10, 125, 165, 179, 88, 67, 83, 56, 55, 240, 78, 168, ...> 241, 104, 124, 212, 13, 10, 30, 80, 2, 170, 174, 8, 129, 205, 30, 40, 7, 196, ...> 2, 32, 27, 21, 21, 174, 186, 126, 63, 184, 50, 195, 46, 118, 188, 2, 112, 214, ...> 196, 121, 250, 48, 223, 110, 152, 189, 231, 137, 152, 25, 78, 29, 76, 191>>, ...> <<4, 210, 136, 107, 189, 140, 118, 86, 124, 217, 244, 69, 111, 61, 56, 224, 56, 150, 230, ...> 194, 203, 81, 213, 212, 220, 19, 1, 180, 114, 44, 230, 149, 21, 125, 69, 206, 32, 173, ...> 186, 81, 243, 58, 13, 198, 129, 169, 33, 179, 201, 50, 49, 67, 38, 156, 38, 199, 97, 59, ...> 70, 95, 28, 35, 233, 21, 230>>) true """ @spec verify_key_certificate?(key(), binary(), binary()) :: boolean() def verify_key_certificate?(_, _, ""), do: true def verify_key_certificate?(<<_::8, origin_id::8, key::binary>>, certificate, root_ca_key) when is_binary(certificate) and is_binary(root_ca_key) do case ID.to_origin(origin_id) do :tpm -> ECDSA.verify?(:secp256r1, root_ca_key, key, certificate) :software -> true end end end
34.109943
331
0.642086
9ece7268964b2c0c076f242b02ce0547e2d87e22
109
ex
Elixir
test/support/postgrex_types.ex
kianmeng/geo_postgis
6550ac3e7b14dbcdf46a5451fec2b19e0277eb6a
[ "MIT" ]
220
2017-07-15T22:20:31.000Z
2022-03-30T22:22:57.000Z
test/support/postgrex_types.ex
kianmeng/geo_postgis
6550ac3e7b14dbcdf46a5451fec2b19e0277eb6a
[ "MIT" ]
100
2017-09-09T19:40:47.000Z
2022-03-23T12:26:56.000Z
test/support/postgrex_types.ex
kianmeng/geo_postgis
6550ac3e7b14dbcdf46a5451fec2b19e0277eb6a
[ "MIT" ]
60
2017-08-10T10:05:39.000Z
2022-01-25T21:53:25.000Z
Postgrex.Types.define( Geo.PostGIS.PostgrexTypes, [Geo.PostGIS.Extension], decode_binary: :reference )
18.166667
28
0.761468
9ece970d229d522c19b1cf3f4404dcbbe88e0a55
1,496
exs
Elixir
chapter5/challenges/jwtchallenge/config/config.exs
mCodex/rocketseat-ignite-elixir
bdb48db778c36b2325c75a41b4d6f7ef77b03cf5
[ "MIT" ]
1
2021-07-23T19:48:27.000Z
2021-07-23T19:48:27.000Z
chapter5/challenges/jwtchallenge/config/config.exs
mCodex/rocketseat-ignite-elixir
bdb48db778c36b2325c75a41b4d6f7ef77b03cf5
[ "MIT" ]
null
null
null
chapter5/challenges/jwtchallenge/config/config.exs
mCodex/rocketseat-ignite-elixir
bdb48db778c36b2325c75a41b4d6f7ef77b03cf5
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. # # This configuration file is loaded before any dependency and # is restricted to this project. # General application configuration use Mix.Config config :jwtchallenge, ecto_repos: [Jwtchallenge.Repo] config :jwtchallenge, Jwtchallenge.Repo, migration_primary_key: [type: :binary_id], migration_foreign_key: [type: :binary_id] config :jwtchallenge, JwtchallengeWeb.Auth.Guardian, issuer: "jwtchallenge", secret_key: "aMlzjAV4CxqmfaPZqNtvNP18YsjScNfmpC2gEKW8HepBbGHJZg3QoeTLxMT/Xn9c" config :jwtchallenge, JwtchallengeWeb.Auth.Pipeline, module: JwtchallengeWeb.Auth.Guardian, error_handler: JwtchallengeWeb.Auth.ErrorHandler # Configures the endpoint config :jwtchallenge, JwtchallengeWeb.Endpoint, url: [host: "localhost"], secret_key_base: "vN+Z+GzAhikYlco0Wy1x/4IKBC1BOP9+eMHlSnmlCM25WKxUCn71E8kWWm5NZa6U", render_errors: [view: JwtchallengeWeb.ErrorView, accepts: ~w(json), layout: false], pubsub_server: Jwtchallenge.PubSub, live_view: [signing_salt: "XZsIdleh"] # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:request_id] # Use Jason for JSON parsing in Phoenix config :phoenix, :json_library, Jason # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. import_config "#{Mix.env()}.exs"
34
86
0.788102
9eceb14c0433152feda05d3024783cb3388eebe7
8,245
ex
Elixir
lib/vintage_net_wizard/backend_server.ex
jfcloutier/vintage_net_wizard
be8806a6de9d528c6560a1d3e49dad1380f1499d
[ "Apache-2.0" ]
null
null
null
lib/vintage_net_wizard/backend_server.ex
jfcloutier/vintage_net_wizard
be8806a6de9d528c6560a1d3e49dad1380f1499d
[ "Apache-2.0" ]
null
null
null
lib/vintage_net_wizard/backend_server.ex
jfcloutier/vintage_net_wizard
be8806a6de9d528c6560a1d3e49dad1380f1499d
[ "Apache-2.0" ]
null
null
null
defmodule VintageNetWizard.BackendServer do @moduledoc """ Server for managing a VintageNet.Backend implementation """ use GenServer alias VintageNetWizard.WiFiConfiguration alias VintageNetWiFi.AccessPoint defmodule State do @moduledoc false defstruct subscriber: nil, backend: nil, backend_state: nil, configurations: [] end @spec start_link(backend :: module()) :: GenServer.on_start() def start_link(backend) do GenServer.start_link(__MODULE__, backend, name: __MODULE__) end @doc """ Subscribe to messages from the backend """ @spec subscribe() :: :ok def subscribe() do GenServer.cast(__MODULE__, {:subscribe, self()}) end @doc """ Return information about the device for the web page's footer """ @spec device_info() :: [{String.t(), String.t()}] def device_info() do GenServer.call(__MODULE__, :device_info) end @doc """ Delete the configuration by `ssid` """ @spec delete_configuration(String.t()) :: :ok def delete_configuration(ssid) do GenServer.call(__MODULE__, {:delete_configuration, ssid}) end @doc """ List out access points """ @spec access_points() :: [AccessPoint.t()] def access_points() do GenServer.call(__MODULE__, :access_points) end @doc """ Pass list of SSIDs (`priority_order`), sort the configurations to match that order. """ @spec set_priority_order([String.t()]) :: :ok def set_priority_order(priority_order) do GenServer.call(__MODULE__, {:set_priority_order, priority_order}) end @doc """ Get the current state of the WiFi configuration """ @spec configuration_state() :: %State{} def configuration_state() do GenServer.call(__MODULE__, :configuration_state) end @doc """ Start scanning for WiFi access points """ @spec start_scan() :: :ok def start_scan() do GenServer.call(__MODULE__, :start_scan) end @doc """ Stop scanning for WiFi access points """ @spec stop_scan() :: :ok def stop_scan() do GenServer.call(__MODULE__, :stop_scan) end @doc """ Save a `WiFiConfiguration` to the backend """ @spec save(WiFiConfiguration.t()) :: :ok | {:error, any()} def save(config) do GenServer.call(__MODULE__, {:save, config}) end @doc """ Get a list of the current configurations """ @spec configurations() :: [WiFiConfiguration.t()] def configurations() do GenServer.call(__MODULE__, :configurations) end @doc """ Get the current configuration status """ def configuration_status() do GenServer.call(__MODULE__, :configuration_status) end @doc """ Apply the configurations saved in the backend to the system. """ @spec apply() :: :ok | {:error, :no_configurations} def apply() do GenServer.call(__MODULE__, :apply) end @doc """ Reset the backend to an initial default state. """ @spec reset() :: :ok def reset() do GenServer.call(__MODULE__, :reset) end @doc """ """ @spec complete() :: :ok def complete() do GenServer.call(__MODULE__, :complete) end @impl true def init(backend) do {:ok, %State{ configurations: %{}, backend: backend, backend_state: apply(backend, :init, []) }} end @impl true def handle_call( :access_points, _from, %State{backend: backend, backend_state: backend_state} = state ) do access_points = apply(backend, :access_points, [backend_state]) {:reply, access_points, state} end def handle_call( :start_scan, _from, %State{backend: backend, backend_state: backend_state} = state ) do new_backend_state = apply(backend, :start_scan, [backend_state]) {:reply, :ok, %{state | backend_state: new_backend_state}} end def handle_call( :stop_scan, _from, %State{backend: backend, backend_state: backend_state} = state ) do new_backend_state = apply(backend, :stop_scan, [backend_state]) {:reply, :ok, %{state | backend_state: new_backend_state}} end def handle_call( {:set_priority_order, priority_order}, _from, %State{configurations: configurations} = state ) do indexed_priority_order = Enum.with_index(priority_order) new_configurations = Enum.map(configurations, fn {ssid, config} -> priority = get_priority_for_ssid(indexed_priority_order, ssid) {ssid, %{config | priority: priority}} end) |> Enum.into(%{}) {:reply, :ok, %{state | configurations: new_configurations}} end def handle_call( :configuration_status, _from, %State{backend: backend, backend_state: backend_state} = state ) do status = apply(backend, :configuration_status, [backend_state]) {:reply, status, state} end def handle_call({:save, config}, _from, %{configurations: configs} = state) do {:reply, :ok, %{state | configurations: Map.put(configs, config.ssid, config)}} end def handle_call( :device_info, _from, %State{backend: backend} = state ) do {:reply, apply(backend, :device_info, []), state} end def handle_call(:configurations, _from, %State{configurations: configs} = state) do {:reply, build_config_list(configs), state} end def handle_call( :apply, _from, %State{configurations: wifi_configs} = state ) when wifi_configs == %{} do {:reply, {:error, :no_configurations}, state} end def handle_call( :apply, _from, %State{backend: backend, configurations: wifi_configs, backend_state: backend_state} = state ) do case apply(backend, :apply, [build_config_list(wifi_configs), backend_state]) do {:ok, new_backend_state} -> {:reply, :ok, %{state | backend_state: new_backend_state}} {:error, _} = error -> {:reply, error, state} end end def handle_call(:reset, _from, %State{backend: backend} = state) do new_state = apply(backend, :reset, []) {:reply, :ok, %{state | configurations: %{}, backend_state: new_state}} end def handle_call({:delete_configuration, ssid}, _from, %State{configurations: configs} = state) do {:reply, :ok, %{state | configurations: Map.delete(configs, ssid)}} end def handle_call(:configuration_state, _from, state) do {:reply, state, state} end def handle_call( :complete, _from, %State{backend: backend, configurations: wifi_configs, backend_state: backend_state} = state ) do {:ok, new_backend_state} = apply(backend, :complete, [build_config_list(wifi_configs), backend_state]) {:reply, :ok, %{state | backend_state: new_backend_state}} end @impl true def handle_cast({:subscribe, subscriber}, state) do {:noreply, %{state | subscriber: subscriber}} end @impl true def handle_info( info, %State{ subscriber: subscriber, backend: backend, backend_state: backend_state } = state ) do case backend.handle_info(info, backend_state) do {:reply, message, new_backend_state} -> maybe_send(subscriber, {VintageNetWizard, message}) {:noreply, %{state | backend_state: new_backend_state}} {:noreply, %{state: :idle, data: %{configuration_status: :good}} = new_backend_state} -> # idle state with good configuration means we've completed setup # and wizard has been shut down. So let's clear configurations # so aren't hanging around in memory {:noreply, %{state | configurations: %{}, backend_state: new_backend_state}} {:noreply, new_backend_state} -> {:noreply, %{state | backend_state: new_backend_state}} end end defp build_config_list(configs) do configs |> Enum.into([], &elem(&1, 1)) |> Enum.sort(&(&1.priority <= &2.priority)) end defp maybe_send(nil, _message), do: :ok defp maybe_send(pid, message), do: send(pid, message) defp get_priority_for_ssid(priority_order_list, ssid) do priority_index = Enum.find(priority_order_list, fn {^ssid, _} -> true _ -> false end) |> elem(1) priority_index + 1 end end
26.257962
99
0.647665
9ecec32bdeb394a06530d03143760366f2e2832a
3,254
ex
Elixir
clients/games/lib/google_api/games/v1/model/leaderboard_entry.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/games/lib/google_api/games/v1/model/leaderboard_entry.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/games/lib/google_api/games/v1/model/leaderboard_entry.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.Games.V1.Model.LeaderboardEntry do @moduledoc """ This is a JSON template for the Leaderboard Entry resource. ## Attributes * `formattedScore` (*type:* `String.t`, *default:* `nil`) - The localized string for the numerical value of this score. * `formattedScoreRank` (*type:* `String.t`, *default:* `nil`) - The localized string for the rank of this score for this leaderboard. * `kind` (*type:* `String.t`, *default:* `games#leaderboardEntry`) - Uniquely identifies the type of this resource. Value is always the fixed string games#leaderboardEntry. * `player` (*type:* `GoogleApi.Games.V1.Model.Player.t`, *default:* `nil`) - The player who holds this score. * `scoreRank` (*type:* `String.t`, *default:* `nil`) - The rank of this score for this leaderboard. * `scoreTag` (*type:* `String.t`, *default:* `nil`) - Additional information about the score. Values must contain no more than 64 URI-safe characters as defined by section 2.3 of RFC 3986. * `scoreValue` (*type:* `String.t`, *default:* `nil`) - The numerical value of this score. * `timeSpan` (*type:* `String.t`, *default:* `nil`) - The time span of this high score. Possible values are: - "ALL_TIME" - The score is an all-time high score. - "WEEKLY" - The score is a weekly high score. - "DAILY" - The score is a daily high score. * `writeTimestampMillis` (*type:* `String.t`, *default:* `nil`) - The timestamp at which this score was recorded, in milliseconds since the epoch in UTC. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :formattedScore => String.t(), :formattedScoreRank => String.t(), :kind => String.t(), :player => GoogleApi.Games.V1.Model.Player.t(), :scoreRank => String.t(), :scoreTag => String.t(), :scoreValue => String.t(), :timeSpan => String.t(), :writeTimestampMillis => String.t() } field(:formattedScore) field(:formattedScoreRank) field(:kind) field(:player, as: GoogleApi.Games.V1.Model.Player) field(:scoreRank) field(:scoreTag) field(:scoreValue) field(:timeSpan) field(:writeTimestampMillis) end defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.LeaderboardEntry do def decode(value, options) do GoogleApi.Games.V1.Model.LeaderboardEntry.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.LeaderboardEntry do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
43.386667
192
0.687154
9eced0ec46abfd8c962c1b09519c04d593b7f4dc
1,257
exs
Elixir
config/config.exs
alanwilhelm/elixir-ethereum
42aba002e485524be2981ae05b6f7134f8439dc4
[ "MIT" ]
null
null
null
config/config.exs
alanwilhelm/elixir-ethereum
42aba002e485524be2981ae05b6f7134f8439dc4
[ "MIT" ]
null
null
null
config/config.exs
alanwilhelm/elixir-ethereum
42aba002e485524be2981ae05b6f7134f8439dc4
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # config :ethereum, ethereum_rpc_url: System.get_env("ETHEREUM_HOST") # # And access this configuration in your application as: # # Application.get_env(:ethereum, :ethereum_rpc_url) # # Or configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs" config :tesla, adapter: Tesla.Adapter.Hackney #, [recv_timeout: 30_000, hackney: :insecure]
40.548387
91
0.762132
9eceeeadaa2cf1b392106c4c668f525f8bc228f9
1,565
ex
Elixir
apps/dtask_tui/lib/dtask/tui/tab.ex
fehu/elixir-dtask
93b39a1acb616cdc7b4fffb4950e82021ef5b0f6
[ "MIT" ]
null
null
null
apps/dtask_tui/lib/dtask/tui/tab.ex
fehu/elixir-dtask
93b39a1acb616cdc7b4fffb4950e82021ef5b0f6
[ "MIT" ]
null
null
null
apps/dtask_tui/lib/dtask/tui/tab.ex
fehu/elixir-dtask
93b39a1acb616cdc7b4fffb4950e82021ef5b0f6
[ "MIT" ]
null
null
null
defmodule DTask.TUI.Tab do @moduledoc false alias DTask.TUI alias DTask.TUI.Render alias DTask.TUI.Views.Stateful use StructAccess @enforce_keys [:id, :shortcuts, :data_key, :render_main] defstruct [:id, :shortcuts, :data_key, :render_main, :render_side, :stateful] @type stateful_def :: module | {module, (term -> term)} | {module, atom, [term]} @type t :: %__MODULE__{ id: atom, shortcuts: [char], data_key: atom, render_main: Render.t, render_side: Render.t | nil, stateful: Stateful.t | [stateful_def] | nil } # # # Build helpers # # # @spec init(t | TUI.State.t) :: t | TUI.State.t def init(state) when is_struct(state, TUI.State) do update_in(state.ui.tab, &init/1) end def init(tab) when is_struct(tab, __MODULE__) do update_in tab.stateful, fn [] -> nil mods when is_list(mods) -> Stateful.create_many(mods) s when is_struct(s, Stateful) -> s _ -> nil end end # # # Access helpers # # # @spec cursor(TUI.state, axis) :: non_neg_integer | nil when axis: :x | :y def cursor(state, axis) when not is_nil(state.ui.tab.stateful) and not is_nil(state.ui.tab.stateful.state.cursor) and axis in [:x, :y], do: state.ui.tab.stateful.state.cursor[axis] def cursor(_, _), do: nil end
30.686275
83
0.536741
9eceef444e58e09857a974eef03d775eb57d78da
3,900
exs
Elixir
test/elenchos_ex/lib/repository_test.exs
maxneuvians/elenchos_ex
03b31e848dafe12614a01104f89d9477c7b21025
[ "MIT" ]
null
null
null
test/elenchos_ex/lib/repository_test.exs
maxneuvians/elenchos_ex
03b31e848dafe12614a01104f89d9477c7b21025
[ "MIT" ]
null
null
null
test/elenchos_ex/lib/repository_test.exs
maxneuvians/elenchos_ex
03b31e848dafe12614a01104f89d9477c7b21025
[ "MIT" ]
null
null
null
defmodule ElenchosEx.RepositoryTest do use ExUnit.Case, async: false import ElenchosEx.Repository @code_dir Application.get_env(:elenchos_ex, :code_dir, "/tmp") describe "checks out code for a checked_out repo at a sha" do test "returns {:ok, :checked_out} if the repository can be checked out" do sha = "f40697d53cbd67d74718dc8a58aa6b66692034f3" new_sha = "686880e3ba2b2d782de57ff1540cdb00c7eb774a" clone(%{full_name: "cds-snc/dns", sha: sha}) assert {:ok, :checked_out} = checkout(%{sha: new_sha}) cleanup(%{sha: sha}) end test "returns {:error, error, code} if the repository can not be checked out" do sha = "f40697d53cbd67d74718dc8a58aa6b66692034f3" clone(%{full_name: "cds-snc/dns", sha: sha}) assert {:error, "2: " <> _rest} = checkout(%{sha: "abcd"}) cleanup(%{sha: sha}) end end describe "clones a repository" do test "returns {:ok, :cloned} if the repository can be checked out" do sha = "f40697d53cbd67d74718dc8a58aa6b66692034f3" assert {:ok, :cloned} = clone(%{full_name: "cds-snc/dns", sha: sha}) cleanup(%{sha: sha}) end test "returns {:error, error, code} if the repository can not be checked out" do sha = "abcd" assert {:error, "128: " <> _rest} = clone(%{full_name: "cds-snc/abcd", sha: sha}) cleanup(%{sha: sha}) end end describe "cleanup exiting code" do test "returns {:ok, :cleaned_up} if the repository is deleted" do sha = "f40697d53cbd67d74718dc8a58aa6b66692034f3" clone(%{full_name: "cds-snc/dns", sha: sha}) assert {:ok, cleaned_up} = cleanup(%{sha: sha}) end end describe "validates elenchos config" do test "returns {:error, 'File does not exist'} if the file does not exist" do sha = "abcd" assert {:error, "File does not exist"} = validate_elenchos_config(%{sha: sha}) end test "returns {:error, 'Could not decode JSON'} if it can not decode JSON" do sha = "f40697d53cbd67d74718dc8a58aa6b66692034f3" clone(%{full_name: "cds-snc/dns", sha: sha}) File.write!(@code_dir <> "/" <> sha <> "/elenchos.json", "") assert {:error, "Could not decode JSON"} = validate_elenchos_config(%{sha: sha}) cleanup(%{sha: sha}) end test "returns {:error, 'Config is missing overlay key'} if overlay key is missing" do sha = "f40697d53cbd67d74718dc8a58aa6b66692034f3" clone(%{full_name: "cds-snc/dns", sha: sha}) File.write!(@code_dir <> "/" <> sha <> "/elenchos.json", "{\"dockerfiles\":{}}") assert {:error, "Config is missing overlay key"} = validate_elenchos_config(%{sha: sha}) cleanup(%{sha: sha}) end test "returns {:error, 'Config is missing overlay key'} if dockerfiles key is missing" do sha = "f40697d53cbd67d74718dc8a58aa6b66692034f3" clone(%{full_name: "cds-snc/dns", sha: sha}) File.write!(@code_dir <> "/" <> sha <> "/elenchos.json", "{\"overlay\":{}}") assert {:error, "Config is missing dockerfiles key"} = validate_elenchos_config(%{sha: sha}) cleanup(%{sha: sha}) end test "returns {:error, 'Config is missing dockerfiles and overlay keys'} if both keys are missing" do sha = "f40697d53cbd67d74718dc8a58aa6b66692034f3" clone(%{full_name: "cds-snc/dns", sha: sha}) File.write!(@code_dir <> "/" <> sha <> "/elenchos.json", "{}") assert {:error, "Config is missing dockerfiles and overlay keys"} = validate_elenchos_config(%{sha: sha}) cleanup(%{sha: sha}) end test "returns true if they key is valid" do sha = "f40697d53cbd67d74718dc8a58aa6b66692034f3" clone(%{full_name: "cds-snc/dns", sha: sha}) File.write!(@code_dir <> "/" <> sha <> "/elenchos.json", "{\"dockerfiles\":{}, \"overlay\":{}}") assert true = validate_elenchos_config(%{sha: sha}) cleanup(%{sha: sha}) end end end
41.489362
111
0.642051
9ecef474d55a3680304207593ab9cb2fc2d30d9f
1,358
ex
Elixir
lib/jerboa/format/body/attribute/dont_fragment.ex
ACollectionOfAtoms/jerboa
16000d450bb60b544b5c91f0fd7540a31b6c90b8
[ "Apache-2.0" ]
14
2016-12-22T10:38:34.000Z
2021-03-11T23:20:26.000Z
lib/jerboa/format/body/attribute/dont_fragment.ex
ACollectionOfAtoms/jerboa
16000d450bb60b544b5c91f0fd7540a31b6c90b8
[ "Apache-2.0" ]
94
2016-12-22T13:13:29.000Z
2021-02-10T14:22:32.000Z
lib/jerboa/format/body/attribute/dont_fragment.ex
ACollectionOfAtoms/jerboa
16000d450bb60b544b5c91f0fd7540a31b6c90b8
[ "Apache-2.0" ]
6
2017-04-03T20:23:00.000Z
2022-03-06T10:14:30.000Z
defmodule Jerboa.Format.Body.Attribute.DontFragment do @moduledoc """ DONT-FRAGMENT attribute as defined in [TURN RFC](https://trac.tools.ietf.org/html/rfc5766#section-14.8) """ alias Jerboa.Format.Body.Attribute.{Decoder,Encoder} alias Jerboa.Format.DontFragment.ValuePresentError alias Jerboa.Format.Meta defstruct [] @typedoc """ Represent DONT-FRAGMENT attribute This attribute doesn't have any value associated with it. """ @type t :: %__MODULE__{} defimpl Encoder do alias Jerboa.Format.Body.Attribute.DontFragment @type_code 0x001A @spec type_code(DontFragment.t) :: integer def type_code(_), do: @type_code @spec encode(DontFragment.t, Meta.t) :: {Meta.t, binary} def encode(_attr, meta), do: {meta, DontFragment.encode()} end defimpl Decoder do alias Jerboa.Format.Body.Attribute.DontFragment @spec decode(DontFragment.t, value :: binary, meta :: Meta.t) :: {:ok, Meta.t, DontFragment.t} | {:error, struct} def decode(_, value, meta), do: DontFragment.decode(value, meta) end @doc false @spec encode :: <<>> def encode, do: <<>> @doc false @spec decode(value :: binary, meta :: Meta.t) :: {:ok, Meta.t, t} | {:error, struct} def decode(<<>>, meta), do: {:ok, meta, %__MODULE__{}} def decode(_, _), do: {:error, ValuePresentError.exception()} end
28.291667
105
0.675994
9ecef94ad3270713c193e3f1969fee8f5820cd93
9,505
ex
Elixir
lib/phoenix/live_dashboard/components/table_component.ex
adrianomitre/phoenix_live_dashboard
34977c3d61655be708761b975ca885680ac3145f
[ "MIT" ]
null
null
null
lib/phoenix/live_dashboard/components/table_component.ex
adrianomitre/phoenix_live_dashboard
34977c3d61655be708761b975ca885680ac3145f
[ "MIT" ]
null
null
null
lib/phoenix/live_dashboard/components/table_component.ex
adrianomitre/phoenix_live_dashboard
34977c3d61655be708761b975ca885680ac3145f
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveDashboard.TableComponent do @moduledoc false # `Phoenix.LiveComponent` to render a simple table. # This component is used in different pages like applications or sockets. # It can be used in a `Phoenix.LiveView` in the `render/1` function: # ``` # def render(assigns) do # ~L\""" # <%= live_component(assigns.socket, Phoenix.LiveDashboard.TableComponent, options) %> # \""" # end # ``` # # Options # These are the options supported by the component: # * `:id` - Required. Because is a stateful `Phoenix.LiveComponent` an unique id is needed. # * `:columns` - Required. A `Keyword` list with the following keys: # * `:field` - Required. An identifier for the column. # * `:header` - Label to show in the current column. Default value is calculated from `:field`. # * `:header_attrs` - A list with HTML attributes for the column header. # More info: `Phoenix.HTML.Tag.tag/1`. Default `[]`. # * `:format` - Function which receives the row data and returns the cell information. # Default is calculated from `:field`: `row[:field]`. # * `:cell_attrs` - A list with HTML attributes for the table cell. # It also can be a function which receives the row data and returns an attribute list. # More info: `Phoenix.HTML.Tag.tag/1`. Default: `[]`. # * `:sortable` - A boolean. When it is true the column header is clickable # and it fetches again rows with the new order. At least one column should be sortable. # Default: `false` # * `:limit_options` - A list of integers to limit the number of rows to show. # Default: `[50, 100, 500, 1000, 5000]` # * `:page_name` - Required. The name of current `Phoenix.LiveView`. # * `:params` - Required. All the params received by the parent `Phoenix.LiveView`, # so the table can handle its own parameters. # * `:row_fetcher` - Required. A function which receives the params and the node and # returns a tuple with the rows and the total number: # `(params(), node()) -> {list(), integer() | binary()}` # * `:rows_name` - A string to name the representation of the rows. # Default is calculated with the given `:page_name`. # * `:title` - The title of the table. # Default is calculated with the given `:page_name`. use Phoenix.LiveDashboard.Web, :live_component @sort_dir ~w(desc asc) @limit [50, 100, 500, 1000, 5000] @type params() :: %{ limit: pos_integer(), sort_by: :atom, sort_dir: :desc | :asc, search: binary() } @impl true def mount(socket) do {:ok, socket} end @impl true def update(assigns, socket) do %{ columns: columns, id: _id, page: page, row_fetcher: row_fetcher, title: title } = assigns limit_options = assigns[:limit_options] || @limit columns = normalize_columns(columns) table_params = normalize_table_params(page.params, columns, limit_options) {rows, total} = row_fetcher.(table_params, page.node) {:ok, assign(socket, columns: columns, limit_options: limit_options, page: page, row_attrs: assigns[:row_attrs] || [], row_fetcher: row_fetcher, rows: rows, rows_name: assigns[:rows_name] || Phoenix.Naming.humanize(title) |> String.downcase(), table_params: table_params, title: title, total: total )} end defp normalize_columns(columns) do Enum.map(columns, fn %{field: field} = column -> column |> Map.put_new_lazy(:header, fn -> Phoenix.Naming.humanize(field) end) |> Map.put_new(:header_attrs, []) |> Map.put_new(:format, & &1[field]) |> Map.put_new(:cell_attrs, []) |> Map.put_new(:sortable, false) end) end defp normalize_table_params(all_params, columns, limit_options) do sortable_columns = sortable_columns(columns) sort_by = all_params |> get_in_or_first("sort_by", sortable_columns) |> String.to_atom() sort_dir = all_params |> get_in_or_first("sort_dir", @sort_dir) |> String.to_atom() limit_options = Enum.map(limit_options, &to_string/1) limit = all_params |> get_in_or_first("limit", limit_options) |> String.to_integer() search = all_params["search"] search = if search == "", do: nil, else: search %{sort_by: sort_by, sort_dir: sort_dir, limit: limit, search: search} end defp sortable_columns(columns) do Enum.flat_map(columns, &if(&1[:sortable], do: [to_string(&1[:field])], else: [])) end defp get_in_or_first(params, key, valid) do value = params[key] if value in valid, do: value, else: hd(valid) end @impl true def render(assigns) do ~L""" <div class="tabular-page"> <h5 class="card-title"><%= @title %></h5> <div class="tabular-search"> <form phx-change="search" phx-submit="search" phx-target="<%= @myself %>" class="form-inline"> <div class="form-row align-items-center"> <div class="col-auto"> <input type="search" name="search" class="form-control form-control-sm" value="<%= @table_params.search %>" placeholder="Search" phx-debounce="300"> </div> </div> </form> </div> <form phx-change="select_limit" phx-target="<%= @myself %>" class="form-inline"> <div class="form-row align-items-center"> <div class="col-auto">Showing at most</div> <div class="col-auto"> <div class="input-group input-group-sm"> <select name="limit" class="custom-select" id="limit-select"> <%= options_for_select(@limit_options, @table_params.limit) %> </select> </div> </div> <div class="col-auto"> <%= @rows_name %> out of <%= @total %> </div> </div> </form> <div class="card tabular-card mb-4 mt-4"> <div class="card-body p-0"> <div class="dash-table-wrapper"> <table class="table table-hover mt-0 dash-table"> <thead> <tr> <%= for column <- @columns do %> <%= tag_with_attrs(:th, column[:header_attrs], [column]) %> <%= if column[:sortable] do %> <%= sort_link(@socket, @page, @table_params, column) %> <% else %> <%= column.header %> <% end %> </th> <% end %> </tr> </thead> <tbody> <%= for row <- @rows do %> <%= tag_with_attrs(:tr, @row_attrs, [row]) %> <%= for column <- @columns do %> <%= tag_with_attrs(:td, column[:cell_attrs], [row]) %> <%= column[:format].(row) %> </td> <% end %> </tr> <% end %> </tbody> </table> </div> </div> </div> </div> """ end defp tag_with_attrs(name, fun, args), do: tag(name, calc_attrs(fun, args)) defp calc_attrs(falsy, _) when falsy in [nil, false], do: [] defp calc_attrs(list, _) when is_list(list), do: list defp calc_attrs(fun, args) when is_function(fun), do: apply(fun, args) defp column_header(column) do column.header || column.field |> to_string() |> String.capitalize() end @impl true def handle_event("search", %{"search" => search}, socket) do new_params = %{socket.assigns.table_params | search: search} to = live_dashboard_path(socket, socket.assigns.page, update_params(new_params)) {:noreply, push_patch(socket, to: to)} end def handle_event("select_limit", %{"limit" => limit}, socket) do new_params = %{socket.assigns.table_params | limit: limit} to = live_dashboard_path(socket, socket.assigns.page, update_params(new_params)) {:noreply, push_patch(socket, to: to)} end defp sort_link(socket, page, table_params, column) do field = column.field case table_params do %{sort_by: ^field, sort_dir: sort_dir} -> table_params = %{table_params | sort_dir: opposite_sort_dir(table_params), sort_by: field} column |> column_header() |> sort_link_body(sort_dir) |> live_patch(to: live_dashboard_path(socket, page, update_params(table_params))) %{} -> table_params = %{table_params | sort_dir: :desc, sort_by: field} column |> column_header() |> sort_link_body() |> live_patch(to: live_dashboard_path(socket, page, update_params(table_params))) end end defp sort_link_body(link_name), do: link_name defp sort_link_body(link_name, sort_dir) do [link_name | sort_link_icon(sort_dir)] end defp sort_link_icon(:asc) do {:safe, """ <div class="dash-table-icon"> <span class="icon-sort icon-asc"></span> </div> """} end defp sort_link_icon(:desc) do {:safe, """ <div class="dash-table-icon"> <span class="icon-sort icon-desc"></span> </div> """} end defp opposite_sort_dir(%{sort_dir: :desc}), do: :asc defp opposite_sort_dir(_), do: :desc defp update_params(new_params) do fn all_params -> new_params = Enum.into(new_params, %{}, fn {k, v} -> {Atom.to_string(k), to_string(v)} end) Map.merge(all_params, new_params) end end end
34.689781
162
0.592741
9ecefc58af59e9c73967fc6c21e4e904bec302e6
2,486
ex
Elixir
clients/service_networking/lib/google_api/service_networking/v1/model/context_rule.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/service_networking/lib/google_api/service_networking/v1/model/context_rule.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/service_networking/lib/google_api/service_networking/v1/model/context_rule.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.ServiceNetworking.V1.Model.ContextRule do @moduledoc """ A context rule provides information about the context for an individual API element. ## Attributes * `allowedRequestExtensions` (*type:* `list(String.t)`, *default:* `nil`) - A list of full type names or extension IDs of extensions allowed in grpc side channel from client to backend. * `allowedResponseExtensions` (*type:* `list(String.t)`, *default:* `nil`) - A list of full type names or extension IDs of extensions allowed in grpc side channel from backend to client. * `provided` (*type:* `list(String.t)`, *default:* `nil`) - A list of full type names of provided contexts. * `requested` (*type:* `list(String.t)`, *default:* `nil`) - A list of full type names of requested contexts. * `selector` (*type:* `String.t`, *default:* `nil`) - Selects the methods to which this rule applies. Refer to selector for syntax details. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :allowedRequestExtensions => list(String.t()), :allowedResponseExtensions => list(String.t()), :provided => list(String.t()), :requested => list(String.t()), :selector => String.t() } field(:allowedRequestExtensions, type: :list) field(:allowedResponseExtensions, type: :list) field(:provided, type: :list) field(:requested, type: :list) field(:selector) end defimpl Poison.Decoder, for: GoogleApi.ServiceNetworking.V1.Model.ContextRule do def decode(value, options) do GoogleApi.ServiceNetworking.V1.Model.ContextRule.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ServiceNetworking.V1.Model.ContextRule do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
42.135593
190
0.716412
9ecf0a34777502099c02dcbe60f1240fc7985041
517
ex
Elixir
apps/toniefy/lib/toniex/recorder/session.ex
benvp/toniefy.me
9a432380e43f1c9a15ccd1910357d491d64a1dc0
[ "MIT" ]
17
2021-04-12T10:01:14.000Z
2022-02-25T17:30:27.000Z
apps/toniefy/lib/toniex/recorder/session.ex
benvp/toniefy.me
9a432380e43f1c9a15ccd1910357d491d64a1dc0
[ "MIT" ]
1
2022-03-09T09:35:00.000Z
2022-03-09T11:46:14.000Z
apps/toniefy/lib/toniex/recorder/session.ex
benvp/toniefy
9a432380e43f1c9a15ccd1910357d491d64a1dc0
[ "MIT" ]
null
null
null
defmodule Toniex.Recorder.Session do use Ecto.Schema import Ecto.Changeset alias Toniex.Accounts alias Toniex.Recorder.SessionTrack schema "recorder_sessions" do embeds_many :tracks, SessionTrack belongs_to :user, Accounts.User, type: :binary_id timestamps(type: :utc_datetime) end @doc false def changeset(session, attrs) do session |> cast(attrs, [:user_id]) |> cast_embed(:tracks, with: &SessionTrack.changeset/2) |> validate_required([:tracks, :user_id]) end end
22.478261
59
0.717602
9ecf175fc47dcd0dae73a1c50d705f484ebfc10c
277
exs
Elixir
priv/repo/migrations/20200605173609_add_delivery_distance_to_task.exs
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
28
2021-10-11T01:53:53.000Z
2022-03-24T17:45:55.000Z
priv/repo/migrations/20200605173609_add_delivery_distance_to_task.exs
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
20
2021-10-21T08:12:31.000Z
2022-03-31T13:35:53.000Z
priv/repo/migrations/20200605173609_add_delivery_distance_to_task.exs
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
null
null
null
defmodule BikeBrigade.Repo.Migrations.AddDeliveryDistanceToTask do use Ecto.Migration def change do alter table(:tasks) do add :delivery_distance, :"integer GENERATED ALWAYS AS (st_distance(pickup_location, dropoff_location)) STORED" end end end
25.181818
96
0.743682
9ecf513f18879b7345451ee648564a4e167d26b6
788
ex
Elixir
apps/tai/lib/tai/venue_adapters/deribit.ex
ccamateur/tai
41c4b3e09dafc77987fa3f6b300c15461d981e16
[ "MIT" ]
276
2018-01-16T06:36:06.000Z
2021-03-20T21:48:01.000Z
apps/tai/lib/tai/venue_adapters/deribit.ex
ccamateur/tai
41c4b3e09dafc77987fa3f6b300c15461d981e16
[ "MIT" ]
73
2018-10-05T18:45:06.000Z
2021-02-08T05:46:33.000Z
apps/tai/lib/tai/venue_adapters/deribit.ex
ccamateur/tai
41c4b3e09dafc77987fa3f6b300c15461d981e16
[ "MIT" ]
43
2018-06-09T09:54:51.000Z
2021-03-07T07:35:17.000Z
defmodule Tai.VenueAdapters.Deribit do alias Tai.VenueAdapters.Deribit.{ StreamSupervisor, Products, Accounts, Positions } @behaviour Tai.Venues.Adapter def stream_supervisor, do: StreamSupervisor defdelegate products(venue_id), to: Products defdelegate accounts(venue_id, credential_id, credentials), to: Accounts def maker_taker_fees(_, _, _), do: {:ok, nil} defdelegate positions(venue_id, credential_id, credentials), to: Positions def create_order(_order, _credentials), do: {:error, :not_implemented} def amend_order(_order, _attrs, _credentials), do: {:error, :not_implemented} def amend_bulk_orders(_orders_with_attrs, _credentials), do: {:error, :not_supported} def cancel_order(_order, _credentials), do: {:error, :not_implemented} end
37.52381
87
0.760152
9ecf87c991a32e2d00f4209afcd735d50500a8b3
1,087
ex
Elixir
apps/site/lib/site_web/controllers/static_page.ex
mbta/crispy-spoon
7ef28a1a6adc73899b007e334b9220f7a48a60fa
[ "MIT" ]
null
null
null
apps/site/lib/site_web/controllers/static_page.ex
mbta/crispy-spoon
7ef28a1a6adc73899b007e334b9220f7a48a60fa
[ "MIT" ]
null
null
null
apps/site/lib/site_web/controllers/static_page.ex
mbta/crispy-spoon
7ef28a1a6adc73899b007e334b9220f7a48a60fa
[ "MIT" ]
null
null
null
defmodule SiteWeb.StaticPage do @moduledoc """ Logic for pages which simply render a static template with no additional logic. Separated into its own module in order to allow use at compile time in other modules. """ @static_pages [ %{ key: :about, meta_description: "Information about the Massachusetts Bay Transportation Authority (MBTA), " <> "including leadership, business opportunities, projects and initiatives, and financials." }, %{ key: :getting_around, meta_description: "Navigate public transit in the Greater Boston region. Routes, schedules, " <> "trip planner, service alerts, real-time updates, and general information." }, %{ key: :menu, meta_description: "Browse the key areas of the MBTA website." } ] def static_pages, do: Enum.map(@static_pages, & &1.key) def meta_description(key), do: Enum.find(@static_pages, &(&1.key == key)).meta_description def convert_path(path) do path |> Atom.to_string() |> String.replace("_", "-") end end
30.194444
100
0.661454
9ecfc6fd561554172aa389e062f5469dd239b63e
2,427
ex
Elixir
clients/billing_budgets/lib/google_api/billing_budgets/v1/model/google_type_date.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/billing_budgets/lib/google_api/billing_budgets/v1/model/google_type_date.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/billing_budgets/lib/google_api/billing_budgets/v1/model/google_type_date.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.BillingBudgets.V1.Model.GoogleTypeDate do @moduledoc """ Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values * A month and day value, with a zero year, such as an anniversary * A year on its own, with zero month and day values * A year and month value, with a zero day, such as a credit card expiration date Related types are google.type.TimeOfDay and `google.protobuf.Timestamp`. ## Attributes * `day` (*type:* `integer()`, *default:* `nil`) - Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. * `month` (*type:* `integer()`, *default:* `nil`) - Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. * `year` (*type:* `integer()`, *default:* `nil`) - Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :day => integer(), :month => integer(), :year => integer() } field(:day) field(:month) field(:year) end defimpl Poison.Decoder, for: GoogleApi.BillingBudgets.V1.Model.GoogleTypeDate do def decode(value, options) do GoogleApi.BillingBudgets.V1.Model.GoogleTypeDate.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.BillingBudgets.V1.Model.GoogleTypeDate do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
45.792453
567
0.721055
9ecff62e06e8332584ad547ffb3a775977788cc0
1,514
ex
Elixir
lib/nifsy/stream.ex
antipax/read_nif
795709bdf7d20ec8a841bccdd39a1c9d5b9360ad
[ "Apache-2.0" ]
9
2018-04-06T07:48:12.000Z
2021-09-09T11:23:09.000Z
lib/nifsy/stream.ex
antipax/read_nif
795709bdf7d20ec8a841bccdd39a1c9d5b9360ad
[ "Apache-2.0" ]
1
2018-11-18T08:41:15.000Z
2018-11-18T09:34:13.000Z
lib/nifsy/stream.ex
ericentin/nifsy
795709bdf7d20ec8a841bccdd39a1c9d5b9360ad
[ "Apache-2.0" ]
null
null
null
defmodule Nifsy.Stream do @moduledoc false alias Nifsy.Native defstruct [:options, :path] @opaque t :: %__MODULE__{ options: Nifsy.options, path: Path.t } defimpl Collectable do def into(%{options: options, path: path} = stream) do case Nifsy.open(path, :write, options) do {:ok, handle} -> {:ok, into(handle.handle, stream)} {:error, reason} -> raise "could not stream #{path}: #{inspect(reason)}" end end def into(handle, stream) do fn :ok, {:cont, x} -> Native.write(handle, x) :ok, :done -> :ok = Native.close(handle) stream :ok, :halt -> :ok = Native.close(handle) end end end defimpl Enumerable do def reduce(%{options: options, path: path}, acc, fun) do start_fun = fn -> case Nifsy.open(path, :read, options) do {:ok, handle} -> handle.handle {:error, reason} -> raise "could not stream #{path}: #{inspect(reason)}" end end next_fun = fn handle -> case Native.read_line(handle) do :eof -> {:halt, handle} {:ok, line} -> {[line], handle} end end Stream.resource(start_fun, next_fun, &Native.close/1).(acc, fun) end def count(_stream) do {:error, __MODULE__} end def member?(_stream, _term) do {:error, __MODULE__} end end end
21.323944
70
0.519815
9ecff7de1008cda19c2b459afb29a7f047d55b4e
9,258
exs
Elixir
test/glimesh/api/chats_test.exs
Eein/glimesh.tv
e55e96b852363b0d9576ca47d19f1499889c68db
[ "MIT" ]
null
null
null
test/glimesh/api/chats_test.exs
Eein/glimesh.tv
e55e96b852363b0d9576ca47d19f1499889c68db
[ "MIT" ]
null
null
null
test/glimesh/api/chats_test.exs
Eein/glimesh.tv
e55e96b852363b0d9576ca47d19f1499889c68db
[ "MIT" ]
null
null
null
defmodule Glimesh.Api.ChatsTest do use GlimeshWeb.ConnCase import Glimesh.AccountsFixtures import Glimesh.Support.GraphqlHelper alias Glimesh.Streams @create_chat_message_mutation """ mutation CreateChatMessage($channelId: ID!, $message: ChatMessageInput!) { createChatMessage(channelId: $channelId, message: $message) { message user { username } tokens { type text ... on EmoteToken { src url } } } } """ @short_timeout_mutation """ mutation ShortTimeoutUser($channelId: ID!, $userId: ID!) { shortTimeoutUser(channelId: $channelId, userId: $userId) { moderator { username } user { username } action } } """ @long_timeout_mutation """ mutation LongTimeoutUser($channelId: ID!, $userId: ID!) { longTimeoutUser(channelId: $channelId, userId: $userId) { moderator { username } user { username } action } } """ @ban_user_mutation """ mutation BanUser($channelId: ID!, $userId: ID!) { banUser(channelId: $channelId, userId: $userId) { moderator { username } user { username } action } } """ @unban_user_mutation """ mutation UnbanUser($channelId: ID!, $userId: ID!) { unbanUser(channelId: $channelId, userId: $userId) { moderator { username } user { username } action } } """ @delete_chat_message_mutation """ mutation DeleteChatmessage($channelId: ID!, $messageId: ID!) { deleteChatMessage(channelId: $channelId, messageId: $messageId) { moderator { username } user { username } action } } """ describe "chat api without scope" do setup [:create_user, :create_channel] setup context do create_token_and_return_context(context.conn, context.user, "public") end test "cannot send a chat message", %{conn: conn, channel: channel} do resp = run_query(conn, @create_chat_message_mutation, %{ channelId: "#{channel.id}", message: %{ message: "Hello world" } }) assert is_nil(resp["data"]["createChatMessage"]) assert [ %{ "locations" => _, "message" => "unauthorized", "path" => _ } ] = resp["errors"] end end describe "chat api with scope" do setup [:register_and_set_user_token, :create_channel] test "can send a chat message", %{conn: conn, user: user, channel: channel} do conn = post(conn, "/api/graph", %{ "query" => @create_chat_message_mutation, "variables" => %{ channelId: "#{channel.id}", message: %{ message: "Hello world" } } }) assert json_response(conn, 200)["data"]["createChatMessage"] == %{ "message" => "Hello world", "user" => %{ "username" => user.username }, "tokens" => [ %{"type" => "text", "text" => "Hello world"} ] } end test "can send a chat message in different channel", %{ conn: conn, user: user } do streamer = streamer_fixture() conn = post(conn, "/api/graph", %{ "query" => @create_chat_message_mutation, "variables" => %{ channelId: "#{streamer.channel.id}", message: %{ message: "Hello world" } } }) assert json_response(conn, 200)["data"]["createChatMessage"] == %{ "message" => "Hello world", "user" => %{ "username" => user.username }, "tokens" => [ %{"type" => "text", "text" => "Hello world"} ] } end test "can send a emote based message", %{conn: conn, user: user, channel: channel} do conn = post(conn, "/api/graph", %{ "query" => @create_chat_message_mutation, "variables" => %{ channelId: "#{channel.id}", message: %{ message: "Hello :glimwow: world!" } } }) assert json_response(conn, 200)["data"]["createChatMessage"] == %{ "message" => "Hello :glimwow: world!", "user" => %{ "username" => user.username }, "tokens" => [ %{"type" => "text", "text" => "Hello "}, %{ "type" => "emote", "text" => ":glimwow:", "src" => "/emotes/svg/glimwow.svg", "url" => "http://localhost:4002/emotes/svg/glimwow.svg" }, %{"type" => "text", "text" => " world!"} ] } end test "can perform moderation actions", %{conn: conn, user: streamer, channel: channel} do user_to_ban = user_fixture() conn = post(conn, "/api/graph", %{ "query" => @ban_user_mutation, "variables" => %{ channelId: "#{channel.id}", userId: "#{user_to_ban.id}" } }) assert json_response(conn, 200)["data"]["banUser"] == %{ "action" => "ban", "moderator" => %{ "username" => streamer.username }, "user" => %{ "username" => user_to_ban.username } } assert {:error, "You are permanently banned from this channel."} = Glimesh.Chat.create_chat_message(user_to_ban, channel, %{message: "Hello world"}) end test "can short timeout users", %{conn: conn, channel: channel} do user_to_ban = user_fixture() resp = run_query(conn, @short_timeout_mutation, %{ channelId: "#{channel.id}", userId: "#{user_to_ban.id}" }) assert resp["data"]["shortTimeoutUser"]["action"] == "short_timeout" assert {:error, "You are banned from this channel for 5 more minutes."} = Glimesh.Chat.create_chat_message(user_to_ban, channel, %{message: "Hello world"}) end test "can long timeout users", %{conn: conn, channel: channel} do user_to_ban = user_fixture() resp = run_query(conn, @long_timeout_mutation, %{ channelId: "#{channel.id}", userId: "#{user_to_ban.id}" }) assert resp["data"]["longTimeoutUser"]["action"] == "long_timeout" assert {:error, "You are banned from this channel for 15 more minutes."} = Glimesh.Chat.create_chat_message(user_to_ban, channel, %{message: "Hello world"}) end test "can unban users", %{conn: conn, user: streamer, channel: channel} do user_to_unban = user_fixture() Glimesh.Chat.ban_user(streamer, channel, user_to_unban) resp = run_query(conn, @unban_user_mutation, %{ channelId: "#{channel.id}", userId: "#{user_to_unban.id}" }) assert resp["data"]["unbanUser"]["action"] == "unban" assert {:ok, %{message: message}} = Glimesh.Chat.create_chat_message(user_to_unban, channel, %{message: "Hello world"}) assert message == "Hello world" end test "can delete chat messages", %{conn: conn, channel: channel} do bad_user = user_fixture() assert {:ok, %{id: chat_message_id}} = Glimesh.Chat.create_chat_message(bad_user, channel, %{ message: "This is a bad message" }) resp = run_query(conn, @delete_chat_message_mutation, %{ channelId: "#{channel.id}", messageId: "#{chat_message_id}" }) assert resp["data"]["deleteChatMessage"]["action"] == "delete_message" messages = Glimesh.Chat.list_chat_messages(channel) Enum.each(messages, fn m -> assert m.message !== "This is a bad message" end) end end describe "chat api with app client credentials" do setup [:register_and_set_user_token, :create_channel] test "can send a chat message", %{conn: conn, user: user, channel: channel} do conn = post(conn, "/api/graph", %{ "query" => @create_chat_message_mutation, "variables" => %{ channelId: "#{channel.id}", message: %{ message: "Hello world" } } }) assert json_response(conn, 200)["data"]["createChatMessage"] == %{ "message" => "Hello world", "user" => %{ "username" => user.username }, "tokens" => [ %{"type" => "text", "text" => "Hello world"} ] } end end def create_user(_) do %{user: user_fixture()} end def create_channel(%{user: user}) do {:ok, channel} = Streams.create_channel(user) %{channel: channel} end end
26.912791
98
0.509505
9ed009c2c12ac8cf652559668fe1ca262b0dc26b
1,601
exs
Elixir
mix.exs
membraneframework/ex_dtls
d227f7c8a3f61eb97de73b6569571c0b83a383a9
[ "Apache-2.0" ]
5
2021-03-09T19:23:51.000Z
2021-12-09T18:40:24.000Z
mix.exs
membraneframework/ex_dtls
d227f7c8a3f61eb97de73b6569571c0b83a383a9
[ "Apache-2.0" ]
8
2021-02-25T14:23:21.000Z
2022-01-15T20:22:21.000Z
mix.exs
membraneframework/ex_dtls
d227f7c8a3f61eb97de73b6569571c0b83a383a9
[ "Apache-2.0" ]
2
2021-04-26T23:31:46.000Z
2022-03-27T15:40:57.000Z
defmodule ExDTLS.Mixfile do use Mix.Project @version "0.8.0" @github_url "https://github.com/membraneframework/ex_dtls" def project do [ app: :ex_dtls, version: @version, elixir: "~> 1.10", compilers: [:unifex, :bundlex] ++ Mix.compilers(), elixirc_paths: elixirc_paths(Mix.env()), start_permanent: Mix.env() == :prod, deps: deps(), # hex description: "Elixir wrapper over OpenSSL for performing DTLS handshake", package: package(), # docs name: "ExDTLS", source_url: @github_url, homepage_url: "https://membraneframework.org", docs: docs() ] end def application do [ extra_applications: [] ] end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_env), do: ["lib"] defp deps do [ {:membrane_core, "~> 0.8.0"}, {:unifex, "~> 0.7.0"}, {:ex_doc, "~> 0.22", only: :dev, runtime: false}, {:dialyxir, "~> 1.0.0", only: :dev, runtime: false}, {:credo, "~> 1.4", only: :dev, runtime: false} ] end defp package do [ maintainers: ["Membrane Team"], licenses: ["Apache 2.0"], links: %{ "GitHub" => @github_url, "Membrane Framework Homepage" => "https://membraneframework.org" }, files: ["lib", "mix.exs", "README*", "LICENSE*", ".formatter.exs", "bundlex.exs", "c_src"] ] end defp docs do [ main: "readme", extras: ["README.md", "LICENSE"], source_ref: "v#{@version}", nest_modules_by_prefix: [ExDTLS] ] end end
23.202899
96
0.558401
9ed0161058e5e1405e05eafef8ae7c6311952a75
191
exs
Elixir
priv/repo/migrations/20220506030225_add_item_status.exs
knoebber/petaller
3532db5a3688459127d2427af42e32ca0f494d44
[ "MIT" ]
null
null
null
priv/repo/migrations/20220506030225_add_item_status.exs
knoebber/petaller
3532db5a3688459127d2427af42e32ca0f494d44
[ "MIT" ]
null
null
null
priv/repo/migrations/20220506030225_add_item_status.exs
knoebber/petaller
3532db5a3688459127d2427af42e32ca0f494d44
[ "MIT" ]
null
null
null
defmodule Purple.Repo.Migrations.AddItemStatus do use Ecto.Migration def change do alter table("items") do add :status, :string, default: "TODO", null: false end end end
19.1
56
0.691099
9ed05c6fb2382b4d4f91440bc8b70b3d882b15dc
13,613
exs
Elixir
config/runtime.exs
fremantle-industries/rewind
1818fe1704cb303e09108cbb5e669e673685fb62
[ "MIT" ]
2
2021-09-18T09:15:13.000Z
2022-03-16T09:29:37.000Z
config/runtime.exs
fremantle-industries/rewind
1818fe1704cb303e09108cbb5e669e673685fb62
[ "MIT" ]
null
null
null
config/runtime.exs
fremantle-industries/rewind
1818fe1704cb303e09108cbb5e669e673685fb62
[ "MIT" ]
null
null
null
import Config # Shared variables env = config_env() |> Atom.to_string() http_port = (System.get_env("HTTP_PORT") || "4000") |> String.to_integer() rewind_host = System.get_env("REWIND_HOST") || "rewind.localhost" workbench_host = System.get_env("WORKBENCH_HOST") || "workbench.localhost" history_host = System.get_env("HISTORY_HOST") || "history.localhost" livebook_host = System.get_env("LIVEBOOK_HOST") || "livebook.localhost" grafana_host = System.get_env("GRAFANA_HOST") || "grafana.localhost" prometheus_host = System.get_env("PROMETHEUS_HOST") || "prometheus.localhost" rewind_secret_key_base = System.get_env("REWIND_SECRET_KEY_BASE") || "uIsXcCsXXptrAhMspslwWysO4zXUvMTannSJy6moML7in7349Ly7Xw5Rkxx/I2dN" rewind_live_view_signing_salt = System.get_env("REWIND_LIVE_VIEW_SIGNING_SALT") || "YCe1E2To" workbench_secret_key_base = System.get_env("WORKBENCH_SECRET_KEY_BASE") || "vJP36v4Gi2Orw8b8iBRg6ZFdzXKLvcRYkk1AaMLYX0+ry7k5XaJXd/LY/itmoxPP" workbench_live_view_signing_salt = System.get_env("WORKBENCH_LIVE_VIEW_SIGNING_SALT") || "TolmUusQ6//zaa5GZHu7DG2V3YAgOoP/" history_secret_key_base = System.get_env("HISTORY_SECRET_KEY_BASE") || "5E5zaJwG5w2ABR+0p+4GQs1nwzz5e7UbkEa6hlpel6wcrI6CAhWsrKWEecfYFWRF" history_live_view_signing_salt = System.get_env("HISTORY_LIVE_VIEW_SIGNING_SALT") || "MXNTK//1Uc1R5wIKBGTZyTPPEQyVxSo3" livebook_secret_key_base = System.get_env("LIVEBOOK_SECRET_KEY_BASE") || "vJP36v4Gi2Orw8b8iBRg6ZFdzXKLvcRYkk1AaMLYX0+ry7k5XaJXd/LY/itmoxPP" livebook_live_view_signing_salt = System.get_env("LIVEBOOK_LIVE_VIEW_SIGNING_SALT") || "TolmUusQ6//zaa5GZHu7DG2V3YAgOoP/" config :rewind, :prometheus_metrics_port, {:system, :integer, "REWIND_PROMETHEUS_METRICS_PORT", 9568} # Telemetry config :telemetry_poller, :default, period: 1_000 # Database partition = System.get_env("MIX_TEST_PARTITION") default_database_url = "postgres://postgres:postgres@localhost:5432/rewind_?" configured_database_url = System.get_env("DATABASE_URL") || default_database_url database_url = "#{String.replace(configured_database_url, "?", env)}#{partition}" # Rewind config :rewind, :prometheus_metrics_port, {:system, :integer, "REWIND_PROMETHEUS_METRICS_PORT", 9572} config :rewind, Rewind.Repo, url: database_url, pool_size: 5 config :rewind, RewindWeb.Endpoint, server: true, url: [host: rewind_host, port: http_port], render_errors: [view: RewindWeb.ErrorView, accepts: ~w(html json), layout: false], pubsub_server: Tai.PubSub, secret_key_base: rewind_secret_key_base, live_view: [signing_salt: rewind_live_view_signing_salt] config :rewind, models: %{} # Workbench config :workbench, :prometheus_metrics_port, {:system, :integer, "WORKBENCH_PROMETHEUS_METRICS_PORT", 9569} config :workbench, Workbench.Repo, url: database_url, pool_size: 5 config :workbench, WorkbenchWeb.Endpoint, http: [port: http_port], url: [host: workbench_host, port: http_port], render_errors: [view: WorkbenchWeb.ErrorView, accepts: ~w(html json)], pubsub_server: Tai.PubSub, secret_key_base: workbench_secret_key_base, live_view: [signing_salt: workbench_live_view_signing_salt], server: false config :workbench, asset_aliases: %{ btc: [:xbt], usd: [:busd, :pax, :usdc, :usdt, :tusd] }, balance_snapshot: %{ enabled: {:system, :boolean, "BALANCE_SNAPSHOT_ENABLED", false}, boot_delay_ms: {:system, :integer, "BALANCE_SNAPSHOT_BOOT_DELAY_MS", 10_000}, every_ms: {:system, :integer, "BALANCE_SNAPSHOT_EVERY_MS", 60_000}, btc_usd_venue: {:system, :atom, "BALANCE_SNAPSHOT_BTC_USD_VENUE", :ftx}, btc_usd_symbol: {:system, :atom, "BALANCE_SNAPSHOT_BTC_USD_SYMBOL", :"btc-perp"}, usd_quote_venue: {:system, :atom, "BALANCE_SNAPSHOT_USD_QUOTE_VENUE", :ftx}, usd_quote_asset: {:system, :atom, "BALANCE_SNAPSHOT_USD_QUOTE_ASSET", :usd}, quote_pairs: [ftx: :usd] } # History config :history, :prometheus_metrics_port, {:system, :integer, "HISTORY_PROMETHEUS_METRICS_PORT", 9570} config :history, History.Repo, url: database_url, pool_size: 5 config :history, HistoryWeb.Endpoint, http: [port: http_port], url: [host: history_host, port: http_port], render_errors: [view: HistoryWeb.ErrorView, accepts: ~w(html json)], pubsub_server: Tai.PubSub, secret_key_base: history_secret_key_base, live_view: [signing_salt: history_live_view_signing_salt], server: false config :history, :download_candle_chunks_concurrency, {:system, :integer, "DOWNLOAD_CANDLE_CHUNKS_CONCURRENCY", 2} config :history, data_adapters: %{ binance: History.Sources.Binance, bitmex: History.Sources.Bitmex, bybit: History.Sources.Bybit, gdax: History.Sources.Gdax, ftx: History.Sources.Ftx, okex: History.Sources.OkEx } # Livebook config :livebook, LivebookWeb.Endpoint, url: [host: livebook_host, port: http_port], pubsub_server: Livebook.PubSub, secret_key_base: livebook_secret_key_base, live_view: [signing_salt: livebook_live_view_signing_salt], server: false config :livebook, :root_path, Livebook.Config.root_path!("LIVEBOOK_ROOT_PATH") if password = Livebook.Config.password!("LIVEBOOK_PASSWORD") do config :livebook, authentication_mode: :password, password: password else config :livebook, token: Livebook.Utils.random_id() end if ip = Livebook.Config.ip!("LIVEBOOK_IP") do config :livebook, LivebookWeb.Endpoint, http: [ip: ip] end config :livebook, :cookie, Livebook.Config.cookie!("LIVEBOOK_COOKIE") || Livebook.Utils.random_cookie() config :livebook, :default_runtime, Livebook.Config.default_runtime!("LIVEBOOK_DEFAULT_RUNTIME") || {Livebook.Runtime.ElixirStandalone, []} # Master Proxy config :master_proxy, # any Cowboy options are allowed http: [:inet6, port: http_port], # https: [:inet6, port: 4443], backends: [ %{ host: ~r/#{rewind_host}/, phoenix_endpoint: RewindWeb.Endpoint }, %{ host: ~r/#{workbench_host}/, phoenix_endpoint: WorkbenchWeb.Endpoint }, %{ host: ~r/#{history_host}/, phoenix_endpoint: HistoryWeb.Endpoint }, %{ host: ~r/#{livebook_host}/, phoenix_endpoint: LivebookWeb.Endpoint } ] # Navigation config :navigator, links: %{ rewind: [ %{ label: "Rewind", link: {RewindWeb.Router.Helpers, :home_path, [RewindWeb.Endpoint, :index]}, class: "text-4xl" }, %{ label: "Models", link: {RewindWeb.Router.Helpers, :model_path, [RewindWeb.Endpoint, :index]} }, %{ label: "Workbench", link: {WorkbenchWeb.Router.Helpers, :balance_all_url, [WorkbenchWeb.Endpoint, :index]} }, %{ label: "History", link: {HistoryWeb.Router.Helpers, :trade_url, [HistoryWeb.Endpoint, :index]} }, %{ label: "Livebook", link: {LivebookWeb.Router.Helpers, :home_url, [LivebookWeb.Endpoint, :page]} }, %{ label: "Grafana", link: "http://#{grafana_host}" }, %{ label: "Prometheus", link: "http://#{prometheus_host}" } ], workbench: [ %{ label: "Workbench", link: {WorkbenchWeb.Router.Helpers, :balance_all_path, [WorkbenchWeb.Endpoint, :index]}, class: "text-4xl" }, %{ label: "Balances", link: {WorkbenchWeb.Router.Helpers, :balance_day_path, [WorkbenchWeb.Endpoint, :index]} }, %{ label: "Wallets", link: {WorkbenchWeb.Router.Helpers, :wallet_path, [WorkbenchWeb.Endpoint, :index]} }, %{ label: "Accounts", link: {WorkbenchWeb.Router.Helpers, :account_path, [WorkbenchWeb.Endpoint, :index]} }, %{ label: "Orders", link: {WorkbenchWeb.Router.Helpers, :order_path, [WorkbenchWeb.Endpoint, :index]} }, %{ label: "Positions", link: {WorkbenchWeb.Router.Helpers, :position_path, [WorkbenchWeb.Endpoint, :index]} }, %{ label: "Products", link: {WorkbenchWeb.Router.Helpers, :product_path, [WorkbenchWeb.Endpoint, :index]} }, %{ label: "Fees", link: {WorkbenchWeb.Router.Helpers, :fee_path, [WorkbenchWeb.Endpoint, :index]} }, %{ label: "Venues", link: {WorkbenchWeb.Router.Helpers, :venue_path, [WorkbenchWeb.Endpoint, :index]} }, %{ label: "Fleets", link: {WorkbenchWeb.Router.Helpers, :fleet_path, [WorkbenchWeb.Endpoint, :index]} }, %{ label: "Rewind", link: {RewindWeb.Router.Helpers, :home_url, [RewindWeb.Endpoint, :index]} }, %{ label: "History", link: {HistoryWeb.Router.Helpers, :trade_url, [HistoryWeb.Endpoint, :index]} }, %{ label: "Livebook", link: {LivebookWeb.Router.Helpers, :home_url, [LivebookWeb.Endpoint, :page]} }, %{ label: "Grafana", link: "http://#{grafana_host}" }, %{ label: "Prometheus", link: "http://#{prometheus_host}" } ], history: [ %{ label: "History", link: {HistoryWeb.Router.Helpers, :trade_path, [HistoryWeb.Endpoint, :index]}, class: "text-4xl" }, %{ label: "Data", link: {HistoryWeb.Router.Helpers, :trade_path, [HistoryWeb.Endpoint, :index]} }, %{ label: "Products", link: {HistoryWeb.Router.Helpers, :product_path, [HistoryWeb.Endpoint, :index]} }, %{ label: "Tokens", link: {HistoryWeb.Router.Helpers, :token_path, [HistoryWeb.Endpoint, :index]} }, %{ label: "Rewind", link: {RewindWeb.Router.Helpers, :home_url, [RewindWeb.Endpoint, :index]} }, %{ label: "Workbench", link: {WorkbenchWeb.Router.Helpers, :balance_all_url, [WorkbenchWeb.Endpoint, :index]} }, %{ label: "Livebook", link: {LivebookWeb.Router.Helpers, :home_url, [LivebookWeb.Endpoint, :page]} }, %{ label: "Grafana", link: "http://#{grafana_host}" }, %{ label: "Prometheus", link: "http://#{prometheus_host}" } ] } # Notifications config :notified, pubsub_server: Tai.PubSub config :notified, receivers: [ {NotifiedPhoenix.Receivers.Speech, []}, {NotifiedPhoenix.Receivers.BrowserNotification, []} ] config :notified_phoenix, to_list: {WorkbenchWeb.Router.Helpers, :notification_path, [WorkbenchWeb.Endpoint, :index]} # Tai config :tai, Tai.Orders.OrderRepo, url: database_url, pool_size: 5 config :tai, order_workers: 2 config :tai, order_workers_max_overflow: 0 config :tai, order_transition_workers: 2 config :tai, send_orders: false config :tai, fleets: %{} config :tai, venues: %{} # Conditional configuration if config_env() == :dev do # 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 # Configure your database config :rewind, Rewind.Repo, show_sensitive_data_on_connection_error: true # 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 :rewind, RewindWeb.Endpoint, debug_errors: true, code_reloader: true, check_origin: false, watchers: [ npm: [ "run", "watch", cd: Path.expand("../assets", __DIR__) ] ] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # 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 :rewind, RewindWeb.Endpoint, live_reload: [ patterns: [ ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", ~r"priv/gettext/.*(po)$", ~r"lib/rewind_web/(live|views)/.*(ex)$", ~r"lib/rewind_web/templates/.*(eex)$" ] ] config :rewind, :download_candle_chunks_concurrency, {:system, :integer, "DOWNLOAD_CANDLE_CHUNKS_CONCURRENCY", 2} config :tai, venues: %{ ftx: [ start_on_boot: true, adapter: Tai.VenueAdapters.Ftx, products: "*", order_books: "" ] } unless System.get_env("DOCKER") == "true" do config :logger, backends: [{LoggerFileBackend, :file_log}] config :logger, :file_log, path: "./logs/#{config_env()}.log", level: :info end end if config_env() == :test do config :tai, Tai.Orders.OrderRepo, pool: Ecto.Adapters.SQL.Sandbox, show_sensitive_data_on_connection_error: true config :tai, e2e_app: :rewind # config :echo_boy, port: 4100 config :logger, backends: [{LoggerFileBackend, :file_log}] config :logger, :file_log, path: "./logs/#{config_env()}.log", level: :info end
31.806075
141
0.667156
9ed0660cc52deb000023dca5fb864ff76ad631a3
1,096
exs
Elixir
exercises/binary-search/example.exs
martinsvalin/xelixir
9469d92e7eecb528a05a8da923d8271ed303c058
[ "MIT" ]
null
null
null
exercises/binary-search/example.exs
martinsvalin/xelixir
9469d92e7eecb528a05a8da923d8271ed303c058
[ "MIT" ]
null
null
null
exercises/binary-search/example.exs
martinsvalin/xelixir
9469d92e7eecb528a05a8da923d8271ed303c058
[ "MIT" ]
null
null
null
defmodule BinarySearch do @doc """ Searches for a key in the list using the binary search algorithm. It returns :not_found if the key is not in the list. Otherwise returns the tuple {:ok, index}. ## Examples iex> BinarySearch.search([], 2) :not_found iex> BinarySearch.search([1, 3, 5], 2) :not_found iex> BinarySearch.search([1, 3, 5], 5) {:ok, 2} """ @spec search(Enumerable.t, integer) :: {:ok, integer} | :not_found def search([], _key), do: :not_found def search(list, key) do if Enum.sort(list) != list do raise ArgumentError, "expected list to be sorted" end do_search(list, key, 0, length(list) - 1) end defp do_search(_list, _key, low, high) when high < low, do: :not_found defp do_search(list, key, low, high) do middle = div(low + high, 2) middle_value = Enum.at(list, middle) cond do key < middle_value -> do_search(list, key, low, middle - 1) key > middle_value -> do_search(list, key, middle + 1, high) true -> {:ok, middle} end end end
26.095238
72
0.609489
9ed07320795ef623acb68cee5011b266d7b172d6
648
ex
Elixir
testData/org/elixir_lang/parser_definition/matched_dot_operator_call_operation/one_argument_parsing_test_case/AtNonNumericOperation.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
1,668
2015-01-03T05:54:27.000Z
2022-03-25T08:01:20.000Z
testData/org/elixir_lang/parser_definition/matched_dot_operator_call_operation/one_argument_parsing_test_case/AtNonNumericOperation.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
2,018
2015-01-01T22:43:39.000Z
2022-03-31T20:13:08.000Z
testData/org/elixir_lang/parser_definition/matched_dot_operator_call_operation/one_argument_parsing_test_case/AtNonNumericOperation.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
145
2015-01-15T11:37:16.000Z
2021-12-22T05:51:02.000Z
@non_numeric.and positional @non_numeric.&& positional @non_numeric.|> positional @non_numeric.@ positional @non_numeric.& positional @non_numeric.== positional @non_numeric.+ positional @non_numeric.^^^ positional @non_numeric.<- positional @non_numeric.in positional @non_numeric.= positional @non_numeric./ positional @non_numeric.* positional @non_numeric.or positional @non_numeric.|| positional @non_numeric.| positional @non_numeric.<= positional @non_numeric.-> positional @non_numeric.<> positional @non_numeric.^ positional @non_numeric.not positional @non_numeric.after positional @non_numeric.do positional @non_numeric.when positional
25.92
29
0.810185
9ed096fe670708a6c3a5f448821c74e1dd68f8e7
687
ex
Elixir
src/lib/changelog/wavestreamer.ex
thenets/docker-chocoquest
856fa5ff41a5831ed67b1ef865cd8951df5af023
[ "MIT" ]
1
2018-01-22T20:07:10.000Z
2018-01-22T20:07:10.000Z
lib/changelog/wavestreamer.ex
joebew42/changelog.com
da4ec68d15f3a2b4b6c29033443d7e7afe814d18
[ "MIT" ]
null
null
null
lib/changelog/wavestreamer.ex
joebew42/changelog.com
da4ec68d15f3a2b4b6c29033443d7e7afe814d18
[ "MIT" ]
null
null
null
defmodule Changelog.Wavestreamer do defmodule Stats do defstruct streaming: false, listeners: 0 end def host do "http://knight.wavestreamer.com:1882" end def live_url do host() <> "/Live" end def is_streaming do stats = get_stats() stats.streaming end def stats_url do host() <> "/stats?sid=1&json=1" end def get_stats do try do response = HTTPoison.get!(stats_url()) decoded = Poison.decode!(response.body) %Stats{streaming: (decoded["streamstatus"] == 1), listeners: decoded["currentlisteners"]} rescue HTTPoison.Error -> %Stats{} Poison.SyntaxError -> %Stats{} end end end
19.628571
55
0.630277
9ed0ad42c0aed4d5309ed113067238c910dfba12
1,024
exs
Elixir
test/xdr/types/ext_test.exs
einerzg/stellar_base
2d10c5fc3b8159efc5de10b5c7c665e3b57b3d8f
[ "MIT" ]
3
2021-08-17T20:32:45.000Z
2022-03-13T20:26:02.000Z
test/xdr/types/ext_test.exs
einerzg/stellar_base
2d10c5fc3b8159efc5de10b5c7c665e3b57b3d8f
[ "MIT" ]
45
2021-08-12T20:19:41.000Z
2022-03-27T21:00:10.000Z
test/xdr/types/ext_test.exs
einerzg/stellar_base
2d10c5fc3b8159efc5de10b5c7c665e3b57b3d8f
[ "MIT" ]
2
2021-09-22T23:11:13.000Z
2022-01-23T03:19:11.000Z
defmodule StellarBase.XDR.ExtTest do use ExUnit.Case alias StellarBase.XDR.Ext describe "Ext" do setup do %{ transaction_ext: Ext.new(), binary: <<0, 0, 0, 0>> } end test "new/1", %{transaction_ext: transaction_ext} do ^transaction_ext = Ext.new() end test "encode_xdr/1", %{transaction_ext: transaction_ext, binary: binary} do {:ok, ^binary} = Ext.encode_xdr(transaction_ext) end test "encode_xdr!/1", %{transaction_ext: transaction_ext, binary: binary} do ^binary = Ext.encode_xdr!(transaction_ext) end test "decode_xdr/2", %{transaction_ext: transaction_ext, binary: binary} do {:ok, {^transaction_ext, ""}} = Ext.decode_xdr(binary) end test "decode_xdr/2 with an invalid binary" do {:error, :not_binary} = Ext.decode_xdr(1234) end test "decode_xdr!/2", %{transaction_ext: transaction_ext, binary: binary} do {^transaction_ext, ^binary} = Ext.decode_xdr!(binary <> binary) end end end
26.25641
80
0.646484
9ed0f5c0c5d11dbc826f02f84cc256fa87e7e798
495
ex
Elixir
nebulex_telemetry_example/lib/nebulex_telemetry_example/hook.ex
cabol/nebulex_examples
21bd2673eecfc0b5c7a2807a3a47488d99a7d725
[ "MIT" ]
25
2017-07-30T01:27:54.000Z
2021-12-10T16:41:03.000Z
nebulex_telemetry_example/lib/nebulex_telemetry_example/hook.ex
cabol/nebulex_examples
21bd2673eecfc0b5c7a2807a3a47488d99a7d725
[ "MIT" ]
2
2019-11-12T09:41:26.000Z
2021-11-08T13:51:24.000Z
nebulex_telemetry_example/lib/nebulex_telemetry_example/hook.ex
cabol/nebulex_examples
21bd2673eecfc0b5c7a2807a3a47488d99a7d725
[ "MIT" ]
1
2019-01-08T19:06:54.000Z
2019-01-08T19:06:54.000Z
defmodule NebulexTelemetryExample.Profiling do alias Nebulex.Hook def prof(%Hook{step: :before}) do System.system_time(:microsecond) end def prof(%Hook{step: :after_return, acc: start}) do diff = System.system_time(:microsecond) - start IO.puts("#=> Duration: #{diff}") end end defmodule NebulexTelemetryExample.Hoook do use Nebulex.Hook @decorate around(&NebulexTelemetryExample.Profiling.prof/1) def test(var) do :ok = Process.sleep(1000) var end end
21.521739
61
0.715152
9ed1112eb82d1301a561d7778840352b9bac1ae0
124
exs
Elixir
mssqlsample/test/mssqlsample_test.exs
Dmdv/ElixirPlayground
02d9e8a7fdd6e8742e200430debc9f0ec7fd28a1
[ "Apache-2.0" ]
null
null
null
mssqlsample/test/mssqlsample_test.exs
Dmdv/ElixirPlayground
02d9e8a7fdd6e8742e200430debc9f0ec7fd28a1
[ "Apache-2.0" ]
null
null
null
mssqlsample/test/mssqlsample_test.exs
Dmdv/ElixirPlayground
02d9e8a7fdd6e8742e200430debc9f0ec7fd28a1
[ "Apache-2.0" ]
null
null
null
defmodule MssqlsampleTest do use ExUnit.Case doctest Mssqlsample test "the truth" do assert 1 + 1 == 2 end end
13.777778
28
0.693548
9ed13c31bac0d5da4636d2d478ed57c5c6c923b8
153
exs
Elixir
test/test_helper.exs
tteerawat/bitly-elixir
a6e3842516d49df9f4cc219d699ff6c5bf50cb24
[ "MIT" ]
2
2019-09-06T08:13:57.000Z
2020-09-18T05:20:39.000Z
test/test_helper.exs
tteerawat/bitly-elixir
a6e3842516d49df9f4cc219d699ff6c5bf50cb24
[ "MIT" ]
null
null
null
test/test_helper.exs
tteerawat/bitly-elixir
a6e3842516d49df9f4cc219d699ff6c5bf50cb24
[ "MIT" ]
2
2020-02-25T08:09:55.000Z
2020-03-19T22:28:33.000Z
ExUnit.start() {:ok, _} = Application.ensure_all_started(:inets) ExVCR.Config.filter_sensitive_data("access_token=[^\&]+", "access_token=ACCESS_TOKEN")
30.6
86
0.75817
9ed145f681b42fa776b31d8eab7f45d6ece9728a
2,815
ex
Elixir
lib/gen_amqp/worker.ex
jogeraca/gen_amqp
4ac8bb55d4da9e5202a0e2dca3de437cbc9bc264
[ "MIT" ]
null
null
null
lib/gen_amqp/worker.ex
jogeraca/gen_amqp
4ac8bb55d4da9e5202a0e2dca3de437cbc9bc264
[ "MIT" ]
null
null
null
lib/gen_amqp/worker.ex
jogeraca/gen_amqp
4ac8bb55d4da9e5202a0e2dca3de437cbc9bc264
[ "MIT" ]
null
null
null
defmodule GenAMQP.PoolWorker do alias GenAMQP.Chan require Logger def start_link(_) do GenServer.start_link(__MODULE__, nil, []) end def init(_) do {:ok, nil} end def handle_call({:do_work, data}, _from, state) do {:reply, work(data), state} end defp work(%{ event: event, exec_module: exec_module, before_funcs: before_funcs, after_funcs: after_funcs, chan: chan, payload: payload, meta: meta }) do payload = reduce_with_funcs(before_funcs, event, payload) {reply?, resp} = try do case apply(exec_module, :execute, [payload]) do {:reply, resp} -> {true, resp} :noreply -> {false, nil} other -> case apply(exec_module, :handle, [other]) do {:reply, resp} -> {true, resp} :noreply -> {false, nil} end end rescue e -> Logger.error("STACKTRACE - RESCUE") st = System.stacktrace() Logger.error("EXCEPTION: #{Exception.message(e)}") Logger.error(inspect(st)) case create_error([e, st]) do {:reply, resp} -> {true, resp} :noreply -> {false, nil} end catch kind, reason -> Logger.error("STACKTRACE - EXIT") st = System.stacktrace() Logger.error(inspect(st)) case create_error([kind, reason, st]) do {:reply, resp} -> {true, resp} :noreply -> {false, nil} end end resp = reduce_with_funcs(after_funcs, event, resp) if reply? do reply(chan, meta, resp) end validation_error([resp]) end defp reply( _chan, %{reply_to: :undefined, correlation_id: :undefined}, _resp ), do: nil defp reply(chan, %{reply_to: _, correlation_id: _} = meta, resp) when is_binary(resp) do Chan.response(chan, meta, resp) end defp reply(chan, %{reply_to: _, correlation_id: _} = meta, resp) do Logger.error("message in wrong type #{inspect(resp)}") Chan.response(chan, meta, create_error("message in wrong type")) end def error_handler() do Application.get_env(:gen_amqp, :error_handler) end defp create_error(args) do sol = apply(error_handler(), :handle, args) IO.puts("SOL = #{inspect(sol)}") sol end @spec validation_error(any()) :: {:ok, any()} | {:error, any()} defp validation_error(args), do: apply(error_handler(), :validate_response, args) defp reduce_with_funcs(funcs, event, payload) do Enum.reduce(funcs, payload, fn f, acc -> f.(event, acc) end) end end
23.264463
69
0.544227
9ed156277ba301b4c670223a64c7567f16045284
35
exs
Elixir
test/test_helper.exs
Eweev/elixir_wit
edb558bbce547287cf58003ef7ef9b1c826e1904
[ "MIT" ]
57
2016-05-03T15:35:12.000Z
2020-11-29T21:02:17.000Z
test/test_helper.exs
DriesDeBackker/quarp-reactivity
88e297818df4c9fd85af0c14dabe5edc4788ffd4
[ "MIT" ]
12
2016-09-11T05:46:27.000Z
2018-09-24T06:38:52.000Z
test/test_helper.exs
DriesDeBackker/quarp-reactivity
88e297818df4c9fd85af0c14dabe5edc4788ffd4
[ "MIT" ]
17
2016-05-03T15:35:27.000Z
2020-11-27T22:01:45.000Z
ExUnit.start(exclude: [:disabled])
17.5
34
0.742857
9ed182d1372a6bf569a0246dec8c0712cc5b9578
602
exs
Elixir
config/dev.exs
esl/elixometer
6678c97f64ac8a4cf7ecbf32a4d342576d466b69
[ "Apache-2.0" ]
1
2021-03-11T23:38:37.000Z
2021-03-11T23:38:37.000Z
config/dev.exs
esl/elixometer
6678c97f64ac8a4cf7ecbf32a4d342576d466b69
[ "Apache-2.0" ]
null
null
null
config/dev.exs
esl/elixometer
6678c97f64ac8a4cf7ecbf32a4d342576d466b69
[ "Apache-2.0" ]
2
2021-03-11T23:58:01.000Z
2022-03-06T10:48:34.000Z
use Mix.Config config :exometer_core, report: [reporters: []] config :lager, [ log_root: 'log', handlers: [ lager_console_backend: [level: :info], lager_file_backend: [file: 'error.log', level: :error, formatter: :lager_default_formatter, formatter_config: [:date, " ", :time, " [", :severity, "]", :pid, " ", :message, "\n"]], lager_file_backend: [file: 'console.log', level: :debug] ]] config :elixometer, reporter: :exometer_report_tty, update_frequency: 1000, env: Mix.env, metric_prefix: "elixometer"
30.1
113
0.594684
9ed1c43e4653508d0601f78be77472b5464a3c66
54
ex
Elixir
apps/language_server/test/fixtures/umbrella_dialyzer/apps/app2/lib/app2.ex
ihabunek/elixir-ls
a8bdf9304f04254160c9fc982ad314a50085c51a
[ "Apache-2.0" ]
865
2018-10-31T20:29:13.000Z
2022-03-29T11:13:39.000Z
apps/language_server/test/fixtures/umbrella_dialyzer/apps/app2/lib/app2.ex
ihabunek/elixir-ls
a8bdf9304f04254160c9fc982ad314a50085c51a
[ "Apache-2.0" ]
441
2019-01-05T02:33:52.000Z
2022-03-30T20:56:50.000Z
apps/language_server/test/fixtures/umbrella_dialyzer/apps/app2/lib/app2.ex
ihabunek/elixir-ls
a8bdf9304f04254160c9fc982ad314a50085c51a
[ "Apache-2.0" ]
126
2018-11-12T19:16:53.000Z
2022-03-26T13:27:50.000Z
defmodule App2 do def error do :error end end
9
17
0.666667
9ed1c4e428ef529cdb8d022655480467cebea8c6
1,033
exs
Elixir
config/config.exs
sinorga/phx_template
730a44df362c1e035cb8afd55d2e49d44fa60632
[ "MIT" ]
null
null
null
config/config.exs
sinorga/phx_template
730a44df362c1e035cb8afd55d2e49d44fa60632
[ "MIT" ]
null
null
null
config/config.exs
sinorga/phx_template
730a44df362c1e035cb8afd55d2e49d44fa60632
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. # # This configuration file is loaded before any dependency and # is restricted to this project. # General application configuration use Mix.Config config :phx_template, ecto_repos: [PhxTemplate.Repo] # Configures the endpoint config :phx_template, PhxTemplateWeb.Endpoint, url: [host: "localhost"], secret_key_base: "V3yWjewYgljoLQhDfZlO4t3u54FlYPD8CrDiOqE9LWBFCFDLbkPNMRYMU6sLWD0z", render_errors: [view: PhxTemplateWeb.ErrorView, accepts: ~w(html json)], pubsub: [name: PhxTemplate.PubSub, adapter: Phoenix.PubSub.PG2] # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:request_id] # Use Jason for JSON parsing in Phoenix config :phoenix, :json_library, Jason # 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"
33.322581
86
0.777348
9ed1c57558f20a9a2c2d86483bfbe2048bf3e80a
1,234
exs
Elixir
test/new_relixir/plug/exception_test.exs
edipox/new-relixir
00de7b6016b840d14004c32e562604de25c0c9b5
[ "MIT" ]
null
null
null
test/new_relixir/plug/exception_test.exs
edipox/new-relixir
00de7b6016b840d14004c32e562604de25c0c9b5
[ "MIT" ]
null
null
null
test/new_relixir/plug/exception_test.exs
edipox/new-relixir
00de7b6016b840d14004c32e562604de25c0c9b5
[ "MIT" ]
null
null
null
defmodule ExceptionTest do use ExUnit.Case use Plug.Test defmodule TestException do defexception plug_status: 403, message: "oops" end defmodule ErrorRaisingPlug do defmacro __using__(_env) do quote do def call(conn, _opts) do raise Plug.Conn.WrapperError, conn: conn, kind: :error, stack: System.stacktrace, reason: TestException.exception([]) end end end end defmodule TestPlug do use NewRelixir.Plug.Exception use ErrorRaisingPlug end defmodule FakeReporter do def record_error(transaction, exception) do send self(), {:record_error, {transaction, exception}} end end setup do Application.put_env(:new_relixir, :reporter, FakeReporter) end test "Raising an error on failure" do conn = conn(:get, "/") assert_raise Plug.Conn.WrapperError, fn -> TestPlug.call(conn, []) end assert_received {:record_error, {"/", {:error, %TestException{}}}} end test "Includes path data in report" do conn = conn(:get, "/some_path") catch_error TestPlug.call(conn, []) assert_received {:record_error, {path, {:error, %TestException{}}}} assert path == "/some_path" end end
22.436364
71
0.659643
9ed1cae306e1abcb579a15840d610b26e61e2a77
382
exs
Elixir
test/acceptance/ast/empty_test.exs
ZeLarpMaster/earmark
35c9661d6647059e507c0278347e21d92351c417
[ "Apache-1.1" ]
null
null
null
test/acceptance/ast/empty_test.exs
ZeLarpMaster/earmark
35c9661d6647059e507c0278347e21d92351c417
[ "Apache-1.1" ]
null
null
null
test/acceptance/ast/empty_test.exs
ZeLarpMaster/earmark
35c9661d6647059e507c0278347e21d92351c417
[ "Apache-1.1" ]
1
2020-03-31T19:53:15.000Z
2020-03-31T19:53:15.000Z
defmodule Acceptance.Ast.EmptyTest do use ExUnit.Case, async: true @moduletag :ast test "empty" do markdown = "" ast = [] messages = [] assert Earmark.as_ast(markdown) == {:ok, ast, messages} end test "almost empty" do markdown = " " ast = [] messages = [] assert Earmark.as_ast(markdown) == {:ok, ast, messages} end end
16.608696
59
0.581152
9ed1cb962bc2c897e885bf56ab5e2d83e34c0f8f
26,987
ex
Elixir
lib/phoenix_live_view/test/client_proxy.ex
joshuataylor/phoenix_live_view
4b4023c07b5c082505961139c4a5c92045c95e23
[ "MIT" ]
null
null
null
lib/phoenix_live_view/test/client_proxy.ex
joshuataylor/phoenix_live_view
4b4023c07b5c082505961139c4a5c92045c95e23
[ "MIT" ]
null
null
null
lib/phoenix_live_view/test/client_proxy.ex
joshuataylor/phoenix_live_view
4b4023c07b5c082505961139c4a5c92045c95e23
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveViewTest.ClientProxy do @moduledoc false use GenServer defstruct session_token: nil, static_token: nil, module: nil, endpoint: nil, pid: nil, proxy: nil, topic: nil, ref: nil, rendered: nil, children: [], child_statics: %{}, id: nil, connect_params: %{}, connect_info: %{} alias Phoenix.LiveViewTest.{ClientProxy, DOM, Element, View} @doc """ Encoding used by the Channel serializer. """ def encode!(msg), do: msg @doc """ Starts a client proxy. ## Options * `:caller` - the required `{ref, pid}` pair identifying the caller. * `:view` - the required `%Phoenix.LiveViewTest.View{}` * `:html` - the required string of HTML for the document. """ def start_link(opts) do GenServer.start_link(__MODULE__, opts) end def init(opts) do # Since we are always running in the test client, # we will disable our own logging and let the client # do the job. Logger.disable(self()) {_caller_pid, _caller_ref} = caller = Keyword.fetch!(opts, :caller) root_html = Keyword.fetch!(opts, :html) root_view = Keyword.fetch!(opts, :proxy) session = Keyword.fetch!(opts, :session) url = Keyword.fetch!(opts, :url) state = %{ join_ref: 0, ref: 0, caller: caller, views: %{}, ids: %{}, pids: %{}, replies: %{}, root_view: nil, html: root_html, session: session } try do {root_view, rendered} = mount_view(state, root_view, url) new_state = state |> Map.put(:root_view, root_view) |> put_view(root_view, rendered) |> detect_added_or_removed_children(root_view, root_html) send_caller(new_state, {:ok, build_view(root_view), DOM.to_html(new_state.html)}) {:ok, new_state} catch :throw, {:stop, {:shutdown, reason}, _state} -> send_caller(state, {:error, reason}) :ignore :throw, {:stop, reason, _} -> Process.unlink(elem(caller, 0)) {:stop, reason} end end defp build_view(%ClientProxy{} = proxy) do %{id: id, ref: ref, topic: topic, module: module, endpoint: endpoint, pid: pid} = proxy %View{id: id, pid: pid, proxy: {ref, topic, self()}, module: module, endpoint: endpoint} end defp mount_view(state, view, url) do ref = make_ref() case start_supervised_channel(state, view, ref, url) do {:ok, pid} -> mon_ref = Process.monitor(pid) receive do {^ref, {:ok, %{rendered: rendered}}} -> Process.demonitor(mon_ref, [:flush]) {%{view | pid: pid}, rendered} {^ref, {:error, %{live_redirect: opts}}} -> throw(stop_redirect(state, view.topic, {:live_redirect, opts})) {^ref, {:error, %{redirect: opts}}} -> throw(stop_redirect(state, view.topic, {:redirect, opts})) {^ref, {:error, reason}} -> throw({:stop, reason, state}) {:DOWN, ^mon_ref, _, _, reason} -> throw({:stop, reason, state}) end {:error, reason} -> throw({:stop, reason, state}) end end defp start_supervised_channel(state, view, ref, url) do socket = %Phoenix.Socket{ transport_pid: self(), serializer: __MODULE__, channel: view.module, endpoint: view.endpoint, private: %{connect_info: Map.put_new(view.connect_info, :session, state.session)}, topic: view.topic, join_ref: state.join_ref } params = %{ "session" => view.session_token, "static" => view.static_token, "url" => url, "params" => view.connect_params, "caller" => state.caller, "joins" => 0 } spec = {Phoenix.LiveView.Channel, {params, {self(), ref}, socket}} DynamicSupervisor.start_child(Phoenix.LiveView.DynamicSupervisor, spec) end def handle_info({:sync_children, topic, from}, state) do view = fetch_view_by_topic!(state, topic) children = Enum.flat_map(view.children, fn {id, _session} -> case fetch_view_by_id(state, id) do {:ok, child} -> [build_view(child)] :error -> [] end end) GenServer.reply(from, {:ok, children}) {:noreply, state} end def handle_info({:sync_render, operation, topic_or_element, from}, state) do view = fetch_view_by_topic!(state, proxy_topic(topic_or_element)) result = state |> root(view) |> select_node(topic_or_element) reply = case {operation, result} do {:find_element, {:ok, node}} -> {:ok, node} {:find_element, {:error, _, message}} -> {:raise, ArgumentError.exception(message)} {:has_element?, {:error, :none, _}} -> {:ok, false} {:has_element?, _} -> {:ok, true} end GenServer.reply(from, reply) {:noreply, state} end def handle_info( %Phoenix.Socket.Message{ event: "redirect", topic: _topic, payload: %{to: _to} = opts }, state ) do stop_redirect(state, state.root_view.topic, {:redirect, opts}) end def handle_info( %Phoenix.Socket.Message{ event: "live_patch", topic: _topic, payload: %{to: _to} = opts }, state ) do send_patch(state, state.root_view.topic, opts) {:noreply, state} end def handle_info( %Phoenix.Socket.Message{ event: "live_redirect", topic: _topic, payload: %{to: _to} = opts }, state ) do stop_redirect(state, state.root_view.topic, {:live_redirect, opts}) end def handle_info( %Phoenix.Socket.Message{ event: "diff", topic: topic, payload: diff }, state ) do {:noreply, merge_rendered(state, topic, diff)} end def handle_info(%Phoenix.Socket.Reply{} = reply, state) do %{ref: ref, payload: payload, topic: topic} = reply case fetch_reply(state, ref) do {:ok, {from, _pid}} -> state = drop_reply(state, ref) case payload do %{live_redirect: %{to: _to} = opts} -> stop_redirect(state, topic, {:live_redirect, opts}) %{live_patch: %{to: _to} = opts} -> send_patch(state, topic, opts) {:noreply, render_reply(reply, from, state)} %{redirect: %{to: _to} = opts} -> stop_redirect(state, topic, {:redirect, opts}) %{} -> {:noreply, render_reply(reply, from, state)} end :error -> {:noreply, state} end end def handle_info({:DOWN, _ref, :process, pid, reason}, state) do case fetch_view_by_pid(state, pid) do {:ok, _view} -> {:stop, reason, state} :error -> {:noreply, state} end end def handle_info({:socket_close, pid, reason}, state) do {:ok, view} = fetch_view_by_pid(state, pid) {:noreply, drop_view_by_id(state, view.id, reason)} end def handle_call({:live_children, topic}, from, state) do view = fetch_view_by_topic!(state, topic) :ok = Phoenix.LiveView.Channel.ping(view.pid) send(self(), {:sync_children, view.topic, from}) {:noreply, state} end def handle_call({:render, operation, topic_or_element}, from, state) do topic = proxy_topic(topic_or_element) %{pid: pid} = fetch_view_by_topic!(state, topic) :ok = Phoenix.LiveView.Channel.ping(pid) send(self(), {:sync_render, operation, topic_or_element, from}) {:noreply, state} end def handle_call({:render_event, topic_or_element, type, value}, from, state) do result = case topic_or_element do {topic, event} -> view = fetch_view_by_topic!(state, topic) {view, nil, event, stringify(:hook, value)} %Element{} = element -> view = fetch_view_by_topic!(state, proxy_topic(element)) root = root(state, view) with {:ok, node} <- select_node(root, element), :ok <- maybe_enabled(type, node, element), {:ok, event} <- maybe_event(type, node, element), {:ok, extra} <- maybe_values(type, node, element), {:ok, cid} <- maybe_cid(root, node) do {view, cid, event, DOM.deep_merge(extra, stringify(type, value))} end end case result do {view, cid, event, values} -> payload = %{ "cid" => cid, "type" => Atom.to_string(type), "event" => event, "value" => encode(type, values) } {:noreply, push_with_reply(state, from, view, "event", payload)} {:patch, topic, path} -> handle_call({:render_patch, topic, path}, from, state) {:stop, topic, reason} -> stop_redirect(state, topic, reason) {:error, _, message} -> {:reply, {:raise, ArgumentError.exception(message)}, state} end end def handle_call({:render_patch, topic, path}, from, state) do view = fetch_view_by_topic!(state, topic) ref = to_string(state.ref + 1) send(view.pid, %Phoenix.Socket.Message{ join_ref: state.join_ref, topic: view.topic, event: "link", payload: %{"url" => path}, ref: ref }) send_patch(state, state.root_view.topic, %{to: path}) {:noreply, put_reply(%{state | ref: state.ref + 1}, ref, from, view.pid)} end defp drop_view_by_id(state, id, reason) do {:ok, view} = fetch_view_by_id(state, id) push(state, view, "phx_leave", %{}) state = Enum.reduce(view.children, state, fn {child_id, _child_session}, acc -> drop_view_by_id(acc, child_id, reason) end) flush_replies( %{ state | ids: Map.delete(state.ids, view.id), views: Map.delete(state.views, view.topic), pids: Map.delete(state.pids, view.pid) }, view.pid, reason ) end defp flush_replies(state, pid, reason) do Enum.reduce(state.replies, state, fn {ref, {from, ^pid}}, acc -> GenServer.reply(from, {:error, reason}) drop_reply(acc, ref) {_ref, {_from, _pid}}, acc -> acc end) end defp fetch_reply(state, ref) do Map.fetch(state.replies, ref) end defp put_reply(state, ref, from, pid) do %{state | replies: Map.put(state.replies, ref, {from, pid})} end defp drop_reply(state, ref) do %{state | replies: Map.delete(state.replies, ref)} end defp put_child(state, %ClientProxy{} = parent, id, session) do update_in(state, [:views, parent.topic], fn %ClientProxy{} = parent -> %ClientProxy{parent | children: [{id, session} | parent.children]} end) end defp drop_child(state, %ClientProxy{} = parent, id, reason) do state |> update_in([:views, parent.topic], fn %ClientProxy{} = parent -> new_children = Enum.reject(parent.children, fn {cid, _session} -> id == cid end) %ClientProxy{parent | children: new_children} end) |> drop_view_by_id(id, reason) end defp verify_session(%ClientProxy{} = view) do Phoenix.LiveView.Static.verify_session(view.endpoint, view.session_token, view.static_token) end defp put_view(state, %ClientProxy{pid: pid} = view, rendered) do {:ok, %{view: module}} = verify_session(view) new_view = %ClientProxy{view | module: module, proxy: self(), pid: pid, rendered: rendered} Process.monitor(pid) patch_view( %{ state | views: Map.put(state.views, new_view.topic, new_view), pids: Map.put(state.pids, pid, new_view.topic), ids: Map.put(state.ids, new_view.id, new_view.topic) }, view, DOM.render_diff(rendered) ) end defp patch_view(state, view, child_html) do case DOM.patch_id(view.id, state.html, child_html) do {new_html, [_ | _] = deleted_cids} -> push(%{state | html: new_html}, view, "cids_destroyed", %{"cids" => deleted_cids}) {new_html, [] = _deleted_cids} -> %{state | html: new_html} end end defp stop_redirect(%{caller: {pid, _}} = state, topic, {_kind, opts} = reason) when is_binary(topic) do send_caller(state, {:redirect, topic, opts}) Process.unlink(pid) {:stop, {:shutdown, reason}, state} end defp fetch_view_by_topic!(state, topic), do: Map.fetch!(state.views, topic) defp fetch_view_by_topic(state, topic), do: Map.fetch(state.views, topic) defp fetch_view_by_pid(state, pid) when is_pid(pid) do with {:ok, topic} <- Map.fetch(state.pids, pid) do fetch_view_by_topic(state, topic) end end defp fetch_view_by_id(state, id) do with {:ok, topic} <- Map.fetch(state.ids, id) do fetch_view_by_topic(state, topic) end end defp render_reply(reply, from, state) do %{payload: diff, topic: topic} = reply new_state = merge_rendered(state, topic, diff) case fetch_view_by_topic(new_state, topic) do {:ok, view} -> GenServer.reply(from, {:ok, new_state.html |> DOM.inner_html!(view.id) |> DOM.to_html()}) new_state :error -> new_state end end defp merge_rendered(state, topic, %{diff: diff}), do: merge_rendered(state, topic, diff) defp merge_rendered(%{html: html_before} = state, topic, %{} = diff) do case diff do %{title: new_title} -> send_caller(state, {:title, new_title}) %{} -> :noop end case fetch_view_by_topic(state, topic) do {:ok, view} -> rendered = DOM.deep_merge(view.rendered, diff) new_view = %ClientProxy{view | rendered: rendered} %{state | views: Map.update!(state.views, topic, fn _ -> new_view end)} |> patch_view(new_view, DOM.render_diff(rendered)) |> detect_added_or_removed_children(new_view, html_before) :error -> state end end defp detect_added_or_removed_children(state, view, html_before) do new_state = recursive_detect_added_or_removed_children(state, view, html_before) {:ok, new_view} = fetch_view_by_topic(new_state, view.topic) ids_after = new_state.html |> DOM.all("[data-phx-view]") |> DOM.all_attributes("id") |> MapSet.new() Enum.reduce(new_view.children, new_state, fn {id, _session}, acc -> if id in ids_after do acc else drop_child(acc, new_view, id, {:shutdown, :left}) end end) end defp recursive_detect_added_or_removed_children(state, view, html_before) do state.html |> DOM.inner_html!(view.id) |> DOM.find_live_views() |> Enum.reduce(state, fn {id, session, static}, acc -> case fetch_view_by_id(acc, id) do {:ok, view} -> patch_view(acc, view, DOM.inner_html!(html_before, view.id)) :error -> static = static || Map.get(state.root_view.child_statics, id) child_view = build_child(view, id: id, session_token: session, static_token: static) {child_view, rendered} = mount_view(acc, child_view, nil) acc |> put_view(child_view, rendered) |> put_child(view, id, child_view.session_token) |> recursive_detect_added_or_removed_children(child_view, acc.html) end end) end defp send_caller(%{caller: {pid, ref}}, msg) when is_pid(pid) do send(pid, {ref, msg}) end defp send_patch(state, topic, %{to: _to} = opts) do send_caller(state, {:patch, topic, opts}) end defp push(state, view, event, payload) do ref = to_string(state.ref + 1) send(view.pid, %Phoenix.Socket.Message{ join_ref: state.join_ref, topic: view.topic, event: event, payload: payload, ref: ref }) %{state | ref: state.ref + 1} end defp push_with_reply(state, from, view, event, payload) do ref = to_string(state.ref + 1) state |> push(view, event, payload) |> put_reply(ref, from, view.pid) end def build(attrs) do attrs_with_defaults = attrs |> Keyword.merge(topic: Phoenix.LiveView.Utils.random_id()) |> Keyword.put_new_lazy(:ref, fn -> make_ref() end) struct(__MODULE__, attrs_with_defaults) end def build_child(%ClientProxy{ref: ref, proxy: proxy} = parent, attrs) do attrs |> Keyword.merge( ref: ref, proxy: proxy, endpoint: parent.endpoint ) |> build() end ## Element helpers defp proxy_topic(topic) when is_binary(topic), do: topic defp proxy_topic(%{proxy: {_ref, topic, _pid}}), do: topic defp root(state, view), do: DOM.by_id!(state.html, view.id) defp select_node(root, %Element{selector: selector, text_filter: nil}) do root |> DOM.child_nodes() |> DOM.maybe_one(selector) end defp select_node(root, %Element{selector: selector, text_filter: text_filter}) do nodes = root |> DOM.child_nodes() |> DOM.all(selector) filtered_nodes = Enum.filter(nodes, &(DOM.to_text(&1) =~ text_filter)) case {nodes, filtered_nodes} do {_, [filtered_node]} -> {:ok, filtered_node} {[], _} -> {:error, :none, "selector #{inspect(selector)} did not return any element within: \n\n" <> DOM.inspect_html(root)} {[node], []} -> {:error, :none, "selector #{inspect(selector)} did not match text filter #{inspect(text_filter)}, " <> "got: \n\n#{DOM.inspect_html(node)}"} {_, []} -> {:error, :none, "selector #{inspect(selector)} returned #{length(nodes)} elements " <> "but none matched the text filter #{inspect(text_filter)}: \n\n" <> DOM.inspect_html(nodes)} {_, _} -> {:error, :many, "selector #{inspect(selector)} returned #{length(nodes)} elements " <> "and #{length(filtered_nodes)} of them matched the text filter #{inspect(text_filter)}: \n\n " <> DOM.inspect_html(filtered_nodes)} end end defp select_node(root, _topic) do {:ok, root} end defp maybe_cid(_tree, nil) do {:ok, nil} end defp maybe_cid(tree, node) do case DOM.all_attributes(node, "phx-target") do [] -> {:ok, nil} ["#" <> _ = target] -> with {:ok, target} <- DOM.maybe_one(tree, target, "phx-target") do if cid = DOM.component_id(target) do {:ok, String.to_integer(cid)} else {:ok, nil} end end [maybe_integer] -> case Integer.parse(maybe_integer) do {cid, ""} -> {:ok, cid} _ -> {:error, :invalid, "expected phx-target to be either an ID or a CID, got: #{inspect(maybe_integer)}"} end end end defp maybe_event(:hook, node, %Element{event: event} = element) do true = is_binary(event) if DOM.attribute(node, "phx-hook") do if DOM.attribute(node, "id") do {:ok, event} else {:error, :invalid, "element selected by #{inspect(element.selector)} for phx-hook does not have an ID"} end else {:error, :invalid, "element selected by #{inspect(element.selector)} does not have phx-hook attribute"} end end # TODO: Remove this once deprecated paths have been removed defp maybe_event(_, _, %{event: event}) when is_binary(event) do {:ok, event} end defp maybe_event(:click, {"a", _, _} = node, element) do cond do event = DOM.attribute(node, "phx-click") -> {:ok, event} to = DOM.attribute(node, "href") -> case DOM.attribute(node, "data-phx-link") do "patch" -> {:patch, proxy_topic(element), to} "redirect" -> kind = DOM.attribute(node, "data-phx-link-state") || "push" {:stop, proxy_topic(element), {:live_redirect, %{to: to, kind: String.to_atom(kind)}}} nil -> {:stop, proxy_topic(element), {:redirect, %{to: to}}} end true -> {:error, :invalid, "clicked link selected by #{inspect(element.selector)} does not have phx-click or href attributes"} end end defp maybe_event(type, node, element) when type in [:keyup, :keydown] do cond do event = DOM.attribute(node, "phx-#{type}") -> {:ok, event} event = DOM.attribute(node, "phx-window-#{type}") -> {:ok, event} true -> {:error, :invalid, "element selected by #{inspect(element.selector)} does not have " <> "phx-#{type} or phx-window-#{type} attributes"} end end defp maybe_event(type, node, element) do if event = DOM.attribute(node, "phx-#{type}") do {:ok, event} else {:error, :invalid, "element selected by #{inspect(element.selector)} does not have phx-#{type} attribute"} end end defp maybe_enabled(_type, {tag, _, _}, %{form_data: form_data}) when tag != "form" and form_data != nil do {:error, :invalid, "a form element was given but the selected node is not a form, got #{inspect(tag)}}"} end defp maybe_enabled(type, node, element) do if DOM.attribute(node, "disabled") do {:error, :invalid, "cannot #{type} element #{inspect(element.selector)} because it is disabled"} else :ok end end defp maybe_values(:hook, _node, _element), do: {:ok, %{}} defp maybe_values(type, {tag, _, _} = node, element) when type in [:change, :submit] do if tag == "form" do defaults = node |> DOM.all("input, select, textarea") |> Enum.reverse() |> Enum.reduce(%{}, &form_defaults/2) stringified = stringify(type, element.form_data || %{}) case fill_in_map(Map.to_list(stringified), "", node) do :ok -> {:ok, DOM.deep_merge(defaults, stringified)} {:error, _, _} = error -> error end else {:error, :invalid, "phx-#{type} is only allowed in forms, got #{inspect(tag)}"} end end defp maybe_values(_type, node, _element) do {:ok, DOM.all_values(node)} end defp form_defaults(node, acc) do cond do DOM.attribute(node, "disabled") -> acc name = DOM.attribute(node, "name") -> form_defaults(node, name, acc) true -> acc end end defp form_defaults({"select", _, _} = node, name, acc) do options = DOM.all(node, "option") all_selected = if DOM.attribute(node, "multiple") do Enum.filter(options, &DOM.attribute(&1, "selected")) else List.wrap(Enum.find(options, &DOM.attribute(&1, "selected")) || List.first(options)) end all_selected |> Enum.reverse() |> Enum.reduce(acc, fn selected, acc -> Plug.Conn.Query.decode_pair({name, DOM.attribute(selected, "value")}, acc) end) end defp form_defaults({"textarea", _, [value]}, name, acc) do Plug.Conn.Query.decode_pair({name, value}, acc) end defp form_defaults({"input", _, _} = node, name, acc) do type = DOM.attribute(node, "type") || "text" value = DOM.attribute(node, "value") || "" cond do type in ["radio", "checkbox"] -> if DOM.attribute(node, "checked") do Plug.Conn.Query.decode_pair({name, value}, acc) else acc end type in ["image", "submit"] -> acc true -> Plug.Conn.Query.decode_pair({name, value}, acc) end end defp fill_in_map([{key, value} | rest], prefix, node) do case fill_in_type(value, fill_in_name(prefix, key), node) do :ok -> fill_in_map(rest, prefix, node) {:error, _, _} = error -> error end end defp fill_in_map([], _prefix, _node) do :ok end defp fill_in_type(%{} = value, key, node), do: fill_in_map(Map.to_list(value), key, node) defp fill_in_type(value, key, node), do: fill_in_value(value, key, node) @limited ["select", "multiple select", "checkbox", "radio", "hidden"] @forbidden ["submit", "image"] defp fill_in_value(value, name, node) do name = if is_list(value), do: name <> "[]", else: name {types, values} = node |> DOM.all("[name=#{inspect(name)}]:not([disabled])") |> collect_values([], []) limited? = Enum.all?(types, &(&1 in @limited)) cond do types == [] -> {:error, :invalid, "could not find non-disabled input, select or textarea with name #{inspect(name)} within:\n\n" <> DOM.inspect_html(DOM.all(node, "[name]"))} forbidden_type = Enum.find(types, &(&1 in @forbidden)) -> {:error, :invalid, "cannot provide value to #{inspect(name)} because #{forbidden_type} inputs are never submitted"} value = limited? && value |> List.wrap() |> Enum.find(&(&1 not in values)) -> {:error, :invalid, "value for #{hd(types)} #{inspect(name)} must be one of #{inspect(values)}, " <> "got: #{inspect(value)}"} true -> :ok end end defp collect_values([{"textarea", _, _} | nodes], types, values) do collect_values(nodes, ["textarea" | types], values) end defp collect_values([{"input", _, _} = node | nodes], types, values) do type = DOM.attribute(node, "type") || "text" if type in ["radio", "checkbox", "hidden"] do value = DOM.attribute(node, "value") || "" collect_values(nodes, [type | types], [value | values]) else collect_values(nodes, [type | types], values) end end defp collect_values([{"select", _, _} = node | nodes], types, values) do options = node |> DOM.all("option") |> Enum.map(&(DOM.attribute(&1, "value") || "")) if DOM.attribute(node, "multiple") do collect_values(nodes, ["multiple select" | types], Enum.reverse(options, values)) else collect_values(nodes, ["select" | types], Enum.reverse(options, values)) end end defp collect_values([_ | nodes], types, values) do collect_values(nodes, types, values) end defp collect_values([], types, values) do {types, Enum.reverse(values)} end defp fill_in_name("", name), do: name defp fill_in_name(prefix, name), do: prefix <> "[" <> name <> "]" defp encode(:form, value), do: Plug.Conn.Query.encode(value) defp encode(_, value), do: value defp stringify(:hook, value), do: do_stringify(value, & &1) defp stringify(_, value), do: do_stringify(value, &to_string/1) defp do_stringify(%{__struct__: _} = struct, fun), do: do_stringify_simple(struct, fun) defp do_stringify(%{} = params, fun), do: Enum.into(params, %{}, &do_stringify_kv(&1, fun)) defp do_stringify([{_, _} | _] = params, fun), do: Enum.into(params, %{}, &do_stringify_kv(&1, fun)) defp do_stringify(params, fun) when is_list(params), do: Enum.map(params, &do_stringify(&1, fun)) defp do_stringify(other, fun), do: do_stringify_simple(other, fun) defp do_stringify_simple(other, fun), do: fun.(other) defp do_stringify_kv({k, v}, fun), do: {to_string(k), do_stringify(v, fun)} end
29.175135
108
0.594101
9ed1e4449c759f541e9c09f3b282c7c0f9acec7a
990
exs
Elixir
example/config/config.exs
jmerriweather/vintage_net_wizard
dc67e75d11911dec536571344e00d0e5ed250b7f
[ "Apache-2.0" ]
null
null
null
example/config/config.exs
jmerriweather/vintage_net_wizard
dc67e75d11911dec536571344e00d0e5ed250b7f
[ "Apache-2.0" ]
null
null
null
example/config/config.exs
jmerriweather/vintage_net_wizard
dc67e75d11911dec536571344e00d0e5ed250b7f
[ "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 :example, target: Mix.target() # Customize non-Elixir parts of the firmware. See # https://hexdocs.pm/nerves/advanced-configuration.html for details. config :nerves, :firmware, rootfs_overlay: "rootfs_overlay" # Use shoehorn to start the main application. See the shoehorn # docs for separating out critical OTP applications such as those # involved with firmware updates. config :shoehorn, init: [:nerves_runtime, :vintage_net], app: Mix.Project.config()[:app] # Use Ringlogger as the logger backend and remove :console. # See https://hexdocs.pm/ring_logger/readme.html for more information on # configuring ring_logger. config :logger, backends: [RamoopsLogger, RingLogger] if Mix.target() != :host do import_config "target.exs" end
30.9375
72
0.771717
9ed1ef3238be397e8ea141d7743d7d550577c922
3,009
exs
Elixir
mix.exs
evaldobratti/floki
8f27729a641fe68eaf778e751da0c0e66d0b9470
[ "MIT" ]
null
null
null
mix.exs
evaldobratti/floki
8f27729a641fe68eaf778e751da0c0e66d0b9470
[ "MIT" ]
null
null
null
mix.exs
evaldobratti/floki
8f27729a641fe68eaf778e751da0c0e66d0b9470
[ "MIT" ]
null
null
null
defmodule Floki.Mixfile do use Mix.Project @description "Floki is a simple HTML parser that enables search for nodes using CSS selectors." @version "0.29.0" def project do [ app: :floki, name: "Floki", version: @version, description: @description, elixir: "~> 1.8", package: package(), erlc_paths: ["src", "gen"], deps: deps(), aliases: aliases(), dialyzer: [ plt_file: {:no_warn, "priv/plts/dialyzer.plt"} ], source_url: "https://github.com/philss/floki", docs: [extras: ["README.md"], main: "Floki", assets: "assets"] ] end def application do [extra_applications: [:logger]] end defp deps do # Needed to avoid installing unnecessary deps on the CI parsers_deps = [ html5ever: {:html5ever, ">= 0.8.0", optional: true, only: [:dev, :test]}, fast_html: {:fast_html, ">= 0.0.0", optional: true, only: [:dev, :test]} ] parsers = case System.get_env("PARSER") do nil -> [:fast_html, :html5ever] parser when parser in ~w(html5ever fast_html) -> [String.to_atom(parser)] _ -> [] end |> Enum.map(fn name -> Keyword.fetch!(parsers_deps, name) end) [ {:html_entities, "~> 0.5.0"}, {:earmark, "~> 1.2", only: :dev}, {:ex_doc, "~> 0.23.0", only: :dev}, {:credo, ">= 0.0.0", only: [:dev, :test]}, {:dialyxir, "~> 1.0", only: [:dev], runtime: false}, {:inch_ex, "~> 2.1.0-rc.1", only: :docs} ] ++ parsers end defp aliases do # Hardcoded because we can't load the floki application and get the module list at this point. parsers = [Floki.HTMLParser.Mochiweb, Floki.HTMLParser.FastHtml, Floki.HTMLParser.Html5ever] {aliases, cli_names} = Enum.map_reduce(parsers, [], fn parser, acc -> cli_name = parser |> Module.split() |> List.last() |> Macro.underscore() {{:"test.#{cli_name}", &test_with_parser(parser, &1)}, [cli_name | acc]} end) aliases |> Keyword.put(:test, &test_with_parser(cli_names, &1)) end defp test_with_parser(parser_cli_names, args) when is_list(parser_cli_names) do Enum.each(parser_cli_names, fn cli_name -> Mix.shell().cmd("mix test.#{cli_name} --color #{Enum.join(args, " ")}", env: [{"MIX_ENV", "test"}] ) end) end defp test_with_parser(parser, args) do Mix.shell().info("Running tests with #{parser}") Application.put_env(:floki, :html_parser, parser, persistent: true) Mix.env(:test) Mix.Tasks.Test.run(args) end defp package do %{ maintainers: ["Philip Sampaio Silva"], licenses: ["MIT"], files: [ "lib", "src/*.xrl", "src/floki_mochi_html.erl", "mix.exs", "README.md", "LICENSE", "CODE_OF_CONDUCT.md", "CONTRIBUTING.md" ], links: %{ "GitHub" => "https://github.com/philss/floki" } } end end
27.605505
98
0.56896
9ed1f943e1e275f204627c35aa740d1414ea3b9c
1,542
exs
Elixir
api/mix.exs
cnole/phoenix-react-slack-clone
852cc32ee157a18c93ddd1eb627ddf61bc294cda
[ "MIT" ]
null
null
null
api/mix.exs
cnole/phoenix-react-slack-clone
852cc32ee157a18c93ddd1eb627ddf61bc294cda
[ "MIT" ]
null
null
null
api/mix.exs
cnole/phoenix-react-slack-clone
852cc32ee157a18c93ddd1eb627ddf61bc294cda
[ "MIT" ]
null
null
null
defmodule Sling.Mixfile do use Mix.Project def project do [app: :sling, version: "0.0.1", elixir: "~> 1.2", elixirc_paths: elixirc_paths(Mix.env), compilers: [:phoenix, :gettext] ++ Mix.compilers, build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, aliases: aliases(), deps: deps()] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [mod: {Sling, []}, applications: [:phoenix, :phoenix_pubsub, :cowboy, :logger, :gettext, :phoenix_ecto, :postgrex]] 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_ecto, "~> 3.0"}, {:postgrex, ">= 0.0.0"}, {:gettext, "~> 0.11"}, {:cowboy, "~> 1.0"}] end # Aliases are shortcuts or tasks specific to the current project. # For example, to create, migrate and run the seeds file at once: # # $ mix ecto.setup # # See the documentation for `Mix` for more info on aliases. defp aliases do ["ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], "ecto.reset": ["ecto.drop", "ecto.setup"], "test": ["ecto.create --quiet", "ecto.migrate", "test"]] end end
29.09434
78
0.603761
9ed21af2c9a613e02237f00bfab76286e4aa1c97
2,305
ex
Elixir
lib/annon_api/configuration/cache_adapters/ets.ex
gabheadz/annon.api
9921d98e44c8472c133554dd55ea649c0f55726c
[ "MIT" ]
328
2017-05-05T15:19:46.000Z
2022-03-11T10:52:45.000Z
lib/annon_api/configuration/cache_adapters/ets.ex
gabheadz/annon.api
9921d98e44c8472c133554dd55ea649c0f55726c
[ "MIT" ]
83
2017-04-30T10:36:15.000Z
2019-10-14T13:14:34.000Z
lib/annon_api/configuration/cache_adapters/ets.ex
gabheadz/annon.api
9921d98e44c8472c133554dd55ea649c0f55726c
[ "MIT" ]
29
2017-05-02T14:36:50.000Z
2021-09-03T13:36:17.000Z
defmodule Annon.Configuration.CacheAdapters.ETS do @moduledoc """ Adapter to access cache using ETS. """ @behaviour Annon.Configuration.CacheAdapter alias Annon.Configuration.API def init(opts) do table_name = Keyword.fetch!(opts, :cache_space) :ets.new(table_name, [:ordered_set, :public, :named_table, read_concurrency: true]) config_change(opts) :ok end def match_request(scheme, method, host, port, path, opts) do table_name = Keyword.fetch!(opts, :cache_space) match_spec = %{ request: %{ scheme: scheme, port: port } } apis = table_name # TODO: Try QLC to filter by methods |> :ets.match_object({:_, match_spec, :_, :_}) |> filter_by_method(method) |> filter_by_host(host) |> filter_by_path(path) case apis do [] -> {:error, :not_found} [{_, api, _, _}|_] -> {:ok, api} end end def config_change(opts) do table_name = Keyword.fetch!(opts, :cache_space) objects = Enum.map(API.dump_apis(), fn api -> priority = -api.matching_priority {{priority, api.id}, api, compile_host_regex(api.request.host), compile_path_regex(api.request.path)} end) case objects do [] -> :ok objects when is_list(objects) -> true = :ets.delete_all_objects(table_name) true = :ets.insert(table_name, objects) :ok end end defp filter_by_method(apis, method) do Enum.filter(apis, fn({_, api, _, _}) -> method in api.request.methods end) end defp compile_host_regex(host) do host_pattern = prepare_regex(host) Regex.compile!("^#{host_pattern}$") end defp filter_by_host(apis, host) do Enum.filter(apis, fn({_, _, host_regex, _}) -> Regex.match?(host_regex, host) end) end defp compile_path_regex(path) do path_pattern = prepare_regex(path) Regex.compile!("^#{path_pattern}") end defp filter_by_path(apis, path) do Enum.filter(apis, fn({_, _, _, path_regex}) -> Regex.match?(path_regex, path) end) end defp prepare_regex(string) do string |> Regex.escape() |> String.replace("%", ".*") |> String.replace("_", ".{1}") # TODO: Paths like /my_path/ will match /myXpath/ which is BAD end end
24.521277
107
0.62256
9ed21ecf65772b5c57d8ced8fd56608c823d9b07
346
exs
Elixir
priv/repo/migrations/20160717185528_create_company.exs
rustedgrail/where_its_due
2140006ecfbe29e9d4ebc1895b147a76b5376fc3
[ "MIT" ]
null
null
null
priv/repo/migrations/20160717185528_create_company.exs
rustedgrail/where_its_due
2140006ecfbe29e9d4ebc1895b147a76b5376fc3
[ "MIT" ]
null
null
null
priv/repo/migrations/20160717185528_create_company.exs
rustedgrail/where_its_due
2140006ecfbe29e9d4ebc1895b147a76b5376fc3
[ "MIT" ]
null
null
null
defmodule WhereItsDue.Repo.Migrations.CreateCompany do use Ecto.Migration def change do create table(:companies) do add :abbreviation, :string add :aliases, {:array, :string} add :deck, :text add :description, :text add :giant_bomb_id, :integer add :name, :string timestamps end end end
19.222222
54
0.647399
9ed2333f7e512e0ffd1bc23147134a5e77e57c53
718
ex
Elixir
lib/wizard/game/deck.ex
jannikbecher/wizard
a4d10b6d2396b960ab7fabf6ec6b0dd0c995acb2
[ "MIT" ]
null
null
null
lib/wizard/game/deck.ex
jannikbecher/wizard
a4d10b6d2396b960ab7fabf6ec6b0dd0c995acb2
[ "MIT" ]
1
2020-02-27T13:04:41.000Z
2020-02-27T13:04:41.000Z
lib/wizard/game/deck.ex
jannikbecher/wizard
a4d10b6d2396b960ab7fabf6ec6b0dd0c995acb2
[ "MIT" ]
null
null
null
defmodule Wizard.Game.Deck do @moduledoc false alias Wizard.Game.Card @colors [:red, :green, :blue, :yellow] @doc false def new do (create_normal_cards() ++ create_wizard_cards() ++ create_fool_cards()) |> Enum.shuffle() end defp create_normal_cards do for color <- @colors, number <- 1..13 do %Card{type: :normal, value: number, color: color} end end defp create_wizard_cards do for _ <- 1..4 do Card.wizard() end end defp create_fool_cards do for _ <- 1..4 do Card.fool() end end @doc false def draw([]), do: :empty @doc false def draw(deck, number) when is_list(deck) and number > 0 do Enum.split(deck, number) end end
17.95
75
0.628134
9ed24d02a218e07626328986b441341aa219f185
734
ex
Elixir
fade/lib/broker/data_mappers/exchange_data_mapper.ex
ahives/Fade
7094b6703933e41a1400b1053764335e32928b0a
[ "Apache-2.0" ]
null
null
null
fade/lib/broker/data_mappers/exchange_data_mapper.ex
ahives/Fade
7094b6703933e41a1400b1053764335e32928b0a
[ "Apache-2.0" ]
null
null
null
fade/lib/broker/data_mappers/exchange_data_mapper.ex
ahives/Fade
7094b6703933e41a1400b1053764335e32928b0a
[ "Apache-2.0" ]
null
null
null
defmodule Fade.Broker.ExchangeDataMapper do alias Fade.Broker.DataMapper alias Fade.Broker.ExchangeTypes.ExchangeInfo alias Fade.Core.PrimitiveDataMapper @behaviour DataMapper @impl DataMapper def map_data(data) do data |> Stream.reject(&is_nil/1) |> Enum.map(fn exchange -> ExchangeInfo.new( name: exchange["name"], vhost: exchange["vhost"], user_who_performed_action: exchange["user_who_performed_action"], routing_type: PrimitiveDataMapper.to_atom(exchange["routing_type"]), durable: exchange["durable"], auto_delete: exchange["auto_delete"], internal: exchange["internal"], arguments: exchange["arguments"] ) end) end end
28.230769
76
0.683924
9ed27539d2f83cbea13c42e88d30d7d0e473f087
324
ex
Elixir
test/support/email_case.ex
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
1,003
2016-02-23T17:21:12.000Z
2022-02-20T14:39:35.000Z
test/support/email_case.ex
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
906
2016-02-22T22:54:19.000Z
2022-03-11T15:19:43.000Z
test/support/email_case.ex
matusf/cog
71708301c7dc570fb0d3498a50f47a70ef957788
[ "Apache-2.0" ]
95
2016-02-23T13:42:31.000Z
2021-11-30T14:39:55.000Z
defmodule Cog.EmailCase do @moduledoc """ Case template used for testing emails. """ use ExUnit.CaseTemplate using do quote do use Bamboo.Test end end setup do Ecto.Adapters.SQL.Sandbox.checkout(Cog.Repo) Ecto.Adapters.SQL.Sandbox.mode(Cog.Repo, {:shared, self()}) :ok end end
14.727273
63
0.657407
9ed276aa9ff9759d37226cb0bebf0150d4a50398
1,159
exs
Elixir
backend/test/getaways_web/schema/query/me_test.exs
Prumme/Projet_phx_ex_gql
6324af91f94f96ee1f8403d5397ab930347e3e4f
[ "Unlicense" ]
null
null
null
backend/test/getaways_web/schema/query/me_test.exs
Prumme/Projet_phx_ex_gql
6324af91f94f96ee1f8403d5397ab930347e3e4f
[ "Unlicense" ]
6
2020-01-31T19:44:15.000Z
2021-09-02T04:26:49.000Z
backend/test/getaways_web/schema/query/me_test.exs
Prumme/Projet_phx_ex_gql
6324af91f94f96ee1f8403d5397ab930347e3e4f
[ "Unlicense" ]
null
null
null
defmodule GetawaysWeb.Schema.Query.MeTest do use GetawaysWeb.ConnCase, async: true @query """ { me { username bookings { startDate endDate } } } """ test "me query returns my bookings" do place = place_fixture() user = user_fixture() booking_attrs = %{ start_date: ~D[2019-04-01], end_date: ~D[2019-04-05], place_id: place.id } assert {:ok, booking} = Getaways.Vacation.create_booking(user, booking_attrs) conn = build_conn() |> auth_user(user) conn = get conn, "/api", query: @query assert %{ "data" => %{ "me" => %{ "username" => user_name, "bookings" => [ %{ "startDate" => "2019-04-01", "endDate" => "2019-04-05" } ] } } } = json_response(conn, 200) assert user.username == user_name end test "me query fails if not signed in" do conn = build_conn() conn = get conn, "/api", query: @query assert %{ "data" => %{ "me" => nil } } == json_response(conn, 200) end end
19.316667
59
0.499569
9ed28e3ca66406b497a464bdb84c09861d46c3b1
264
ex
Elixir
apps/splatoon_data/priv/repo/factories/weapons.ex
ndac-todoroki/DiscordSplatoonBot
6a082b0352684cb64d36fe9116e7f060691cba37
[ "MIT" ]
6
2017-08-10T13:57:06.000Z
2019-01-17T08:48:40.000Z
apps/splatoon_data/priv/repo/factories/weapons.ex
ndac-todoroki/DiscordSplatoonBot
6a082b0352684cb64d36fe9116e7f060691cba37
[ "MIT" ]
14
2017-08-08T13:07:00.000Z
2019-02-28T15:10:18.000Z
apps/splatoon_data/priv/repo/factories/weapons.ex
ndac-todoroki/DiscordSplatoonBot
6a082b0352684cb64d36fe9116e7f060691cba37
[ "MIT" ]
null
null
null
defmodule SplatoonData.Repo.Factories.Weapons do defmacro __using__(_opts) do quote do def weapon_factory do %SplatoonData.Weapons.Weapon{ name: nil, # 何か入れないとエラー get_rank: 0 # これもエラー } end end end end
22
48
0.613636
9ed299c7de59043d1d355e2c91bcb0a3ea232011
2,308
ex
Elixir
lib/matrex/operators.ex
scripbox/matrex
9a080311836a151ef9f2b780c3cd751a0fa0df22
[ "BSD-3-Clause" ]
464
2018-05-13T00:48:25.000Z
2022-02-01T18:29:38.000Z
lib/matrex/operators.ex
scripbox/matrex
9a080311836a151ef9f2b780c3cd751a0fa0df22
[ "BSD-3-Clause" ]
30
2018-05-28T11:00:37.000Z
2021-12-09T11:38:28.000Z
lib/matrex/operators.ex
scripbox/matrex
9a080311836a151ef9f2b780c3cd751a0fa0df22
[ "BSD-3-Clause" ]
34
2018-05-21T15:40:11.000Z
2021-03-29T07:30:02.000Z
defmodule Matrex.Operators do @moduledoc """ Overrides Kernel math operators and adds common math functions shortcuts for use with matrices. Use with caution. ## Usage iex> import IEx.Helpers, except: [t: 1] # Only in iex, conflicts with transpose function iex> import Matrex.Operators iex> import Kernel, except: [-: 1, +: 2, -: 2, *: 2, /: 2, <|>: 2] iex> import Matrex iex> m = random(5, 3) #Matrex[5×3] ┌ ┐ │ 0.51502 0.03132 0.94185 │ │ 0.49434 0.93887 0.91102 │ │ 0.70671 0.89428 0.28817 │ │ 0.23771 0.37695 0.38214 │ │ 0.37221 0.34008 0.19615 │ └ ┘ iex> m * t(m) / eye(5) |> sigmoid() #Matrex[5×5] ┌ ┐ │ 0.76012 1.0 1.0 1.0 1.0 │ │ 1.0 0.87608 1.0 1.0 1.0 │ │ 1.0 1.0 0.79935 1.0 1.0 │ │ 1.0 1.0 1.0 0.58531 1.0 │ │ 1.0 1.0 1.0 1.0 0.57265 │ └ ┘ """ # Unary @doc false def -m, do: Matrex.neg(m) # Binary @doc false def a + b when is_number(a) and is_number(b), do: Kernel.+(a, b) def a + b, do: Matrex.add(a, b) @doc false def a - b when is_number(a) and is_number(b), do: Kernel.-(a, b) def a - b, do: Matrex.subtract(a, b) @doc false def a * b when is_number(a) and is_number(b), do: Kernel.*(a, b) def a * b when is_number(a), do: Matrex.multiply(a, b) def a * b when is_number(b), do: Matrex.multiply(a, b) def a * b, do: Matrex.dot(a, b) @doc false def a / b when is_number(a) and is_number(b), do: Kernel./(a, b) def a / b, do: Matrex.divide(a, b) @doc "Element-wise matrices multiplication. The same as `Matrex.multiply/2`" def a <|> b, do: Matrex.multiply(a, b) # Define shortcuts for math funcions Enum.each(Matrex.math_functions_list(), fn f -> @doc "Applies C language #{f}(x) to each element of the matrix. See `Matrex.apply/2`" def unquote(f)(%Matrex{} = m), do: Matrex.apply(m, unquote(f)) end) # Functions @doc "Transpose a matrix." defdelegate t(m), to: Matrex, as: :transpose @doc "See `Matrex.square/1`" defdelegate pow2(matrex), to: Matrex, as: :square end
32.055556
97
0.533795
9ed2f0b96b092044dba1766ca054a031f4e018f0
1,958
exs
Elixir
test/test_webhook.exs
starkinfra/sdk-elixir
d434de336ad7d2331b860519f04e9d107bb9c9cd
[ "MIT" ]
1
2022-03-15T18:58:21.000Z
2022-03-15T18:58:21.000Z
test/test_webhook.exs
starkinfra/sdk-elixir
d434de336ad7d2331b860519f04e9d107bb9c9cd
[ "MIT" ]
null
null
null
test/test_webhook.exs
starkinfra/sdk-elixir
d434de336ad7d2331b860519f04e9d107bb9c9cd
[ "MIT" ]
null
null
null
defmodule StarkInfraTest.Webhook do use ExUnit.Case @tag :webhook test "create, get and delete webhook" do {:ok, create_webhook} = StarkInfra.Webhook.create( url: "https://webhook.site/a10b29fc-45cf-4a09-b743-b7dff8c9eea5", subscriptions: ["contract", "credit-note", "signer", "issuing-card", "issuing-invoice", "issuing-purchase", "pix-request.in", "pix-request.out", "pix-reversal.in", "pix-reversal.out", "pix-claim", "pix-key", "pix-chargeback", "pix-infraction"] ) {:ok, get_webhook} = StarkInfra.Webhook.get(create_webhook.id) {:ok, delete_webhook} = StarkInfra.Webhook.delete(get_webhook.id) assert !is_nil(delete_webhook) end @tag :webhook test "create!, get! and delete! webhook" do create_webhook = StarkInfra.Webhook.create!( url: "https://webhook.site/a10b29fc-45cf-4a09-b743-b7dff8c9eea5", subscriptions: ["contract", "credit-note", "signer", "issuing-card", "issuing-invoice", "issuing-purchase", "pix-request.in", "pix-request.out", "pix-reversal.in", "pix-reversal.out", "pix-claim", "pix-key", "pix-chargeback", "pix-infraction"] ) get_webhook = StarkInfra.Webhook.get!(create_webhook.id) delete_webhook = StarkInfra.Webhook.delete!(get_webhook.id) assert !is_nil(delete_webhook) end @tag :webhook test "query webhook" do StarkInfra.Webhook.query(limit: 5) |> Enum.take(5) |> (fn list -> assert length(list) <= 5 end).() end @tag :webhook test "query! webhook" do StarkInfra.Webhook.query!(limit: 5) |> Enum.take(5) |> (fn list -> assert length(list) <= 5 end).() end @tag :webhook test "page webhook" do {:ok, ids} = StarkInfraTest.Utils.Page.get(&StarkInfra.Webhook.page/1, 2, limit: 2) assert length(ids) <= 4 end @tag :webhook test "page! webhook" do ids = StarkInfraTest.Utils.Page.get!(&StarkInfra.Webhook.page!/1, 2, limit: 2) assert length(ids) <= 4 end end
34.350877
251
0.663943
9ed2f53cd48be99a129942beacf25c72ca9a7f27
2,027
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/target_pools_scoped_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/target_pools_scoped_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/target_pools_scoped_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.TargetPoolsScopedListWarningData 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.TargetPoolsScopedListWarningData do def decode(value, options) do GoogleApi.Compute.V1.Model.TargetPoolsScopedListWarningData.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.TargetPoolsScopedListWarningData do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
40.54
527
0.741983
9ed2fbb4ec8dd95e050e92aea0b038baa21c7c53
352
ex
Elixir
lib/supabase_surface/components/icons/icon_arrow_up_left.ex
treebee/supabase-surface
5a184ca92323c085dd81e2fc8aa8c10367f2382e
[ "Apache-2.0" ]
5
2021-06-08T08:02:43.000Z
2022-02-09T23:13:46.000Z
lib/supabase_surface/components/icons/icon_arrow_up_left.ex
treebee/supabase-surface
5a184ca92323c085dd81e2fc8aa8c10367f2382e
[ "Apache-2.0" ]
null
null
null
lib/supabase_surface/components/icons/icon_arrow_up_left.ex
treebee/supabase-surface
5a184ca92323c085dd81e2fc8aa8c10367f2382e
[ "Apache-2.0" ]
1
2021-07-14T05:20:31.000Z
2021-07-14T05:20:31.000Z
defmodule SupabaseSurface.Components.Icons.IconArrowUpLeft do use SupabaseSurface.Components.Icon @impl true def render(assigns) do icon_size = IconContainer.get_size(assigns.size) ~F""" <IconContainer assigns={assigns}> {Feathericons.arrow_up_left(width: icon_size, height: icon_size)} </IconContainer> """ end end
23.466667
71
0.727273
9ed33c061728c8e378eda62e9a84465e0f72834a
646
ex
Elixir
web/views/asset_view.ex
andreihod/cryptofolio-api
063bfcf39a0b334204e6b6ef01990622a1f316af
[ "MIT" ]
2
2017-07-19T17:03:41.000Z
2017-09-18T12:58:42.000Z
web/views/asset_view.ex
mateusfs/cryptofolio-api
063bfcf39a0b334204e6b6ef01990622a1f316af
[ "MIT" ]
7
2017-07-18T23:32:45.000Z
2017-08-18T01:09:11.000Z
web/views/asset_view.ex
mateusfs/cryptofolio-api
063bfcf39a0b334204e6b6ef01990622a1f316af
[ "MIT" ]
2
2017-08-03T19:55:21.000Z
2018-07-01T19:54:22.000Z
defmodule Cryptofolio.AssetView do use Cryptofolio.Web, :view def render("index.json", %{assets: assets}) do render_many(assets, Cryptofolio.AssetView, "show.json") end def render("show.json", %{asset: asset}) do %{asset: render_one(asset, Cryptofolio.AssetView, "asset.json")} end def render("asset.json", %{asset: asset}) do %{id: asset.id, mybalance: asset.mybalance, inserted_at: asset.inserted_at, updated_at: asset.updated_at, exchange: render_one(asset.exchange, Cryptofolio.ExchangeView, "exchange.json"), coin: render_one(asset.coin, Cryptofolio.CoinView, "coin.json")} end end
30.761905
86
0.695046
9ed37daebfb92282f9178f3be907c57007d75606
154
ex
Elixir
04-chapter/05_factorial.ex
herminiotorres/learn-funcional-programming-with-elixir
01b0696e0859da20f389a6e53c51b5ab6c4f6e24
[ "MIT" ]
1
2022-03-01T13:54:43.000Z
2022-03-01T13:54:43.000Z
04-chapter/05_factorial.ex
herminiotorres/learn-funcional-programming-with-elixir
01b0696e0859da20f389a6e53c51b5ab6c4f6e24
[ "MIT" ]
null
null
null
04-chapter/05_factorial.ex
herminiotorres/learn-funcional-programming-with-elixir
01b0696e0859da20f389a6e53c51b5ab6c4f6e24
[ "MIT" ]
null
null
null
defmodule Factorial do def of(0), do: 1 def of(1), do: 1 * of(0) def of(2), do: 2 * of(1) def of(3), do: 3 * of(2) def of(4), do: 4 * of(3) end
19.25
26
0.519481
9ed38b92ced64e31a4def3737521a97d2ce1c527
504
ex
Elixir
lib/step_flow/view/changeset_view.ex
mathiaHT/ex_step_flow
6496e9511239de64f00119428476338dfcde9dea
[ "MIT" ]
4
2019-12-07T05:18:26.000Z
2020-11-06T23:28:43.000Z
lib/step_flow/view/changeset_view.ex
mathiaHT/ex_step_flow
6496e9511239de64f00119428476338dfcde9dea
[ "MIT" ]
53
2020-01-06T11:23:09.000Z
2021-06-25T15:30:07.000Z
lib/step_flow/view/changeset_view.ex
mathiaHT/ex_step_flow
6496e9511239de64f00119428476338dfcde9dea
[ "MIT" ]
3
2020-01-30T15:37:40.000Z
2020-10-27T14:10:02.000Z
defmodule StepFlow.ChangesetView do use StepFlow, :view @doc """ Traverses and translates changeset errors. See `Ecto.Changeset.traverse_errors/2` for more details. """ def translate_errors(changeset) do Ecto.Changeset.traverse_errors(changeset, &translate_error/1) end def render("error.json", %{changeset: changeset}) do # When encoded, the changeset returns its errors # as a JSON object. So we just pass it forward. %{errors: translate_errors(changeset)} end end
26.526316
65
0.728175
9ed3ae82addd682cc48060aa4067b2d07c18868f
850
ex
Elixir
src/server/apps/domain_web/lib/domain_web/graphql/resolvers/resolver.ex
akeating/pespa
f6be1a61cdcbdf0b7ee7ce20161504300ed4d0e4
[ "MIT" ]
28
2017-04-07T03:23:30.000Z
2021-09-29T13:41:04.000Z
src/server/apps/domain_web/lib/domain_web/graphql/resolvers/resolver.ex
akeating/pespa
f6be1a61cdcbdf0b7ee7ce20161504300ed4d0e4
[ "MIT" ]
null
null
null
src/server/apps/domain_web/lib/domain_web/graphql/resolvers/resolver.ex
akeating/pespa
f6be1a61cdcbdf0b7ee7ce20161504300ed4d0e4
[ "MIT" ]
7
2017-10-22T10:47:53.000Z
2021-04-21T23:11:22.000Z
defmodule DomainWeb.Graphql.Resolvers do alias Domain.Accounts alias DomainWeb.Guardian def exchange_credentials_for_token %{ email: email, password: password }, _info do case Accounts.exchange_credentials_for_token(email, password) do {:ok, user} -> encode_and_sign(user) {:error, reason} -> {:error, reason} end end def whoami _args, info do %{context: %{current_user: user}} = info {:ok, user} end def increment_count_by %{by: by}, info do %{context: %{current_user: user}} = info if user == nil do {:error, :not_authorized } else Accounts.increment_count_by by end end defp encode_and_sign(user) do case Guardian.encode_and_sign(user) do {:ok, token, _full_claims } -> {:ok, token} _ -> {:error, :encode_and_sign} end end end
22.972973
84
0.645882
9ed3d201964277f3cb420bdd919e0289bc6cec35
1,948
exs
Elixir
test/sna_web/controllers/provider_oauth_controller_test.exs
runasio/sna
39127ec4c2c9b97fd4583b2683fce634fe74613b
[ "Apache-2.0" ]
6
2019-07-16T13:34:33.000Z
2020-08-25T08:51:01.000Z
test/sna_web/controllers/provider_oauth_controller_test.exs
runasio/sna
39127ec4c2c9b97fd4583b2683fce634fe74613b
[ "Apache-2.0" ]
3
2019-07-17T14:18:50.000Z
2020-06-06T08:07:45.000Z
test/sna_web/controllers/provider_oauth_controller_test.exs
runasio/sna
39127ec4c2c9b97fd4583b2683fce634fe74613b
[ "Apache-2.0" ]
2
2019-07-17T05:42:04.000Z
2020-05-06T11:12:53.000Z
defmodule SnaWeb.ProviderOAuthControllerTest do use SnaWeb.ConnCase setup do Sna.Repo.insert(%Sna.Repo.Provider{ name: "github", strategy: "github", production: false, }) on_exit(fn -> Application.put_env(:sna, :oauth_providers, github: Ueberauth.Strategy.Github) end) end defp example_email do "[email protected]" end defp example_token do {:ok, token, _claims} = SnaWeb.Token.generate_bearer(%{"email" => example_email()}) token end defp login(conn) do conn |> post("/auth/email", token: example_token(), login: "login") |> recycle() end test "GET /providers/github/oauth", %{conn: conn} do conn = conn |> login() |> get("/providers/github/oauth") assert redirected_to(conn) =~ "github.com" end test "GET /providers/github/oauth/callback?code=error", %{conn: conn} do Application.put_env(:sna, :oauth_providers, github: SnaWeb.UeberauthStrategyGithubMock) conn = conn |> login() |> get("/providers/github/oauth/callback?code=error") assert redirected_to(conn) === "/" assert get_flash(conn, :error) === "Failed to authenticate." end test "GET /providers/github/oauth/callback?code=ok", %{conn: conn} do import Ecto.Query Application.put_env(:sna, :oauth_providers, github: SnaWeb.UeberauthStrategyGithubMock) conn = conn |> login() |> get("/providers/github/oauth/callback?code=ok") assert redirected_to(conn) === "/" assert get_flash(conn, :info) === "Connected." token = Sna.Repo.one( from t in Sna.Repo.Token, join: p in assoc(t, :provider), join: u in assoc(t, :user), where: u.email == ^example_email(), where: p.name == "github", select: t) assert token != nil assert token.token === "valid-token" assert token.token_secret === "valid-secret" assert token.retention === 42 end end
25.973333
91
0.634497
9ed4001b040605ab9df9a7d2fb53eb31ab54b939
5,406
ex
Elixir
lib/chat_api_web/channels/conversation_channel.ex
8otco/papercups
f07fe51e6161fdd772fe7cef59e7777951cddc41
[ "MIT" ]
1
2021-06-17T03:17:24.000Z
2021-06-17T03:17:24.000Z
lib/chat_api_web/channels/conversation_channel.ex
8otco/papercups
f07fe51e6161fdd772fe7cef59e7777951cddc41
[ "MIT" ]
null
null
null
lib/chat_api_web/channels/conversation_channel.ex
8otco/papercups
f07fe51e6161fdd772fe7cef59e7777951cddc41
[ "MIT" ]
null
null
null
defmodule ChatApiWeb.ConversationChannel do use ChatApiWeb, :channel alias ChatApiWeb.Presence alias ChatApi.{Messages, Conversations} alias ChatApi.Messages.Message @impl true def join("conversation:lobby", _payload, socket) do {:ok, socket} end def join("conversation:lobby:" <> customer_id, _params, socket) do {:ok, assign(socket, :customer_id, customer_id)} end def join("conversation:" <> private_conversation_id, payload, socket) do if authorized?(payload, private_conversation_id) do conversation = Conversations.get_conversation!(private_conversation_id) socket = assign( socket, :conversation, ChatApiWeb.ConversationView.render("basic.json", conversation: conversation) ) # If the payload includes a customer_id, we want to mark this customer # as "online" via Phoenix Presence in the :after_join hook case payload do %{"customer_id" => customer_id} -> send(self(), :after_join) {:ok, socket |> assign(:customer_id, customer_id)} _ -> {:ok, socket} end else {:error, %{reason: "unauthorized"}} end end @impl true def handle_info(:after_join, socket) do with %{customer_id: customer_id, conversation: conversation} <- socket.assigns, %{account_id: account_id} <- conversation do key = "customer:" <> customer_id # Track the presence of this customer in the conversation {:ok, _} = Presence.track(socket, key, %{ online_at: inspect(System.system_time(:second)), customer_id: customer_id }) topic = "notification:" <> account_id # Track the presence of this customer for the given account, # so agents can see the "online" status in the dashboard {:ok, _} = Presence.track(self(), topic, key, %{ online_at: inspect(System.system_time(:second)), customer_id: customer_id }) push(socket, "presence_state", Presence.list(socket)) ChatApiWeb.Endpoint.broadcast!(topic, "presence_state", Presence.list(topic)) end {:noreply, socket} end @impl true def handle_in("ping", payload, socket) do {:reply, {:ok, payload}, socket} end def handle_in("shout", payload, socket) do with %{conversation: conversation} <- socket.assigns, %{id: conversation_id, account_id: account_id} <- conversation, {:ok, message} <- payload |> Map.merge(%{"conversation_id" => conversation_id, "account_id" => account_id}) |> Messages.create_message() do case Map.get(payload, "file_ids") do file_ids when is_list(file_ids) -> Messages.create_attachments(message, file_ids) _ -> nil end message = Messages.get_message!(message.id) broadcast_new_message(socket, message) else _ -> broadcast(socket, "shout", payload) end {:noreply, socket} end def handle_in("messages:seen", _payload, socket) do with %{conversation: conversation} <- socket.assigns, %{id: conversation_id} <- conversation do Conversations.mark_agent_messages_as_seen(conversation_id) end {:noreply, socket} end @spec broadcast_conversation_update!(Message.t()) :: Message.t() defp broadcast_conversation_update!(%Message{conversation_id: conversation_id} = message) do # Mark as unread and ensure the conversation is open, since we want to # reopen a conversation if it received a new message after being closed. conversation = Conversations.get_conversation!(conversation_id) updates = %{status: "open", read: false} if Conversations.should_update?(conversation, updates) do {:ok, conversation} = Conversations.update_conversation(conversation, %{status: "open", read: false}) conversation |> Conversations.Notification.broadcast_conversation_update_to_admin!() |> Conversations.Notification.notify(:webhooks, event: "conversation:updated") end message end @spec broadcast_to_admin_channel!(Message.t()) :: Message.t() defp broadcast_to_admin_channel!(%Message{account_id: account_id} = message) do ChatApiWeb.Endpoint.broadcast!( "notification:" <> account_id, "shout", Messages.Helpers.format(message) ) message end @spec broadcast_new_message(any(), Message.t()) :: Message.t() defp broadcast_new_message(socket, message) do broadcast_conversation_update!(message) broadcast(socket, "shout", Messages.Helpers.format(message)) broadcast_to_admin_channel!(message) message |> Messages.Notification.notify(:slack) # TODO: check if :slack_support_channel and :slack_company_channel are relevant |> Messages.Notification.notify(:slack_support_channel) |> Messages.Notification.notify(:slack_company_channel) |> Messages.Notification.notify(:mattermost) |> Messages.Notification.notify(:new_message_email) |> Messages.Notification.notify(:webhooks) |> Messages.Helpers.handle_post_creation_hooks() end # Add authorization logic here as required. @spec authorized?(any(), binary()) :: boolean() defp authorized?(_payload, conversation_id) do case Conversations.get_conversation(conversation_id) do %Conversations.Conversation{} -> true _ -> false end end end
32.566265
94
0.676656
9ed40ad60431d0ccc9915921d7f6d82946b76702
1,062
exs
Elixir
ur2/mix.exs
jefk/phoenix_live_view
5ef754b4246d3ba5aeeceb3875eda116bddfa834
[ "MIT" ]
null
null
null
ur2/mix.exs
jefk/phoenix_live_view
5ef754b4246d3ba5aeeceb3875eda116bddfa834
[ "MIT" ]
null
null
null
ur2/mix.exs
jefk/phoenix_live_view
5ef754b4246d3ba5aeeceb3875eda116bddfa834
[ "MIT" ]
null
null
null
defmodule Ur2.MixProject do use Mix.Project def project do [ app: :ur2, version: "0.1.0", elixir: "~> 1.5", elixirc_paths: elixirc_paths(Mix.env()), compilers: [:phoenix, :gettext] ++ Mix.compilers(), start_permanent: Mix.env() == :prod, deps: deps() ] end # Configuration for the OTP application. # # Type `mix help compile.app` for more information. def application do [ mod: {Ur2.Application, []}, extra_applications: [:logger, :runtime_tools] ] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Specifies your project dependencies. # # Type `mix help deps` for examples and options. defp deps do [ {:phoenix, "~> 1.4.12"}, {:phoenix_pubsub, "~> 1.1"}, {:phoenix_html, "~> 2.11"}, {:phoenix_live_reload, "~> 1.2", only: :dev}, {:gettext, "~> 0.11"}, {:jason, "~> 1.0"}, {:plug_cowboy, "~> 2.0"} ] end end
23.6
57
0.571563
9ed42096561cfa9550a003277adb05776e8f6567
10,295
exs
Elixir
lib/elixir/test/elixir/kernel/quote_test.exs
liveforeverx/elixir
cf3cf0bd5443b59206e5733602244bc3543f0a53
[ "Apache-2.0" ]
null
null
null
lib/elixir/test/elixir/kernel/quote_test.exs
liveforeverx/elixir
cf3cf0bd5443b59206e5733602244bc3543f0a53
[ "Apache-2.0" ]
null
null
null
lib/elixir/test/elixir/kernel/quote_test.exs
liveforeverx/elixir
cf3cf0bd5443b59206e5733602244bc3543f0a53
[ "Apache-2.0" ]
null
null
null
Code.require_file "../test_helper.exs", __DIR__ defmodule Kernel.QuoteTest do use ExUnit.Case, async: true test :list do assert quote(do: [1, 2, 3]) == [1, 2, 3] end test :tuple do assert quote(do: {:a, 1}) == {:a, 1} end test :keep_line do ## DO NOT MOVE THIS LINE assert quote(location: :keep, do: bar(1, 2, 3)) == {:bar, [file: Path.relative_to_cwd(__ENV__.file), keep: 16], [1, 2, 3]} end test :fixed_line do assert quote(line: 3, do: bar(1, 2, 3)) == {:bar, [line: 3], [1, 2, 3]} end test :quote_line_var do ## DO NOT MOVE THIS LINE line = __ENV__.line assert quote(line: line, do: bar(1, 2, 3)) == {:bar, [line: 26], [1, 2, 3]} end test :unquote_call do assert quote(do: foo(bar)[unquote(:baz)]) == quote(do: foo(bar)[:baz]) assert quote(do: unquote(:bar)()) == quote(do: bar()) assert quote(do: unquote(:bar)(1) do 2 + 3 end) == quote(do: bar(1) do 2 + 3 end) assert quote(do: foo.unquote(:bar)) == quote(do: foo.bar) assert quote(do: foo.unquote(:bar)(1)) == quote(do: foo.bar(1)) assert quote(do: foo.unquote(:bar)(1) do 2 + 3 end) == quote(do: foo.bar(1) do 2 + 3 end) assert quote(do: foo.unquote({:bar, [], nil})) == quote(do: foo.bar) assert quote(do: foo.unquote({:bar, [], [1, 2]})) == quote(do: foo.bar(1, 2)) assert Code.eval_quoted(quote(do: Foo.unquote(Bar))) == {Elixir.Foo.Bar, []} assert Code.eval_quoted(quote(do: Foo.unquote(quote do: Bar))) == {Elixir.Foo.Bar, []} assert_raise ArgumentError, fn -> quote(do: foo.unquote(1)) end end test :nested_quote do assert {:quote, _, [[do: {:unquote, _, _}]]} = quote(do: quote(do: unquote(x))) end defmacrop nested_quote_in_macro do x = 1 quote do x = unquote(x) quote do unquote(x) end end end test :nested_quote_in_macro do assert nested_quote_in_macro == 1 end Enum.each [foo: 1, bar: 2, baz: 3], fn {k, v} -> def unquote(k)(arg) do unquote(v) + arg end end test :dynamic_definition_with_unquote do assert foo(1) == 2 assert bar(2) == 4 assert baz(3) == 6 end test :splice_on_root do contents = [1, 2, 3] assert quote(do: (unquote_splicing(contents))) == quote do: (1; 2; 3) end test :splice_with_tail do contents = [1, 2, 3] assert quote(do: [unquote_splicing(contents)|[1, 2, 3]]) == [1, 2, 3, 1, 2, 3] assert quote(do: [unquote_splicing(contents)|val]) == quote(do: [1, 2, 3 | val]) assert quote(do: [unquote_splicing(contents)|unquote([4])]) == quote(do: [1, 2, 3, 4]) end test :splice_on_stab do {fun, []} = Code.eval_quoted(quote(do: fn(unquote_splicing([1, 2, 3])) -> :ok end), []) assert fun.(1, 2, 3) == :ok {fun, []} = Code.eval_quoted(quote(do: fn(1, unquote_splicing([2, 3])) -> :ok end), []) assert fun.(1, 2, 3) == :ok end test :splice_on_definition do defmodule Hello do def world([unquote_splicing(["foo", "bar"])|rest]) do rest end end assert Hello.world(["foo", "bar", "baz"]) == ["baz"] end test :splice_on_map do assert %{unquote_splicing([foo: :bar])} == %{foo: :bar} assert %{unquote_splicing([foo: :bar]), baz: :bat} == %{foo: :bar, baz: :bat} assert %{unquote_splicing([foo: :bar]), :baz => :bat} == %{foo: :bar, baz: :bat} assert %{:baz => :bat, unquote_splicing([foo: :bar])} == %{foo: :bar, baz: :bat} map = %{foo: :default} assert %{map | unquote_splicing([foo: :bar])} == %{foo: :bar} end test :when do assert [{:->, _, [[{:when, _, [1, 2, 3, 4]}], 5]}] = quote(do: (1, 2, 3 when 4 -> 5)) assert [{:->, _, [[{:when, _, [1, 2, 3, 4]}], 5]}] = quote(do: ((1, 2, 3) when 4 -> 5)) assert [{:->, _, [[{:when, _, [1, 2, 3, {:when, _, [4, 5]}]}], 6]}] = quote(do: ((1, 2, 3) when 4 when 5 -> 6)) end test :stab do assert [{:->, _, [[], nil]}] = (quote do -> end) assert [{:->, _, [[], nil]}] = (quote do: (->)) assert [{:->, _, [[1], nil]}] = (quote do 1 -> end) assert [{:->, _, [[1], nil]}] = (quote do: (1 ->)) assert [{:->, _, [[], 1]}] = (quote do -> 1 end) assert [{:->, _, [[], 1]}] = (quote do: (-> 1)) end test :bind_quoted do assert quote(bind_quoted: [foo: 1 + 2], do: foo) == {:__block__, [], [ {:=, [], [{:foo, [], Kernel.QuoteTest}, 3]}, {:foo, [], Kernel.QuoteTest} ]} end test :literals do assert (quote do: []) == [] assert (quote do: nil) == nil assert (quote do [] end) == [] assert (quote do nil end) == nil end defmacrop dynamic_opts do [line: 3] end test :with_dynamic_opts do assert quote(dynamic_opts, do: bar(1, 2, 3)) == {:bar, [line: 3], [1, 2, 3]} end test :unary_with_integer_precedence do assert quote(do: +1.foo) == quote(do: (+1).foo) assert quote(do: @1.foo) == quote(do: (@1).foo) assert quote(do: &1.foo) == quote(do: (&1).foo) end test :operators_slash_arity do assert {:/, _, [{:+, _, _}, 2]} = quote do: +/2 assert {:/, _, [{:&&, _, _}, 3]} = quote do: &&/3 end end ## DO NOT MOVE THIS LINE defmodule Kernel.QuoteTest.Errors do defmacro defadd do quote location: :keep do def add(a, b), do: a + b end end defmacro will_raise do quote location: :keep, do: raise "omg" end end defmodule Kernel.QuoteTest.ErrorsTest do use ExUnit.Case, async: true import Kernel.QuoteTest.Errors # Defines the add function defadd test :inside_function_error do assert_raise ArithmeticError, fn -> add(:a, :b) end mod = Kernel.QuoteTest.ErrorsTest file = __ENV__.file |> Path.relative_to_cwd |> String.to_char_list assert [{^mod, :add, 2, [file: ^file, line: 182]}|_] = System.stacktrace end test :outside_function_error do assert_raise RuntimeError, fn -> will_raise end mod = Kernel.QuoteTest.ErrorsTest file = __ENV__.file |> Path.relative_to_cwd |> String.to_char_list assert [{^mod, _, _, [file: ^file, line: 210]}|_] = System.stacktrace end end defmodule Kernel.QuoteTest.VarHygiene do defmacro no_interference do quote do: a = 1 end defmacro write_interference do quote do: var!(a) = 1 end defmacro read_interference do quote do: 10 = var!(a) end defmacro cross_module_interference do quote do: var!(a, Kernel.QuoteTest.VarHygieneTest) = 1 end end defmodule Kernel.QuoteTest.VarHygieneTest do use ExUnit.Case, async: true import Kernel.QuoteTest.VarHygiene defmacrop cross_module_no_interference do quote do: a = 10 end defmacrop read_cross_module do quote do: var!(a, __MODULE__) end defmacrop nested(var, do: block) do quote do var = unquote(var) unquote(block) var end end defmacrop hat do quote do var = 1 ^var = 1 var end end test :no_interference do a = 10 no_interference assert a == 10 end test :cross_module_interference do cross_module_no_interference cross_module_interference assert read_cross_module == 1 end test :write_interference do write_interference assert a == 1 end test :read_interference do a = 10 read_interference end test :nested do assert (nested 1 do nested 2 do :ok end end) == 1 end test :hat do assert hat == 1 end end defmodule Kernel.QuoteTest.AliasHygiene do alias Dict, as: SuperDict defmacro dict do quote do: Dict.Bar end defmacro super_dict do quote do: SuperDict.Bar end end defmodule Kernel.QuoteTest.AliasHygieneTest do use ExUnit.Case, async: true alias Dict, as: SuperDict test :annotate_aliases do assert {:__aliases__, [alias: false], [:Foo, :Bar]} = quote(do: Foo.Bar) assert {:__aliases__, [alias: false], [:Dict, :Bar]} = quote(do: Dict.Bar) assert {:__aliases__, [alias: Dict.Bar], [:SuperDict, :Bar]} = quote(do: SuperDict.Bar) end test :expand_aliases do assert Code.eval_quoted(quote do: SuperDict.Bar) == {Elixir.Dict.Bar, []} assert Code.eval_quoted(quote do: alias!(SuperDict.Bar)) == {Elixir.SuperDict.Bar, []} end test :expand_aliases_without_macro do alias HashDict, as: SuperDict assert SuperDict.Bar == Elixir.HashDict.Bar end test :expand_aliases_with_macro_does_not_expand_source_alias do alias HashDict, as: Dict, warn: false require Kernel.QuoteTest.AliasHygiene assert Kernel.QuoteTest.AliasHygiene.dict == Elixir.Dict.Bar end test :expand_aliases_with_macro_has_higher_preference do alias HashDict, as: SuperDict, warn: false require Kernel.QuoteTest.AliasHygiene assert Kernel.QuoteTest.AliasHygiene.super_dict == Elixir.Dict.Bar end end defmodule Kernel.QuoteTest.ImportsHygieneTest do use ExUnit.Case, async: true defmacrop get_list_length do quote do length('hello') end end defmacrop get_list_length_with_partial do quote do (&length(&1)).('hello') end end defmacrop get_list_length_with_function do quote do (&length/1).('hello') end end test :expand_imports do import Kernel, except: [length: 1] assert get_list_length == 5 assert get_list_length_with_partial == 5 assert get_list_length_with_function == 5 end defmacrop get_string_length do import Kernel, except: [length: 1] quote do length("hello") end end test :lazy_expand_imports do import Kernel, except: [length: 1] import String, only: [length: 1] assert get_string_length == 5 end test :lazy_expand_imports_no_conflicts do import Kernel, except: [length: 1] import String, only: [length: 1] assert get_list_length == 5 assert get_list_length_with_partial == 5 assert get_list_length_with_function == 5 end defmacrop with_length do quote do import Kernel, except: [length: 1] import String, only: [length: 1] length('hello') end end test :explicitly_overridden_imports do assert with_length == 5 end end defmodule Kernel.QuoteTest.NoQuoteConflictTest do defmacro x |> f do quote do unquote(x) |> unquote(f) end end end
24.511905
93
0.610588
9ed42cb0a2842409b25f5cfc5df8b1f9fc8f2439
37,097
ex
Elixir
data/web/deps/phoenix_html/lib/phoenix_html/form.ex
lydiadwyer/trains_elixir
16da18d4582307f4967b6cce7320e9aa08a849c3
[ "Apache-2.0" ]
null
null
null
data/web/deps/phoenix_html/lib/phoenix_html/form.ex
lydiadwyer/trains_elixir
16da18d4582307f4967b6cce7320e9aa08a849c3
[ "Apache-2.0" ]
null
null
null
data/web/deps/phoenix_html/lib/phoenix_html/form.ex
lydiadwyer/trains_elixir
16da18d4582307f4967b6cce7320e9aa08a849c3
[ "Apache-2.0" ]
null
null
null
defmodule Phoenix.HTML.Form do @moduledoc ~S""" Helpers related to producing HTML forms. The functions in this module can be used in three distinct scenarios: * with changeset data - when information to populate the form comes from a changeset * with connection data - when a form is created based on the information in the connection (aka `Plug.Conn`) * without form data - when the functions are used directly, outside of a form We will explore all three scenarios below. ## With changeset data The entry point for defining forms in Phoenix is with the `form_for/4` function. For this example, we will use `Ecto.Changeset`, which integrate nicely with Phoenix forms via the `phoenix_ecto` package. Imagine you have the following action in your controller: def new(conn, _params) do changeset = User.changeset(%User{}) render conn, "new.html", changeset: changeset end where `User.changeset/2` is defined as follows: def changeset(user, params \\ %{}) do cast(user, params, [:name, :age]) end Now a `@changeset` assign is available in views which we can pass to the form: <%= form_for @changeset, user_path(@conn, :create), fn f -> %> <label> Name: <%= text_input f, :name %> </label> <label> Age: <%= select f, :age, 18..100 %> </label> <%= submit "Submit" %> <% end %> `form_for/4` receives the `Ecto.Changeset` and converts it to a form, which is passed to the function as the argument `f`. All the remaining functions in this module receive the form and automatically generate the input fields, often by extracting information from the given changeset. For example, if the user had a default value for age set, it will automatically show up as selected in the form. ## With connection data `form_for/4` expects as first argument any data structure that implements the `Phoenix.HTML.FormData` protocol. By default, Phoenix implements this protocol for `Plug.Conn`, allowing us to create forms based only on connection information. This is useful when you are creating forms that are not backed by any kind of data from the data layer, like a search form. <%= form_for @conn, search_path(@conn, :new), [as: :search], fn f -> %> <%= text_input f, :for %> <%= submit "Search" %> <% end %> `form_for/4` uses the `Plug.Conn` to set input values from the request parameters. In this case, the input's value would be set to `@conn.params["search"]["for"]`. ## Without form data Sometimes we may want to generate a `text_input/3` or any other tag outside of a form. The functions in this module also support such usage by simply passing an atom as first argument instead of the form. <%= text_input :user, :name, value: "This is a prepopulated value" %> ## Nested inputs If your data layer supports embedding or nested associations, you can use `inputs_for` to attach nested data to the form. Imagine the following Ecto schemas: defmodule User do use Ecto.Schema schema "users" do field :name embeds_one :permalink, Permalink end end defmodule Permalink do use Ecto.Schema embedded_schema do field :url end end In the form, you now can: <%= form_for @changeset, user_path(@conn, :create), fn f -> %> <%= text_input f, :name %> <%= inputs_for f, :permalink, fn fp -> %> <%= text_input fp, :url %> <% end %> <% end %> The default option can be given to populate the fields if none is given: <%= inputs_for f, :permalink, [default: %Permalink{title: "default"}], fn fp -> %> <%= text_input fp, :url %> <% end %> `inputs_for/4` can be used to work with single entities or collections. When working with collections, `:prepend` and `:append` can be used to add entries to the collection stored in the changeset. """ alias Phoenix.HTML.Form import Phoenix.HTML import Phoenix.HTML.Tag @doc """ Defines the Phoenix.HTML.Form struct. Its fields are: * `:source` - the data structure given to `form_for/4` that implements the form data protocol * `:impl` - the module with the form data protocol implementation. This is used to avoid multiple protocol dispatches. * `:id` - the id to be used when generating input fields * `:name` - the name to be used when generating input fields * `:data` - the field used to store lookup data * `:params` - the parameters associated to this form in case they were sent as part of a previous request * `:hidden` - a keyword list of fields that are required for submitting the form behind the scenes as hidden inputs * `:options` - a copy of the options given when creating the form via `form_for/4` without any form data specific key * `:errors` - a keyword list of errors that associated with the form """ defstruct source: nil, impl: nil, id: nil, name: nil, data: nil, hidden: [], params: %{}, errors: [], options: [], index: nil @type t :: %Form{source: Phoenix.HTML.FormData.t, name: String.t, data: %{atom => term}, params: %{binary => term}, hidden: Keyword.t, options: Keyword.t, errors: Keyword.t, impl: module, id: String.t, index: nil | non_neg_integer} @doc """ Converts an attribute/form field into its humanize version. iex> humanize(:username) "Username" iex> humanize(:created_at) "Created at" iex> humanize("user_id") "User" """ def humanize(atom) when is_atom(atom), do: humanize(Atom.to_string(atom)) def humanize(bin) when is_binary(bin) do bin = if String.ends_with?(bin, "_id") do binary_part(bin, 0, byte_size(bin) - 3) else bin end bin |> String.replace("_", " ") |> String.capitalize end @doc """ Generates a form tag with a form builder. See the module documentation for examples of using this function. ## Options * `:as` - the server side parameter in which all params for this form will be collected (i.e. `as: :user_params` would mean all fields for this form will be accessed as `conn.params.user_params` server side). Automatically inflected when a changeset is given. * `:method` - the HTTP method. If the method is not "get" nor "post", an input tag with name `_method` is generated along-side the form tag. Defaults to "post". * `:multipart` - when true, sets enctype to "multipart/form-data". Required when uploading files * `:csrf_token` - for "post" requests, the form tag will automatically include an input tag with name `_csrf_token`. When set to false, this is disabled * `:enforce_utf8` - the form will have an `accept-charset` attribute set to "UTF-8" and a hidden input named `_utf8` containing a unicode character to force the browser to use UTF-8 as the charset. When set to false, this is disabled. See `Phoenix.HTML.Tag.form_tag/2` for more information on the options above. """ @spec form_for(Phoenix.HTML.FormData.t, String.t, Keyword.t, (t -> Phoenix.HTML.unsafe)) :: Phoenix.HTML.safe def form_for(form_data, action, options \\ [], fun) when is_function(fun, 1) do form = Phoenix.HTML.FormData.to_form(form_data, options) html_escape [form_tag(action, form.options), fun.(form), raw("</form>")] end @doc """ Generate a new form builder for the given parameter in form. See the module documentation for examples of using this function. ## Options * `:id` - the id to be used in the form, defaults to the concatenation of the given `field` to the parent form id * `:as` - the name to be used in the form, defaults to the concatenation of the given `field` to the parent form name * `:default` - the value to use if none is available * `:prepend` - the values to prepend when rendering. This only applies if the field value is a list and no parameters were sent through the form. * `:append` - the values to append when rendering. This only applies if the field value is a list and no parameters were sent through the form. """ @spec inputs_for(t, atom, Keyword.t, (t -> Phoenix.HTML.unsafe)) :: Phoenix.HTML.safe def inputs_for(form, field, options \\ [], fun) do options = form.options |> Keyword.take([:multipart]) |> Keyword.merge(options) forms = form.impl.to_form(form.source, form, field, options) html_escape Enum.map(forms, fn form -> hidden = Enum.map(form.hidden, fn {k, v} -> hidden_input(form, k, value: v) end) [hidden, fun.(form)] end) end @doc """ Returns the HTML5 validations that would apply to the given field. """ @spec input_validations(t, atom) :: boolean def input_validations(form, field) do form.impl.input_validations(form.source, field) end @mapping %{ "url" => :url_input, "email" => :email_input, "search" => :search_input, "password" => :password_input } @doc """ Gets the input type for a given field. If the underlying input type is a `:text_field`, a mapping could be given to further inflect the input type based solely on the field name. The default mapping is: %{"url" => :url_input, "email" => :email_input, "search" => :search_input, "password" => :password_input} """ @spec input_type(t, atom) :: atom def input_type(form, field, mapping \\ @mapping) do type = form.impl.input_type(form.source, field) if type == :text_input do field = Atom.to_string(field) Enum.find_value(mapping, type, fn {k, v} -> String.contains?(field, k) && v end) else type end end ## Form helpers @doc """ Generates a text input. The form should either be a `Phoenix.HTML.Form` emitted by `form_for` or an atom. All given options are forwarded to the underlying input, default values are provided for id, name and value if possible. ## Examples # Assuming form contains a User schema text_input(form, :name) #=> <input id="user_name" name="user[name]" type="text" value=""> text_input(:user, :name) #=> <input id="user_name" name="user[name]" type="text" value=""> """ def text_input(form, field, opts \\ []) do generic_input(:text, form, field, opts) end @doc """ Generates a hidden input. See `text_input/3` for example and docs. """ def hidden_input(form, field, opts \\ []) do generic_input(:hidden, form, field, opts) end @doc """ Generates an email input. See `text_input/3` for example and docs. """ def email_input(form, field, opts \\ []) do generic_input(:email, form, field, opts) end @doc """ Generates a number input. See `text_input/3` for example and docs. """ def number_input(form, field, opts \\ []) do generic_input(:number, form, field, opts) end @doc """ Generates a password input. For security reasons, the form data and parameter values are never re-used in `password_input/3`. Pass the value explicitly if you would like to set one. See `text_input/3` for example and docs. """ def password_input(form, field, opts \\ []) do opts = opts |> Keyword.put_new(:type, "password") |> Keyword.put_new(:id, field_id(form, field)) |> Keyword.put_new(:name, field_name(form, field)) tag(:input, opts) end @doc """ Generates an url input. See `text_input/3` for example and docs. """ def url_input(form, field, opts \\ []) do generic_input(:url, form, field, opts) end @doc """ Generates a search input. See `text_input/3` for example and docs. """ def search_input(form, field, opts \\ []) do generic_input(:search, form, field, opts) end @doc """ Generates a telephone input. See `text_input/3` for example and docs. """ def telephone_input(form, field, opts \\ []) do generic_input(:tel, form, field, opts) end @doc """ Generates a color input. Warning: this feature isn't available in all browsers. Check `http://caniuse.com/#feat=input-color` for further informations. See `text_input/3` for example and docs. """ def color_input(form, field, opts \\ []) do generic_input(:color, form, field, opts) end @doc """ Generates a range input. See `text_input/3` for example and docs. """ def range_input(form, field, opts \\ []) do generic_input(:range, form, field, opts) end defp generic_input(type, form, field, opts) when is_atom(field) and is_list(opts) do opts = opts |> Keyword.put_new(:type, type) |> Keyword.put_new(:id, field_id(form, field)) |> Keyword.put_new(:name, field_name(form, field)) |> Keyword.put_new(:value, field_value(form, field)) tag(:input, opts) end @doc """ Generates a textarea input. All given options are forwarded to the underlying input, default values are provided for id, name and textarea content if possible. ## Examples # Assuming form contains a User schema textarea(form, :description) #=> <textarea id="user_description" name="user[description]"></textarea> ## New lines Notice the generated textarea includes a new line after the opening tag. This is because the HTML spec says new lines after tags must be ignored and all major browser implementations do that. So in order to avoid new lines provided by the user from being ignored when the form is resubmitted, we automatically add a new line before the text area value. """ def textarea(form, field, opts \\ []) do opts = opts |> Keyword.put_new(:id, field_id(form, field)) |> Keyword.put_new(:name, field_name(form, field)) {value, opts} = Keyword.pop(opts, :value, field_value(form, field) || "") content_tag(:textarea, html_escape(["\n", value]), opts) end @doc """ Generates a file input. It requires the given form to be configured with `multipart: true` when invoking `form_for/4`, otherwise it fails with `ArgumentError`. See `text_input/3` for example and docs. """ def file_input(form, field, opts \\ []) do if match?(%Form{}, form) and !form.options[:multipart] do raise ArgumentError, "file_input/3 requires the enclosing form_for/4 " <> "to be configured with multipart: true" end opts = opts |> Keyword.put_new(:type, :file) |> Keyword.put_new(:id, field_id(form, field)) |> Keyword.put_new(:name, field_name(form, field)) opts = if opts[:multiple] do Keyword.update!(opts, :name, &("#{&1}[]")) else opts end tag(:input, opts) end @doc """ Generates a submit button to send the form. All options are forwarded to the underlying button tag. ## Examples submit "Submit" #=> <button type="submit">Submit</button> """ def submit([do: _] = block_option), do: submit([], block_option) def submit(_, opts \\ []) def submit(opts, [do: _] = block_option) do opts = Keyword.put_new(opts, :type, "submit") content_tag(:button, opts, block_option) end def submit(value, opts) do opts = Keyword.put_new(opts, :type, "submit") content_tag(:button, html_escape(value), opts) end @doc """ Generates a reset input to reset all the form fields to their original state. All options are forwarded to the underlying input tag. ## Examples reset "Reset" #=> <input type="reset" value="Reset"> reset "Reset", class: "btn" #=> <input type="reset" value="Reset" class="btn"> """ def reset(value, opts \\ []) do opts = opts |> Keyword.put_new(:type, "reset") |> Keyword.put_new(:value, value) tag(:input, opts) end @doc """ Generates a radio button. Invoke this function for each possible value you to be sent to the server. ## Examples # Assuming form contains a User schema radio_button(form, :role, "admin") #=> <input id="user_role_admin" name="user[role]" type="radio" value="admin"> ## Options All options are simply forwarded to the underlying HTML tag. """ def radio_button(form, field, value, opts \\ []) do value = html_escape(value) opts = opts |> Keyword.put_new(:type, "radio") |> Keyword.put_new(:id, field_id(form, field) <> "_" <> elem(value, 1)) |> Keyword.put_new(:name, field_name(form, field)) opts = if value == html_escape(field_value(form, field)) do Keyword.put_new(opts, :checked, true) else opts end tag(:input, [value: value] ++ opts) end @doc """ Generates a checkbox. This function is useful for sending boolean values to the server. ## Examples # Assuming form contains a User schema checkbox(form, :famous) #=> <input name="user[famous]" type="hidden" value="false"> <input checked="checked" id="user_famous" name="user[famous]" type="checkbox" value="true"> ## Options * `:checked_value` - the value to be sent when the checkbox is checked. Defaults to "true" * `:unchecked_value` - the value to be sent then the checkbox is unchecked, Defaults to "false" * `:value` - the value used to check if a checkbox is checked or unchecked. The default value is extracted from the form data if available All other options are forwarded to the underlying HTML tag. ## Hidden fields Because an unchecked checkbox is not sent to the server, Phoenix automatically generates a hidden field with the unchecked_value *before* the checkbox field to ensure the `unchecked_value` is sent when the checkbox is not marked. """ def checkbox(form, field, opts \\ []) do opts = opts |> Keyword.put_new(:type, "checkbox") |> Keyword.put_new(:id, field_id(form, field)) |> Keyword.put_new(:name, field_name(form, field)) {value, opts} = Keyword.pop(opts, :value, field_value(form, field)) {checked_value, opts} = Keyword.pop(opts, :checked_value, true) {unchecked_value, opts} = Keyword.pop(opts, :unchecked_value, false) # We html escape all values to be sure we are comparing # apples to apples. After all we may have true in the data # but "true" in the params and both need to match. value = html_escape(value) checked_value = html_escape(checked_value) unchecked_value = html_escape(unchecked_value) opts = if value == checked_value do Keyword.put_new(opts, :checked, true) else opts end html_escape [tag(:input, name: Keyword.get(opts, :name), type: "hidden", value: unchecked_value), tag(:input, [value: checked_value] ++ opts)] end @doc """ Generates a select tag with the given `options`. Values are expected to be an Enumerable containing two-item tuples (like a regular list or a map) or any Enumerable where the element will be used both as key and value for the generated select. ## Optgroups When a two-item map contains a list as its value, the options will be wrapped in an `<optroup>` using the key as its label. ## Examples # Assuming form contains a User schema select(form, :age, 0..120) #=> <select id="user_age" name="user[age]"> <option value="0">0</option> ... <option value="120">120</option> </select> select(form, :role, ["Admin": "admin", "User": "user"]) #=> <select id="user_role" name="user[role]"> <option value="admin">Admin</option> <option value="user">User</option> </select> select(form, :role, ["Admin": "admin", "User": "user"], prompt: "Choose your role") #=> <select id="user_role" name="user[role]"> <option value="">Choose your role</option> <option value="admin">Admin</option> <option value="user">User</option> </select> select(form, :country, %{"Europe" => ["UK", "Sweden", "France"], …}) #=> <select id="user_country" name="user[country]"> <optgroup label="Europe"> <option>UK</option> <option>Sweden</option> <option>France</option> </optgroup> ... </select> # Assuming users is a list of User schemas and form contains a Resource Schema select(form, :user_id, users |> Enum.map(&{&1.name, &1.id})) #=> <select id="user_id" name="resource[user_id]"> <option value="1">Ylva</option> <option value="2">Annora</option> </select> ## Options * `:prompt` - an option to include at the top of the options with the given prompt text * `:value` - the value used to select a given option. The default value is extracted from the form data if available * `:selected` - the default value to use when none was given in `:value` and none was sent as parameter All other options are forwarded to the underlying HTML tag. """ def select(form, field, options, opts \\ []) do {selected, opts} = Keyword.pop(opts, :selected) {value, opts} = Keyword.pop(opts, :value, field_value(form, field, selected)) {prefix, opts} = case Keyword.pop(opts, :prompt) do {nil, opts} -> {raw(""), opts} {prompt, opts} -> {content_tag(:option, prompt, value: ""), opts} end opts = opts |> Keyword.put_new(:id, field_id(form, field)) |> Keyword.put_new(:name, field_name(form, field)) options = options_for_select(options, prefix, html_escape(value)) content_tag(:select, options, opts) end defp options_for_select(values, options, value) do Enum.reduce values, options, fn {option_key, option_value}, acc -> option(option_key, option_value, value, acc) option, acc -> option(option, option, value, acc) end end defp option(group_label, group_values, value, acc) when is_list(group_values) or is_map(group_values) do section_options = options_for_select(group_values, [], value) tag = content_tag(:optgroup, section_options, label: group_label) html_escape [acc|tag] end defp option(option_key, option_value, value, acc) do option_key = html_escape(option_key) option_value = html_escape(option_value) selected = if is_list(value) do option_value in value else value == option_value end opts = [value: option_value, selected: selected] html_escape [acc|content_tag(:option, option_key, opts)] end @doc """ Generates a select tag with the given `options`. Values are expected to be an Enumerable containing two-item tuples (like maps and keyword lists) or any Enumerable where the element will be used both as key and value for the generated select. ## Examples # Assuming form contains a User schema multiple_select(form, :roles, ["Admin": 1, "Power User": 2]) #=> <select id="user_roles" name="user[roles][]"> <option value="1">Admin</option> <option value="2">Power User</option> </select> multiple_select(form, :roles, ["Admin": 1, "Power User": 2], value: [1]) #=> <select id="user_roles" name="user[roles]"> <option value="1" selected="selected" >Admin</option> <option value="2">Power User</option> </select> When working with structs, associations and embeds, you will need to tell Phoenix how to extract the value out of the collection. For example, imagine `user.roles` is a list of `%Role{}` structs. You must call it as: multiple_select(form, :roles, ["Admin": 1, "Power User": 2], selected: Enum.map(@user.roles, &(&1.id)) The `:selected` option will mark the given IDs as selected unless the form is being resubmitted. When resubmitted, it uses the form params as values. ## Options * `:value` - an Enum of values used to select given options. * `:selected` - the default value to use when none was given in `:value` and none was sent as parameter All other options are forwarded to the underlying HTML tag. """ def multiple_select(form, field, options, opts \\ []) do {selected, opts} = Keyword.pop(opts, :selected) {multiple, opts} = Keyword.pop(opts, :value, field_value(form, field, selected) || []) opts = opts |> Keyword.put_new(:id, field_id(form, field)) |> Keyword.put_new(:name, field_name(form, field) <> "[]") |> Keyword.put_new(:multiple, "") options = options_for_select(options, "", Enum.map(multiple, &html_escape/1)) content_tag(:select, options, opts) end ## Datetime @doc ~S""" Generates select tags for datetime. ## Examples # Assuming form contains a User schema datetime_select form, :born_at #=> <select id="user_born_at_year" name="user[born_at][year]">...</select> / <select id="user_born_at_month" name="user[born_at][month]">...</select> / <select id="user_born_at_day" name="user[born_at][day]">...</select> — <select id="user_born_at_hour" name="user[born_at][hour]">...</select> : <select id="user_born_at_min" name="user[born_at][minute]">...</select> If you want to include the seconds field (hidden by default), pass `second: []`: # Assuming form contains a User schema datetime_select form, :born_at, second: [] If you want to configure the years range: # Assuming form contains a User schema datetime_select form, :born_at, year: [options: 1900..2100] You are also able to configure `:month`, `:day`, `:hour`, `:minute` and `:second`. All options given to those keys will be forwarded to the underlying select. See `select/4` for more information. ## Options * `:value` - the value used to select a given option. The default value is extracted from the form data if available * `:default` - the default value to use when none was given in `:value` and none is available in the form data * `:year`, `:month`, `:day`, `:hour`, `:minute`, `:second` - options passed to the underlying select. See `select/4` for more information. The available values can be given in `:options`. * `:builder` - specify how the select can be build. It must be a function that receives a builder that should be invoked with the select name and a set of options. See builder below for more information. ## Builder The generated datetime_select can be customized at will by providing a builder option. Here is an example from EEx: <%= datetime_select form, :born_at, builder: fn b -> %> Date: <%= b.(:day, []) %> / <%= b.(:month, []) %> / <%= b.(:year, []) %> Time: <%= b.(:hour, []) %> : <%= b.(:minute, []) %> <% end %> Although we have passed empty lists as options (they are required), you could pass any option there and it would be given to the underlying select input. In practice, we recommend you to create your own helper with your default builder: def my_datetime_select(form, field, opts \\ []) do builder = fn b -> ~e"\"" Date: <%= b.(:day, []) %> / <%= b.(:month, []) %> / <%= b.(:year, []) %> Time: <%= b.(:hour, []) %> : <%= b.(:minute, []) %> "\"" end datetime_select(form, field, [builder: builder] ++ opts) end Then you are able to use your own datetime_select throughout your whole application. ## Supported date values The following values are supported as date: * a map containing the `year`, `month` and `day` keys (either as strings or atoms) * a tuple with three elements: `{year, month, day}` * `nil` ## Supported time values The following values are supported as time: * a map containing the `hour` and `min` keys and an optional `sec` key (either as strings or atoms) * a tuple with three elements: `{hour, min, sec}` * a tuple with four elements: `{hour, min, sec, usec}` * `nil` """ def datetime_select(form, field, opts \\ []) do value = Keyword.get(opts, :value, field_value(form, field) || Keyword.get(opts, :default)) builder = Keyword.get(opts, :builder) || fn b -> date = date_builder(b, opts) time = time_builder(b, opts) html_escape [date, raw(" &mdash; "), time] end builder.(datetime_builder(form, field, date_value(value), time_value(value), opts)) end @doc """ Generates select tags for date. Check `datetime_select/3` for more information on options and supported values. """ def date_select(form, field, opts \\ []) do value = Keyword.get(opts, :value, field_value(form, field) || Keyword.get(opts, :default)) builder = Keyword.get(opts, :builder) || &date_builder(&1, opts) builder.(datetime_builder(form, field, date_value(value), nil, opts)) end defp date_builder(b, _opts) do html_escape [b.(:year, []), raw(" / "), b.(:month, []), raw(" / "), b.(:day, [])] end defp date_value(%{"year" => year, "month" => month, "day" => day}), do: %{year: year, month: month, day: day} defp date_value(%{year: year, month: month, day: day}), do: %{year: year, month: month, day: day} defp date_value({{year, month, day}, _}), do: %{year: year, month: month, day: day} defp date_value({year, month, day}), do: %{year: year, month: month, day: day} defp date_value(nil), do: %{year: nil, month: nil, day: nil} defp date_value(other), do: raise(ArgumentError, "unrecognized date #{inspect other}") @doc """ Generates select tags for time. Check `datetime_select/3` for more information on options and supported values. """ def time_select(form, field, opts \\ []) do value = Keyword.get(opts, :value, field_value(form, field) || Keyword.get(opts, :default)) builder = Keyword.get(opts, :builder) || &time_builder(&1, opts) builder.(datetime_builder(form, field, nil, time_value(value), opts)) end defp time_builder(b, opts) do time = html_escape [b.(:hour, []), raw(" : "), b.(:minute, [])] if Keyword.get(opts, :second) do html_escape [time, raw(" : "), b.(:second, [])] else time end end defp time_value(%{"hour" => hour, "minute" => min} = map), do: %{hour: hour, minute: min, second: Map.get(map, "second", 0)} defp time_value(%{hour: hour, minute: min} = map), do: %{hour: hour, minute: min, second: Map.get(map, :second, 0)} # Backwards compatibility with Ecto v1.1 versions defp time_value(%{"hour" => hour, "min" => min} = map), do: %{hour: hour, minute: min, second: Map.get(map, "sec", 0)} defp time_value(%{hour: hour, min: min} = map), do: %{hour: hour, minute: min, second: Map.get(map, :sec, 0)} defp time_value({_, {hour, min, sec, _msec}}), do: %{hour: hour, minute: min, second: sec} defp time_value({hour, min, sec, _mseg}), do: %{hour: hour, minute: min, second: sec} defp time_value({_, {hour, min, sec}}), do: %{hour: hour, minute: min, second: sec} defp time_value({hour, min, sec}), do: %{hour: hour, minute: min, second: sec} defp time_value(nil), do: %{hour: nil, minute: nil, second: nil} defp time_value(other), do: raise(ArgumentError, "unrecognized time #{inspect other}") @months [ {"January", "1"}, {"February", "2"}, {"March", "3"}, {"April", "4"}, {"May", "5"}, {"June", "6"}, {"July", "7"}, {"August", "8"}, {"September", "9"}, {"October", "10"}, {"November", "11"}, {"December", "12"}, ] map = &Enum.map(&1, fn i -> i = Integer.to_string(i) {String.rjust(i, 2, ?0), i} end) @days map.(1..31) @hours map.(0..23) @minsec map.(0..59) defp datetime_builder(form, field, date, time, parent) do id = Keyword.get(parent, :id, field_id(form, field)) name = Keyword.get(parent, :name, field_name(form, field)) fn :year, opts when date != nil -> {year, _, _} = :erlang.date() {value, opts} = datetime_options(:year, year-5..year+5, id, name, parent, date, opts) select(:datetime, :year, value, opts) :month, opts when date != nil -> {value, opts} = datetime_options(:month, @months, id, name, parent, date, opts) select(:datetime, :month, value, opts) :day, opts when date != nil -> {value, opts} = datetime_options(:day, @days, id, name, parent, date, opts) select(:datetime, :day, value, opts) :hour, opts when time != nil -> {value, opts} = datetime_options(:hour, @hours, id, name, parent, time, opts) select(:datetime, :hour, value, opts) :minute, opts when time != nil -> {value, opts} = datetime_options(:minute, @minsec, id, name, parent, time, opts) select(:datetime, :minute, value, opts) :second, opts when time != nil -> {value, opts} = datetime_options(:second, @minsec, id, name, parent, time, opts) select(:datetime, :second, value, opts) end end defp datetime_options(type, values, id, name, parent, datetime, opts) do opts = Keyword.merge Keyword.get(parent, type, []), opts suff = Atom.to_string(type) {value, opts} = Keyword.pop(opts, :options, values) {value, opts |> Keyword.put_new(:id, id <> "_" <> suff) |> Keyword.put_new(:name, name <> "[" <> suff <> "]") |> Keyword.put_new(:value, Map.get(datetime, type))} end @doc """ Generates a label tag. The form should either be a `Phoenix.HTML.Form` emitted by `form_for` or an atom. All given options are forwarded to the underlying tag. A default value is provided for `for` attribute but can be overriden if you pass a value to the `for` option. Text content would be inferred from `field` if not specified. ## Examples # Assuming form contains a User schema label(form, :name, "Name") #=> <label for="user_name">Name</label> label(:user, :email, "Email") #=> <label for="user_email">Email</label> label(:user, :email) #=> <label for="user_email">Email</label> label(:user, :email, class: "control-label") #=> <label for="user_email" class="control-label">Email</label> label :user, :email do "E-mail Address" end #=> <label for="user_email">E-mail Address</label> label :user, :email, class: "control-label" do "E-mail Address" end #=> <label class="control-label" for="user_email">E-mail Address</label> """ def label(form, field) do label(form, field, humanize(field), []) end @doc """ See `label/2`. """ def label(form, field, text) when is_binary(text) do label(form, field, text, []) end def label(form, field, [do: block]) do label(form, field, [], do: block) end def label(form, field, opts) when is_list(opts) do label(form, field, humanize(field), opts) end @doc """ See `label/2`. """ def label(form, field, text, opts) when is_binary(text) and is_list(opts) do opts = Keyword.put_new(opts, :for, field_id(form, field)) content_tag(:label, text, opts) end def label(form, field, opts, [do: block]) do opts = Keyword.put_new(opts, :for, field_id(form, field)) content_tag(:label, opts, do: block) end @doc """ Returns a value of a corresponding form field. The `form` should either be a `Phoenix.HTML.Form` emitted by `form_for` or an atom. When a form is given, the value will first be looked up in `params`, then fallback to the optional `default` argument. If no `default` argument is provided, it will try to fetch the value from the form data. Always returns `default` if a given form is an atom. """ def field_value(form, field, default \\ nil) def field_value(%{data: data, params: params}, field, default) do case Map.fetch(params, Atom.to_string(field)) do {:ok, value} -> value :error -> default || Map.get(data, field) end end def field_value(name, _field, default) when is_atom(name), do: default @doc """ Returns an id of a corresponding form field. The form should either be a `Phoenix.HTML.Form` emitted by `form_for` or an atom. """ def field_id(%{id: id}, field), do: "#{id}_#{field}" def field_id(name, field) when is_atom(name), do: "#{name}_#{field}" @doc """ Returns a name of a corresponding form field. The form should either be a `Phoenix.HTML.Form` emitted by `form_for` or an atom. """ def field_name(%{name: name}, field), do: "#{name}[#{field}]" def field_name(name, field) when is_atom(name), do: "#{name}[#{field}]" end
31.200168
106
0.63272
9ed43bab2301fbeb172fca44b85d17d1cf240d7a
984
ex
Elixir
lib/cforum/accounts/badge_group.ex
campingrider/cforum_ex
cf27684c47d6dc26c9c37a946f1c729a79d27c70
[ "MIT" ]
null
null
null
lib/cforum/accounts/badge_group.ex
campingrider/cforum_ex
cf27684c47d6dc26c9c37a946f1c729a79d27c70
[ "MIT" ]
null
null
null
lib/cforum/accounts/badge_group.ex
campingrider/cforum_ex
cf27684c47d6dc26c9c37a946f1c729a79d27c70
[ "MIT" ]
null
null
null
defmodule Cforum.Accounts.BadgeGroup do use CforumWeb, :model @primary_key {:badge_group_id, :id, autogenerate: true} @derive {Phoenix.Param, key: :badge_group_id} schema "badge_groups" do field(:name, :string) many_to_many(:badges, Cforum.Accounts.Badge, join_through: "badges_badge_groups", on_delete: :delete_all, join_keys: [badge_group_id: :badge_group_id, badge_id: :badge_id] ) timestamps(inserted_at: :created_at) end # def changeset(struct, params \\ %{}) do # struct # |> cast(params, [:score_needed, :name, :description, :slug, :badge_medal_type, :badge_type, :order]) # |> validate_required([:name, :slug, :badge_medal_type, :badge_type, :order]) # |> unique_constraint(:slug, name: :badges_slug_key) # |> unique_constraint(:badge_type, name: :badges_badge_type_idx) # |> validate_inclusion(:badge_type, @badge_types) # |> validate_inclusion(:badge_medal_type, @badge_medal_types) # end end
33.931034
106
0.698171
9ed44af9e9e7ab44ba95ebce809824037460382b
1,398
ex
Elixir
lib/upload/adapters/local.ex
artemeff/upload
ab495e79caed499c0c80d273e581887b7df51b9d
[ "MIT" ]
null
null
null
lib/upload/adapters/local.ex
artemeff/upload
ab495e79caed499c0c80d273e581887b7df51b9d
[ "MIT" ]
null
null
null
lib/upload/adapters/local.ex
artemeff/upload
ab495e79caed499c0c80d273e581887b7df51b9d
[ "MIT" ]
null
null
null
defmodule Upload.Adapters.Local do @moduledoc """ An `Upload.Adapter` that saves files to disk. ### Configuration config :upload, Upload.Adapters.Local, base_url: "/uploads", # optional storage_path: "priv/static/uploads" # optional """ use Upload.Adapter alias Upload.Config @doc """ Path where files are stored. Defaults to `priv/static/uploads`. ## Examples iex> Upload.Adapters.Local.storage_path() "priv/static/uploads" """ def storage_path do Config.get(__MODULE__, :storage_path, "priv/static/uploads") end @doc """ The URL prefix for the file key. ## Examples iex> Upload.Adapters.Local.base_url() "/uploads" """ def base_url do Config.get(__MODULE__, :base_url, "/uploads") end @impl true def get_url(key), do: join_url(base_url(), key) @impl true def get_signed_url(key, _opts), do: {:ok, get_url(key)} @impl true def transfer(%Upload{key: key, path: path} = upload) do filename = Path.join(storage_path(), key) directory = Path.dirname(filename) with :ok <- File.mkdir_p(directory), :ok <- File.cp(path, filename) do {:ok, %Upload{upload | status: :transferred}} else {:error, posix} -> {:error, posix} end end defp join_url(a, b) do String.trim_trailing(a, "/") <> "/" <> String.trim_leading(b, "/") end end
21.181818
70
0.628755
9ed4522547f8691fa04414455e97fb582b47288a
906
ex
Elixir
clients/big_query_data_transfer/lib/google_api/big_query_data_transfer/v1/metadata.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/big_query_data_transfer/lib/google_api/big_query_data_transfer/v1/metadata.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/big_query_data_transfer/lib/google_api/big_query_data_transfer/v1/metadata.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "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.BigQueryDataTransfer.V1 do @moduledoc """ API client metadata for GoogleApi.BigQueryDataTransfer.V1. """ @discovery_revision "20211125" def discovery_revision(), do: @discovery_revision end
33.555556
74
0.764901
9ed465cee72620d6082580b10112daf525a946b1
1,828
exs
Elixir
test/core/sup_tree_core/executor_pool/executor_pool_test.exs
ikeyasu/antikythera
544fdd22e46b1f34177053d87d9e2a9708c74113
[ "Apache-2.0" ]
null
null
null
test/core/sup_tree_core/executor_pool/executor_pool_test.exs
ikeyasu/antikythera
544fdd22e46b1f34177053d87d9e2a9708c74113
[ "Apache-2.0" ]
null
null
null
test/core/sup_tree_core/executor_pool/executor_pool_test.exs
ikeyasu/antikythera
544fdd22e46b1f34177053d87d9e2a9708c74113
[ "Apache-2.0" ]
null
null
null
# Copyright(c) 2015-2018 ACCESS CO., LTD. All rights reserved. defmodule AntikytheraCore.ExecutorPoolTest do use Croma.TestCase alias ExecutorPool.Setting, as: EPoolSetting alias ExecutorPool.RegisteredName, as: RegName alias AntikytheraCore.Ets.GearActionRunnerPools defp child_pids(pid) do Supervisor.which_children(pid) |> Enum.map(fn {_, p, _, _} -> p end) end test "should correctly setup processes within the supervision tree structure" do epool_root = Process.whereis(ExecutorPool.Sup) assert child_pids(epool_root) == [] assert RaftFleet.consensus_groups() == %{} # spawn an ExecutorPool epool_id = {:gear, :testgear} setting = %EPoolSetting{n_pools_a: 2, pool_size_a: 1, pool_size_j: 1, ws_max_connections: 100} ExecutorPool.start_executor_pool(epool_id, setting) [{_, epool_pid, _, _}] = Supervisor.which_children(epool_root) assert Process.whereis(RegName.supervisor(epool_id)) == epool_pid action_pool_multi = Process.whereis(RegName.action_runner_pool_multi(epool_id)) job_pool_sup = Process.whereis(RegName.async_job_runner_pool(epool_id)) child_pids = child_pids(epool_pid) assert length(child_pids) == 7 assert action_pool_multi in child_pids assert job_pool_sup in child_pids ExecutorPoolHelper.wait_until_async_job_queue_added(epool_id) # should be able to checkout worker pid from the 2 types of process pools assert PoolSup.Multi.transaction(GearActionRunnerPools.table_name(), epool_id, &is_pid/1) assert PoolSup.transaction(job_pool_sup, &is_pid/1) ExecutorPoolHelper.kill_and_wait(epool_id) refute Process.alive?(epool_pid) assert Process.whereis(RegName.supervisor(epool_id)) == nil assert ExecutorPool.kill_executor_pool(epool_id) == :ok # should be idempotent end end
43.52381
98
0.756018
9ed49f4a2394d12cc26733c97cc67f248a536bf3
33
exs
Elixir
.iex.exs
milmazz/aaron
2c8fb36ee92381b4ee0a744353aae3bd0b12fa8e
[ "Apache-2.0" ]
2
2019-01-09T07:47:49.000Z
2020-10-24T06:45:36.000Z
.iex.exs
milmazz/aaron
2c8fb36ee92381b4ee0a744353aae3bd0b12fa8e
[ "Apache-2.0" ]
7
2019-11-11T12:22:36.000Z
2021-06-25T15:20:43.000Z
.iex.exs
milmazz/aaron
2c8fb36ee92381b4ee0a744353aae3bd0b12fa8e
[ "Apache-2.0" ]
1
2021-06-13T07:39:05.000Z
2021-06-13T07:39:05.000Z
import NimbleParsec import Aaron
11
19
0.878788
9ed4e7bd6f0c3f9d476e31058814c2e218cf287e
1,100
ex
Elixir
phoenix/lib/hello_world_web/channels/user_socket.ex
jrpotter/flake-templates
82799f9fe3ee9d2cfc28550aef74e759a5d5534d
[ "Apache-2.0" ]
null
null
null
phoenix/lib/hello_world_web/channels/user_socket.ex
jrpotter/flake-templates
82799f9fe3ee9d2cfc28550aef74e759a5d5534d
[ "Apache-2.0" ]
null
null
null
phoenix/lib/hello_world_web/channels/user_socket.ex
jrpotter/flake-templates
82799f9fe3ee9d2cfc28550aef74e759a5d5534d
[ "Apache-2.0" ]
null
null
null
defmodule HelloWorldWeb.UserSocket do use Phoenix.Socket ## Channels # channel "room:*", HelloWorldWeb.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(_params, socket, _connect_info) do {:ok, socket} 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: # # HelloWorldWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) # # Returning `nil` makes this socket anonymous. @impl true def id(_socket), do: nil end
30.555556
85
0.697273
9ed52617b7299f182ce54bda1cf8a6e540ff407a
2,483
ex
Elixir
lib/texas_holdem_web.ex
thelightcosine/texas_holdem-phoenix
31da9754082015b7562639bf2d5b8ac5212f11d0
[ "BSD-3-Clause" ]
null
null
null
lib/texas_holdem_web.ex
thelightcosine/texas_holdem-phoenix
31da9754082015b7562639bf2d5b8ac5212f11d0
[ "BSD-3-Clause" ]
null
null
null
lib/texas_holdem_web.ex
thelightcosine/texas_holdem-phoenix
31da9754082015b7562639bf2d5b8ac5212f11d0
[ "BSD-3-Clause" ]
null
null
null
defmodule TexasHoldemWeb do @moduledoc """ The entrypoint for defining your web interface, such as controllers, views, channels and so on. This can be used in your application as: use TexasHoldemWeb, :controller use TexasHoldemWeb, :view The definitions below will be executed for every view, controller, etc, so keep them short and clean, focused on imports, uses and aliases. Do NOT define functions inside the quoted expressions below. Instead, define any helper function in modules and import those modules here. """ def controller do quote do use Phoenix.Controller, namespace: TexasHoldemWeb import Plug.Conn import TexasHoldemWeb.Gettext alias TexasHoldemWeb.Router.Helpers, as: Routes end end def view do quote do use Phoenix.View, root: "lib/texas_holdem_web/templates", namespace: TexasHoldemWeb # Import convenience functions from controllers import Phoenix.Controller, only: [get_flash: 1, get_flash: 2, view_module: 1, view_template: 1] # Include shared imports and aliases for views unquote(view_helpers()) end end def live_view do quote do use Phoenix.LiveView, layout: {TexasHoldemWeb.LayoutView, "live.html"} unquote(view_helpers()) end end def live_component do quote do use Phoenix.LiveComponent unquote(view_helpers()) end end def component do quote do use Phoenix.Component unquote(view_helpers()) end end def router do quote do use Phoenix.Router import Plug.Conn import Phoenix.Controller import Phoenix.LiveView.Router end end def channel do quote do use Phoenix.Channel import TexasHoldemWeb.Gettext end end defp view_helpers do quote do # Use all HTML functionality (forms, tags, etc) use Phoenix.HTML # Import LiveView and .heex helpers (live_render, live_patch, <.form>, etc) import Phoenix.LiveView.Helpers # Import basic rendering functionality (render, render_layout, etc) import Phoenix.View import TexasHoldemWeb.ErrorHelpers import TexasHoldemWeb.Gettext alias TexasHoldemWeb.Router.Helpers, as: Routes end end @doc """ When used, dispatch to the appropriate controller/view/etc. """ defmacro __using__(which) when is_atom(which) do apply(__MODULE__, which, []) end end
22.369369
81
0.68385
9ed5309d4441bb420410cf86b83df8c0c9caae61
204
exs
Elixir
apps/nerves_hub_web_core/priv/repo/migrations/20200827172631_add_patchable_to_firmware.exs
tonnenpinguin/nerves_hub_web
9d36921eb7e20d20a3e3bd308cc98ad7b60cfa72
[ "Apache-2.0" ]
111
2018-07-25T01:07:51.000Z
2022-01-25T17:03:01.000Z
apps/nerves_hub_web_core/priv/repo/migrations/20200827172631_add_patchable_to_firmware.exs
tonnenpinguin/nerves_hub_web
9d36921eb7e20d20a3e3bd308cc98ad7b60cfa72
[ "Apache-2.0" ]
361
2018-07-22T12:53:00.000Z
2022-03-31T18:50:34.000Z
apps/nerves_hub_web_core/priv/repo/migrations/20200827172631_add_patchable_to_firmware.exs
tonnenpinguin/nerves_hub_web
9d36921eb7e20d20a3e3bd308cc98ad7b60cfa72
[ "Apache-2.0" ]
54
2018-08-26T02:58:04.000Z
2022-03-09T10:12:19.000Z
defmodule NervesHubWebCore.Repo.Migrations.AddPatchableToFirmware do use Ecto.Migration def change do alter table(:firmwares) do add(:patchable, :boolean, default: false) end end end
20.4
68
0.740196
9ed54c0a8e6eb8d3dcc03c52335b52b7ab75d489
424
ex
Elixir
test/support/user.ex
Frameio/ex_aws
3b335b6ed7932b5cf991323d26cf5497e1e6c122
[ "Unlicense", "MIT" ]
null
null
null
test/support/user.ex
Frameio/ex_aws
3b335b6ed7932b5cf991323d26cf5497e1e6c122
[ "Unlicense", "MIT" ]
null
null
null
test/support/user.ex
Frameio/ex_aws
3b335b6ed7932b5cf991323d26cf5497e1e6c122
[ "Unlicense", "MIT" ]
1
2021-01-22T12:16:23.000Z
2021-01-22T12:16:23.000Z
defmodule Test.User do @derive ExAws.Dynamo.Encodable defstruct [:email, :name, :age, :admin] defimpl ExAws.Dynamo.Decodable do def decode(%{name: %{"first" => first, "last" => last}} = user) do %{user | name: %{first: first, last: last}} end def decode(value), do: value end end defmodule Test.Nested do @derive {ExAws.Dynamo.Encodable, only: [:items]} defstruct items: [], secret: nil end
23.555556
70
0.648585
9ed57055f6487e7cbdbbbf630f650d74dc77ad7c
1,871
ex
Elixir
clients/genomics/lib/google_api/genomics/v1/model/program.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/genomics/lib/google_api/genomics/v1/model/program.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/genomics/lib/google_api/genomics/v1/model/program.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &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.Genomics.V1.Model.Program do @moduledoc """ ## Attributes - commandLine (String): The command line used to run this program. Defaults to: `null`. - id (String): The user specified locally unique ID of the program. Used along with &#x60;prevProgramId&#x60; to define an ordering between programs. Defaults to: `null`. - name (String): The display name of the program. This is typically the colloquial name of the tool used, for example &#39;bwa&#39; or &#39;picard&#39;. Defaults to: `null`. - prevProgramId (String): The ID of the program run before this one. Defaults to: `null`. - version (String): The version of the program run. Defaults to: `null`. """ defstruct [ :"commandLine", :"id", :"name", :"prevProgramId", :"version" ] end defimpl Poison.Decoder, for: GoogleApi.Genomics.V1.Model.Program do def decode(value, _options) do value end end defimpl Poison.Encoder, for: GoogleApi.Genomics.V1.Model.Program do def encode(value, options) do GoogleApi.Genomics.V1.Deserializer.serialize_non_nil(value, options) end end
34.648148
175
0.728487
9ed57b4c32a4dbdf7798a150b086883cd509c54e
547
exs
Elixir
apps/management/mix.exs
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
12
2020-01-27T19:43:02.000Z
2021-07-28T19:46:29.000Z
apps/management/mix.exs
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
81
2020-01-28T18:07:23.000Z
2021-11-22T02:12:13.000Z
apps/management/mix.exs
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
10
2020-02-13T21:24:09.000Z
2020-05-21T18:39:35.000Z
defmodule Management.MixProject do use Mix.Project def project do [ app: :management, version: "0.1.0", build_path: "../../_build", config_path: "../../config/config.exs", deps_path: "../../deps", lockfile: "../../mix.lock", elixir: "~> 1.9", start_permanent: Mix.env() == :prod, deps: deps() ] end def application do [ extra_applications: [:logger] ] end defp deps do [ {:brook, "~> 0.6"}, {:credo, "~> 1.3", only: [:dev]} ] end end
17.645161
45
0.499086
9ed59f3bb6023258907f7a8860ba73b40189fe28
1,251
ex
Elixir
lib/entice/web/endpoint.ex
hoodaly/web
852f4c3da5b1f248d08206b58cd58981e76f6899
[ "WTFPL" ]
null
null
null
lib/entice/web/endpoint.ex
hoodaly/web
852f4c3da5b1f248d08206b58cd58981e76f6899
[ "WTFPL" ]
null
null
null
lib/entice/web/endpoint.ex
hoodaly/web
852f4c3da5b1f248d08206b58cd58981e76f6899
[ "WTFPL" ]
null
null
null
defmodule Entice.Web.Endpoint do use Phoenix.Endpoint, otp_app: :entice_web socket "/socket", Entice.Web.Socket plug Plug.Static, at: "/", from: :entice_web, gzip: false, only: ~w(css fonts images js favicon.ico robots.txt) # Code reloading can be explicitly enabled under the # :code_reloader configuration of your endpoint. if code_reloading? do socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket plug Phoenix.LiveReloader plug Phoenix.CodeReloader end plug Plug.RequestId plug Plug.Logger plug Plug.Parsers, parsers: [:urlencoded, :multipart, :json], pass: ["*/*"], json_decoder: Poison plug Plug.MethodOverride plug Plug.Head plug Plug.Session, store: :cookie, key: "entice_session", signing_salt: "wZg9FGRp", encryption_salt: "KzX0FbQY" plug Entice.Web.Router # Helpers that are not offered by phoenix by default def plain_broadcast(topic, message), do: Phoenix.PubSub.broadcast(@pubsub_server, topic, message) def plain_broadcast_from(topic, message), do: plain_broadcast_from(self(), topic, message) def plain_broadcast_from(pid, topic, message), do: Phoenix.PubSub.broadcast_from(@pubsub_server, pid, topic, message) end
24.529412
72
0.721823
9ed5bfd8ba34fa2efc7d1cac02c120bb86eee113
1,131
exs
Elixir
config/config.exs
kevsmith/usgov_data
5c5365f40f191e70480a76e83a53c2d03965ace2
[ "BSD-2-Clause" ]
null
null
null
config/config.exs
kevsmith/usgov_data
5c5365f40f191e70480a76e83a53c2d03965ace2
[ "BSD-2-Clause" ]
null
null
null
config/config.exs
kevsmith/usgov_data
5c5365f40f191e70480a76e83a53c2d03965ace2
[ "BSD-2-Clause" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :usgov_data, key: :value # # and access this configuration in your application as: # # Application.get_env(:usgov_data, :key) # # You can also configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env()}.exs"
36.483871
73
0.751547
9ed5d380742d43645e77ab1b00099e82e70587ec
1,659
ex
Elixir
clients/service_management/lib/google_api/service_management/v1/model/submit_config_source_response.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
null
null
null
clients/service_management/lib/google_api/service_management/v1/model/submit_config_source_response.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "Apache-2.0" ]
null
null
null
clients/service_management/lib/google_api/service_management/v1/model/submit_config_source_response.ex
hauptbenutzer/elixir-google-api
7b9e3a114a49cfc774a7afd03e299a0d43e4e6b2
[ "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.ServiceManagement.V1.Model.SubmitConfigSourceResponse do @moduledoc """ Response message for SubmitConfigSource method. ## Attributes - serviceConfig (Service): The generated service configuration. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :serviceConfig => GoogleApi.ServiceManagement.V1.Model.Service.t() } field(:serviceConfig, as: GoogleApi.ServiceManagement.V1.Model.Service) end defimpl Poison.Decoder, for: GoogleApi.ServiceManagement.V1.Model.SubmitConfigSourceResponse do def decode(value, options) do GoogleApi.ServiceManagement.V1.Model.SubmitConfigSourceResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ServiceManagement.V1.Model.SubmitConfigSourceResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.5625
95
0.768535
9ed64874661b6e7449ef5d73da14c02b20e7ef74
3,206
exs
Elixir
test/map_test.exs
MikaAK/riak-elixir-client
c58700ec30a451a46b226a09387144becc47d5ae
[ "Apache-2.0" ]
193
2015-01-04T15:36:15.000Z
2022-03-17T21:31:57.000Z
test/map_test.exs
MikaAK/riak-elixir-client
c58700ec30a451a46b226a09387144becc47d5ae
[ "Apache-2.0" ]
51
2015-02-12T02:32:23.000Z
2020-09-22T11:10:56.000Z
test/map_test.exs
MikaAK/riak-elixir-client
c58700ec30a451a46b226a09387144becc47d5ae
[ "Apache-2.0" ]
54
2015-03-05T01:10:33.000Z
2021-09-27T10:40:26.000Z
defmodule Riak.CRDT.MapTest do require IEx use Riak.Case alias Riak.CRDT.Map alias Riak.CRDT.Register alias Riak.CRDT.Flag alias Riak.CRDT.Counter alias Riak.CRDT.Set @moduletag :riak2 test "create, update and find a map with other CRDTs" do key = Riak.Helper.random_key reg_data = "Register data" reg = Register.new(reg_data) reg_key = "register_key" flag = Flag.new |> Flag.enable flag_key = "flag_key" counter = Counter.new |> Counter.increment counter_key = "counter_key" set = Set.new |> Set.put("foo") set_key = "set_key" Map.new |> Map.put(reg_key, reg) |> Map.put(flag_key, flag) |> Map.update(:counter, counter_key, fn _ -> counter end) |> Map.put(set_key, set) |> Riak.update("maps", "bucketmap", key) map = Riak.find("maps", "bucketmap", key) |> Map.value map_keys = :orddict.fetch_keys(map) assert {"counter_key", :counter} in map_keys assert {"flag_key", :flag} in map_keys assert {"register_key", :register} in map_keys assert {"set_key", :set} in map_keys assert :orddict.size(map) == 4 data = :orddict.to_list(map) assert {{reg_key, :register}, reg_data} in data assert {{flag_key, :flag}, true} in data assert {{counter_key, :counter}, 1} in data assert {{set_key, :set}, ["foo"]} in data end test "create, update and find nested maps" do key = Riak.Helper.random_key flag = Flag.new |> Flag.enable flag_key = "flag_key" nested = Map.new |> Map.put(flag_key, flag) nested_key = "nested_key" Map.new |> Map.put(nested_key, nested) |> Riak.update("maps", "bucketmap", key) map = Riak.find("maps", "bucketmap", key) value_map = map |> Map.value assert :orddict.size(value_map) == 1 assert :orddict.fetch({nested_key, :map}, value_map) == [{{flag_key, :flag}, true}] exists = Riak.find("maps", "bucketmap", key) |> Map.has_key?({nested_key, :map}) assert exists == true Riak.find("maps", "bucketmap", key) |> Map.delete({nested_key, :map}) |> Riak.update("maps", "bucketmap", key) exists = Riak.find("maps", "bucketmap", key) |> Map.has_key?({nested_key, :map}) assert exists == false end test "create, update, delete map" do key = Riak.Helper.random_key Map.new |> Map.put("register_key", Register.new("Some Data")) |> Riak.update("maps", "users", key) reg_data = Riak.find("maps", "users", key) |> Map.get(:register, "register_key") assert "Some Data" == reg_data Riak.delete("maps", "users", key) assert Riak.find("maps", "users", key) == nil end test "map key exists" do key = Riak.Helper.random_key Map.new |> Map.put("register_key", Register.new("Some Data")) |> Riak.update("maps", "users", key) exists = Riak.find("maps", "users", key) |> Map.has_key?({"nothere", :register}) assert exists == false exists = Riak.find("maps", "users", key) |> Map.has_key?({"register_key", :register}) assert exists == true keys = Riak.find("maps", "users", key) |> Map.keys() assert keys == [{"register_key", :register}] end end
25.046875
87
0.616344
9ed6629b88f05531d4dd21dfd73dd75a6ffe9a69
781
ex
Elixir
Microsoft.Azure.Management.Network/lib/microsoft/azure/management/network/model/load_balancer_probe_list_result.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
4
2018-09-29T03:43:15.000Z
2021-04-01T18:30:46.000Z
Microsoft.Azure.Management.Network/lib/microsoft/azure/management/network/model/load_balancer_probe_list_result.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
Microsoft.Azure.Management.Network/lib/microsoft/azure/management/network/model/load_balancer_probe_list_result.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
# NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule Microsoft.Azure.Management.Network.Model.LoadBalancerProbeListResult do @moduledoc """ Response for ListProbe API service call. """ @derive [Poison.Encoder] defstruct [ :"value", :"nextLink" ] @type t :: %__MODULE__{ :"value" => [Probe], :"nextLink" => String.t } end defimpl Poison.Decoder, for: Microsoft.Azure.Management.Network.Model.LoadBalancerProbeListResult do import Microsoft.Azure.Management.Network.Deserializer def decode(value, options) do value |> deserialize(:"value", :list, Microsoft.Azure.Management.Network.Model.Probe, options) end end
26.033333
100
0.724712
9ed6746a6afb4b64bfc7f7721bd9dff2519be617
5,384
ex
Elixir
lib/excoveralls/local.ex
Apelsinka223/excoveralls
500b8638851a3b6f261127ee72fe4a4a1805ea61
[ "MIT" ]
null
null
null
lib/excoveralls/local.ex
Apelsinka223/excoveralls
500b8638851a3b6f261127ee72fe4a4a1805ea61
[ "MIT" ]
null
null
null
lib/excoveralls/local.ex
Apelsinka223/excoveralls
500b8638851a3b6f261127ee72fe4a4a1805ea61
[ "MIT" ]
2
2019-03-15T08:12:53.000Z
2019-06-11T11:34:04.000Z
defmodule ExCoveralls.Local do @moduledoc """ Locally displays the result to screen. """ defmodule Count do @moduledoc """ Stores count information for calculating coverage values. """ defstruct lines: 0, relevant: 0, covered: 0 end @doc """ Provides an entry point for the module. """ def execute(stats, options \\ []) do print_summary(stats, options) if options[:detail] == true do source(stats, options[:filter]) |> IO.puts end ExCoveralls.Stats.ensure_minimum_coverage(stats) end @doc """ Format the source code with color for the files that matches with the specified patterns. """ def source(stats, _patterns = nil), do: source(stats) def source(stats, _patterns = []), do: source(stats) def source(stats, patterns) do Enum.filter(stats, fn(stat) -> String.contains?(stat[:name], patterns) end) |> source end def source(stats) do stats |> Enum.map(&format_source/1) |> Enum.join("\n") end @doc """ Prints summary statistics for given coverage. """ def print_summary(stats, options \\ []) do enabled = ExCoveralls.Settings.get_print_summary if enabled do file_width = ExCoveralls.Settings.get_file_col_width IO.puts "----------------" IO.puts print_string("~-6s ~-#{file_width}s ~8s ~8s ~8s", ["COV", "FILE", "LINES", "RELEVANT", "MISSED"]) coverage(stats, options) |> IO.puts IO.puts "----------------" end end defp format_source(stat) do "\n\e[33m--------#{stat[:name]}--------\e[m\n" <> colorize(stat) end defp colorize(%{name: _name, source: source, coverage: coverage}) do lines = String.split(source, "\n") Enum.zip(lines, coverage) |> Enum.map(&do_colorize/1) |> Enum.join("\n") end defp do_colorize({line, coverage}) do case coverage do nil -> line 0 -> "\e[31m#{line}\e[m" _ -> "\e[32m#{line}\e[m" end end @doc """ Format the source coverage stats into string. """ def coverage(stats, options \\ []) do count_info = Enum.map(stats, fn(stat) -> [stat, calculate_count(stat[:coverage])] end) count_info = sort(count_info, options) Enum.join(format_body(count_info), "\n") <> "\n" <> format_total(count_info) end defp sort(count_info, options) do if options[:sort] do sort_order = parse_sort_options(options) flattened = Enum.map(count_info, fn original -> [stat, count] = original %{ "cov" => get_coverage(count), "file" => stat[:name], "lines" => count.lines, "relevant" => count.relevant, "missed" => count.relevant - count.covered, :_original => original } end) sorted = Enum.reduce(sort_order, flattened, fn {key, comparator}, acc -> Enum.sort(acc, fn(x, y) -> args = [x[key], y[key]] apply(Kernel, comparator, args) end) end) Enum.map(sorted, fn flattened -> flattened[:_original] end) else Enum.sort(count_info, fn([x, _], [y, _]) -> x[:name] <= y[:name] end) end end defp parse_sort_options(options) do sort_order = options[:sort] |> String.split(",") |> Enum.reverse() Enum.map(sort_order, fn sort_chunk -> case String.split(sort_chunk, ":") do [key, "asc"] -> {key, :<=} [key, "desc"] -> {key, :>=} [key] -> {key, :>=} end end) end defp format_body(info) do Enum.map(info, &format_info/1) end defp format_info([stat, count]) do coverage = get_coverage(count) file_width = ExCoveralls.Settings.get_file_col_width print_string("~5.1f% ~-#{file_width}s ~8w ~8w ~8w", [coverage, stat[:name], count.lines, count.relevant, count.relevant - count.covered]) end defp format_total(info) do totals = Enum.reduce(info, %Count{}, fn([_, count], acc) -> append(count, acc) end) coverage = get_coverage(totals) print_string("[TOTAL] ~5.1f%", [coverage]) end defp append(a, b) do %Count{ lines: a.lines + b.lines, relevant: a.relevant + b.relevant, covered: a.covered + b.covered } end defp get_coverage(count) do case count.relevant do 0 -> default_coverage_value() _ -> (count.covered / count.relevant) * 100 end end defp default_coverage_value do options = ExCoveralls.Settings.get_coverage_options case Map.fetch(options, "treat_no_relevant_lines_as_covered") do {:ok, false} -> 0.0 _ -> 100.0 end end @doc """ Calucate count information from thhe coverage stats. """ def calculate_count(coverage) do do_calculate_count(coverage, 0, 0, 0) end defp do_calculate_count([], lines, relevant, covered) do %Count{lines: lines, relevant: relevant, covered: covered} end defp do_calculate_count([h|t], lines, relevant, covered) do case h do nil -> do_calculate_count(t, lines + 1, relevant, covered) 0 -> do_calculate_count(t, lines + 1, relevant + 1, covered) n when is_number(n) -> do_calculate_count(t, lines + 1, relevant + 1, covered + 1) _ -> raise "Invalid data - #{h}" end end defp print_string(format, params) do char_list = :io_lib.format(format, params) List.to_string(char_list) end end
27.191919
111
0.603083
9ed694011bebcc9f8596516b91767d8909c66b0d
1,084
exs
Elixir
config/config.exs
seanbreckenridge/glue
60cbe6478be27572de6c6d5276a806b5940ffcbc
[ "Apache-2.0" ]
5
2020-07-04T12:18:58.000Z
2022-01-13T22:35:40.000Z
config/config.exs
seanbreckenridge/glue
60cbe6478be27572de6c6d5276a806b5940ffcbc
[ "Apache-2.0" ]
37
2020-07-20T23:35:56.000Z
2022-03-19T02:13:16.000Z
config/config.exs
seanbreckenridge/glue
60cbe6478be27572de6c6d5276a806b5940ffcbc
[ "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. # General application configuration use Mix.Config config :glue, ecto_repos: [Glue.Repo] # import application specific setup import_config "application.exs" # Configures the endpoint config :glue, GlueWeb.Endpoint, url: [host: "localhost"], secret_key_base: "5QFoBI8DVq5A+TYnHgx7cq6nr0dFTFdz9YNBMvyp6rdI+8hHGyC+99zDJ7gA3uAq", render_errors: [view: GlueWeb.ErrorView, accepts: ~w(html json), layout: false], pubsub_server: Glue.PubSub, live_view: [signing_salt: "9DEMuP5K"] # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:request_id] # Use Jason for JSON parsing in Phoenix config :phoenix, :json_library, Jason # 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.971429
86
0.76845
9ed6a56c42f38d6a1b37deab393b8b4e1131d0b8
1,859
exs
Elixir
test/domo/interactive_type_registration_test.exs
BasileNouvellet/Domo
43617a8e14880853058ea6c5b20944506ade9af0
[ "MIT" ]
null
null
null
test/domo/interactive_type_registration_test.exs
BasileNouvellet/Domo
43617a8e14880853058ea6c5b20944506ade9af0
[ "MIT" ]
null
null
null
test/domo/interactive_type_registration_test.exs
BasileNouvellet/Domo
43617a8e14880853058ea6c5b20944506ade9af0
[ "MIT" ]
null
null
null
defmodule Domo.InteractiveTypeRegistrationTest do use Domo.FileCase, async: false use Placebo alias Domo.CodeEvaluation alias Domo.TypeEnsurerFactory @moduletag in_mix_compile?: false setup tags do ResolverTestHelper.disable_raise_in_test_env() allow CodeEvaluation.in_mix_compile?(any()), meck_options: [:passthrough], return: tags.in_mix_compile? Code.compiler_options(ignore_module_conflict: true) on_exit(fn -> Code.compiler_options(ignore_module_conflict: false) ResolverTestHelper.enable_raise_in_test_env() end) :ok end describe "Interactive type registration in iex should" do setup do allow TypeEnsurerFactory.start_resolve_planner(any(), any(), any()), return: :ok allow TypeEnsurerFactory.register_in_memory_types(any(), any()), return: :ok allow TypeEnsurerFactory.get_dependants(any(), any()), return: {:ok, []} :ok end test "start ResolvePlanner" do defmodule ModuleMemoryTypes do use Domo.InteractiveTypesRegistration @type id :: integer() end assert_called TypeEnsurerFactory.start_resolve_planner(:in_memory, :in_memory, any()) end test "register types in iex" do {:module, _, bytecode, _} = defmodule ModuleMemoryTypes do use Domo.InteractiveTypesRegistration @type id :: integer() end assert_called TypeEnsurerFactory.register_in_memory_types(ModuleMemoryTypes, bytecode) end end @tag in_mix_compile?: true test "Interactive type registration in mix compile raises an error" do assert_raise CompileError, ~r/Domo.InteractiveTypesRegistration should be used only in interactive elixir./, fn -> defmodule ModuleMemoryTypes do use Domo.InteractiveTypesRegistration @type id :: integer() end end end end
29.046875
118
0.713825
9ed6c0fe855fca6bbbf91896dc99c501a02c0bb9
1,690
ex
Elixir
test/support/conn_case.ex
brownt23/crit19
c45c7b3ae580c193168d83144da0eeb9bc91c8a9
[ "MIT" ]
6
2019-07-16T19:31:23.000Z
2021-06-05T19:01:05.000Z
test/support/conn_case.ex
brownt23/crit19
c45c7b3ae580c193168d83144da0eeb9bc91c8a9
[ "MIT" ]
null
null
null
test/support/conn_case.ex
brownt23/crit19
c45c7b3ae580c193168d83144da0eeb9bc91c8a9
[ "MIT" ]
3
2020-02-24T23:38:27.000Z
2020-08-01T23:50:17.000Z
defmodule CritWeb.ConnCase do @moduledoc """ This module defines the test case to be used by tests that require setting up a connection. Such tests rely on `Phoenix.ConnTest` and also import other functionality to make it easier to build common data structures and query the data layer. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest alias CritWeb.Router.Helpers, as: Routes alias Crit.Factory import CritWeb.Templates.Purpose alias CritWeb.Controller.Common import CritWeb.ConnExtras import CritWeb.Assertions.Conn alias Crit.Audit.ToMemory.Server, as: AuditServer import CritWeb.Plugs.Accessors use Crit.TestConstants use Crit.Mock alias Crit.Extras.SqlT import FlowAssertions import Crit.Assertions.Form use Crit.Errors # The default endpoint for testing @endpoint CritWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Crit.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(Crit.Repo, {:shared, self()}) end audit_module = Crit.Audit.ToMemory.Server audit_pid = start_supervised!(audit_module) conn = Phoenix.ConnTest.build_conn() |> Plug.Test.init_test_session([]) |> CritWeb.Plugs.Accessors.assign_audit(audit_module, audit_pid) {:ok, conn: conn} end end
28.644068
70
0.707692
9ed6ff793eb74e20d7a8fe26ee324d3d5833f38b
233
ex
Elixir
farmbot_core/lib/farmbot_core/asset/box_led.ex
adamswsk/farmbot_os
d177d3b74888c1e7bcbf8f8595818708ee97f73b
[ "MIT" ]
843
2016-10-05T23:46:05.000Z
2022-03-14T04:31:55.000Z
farmbot_core/lib/farmbot_core/asset/box_led.ex
adamswsk/farmbot_os
d177d3b74888c1e7bcbf8f8595818708ee97f73b
[ "MIT" ]
455
2016-10-15T08:49:16.000Z
2022-03-15T12:23:04.000Z
farmbot_core/lib/farmbot_core/asset/box_led.ex
adamswsk/farmbot_os
d177d3b74888c1e7bcbf8f8595818708ee97f73b
[ "MIT" ]
261
2016-10-10T04:37:06.000Z
2022-03-13T21:07:38.000Z
defmodule FarmbotCore.Asset.BoxLed do @moduledoc """ """ defstruct [:id] defimpl String.Chars, for: FarmbotCore.Asset.BoxLed do def to_string(%FarmbotCore.Asset.BoxLed{id: id}) do "BoxLed #{id}" end end end
17.923077
56
0.665236
9ed70e193480fafec290d902965252a4728e85b4
383
ex
Elixir
lib/senti_web/views/user_view.ex
jeepers3327/senti
2e346759d8a8704f11364a835b6b9cd00a52c640
[ "MIT" ]
null
null
null
lib/senti_web/views/user_view.ex
jeepers3327/senti
2e346759d8a8704f11364a835b6b9cd00a52c640
[ "MIT" ]
null
null
null
lib/senti_web/views/user_view.ex
jeepers3327/senti
2e346759d8a8704f11364a835b6b9cd00a52c640
[ "MIT" ]
null
null
null
defmodule SentiWeb.UserView do use SentiWeb, :view alias SentiWeb.UserView def render("index.json", %{users: users}) do %{data: render_many(users, UserView, "user.json")} end def render("show.json", %{user: user}) do %{data: render_one(user, UserView, "user.json")} end def render("user.json", %{user: user}) do %{id: user.id, name: user.name} end end
22.529412
54
0.650131
9ed71c5fa44b936e9d5d92d75c6f67cba2eb7792
978
ex
Elixir
lib/code_runner/application.ex
harfangk/code_runner
7faa945230f16f64cb1d1f0e8977bc128ebb7ac8
[ "MIT" ]
2
2017-12-20T15:43:53.000Z
2018-07-12T09:47:25.000Z
lib/code_runner/application.ex
harfangk/code_runner
7faa945230f16f64cb1d1f0e8977bc128ebb7ac8
[ "MIT" ]
null
null
null
lib/code_runner/application.ex
harfangk/code_runner
7faa945230f16f64cb1d1f0e8977bc128ebb7ac8
[ "MIT" ]
null
null
null
defmodule CodeRunner.Application do @moduledoc false use Application def start(_type, _args) do import Supervisor.Spec, warn: false poolboy_config = [ name: {:local, pool_name()}, worker_module: CodeRunner.Worker, size: pool_size(), max_overflow: pool_overflow(), ] children = [ :poolboy.child_spec(pool_name(), poolboy_config, []) ] opts = [strategy: :one_for_one, name: CodeRunner.Supervisor] Supervisor.start_link(children, opts) end defp pool_name do case Application.fetch_env(:code_runner, :pool_name) do {:ok, pool_name} -> pool_name _ -> :code_runner_pool end end defp pool_size do case Application.fetch_env(:code_runner, :pool_size) do {:ok, pool_size} -> pool_size _ -> 50 end end defp pool_overflow do case Application.fetch_env(:code_runner, :pool_overflow) do {:ok, pool_overflow} -> pool_overflow _ -> 10 end end end
21.733333
64
0.655419
9ed72426178c38f8f9d7b1800c044b43ff911b84
3,392
ex
Elixir
lib/wobserver/util/metrics/prometheus.ex
szlend/wobserver
6c3ea1ef772ddb4a0b35956d155f33fc46f71a8c
[ "MIT" ]
984
2017-02-06T17:13:48.000Z
2022-03-18T22:46:55.000Z
lib/wobserver/util/metrics/prometheus.ex
szlend/wobserver
6c3ea1ef772ddb4a0b35956d155f33fc46f71a8c
[ "MIT" ]
52
2017-02-13T16:12:10.000Z
2021-04-08T22:31:28.000Z
lib/wobserver/util/metrics/prometheus.ex
szlend/wobserver
6c3ea1ef772ddb4a0b35956d155f33fc46f71a8c
[ "MIT" ]
74
2017-02-13T15:23:49.000Z
2021-07-30T07:43:27.000Z
defmodule Wobserver.Util.Metrics.Prometheus do @moduledoc ~S""" Prometheus formatter. Formats metrics in a for Prometheus readable way. See: [https://prometheus.io/docs/instrumenting/writing_exporters/](https://prometheus.io/docs/instrumenting/writing_exporters/) """ @behaviour Wobserver.Util.Metrics.Formatter @doc ~S""" Format a set of `data` with a `label` for a Prometheus. The `data` must be given as a `list` of tuples with the following format: `{value, labels}`, where `labels` is a keyword list with labels and their values. The following options can also be given: - `type`, the type of the metric. The following values are currently supported: `:gauge`, `:counter`. - `help`, a single line text description of the metric. """ @spec format_data( name :: String.t, data :: [{integer | float, keyword}], type :: :atom, help :: String.t ) :: String.t def format_data(name, data, type, help) do "#{format_help name, help}#{format_type name, type}#{format_values name, data}" end @doc ~S""" Combines formatted metrics together. Arguments: - `metrics`, a list of formatted metrics for one node. Example: iex> combine_metrics ["metric1{node="127.0.0.1"} 5\n", "metric2{node="127.0.0.1"} 5\n"] "metric1{node="127.0.0.1"} 5\n", "metric2{node="127.0.0.1"} 5\n" """ @spec combine_metrics( metrics :: list[String.t] ) :: String.t def combine_metrics(metrics), do: Enum.join(metrics) @doc ~S""" Merges formatted sets of metrics from different nodes together. The merge will filter out double declarations of help and type. Arguments: - `metrics`, a list of formatted sets metrics for multiple node. Example: iex> combine_metrics ["metric{node="192.168.0.6"} 5\n", "metric{node="192.168.0.5"} 5\n"] "metric{node="192.168.0.6"} 5\n", "metric{node="192.168.0.7"} 5\n" """ @spec merge_metrics( metrics :: list[String.t] ) :: String.t def merge_metrics(metrics) do {combined, _} = Enum.reduce(metrics, {"", []}, &filter/2) combined end # Helpers defp format_help(_name, nil), do: "" defp format_help(name, help) do "\# HELP #{name} #{help}\n" end defp format_type(_name, nil), do: "" defp format_type(name, type) do "\# TYPE #{name} #{type}\n" end defp format_labels(labels) do labels |> Enum.map(fn {label, value} -> "#{label}=\"#{value}\"" end) |> Enum.join(",") end defp format_values(name, data) do data |> Enum.map(fn {value, labels} -> "#{name}{#{format_labels labels}} #{value}\n" end) |> Enum.join end defp analyze_metrics(metrics) do help = ~r/^\# HELP ([a-zA-Z_]+\ )/m |> Regex.scan(metrics) |> Enum.map(fn [match | _] -> match end) type = ~r/^\# TYPE ([a-zA-Z_]+\ )/m |> Regex.scan(metrics) |> Enum.map(fn [match | _] -> match end) help ++ type end defp filter_line(line, filter) do filter |> Enum.find_value(false, &String.starts_with?(line, &1)) |> Kernel.! end defp filter(metric, {metrics, filter}) do filtered_metric = metric |> String.split("\n") |> Enum.filter(&filter_line(&1, filter)) |> Enum.join("\n") updated_filter = filtered_metric |> analyze_metrics() |> Kernel.++(filter) {metrics <> filtered_metric, updated_filter} end end
27.136
157
0.625295
9ed72c426f0d8f96df2f1478cc0c8af84eb2ade4
74
exs
Elixir
test/input_parser_test.exs
Frost/eh
52213603e94f15a58612fb8fd100d08de1230a5b
[ "Apache-2.0" ]
20
2015-03-18T21:59:04.000Z
2021-07-14T02:00:53.000Z
test/input_parser_test.exs
Frost/eh
52213603e94f15a58612fb8fd100d08de1230a5b
[ "Apache-2.0" ]
1
2015-04-20T06:06:16.000Z
2015-04-20T06:28:58.000Z
test/input_parser_test.exs
Frost/eh
52213603e94f15a58612fb8fd100d08de1230a5b
[ "Apache-2.0" ]
4
2015-04-19T21:12:11.000Z
2018-05-10T17:08:37.000Z
defmodule InputParserTest do use ExUnit.Case doctest InputParser end
12.333333
28
0.810811
9ed756355759180c9c31c4a1e472d26929768eab
5,097
exs
Elixir
test/filter/filter_interaction_test.exs
MrFlorius/ash
247abbb8333d252da5440a58ddf4f1b7f184342f
[ "MIT" ]
null
null
null
test/filter/filter_interaction_test.exs
MrFlorius/ash
247abbb8333d252da5440a58ddf4f1b7f184342f
[ "MIT" ]
null
null
null
test/filter/filter_interaction_test.exs
MrFlorius/ash
247abbb8333d252da5440a58ddf4f1b7f184342f
[ "MIT" ]
null
null
null
defmodule Ash.Test.Filter.FilterInteractionTest do use ExUnit.Case, async: false import Ash.Changeset import ExUnit.CaptureLog alias Ash.DataLayer.Mnesia require Ash.Query defmodule Profile do @moduledoc false use Ash.Resource, data_layer: Ash.DataLayer.Ets ets do private?(true) end actions do read(:read) create(:create) update(:update) end attributes do uuid_primary_key :id attribute(:bio, :string) end relationships do belongs_to(:user, Ash.Test.Filter.FilterInteractionTest.User) end end defmodule User do @moduledoc false use Ash.Resource, data_layer: Ash.DataLayer.Ets ets do private?(true) end actions do read(:read) create(:create) update(:update) end attributes do uuid_primary_key :id attribute(:name, :string) attribute(:allow_second_author, :boolean) end relationships do has_many(:posts, Ash.Test.Filter.FilterInteractionTest.Post, destination_field: :author_id) has_many(:second_posts, Ash.Test.Filter.FilterInteractionTest.Post, destination_field: :author_id ) has_one(:profile, Profile, destination_field: :user_id) end end defmodule PostLink do @moduledoc false use Ash.Resource, data_layer: Ash.DataLayer.Mnesia actions do read(:read) create(:create) update(:update) end relationships do belongs_to(:source_post, Ash.Test.Filter.FilterInteractionTest.Post, primary_key?: true, required?: true ) belongs_to(:destination_post, Ash.Test.Filter.FilterInteractionTest.Post, primary_key?: true, required?: true ) end end defmodule Post do @moduledoc false use Ash.Resource, data_layer: Ash.DataLayer.Mnesia actions do read(:read) create(:create) update(:update) destroy(:destroy) end attributes do uuid_primary_key :id attribute(:title, :string) attribute(:contents, :string) attribute(:points, :integer) end relationships do belongs_to(:author, User, destination_field: :id, source_field: :author_id ) many_to_many(:related_posts, __MODULE__, through: PostLink, source_field_on_join_table: :source_post_id, destination_field_on_join_table: :destination_post_id ) end end defmodule Api do @moduledoc false use Ash.Api resources do resource(Post) resource(User) resource(Profile) resource(PostLink) end end setup do capture_log(fn -> Mnesia.start(Api) end) on_exit(fn -> capture_log(fn -> :mnesia.stop() :mnesia.delete_schema([node()]) end) end) end test "mnesia data layer sanity test" do post = Post |> new(%{title: "best"}) |> Api.create!() assert [^post] = Api.read!(Post) post |> new(%{title: "worst"}) |> Api.update!() new_post = %{post | title: "worst"} assert [^new_post] = Api.read!(Post) Api.destroy!(post) assert [] = Api.read!(Post) end describe "cross data layer filtering" do test "it properly filters with a simple filter" do author = User |> new(%{name: "best author"}) |> Api.create!() post1 = Post |> new(%{title: "best"}) |> replace_relationship(:author, author) |> Api.create!() post1_id = post1.id Post |> new(%{title: "worst"}) |> Api.create!() query = Post |> Ash.Query.filter(author.name == "best author") assert [%{id: ^post1_id}] = Api.read!(query) end test "parallelizable filtering of related resources with a data layer that cannot join" do post2 = Post |> new(%{title: "two"}) |> Api.create!() Post |> new(%{title: "three"}) |> Api.create!() post1 = Post |> new(%{title: "one"}) |> replace_relationship(:related_posts, [post2]) |> Api.create!() query = Post |> Ash.Query.filter(related_posts.title == "two") post1_id = post1.id assert [%{id: ^post1_id}] = Api.read!(query) end test "parallelizable filter with filtered loads" do post2 = Post |> new(%{title: "two"}) |> Api.create!() post3 = Post |> new(%{title: "three"}) |> Api.create!() post1 = Post |> new(%{title: "one"}) |> replace_relationship(:related_posts, [post2, post3]) |> Api.create!() posts_query = Post |> Ash.Query.filter(title == "three") query = Post |> Ash.Query.filter(related_posts.title == "two") |> Ash.Query.load(related_posts: posts_query) post1_id = post1.id post3_id = post3.id assert [%{id: ^post1_id, related_posts: [%{id: ^post3_id}]}] = Api.read!(query) end end end
20.066929
97
0.5825
9ed76719079c5c1197f2620c233381e48052bbdf
896
exs
Elixir
Task_4/flights/test/flights_stm_test.exs
andfoy/cpd-exercises
f36ac16c74bb980d7edd6aaf5661a6d4d4b09489
[ "MIT" ]
null
null
null
Task_4/flights/test/flights_stm_test.exs
andfoy/cpd-exercises
f36ac16c74bb980d7edd6aaf5661a6d4d4b09489
[ "MIT" ]
null
null
null
Task_4/flights/test/flights_stm_test.exs
andfoy/cpd-exercises
f36ac16c74bb980d7edd6aaf5661a6d4d4b09489
[ "MIT" ]
null
null
null
defmodule FlightsStmTest do use ExUnit.Case doctest FlightsStm test "search a specific flight" do assert length(FlightsStm.search_flights("BOG", "MAD")) == 2 end test "reserve a flight" do rand_flight = Enum.random(:mnesia.dirty_all_keys(Flights)) {_, {:ok, [_, _, _, _, num]}} = FlightsStm.reserve_flight( rand_flight, "2018-05-02") assert num == 1 end test "fully reserve a flight" do rand_flight = Enum.random(:mnesia.dirty_all_keys(Flights)) for _ <- 1..120, do: FlightsStm.reserve_flight( rand_flight, "2018-05-02") {_, response} = FlightsStm.reserve_flight( rand_flight, "2018-05-02") assert match?({:flight_fully_occupied, _}, response) end test "reserve a flight that does not exist" do {_, response} = FlightsStm.reserve_flight("bla-bla-bla", "2018-05-02") assert match?({:noexists, _}, response) end end
29.866667
74
0.674107
9ed7ac639323db61ae142986c664bcfbedc1085b
1,584
ex
Elixir
clients/webmaster/lib/google_api/webmaster/v3/model/sitemaps_list_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/webmaster/lib/google_api/webmaster/v3/model/sitemaps_list_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/webmaster/lib/google_api/webmaster/v3/model/sitemaps_list_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Webmaster.V3.Model.SitemapsListResponse do @moduledoc """ List of sitemaps. ## Attributes * `sitemap` (*type:* `list(GoogleApi.Webmaster.V3.Model.WmxSitemap.t)`, *default:* `nil`) - Contains detailed information about a specific URL submitted as a sitemap. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :sitemap => list(GoogleApi.Webmaster.V3.Model.WmxSitemap.t()) | nil } field(:sitemap, as: GoogleApi.Webmaster.V3.Model.WmxSitemap, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Webmaster.V3.Model.SitemapsListResponse do def decode(value, options) do GoogleApi.Webmaster.V3.Model.SitemapsListResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Webmaster.V3.Model.SitemapsListResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.702128
170
0.746843
9ed7e1e7803f34e494d447b180c91ef492a0d1ee
1,018
ex
Elixir
test/support/conn_case.ex
ryancharris/who
187a207576240d07e338a1707e5a8eba2e2852d5
[ "MIT" ]
1
2017-08-08T13:22:23.000Z
2017-08-08T13:22:23.000Z
test/support/conn_case.ex
ryancharris/who
187a207576240d07e338a1707e5a8eba2e2852d5
[ "MIT" ]
null
null
null
test/support/conn_case.ex
ryancharris/who
187a207576240d07e338a1707e5a8eba2e2852d5
[ "MIT" ]
null
null
null
defmodule WhoWeb.ConnCase do @moduledoc """ This module defines the test case to be used by tests that require setting up a connection. Such tests rely on `Phoenix.ConnTest` and also import other functionality to make it easier to build common datastructures and query the data layer. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest import WhoWeb.Router.Helpers # The default endpoint for testing @endpoint WhoWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Who.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(Who.Repo, {:shared, self()}) end {:ok, conn: Phoenix.ConnTest.build_conn()} end end
26.102564
65
0.714145
9ed7ff8cba5ef434f9bf6e7e5d549447f93ad0a9
1,193
exs
Elixir
mix.exs
devstopfix/excheck
c8cbf457e9bf7c13a0a4b70c60c8e02495ff53a1
[ "MIT" ]
null
null
null
mix.exs
devstopfix/excheck
c8cbf457e9bf7c13a0a4b70c60c8e02495ff53a1
[ "MIT" ]
null
null
null
mix.exs
devstopfix/excheck
c8cbf457e9bf7c13a0a4b70c60c8e02495ff53a1
[ "MIT" ]
null
null
null
defmodule ExCheck.Mixfile do use Mix.Project def project do [ app: :excheck, name: "ExCheck", source_url: "https://github.com/devstopfix/excheck", homepage_url: "https://github.com/parroty/ExCheck.git", version: "0.7.6", elixir: "~> 1.5", deps: deps(), description: description(), package: package() # test_coverage: [tool: ExCoveralls], # preferred_cli_env: ["coveralls": :test, "coveralls.detail": :test] ] end def application do [ applications: [:triq], mod: {ExCheck, []} ] end def deps do [ # {:excoveralls, "~> 0.5", only: :test}, {:triq, "~> 1.3", only: [:dev, :test]}, {:ex_doc, "~> 0.12", only: :dev}, {:inch_ex, only: :docs} ] end defp description do """ Property-based testing library for Elixir (QuickCheck style). """ end defp package do [ maintainers: ["parroty"], licenses: ["MIT"], links: %{ "GitHub" => "https://github.com/parroty/excheck", "Fork" => "https://github.com/devstopfix/excheck", "CI" => "https://travis-ci.org/devstopfix/excheck" } ] end end
22.092593
74
0.545683
9ed806323358ceaff73104a7de6743d8b4754abb
310
ex
Elixir
lib/uro_web/pow/routes.ex
V-Sekai/uro
0b23da65d5c7e459efcd6b2c3d9bdf91c533b737
[ "MIT" ]
1
2022-01-11T04:05:39.000Z
2022-01-11T04:05:39.000Z
lib/uro_web/pow/routes.ex
V-Sekai/uro
0b23da65d5c7e459efcd6b2c3d9bdf91c533b737
[ "MIT" ]
35
2021-02-10T08:18:57.000Z
2021-05-06T17:19:50.000Z
lib/uro_web/pow/routes.ex
V-Sekai/uro
0b23da65d5c7e459efcd6b2c3d9bdf91c533b737
[ "MIT" ]
null
null
null
defmodule UroWeb.Pow.Routes do use Pow.Phoenix.Routes alias UroWeb.Router.Helpers, as: Routes def session_path(conn, verb, query_params \\ []), do: Routes.signin_path(conn, verb, query_params) def registration_path(conn, verb, query_params \\ []), do: Routes.signup_path(conn, verb, query_params) end
38.75
105
0.751613
9ed822e3fa5afa1d064bd4e94906af3d89a91b2c
544
exs
Elixir
benchmark/mix.exs
braverhealth/grpc
eff8a8828d27ddd7f63a3c1dd5aae86246df215e
[ "Apache-2.0" ]
561
2019-03-18T09:10:57.000Z
2022-03-27T17:34:59.000Z
benchmark/mix.exs
braverhealth/grpc
eff8a8828d27ddd7f63a3c1dd5aae86246df215e
[ "Apache-2.0" ]
94
2019-03-20T09:34:38.000Z
2022-02-27T20:44:04.000Z
benchmark/mix.exs
braverhealth/grpc
eff8a8828d27ddd7f63a3c1dd5aae86246df215e
[ "Apache-2.0" ]
112
2019-03-25T03:27:26.000Z
2022-03-21T12:43:59.000Z
defmodule Benchmark.MixProject do use Mix.Project def project do [ app: :benchmark, 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 [ {:grpc, path: ".."}, {:protobuf, github: "tony612/protobuf-elixir", override: true} ] end end
18.758621
68
0.582721