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
739e63f76381e9036adb9f1fcd959575cdf76ae1
275
ex
Elixir
lib/rostrum2_web/views/layout_view.ex
ashton314/rostrum2
e392190b27f7dae4cc2de3668c1f4fea5cca63c1
[ "MIT" ]
null
null
null
lib/rostrum2_web/views/layout_view.ex
ashton314/rostrum2
e392190b27f7dae4cc2de3668c1f4fea5cca63c1
[ "MIT" ]
3
2021-11-25T05:44:03.000Z
2021-11-26T06:33:53.000Z
lib/rostrum2_web/views/layout_view.ex
ashton314/rostrum2
e392190b27f7dae4cc2de3668c1f4fea5cca63c1
[ "MIT" ]
null
null
null
defmodule RostrumWeb.LayoutView do use RostrumWeb, :view # Phoenix LiveDashboard is available only in development by default, # so we instruct Elixir to not warn if the dashboard route is missing. @compile {:no_warn_undefined, {Routes, :live_dashboard_path, 2}} end
34.375
72
0.774545
739e6b389c8d2da69f1133fc589eb688477e7c92
1,278
ex
Elixir
lib/vaulter/vaulter.ex
harmon25/vaulter
f36a40e0ff6d610d5ed96251cd9fdef2a8ab899b
[ "MIT" ]
null
null
null
lib/vaulter/vaulter.ex
harmon25/vaulter
f36a40e0ff6d610d5ed96251cd9fdef2a8ab899b
[ "MIT" ]
null
null
null
lib/vaulter/vaulter.ex
harmon25/vaulter
f36a40e0ff6d610d5ed96251cd9fdef2a8ab899b
[ "MIT" ]
null
null
null
defmodule Vaulter do alias Vaulter.Util alias Vaulter.Client def auth(username, password) do Util.genAuthRequest(:post,"auth/userpass/login/" <> username, %{password: password}) |> Client.sendRequest |> saveToken end defp saveToken({:ok, respBody}) do if Map.has_key?(respBody, "auth") do authInfo = Map.get(respBody, "auth") if Map.has_key?(authInfo, "client_token") do token = Map.get(authInfo, "client_token") System.put_env("VAULTER_TOKEN", token) {:ok, token } end end end defp saveToken({:err, _}) do {:err, "Login Failed..."} end def get(path, params) do Util.genRequest(:get, path, params) |> Client.sendRequest end def get(path) do Util.genRequest(:get, path) |> Client.sendRequest end def put(path, params) do Util.genRequest(:put, path, params) |> Client.sendRequest end def put(path) do Util.genRequest(:put, path) |> Client.sendRequest end def post(path, params) do Util.genRequest(:post, path, params) |> Client.sendRequest end def post(path) do Util.genRequest(:post, path) |> Client.sendRequest end def del(path, params) do Util.genRequest(:del, path, params) |> Client.sendRequest end def del(path) do Util.genRequest(:del, path) |> Client.sendRequest end end
19.363636
86
0.683099
739e8474ff9b4c9e7a5c18218af47fba3f8a9251
12,107
exs
Elixir
test/groupher_server/cms/article_community/job_test.exs
coderplanets/coderplanets_server
3663e56340d6d050e974c91f7e499d8424fc25e9
[ "Apache-2.0" ]
240
2018-11-06T09:36:54.000Z
2022-02-20T07:12:36.000Z
test/groupher_server/cms/article_community/job_test.exs
coderplanets/coderplanets_server
3663e56340d6d050e974c91f7e499d8424fc25e9
[ "Apache-2.0" ]
363
2018-07-11T03:38:14.000Z
2021-12-14T01:42:40.000Z
test/groupher_server/cms/article_community/job_test.exs
mydearxym/mastani_server
f24034a4a5449200165cf4a547964a0961793eab
[ "Apache-2.0" ]
22
2019-01-27T11:47:56.000Z
2021-02-28T13:17:52.000Z
defmodule GroupherServer.Test.CMS.ArticleCommunity.Job do use GroupherServer.TestTools alias Helper.ORM alias GroupherServer.CMS alias CMS.Model.Job setup do {:ok, user} = db_insert(:user) {:ok, user2} = db_insert(:user) {:ok, job} = db_insert(:job) {:ok, community} = db_insert(:community) {:ok, community2} = db_insert(:community) {:ok, community3} = db_insert(:community) job_attrs = mock_attrs(:job, %{community_id: community.id}) {:ok, ~m(user user2 community community2 community3 job job_attrs)a} end describe "[article mirror/move]" do test "created job has origial community info", ~m(user community job_attrs)a do {:ok, job} = CMS.create_article(community, :job, job_attrs, user) {:ok, job} = ORM.find(Job, job.id, preload: :original_community) assert job.original_community_id == community.id end test "job can be move to other community", ~m(user community community2 job_attrs)a do {:ok, job} = CMS.create_article(community, :job, job_attrs, user) assert job.original_community_id == community.id {:ok, _} = CMS.move_article(:job, job.id, community2.id) {:ok, job} = ORM.find(Job, job.id, preload: [:original_community, :communities]) assert job.original_community.id == community2.id assert exist_in?(community2, job.communities) end test "tags should be clean after job move to other community", ~m(user community community2 job_attrs)a do article_tag_attrs = mock_attrs(:article_tag) article_tag_attrs2 = mock_attrs(:article_tag) {:ok, job} = CMS.create_article(community, :job, job_attrs, user) {:ok, article_tag} = CMS.create_article_tag(community, :job, article_tag_attrs, user) {:ok, article_tag2} = CMS.create_article_tag(community, :job, article_tag_attrs2, user) {:ok, _job} = CMS.set_article_tag(:job, job.id, article_tag.id) {:ok, job} = CMS.set_article_tag(:job, job.id, article_tag2.id) assert job.article_tags |> length == 2 assert job.original_community_id == community.id {:ok, _} = CMS.move_article(:job, job.id, community2.id) {:ok, job} = ORM.find(Job, job.id, preload: [:original_community, :communities, :article_tags]) assert job.article_tags |> length == 0 assert job.original_community.id == community2.id assert exist_in?(community2, job.communities) end test "job move to other community with new tag", ~m(user community community2 job_attrs)a do article_tag_attrs0 = mock_attrs(:article_tag) article_tag_attrs = mock_attrs(:article_tag) article_tag_attrs2 = mock_attrs(:article_tag) {:ok, article_tag0} = CMS.create_article_tag(community, :job, article_tag_attrs0, user) {:ok, article_tag} = CMS.create_article_tag(community2, :job, article_tag_attrs, user) {:ok, article_tag2} = CMS.create_article_tag(community2, :job, article_tag_attrs2, user) {:ok, job} = CMS.create_article(community, :job, job_attrs, user) {:ok, _} = CMS.set_article_tag(:job, job.id, article_tag0.id) {:ok, _} = CMS.set_article_tag(:job, job.id, article_tag.id) {:ok, _} = CMS.set_article_tag(:job, job.id, article_tag2.id) {:ok, job} = ORM.find(Job, job.id, preload: [:article_tags]) assert job.article_tags |> length == 3 {:ok, _} = CMS.move_article(:job, job.id, community2.id, [article_tag.id, article_tag2.id]) {:ok, job} = ORM.find(Job, job.id, preload: [:original_community, :communities, :article_tags]) assert job.original_community.id == community2.id assert job.article_tags |> length == 2 assert not exist_in?(article_tag0, job.article_tags) assert exist_in?(article_tag, job.article_tags) assert exist_in?(article_tag2, job.article_tags) end test "job can be mirror to other community", ~m(user community community2 job_attrs)a do {:ok, job} = CMS.create_article(community, :job, job_attrs, user) {:ok, job} = ORM.find(Job, job.id, preload: :communities) assert job.communities |> length == 1 assert exist_in?(community, job.communities) {:ok, _} = CMS.mirror_article(:job, job.id, community2.id) {:ok, job} = ORM.find(Job, job.id, preload: :communities) assert job.communities |> length == 2 assert exist_in?(community, job.communities) assert exist_in?(community2, job.communities) end test "job can be mirror to other community with tags", ~m(user community community2 job_attrs)a do article_tag_attrs = mock_attrs(:article_tag) article_tag_attrs2 = mock_attrs(:article_tag) {:ok, article_tag} = CMS.create_article_tag(community2, :job, article_tag_attrs, user) {:ok, article_tag2} = CMS.create_article_tag(community2, :job, article_tag_attrs2, user) {:ok, job} = CMS.create_article(community, :job, job_attrs, user) {:ok, _} = CMS.mirror_article(:job, job.id, community2.id, [article_tag.id, article_tag2.id]) {:ok, job} = ORM.find(Job, job.id, preload: :article_tags) assert job.article_tags |> length == 2 assert exist_in?(article_tag, job.article_tags) assert exist_in?(article_tag2, job.article_tags) end test "job can be unmirror from community", ~m(user community community2 community3 job_attrs)a do {:ok, job} = CMS.create_article(community, :job, job_attrs, user) {:ok, _} = CMS.mirror_article(:job, job.id, community2.id) {:ok, _} = CMS.mirror_article(:job, job.id, community3.id) {:ok, job} = ORM.find(Job, job.id, preload: :communities) assert job.communities |> length == 3 {:ok, _} = CMS.unmirror_article(:job, job.id, community3.id) {:ok, job} = ORM.find(Job, job.id, preload: :communities) assert job.communities |> length == 2 assert not exist_in?(community3, job.communities) end test "job can be unmirror from community with tags", ~m(user community community2 community3 job_attrs)a do article_tag_attrs2 = mock_attrs(:article_tag) article_tag_attrs3 = mock_attrs(:article_tag) {:ok, article_tag2} = CMS.create_article_tag(community2, :job, article_tag_attrs2, user) {:ok, article_tag3} = CMS.create_article_tag(community3, :job, article_tag_attrs3, user) {:ok, job} = CMS.create_article(community, :job, job_attrs, user) {:ok, _} = CMS.mirror_article(:job, job.id, community2.id, [article_tag2.id]) {:ok, _} = CMS.mirror_article(:job, job.id, community3.id, [article_tag3.id]) {:ok, _} = CMS.unmirror_article(:job, job.id, community3.id) {:ok, job} = ORM.find(Job, job.id, preload: :article_tags) assert exist_in?(article_tag2, job.article_tags) assert not exist_in?(article_tag3, job.article_tags) end test "job can not unmirror from original community", ~m(user community community2 community3 job_attrs)a do {:ok, job} = CMS.create_article(community, :job, job_attrs, user) {:ok, _} = CMS.mirror_article(:job, job.id, community2.id) {:ok, _} = CMS.mirror_article(:job, job.id, community3.id) {:ok, job} = ORM.find(Job, job.id, preload: :communities) assert job.communities |> length == 3 {:error, reason} = CMS.unmirror_article(:job, job.id, community.id) assert reason |> is_error?(:mirror_article) end test "job can be mirror to home", ~m(community job_attrs user)a do {:ok, home_community} = db_insert(:community, %{raw: "home"}) {:ok, job} = CMS.create_article(community, :job, job_attrs, user) assert job.original_community_id == community.id {:ok, _} = CMS.mirror_to_home(:job, job.id) {:ok, job} = ORM.find(Job, job.id, preload: [:original_community, :communities]) assert job.original_community_id == community.id assert job.communities |> length == 2 assert exist_in?(community, job.communities) assert exist_in?(home_community, job.communities) filter = %{page: 1, size: 10, community: community.raw} {:ok, paged_articles} = CMS.paged_articles(:job, filter) assert exist_in?(job, paged_articles.entries) assert paged_articles.total_count === 1 filter = %{page: 1, size: 10, community: home_community.raw} {:ok, paged_articles} = CMS.paged_articles(:job, filter) assert exist_in?(job, paged_articles.entries) assert paged_articles.total_count === 1 end test "job can be mirror to home with tags", ~m(community job_attrs user)a do {:ok, home_community} = db_insert(:community, %{raw: "home"}) article_tag_attrs0 = mock_attrs(:article_tag) article_tag_attrs = mock_attrs(:article_tag) {:ok, article_tag0} = CMS.create_article_tag(home_community, :job, article_tag_attrs0, user) {:ok, article_tag} = CMS.create_article_tag(home_community, :job, article_tag_attrs, user) {:ok, job} = CMS.create_article(community, :job, job_attrs, user) assert job.original_community_id == community.id {:ok, _} = CMS.mirror_to_home(:job, job.id, [article_tag0.id, article_tag.id]) {:ok, job} = ORM.find(Job, job.id, preload: [:original_community, :communities, :article_tags]) assert job.original_community_id == community.id assert job.communities |> length == 2 assert exist_in?(community, job.communities) assert exist_in?(home_community, job.communities) assert job.article_tags |> length == 2 assert exist_in?(article_tag0, job.article_tags) assert exist_in?(article_tag, job.article_tags) filter = %{page: 1, size: 10, community: community.raw} {:ok, paged_articles} = CMS.paged_articles(:job, filter) assert exist_in?(job, paged_articles.entries) assert paged_articles.total_count === 1 filter = %{page: 1, size: 10, community: home_community.raw} {:ok, paged_articles} = CMS.paged_articles(:job, filter) assert exist_in?(job, paged_articles.entries) assert paged_articles.total_count === 1 end test "job can be move to blackhole", ~m(community job_attrs user)a do {:ok, blackhole_community} = db_insert(:community, %{raw: "blackhole"}) {:ok, job} = CMS.create_article(community, :job, job_attrs, user) assert job.original_community_id == community.id {:ok, _} = CMS.move_to_blackhole(:job, job.id) {:ok, job} = ORM.find(Job, job.id, preload: [:original_community, :communities]) assert job.original_community.id == blackhole_community.id assert job.communities |> length == 1 assert exist_in?(blackhole_community, job.communities) filter = %{page: 1, size: 10, community: blackhole_community.raw} {:ok, paged_articles} = CMS.paged_articles(:job, filter) assert exist_in?(job, paged_articles.entries) assert paged_articles.total_count === 1 end test "job can be move to blackhole with tags", ~m(community job_attrs user)a do {:ok, blackhole_community} = db_insert(:community, %{raw: "blackhole"}) article_tag_attrs0 = mock_attrs(:article_tag) article_tag_attrs = mock_attrs(:article_tag) {:ok, article_tag0} = CMS.create_article_tag(blackhole_community, :job, article_tag_attrs0, user) {:ok, article_tag} = CMS.create_article_tag(blackhole_community, :job, article_tag_attrs, user) {:ok, job} = CMS.create_article(community, :job, job_attrs, user) {:ok, _} = CMS.set_article_tag(:job, job.id, article_tag0.id) assert job.original_community_id == community.id {:ok, _} = CMS.move_to_blackhole(:job, job.id, [article_tag.id]) {:ok, job} = ORM.find(Job, job.id, preload: [:original_community, :communities, :article_tags]) assert job.original_community.id == blackhole_community.id assert job.communities |> length == 1 assert job.article_tags |> length == 1 assert exist_in?(blackhole_community, job.communities) assert exist_in?(article_tag, job.article_tags) end end end
40.356667
98
0.675312
739ea361e7906e5371cba913f7da20e5c396215f
3,436
exs
Elixir
mix.exs
harmon25/webengine_kiosk
89325351f035ecd15933f93785a061182734c602
[ "Apache-2.0" ]
null
null
null
mix.exs
harmon25/webengine_kiosk
89325351f035ecd15933f93785a061182734c602
[ "Apache-2.0" ]
null
null
null
mix.exs
harmon25/webengine_kiosk
89325351f035ecd15933f93785a061182734c602
[ "Apache-2.0" ]
null
null
null
defmodule WebengineKiosk.MixProject do use Mix.Project @version "0.2.5" @source_url "https://github.com/fhunleth/webengine_kiosk" def project do [ app: :webengine_kiosk, version: @version, elixir: "~> 1.6", description: description(), package: package(), source_url: @source_url, compilers: [:elixir_make | Mix.compilers()], make_targets: ["all"], make_clean: ["clean"], make_error_message: make_help(), docs: docs(), dialyzer: [ flags: [:unmatched_returns, :error_handling, :race_conditions, :underspecs] ], deps: deps() ] end def application do [ extra_applications: [:logger], mod: {WebengineKiosk.Application, []} ] end defp description do "Display and control web pages on a local fullscreen browser" end defp package do [ files: [ "lib", "src", "assets", "test", "mix.exs", "README.md", "LICENSE", "CHANGELOG.md", "Makefile" ], licenses: ["Apache-2.0", "LGPL-3.0-only"], links: %{"GitHub" => @source_url} ] end defp deps do [ {:system_registry, "~> 0.8", optional: true}, {:elixir_make, "~> 0.6", runtime: false}, {:ex_doc, "~> 0.19", only: [:dev, :test], runtime: false}, {:dialyxir, "~> 1.0.0-rc.6", only: :dev, runtime: false} ] end defp docs do [ extras: ["README.md"], main: "readme", source_ref: "v#{@version}", source_url: @source_url ] end defp using_nerves? do System.get_env("CROSSCOMPILE") != nil end defp make_help do """ Please look above this message for the compiler error before filing an issue. The first error after the text `==> webengine_kiosk` is usually the most helpful. The webengine_kiosk library requires the Qt framework to build. """ <> make_help_os(:os.type(), using_nerves?()) end defp make_help_os({:unix, :darwin}, _nerves) do """ To install Qt using Homebrew, run `brew install qt`. Homebrew doesn't add qt to your path, so you'll need to add it or set the QMAKE environment variable. For example, `export QMAKE=/usr/local/opt/qt/bin/qmake`. """ end defp make_help_os({:unix, _}, true) do """ Please install Qt using your system's package manager or via source. Since this is a Nerves-based project, only `qmake` is needed. For Ubuntu, this looks like: sudo apt install qt5-qmake Another option is to set the `QMAKE` environment variable to the path to the qmake binary: QMAKE=~/Qt/5.11.1/gcc_64/bin/qmake """ end defp make_help_os({:unix, _}, false) do """ Please install Qt using your system's package manager or via source. Be sure to install the development headers and libraries for Qt Webengine. For Ubuntu, this looks like: sudo apt install qt5-default qtwebengine5-dev qtmultimedia5-dev """ end defp make_help_os({other, _}, _nerves) do """ I'm not familiar with installing Qt5 on #{inspect(other)}. Please install Qt5 using your platform's package manager or from source and consider making an issue or a PR to #{@source_url} to benefit other users. If you're getting an error that `qmake` isn't found, try setting the `QMAKE` environment variable to the path to `qmake`. """ end end
25.641791
83
0.620489
739ec874eb643afa613b9027e1a85f702d81eb95
372
exs
Elixir
priv/repo/migrations/20210719050501_add_schedule_to_campaign.exs
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
28
2021-10-11T01:53:53.000Z
2022-03-24T17:45:55.000Z
priv/repo/migrations/20210719050501_add_schedule_to_campaign.exs
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
20
2021-10-21T08:12:31.000Z
2022-03-31T13:35:53.000Z
priv/repo/migrations/20210719050501_add_schedule_to_campaign.exs
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
null
null
null
defmodule BikeBrigade.Repo.Migrations.AddScheduleToCampaign do use Ecto.Migration def change do create table(:scheduled_messages) do add :campaign_id, references(:campaigns) add :send_at, :utc_datetime timestamps() end create unique_index(:scheduled_messages, [:campaign_id]) create index(:scheduled_messages, [:send_at]) end end
24.8
62
0.731183
739ecd8b4850b11cda21ce33529299c82dbe0ebe
1,135
exs
Elixir
mix.exs
grrrisu/meeple
428762a58a94306a6643b09c08d72fb2883a0309
[ "MIT" ]
null
null
null
mix.exs
grrrisu/meeple
428762a58a94306a6643b09c08d72fb2883a0309
[ "MIT" ]
13
2021-12-24T23:44:10.000Z
2022-03-04T20:56:28.000Z
mix.exs
grrrisu/meeple
428762a58a94306a6643b09c08d72fb2883a0309
[ "MIT" ]
null
null
null
defmodule Meeple.Umbrella.MixProject do use Mix.Project def project do [ apps_path: "apps", version: "0.1.0", start_permanent: Mix.env() == :prod, deps: deps(), aliases: aliases() ] end # Dependencies can be Hex packages: # # {:mydep, "~> 0.3.0"} # # Or git/path repositories: # # {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"} # # Type "mix help deps" for more examples and options. # # Dependencies listed here are available only for this project # and cannot be accessed from applications inside the apps/ folder. defp deps do [] end # Aliases are shortcuts or tasks specific to the current project. # For example, to install project dependencies and perform other setup tasks, run: # # $ mix setup # # See the documentation for `Mix` for more info on aliases. # # Aliases listed here are available only for this project # and cannot be accessed from applications inside the apps/ folder. defp aliases do [ # run `mix setup` in all child apps setup: ["cmd mix setup"] ] end end
24.673913
84
0.64141
739ed95a495545b7b2601b4f1e4865f7a540345c
12,153
ex
Elixir
lib/nsq/consumer.ex
wingyplus/elixir_nsq
a3d6af736efb508c2e3dfbc8d1cab3c624f57c53
[ "MIT" ]
null
null
null
lib/nsq/consumer.ex
wingyplus/elixir_nsq
a3d6af736efb508c2e3dfbc8d1cab3c624f57c53
[ "MIT" ]
9
2020-04-05T15:39:46.000Z
2020-04-06T17:29:00.000Z
lib/nsq/consumer.ex
wingyplus/elixir_nsq
a3d6af736efb508c2e3dfbc8d1cab3c624f57c53
[ "MIT" ]
null
null
null
defmodule NSQ.Consumer do @moduledoc """ A consumer is a process that creates connections to NSQD to receive messages for a specific topic and channel. It has three primary functions: 1. Provide a simple interface for a user to setup and configure message handlers. 2. Balance RDY across all available connections. 3. Add/remove connections as they are discovered. ## Simple Interface In standard practice, the only function a user should need to know about is `NSQ.Consumer.Supervisor.start_link/3`. It takes a topic, a channel, and an NSQ.Config struct, which has possible values defined and explained in nsq/config.ex. {:ok, consumer} = NSQ.Consumer.Supervisor.start_link("my-topic", "my-channel", %NSQ.Config{ nsqlookupds: ["127.0.0.1:6751", "127.0.0.1:6761"], message_handler: fn(body, msg) -> # handle them message :ok end }) ### Message handler return values The return value of the message handler determines how we will respond to NSQ. #### :ok The message was handled and should not be requeued. This sends a FIN command to NSQD. #### :req This message should be requeued. With no delay specified, it will calculate delay exponentially based on the number of attempts. Refer to Message.calculate_delay for the exact formula. #### {:req, delay} This message should be requeued. Use the delay specified. A positive integer is expected. #### {:req, delay, backoff} This message should be requeued. Use the delay specified. If `backoff` is truthy, the consumer will temporarily set RDY to 0 in order to stop receiving messages. It will use a standard strategy to resume from backoff mode. This type of return value is only meant for exceptional cases, such as internal network partitions, where stopping message handling briefly could be beneficial. Only use this return value if you know what you're doing. A message handler that throws an unhandled exception will automatically requeue and enter backoff mode. ### NSQ.Message.touch(msg) NSQ.Config has a property called msg_timeout, which configures the NSQD server to wait that long before assuming the message failed and requeueing it. If you expect your message handler to take longer than that, you can call `NSQ.Message.touch(msg)` from the message handler to reset the server-side timer. ### NSQ.Consumer.change_max_in_flight(consumer, max_in_flight) If you'd like to manually change the max in flight of a consumer, use this function. It will cause the consumer's connections to rebalance to the new value. If the new `max_in_flight` is smaller than the current messages in flight, it must wait for the existing handlers to finish or requeue before it can fully rebalance. """ # ------------------------------------------------------- # # Directives # # ------------------------------------------------------- # use GenServer require Logger import NSQ.Protocol import NSQ.Consumer.Helpers alias NSQ.Consumer.Backoff alias NSQ.Consumer.Connections alias NSQ.Consumer.RDY alias NSQ.ConnInfo, as: ConnInfo # ------------------------------------------------------- # # Module Attributes # # ------------------------------------------------------- # @initial_state %{ channel: nil, config: %NSQ.Config{}, conn_sup_pid: nil, conn_info_pid: nil, event_manager_pid: nil, max_in_flight: 2500, topic: nil, message_handler: nil, need_rdy_redistributed: false, stop_flag: false, backoff_counter: 0, backoff_duration: 0, distribution_counter: 0 } # ------------------------------------------------------- # # Type Definitions # # ------------------------------------------------------- # @typedoc """ A tuple with a host and a port. """ @type host_with_port :: {String.t(), integer} @typedoc """ A tuple with a string ID (used to target the connection in NSQ.Connection.Supervisor) and a PID of the connection. """ @type connection :: {String.t(), pid} @typedoc """ A map, but we can be more specific by asserting some entries that should be set for a connection's state map. """ @type cons_state :: %{conn_sup_pid: pid, config: NSQ.Config.t(), conn_info_pid: pid} @type state :: %{conn_sup_pid: pid, config: NSQ.Config.t(), conn_info_pid: pid} # ------------------------------------------------------- # # Behaviour Implementation # # ------------------------------------------------------- # @doc """ Starts a Consumer process, called via the supervisor. """ @spec start_link({String.t(), String.t(), String.t(), NSQ.Config.t()}) :: {:ok, pid} def start_link({topic, channel, cons_name, config}) do {:ok, config} = NSQ.Config.validate(config) {:ok, config} = NSQ.Config.normalize(config) unless is_valid_topic_name?(topic), do: raise("Invalid topic name #{topic}") unless is_valid_channel_name?(channel), do: raise("Invalid channel name #{channel}") state = %{ @initial_state | topic: topic, channel: channel, config: config, max_in_flight: config.max_in_flight } GenServer.start_link(__MODULE__, state, name: cons_name) end @doc """ On init, we create a connection for each NSQD instance discovered, and set up loops for discovery and RDY redistribution. """ @spec init(map) :: {:ok, cons_state} def init(cons_state) do {:ok, conn_sup_pid} = NSQ.Connection.Supervisor.start_link() cons_state = %{cons_state | conn_sup_pid: conn_sup_pid} {:ok, conn_info_pid} = Agent.start_link(fn -> %{} end) cons_state = %{cons_state | conn_info_pid: conn_info_pid} manager = if cons_state.config.event_manager do cons_state.config.event_manager else {:ok, manager} = GenEvent.start_link() manager end cons_state = %{cons_state | event_manager_pid: manager} cons_state = %{cons_state | max_in_flight: cons_state.config.max_in_flight} {:ok, _cons_state} = Connections.discover_nsqds_and_connect(self(), cons_state) end @doc """ The RDY loop periodically calls this to make sure RDY is balanced among our connections. """ @spec handle_call(:redistribute_rdy, {reference, pid}, cons_state) :: {:reply, :ok, cons_state} def handle_call(:redistribute_rdy, _from, cons_state) do {:reply, :ok, RDY.redistribute!(self(), cons_state)} end @doc """ The discovery loop calls this periodically to add/remove active nsqd connections. Called from Consumer.Supervisor. """ @spec handle_call(:discover_nsqds, {reference, pid}, cons_state) :: {:reply, :ok, cons_state} def handle_call(:discover_nsqds, _from, cons_state) do {:reply, :ok, Connections.refresh!(cons_state)} end @doc """ Only used for specs. """ @spec handle_call(:delete_dead_connections, {reference, pid}, cons_state) :: {:reply, :ok, cons_state} def handle_call(:delete_dead_connections, _from, cons_state) do {:reply, :ok, Connections.delete_dead!(cons_state)} end @doc """ Called from `NSQ.Message.fin/1`. Not for external use. """ @spec handle_call({:start_stop_continue_backoff, atom}, {reference, pid}, cons_state) :: {:reply, :ok, cons_state} def handle_call({:start_stop_continue_backoff, backoff_flag}, _from, cons_state) do {:reply, :ok, Backoff.start_stop_continue!(self(), backoff_flag, cons_state)} end @spec handle_call({:update_rdy, connection, integer}, {reference, pid}, cons_state) :: {:reply, :ok, cons_state} def handle_call({:update_rdy, conn, count}, _from, cons_state) do {:reply, :ok, RDY.update!(self(), conn, count, cons_state)} end @doc """ Called from tests to assert correct consumer state. Not for external use. """ @spec handle_call(:state, {reference, pid}, cons_state) :: {:reply, cons_state, cons_state} def handle_call(:state, _from, state) do {:reply, state, state} end def handle_call(:starved, _from, cons_state) do is_starved = ConnInfo.all(cons_state.conn_info_pid) |> Enum.any?(fn {_conn_id, info} -> info.messages_in_flight > 0 && info.messages_in_flight >= info.last_rdy * 0.85 end) {:reply, is_starved, cons_state} end @doc """ Called from `NSQ.Consumer.change_max_in_flight(consumer, max_in_flight)`. Not for external use. """ @spec handle_call({:max_in_flight, integer}, {reference, pid}, cons_state) :: {:reply, :ok, cons_state} def handle_call({:max_in_flight, new_max_in_flight}, _from, state) do {:reply, :ok, %{state | max_in_flight: new_max_in_flight}} end def handle_call(:close, _, cons_state) do {:reply, :ok, Connections.close!(cons_state)} end @doc """ Called from NSQ.Consume.event_manager. """ @spec handle_call(:event_manager, any, cons_state) :: {:reply, pid, cons_state} def handle_call(:event_manager, _from, state) do {:reply, state.event_manager_pid, state} end @doc """ Called to observe all connection stats. For debugging or reporting purposes. """ @spec handle_call(:conn_info, any, cons_state) :: {:reply, map, cons_state} def handle_call(:conn_info, _from, state) do {:reply, ConnInfo.all(state.conn_info_pid), state} end @doc """ Called from `Backoff.resume_later/3`. Not for external use. """ @spec handle_cast(:resume, cons_state) :: {:noreply, cons_state} def handle_cast(:resume, state) do {:noreply, Backoff.resume!(self(), state)} end @doc """ Called from `NSQ.Connection.handle_cast({:nsq_msg, _}, _)` after each message is received. Not for external use. """ @spec handle_cast({:maybe_update_rdy, host_with_port}, cons_state) :: {:noreply, cons_state} def handle_cast({:maybe_update_rdy, {_host, _port} = nsqd}, cons_state) do conn = conn_from_nsqd(self(), nsqd, cons_state) {:noreply, RDY.maybe_update!(self(), conn, cons_state)} end # ------------------------------------------------------- # # API Definitions # # ------------------------------------------------------- # def starved?(sup_pid) do cons = get(sup_pid) GenServer.call(cons, :starved) end def close(sup_pid) do cons = get(sup_pid) GenServer.call(cons, :close) end @doc """ Called from tests to assert correct consumer state. Not for external use. """ @spec get_state(pid) :: {:ok, cons_state} def get_state(cons) do GenServer.call(cons, :state) end @doc """ Public function to change `max_in_flight` for a consumer. The new value will be balanced across connections. """ @spec change_max_in_flight(pid, integer) :: {:ok, :ok} def change_max_in_flight(sup_pid, new_max_in_flight) do cons = get(sup_pid) GenServer.call(cons, {:max_in_flight, new_max_in_flight}) end @doc """ If the event manager is not defined in NSQ.Config, it will be generated. So if you want to attach event handlers on the fly, you can use a syntax like `NSQ.Consumer.event_manager(consumer) |> GenEvent.add_handler(MyHandler, [])` """ def event_manager(sup_pid) do cons = get(sup_pid) GenServer.call(cons, :event_manager) end def conn_info(sup_pid) do cons = get(sup_pid) GenServer.call(cons, :conn_info) end @doc """ NSQ.Consumer.Supervisor.start_link returns the supervisor pid so that we can effectively recover from consumer crashes. This function takes the supervisor pid and returns the consumer pid. We use this for public facing functions so that the end user can simply target the supervisor, e.g. `NSQ.Consumer.change_max_in_flight(supervisor_pid, 100)`. Not for external use. """ @spec get(pid) :: pid def get(sup_pid) do children = Supervisor.which_children(sup_pid) child = Enum.find(children, fn {kind, _, _, _} -> kind == NSQ.Consumer end) {_, pid, _, _} = child pid end end
34.233803
97
0.647741
739efeb861b0b6ab2408c60b21b22d17f1eddb92
221
exs
Elixir
test/grizzly/zwave/commands/date_get_test.exs
jellybob/grizzly
290bee04cb16acbb9dc996925f5c501697b7ac94
[ "Apache-2.0" ]
76
2019-09-04T16:56:58.000Z
2022-03-29T06:54:36.000Z
test/grizzly/zwave/commands/date_get_test.exs
jellybob/grizzly
290bee04cb16acbb9dc996925f5c501697b7ac94
[ "Apache-2.0" ]
124
2019-09-05T14:01:24.000Z
2022-02-28T22:58:14.000Z
test/grizzly/zwave/commands/date_get_test.exs
jellybob/grizzly
290bee04cb16acbb9dc996925f5c501697b7ac94
[ "Apache-2.0" ]
10
2019-10-23T19:25:45.000Z
2021-11-17T13:21:20.000Z
defmodule Grizzly.ZWave.Commands.DateGetTest do use ExUnit.Case, async: true alias Grizzly.ZWave.Commands.DateGet test "creates the command and validates params" do {:ok, _command} = DateGet.new([]) end end
22.1
52
0.737557
739f1f4a9178b01d233106ab27dbddc9d28c9af5
15,091
ex
Elixir
lib/phoenix_live_component.ex
dbi1/phoenix_live_view
1fff01e0234a75b369ac9085b3b4ec096ef0b52b
[ "MIT" ]
null
null
null
lib/phoenix_live_component.ex
dbi1/phoenix_live_view
1fff01e0234a75b369ac9085b3b4ec096ef0b52b
[ "MIT" ]
null
null
null
lib/phoenix_live_component.ex
dbi1/phoenix_live_view
1fff01e0234a75b369ac9085b3b4ec096ef0b52b
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveComponent do @moduledoc """ Components are a mechanism to compartmentalize state, markup, and events in LiveView. Components are defined by using `Phoenix.LiveComponent` and are used by calling `Phoenix.LiveView.Helpers.live_component/3` in a parent LiveView. Components run inside the LiveView process, but may have their own state and event handling. The simplest component only needs to define a `render` function: defmodule HeroComponent do use Phoenix.LiveComponent def render(assigns) do ~L\""" <div class="hero"><%= @content %></div> \""" end end When `use Phoenix.LiveComponent` is used, all functions in `Phoenix.LiveView` are imported. A component can be invoked as: <%= live_component @socket, HeroComponent, content: @content %> Components come in two shapes, stateless or stateful. The component above is a stateless component. Of course, the component above is not any different compared to a regular function. However, as we will see, components do provide their own exclusive feature set. ## Stateless components life-cycle When `live_component` is called, the following callbacks will be invoked in the component: mount(socket) -> update(assigns, socket) -> render(assigns) First `c:mount/1` is called only with the socket. `mount/1` can be used to set any initial state. Then `c:update/2` is invoked with all of the assigns given to `live_component/3`. The default implementation of `c:update/2` simply merges all assigns into the socket. Then, after the component is updated, `c:render/1` is called with all assigns. A stateless component is always mounted, updated, and rendered whenever the parent template changes. That's why they are stateless: no state is kept after the component. However, any component can be made stateful by passing an `:id` assign. ## Stateful components life-cycle A stateful component is a component that receives an `:id` on `live_component/3`: <%= live_component @socket, HeroComponent, id: :hero, content: @content %> Stateful components are identified by the component module and their ID. Therefore, two different component modules with the same ID are different components. This means we can often tie the component ID to some application based ID: <%= live_component @socket, UserComponent, id: @user.id, user: @user %> Also note the given `:id` is not necessarily used as the DOM ID. If you want to set a DOM ID, it is your responsibility to set it when rendering: defmodule UserComponent do use Phoenix.LiveComponent def render(assigns) do ~L\""" <div id="user-<%= @id %>" class="user"><%= @user.name %></div> \""" end end In stateful components, `c:mount/1` is called only once, when the component is first rendered. Then for each rendering, the optional `c:preload/1` and `c:update/2` callbacks are called before `c:render/1`. ## Targeting Component Events Stateful components can also implement the `c:handle_event/3` callback that works exactly the same as in LiveView. For a client event to reach a component, the tag must be annotated with a `phx-target`. If you want to send the event to yourself, you can simply use the `@myself` assign, which is an *internal unique reference* to the component instance: <a href="#" phx-click="say_hello" phx-target="<%= @myself %>"> Say hello! </a> Note `@myself` is not set for stateless components, as they cannot receive events. If you want to target another component, you can also pass an ID or a class selector to any element inside the targeted component. For example, if there is a `UserComponent` with `:id` of `13`, it will have the DOM ID of `user-13`. Using a query selector, we can send an event to it with: <a href="#" phx-click="say_hello" phx-target="#user-13"> Say hello! </a> In both cases, `c:handle_event/3` will be called with the "say_hello" event. When `c:handle_event/3` is called for a component, only the diff of the component is sent to the client, making them extremely efficient. Any valid query selector for `phx-target` is supported, provided that the matched nodes are children of a LiveView or LiveComponent, for example to send the `close` event to multiple components: <a href="#" phx-click="close" phx-target="#modal, #sidebar"> Dismiss </a> ### Preloading and update Every time a stateful component is rendered, both `c:preload/1` and `c:update/2` is called. To understand why both callbacks are necessary, imagine that you implement a component and the component needs to load some state from the database. For example: <%= live_component @socket, UserComponent, id: user_id %> A possible implementation would be to load the user on the `c:update/2` callback: def update(assigns, socket) do user = Repo.get! User, assigns.id {:ok, assign(socket, :user, user)} end However, the issue with said approach is that, if you are rendering multiple user components in the same page, you have a N+1 query problem. The `c:preload/1` callback helps address this problem as it is invoked with a list of assigns for all components of the same type. For example, instead of implementing `c:update/2` as above, one could implement: def preload(list_of_assigns) do list_of_ids = Enum.map(list_of_assigns, & &1.id) users = from(u in User, where: u.id in ^list_of_ids, select: {u.id, u}) |> Repo.all() |> Map.new() Enum.map(list_of_assigns, fn assigns -> Map.put(assigns, :user, users[assigns.id]) end) end Now only a single query to the database will be made. In fact, the preloading algorithm is a breadth-first tree traversal, which means that even for nested components, the amount of queries are kept to a minimum. Finally, note that `c:preload/1` must return an updated `list_of_assigns`, keeping the assigns in the same order as they were given. ## Managing state Now that we have learned how to define and use components, as well as how to use `c:preload/1` as a data loading optimization, it is important to talk about how to manage state in components. Generally speaking, you want to avoid both the parent LiveView and the LiveComponent working on two different copies of the state. Instead, you should assume only one of them to be the source of truth. Let's discuss these approaches in detail. Imagine that the scenario we will explore is that we have a LiveView representing a board, where each card in the board is a separate component. Each card has a form that allows to update the form title directly in the component. We will see how to organize the data flow keeping either the view or the component as the source of truth. ### LiveView as the source of truth If the LiveView is the source of truth, the LiveView will be responsible for fetching all of the cards in a board. Then it will call `live_component/3` for each card, passing the card struct as argument to CardComponent: <%= for card <- @cards do %> <%= live_component @socket, CardComponent, card: card, board_id: @id %> <% end %> Now, when the user submits a form inside the CardComponent to update the card, `CardComponent.handle_event/3` will be triggered. However, if the update succeeds, you must not change the card struct inside the component. If you do so, the card struct in the component will get out of sync with the LiveView. Since the LiveView is the source of truth, we should instead tell the LiveView the card was updated. Luckily, because the component and the view run in the same process, sending a message from the component to the parent LiveView is as simple as sending a message to self: defmodule CardComponent do ... def handle_event("update_title", %{"title" => title}, socket) do send self(), {:updated_card, %{socket.assigns.card | title: title}} {:noreply, socket} end end The LiveView can receive this event using `handle_info`: defmodule BoardView do ... def handle_info({:updated_card, card}, socket) do # update the list of cards in the socket {:noreply, updated_socket} end end As the list of cards in the parent socket was updated, the parent will be re-rendered, sending the updated card to the component. So in the end, the component does get the updated card, but always driven from the parent. Alternatively, instead of having the component directly send a message to the parent, the component could broadcast the update using `Phoenix.PubSub`. Such as: defmodule CardComponent do ... def handle_event("update_title", %{"title" => title}, socket) do message = {:updated_card, %{socket.assigns.card | title: title}} Phoenix.PubSub.broadcast(MyApp.PubSub, board_topic(socket), message) {:noreply, socket} end defp board_topic(socket) do "board:" <> socket.assigns.board_id end end As long as the parent LiveView subscribes to the "board:ID" topic, it will receive updates. The advantage of using PubSub is that we get distributed updates out of the box. Now if any user connected to the board changes a card, all other users will see the change. ### LiveComponent as the source of truth If the component is the source of truth, then the LiveView must no longer fetch all of the cards structs from the database. Instead, the view must only fetch all of the card ids and render the component only by passing the IDs: <%= for card_id <- @card_ids do %> <%= live_component @socket, CardComponent, card_id: card_id, board_id: @id %> <% end %> Now, each CardComponent loads their own card. Of course, doing so per card would be expensive and lead to N queries, where N is the number of components, so we must use the `c:preload/1` callback to make it efficient. Once all card components are started, they can fully manage each card as a whole, without concerning themselves with the parent LiveView. However, note that components do not have a `handle_info/2` callback. Therefore, if you want to track distributed changes on a card, you must have the parent LiveView receive those events and redirect them to the appropriate card. For example, assuming card updates are sent to the "board:ID" topic, and that the board LiveView is subscribed to said topic, one could do: def handle_info({:updated_card, card}, socket) do send_update CardComponent, id: card.id, board_id: socket.assigns.id {:noreply, socket} end With `send_update`, the CardComponent given by `id` will be invoked, triggering both preload and update callbacks, which will load the most up to date data from the database. ## Live component blocks When `live_component` is invoked, it is also possible to pass a `do/end` block: <%= live_component @socket, GridComponent, entries: @entries do %> New entry: <%= @entry %> <% end %> The `do/end` will be available as an anonymous function in an assign named `@inner_content`. The anonymous function must be invoked passing a new set of assigns that will be merged into the user assigns. For example, the grid component above could be implemented as: defmodule GridComponent do use Phoenix.LiveComponent def render(assigns) do ~L\""" <div class="grid"> <%= for entry <- @entries do %> <div class="column"> <%= @inner_content.(entry: entry) %> </div> <% end %> </div> \""" end end Where the `:entry` assign was injected into the `do/end` block. The approach above is the preferred one when passing blocks to `do/end`. However, if you are outside of a .leex template and you want to invoke a component passing `do/end` blocks, you will have to explicitly handle the assigns by giving it a clause: live_component @socket, GridComponent, entries: @entries do new_assigns -> "New entry: " <> new_assigns[:entry] end ## Live patches and live redirects A template rendered inside a component can use `live_patch` and `live_redirect` calls. The `live_patch` is always handled by the parent `LiveView`, as components do not provide `handle_params`. ## Limitations Components must only contain HTML tags at their root. At least one HTML tag must be present. It is not possible to have components that render only text or text mixed with tags at the root. Another limitation of components is that they must always be change tracked. For example, if you render a component inside `form_for`, like this: <%= form_for @changeset, "#", fn f -> %> <%= live_component @socket, SomeComponent, f: f %> <% end %> The component ends up enclosed by the form markup, where LiveView cannot track it. In such cases, you may receive an error such as: ** (ArgumentError) cannot convert component SomeComponent to HTML. A component must always be returned directly as part of a LiveView template In this particular case, this can be addressed by using the `form_for` variant without anonymous functions: <%= f = form_for @changeset, "#" %> <%= live_component @socket, SomeComponent, f: f %> </form> This issue can also happen with other helpers, such as `content_tag`: <%= content_tag :div do %> <%= live_component @socket, SomeComponent, f: f %> <% end %> In this case, the solution is to not use `content_tag` and rely on LiveEEx to build the markup. """ alias Phoenix.LiveView.Socket defmacro __using__(_) do quote do import Phoenix.LiveView import Phoenix.LiveView.Helpers @behaviour Phoenix.LiveComponent @before_compile Phoenix.LiveView.Renderer @doc false def __live__, do: %{kind: :component, module: __MODULE__} end end @callback mount(socket :: Socket.t()) :: {:ok, Socket.t()} | {:ok, Socket.t(), keyword()} @callback preload(list_of_assigns :: [Socket.assigns()]) :: list_of_assigns :: [Socket.assigns()] @callback update(assigns :: Socket.assigns(), socket :: Socket.t()) :: {:ok, Socket.t()} @callback render(assigns :: Socket.assigns()) :: Phoenix.LiveView.Rendered.t() @callback handle_event( event :: binary, unsigned_params :: Socket.unsigned_params(), socket :: Socket.t() ) :: {:noreply, Socket.t()} @optional_callbacks mount: 1, preload: 1, update: 2, handle_event: 3 end
37.633416
85
0.689086
739f3cefb292784fb3212aac36ade4c8b93f76e5
58
ex
Elixir
lib/gaga_web/views/session_view.ex
madvoidhq/gaga
1a539edc327135c7910a51bffd6824bddcba5f7d
[ "MIT" ]
13
2020-11-22T18:43:21.000Z
2022-02-12T00:57:45.000Z
lib/gaga_web/views/session_view.ex
madvoidhq/gaga
1a539edc327135c7910a51bffd6824bddcba5f7d
[ "MIT" ]
2
2020-11-25T16:58:15.000Z
2021-06-21T12:02:41.000Z
lib/gaga_web/views/session_view.ex
madvoidhq/gaga
1a539edc327135c7910a51bffd6824bddcba5f7d
[ "MIT" ]
4
2020-11-23T08:14:03.000Z
2022-01-25T08:18:41.000Z
defmodule GagaWeb.SessionView do use GagaWeb, :view end
14.5
32
0.793103
739f5933bb6934c3c39b92e68cda5fddf53e6850
113
ex
Elixir
web/views/admin_view.ex
devonestes/ex_admin
e135ae7c28de78fc87baf519ff8a32da12e8bf66
[ "MIT" ]
1,347
2015-10-05T18:23:49.000Z
2022-01-09T18:38:36.000Z
web/views/admin_view.ex
leonardzhou/ex_admin
c241e956503c548a472e3ee89751e64a16477638
[ "MIT" ]
402
2015-10-03T13:53:32.000Z
2021-07-08T09:52:22.000Z
web/views/admin_view.ex
leonardzhou/ex_admin
c241e956503c548a472e3ee89751e64a16477638
[ "MIT" ]
333
2015-10-12T22:56:57.000Z
2021-05-26T18:40:24.000Z
Code.ensure_compiled(ExAdmin.Web) defmodule ExAdmin.AdminView do @moduledoc false use ExAdmin.Web, :view end
18.833333
33
0.79646
739f7812e7266d5575f9f9c2dcd8374c0fed180c
1,151
ex
Elixir
src/inmana.ex
salespaulo/inmana
26c0c1c1b61f37e4b108800eb8ed29fca986b9b7
[ "MIT" ]
null
null
null
src/inmana.ex
salespaulo/inmana
26c0c1c1b61f37e4b108800eb8ed29fca986b9b7
[ "MIT" ]
null
null
null
src/inmana.ex
salespaulo/inmana
26c0c1c1b61f37e4b108800eb8ed29fca986b9b7
[ "MIT" ]
null
null
null
defmodule Inmana do @moduledoc """ Inmana keeps the contexts that define your domain and business logic. Contexts are also responsible for managing your data, regardless if it comes from the database, an external API or others. """ alias Inmana.Restaurant alias Inmana.Supply # Restaurant defdelegate restaurant_create(params), to: Restaurant, as: :create defdelegate restaurant_get(uuid), to: Restaurant, as: :get defdelegate restaurant_get_all(), to: Restaurant, as: :get_all defdelegate restaurant_get_all(params), to: Restaurant, as: :get_all defdelegate restaurant_get_with_supplies(uuid), to: Restaurant, as: :get_with_supplies # Supply defdelegate supply_get(uuid), to: Supply, as: :get defdelegate supply_get_all(), to: Supply, as: :get_all defdelegate supply_get_all(params), to: Supply, as: :get_all defdelegate supply_get_by_expiration(), to: Supply, as: :get_by_expiration defdelegate supply_get_by_expiration(date), to: Supply, as: :get_by_expiration defdelegate supply_create(params), to: Supply, as: :create defdelegate supply_expiration_notify(), to: Supply, as: :expiration_notify end
38.366667
88
0.768897
739f8e787fb66c1872b5ad6d2ba595064ff1ef17
902
ex
Elixir
test/support/conn_case.ex
c18t/supreme-tsugu-chan
9d1d4cffcd917f2454a8a2918389ea239f2a6cdc
[ "MIT" ]
null
null
null
test/support/conn_case.ex
c18t/supreme-tsugu-chan
9d1d4cffcd917f2454a8a2918389ea239f2a6cdc
[ "MIT" ]
null
null
null
test/support/conn_case.ex
c18t/supreme-tsugu-chan
9d1d4cffcd917f2454a8a2918389ea239f2a6cdc
[ "MIT" ]
null
null
null
defmodule SupremeTsuguChanWeb.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 SupremeTsuguChanWeb.Router.Helpers # The default endpoint for testing @endpoint SupremeTsuguChanWeb.Endpoint end end setup _tags do {:ok, conn: Phoenix.ConnTest.build_conn()} end end
25.771429
58
0.737251
739f911e9b7668cb404286ef948a235afa4f9383
1,265
ex
Elixir
lib/tanegashima/device.ex
massn/Tanegashima
d7a473500dfccf6e15f89848f22e4194b87108cb
[ "MIT" ]
4
2016-02-17T13:15:51.000Z
2017-04-29T16:12:55.000Z
lib/tanegashima/device.ex
massn/Tanegashima
d7a473500dfccf6e15f89848f22e4194b87108cb
[ "MIT" ]
1
2017-05-25T06:55:18.000Z
2021-02-27T21:03:15.000Z
lib/tanegashima/device.ex
massn/Tanegashima
d7a473500dfccf6e15f89848f22e4194b87108cb
[ "MIT" ]
1
2017-04-29T16:12:56.000Z
2017-04-29T16:12:56.000Z
defmodule Tanegashima.Device do @moduledoc""" Elixir wrapper for Pushbullet-Device-API. """ defstruct [:active, :app_version, :created, :fingerprint, :generated_nickname, :has_mms, :has_sms, :icon, :iden, :key_fingerprint, :kind, :manufacturer, :model, :modified, :nickname, :pushable, :push_token, :remote_files, :type] @type t :: %__MODULE__{} @device_api "https://api.pushbullet.com/v2/devices" @doc""" get devices. """ @spec get :: {:ok, [Tanegashima.Device.t]} | {:error, term} def get do with {:ok, %{status_code: status_code, body: response}} <- HTTPoison.get(@device_api, [{"Access-Token", Tanegashima.access_token}]), {:error, [status_code: 200, response: ^response]} <- {:error, [status_code: status_code, response: response]}, {:ok, poison_struct} <- Poison.decode(response, as: %{}), {:ok, %{devices: devices}} <- Tanegashima.to_struct(Tanegashima, poison_struct) do device_structs = for device <- devices do {:ok, device_struct} = Tanegashima.to_struct(Tanegashima.Device, device) device_struct end {:ok, device_structs} end end end
34.189189
90
0.599209
73a0141854189b95771d0a29aef232d8619fef45
2,055
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/target_https_proxies_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_https_proxies_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_https_proxies_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.TargetHttpsProxiesScopedListWarningData 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.TargetHttpsProxiesScopedListWarningData do def decode(value, options) do GoogleApi.Compute.V1.Model.TargetHttpsProxiesScopedListWarningData.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.TargetHttpsProxiesScopedListWarningData do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
41.1
527
0.745499
73a01d3ab606e8b59926d73d742ad000665f2591
1,628
ex
Elixir
test/support/data_case.ex
cogini/phoenix_container_example
2c4d66ad7186ec165b9d260bc232d6c6ee9b2abe
[ "Apache-2.0" ]
19
2020-07-21T06:03:36.000Z
2022-03-21T22:35:22.000Z
test/support/data_case.ex
cogini/phoenix_container_example
2c4d66ad7186ec165b9d260bc232d6c6ee9b2abe
[ "Apache-2.0" ]
1
2022-03-08T10:26:55.000Z
2022-03-08T10:26:55.000Z
test/support/data_case.ex
cogini/phoenix_container_example
2c4d66ad7186ec165b9d260bc232d6c6ee9b2abe
[ "Apache-2.0" ]
1
2022-02-09T01:25:09.000Z
2022-02-09T01:25:09.000Z
defmodule PhoenixContainerExample.DataCase do @moduledoc """ This module defines the setup for tests requiring access to the application's data layer. You may define functions here to be used as helpers in your tests. Finally, if the test case interacts with the database, we enable the SQL sandbox, so changes done to the database are reverted at the end of every test. If you are using PostgreSQL, you can even run database tests asynchronously by setting `use PhoenixContainerExample.DataCase, async: true`, although this option is not recommended for other databases. """ use ExUnit.CaseTemplate using do quote do alias PhoenixContainerExample.Repo import Ecto import Ecto.Changeset import Ecto.Query import PhoenixContainerExample.DataCase end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(PhoenixContainerExample.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(PhoenixContainerExample.Repo, {:shared, self()}) end :ok end @doc """ A helper that transforms changeset errors into a map of messages. assert {:error, changeset} = Accounts.create_user(%{password: "short"}) assert "password is too short" in errors_on(changeset).password assert %{password: ["password is too short"]} = errors_on(changeset) """ def errors_on(changeset) do Ecto.Changeset.traverse_errors(changeset, fn {message, opts} -> Regex.replace(~r"%{(\w+)}", message, fn _, key -> opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string() end) end) end end
29.071429
85
0.707002
73a02970ec46c018e4f3ff216e544754bc308e01
1,997
exs
Elixir
test/examples/regexp_matcher_test.exs
lincolnf/pact_elixir
21e5f473e3c30173881e577ffda8df1e1419d47d
[ "MIT" ]
27
2018-02-28T22:42:14.000Z
2022-03-20T00:30:08.000Z
test/examples/regexp_matcher_test.exs
lincolnf/pact_elixir
21e5f473e3c30173881e577ffda8df1e1419d47d
[ "MIT" ]
180
2017-12-04T09:42:53.000Z
2022-03-28T09:33:23.000Z
test/examples/regexp_matcher_test.exs
lincolnf/pact_elixir
21e5f473e3c30173881e577ffda8df1e1419d47d
[ "MIT" ]
8
2018-08-01T17:14:52.000Z
2022-01-26T12:46:46.000Z
defmodule PactElixir.Examples.RegexpMatcherTest do @moduledoc false # https://docs.pact.io/getting_started/matching#regular-expressions # https://github.com/pact-foundation/pact-specification/tree/version-2#matching-rules use ExUnit.Case alias PactElixir.PactMockServer import PactElixir.Dsl setup do provider = provider_with_interaction() exported_pact_file_path = Path.join(PactMockServer.pact_output_dir_path(provider), "Consumer-Provider.json") on_exit(fn -> if File.exists?(exported_pact_file_path) do File.rm(exported_pact_file_path) end end) {:ok, provider: provider, exported_pact_file_path: exported_pact_file_path} end defp provider_with_interaction do pact_output_dir_path = Path.join(File.cwd!(), "test") service_provider( consumer: "Consumer", provider: "Provider", pact_output_dir_path: pact_output_dir_path ) |> add_interaction( "a retrieve thing request", given("foo exists"), with_request(method: :get, path: "/thing"), will_respond_with( status: 200, body: %{ name: "Mary", dateOfBirth: PactElixir.term(generate: "02/11/2013", regex: "\d{2}\/\d{2}\/\d{4}") } ) ) |> build() end test "regexp matcher", %{provider: provider, exported_pact_file_path: exported_pact_file_path} do get_request(provider, "/thing") assert :ok = after_test_suite(provider) expected = File.read!("test/examples/regexp_matcher.pact.json") |> get_response_from_json() generated = File.read!(exported_pact_file_path) |> get_response_from_json() assert expected == generated end def get_response_from_json(response) do json = response |> Poison.decode!() [interation] = json["interactions"] interation["response"] end defp get_request(provider, path) do %HTTPoison.Response{} = HTTPoison.get!("http://localhost:#{PactMockServer.port(provider)}#{path}") end end
28.942029
99
0.688032
73a04f2bbe84b93935766b94627172cc7d086309
1,159
exs
Elixir
clients/video_intelligence/config/config.exs
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/video_intelligence/config/config.exs
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/video_intelligence/config/config.exs
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :cloud_video_intelligence_api, key: :value # # And access this configuration in your application as: # # Application.get_env(:cloud_video_intelligence_api, :key) # # Or configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs"
37.387097
73
0.760138
73a058b9783a2d39a0a9fa7d948774dfed74fd34
3,418
ex
Elixir
lib/ex_integrate/core/pipeline.ex
samrose/ExIntegrate
5effbfe7e00ee06410218ed01fea2e3b7d4ebe62
[ "Apache-2.0" ]
3
2022-01-14T20:04:07.000Z
2022-01-26T03:47:49.000Z
lib/ex_integrate/core/pipeline.ex
samrose/ExIntegrate
5effbfe7e00ee06410218ed01fea2e3b7d4ebe62
[ "Apache-2.0" ]
30
2021-11-01T23:29:32.000Z
2022-02-28T21:35:03.000Z
lib/ex_integrate/core/pipeline.ex
samrose/ExIntegrate
5effbfe7e00ee06410218ed01fea2e3b7d4ebe62
[ "Apache-2.0" ]
null
null
null
defmodule ExIntegrate.Core.Pipeline do @moduledoc """ A collection of Steps to be run sequentially. """ alias ExIntegrate.Core.Step @behaviour Access @enforce_keys [:name, :steps] defstruct @enforce_keys ++ [failed?: false] @type key :: String.t() @type t :: %__MODULE__{ failed?: boolean, name: key, steps: ZipZip.t(Step.t()) } @spec new(fields :: Access.t()) :: t def new(fields) do fields = put_in(fields[:steps], ZipZip.zip(fields[:steps])) struct!(__MODULE__, fields) end @spec steps(t) :: [Step.t()] def steps(%__MODULE__{} = pipeline), do: ZipZip.to_list(pipeline.steps) @spec pop_step(t()) :: {Step.t(), t()} def pop_step(%__MODULE__{} = pipeline) do Map.get_and_update(pipeline, :steps, fn steps -> {{:value, value}, _} = :queue.out(steps) {value, steps} end) end @spec advance(t) :: t def advance(%__MODULE__{} = pipeline), do: %{pipeline | steps: ZipZip.right(pipeline.steps)} @spec current_step(t) :: Step.t() | nil def current_step(%__MODULE__{} = pipeline), do: ZipZip.node(pipeline.steps) @spec get_step_by_name(t, String.t()) :: Step.t() def get_step_by_name(%__MODULE__{} = pipeline, step_name) do pipeline |> steps() |> Enum.find(&(&1.name == step_name)) end @spec replace_current_step(t, Step.t()) :: t def replace_current_step(%__MODULE__{} = pipeline, %Step{} = step) do put_step(pipeline, current_step(pipeline), step) end def replace_step_and_advance(%__MODULE__{} = pipeline, %Step{} = step) do pipeline |> replace_current_step(step) |> advance() end @spec put_step(t, Step.t(), Step.t()) :: t def put_step( %__MODULE__{} = pipeline, %Step{name: name} = _old_step, %Step{name: name} = new_step ) do pipeline |> Map.update(:steps, pipeline.steps, fn steps -> index = pipeline |> steps() |> Enum.find_index(&(&1.name == name)) ZipZip.replace_at(steps, index, new_step) end) |> Map.put(:failed?, pipeline.failed? || Step.failed?(new_step)) end def put_step(%__MODULE__{}, %Step{} = old_step, %Step{} = new_step) do raise ArgumentError, """ cannot alter step names after creation! Old step: #{inspect(old_step)}, Attempted new step: #{inspect(new_step)} """ end @spec failed?(t) :: boolean def failed?(%__MODULE__{} = pipeline), do: pipeline.failed? @spec complete?(t) :: boolean def complete?(%__MODULE__{} = pipeline), do: failed?(pipeline) or ZipZip.end?(pipeline.steps) @impl Access @spec fetch(t, String.t()) :: {:ok, Step.t()} def fetch(%__MODULE__{} = pipeline, step_name) do {:ok, get_step_by_name(pipeline, step_name)} end @impl Access @spec get_and_update(t, String.t(), function) :: {Step.t(), t} | no_return def get_and_update(%__MODULE__{} = pipeline, step_name, fun) when is_function(fun, 1) do current = get_step_by_name(pipeline, step_name) case fun.(current) do {get, update} -> {get, put_step(pipeline, current, update)} :pop -> raise "cannot pop steps!" other -> raise "the given function must return a two-element tuple or :pop; got: #{inspect(other)}" end end @impl Access @spec pop(term, term) :: no_return def pop(_pipeline, _step), do: raise("cannot pop steps!") end
27.344
98
0.619953
73a05a63fd27e633667781f277b03e36d62af7f7
138
exs
Elixir
test/ueber_wecounsel_test.exs
wecounsel/ueberauth_wecounsel
4a4ce349a969664c0a5ef26e30bf893da61c1d4e
[ "MIT" ]
1
2019-10-13T16:39:02.000Z
2019-10-13T16:39:02.000Z
test/ueber_wecounsel_test.exs
wecounsel/ueberauth_wecounsel
4a4ce349a969664c0a5ef26e30bf893da61c1d4e
[ "MIT" ]
null
null
null
test/ueber_wecounsel_test.exs
wecounsel/ueberauth_wecounsel
4a4ce349a969664c0a5ef26e30bf893da61c1d4e
[ "MIT" ]
null
null
null
defmodule UeberauthWecounselTest do use ExUnit.Case doctest UeberauthWecounsel test "the truth" do assert 1 + 1 == 2 end end
15.333333
35
0.724638
73a074681a0ec0d341c86d8b5b978dc63ad878e7
904
ex
Elixir
day05/lib/day05.ex
bjorng/advent-of-code-2015
d59ac2fc4a93c86ebfe3917d89ebaad3b571bdb6
[ "Apache-2.0" ]
null
null
null
day05/lib/day05.ex
bjorng/advent-of-code-2015
d59ac2fc4a93c86ebfe3917d89ebaad3b571bdb6
[ "Apache-2.0" ]
null
null
null
day05/lib/day05.ex
bjorng/advent-of-code-2015
d59ac2fc4a93c86ebfe3917d89ebaad3b571bdb6
[ "Apache-2.0" ]
null
null
null
defmodule Day05 do def part1(input) do Enum.count(input, &is_nice_part1?/1) end def part2(input) do Enum.count(input, &is_nice_part2?/1) end defp is_nice_part1?(string) do not String.contains?(string, ~w(ab cd pq xy)) and String.length(String.replace(string, ~r/[^aeiou]/, "")) >= 3 and String.match?(string, ~r/(.)\1/) end defp is_nice_part2?(string) do String.match?(string, ~r/(.).\1/) and has_pairs?(string) end defp has_pairs?(string) do string |> String.to_charlist |> collect_pairs |> Enum.frequencies |> Enum.find(fn {_, frequency} -> frequency >= 2 end) end defp collect_pairs(charlist) do case charlist do [c, c, c | tail] -> [[c, c] | collect_pairs([c | tail])] [c1, c2 | tail] -> [[c1, c2] | collect_pairs([c2 | tail])] [_] -> [] [] -> [] end end end
21.52381
68
0.567478
73a0776b98de84820abe45598f01dc3c63a4b062
860
ex
Elixir
lib/protocol.ex
vpsinc/modbus
e1b04916dc12c104e032122738815a1e3910394b
[ "Apache-2.0" ]
null
null
null
lib/protocol.ex
vpsinc/modbus
e1b04916dc12c104e032122738815a1e3910394b
[ "Apache-2.0" ]
null
null
null
lib/protocol.ex
vpsinc/modbus
e1b04916dc12c104e032122738815a1e3910394b
[ "Apache-2.0" ]
null
null
null
defmodule Modbus.Protocol do @moduledoc false @callback next(tid :: any()) :: any() @callback pack_req(cmd :: tuple(), tid :: any) :: req :: binary() @callback res_len(cmd :: tuple()) :: len :: integer() @callback parse_res(cmd :: tuple(), res :: binary(), tid :: any) :: list(integer()) @callback parse_req(req :: binary()) :: {cmd :: tuple(), tid :: any} @callback pack_res(cmd :: tuple(), values :: list(integer()), tid :: any) :: req :: binary() def next(mod, tid) do mod.next(tid) end def pack_req(mod, cmd, tid) do mod.pack_req(cmd, tid) end def res_len(mod, cmd) do mod.res_len(cmd) end def parse_res(mod, cmd, res, tid) do mod.parse_res(cmd, res, tid) end def parse_req(mod, req) do mod.parse_req(req) end def pack_res(mod, cmd, values, tid) do mod.pack_res(cmd, values, tid) end end
25.294118
94
0.613953
73a09d2622c3f56cbdb6d1a4a3cd52d4234f9cb1
5,774
exs
Elixir
test/ex_oauth2_provider/oauth2/token/strategy/password_test.exs
loopsocial/ex_oauth2_provider
59d177f1c7581e1d794823279067022b1598f5f2
[ "MIT" ]
null
null
null
test/ex_oauth2_provider/oauth2/token/strategy/password_test.exs
loopsocial/ex_oauth2_provider
59d177f1c7581e1d794823279067022b1598f5f2
[ "MIT" ]
null
null
null
test/ex_oauth2_provider/oauth2/token/strategy/password_test.exs
loopsocial/ex_oauth2_provider
59d177f1c7581e1d794823279067022b1598f5f2
[ "MIT" ]
null
null
null
defmodule ExOauth2Provider.Token.Strategy.PasswordTest do use ExOauth2Provider.TestCase alias ExOauth2Provider.{Config, Token, Token.Password} alias ExOauth2Provider.Test.{Fixtures, QueryHelpers} alias Dummy.OauthAccessTokens.OauthAccessToken @client_id "Jf5rM8hQBc" @client_secret "secret" @username "[email protected]" @password "secret" @valid_request %{ "client_id" => @client_id, "client_secret" => @client_secret, "grant_type" => "password", "username" => @username, "password" => @password } @invalid_client_error %{ error: :invalid_client, error_description: "Client authentication failed due to unknown client, no client authentication included, or unsupported authentication method." } @invalid_request_error %{ error: :invalid_request, error_description: "The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed." } @invalid_scope %{ error: :invalid_scope, error_description: "The requested scope is invalid, unknown, or malformed." } setup do user = Fixtures.resource_owner(email: @username) application = Fixtures.application(uid: @client_id, secret: @client_secret, scopes: "app:read app:write") {:ok, %{user: user, application: application}} end test "#grant/2 error when invalid client" do request_invalid_client = Map.merge(@valid_request, %{"client_id" => "invalid"}) assert Token.grant(request_invalid_client, otp_app: :ex_oauth2_provider) == {:error, @invalid_client_error, :unprocessable_entity} end test "#grant/2 error when invalid secret" do request_invalid_client = Map.merge(@valid_request, %{"client_secret" => "invalid"}) assert Token.grant(request_invalid_client, otp_app: :ex_oauth2_provider) == {:error, @invalid_client_error, :unprocessable_entity} request_invalid_client = Map.delete(@valid_request, "client_secret") assert Token.grant(request_invalid_client, otp_app: :ex_oauth2_provider) == {:error, @invalid_client_error, :unprocessable_entity} end test "#grant/2 error when missing required values" do Enum.each(["username", "password"], fn k -> params = Map.delete(@valid_request, k) assert Token.grant(params, otp_app: :ex_oauth2_provider) == {:error, @invalid_request_error, :bad_request} end) end test "#grant/2 error when invalid password" do params = Map.merge(@valid_request, %{"password" => "invalid"}) assert Token.grant(params, otp_app: :ex_oauth2_provider) == {:error, :unauthorized, :unauthorized} end test "#grant/1 error when invalid scope" do params = Map.merge(@valid_request, %{"scope" => "invalid"}) assert Token.grant(params, otp_app: :ex_oauth2_provider) == {:error, @invalid_scope, :unprocessable_entity} end test "#grant/1 error when no password auth set" do expected_error = %{ error: :unsupported_grant_type, error_description: "The authorization grant type is not supported by the authorization server." } assert Password.grant(@valid_request, otp_app: :ex_oauth2_provider, password_auth: nil) == {:error, expected_error, :unprocessable_entity} end test "#grant/1 returns access token", %{user: user, application: application} do assert {:ok, body} = Token.grant(@valid_request, otp_app: :ex_oauth2_provider) access_token = QueryHelpers.get_latest_inserted(OauthAccessToken) assert body.access_token == access_token.token assert access_token.resource_owner_id == user.id assert access_token.application_id == application.id assert access_token.scopes == application.scopes assert access_token.expires_in == Config.access_token_expires_in(otp_app: :ex_oauth2_provider) refute is_nil(access_token.refresh_token) end test "#grant/1 returns access token when only client_id required", %{ user: user, application: application } do QueryHelpers.change!(application, secret: "") params = Map.delete(@valid_request, "client_secret") assert {:ok, body} = Token.grant(params, otp_app: :ex_oauth2_provider) access_token = QueryHelpers.get_latest_inserted(OauthAccessToken) assert body.access_token == access_token.token assert access_token.resource_owner_id == user.id assert access_token.application_id == application.id end test "#grant/1 returns access token with custom response handler" do assert {:ok, body} = Password.grant(@valid_request, otp_app: :ex_oauth2_provider, access_token_response_body_handler: {__MODULE__, :access_token_response_body_handler} ) access_token = QueryHelpers.get_latest_inserted(OauthAccessToken) assert body.custom_attr == access_token.inserted_at end test "#grant/1 doesn't set refresh_token when ExOauth2Provider.Config.use_refresh_token? == false" do assert {:ok, body} = Password.grant(@valid_request, otp_app: :ex_oauth2_provider, use_refresh_token: false) access_token = QueryHelpers.get_latest_inserted(OauthAccessToken) assert body.access_token == access_token.token assert is_nil(access_token.refresh_token) end test "#grant/1 returns access token with limited scope" do params = Map.merge(@valid_request, %{"scope" => "app:read"}) assert {:ok, _} = Token.grant(params, otp_app: :ex_oauth2_provider) access_token = QueryHelpers.get_latest_inserted(OauthAccessToken) assert access_token.scopes == "app:read" end def access_token_response_body_handler(body, access_token) do Map.merge(body, %{custom_attr: access_token.inserted_at}) end end
36.314465
132
0.715795
73a0b854686d4514558b6e7d1d5d18d5dba0daa0
177
exs
Elixir
apps/fares/test/test_helper.exs
noisecapella/dotcom
d5ef869412102d2230fac3dcc216f01a29726227
[ "MIT" ]
42
2019-05-29T16:05:30.000Z
2021-08-09T16:03:37.000Z
apps/fares/test/test_helper.exs
noisecapella/dotcom
d5ef869412102d2230fac3dcc216f01a29726227
[ "MIT" ]
872
2019-05-29T17:55:50.000Z
2022-03-30T09:28:43.000Z
apps/fares/test/test_helper.exs
noisecapella/dotcom
d5ef869412102d2230fac3dcc216f01a29726227
[ "MIT" ]
12
2019-07-01T18:33:21.000Z
2022-03-10T02:13:57.000Z
# Ensure the deps are all started Application.ensure_all_started(:fares) # Report warnings as errors Code.compiler_options(warnings_as_errors: true) ExUnit.start(max_cases: 1)
25.285714
47
0.819209
73a0e6eebf67ce20c375cd9790cf8e64513ad875
2,244
exs
Elixir
test/endpoint/dynamic_test.exs
OpenMatchmaking/spotter
d4680b14074991811623147cc4c4bf73c95b3090
[ "BSD-3-Clause" ]
null
null
null
test/endpoint/dynamic_test.exs
OpenMatchmaking/spotter
d4680b14074991811623147cc4c4bf73c95b3090
[ "BSD-3-Clause" ]
1
2018-09-03T15:50:45.000Z
2018-11-29T07:37:19.000Z
test/endpoint/dynamic_test.exs
OpenMatchmaking/spotter
d4680b14074991811623147cc4c4bf73c95b3090
[ "BSD-3-Clause" ]
null
null
null
defmodule SpotterEndpointDynamicTest do use ExUnit.Case test "Spotter.Endpoint.Dynamic contructor set permissions to empty list" do endpoint = Spotter.Endpoint.Dynamic.new("api.leaderboard.get.{user_id}", []) assert endpoint.regex == ~r/^api.leaderboard.get.(?P<user_id>[^{}\/.]+)$/ assert endpoint.base.path == "api.leaderboard.get.{user_id}" assert endpoint.base.permissions == [] end test "Spotter.Endpoint.Dynamic contructor with custom permissions" do endpoint = Spotter.Endpoint.Dynamic.new( "api.leaderboard.get.{user_id}", ["api.leaderboard.get"] ) assert endpoint.regex == ~r/^api.leaderboard.get.(?P<user_id>[^{}\/.]+)$/ assert endpoint.base.path == "api.leaderboard.get.{user_id}" assert endpoint.base.permissions == ["api.leaderboard.get", ] end test "Spotter.Endpoint.Dynamic.match returns true for exact match" do endpoint = Spotter.Endpoint.Dynamic.new( "api.leaderboard.get.{user_id}", ["api.leaderboard.get", ] ) assert Spotter.Endpoint.Dynamic.match(endpoint, "api.leaderboard.get.user-123456789") end test "Spotter.Endpoint.Dynamic.match returns false for not matched path" do endpoint = Spotter.Endpoint.Dynamic.new( "api.leaderboard.get.{user_id}", ["api.leaderboard.get", ] ) assert not Spotter.Endpoint.Dynamic.match(endpoint, "some.another.api") end test "Spotter.Endpoint.Dynamic.has_permission returns true for correct permissions" do endpoint = Spotter.Endpoint.Dynamic.new("api.leaderboard.get.{user_id}", ["get", "update"]) assert Spotter.Endpoint.Dynamic.has_permissions(endpoint, ["get", "update", "delete"]) end test "Spotter.Endpoint.Dynamic.has_permission returns false for invalid permissions" do endpoint = Spotter.Endpoint.Dynamic.new("api.leaderboard.get.{user_id}", ["list", "delete"]) assert not Spotter.Endpoint.Dynamic.has_permissions(endpoint, ["list", "update"]) end test "Spotter.Endpoint.Dynamic.has_permission returns true for the endpoint without permissions" do endpoint = Spotter.Endpoint.Dynamic.new("api.leaderboard.get.{user_id}", []) assert Spotter.Endpoint.Dynamic.has_permissions(endpoint, ["get", "patch", "head"]) end end
38.033898
101
0.711676
73a0f04992cdc0ed670f74fbfbd2646899ec7b62
4,062
ex
Elixir
lib/mongoose_push/application.ex
Switch168/MongoosePush
d997bd9cd0e63e16684bec9495cd12790bcaa8f1
[ "Apache-2.0" ]
null
null
null
lib/mongoose_push/application.ex
Switch168/MongoosePush
d997bd9cd0e63e16684bec9495cd12790bcaa8f1
[ "Apache-2.0" ]
null
null
null
lib/mongoose_push/application.ex
Switch168/MongoosePush
d997bd9cd0e63e16684bec9495cd12790bcaa8f1
[ "Apache-2.0" ]
null
null
null
defmodule MongoosePush.Application do # See http://elixir-lang.org/docs/stable/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application require Logger @typedoc "Possible keys in FCM config" @type fcm_key :: :key | :pool_size | :mode | :endpoint @typedoc "Possible keys in APNS config" @type apns_key :: :cert | :key | :pool_size | :mode | :endpoint | :use_2197 @typedoc """ In FCM `:key` and `:pool_size` are required and `:mode` has to be either `:dev` or `:prod` """ @type fcm_config :: [{fcm_key, String.t() | atom | integer}] @typedoc """ In APNS `:cert`, `:key` and `:pool_size` are required. `:mode` has to be either `:dev` or `:prod` """ @type apns_config :: [{apns_key, String.t() | atom | integer}] @type pool_name :: atom() @type pool_definition :: {pool_name, fcm_config | apns_config} @spec start(atom, list(term)) :: {:ok, pid} def start(_type, _args) do # Logger setup loglevel = Application.get_env(:mongoose_push, :loglevel, :info) set_loglevel(loglevel) # Define workers and child supervisors to be supervised children = children() # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: MongoosePush.Supervisor] Supervisor.start_link(children, opts) end @spec pools_config(MongoosePush.service()) :: [pool_definition] def pools_config(service) do enabled_opt = String.to_atom(~s"#{service}_enabled") service_config = Application.get_env(:mongoose_push, service, nil) pools_config = case Application.get_env(:mongoose_push, enabled_opt, !is_nil(service_config)) do false -> [] true -> service_config end Enum.map(Enum.with_index(pools_config), fn {{pool_name, pool_config}, index} -> normalized_pool_config = pool_config |> generate_pool_id(service, index) |> fix_priv_paths(service) |> ensure_mode() |> ensure_tls_opts() {pool_name, normalized_pool_config} end) end def services do [ fcm: MongoosePush.Service.FCM, apns: MongoosePush.Service.APNS ] end defp children do List.foldl(services(), [], fn {service, module}, acc -> pools_config = pools_config(service) case pools_config do [] -> acc _ -> [module.supervisor_entry(pools_config) | acc] end end) end defp generate_pool_id(config, service, index) do id = String.to_atom("#{service}.pool.ID.#{index}") Keyword.merge(config, id: id) end defp ensure_mode(config) do case config[:mode] do nil -> Keyword.merge(config, mode: mode(config)) _ -> config end end defp fix_priv_paths(config, service) do path_keys = case service do :apns -> [:cert, :key, :p8_file_path] :fcm -> [:appfile] end case service do :fcm -> check_paths(config, path_keys) :apns -> Keyword.update!(config, :auth, fn auth -> check_paths(auth, path_keys) end) end end defp check_paths(config, path_keys) do Enum.map(config, fn {key, value} -> case Enum.member?(path_keys, key) do true -> {key, Application.app_dir(:mongoose_push, value)} false -> {key, value} end end) end defp ensure_tls_opts(config) do case Application.get_env(:mongoose_push, :tls_server_cert_validation, nil) do false -> Keyword.put(config, :tls_opts, []) _ -> config end end defp mode(config), do: config[:mode] || :prod defp set_loglevel(level) do Logger.configure(level: level) # This project uses some Erlang deps, so lager may be present case Code.ensure_loaded?(:lager) do true -> :lager.set_loglevel(:lager_file_backend, level) :lager.set_loglevel(:lager_console_backend, level) false -> :ok end end end
25.872611
99
0.632201
73a0f8d82d4eb0c996caf8851aef0e6f8e058e0d
1,636
ex
Elixir
lib/igwet/scheduler_helper.ex
TheSwanFactory/igwet
0a450686d1d222eb8e39e23ba5d2ea83657862d1
[ "MIT" ]
null
null
null
lib/igwet/scheduler_helper.ex
TheSwanFactory/igwet
0a450686d1d222eb8e39e23ba5d2ea83657862d1
[ "MIT" ]
18
2018-02-25T11:13:46.000Z
2022-03-28T03:43:38.000Z
lib/igwet/scheduler_helper.ex
TheSwanFactory/igwet
0a450686d1d222eb8e39e23ba5d2ea83657862d1
[ "MIT" ]
1
2019-01-04T12:16:47.000Z
2019-01-04T12:16:47.000Z
# Sample email: http://bin.mailgun.net/b1748eea#7jmd defmodule Igwet.Scheduler.Helper do require Logger alias Igwet.Network alias Igwet.Network.SMS alias Igwet.Network.Sendmail alias Igwet.Admin.Mailer @server "https://www.igwet.com" def email_member(message, member, url) do try do Sendmail.to_member(message, member, url) |> Mailer.deliver_now() rescue e in Bamboo.ApiError -> Logger.error("failed.send_email.member\n#{inspect(member)}\n#{inspect(e)}") end end def sms_event_owner(message, event) do if (event.phone) do %{debug: true, to: event.phone, body: message} |> Map.put(:from, System.get_env("PHONE_IGWET")) |> SMS.send_message() end end def email_event(event) do group = Network.get_node!(event.meta.parent_id) message = Sendmail.event_message(group, event) result = for member <- Network.node_members(group) do if (member.email && (member.email =~ "@")) do # https://www.igwet.com/rsvp/for/us.kingsway.0kss_2021-02-21/ernest%40drernie.com email = String.replace(member.email, "@", "%40") url = @server <> "/rsvp/for/" <> event.key <> "/" <> email email_member(message, member, url) member.email end end "#{Enum.count(result)} emails sent\n #{inspect result}" end def email_upcoming(node) do %{name: pattern, about: action} = node event = Network.last_event!(pattern) upcoming = Network.upcoming_event!(event.key) |> Map.put(:about, action) email_event(upcoming) end def test(event) do Logger.warn("RSVP.test: #{event.key}") end end
29.745455
105
0.654034
73a0fccc1ff1ac37bcf087320e2b2453e5a7c3dd
8,309
exs
Elixir
test/gorpo_test/consul_test.exs
dgvncsz0f/exul
ce989851d8237f38a422c16122ca0affa17f9a3b
[ "BSD-2-Clause" ]
3
2017-01-06T03:28:00.000Z
2022-01-04T01:10:13.000Z
test/gorpo_test/consul_test.exs
dgvncsz0f/exul
ce989851d8237f38a422c16122ca0affa17f9a3b
[ "BSD-2-Clause" ]
2
2017-11-28T17:13:33.000Z
2017-11-28T19:54:28.000Z
test/gorpo_test/consul_test.exs
dgvncsz0f/exul
ce989851d8237f38a422c16122ca0affa17f9a3b
[ "BSD-2-Clause" ]
1
2017-11-28T14:20:33.000Z
2017-11-28T14:20:33.000Z
defmodule Gorpo.ConsulTest do use ExUnit.Case, async: true test "service_register" do driver = Gorpo.Drivers.Echo.success([status: 200]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} service = %Gorpo.Service{id: "foobar", name: "foobar", check: %Gorpo.Check{}} {:ok, reply} = Gorpo.Consul.service_register(agent, service) assert "endpoint/v1/agent/service/register" == reply[:request][:url] assert Gorpo.Service.dump(service) == Poison.decode!(reply[:request][:payload]) assert [params: [token: "token"]] == reply[:request][:options] assert :put == reply[:request][:method] end test "service_deregister" do driver = Gorpo.Drivers.Echo.success([status: 200]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} {:ok, reply} = Gorpo.Consul.service_deregister(agent, "foobar") assert "endpoint/v1/agent/service/deregister/foobar" == reply[:request][:url] assert [params: [token: "token"]] == reply[:request][:options] assert :post == reply[:request][:method] end test "check_update" do driver = Gorpo.Drivers.Echo.success([status: 200]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} status = Enum.random([Gorpo.Status.passing, Gorpo.Status.warning, Gorpo.Status.critical]) service = %Gorpo.Service{id: "foobar", name: "foobar", check: %Gorpo.Check{}} check_id = Gorpo.Service.check_id(service) {:ok, reply} = Gorpo.Consul.check_update(agent, service, status) assert "endpoint/v1/agent/check/update/#{check_id}" == reply[:request][:url] assert Gorpo.Status.dump(status) == Poison.decode!(reply[:request][:payload]) assert [params: [token: "token"]] == reply[:request][:options] assert :put == reply[:request][:method] end test "empty services" do driver = Gorpo.Drivers.Echo.success([status: 200, payload: "[]"]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} {:ok, reply} = Gorpo.Consul.services(agent, "foobar") assert [] == reply end test "reply services with no checks" do node = %Gorpo.Node{id: "consul", address: "localhost"} service = %Gorpo.Service{id: "foobar", name: "foobar", port: 10, address: "localhost", tags: ["foo", "bar"]} payload = Poison.encode!([%{"Node" => node, "Service" => service, "Checks" => [] }]) driver = Gorpo.Drivers.Echo.success([status: 200, payload: payload]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} {:ok, reply} = Gorpo.Consul.services(agent, "foobar") assert [{node, service, nil}] == reply end test "use node address if service addresses is not set" do node = %Gorpo.Node{id: "consul", address: "localhost"} service = %Gorpo.Service{id: "foobar", name: "foobar", port: 10, address: "", tags: ["foo", "bar"]} payload = Poison.encode!([%{"Node" => node, "Service" => service, "Checks" => [] }]) driver = Gorpo.Drivers.Echo.success([status: 200, payload: payload]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} {:ok, reply} = Gorpo.Consul.services(agent, "foobar") assert [{node, %{service| address: node.address}, nil}] == reply end test "single service and a single check" do node = %Gorpo.Node{id: "consul", address: "localhost"} status = %Gorpo.Status{status: Enum.random([:passing, :warning, :critical])} service = %Gorpo.Service{id: "foobar", name: "foobar", address: "localhost"} payload = Poison.encode!([%{"Node" => node, "Service" => service, "Checks" => [%{"CheckID" => Gorpo.Service.check_id(service), "Status" => status.status}] }]) driver = Gorpo.Drivers.Echo.success([status: 200, payload: payload]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} {:ok, reply} = Gorpo.Consul.services(agent, "foobar") assert [{node, service, status}] == reply end test "multiple services and checks" do node = %Gorpo.Node{id: "consul", address: "localhost"} service_0 = %Gorpo.Service{id: "foobar_0", name: "foobar", address: "localhost"} service_1 = %Gorpo.Service{id: "foobar_1", name: "foobar", address: "localhost"} service_2 = %Gorpo.Service{id: "foobar_2", name: "foobar", address: "localhost"} status_0 = %Gorpo.Status{status: :passing} status_1 = %Gorpo.Status{status: :warning} status_2 = %Gorpo.Status{status: :critical} payload = Poison.encode!([%{"Node" => node, "Service" => service_0, "Checks" => [%{"CheckID" => "aaa"}, %{"CheckID" => Gorpo.Service.check_id(service_0), "Status" => status_0.status}]}, %{"Node" => node, "Service" => service_1, "Checks" => [%{"CheckID" => "bbb"}, %{"CheckID" => Gorpo.Service.check_id(service_1), "Status" => status_1.status}]}, %{"Node" => node, "Service" => service_2, "Checks" => [%{"CheckID" => "ccc"}, %{"CheckID" => Gorpo.Service.check_id(service_2), "Status" => status_2.status}]}]) driver = Gorpo.Drivers.Echo.success([status: 200, payload: payload]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} {:ok, reply} = Gorpo.Consul.services(agent, "foobar") assert [{node, service_0, status_0}, {node, service_1, status_1}, {node, service_2, status_2}] == reply end test "session create " do payload = Poison.encode!(%{"ID" => "foobar"}) driver = Gorpo.Drivers.Echo.success([status: 200, payload: payload]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} {:ok, reply} = Gorpo.Consul.session_create(agent) assert "foobar" == reply end test "session create (failure case)" do driver = Gorpo.Drivers.Echo.success([status: 500]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} assert {:error, _} = Gorpo.Consul.session_create(agent) end test "session renew" do driver = Gorpo.Drivers.Echo.success([status: 200]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} assert :ok == Gorpo.Consul.session_renew(agent, "foobar") end test "session renew (failure case)" do driver = Gorpo.Drivers.Echo.success([status: 500]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} assert {:error, _} = Gorpo.Consul.session_renew(agent, "foobar") end test "session destroy" do driver = Gorpo.Drivers.Echo.success([status: 200]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} assert :ok == Gorpo.Consul.session_destroy(agent, "foobar") end test "session destroy (failure case)" do driver = Gorpo.Drivers.Echo.failure(:no_reason) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} assert {:error, _} = Gorpo.Consul.session_destroy(agent, "foobar") end test "session info" do payload = %{"ID" => "foobar"} driver = Gorpo.Drivers.Echo.success([status: 200, payload: Poison.encode!([payload])]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} assert {:ok, payload, %{}} == Gorpo.Consul.session_info(agent, "foobar") end test "session info (not found)" do driver = Gorpo.Drivers.Echo.success([status: 200, payload: "[]"]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} assert {:error, :not_found} == Gorpo.Consul.session_info(agent, "foobar") end test "session info (other errors)" do driver = Gorpo.Drivers.Echo.success([status: 500]) agent = %Gorpo.Consul{endpoint: "endpoint", token: "token", driver: driver} assert {:error, _} = Gorpo.Consul.session_info(agent, "foobar") end end
45.404372
153
0.607414
73a105dd5f85e5436c633a47b235c113f1468d77
282
ex
Elixir
lib/types.ex
alexdeleon/focus
9212e552b725053d0763cee80baf4882c1f80b99
[ "BSD-2-Clause" ]
null
null
null
lib/types.ex
alexdeleon/focus
9212e552b725053d0763cee80baf4882c1f80b99
[ "BSD-2-Clause" ]
null
null
null
lib/types.ex
alexdeleon/focus
9212e552b725053d0763cee80baf4882c1f80b99
[ "BSD-2-Clause" ]
null
null
null
defmodule Focus.Types do @moduledoc """ Shared elements for the Focus modules. """ @type product :: map | struct | tuple @type sum :: list @type traversable :: product | sum @type maybe :: {:ok, any} | {:error, any} @type optic :: Lens.t end
25.636364
49
0.574468
73a10a35baa547a35e7bcb0965e5060286ea4b3d
1,105
exs
Elixir
mix.exs
optoro/worker_tracker
0a9381cbb596edd5948bbad82dcde409d5f6ab5b
[ "MIT" ]
1
2020-02-06T17:15:44.000Z
2020-02-06T17:15:44.000Z
mix.exs
optoro/worker_tracker
0a9381cbb596edd5948bbad82dcde409d5f6ab5b
[ "MIT" ]
null
null
null
mix.exs
optoro/worker_tracker
0a9381cbb596edd5948bbad82dcde409d5f6ab5b
[ "MIT" ]
1
2021-04-01T13:29:18.000Z
2021-04-01T13:29:18.000Z
defmodule WorkerTracker.MixProject do use Mix.Project def project do [ app: :worker_tracker, version: "0.4.1", elixir: "~> 1.9", start_permanent: Mix.env() == :prod, description: description(), package: package(), deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger, :redix], mod: {WorkerTracker, []} ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:redix, ">= 0.0.0"}, {:dialyxir, "~> 0.5", only: [:dev], runtime: false}, {:ex_doc, ">= 0.0.0", only: :dev, runtime: false} ] end defp description() do "Track system processes across multiple instances over ssh connections" end defp package() do [ maintainers: ["Jeff Gillis", "Spencer Gilbert", "Anthony Johnston", "Venky Jeyanthilal"], files: ~w(config lib test .formatter.exs mix.exs README.md), licenses: ["MIT"], links: %{"GitHub" => "https://github.com/optoro/worker_tracker"} ] end end
24.021739
95
0.59457
73a14f6ddd77e9fd93ec5a2b7ecf404904d74f3f
5,488
ex
Elixir
lib/livebook/application.ex
oo6/livebook
0e059f4f840a56c122266a62cc8fdb3b97920efc
[ "Apache-2.0" ]
null
null
null
lib/livebook/application.ex
oo6/livebook
0e059f4f840a56c122266a62cc8fdb3b97920efc
[ "Apache-2.0" ]
null
null
null
lib/livebook/application.ex
oo6/livebook
0e059f4f840a56c122266a62cc8fdb3b97920efc
[ "Apache-2.0" ]
null
null
null
defmodule Livebook.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do ensure_local_filesystem!() ensure_distribution!() validate_hostname_resolution!() set_cookie() children = [ # Start the Telemetry supervisor LivebookWeb.Telemetry, # Start the PubSub system {Phoenix.PubSub, name: Livebook.PubSub}, # Start the storage module Livebook.Storage.current(), # Periodid measurement of system resources Livebook.SystemResources, # Start the tracker server on this node {Livebook.Tracker, pubsub_server: Livebook.PubSub}, # Start the supervisor dynamically managing sessions {DynamicSupervisor, name: Livebook.SessionSupervisor, strategy: :one_for_one}, # Start the server responsible for associating files with sessions Livebook.Session.FileGuard, # Start the Node Pool for managing node names Livebook.Runtime.NodePool, # Start the unique task dependencies Livebook.UniqueTask, # Start the Endpoint (http/https) # We skip the access url as we do our own logging below {LivebookWeb.Endpoint, log_access_url: false} ] ++ app_specs() opts = [strategy: :one_for_one, name: Livebook.Supervisor] with {:ok, _} = result <- Supervisor.start_link(children, opts) do clear_env_vars() display_startup_info() result end end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do LivebookWeb.Endpoint.config_change(changed, removed) :ok end defp ensure_local_filesystem!() do home = Livebook.Config.home() |> Livebook.FileSystem.Utils.ensure_dir_path() local_filesystem = Livebook.FileSystem.Local.new(default_path: home) :persistent_term.put(:livebook_local_filesystem, local_filesystem) end defp ensure_distribution!() do unless Node.alive?() do case System.cmd("epmd", ["-daemon"]) do {_, 0} -> :ok _ -> Livebook.Config.abort!(""" could not start epmd (Erlang Port Mapper Driver). Livebook uses epmd to \ talk to different runtimes. You may have to start epmd explicitly by calling: epmd -daemon Or by calling: elixir --sname test -e "IO.puts node()" Then you can try booting Livebook again """) end {type, name} = get_node_type_and_name() case Node.start(name, type) do {:ok, _} -> :ok {:error, reason} -> Livebook.Config.abort!("could not start distributed node: #{inspect(reason)}") end end end import Record defrecordp :hostent, Record.extract(:hostent, from_lib: "kernel/include/inet.hrl") # See https://github.com/livebook-dev/livebook/issues/302 defp validate_hostname_resolution!() do unless Livebook.Config.longname() do hostname = Livebook.Utils.node_host() |> to_charlist() case :inet.gethostbyname(hostname) do {:error, :nxdomain} -> invalid_hostname!("your hostname \"#{hostname}\" does not resolve to an IP address") # We only try the first address, so that's the one we validate. {:ok, hostent(h_addrtype: :inet, h_addr_list: [address | _])} -> unless inet_loopback?(address) or inet_if?(address) do invalid_hostname!( "your hostname \"#{hostname}\" does not resolve to a loopback address (127.0.0.0/8)" ) end _ -> :ok end end end defp inet_loopback?(address) do match?({127, _, _, _}, address) end defp inet_if?(address) do case :inet.getifaddrs() do {:ok, addrs} -> Enum.any?(addrs, fn {_name, flags} -> {:addr, address} in flags end) _ -> false end end @spec invalid_hostname!(String.t()) :: no_return() defp invalid_hostname!(prelude) do Livebook.Config.abort!(""" #{prelude}, which indicates something wrong in your OS configuration. Make sure your computer's name resolves locally or start Livebook using a long distribution name. If you are using Livebook's CLI, you can: livebook server --name [email protected] If you are running it from source, do instead: MIX_ENV=prod elixir --name [email protected] -S mix phx.server """) end defp set_cookie() do cookie = Application.fetch_env!(:livebook, :cookie) Node.set_cookie(cookie) end defp get_node_type_and_name() do Application.get_env(:livebook, :node) || {:shortnames, random_short_name()} end defp random_short_name() do :"livebook_#{Livebook.Utils.random_short_id()}" end defp display_startup_info() do if Phoenix.Endpoint.server?(:livebook, LivebookWeb.Endpoint) do IO.puts("[Livebook] Application running at #{LivebookWeb.Endpoint.access_url()}") end end defp clear_env_vars() do for {var, _} <- System.get_env(), config_env_var?(var) do System.delete_env(var) end end defp config_env_var?("LIVEBOOK_" <> _), do: true defp config_env_var?("RELEASE_" <> _), do: true defp config_env_var?(_), do: false if Mix.target() == :app do defp app_specs, do: [LivebookApp] else defp app_specs, do: [] end end
29.664865
143
0.649235
73a172897b7b0206cfcdeb1d272ccfe84abb3f79
1,993
exs
Elixir
test/mix/tasks/phoenix/pow.phoenix.gen.templates_test.exs
patrickbiermann/pow
ebc2ac7d6e15961dac4be38091ff75dae0d26554
[ "MIT" ]
1
2021-06-25T10:36:01.000Z
2021-06-25T10:36:01.000Z
test/mix/tasks/phoenix/pow.phoenix.gen.templates_test.exs
patrickbiermann/pow
ebc2ac7d6e15961dac4be38091ff75dae0d26554
[ "MIT" ]
null
null
null
test/mix/tasks/phoenix/pow.phoenix.gen.templates_test.exs
patrickbiermann/pow
ebc2ac7d6e15961dac4be38091ff75dae0d26554
[ "MIT" ]
1
2020-07-13T01:11:17.000Z
2020-07-13T01:11:17.000Z
defmodule Mix.Tasks.Pow.Phoenix.Gen.TemplatesTest do use Pow.Test.Mix.TestCase alias Mix.Tasks.Pow.Phoenix.Gen.Templates @tmp_path Path.join(["tmp", inspect(Templates)]) @expected_msg "Pow Phoenix templates and views has been generated." @expected_template_files %{ "registration" => ["edit.html.eex", "new.html.eex"], "session" => ["new.html.eex"] } @expected_views Map.keys(@expected_template_files) setup do File.rm_rf!(@tmp_path) File.mkdir_p!(@tmp_path) :ok end test "generates templates" do File.cd!(@tmp_path, fn -> Templates.run([]) templates_path = Path.join(["lib", "pow_web", "templates", "pow"]) expected_dirs = Map.keys(@expected_template_files) assert ls(templates_path) == expected_dirs for {dir, expected_files} <- @expected_template_files do files = templates_path |> Path.join(dir) |> ls() assert files == expected_files end views_path = Path.join(["lib", "pow_web", "views", "pow"]) expected_view_files = Enum.map(@expected_views, &"#{&1}_view.ex") view_content = views_path |> Path.join("session_view.ex") |> File.read!() assert ls(views_path) == expected_view_files assert view_content =~ "defmodule PowWeb.Pow.SessionView do" assert view_content =~ "use PowWeb, :view" assert_received {:mix_shell, :info, [@expected_msg <> msg]} assert msg =~ "config :pow, :pow," assert msg =~ "web_module: PowWeb" end) end describe "with `:web_module` environment config set" do setup do Application.put_env(:pow, :pow, web_module: PowWeb) on_exit(fn -> Application.delete_env(:pow, :pow) end) end test "doesn't print web_module instructions" do File.cd!(@tmp_path, fn -> Templates.run([]) refute_received {:mix_shell, :info, [@expected_msg <> _msg]} end) end end defp ls(path), do: path |> File.ls!() |> Enum.sort() end
28.884058
86
0.636729
73a178934e75eddd4d27fc82a4c4e88f6156db89
1,901
exs
Elixir
test/plausible_web/controllers/api/stats_controller/pages_test.exs
samuel-p/analytics
5d35bab9c6c2aafc556659f64e4213848a37ed8a
[ "MIT" ]
null
null
null
test/plausible_web/controllers/api/stats_controller/pages_test.exs
samuel-p/analytics
5d35bab9c6c2aafc556659f64e4213848a37ed8a
[ "MIT" ]
null
null
null
test/plausible_web/controllers/api/stats_controller/pages_test.exs
samuel-p/analytics
5d35bab9c6c2aafc556659f64e4213848a37ed8a
[ "MIT" ]
null
null
null
defmodule PlausibleWeb.Api.StatsController.PagesTest do use PlausibleWeb.ConnCase import Plausible.TestUtils describe "GET /api/stats/:domain/pages" do setup [:create_user, :log_in, :create_site] test "returns top pages sources by pageviews", %{conn: conn, site: site} do conn = get(conn, "/api/stats/#{site.domain}/pages?period=day&date=2019-01-01") assert json_response(conn, 200) == [ %{"count" => 2, "name" => "/"}, %{"count" => 2, "name" => "/register"}, %{"count" => 1, "name" => "/contact"}, %{"count" => 1, "name" => "/irrelevant"} ] end test "calculates bounce rate and unique visitors for pages", %{conn: conn, site: site} do conn = get( conn, "/api/stats/#{site.domain}/pages?period=day&date=2019-01-01&include=bounce_rate,unique_visitors" ) assert json_response(conn, 200) == [ %{"bounce_rate" => 33.0, "count" => 2, "unique_visitors" => 2, "name" => "/"}, %{ "bounce_rate" => nil, "count" => 2, "unique_visitors" => 2, "name" => "/register" }, %{ "bounce_rate" => nil, "count" => 1, "unique_visitors" => 1, "name" => "/contact" }, %{ "bounce_rate" => nil, "count" => 1, "unique_visitors" => 1, "name" => "/irrelevant" } ] end test "returns top pages in realtime report", %{conn: conn, site: site} do conn = get(conn, "/api/stats/#{site.domain}/pages?period=realtime") assert json_response(conn, 200) == [ %{"count" => 3, "name" => "/"} ] end end end
32.775862
106
0.46344
73a18be7d573a51b02b1275362ac9050116cf4a5
3,214
ex
Elixir
clients/street_view_publish/lib/google_api/street_view_publish/v1/model/operation.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/street_view_publish/lib/google_api/street_view_publish/v1/model/operation.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/street_view_publish/lib/google_api/street_view_publish/v1/model/operation.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.StreetViewPublish.V1.Model.Operation do @moduledoc """ This resource represents a long-running operation that is the result of a network API call. ## Attributes * `done` (*type:* `boolean()`, *default:* `nil`) - If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. * `error` (*type:* `GoogleApi.StreetViewPublish.V1.Model.Status.t`, *default:* `nil`) - The error result of the operation in case of failure or cancellation. * `metadata` (*type:* `map()`, *default:* `nil`) - Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. * `name` (*type:* `String.t`, *default:* `nil`) - The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. * `response` (*type:* `map()`, *default:* `nil`) - The normal response of the operation in case of success. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :done => boolean() | nil, :error => GoogleApi.StreetViewPublish.V1.Model.Status.t() | nil, :metadata => map() | nil, :name => String.t() | nil, :response => map() | nil } field(:done) field(:error, as: GoogleApi.StreetViewPublish.V1.Model.Status) field(:metadata, type: :map) field(:name) field(:response, type: :map) end defimpl Poison.Decoder, for: GoogleApi.StreetViewPublish.V1.Model.Operation do def decode(value, options) do GoogleApi.StreetViewPublish.V1.Model.Operation.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.StreetViewPublish.V1.Model.Operation do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
54.474576
543
0.724953
73a19ce7290e7186019a3e983dd1b260cee3647a
283
ex
Elixir
lib/phoenix_container_example.ex
wwaldner-amtelco/phoenix_container_example
aeee424b40f444fe6bbfeab4d57b78d201397701
[ "Apache-2.0" ]
19
2020-07-21T06:03:36.000Z
2022-03-21T22:35:22.000Z
lib/phoenix_container_example.ex
wwaldner-amtelco/phoenix_container_example
aeee424b40f444fe6bbfeab4d57b78d201397701
[ "Apache-2.0" ]
1
2022-03-08T10:26:55.000Z
2022-03-08T10:26:55.000Z
lib/phoenix_container_example.ex
wwaldner-amtelco/phoenix_container_example
aeee424b40f444fe6bbfeab4d57b78d201397701
[ "Apache-2.0" ]
1
2022-02-09T01:25:09.000Z
2022-02-09T01:25:09.000Z
defmodule PhoenixContainerExample do @moduledoc """ PhoenixContainerExample keeps the contexts that define your domain and business logic. Contexts are also responsible for managing your data, regardless if it comes from the database, an external API or others. """ end
28.3
68
0.780919
73a1ad3c20af6ffb2fd6faa25030e1e350bc4bde
5,314
exs
Elixir
backend/test/edgehog_web/schema/mutation/update_hardware_type_test.exs
harlem88/edgehog
7a278d119c3d592431fdbba406207376e194f7eb
[ "Apache-2.0" ]
null
null
null
backend/test/edgehog_web/schema/mutation/update_hardware_type_test.exs
harlem88/edgehog
7a278d119c3d592431fdbba406207376e194f7eb
[ "Apache-2.0" ]
null
null
null
backend/test/edgehog_web/schema/mutation/update_hardware_type_test.exs
harlem88/edgehog
7a278d119c3d592431fdbba406207376e194f7eb
[ "Apache-2.0" ]
null
null
null
# # This file is part of Edgehog. # # Copyright 2021 SECO Mind Srl # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # defmodule EdgehogWeb.Schema.Mutation.UpdateHardwareTypeTest do use EdgehogWeb.ConnCase alias Edgehog.Devices alias Edgehog.Devices.HardwareType describe "updateHardwareType field" do import Edgehog.DevicesFixtures setup do {:ok, hardware_type: hardware_type_fixture()} end @query """ mutation UpdateHardwareType($input: UpdateHardwareTypeInput!) { updateHardwareType(input: $input) { hardwareType { id name handle partNumbers } } } """ test "updates hardware type with valid data", %{ conn: conn, api_path: api_path, hardware_type: hardware_type } do name = "Foobaz" handle = "foobaz" part_number = "12345/Z" id = Absinthe.Relay.Node.to_global_id(:hardware_type, hardware_type.id, EdgehogWeb.Schema) variables = %{ input: %{ hardware_type_id: id, name: name, handle: handle, part_numbers: [part_number] } } conn = post(conn, api_path, query: @query, variables: variables) assert %{ "data" => %{ "updateHardwareType" => %{ "hardwareType" => %{ "id" => ^id, "name" => ^name, "handle" => ^handle, "partNumbers" => [^part_number] } } } } = assert(json_response(conn, 200)) assert {:ok, %HardwareType{name: ^name, handle: ^handle}} = Devices.fetch_hardware_type(hardware_type.id) end test "updates hardware type with partial data", %{ conn: conn, api_path: api_path, hardware_type: hardware_type } do %HardwareType{name: initial_name, handle: initial_handle} = hardware_type name = "Foobaz" part_number = "12345/Z" id = Absinthe.Relay.Node.to_global_id(:hardware_type, hardware_type.id, EdgehogWeb.Schema) variables = %{ input: %{ hardware_type_id: id, part_numbers: [part_number] } } conn = post(conn, api_path, query: @query, variables: variables) assert %{ "data" => %{ "updateHardwareType" => %{ "hardwareType" => %{ "id" => ^id, "name" => ^initial_name, "handle" => ^initial_handle, "partNumbers" => [^part_number] } } } } = assert(json_response(conn, 200)) assert {:ok, %HardwareType{name: ^initial_name, handle: ^initial_handle}} = Devices.fetch_hardware_type(hardware_type.id) variables = %{ input: %{ hardware_type_id: id, name: name } } conn = post(conn, api_path, query: @query, variables: variables) assert %{ "data" => %{ "updateHardwareType" => %{ "hardwareType" => %{ "id" => ^id, "name" => ^name, "handle" => ^initial_handle, "partNumbers" => [^part_number] } } } } = assert(json_response(conn, 200)) assert {:ok, %HardwareType{name: ^name, handle: ^initial_handle}} = Devices.fetch_hardware_type(hardware_type.id) end test "fails with invalid data", %{ conn: conn, api_path: api_path, hardware_type: hardware_type } do id = Absinthe.Relay.Node.to_global_id(:hardware_type, hardware_type.id, EdgehogWeb.Schema) variables = %{ input: %{ hardware_type_id: id, name: nil, handle: nil, part_numbers: [] } } conn = post(conn, api_path, query: @query, variables: variables) assert %{"errors" => _} = assert(json_response(conn, 200)) end test "fails with non-existing id", %{conn: conn, api_path: api_path} do name = "Foobaz" handle = "foobaz" part_number = "12345/Z" id = Absinthe.Relay.Node.to_global_id(:hardware_type, 10_000_000, EdgehogWeb.Schema) variables = %{ input: %{ hardware_type_id: id, name: name, handle: handle, part_numbers: [part_number] } } conn = post(conn, api_path, query: @query, variables: variables) assert %{"errors" => [%{"code" => "not_found", "status_code" => 404}]} = assert(json_response(conn, 200)) end end end
27.968421
96
0.542153
73a1c9e0ab4eb2068d12f3476596befdc6536831
1,364
exs
Elixir
test/event_queues_test.exs
cenurv/event_stream
cbe8f5702551435dc94eee6833df8cf9ac3084ce
[ "Apache-2.0" ]
5
2017-01-15T13:31:15.000Z
2020-09-23T19:40:27.000Z
test/event_queues_test.exs
cenurv/event_stream
cbe8f5702551435dc94eee6833df8cf9ac3084ce
[ "Apache-2.0" ]
null
null
null
test/event_queues_test.exs
cenurv/event_stream
cbe8f5702551435dc94eee6833df8cf9ac3084ce
[ "Apache-2.0" ]
1
2021-03-04T21:49:14.000Z
2021-03-04T21:49:14.000Z
defmodule EventQueuesTest do use ExUnit.Case test "Test Sync Notify" do SampleQueue.announce_sync(category: :ticket, name: :update, data: %{id: 15, pid: self()}) receive do event -> assert event.category == :ticket assert event.name == :update assert event.data.id == 15 after 500 -> assert "Did not receive response." == true end end test "Test Async Notify" do SampleQueue.announce(category: :ticket, name: :update, data: %{id: 123456, pid: self()}) receive do event -> assert event.category == :ticket assert event.name == :update assert event.data.id == 123456 after 500 -> assert "Did not receive response." == true end end test "Test Matching" do SampleQueue.announce_sync(category: :ticket, name: :insert, data: %{id: 15, pid: self()}) receive do _ -> assert "Event should not arrive." == true after 100 -> nil end end test "Announcer and handler" do SampleAnnouncer.execute_event assert true == SampleAnnouncer.has_after_insert? assert false == SampleAnnouncer.has_after_update? receive do event -> assert event.category == :test assert event.name == :after_insert after 500 -> assert "Did not receive response." == true end end end
23.929825
93
0.618035
73a1e6f71509d26541f5fe6c3d432ab86937c718
1,535
ex
Elixir
lib/demo_web/views/error_helpers.ex
jefk/phoenix_live_view
5ef754b4246d3ba5aeeceb3875eda116bddfa834
[ "MIT" ]
null
null
null
lib/demo_web/views/error_helpers.ex
jefk/phoenix_live_view
5ef754b4246d3ba5aeeceb3875eda116bddfa834
[ "MIT" ]
null
null
null
lib/demo_web/views/error_helpers.ex
jefk/phoenix_live_view
5ef754b4246d3ba5aeeceb3875eda116bddfa834
[ "MIT" ]
null
null
null
defmodule DemoWeb.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do Enum.map(Keyword.get_values(form.errors, field), fn error -> content_tag(:span, translate_error(error), class: "help-block", data: [phx_error_for: input_id(form, field)] ) end) end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # When using gettext, we typically pass the strings we want # to translate as a static argument: # # # Translate "is invalid" in the "errors" domain # dgettext "errors", "is invalid" # # # Translate the number of files with plural rules # dngettext "errors", "1 file", "%{count} files", count # # Because the error messages we show in our forms and APIs # are defined inside Ecto, we need to translate them dynamically. # This requires us to call the Gettext module passing our gettext # backend as first argument. # # Note we use the "errors" domain, which means translations # should be written to the errors.po file. The :count option is # set by Ecto and indicates we should also apply plural rules. if count = opts[:count] do Gettext.dngettext(DemoWeb.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(DemoWeb.Gettext, "errors", msg, opts) end end end
31.979167
73
0.661238
73a1f799b243e9f65c212f1e294a1b632c46e67a
267
ex
Elixir
lib/quickstart/friend/friend.ex
LosEagle/elixir-graphql-sqlite-quickstart
63e0c15e8adf8e527ac232ac4966b758cede141e
[ "MIT" ]
null
null
null
lib/quickstart/friend/friend.ex
LosEagle/elixir-graphql-sqlite-quickstart
63e0c15e8adf8e527ac232ac4966b758cede141e
[ "MIT" ]
null
null
null
lib/quickstart/friend/friend.ex
LosEagle/elixir-graphql-sqlite-quickstart
63e0c15e8adf8e527ac232ac4966b758cede141e
[ "MIT" ]
null
null
null
defmodule Quickstart.Friend do use Ecto.Schema schema "friends" do field(:first_name, :string) field(:last_name, :string) end def changeset(friend, params \\ %{}) do friend |> Ecto.Changeset.cast(params, [:first_name, :last_name]) end end
19.071429
61
0.670412
73a249dac0dd652443b9ff715d633dafacedb169
315
exs
Elixir
maze/mix.exs
ChrisWilding/Advent-of-Code-2017
62284eec7a0e924230d82765d9ae17e52bc52ca8
[ "Apache-2.0" ]
1
2019-05-14T05:10:34.000Z
2019-05-14T05:10:34.000Z
maze/mix.exs
ChrisWilding/Advent-of-Code-2017
62284eec7a0e924230d82765d9ae17e52bc52ca8
[ "Apache-2.0" ]
null
null
null
maze/mix.exs
ChrisWilding/Advent-of-Code-2017
62284eec7a0e924230d82765d9ae17e52bc52ca8
[ "Apache-2.0" ]
null
null
null
defmodule Maze.Mixfile do use Mix.Project def project do [ app: :maze, version: "0.1.0", elixir: "~> 1.5", start_permanent: Mix.env == :prod, deps: deps() ] end def application do [ extra_applications: [:logger] ] end defp deps do [] end end
13.125
40
0.530159
73a24a845bf878887359de9b2e12d608bdc1bbf1
499
ex
Elixir
test/support/live_views/host.ex
gaslight/live_element
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
[ "MIT" ]
null
null
null
test/support/live_views/host.ex
gaslight/live_element
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
[ "MIT" ]
null
null
null
test/support/live_views/host.ex
gaslight/live_element
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
[ "MIT" ]
null
null
null
defmodule LiveElementTest.HostLive do use LiveElement alias LiveElementTest.Router.Helpers, as: Routes def handle_params(_params, uri, socket) do {:noreply, assign(socket, :uri, uri)} end def render(assigns) do ~H""" URI: <%= @uri %> LiveAction: <%= @live_action %> <%= live_patch "Path", id: "path", to: Routes.host_path(@socket, :path) %> <%= live_patch "Full", id: "full", to: "https://app.example.com" <> Routes.host_path(@socket, :full) %> """ end end
27.722222
107
0.631263
73a2597348d33929fc2330e18135d673c75dda08
7,590
ex
Elixir
clients/data_catalog/lib/google_api/data_catalog/v1beta1/model/google_cloud_datacatalog_v1beta1_entry.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/data_catalog/lib/google_api/data_catalog/v1beta1/model/google_cloud_datacatalog_v1beta1_entry.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/data_catalog/lib/google_api/data_catalog/v1beta1/model/google_cloud_datacatalog_v1beta1_entry.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.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1Entry do @moduledoc """ Entry Metadata. A Data Catalog Entry resource represents another resource in Google Cloud Platform (such as a BigQuery dataset or a Pub/Sub topic), or outside of Google Cloud Platform. Clients can use the `linked_resource` field in the Entry resource to refer to the original resource ID of the source system. An Entry resource contains resource details, such as its schema. An Entry can also be used to attach flexible metadata, such as a Tag. ## Attributes * `bigqueryDateShardedSpec` (*type:* `GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1BigQueryDateShardedSpec.t`, *default:* `nil`) - Specification for a group of BigQuery tables with name pattern `[prefix]YYYYMMDD`. Context: https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding. * `bigqueryTableSpec` (*type:* `GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1BigQueryTableSpec.t`, *default:* `nil`) - Specification that applies to a BigQuery table. This is only valid on entries of type `TABLE`. * `description` (*type:* `String.t`, *default:* `nil`) - Entry description, which can consist of several sentences or paragraphs that describe entry contents. Default value is an empty string. * `displayName` (*type:* `String.t`, *default:* `nil`) - Display information such as title and description. A short name to identify the entry, for example, "Analytics Data - Jan 2011". Default value is an empty string. * `gcsFilesetSpec` (*type:* `GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1GcsFilesetSpec.t`, *default:* `nil`) - Specification that applies to a Cloud Storage fileset. This is only valid on entries of type FILESET. * `integratedSystem` (*type:* `String.t`, *default:* `nil`) - Output only. This field indicates the entry's source system that Data Catalog integrates with, such as BigQuery or Pub/Sub. * `linkedResource` (*type:* `String.t`, *default:* `nil`) - The resource this metadata entry refers to. For Google Cloud Platform resources, `linked_resource` is the [full name of the resource](https://cloud.google.com/apis/design/resource_names#full_resource_name). For example, the `linked_resource` for a table resource from BigQuery is: * //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId Output only when Entry is of type in the EntryType enum. For entries with user_specified_type, this field is optional and defaults to an empty string. * `name` (*type:* `String.t`, *default:* `nil`) - Output only. The Data Catalog resource name of the entry in URL format. Example: * projects/{project_id}/locations/{location}/entryGroups/{entry_group_id}/entries/{entry_id} Note that this Entry and its child resources may not actually be stored in the location in this name. * `schema` (*type:* `GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1Schema.t`, *default:* `nil`) - Schema of the entry. An entry might not have any schema attached to it. * `sourceSystemTimestamps` (*type:* `GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SystemTimestamps.t`, *default:* `nil`) - Output only. Timestamps about the underlying resource, not about this Data Catalog entry. Output only when Entry is of type in the EntryType enum. For entries with user_specified_type, this field is optional and defaults to an empty timestamp. * `type` (*type:* `String.t`, *default:* `nil`) - The type of the entry. Only used for Entries with types in the EntryType enum. * `userSpecifiedSystem` (*type:* `String.t`, *default:* `nil`) - This field indicates the entry's source system that Data Catalog does not integrate with. `user_specified_system` strings must begin with a letter or underscore and can only contain letters, numbers, and underscores; are case insensitive; must be at least 1 character and at most 64 characters long. * `userSpecifiedType` (*type:* `String.t`, *default:* `nil`) - Entry type if it does not fit any of the input-allowed values listed in `EntryType` enum above. When creating an entry, users should check the enum values first, if nothing matches the entry to be created, then provide a custom value, for example "my_special_type". `user_specified_type` strings must begin with a letter or underscore and can only contain letters, numbers, and underscores; are case insensitive; must be at least 1 character and at most 64 characters long. Currently, only FILESET enum value is allowed. All other entries created through Data Catalog must use `user_specified_type`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :bigqueryDateShardedSpec => GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1BigQueryDateShardedSpec.t(), :bigqueryTableSpec => GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1BigQueryTableSpec.t(), :description => String.t(), :displayName => String.t(), :gcsFilesetSpec => GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1GcsFilesetSpec.t(), :integratedSystem => String.t(), :linkedResource => String.t(), :name => String.t(), :schema => GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1Schema.t(), :sourceSystemTimestamps => GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SystemTimestamps.t(), :type => String.t(), :userSpecifiedSystem => String.t(), :userSpecifiedType => String.t() } field(:bigqueryDateShardedSpec, as: GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1BigQueryDateShardedSpec ) field(:bigqueryTableSpec, as: GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1BigQueryTableSpec ) field(:description) field(:displayName) field(:gcsFilesetSpec, as: GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1GcsFilesetSpec ) field(:integratedSystem) field(:linkedResource) field(:name) field(:schema, as: GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1Schema) field(:sourceSystemTimestamps, as: GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SystemTimestamps ) field(:type) field(:userSpecifiedSystem) field(:userSpecifiedType) end defimpl Poison.Decoder, for: GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1Entry do def decode(value, options) do GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1Entry.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1Entry do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
73.68932
666
0.760474
73a27a0aa92afd5e8d18f69626194d9d607270fe
1,076
exs
Elixir
mix.exs
swelham/social_parser
fd8b6f9376474632c01fd2d6c7cabb17d3b3b1d1
[ "MIT" ]
13
2016-11-03T11:03:14.000Z
2021-03-13T00:24:36.000Z
mix.exs
swelham/social_parser
fd8b6f9376474632c01fd2d6c7cabb17d3b3b1d1
[ "MIT" ]
4
2016-11-09T09:38:03.000Z
2019-03-21T12:54:49.000Z
mix.exs
swelham/social_parser
fd8b6f9376474632c01fd2d6c7cabb17d3b3b1d1
[ "MIT" ]
4
2016-11-08T22:25:03.000Z
2019-06-07T18:16:46.000Z
defmodule SocialParser.Mixfile do use Mix.Project def project do [app: :social_parser, version: "2.0.0", elixir: "~> 1.3", description: description(), package: package(), build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, deps: deps()] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do [applications: [:logger]] end # Dependencies can be Hex packages: # # {:mydep, "~> 0.3.0"} # # Or git/path repositories: # # {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"} # # Type "mix help deps" for more examples and options defp deps do [{:ex_doc, ">= 0.14.0", only: :dev}] end defp description do "A small library for parsing out common social elements such as hashtags, mentions and urls." end defp package do [name: :social_parser, maintainers: ["swelham"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/swelham/social_parser"}] end end
23.391304
97
0.624535
73a27e4afef79683bc99b6b7bf8b57949a3ccc56
1,177
ex
Elixir
lib/errol/monitoring/rabbitmq.ex
ceritium/errol
cf2d50795dc7278cca7a6d158aaaa39713cbe493
[ "MIT" ]
23
2018-04-16T20:03:54.000Z
2018-09-03T20:08:19.000Z
lib/errol/monitoring/rabbitmq.ex
ceritium/errol
cf2d50795dc7278cca7a6d158aaaa39713cbe493
[ "MIT" ]
null
null
null
lib/errol/monitoring/rabbitmq.ex
ceritium/errol
cf2d50795dc7278cca7a6d158aaaa39713cbe493
[ "MIT" ]
1
2018-09-21T09:56:13.000Z
2018-09-21T09:56:13.000Z
defmodule Errol.Monitoring.RabbitMQ do @moduledoc false use GenServer def start_link() do GenServer.start_link(__MODULE__, [], name: __MODULE__) end def init(_args) do {:ok, %{}} end def handle_call({:monitor, {connection_pid, process_name}}, _from, state) do Process.monitor(connection_pid) process_names = process_names_for_connection(connection_pid, state) new_state = Map.put(state, connection_pid, process_names ++ [process_name]) {:reply, :ok, new_state} end defp process_names_for_connection(pid, state) do case Map.get(state, pid) do nil -> [] names -> names end end def handle_info({:DOWN, _, :process, connection_pid, _}, state) do process_names = process_names_for_connection(connection_pid, state) {_, new_state} = Map.pop(state, connection_pid) Enum.each(process_names, fn process_name -> process_name |> Process.whereis() |> IO.inspect() |> Process.exit(:kill) end) {:noreply, new_state} end def monitor(connection_pid, process_name) do GenServer.call(__MODULE__, {:monitor, {connection_pid, process_name}}) end end
23.54
79
0.676296
73a28178bcafa455f8e4f3f60d8201666748f6fc
1,719
ex
Elixir
lib/elixir/lib/atom.ex
doughsay/elixir
7356a47047d0b54517bd6886603f09b1121dde2b
[ "Apache-2.0" ]
19,291
2015-01-01T02:42:49.000Z
2022-03-31T21:01:40.000Z
lib/elixir/lib/atom.ex
doughsay/elixir
7356a47047d0b54517bd6886603f09b1121dde2b
[ "Apache-2.0" ]
8,082
2015-01-01T04:16:23.000Z
2022-03-31T22:08:02.000Z
lib/elixir/lib/atom.ex
doughsay/elixir
7356a47047d0b54517bd6886603f09b1121dde2b
[ "Apache-2.0" ]
3,472
2015-01-03T04:11:56.000Z
2022-03-29T02:07:30.000Z
defmodule Atom do @moduledoc """ Atoms are constants whose values are their own name. They are often useful to enumerate over distinct values, such as: iex> :apple :apple iex> :orange :orange iex> :watermelon :watermelon Atoms are equal if their names are equal. iex> :apple == :apple true iex> :apple == :orange false Often they are used to express the state of an operation, by using values such as `:ok` and `:error`. The booleans `true` and `false` are also atoms: iex> true == :true true iex> is_atom(false) true iex> is_boolean(:false) true Elixir allows you to skip the leading `:` for the atoms `false`, `true`, and `nil`. Atoms must be composed of Unicode characters such as letters, numbers, underscore, and `@`. If the keyword has a character that does not belong to the category above, such as spaces, you can wrap it in quotes: iex> :"this is an atom with spaces" :"this is an atom with spaces" """ @doc """ Converts an atom to a string. Inlined by the compiler. ## Examples iex> Atom.to_string(:foo) "foo" """ @spec to_string(atom) :: String.t() def to_string(atom) do :erlang.atom_to_binary(atom, :utf8) end @doc """ Converts an atom to a charlist. Inlined by the compiler. ## Examples iex> Atom.to_charlist(:"An atom") 'An atom' """ @spec to_charlist(atom) :: charlist def to_charlist(atom) do :erlang.atom_to_list(atom) end @doc false @deprecated "Use Atom.to_charlist/1 instead" @spec to_char_list(atom) :: charlist def to_char_list(atom), do: Atom.to_charlist(atom) end
20.710843
74
0.636998
73a2a6c6554ac720311273ffa4131c4fc1e29d5c
2,087
exs
Elixir
mix.exs
ream88/ecto_sqlite3
7c384f4bd09560ad6166ba01b4e398af330bf215
[ "MIT" ]
null
null
null
mix.exs
ream88/ecto_sqlite3
7c384f4bd09560ad6166ba01b4e398af330bf215
[ "MIT" ]
null
null
null
mix.exs
ream88/ecto_sqlite3
7c384f4bd09560ad6166ba01b4e398af330bf215
[ "MIT" ]
null
null
null
defmodule EctoSQLite3.MixProject do use Mix.Project @version "0.5.4" def project do [ app: :ecto_sqlite3, version: @version, elixir: "~> 1.8", start_permanent: Mix.env() == :prod, source_url: "https://github.com/elixir-sqlite/ecto_sqlite3", homepage_url: "https://github.com/elixir-sqlite/ecto_sqlite3", deps: deps(), package: package(), description: description(), test_paths: test_paths(System.get_env("EXQLITE_INTEGRATION")), elixirc_paths: elixirc_paths(Mix.env()), # Docs name: "Ecto SQLite3", docs: docs() ] 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 [ {:decimal, "~> 1.6 or ~> 2.0"}, {:ecto_sql, "~> 3.6"}, {:ecto, "~> 3.5"}, {:exqlite, "~> 0.5"}, {:ex_doc, "~> 0.23.0", only: [:dev], runtime: false}, {:jason, ">= 0.0.0", only: [:bench, :test, :docs]}, {:temp, "~> 0.4", only: [:test]}, # Benchmarks {:benchee, "~> 1.0", only: :bench}, {:benchee_markdown, "~> 0.2", only: :bench}, {:postgrex, "~> 0.15.0", only: :bench}, {:myxql, "~> 0.4.0", only: :bench} ] end defp description do "An SQLite3 Ecto3 adapter." end defp package do [ files: ~w( lib .formatter.exs mix.exs README.md LICENSE ), name: "ecto_sqlite3", licenses: ["MIT"], links: %{ "GitHub" => "https://github.com/elixir-sqlite/ecto_sqlite3", "docs" => "https://hexdocs.pm/ecto_sqlite3" } ] end defp docs do [ main: "Ecto.Adapters.SQLite3", source_ref: "v#{@version}", source_url: "https://github.com/elixir-sqlite/ecto_sqlite3" ] end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] defp test_paths(nil), do: ["test"] defp test_paths(_any), do: ["integration_test"] end
23.715909
68
0.551509
73a2b57f0cc182296031aaf4791dec6faa3fec2a
1,800
ex
Elixir
clients/sheets/lib/google_api/sheets/v4/model/clear_values_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/sheets/lib/google_api/sheets/v4/model/clear_values_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/sheets/lib/google_api/sheets/v4/model/clear_values_response.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.Sheets.V4.Model.ClearValuesResponse do @moduledoc """ The response when clearing a range of values in a spreadsheet. ## Attributes * `clearedRange` (*type:* `String.t`, *default:* `nil`) - The range (in A1 notation) that was cleared. (If the request was for an unbounded range or a ranger larger than the bounds of the sheet, this will be the actual range that was cleared, bounded to the sheet's limits.) * `spreadsheetId` (*type:* `String.t`, *default:* `nil`) - The spreadsheet the updates were applied to. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :clearedRange => String.t(), :spreadsheetId => String.t() } field(:clearedRange) field(:spreadsheetId) end defimpl Poison.Decoder, for: GoogleApi.Sheets.V4.Model.ClearValuesResponse do def decode(value, options) do GoogleApi.Sheets.V4.Model.ClearValuesResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Sheets.V4.Model.ClearValuesResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36
278
0.732778
73a33a520aeadc36f84ae5236b14bf7997f1d7b2
6,702
ex
Elixir
clients/data_fusion/lib/google_api/data_fusion/v1beta1/model/policy.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/data_fusion/lib/google_api/data_fusion/v1beta1/model/policy.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/data_fusion/lib/google_api/data_fusion/v1beta1/model/policy.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DataFusion.V1beta1.Model.Policy do @moduledoc """ An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud resources. A `Policy` is a collection of `bindings`. A `binding` binds one or more `members` to a single `role`. Members can be user accounts, service accounts, Google groups, and domains (such as G Suite). A `role` is a named list of permissions; each `role` can be an IAM predefined role or a user-created custom role. For some types of Google Cloud resources, a `binding` can also specify a `condition`, which is a logical expression that allows access to a resource only if the expression evaluates to `true`. A condition can add constraints based on attributes of the request, the resource, or both. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies). **JSON example:** { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:[email protected]", "group:[email protected]", "domain:google.com", "serviceAccount:[email protected]" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:[email protected]" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 } **YAML example:** bindings: - members: - user:[email protected] - group:[email protected] - domain:google.com - serviceAccount:[email protected] role: roles/resourcemanager.organizationAdmin - members: - user:[email protected] role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - etag: BwWWja0YfJA= - version: 3 For a description of IAM and its features, see the [IAM documentation](https://cloud.google.com/iam/docs/). ## Attributes * `auditConfigs` (*type:* `list(GoogleApi.DataFusion.V1beta1.Model.AuditConfig.t)`, *default:* `nil`) - Specifies cloud audit logging configuration for this policy. * `bindings` (*type:* `list(GoogleApi.DataFusion.V1beta1.Model.Binding.t)`, *default:* `nil`) - Associates a list of `members` to a `role`. Optionally, may specify a `condition` that determines how and when the `bindings` are applied. Each of the `bindings` must contain at least one member. * `etag` (*type:* `String.t`, *default:* `nil`) - `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a policy from overwriting each other. It is strongly suggested that systems make use of the `etag` in the read-modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned in the response to `getIamPolicy`, and systems are expected to put that etag in the request to `setIamPolicy` to ensure that their change will be applied to the same version of the policy. **Important:** If you use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit this field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the conditions in the version `3` policy are lost. * `version` (*type:* `integer()`, *default:* `nil`) - Specifies the format of the policy. Valid values are `0`, `1`, and `3`. Requests that specify an invalid value are rejected. Any operation that affects conditional role bindings must specify version `3`. This requirement applies to the following operations: * Getting a policy that includes a conditional role binding * Adding a conditional role binding to a policy * Changing a conditional role binding in a policy * Removing any role binding, with or without a condition, from a policy that includes conditions **Important:** If you use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit this field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the conditions in the version `3` policy are lost. If a policy does not include any conditions, operations on that policy may specify any valid version or leave the field unset. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies). """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :auditConfigs => list(GoogleApi.DataFusion.V1beta1.Model.AuditConfig.t()), :bindings => list(GoogleApi.DataFusion.V1beta1.Model.Binding.t()), :etag => String.t(), :version => integer() } field(:auditConfigs, as: GoogleApi.DataFusion.V1beta1.Model.AuditConfig, type: :list) field(:bindings, as: GoogleApi.DataFusion.V1beta1.Model.Binding, type: :list) field(:etag) field(:version) end defimpl Poison.Decoder, for: GoogleApi.DataFusion.V1beta1.Model.Policy do def decode(value, options) do GoogleApi.DataFusion.V1beta1.Model.Policy.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DataFusion.V1beta1.Model.Policy do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
42.417722
169
0.680543
73a36c6a32d8b6881b5ba67cabf9d62e0b324e73
168
ex
Elixir
lib/parsers/command.ex
aeturnum/blur
e59bb4a7451cea60d92166e495a3029645a1ffaf
[ "MIT" ]
19
2015-07-21T04:58:12.000Z
2022-01-20T23:25:18.000Z
lib/parsers/command.ex
aeturnum/blur
e59bb4a7451cea60d92166e495a3029645a1ffaf
[ "MIT" ]
3
2020-07-17T22:29:17.000Z
2020-07-20T00:31:41.000Z
lib/parsers/command.ex
aeturnum/blur
e59bb4a7451cea60d92166e495a3029645a1ffaf
[ "MIT" ]
3
2015-08-26T14:59:37.000Z
2021-05-05T04:00:06.000Z
defmodule Blur.Parser.Command do @moduledoc """ Parses messages for commands """ def command("!" <> command), do: command def command(_message), do: nil end
18.666667
42
0.678571
73a37a70fb7807c2debb3292c627b312a4a25521
1,136
ex
Elixir
lib/csv2json.ex
santif/csv2json
e25fe9fb1adfa2396b2a20a17ff1c5b8b0a76266
[ "MIT" ]
null
null
null
lib/csv2json.ex
santif/csv2json
e25fe9fb1adfa2396b2a20a17ff1c5b8b0a76266
[ "MIT" ]
null
null
null
lib/csv2json.ex
santif/csv2json
e25fe9fb1adfa2396b2a20a17ff1c5b8b0a76266
[ "MIT" ]
1
2017-08-08T14:03:06.000Z
2017-08-08T14:03:06.000Z
defmodule Csv2Json do @moduledoc false def main(args \\ []) do case OptionParser.parse!(args, strict: [output: :string], aliases: [o: :output]) do {[output: output_path], [input_path]} -> output_file = File.open! output_path, [:write] try do process_file(input_path, output_file) after File.close(output_file) end {[], [input_path]} -> process_file(input_path, :stdio) _ -> IO.write """ csv2json - Converts CSV file to JSON (one JSON object per line) Usage: csv2json INPUT_FILE [-o OUTPUT_FILE] """ end end @doc """ Converts fields from a CSV line to JSON """ def encode_line(obj) do obj |> Enum.filter(fn {_key, value} -> value != "" end) |> Enum.into(%{}) |> Poison.encode!() end @doc """ Process input file and print JSON to output (file or stdout) """ def process_file(input_path, output) do input_path |> File.stream!() |> CSV.decode!(headers: true) |> Stream.map(&encode_line/1) |> Stream.each(&IO.puts(output, &1)) |> Stream.run() end end
23.666667
87
0.580986
73a384fec139ee87b6373c759a013cb0cff44e8e
2,030
ex
Elixir
clients/android_enterprise/lib/google_api/android_enterprise/v1/model/configuration_variables.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/android_enterprise/lib/google_api/android_enterprise/v1/model/configuration_variables.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/android_enterprise/lib/google_api/android_enterprise/v1/model/configuration_variables.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.AndroidEnterprise.V1.Model.ConfigurationVariables do @moduledoc """ A configuration variables resource contains the managed configuration settings ID to be applied to a single user, as well as the variable set that is attributed to the user. The variable set will be used to replace placeholders in the managed configuration settings. ## Attributes * `mcmId` (*type:* `String.t`, *default:* `nil`) - The ID of the managed configurations settings. * `variableSet` (*type:* `list(GoogleApi.AndroidEnterprise.V1.Model.VariableSet.t)`, *default:* `nil`) - The variable set that is attributed to the user. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :mcmId => String.t(), :variableSet => list(GoogleApi.AndroidEnterprise.V1.Model.VariableSet.t()) } field(:mcmId) field(:variableSet, as: GoogleApi.AndroidEnterprise.V1.Model.VariableSet, type: :list) end defimpl Poison.Decoder, for: GoogleApi.AndroidEnterprise.V1.Model.ConfigurationVariables do def decode(value, options) do GoogleApi.AndroidEnterprise.V1.Model.ConfigurationVariables.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AndroidEnterprise.V1.Model.ConfigurationVariables do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
40.6
268
0.753202
73a3a9926334b2a182201c2d64dfd3f23c7f2408
1,271
ex
Elixir
lib/types/parsed/invite.ex
mirtyl-wacdec/urbit_ex
82db4e96c2f3dc2a28e65c442350d7f8b228901f
[ "MIT" ]
7
2021-05-22T12:05:41.000Z
2021-08-11T20:05:59.000Z
lib/types/parsed/invite.ex
mirtyl-wacdec/urbit_ex
82db4e96c2f3dc2a28e65c442350d7f8b228901f
[ "MIT" ]
null
null
null
lib/types/parsed/invite.ex
mirtyl-wacdec/urbit_ex
82db4e96c2f3dc2a28e65c442350d7f8b228901f
[ "MIT" ]
2
2021-05-29T10:10:52.000Z
2021-08-11T20:06:07.000Z
defmodule UrbitEx.Invite do alias UrbitEx.{Resource, Utils} defstruct hash: "0v6.2a08h.q8qp2.45o52.qdsdu.2qibn", term: "graph or group", recipient: "~mirtyl-wacdec", ship: "~havsem-mirtyl-wacdec", text: "please come", resource: %Resource{} def to_list(nil, _term), do: [] def to_list(graph, _term) when graph == %{}, do: [] def to_list(graph, term) do _hashes = Map.keys(graph) |> Enum.map(&new(graph, &1, term)) end def test(%{}), do: :empty def test(graph), do: Map.keys(graph) def new(graph, index, term) do node = graph[index] %__MODULE__{ hash: index, term: term, recipient: node["recipient"] |> Utils.add_tilde(), ship: node["ship"] |> Utils.add_tilde(), text: node["text"], resource: Resource.new(node["resource"]["ship"], node["resource"]["name"]) } end def new_incoming(invite) do node = invite["invite"] %__MODULE__{ hash: invite["uid"], term: invite["term"], recipient: node["recipient"] |> Utils.add_tilde(), ship: node["ship"] |> Utils.add_tilde(), text: node["text"], resource: Resource.new(node["resource"]["ship"], node["resource"]["name"]) } end end
25.938776
80
0.575138
73a3ae389a294d6eecad2632acbf76a7e89894ac
443
exs
Elixir
test/birdbeak_web/views/error_view_test.exs
qtheninja/birdbeak
f3af66ee84a201a373ab0b9b5c245c861b7e88ab
[ "MIT" ]
null
null
null
test/birdbeak_web/views/error_view_test.exs
qtheninja/birdbeak
f3af66ee84a201a373ab0b9b5c245c861b7e88ab
[ "MIT" ]
null
null
null
test/birdbeak_web/views/error_view_test.exs
qtheninja/birdbeak
f3af66ee84a201a373ab0b9b5c245c861b7e88ab
[ "MIT" ]
null
null
null
defmodule BirdbeakWeb.ErrorViewTest do use BirdbeakWeb.ConnCase, async: true # Bring render/3 and render_to_string/3 for testing custom views import Phoenix.View test "renders 404.html" do assert render_to_string(BirdbeakWeb.ErrorView, "404.html", []) == "Not Found" end test "renders 500.html" do assert render_to_string(BirdbeakWeb.ErrorView, "500.html", []) == "Internal Server Error" end end
26.058824
69
0.699774
73a40d87fb4927ffebdb42436ebf52fdb9d7c08a
2,301
ex
Elixir
clients/replica_pool/lib/google_api/replica_pool/v1beta1/model/new_disk_initialize_params.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/replica_pool/lib/google_api/replica_pool/v1beta1/model/new_disk_initialize_params.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/replica_pool/lib/google_api/replica_pool/v1beta1/model/new_disk_initialize_params.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.ReplicaPool.V1beta1.Model.NewDiskInitializeParams do @moduledoc """ Initialization parameters for creating a new disk. ## Attributes * `diskSizeGb` (*type:* `String.t`, *default:* `nil`) - The size of the created disk in gigabytes. * `diskType` (*type:* `String.t`, *default:* `nil`) - Name of the disk type resource describing which disk type to use to create the disk. For example 'pd-ssd' or 'pd-standard'. Default is 'pd-standard' * `sourceImage` (*type:* `String.t`, *default:* `nil`) - The name or fully-qualified URL of a source image to use to create this disk. If you provide a name of the source image, Replica Pool will look for an image with that name in your project. If you are specifying an image provided by Compute Engine, you will need to provide the full URL with the correct project, such as: http://www.googleapis.com/compute/v1/projects/debian-cloud/ global/images/debian-wheezy-7-vYYYYMMDD """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :diskSizeGb => String.t(), :diskType => String.t(), :sourceImage => String.t() } field(:diskSizeGb) field(:diskType) field(:sourceImage) end defimpl Poison.Decoder, for: GoogleApi.ReplicaPool.V1beta1.Model.NewDiskInitializeParams do def decode(value, options) do GoogleApi.ReplicaPool.V1beta1.Model.NewDiskInitializeParams.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ReplicaPool.V1beta1.Model.NewDiskInitializeParams do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
42.611111
381
0.734463
73a429faaadf0154430bf4598b140d36573ef4b5
4,749
ex
Elixir
lib/ecto/erd/document.ex
patatoid/ecto_erd
526a97001bcdeb4c956eb8bc04c30480e762d0b3
[ "Apache-2.0" ]
null
null
null
lib/ecto/erd/document.ex
patatoid/ecto_erd
526a97001bcdeb4c956eb8bc04c30480e762d0b3
[ "Apache-2.0" ]
null
null
null
lib/ecto/erd/document.ex
patatoid/ecto_erd
526a97001bcdeb4c956eb8bc04c30480e762d0b3
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.ERD.Document do @moduledoc false alias Ecto.ERD.{Node, Field, Edge} defstruct [:edges, :nodes, :clusters] def map_nodes(%__MODULE__{nodes: nodes, edges: edges, clusters: []}, map_node_callback) when is_function(map_node_callback, 1) do {nodes, removed_nodes} = Enum.flat_map_reduce(nodes, [], fn node, removed_nodes -> case map_node_callback.(node) do nil -> {[], [node | removed_nodes]} node -> {[node], removed_nodes} end end) clusters = Enum.group_by(nodes, & &1.cluster) edges = Enum.reject(edges, fn edge -> Enum.any?(removed_nodes, fn node -> Edge.connected_with_node?(edge, node) end) end) {nodes, clusters} = Map.pop(clusters, nil) %__MODULE__{ nodes: List.wrap(nodes), clusters: clusters, edges: edges } end def new(modules) do data = modules |> Enum.flat_map(fn module -> association_components = :associations |> module.__schema__() |> Enum.flat_map(fn assoc_field -> from_reflection(module.__schema__(:association, assoc_field)) end) embed_components = :embeds |> module.__schema__() |> Enum.flat_map(fn embed_field -> from_reflection(module.__schema__(:embed, embed_field)) end) [Node.from_schema_module(module) | embed_components ++ association_components] end) |> Enum.group_by(fn %Edge{} -> :edges %Node{} -> :nodes end) %__MODULE__{ # multiple nodes could be generated by multiple schemas which use the same table in many to many relation nodes: Enum.uniq(Map.get(data, :nodes, [])), edges: merge_edges_with_same_direction(Map.get(data, :edges, [])), clusters: [] } end defp merge_edges_with_same_direction(edges) do edges |> Enum.group_by(fn %Edge{from: from, to: to} -> {from, to} end) |> Enum.map(fn {_direction, edges} -> Enum.reduce(edges, &Edge.merge/2) end) end defp from_reflection(%Ecto.Embedded{} = embedded) do [ Edge.new(%{ from: {embedded.owner.__schema__(:source), embedded.owner, {:field, embedded.field}}, to: {embedded.related.__schema__(:source), embedded.related, {:header, :schema_module}}, assoc_types: [has: embedded.cardinality] }) ] end defp from_reflection(%Ecto.Association.BelongsTo{ owner: owner, owner_key: owner_key, related: related, related_key: related_key }) do related_source = related.__schema__(:source) owner_source = owner.__schema__(:source) [ Edge.new(%{ from: {related_source, related, {:field, related_key}}, to: {owner_source, owner, {:field, owner_key}}, assoc_types: [:belongs_to] }) ] end defp from_reflection(%Ecto.Association.Has{ owner: owner, owner_key: owner_key, related: related, related_key: related_key, cardinality: cardinality }) do related_source = related.__schema__(:source) owner_source = owner.__schema__(:source) [ Edge.new(%{ from: {owner_source, owner, {:field, owner_key}}, to: {related_source, related, {:field, related_key}}, assoc_types: [has: cardinality] }) ] end defp from_reflection(%Ecto.Association.ManyToMany{ join_through: join_through, owner: owner, related: related, join_keys: [{join_source_owner_fk, owner_pk}, {join_source_related_fk, related_pk}] }) do {join_module, join_source} = case join_through do value when is_atom(value) -> {value, value.__schema__(:source)} value when is_binary(value) -> {nil, value} end nodes = case join_module do nil -> fields = [ Field.new(join_source_owner_fk, owner.__schema__(:type, owner_pk)), Field.new(join_source_related_fk, related.__schema__(:type, related_pk)) ] [Node.from_schemaless_join_source(join_source, fields)] _join_module -> [] end nodes ++ [ Edge.new(%{ from: {owner.__schema__(:source), owner, {:field, owner_pk}}, to: {join_source, join_module, {:field, join_source_owner_fk}}, assoc_types: [has: :many] }), Edge.new(%{ from: {related.__schema__(:source), related, {:field, related_pk}}, to: {join_source, join_module, {:field, join_source_related_fk}}, assoc_types: [has: :many] }) ] end defp from_reflection(%Ecto.Association.HasThrough{}) do [] end end
29.134969
111
0.601811
73a4499081656de65afbd5d8437f33fdcdb5d03c
5,453
ex
Elixir
lib/wasmex/module.ex
phaleth/wasmex
6fdb790c5dbbe229e12db71629b3a58ea9bbbf9f
[ "MIT" ]
243
2020-01-15T11:36:36.000Z
2022-03-30T09:38:04.000Z
lib/wasmex/module.ex
phaleth/wasmex
6fdb790c5dbbe229e12db71629b3a58ea9bbbf9f
[ "MIT" ]
255
2020-01-16T00:00:16.000Z
2022-03-29T10:05:52.000Z
lib/wasmex/module.ex
phaleth/wasmex
6fdb790c5dbbe229e12db71629b3a58ea9bbbf9f
[ "MIT" ]
11
2020-04-24T14:57:33.000Z
2022-03-25T12:04:40.000Z
defmodule Wasmex.Module do @moduledoc """ A compiled WebAssembly module. A WebAssembly Module contains stateless WebAssembly code that has already been compiled and can be instantiated multiple times. # Read a WASM file and compile it into a WASM module {:ok, bytes } = File.read("wasmex_test.wasm") {:ok, module} = Wasmex.Module.compile(bytes) # use the compiled module to start as many running instances as you want {:ok, instance } = Wasmex.start_link(%{module: module}) """ @type t :: %__MODULE__{ resource: binary(), reference: reference() } defstruct resource: nil, # The actual NIF module resource. # Normally the compiler will happily do stuff like inlining the # resource in attributes. This will convert the resource into an # empty binary with no warning. This will make that harder to # accidentally do. reference: nil @doc """ Compiles a WASM module from it's WASM (usually a .wasm file) or WAT (usually a .wat file) representation. Compiled modules can be instantiated using `Wasmex.start_link/1`. Since module compilation takes time and resources but instantiation is comparatively cheap, it may be a good idea to compile a module once and instantiate it often if you want to run a WASM binary multiple times. """ @spec compile(binary()) :: {:ok, __MODULE__.t()} | {:error, binary()} def compile(bytes) when is_binary(bytes) do case Wasmex.Native.module_compile(bytes) do {:ok, resource} -> {:ok, wrap_resource(resource)} {:error, err} -> {:error, err} end end @doc """ Returns the name of the current module if a name is given. This name is normally set in the WebAssembly bytecode by some compilers, but can be also overwritten using `set_name/2`. """ @spec name(__MODULE__.t()) :: binary() | nil def name(%__MODULE__{resource: resource}) do case Wasmex.Native.module_name(resource) do {:error, _} -> nil name -> name end end @doc """ Sets the name of the current module. This is normally useful for stacktraces and debugging. It will return `:ok` if the module name was changed successfully, and return an `{:error, reason}` tuple otherwise (in case the module is already instantiated). """ @spec set_name(__MODULE__.t(), binary()) :: :ok | {:error, binary()} def set_name(%__MODULE__{resource: resource}, name) when is_binary(name) do Wasmex.Native.module_set_name(resource, name) end @doc """ Lists all exports of a WebAssembly module. Returns a map which has the exports name (string) as key and export info-tuples as values. Info tuples always start with an atom indicating the exports type: * `:fn` (function) * `:global` * `:table` * `:memory` Further parts of the info tuple vary depending on the type. """ @spec exports(__MODULE__.t()) :: map() def exports(%__MODULE__{resource: resource}) do Wasmex.Native.module_exports(resource) end @doc """ Lists all imports of a WebAssembly module grouped by their module namespace. Returns a map of namespaces, each being a map which has the imports name (string) as key and import info-tuples as values. Info tuples always start with an atom indicating the imports type: * `:fn` (function) * `:global` * `:table` * `:memory` Further parts of the info tuple vary depending on the type. """ @spec imports(__MODULE__.t()) :: map() def imports(%__MODULE__{resource: resource}) do Wasmex.Native.module_imports(resource) end @doc """ Serializes a compiled WASM module into a binary. The generated binary can be deserialized back into a module using `unsafe_deserialize/1`. It is unsafe do alter the binary in any way. See `unsafe_deserialize/1` for safety considerations. """ @spec serialize(__MODULE__.t()) :: {:ok, binary()} | {:error, binary()} def serialize(%__MODULE__{resource: resource}) do case Wasmex.Native.module_serialize(resource) do {:error, err} -> {:error, err} binary -> {:ok, binary} end end @doc """ Deserializes a module from its binary representation. This function is inherently unsafe as the provided binary: 1. Is going to be deserialized directly into Rust objects. 2. Contains the WASM function assembly bodies and, if intercepted, a malicious actor could inject code into executable memory. And as such, the deserialize method is unsafe. Only pass binaries directly coming from `serialize/1`, never any user input. Best case is it crashing the NIF, worst case is malicious input doing... malicious things. The deserialization must be done on the same CPU architecture as the serialization (e.g. don't serialize a x86_64-compiled module and deserialize it on ARM64). """ @spec unsafe_deserialize(binary()) :: {:ok, __MODULE__.t()} | {:error, binary()} def unsafe_deserialize(bytes) when is_binary(bytes) do case Wasmex.Native.module_unsafe_deserialize(bytes) do {:ok, resource} -> {:ok, wrap_resource(resource)} {:error, err} -> {:error, err} end end defp wrap_resource(resource) do %__MODULE__{ resource: resource, reference: make_ref() } end end defimpl Inspect, for: Wasmex.Module do import Inspect.Algebra def inspect(dict, opts) do concat(["#Wasmex.Module<", to_doc(dict.reference, opts), ">"]) end end
33.660494
130
0.689529
73a458701f15366ee21d82dd48f0ba13c2a0f046
948
ex
Elixir
example/lib/example/users/user_aggregate.ex
sebaughman/elixir_cqrs_tools
3f226e23af568d0422765e8bb526d966d83d34da
[ "MIT" ]
17
2021-05-04T09:27:48.000Z
2022-02-02T00:53:28.000Z
example/lib/example/users/user_aggregate.ex
sebaughman/elixir_cqrs_tools
3f226e23af568d0422765e8bb526d966d83d34da
[ "MIT" ]
18
2021-05-05T21:17:54.000Z
2021-12-08T19:25:21.000Z
example/lib/example/users/user_aggregate.ex
sebaughman/elixir_cqrs_tools
3f226e23af568d0422765e8bb526d966d83d34da
[ "MIT" ]
2
2021-05-04T13:35:00.000Z
2021-07-08T22:28:32.000Z
defmodule Example.Users.UserAggregate do defstruct [:id, :status] alias Example.Users.Protocol.{CreateUser, UserCreated} alias Example.Users.Protocol.{SuspendUser, UserSuspended} alias Example.Users.Protocol.{ReinstateUser, UserReinstated} def execute(%{id: nil}, %CreateUser{} = cmd), do: UserCreated.new(cmd) def execute(_state, %CreateUser{}), do: {:error, :user_already_created} def execute(%{id: nil}, _), do: {:error, :user_not_found} def execute(%{status: :active}, %SuspendUser{} = cmd), do: UserSuspended.new(cmd) def execute(_, %SuspendUser{}), do: nil def execute(%{status: :suspended}, %ReinstateUser{} = cmd), do: UserReinstated.new(cmd) def execute(_, %ReinstateUser{}), do: nil def apply(state, %UserCreated{id: id}), do: %{state | id: id, status: :active} def apply(state, %UserSuspended{}), do: %{state | status: :suspended} def apply(state, %UserReinstated{}), do: %{state | status: :active} end
41.217391
89
0.697257
73a4755502f1785f58b499f0425521ed1557a776
1,814
ex
Elixir
lib/diode_client/transport.ex
diodechain/diode_client_ex
0aec3aa7a2e3448cccfc255b4d4e8d2cbf475c7f
[ "Apache-2.0" ]
null
null
null
lib/diode_client/transport.ex
diodechain/diode_client_ex
0aec3aa7a2e3448cccfc255b4d4e8d2cbf475c7f
[ "Apache-2.0" ]
null
null
null
lib/diode_client/transport.ex
diodechain/diode_client_ex
0aec3aa7a2e3448cccfc255b4d4e8d2cbf475c7f
[ "Apache-2.0" ]
null
null
null
defmodule DiodeClient.Transport do @moduledoc """ DiodeClient Transport interface for use with Cowboy2 Adapter and :hackeny. Potentially more depending on interface compatibility # Example using hackney to make http requests via Diode: {:ok, ref} = :hackney.connect(DiodeClient.Transport, address, port) request = {:get, path, [], ""} {:ok, status, headers, ^ref} = :hackney.send_request(ref, request) {:ok, content} = :hackney.body(ref) """ alias DiodeClient.Rlpx def connect(addr, port, opts \\ [], timeout \\ 5000) when is_integer(port) do port = Rlpx.bin2uint("tls:#{port}") DiodeClient.Port.connect(addr, port, opts, timeout) end def listen(opts) do port = Keyword.fetch!(opts, :port) portnum = Rlpx.bin2uint("tls:#{port}") DiodeClient.Port.listen(portnum) end def accept(portnum, timeout) do DiodeClient.Port.accept(portnum, timeout) end def sockname(ssl) when is_tuple(ssl), do: :ssl.sockname(ssl) def sockname(port), do: DiodeClient.Port.sockname(port) def handshake(pid, _opts, _timeout) do {:ok, pid} end defdelegate controlling_process(pid, dst), to: :ssl defdelegate peername(pid), to: :ssl defdelegate setopts(pid, opts), to: :ssl defdelegate send(pid, data), to: :ssl defdelegate recv(pid, length), to: :ssl defdelegate recv(pid, length, timeout), to: :ssl defdelegate shutdown(pid, reason), to: :ssl defdelegate close(pid), to: :ssl def sendfile(socket, path, offset, bytes) do :ranch_transport.sendfile(name(), socket, path, offset, bytes, chunk_size: DiodeClient.Port.chunk_size() ) end def messages(), do: {:ssl, :ssl_closed, :ssl_error, :ssl_passive} def messages(_pid), do: {:ssl, :ssl_closed, :ssl_error} def name(), do: __MODULE__ def secure(), do: true end
31.824561
79
0.686329
73a4952c2502b62e01447c34f4c04572d8181f1f
1,918
ex
Elixir
priv/templates/ja_serializer.gen.phoenix_api/controller.ex
strzibny/ja_serializer
9823ada739ec1f0db9f14bd29f62a701dbd3b094
[ "Apache-2.0" ]
null
null
null
priv/templates/ja_serializer.gen.phoenix_api/controller.ex
strzibny/ja_serializer
9823ada739ec1f0db9f14bd29f62a701dbd3b094
[ "Apache-2.0" ]
1
2021-06-25T13:28:34.000Z
2021-06-25T13:28:34.000Z
priv/templates/ja_serializer.gen.phoenix_api/controller.ex
strzibny/ja_serializer
9823ada739ec1f0db9f14bd29f62a701dbd3b094
[ "Apache-2.0" ]
null
null
null
defmodule <%= module %>Controller do use <%= base %>.Web, :controller alias <%= module %> alias JaSerializer.Params plug :scrub_params, "data" when action in [:create, :update] def index(conn, _params) do <%= plural %> = Repo.all(<%= alias %>) render(conn, "index.json-api", data: <%= plural %>) end def create(conn, %{"data" => data = %{"type" => <%= inspect singular %>, "attributes" => _<%= singular %>_params}}) do changeset = <%= alias %>.changeset(%<%= alias %>{}, Params.to_attributes(data)) case Repo.insert(changeset) do {:ok, <%= singular %>} -> conn |> put_status(:created) |> put_resp_header("location", <%= singular %>_path(conn, :show, <%= singular %>)) |> render("show.json-api", data: <%= singular %>) {:error, changeset} -> conn |> put_status(:unprocessable_entity) |> render(:errors, data: changeset) end end def show(conn, %{"id" => id}) do <%= singular %> = Repo.get!(<%= alias %>, id) render(conn, "show.json-api", data: <%= singular %>) end def update(conn, %{"id" => id, "data" => data = %{"type" => <%= inspect singular %>, "attributes" => _<%= singular %>_params}}) do <%= singular %> = Repo.get!(<%= alias %>, id) changeset = <%= alias %>.changeset(<%= singular %>, Params.to_attributes(data)) case Repo.update(changeset) do {:ok, <%= singular %>} -> render(conn, "show.json-api", data: <%= singular %>) {:error, changeset} -> conn |> put_status(:unprocessable_entity) |> render(:errors, data: changeset) end end def delete(conn, %{"id" => id}) do <%= singular %> = Repo.get!(<%= alias %>, id) # Here we use delete! (with a bang) because we expect # it to always work (and if it does not, it will raise). Repo.delete!(<%= singular %>) send_resp(conn, :no_content, "") end end
31.966667
132
0.557873
73a4955a05c9aac331968a09b1de224c27cf96a8
1,360
ex
Elixir
clients/cloud_error_reporting/lib/google_api/cloud_error_reporting/v1beta1/model/list_group_stats_response.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/cloud_error_reporting/lib/google_api/cloud_error_reporting/v1beta1/model/list_group_stats_response.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/cloud_error_reporting/lib/google_api/cloud_error_reporting/v1beta1/model/list_group_stats_response.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.CloudErrorReporting.V1beta1.Model.ListGroupStatsResponse do @moduledoc """ Contains a set of requested error group stats. """ @derive [Poison.Encoder] defstruct [ :"errorGroupStats", :"nextPageToken", :"timeRangeBegin" ] end defimpl Poison.Decoder, for: GoogleApi.CloudErrorReporting.V1beta1.Model.ListGroupStatsResponse do import GoogleApi.CloudErrorReporting.V1beta1.Deserializer def decode(value, options) do value |> deserialize(:"errorGroupStats", :list, GoogleApi.CloudErrorReporting.V1beta1.Model.ErrorGroupStats, options) end end
33.170732
115
0.763971
73a49abdb81a5d80c52cc54377349cf59c1295e6
1,112
exs
Elixir
test/support/case.exs
brentjanderson/current
8c974e202c980cbf8fd28630d794574ec10f94ed
[ "Unlicense" ]
4
2020-09-17T15:55:21.000Z
2022-02-11T22:11:55.000Z
test/support/case.exs
brentjanderson/current
8c974e202c980cbf8fd28630d794574ec10f94ed
[ "Unlicense" ]
null
null
null
test/support/case.exs
brentjanderson/current
8c974e202c980cbf8fd28630d794574ec10f94ed
[ "Unlicense" ]
1
2022-03-07T20:22:23.000Z
2022-03-07T20:22:23.000Z
defmodule Current.Test.Case do use ExUnit.CaseTemplate using do quote do alias Current.Test.{Repo, Actor, Movie, Credit} import Ecto.Query import Current.Test.Case.Helpers end end setup context do if context[:db] do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Current.Test.Repo) # Move into `Current.StreamerTest` cases? Ecto.Adapters.SQL.Sandbox.mode(Current.Test.Repo, {:shared, self()}) # Toggle with different tag? Current.Test.Data.insert!() end end defmodule Helpers do def ascending?(rows, options \\ []), do: ordered?(rows, &>/2, options) def descending?(rows, options \\ []), do: ordered?(rows, &</2, options) defp ordered?(rows, comparer, options) do key = Keyword.get(options, :key, :id) {_, ordered} = Enum.reduce(rows, {nil, true}, fn %{^key => current}, {nil, true} -> {current, true} %{^key => current}, {_, false} -> {current, false} %{^key => current}, {prev, true} -> {current, comparer.(current, prev)} end) ordered end end end
25.272727
81
0.598921
73a4a49da54f13698d724bca1297c3c8fd1b4505
1,083
ex
Elixir
web/views/artwork_view.ex
ImpossibilityLabs/artheon
2fd1284c8bd087107e56432ebefc3345db10e60e
[ "Apache-2.0" ]
null
null
null
web/views/artwork_view.ex
ImpossibilityLabs/artheon
2fd1284c8bd087107e56432ebefc3345db10e60e
[ "Apache-2.0" ]
null
null
null
web/views/artwork_view.ex
ImpossibilityLabs/artheon
2fd1284c8bd087107e56432ebefc3345db10e60e
[ "Apache-2.0" ]
null
null
null
defmodule Artheon.ArtworkView do use Artheon.Web, :view def render("index.json", %{artworks: artworks}) do %{data: render_many(artworks, Artheon.ArtworkView, "artwork.json")} end def render("show.json", %{artwork: artwork}) do %{data: render_one(artwork, Artheon.ArtworkView, "artwork.json")} end def render("artwork.json", %{artwork: artwork}) do %{ id: artwork.id, uid: artwork.uid, slug: artwork.slug, title: artwork.title, category: artwork.category, medium: artwork.medium, created_at: artwork.created_at, updated_at: artwork.updated_at, date: artwork.date, height: artwork.height, width: artwork.width, depth: artwork.depth, diameter: artwork.diameter, website: artwork.website, collecting_institution: artwork.collecting_institution, image_rights: artwork.image_rights, images: render_many(artwork.images, Artheon.ArtworkImageView, "artwork_image.json"), artist: render_one(artwork.artist, Artheon.ArtistView, "artist.json") } end end
30.942857
90
0.680517
73a51f204079b85227ca844c5b712942f5ca578a
3,012
exs
Elixir
test/pdf_generator_test.exs
egze/elixir-pdf-generator
7fdf48105d7b51fe19ab6e2d73320973e42aa37e
[ "MIT" ]
null
null
null
test/pdf_generator_test.exs
egze/elixir-pdf-generator
7fdf48105d7b51fe19ab6e2d73320973e42aa37e
[ "MIT" ]
null
null
null
test/pdf_generator_test.exs
egze/elixir-pdf-generator
7fdf48105d7b51fe19ab6e2d73320973e42aa37e
[ "MIT" ]
1
2019-02-05T20:52:13.000Z
2019-02-05T20:52:13.000Z
defmodule PdfGeneratorTest do use ExUnit.Case @html "<html><body><h1>Hi</h1><p>Yikes!</p></body></html>" test "agent startup" do {:ok, _ } = File.stat PdfGenerator.PathAgent.get.wkhtml_path end test "basic PDF generation" do {:ok, temp_filename } = PdfGenerator.generate @html # File should exist and has some size file_info = File.stat! temp_filename assert file_info.size > 0 pdf = File.read! temp_filename # PDF header should be present assert String.slice( pdf, 0, 6) == "%PDF-1" end test "command prefix with noop env" do {:ok, _temp_filename } = PdfGenerator.generate @html, command_prefix: "env" end test "command prefix with args with noop env" do {:ok, _temp_filename } = PdfGenerator.generate @html, command_prefix: ["env", "foo=bar"] end test "generate_binary reads file" do assert {:ok, "%PDF-1" <> _pdf} = @html |> PdfGenerator.generate_binary end test "chrome-headless from file" do {:ok, temp_filename } = PdfGenerator.generate(@html, generator: :chrome, page_size: "A5") # File should exist and has some size file_info = File.stat! temp_filename assert file_info.size > 0 pdf = File.read! temp_filename # PDF header should be present assert String.slice( pdf, 0, 6) == "%PDF-1" end test "chrome-headless from URL (assuming google.com is up and running)" do {status, result} = PdfGenerator.generate({:url, "http://google.com"}, generator: :chrome) assert status == :ok assert result |> File.read! |> String.slice(0, 6) == "%PDF-1" end test "generate! returns a filename" do @html |> PdfGenerator.generate! |> File.exists? |> assert end test "generate! with filename option returns custom filename" do filename = PdfGenerator.generate!(@html, filename: "custom_file_name") assert File.exists?(filename) assert Path.basename(filename, ".pdf") == "custom_file_name" end test "generate_binary! reads file" do assert "%PDF-1" <> _pdf = @html |> PdfGenerator.generate_binary! end test "delete_temporary works" do # w/o delete_temporary, html should be there @html |> PdfGenerator.generate! |> String.replace( ~r(\.pdf$), ".html") |> File.exists? |> assert # with delete_temporary, html file should be gone @html |> PdfGenerator.generate!(delete_temporary: true) |> String.replace( ~r(\.pdf$), ".html") |> File.exists?() |> refute # cannot really be sure if temporyr file was deleted but this shouldn't # crash at least. We could scan the temp dir before and after but had to # make sure no other process wrote something in there which isn't exactly # robust. assert {:ok, "%PDF-1" <> _pdf} = @html |> PdfGenerator.generate_binary(delete_temporary: true) end test "shell_params are accepted" do @html |> PdfGenerator.generate!(shell_params: ["--orientation", "landscape", "--margin-right", "0"]) |> File.exists?() |> assert end end
30.424242
98
0.663679
73a525ee019387a96ecd642c9be482cd330fd15f
750
ex
Elixir
lib/nacha/records/batch_control.ex
tokkenops/nacha.ex
0232ed5578d01b89cb554cd8cd0e574504aa5137
[ "Apache-2.0" ]
8
2020-02-06T17:38:02.000Z
2022-01-01T01:41:07.000Z
lib/nacha/records/batch_control.ex
tokkenops/nacha.ex
0232ed5578d01b89cb554cd8cd0e574504aa5137
[ "Apache-2.0" ]
2
2019-06-28T03:40:09.000Z
2019-06-28T04:10:34.000Z
lib/nacha/records/batch_control.ex
tokkenops/nacha.ex
0232ed5578d01b89cb554cd8cd0e574504aa5137
[ "Apache-2.0" ]
2
2020-01-18T22:27:17.000Z
2021-12-29T17:21:57.000Z
defmodule Nacha.Records.BatchControl do @moduledoc """ A struct containing data for a batch control record. """ @required [ :record_type_code, :service_class_code, :entry_count, :entry_hash, :total_debits, :total_credits, :company_id, :odfi_id, :batch_number ] use Nacha.Record, fields: [ {:record_type_code, :number, 1, 8}, {:service_class_code, :string, 3}, {:entry_count, :number, 6, 0}, {:entry_hash, :number, 10}, {:total_debits, :number, 12}, {:total_credits, :number, 12}, {:company_id, :string, 10}, {:message_auth_code, :string, 19}, {:reserved, :string, 6}, {:odfi_id, :string, 8}, {:batch_number, :number, 7} ] end
22.727273
54
0.593333
73a56154c4a15a417fc6c7e414d2d073b62b9ee1
3,755
ex
Elixir
clients/chat/lib/google_api/chat/v1/model/deprecated_event.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/chat/lib/google_api/chat/v1/model/deprecated_event.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/chat/lib/google_api/chat/v1/model/deprecated_event.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.Chat.V1.Model.DeprecatedEvent do @moduledoc """ Hangouts Chat events. ## Attributes * `action` (*type:* `GoogleApi.Chat.V1.Model.FormAction.t`, *default:* `nil`) - The form action data associated with an interactive card that was clicked. Only populated for CARD_CLICKED events. See the [Interactive Cards guide](/hangouts/chat/how-tos/cards-onclick) for more information. * `configCompleteRedirectUrl` (*type:* `String.t`, *default:* `nil`) - The URL the bot should redirect the user to after they have completed an authorization or configuration flow outside of Hangouts Chat. See the [Authorizing access to 3p services guide](/hangouts/chat/how-tos/auth-3p) for more information. * `eventTime` (*type:* `DateTime.t`, *default:* `nil`) - The timestamp indicating when the event was dispatched. * `message` (*type:* `GoogleApi.Chat.V1.Model.Message.t`, *default:* `nil`) - The message that triggered the event, if applicable. * `space` (*type:* `GoogleApi.Chat.V1.Model.Space.t`, *default:* `nil`) - The room or DM in which the event occurred. * `threadKey` (*type:* `String.t`, *default:* `nil`) - The bot-defined key for the thread related to the event. See the thread_key field of the `spaces.message.create` request for more information. * `token` (*type:* `String.t`, *default:* `nil`) - A secret value that bots can use to verify if a request is from Google. The token is randomly generated by Google, remains static, and can be obtained from the Hangouts Chat API configuration page in the Cloud Console. Developers can revoke/regenerate it if needed from the same page. * `type` (*type:* `String.t`, *default:* `nil`) - The type of the event. * `user` (*type:* `GoogleApi.Chat.V1.Model.User.t`, *default:* `nil`) - The user that triggered the event. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :action => GoogleApi.Chat.V1.Model.FormAction.t(), :configCompleteRedirectUrl => String.t(), :eventTime => DateTime.t(), :message => GoogleApi.Chat.V1.Model.Message.t(), :space => GoogleApi.Chat.V1.Model.Space.t(), :threadKey => String.t(), :token => String.t(), :type => String.t(), :user => GoogleApi.Chat.V1.Model.User.t() } field(:action, as: GoogleApi.Chat.V1.Model.FormAction) field(:configCompleteRedirectUrl) field(:eventTime, as: DateTime) field(:message, as: GoogleApi.Chat.V1.Model.Message) field(:space, as: GoogleApi.Chat.V1.Model.Space) field(:threadKey) field(:token) field(:type) field(:user, as: GoogleApi.Chat.V1.Model.User) end defimpl Poison.Decoder, for: GoogleApi.Chat.V1.Model.DeprecatedEvent do def decode(value, options) do GoogleApi.Chat.V1.Model.DeprecatedEvent.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Chat.V1.Model.DeprecatedEvent do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
45.240964
158
0.694008
73a57451b8d869d488f89d61d1ee3f94e635c997
196
ex
Elixir
lib/test_processor.ex
dkataskin/honeydew_nodelru
8b7e8e62a42d0efbd3d158a3f572f3d12011d92e
[ "MIT" ]
null
null
null
lib/test_processor.ex
dkataskin/honeydew_nodelru
8b7e8e62a42d0efbd3d158a3f572f3d12011d92e
[ "MIT" ]
null
null
null
lib/test_processor.ex
dkataskin/honeydew_nodelru
8b7e8e62a42d0efbd3d158a3f572f3d12011d92e
[ "MIT" ]
null
null
null
defmodule HoneydewNodeLRU.TestProcessor do require Logger def init(args) do {:ok, args} end def process(id, _state) do Logger.debug "#{node()}: processed job id=#{id}" end end
16.333333
52
0.668367
73a5867c5fda64b7c46af76b82e7e86baff23c31
134
ex
Elixir
web/controllers/page_controller.ex
tahmidsadik112/bloom
edf9995535cdb189b47addb7aee7311f590c5a87
[ "MIT" ]
null
null
null
web/controllers/page_controller.ex
tahmidsadik112/bloom
edf9995535cdb189b47addb7aee7311f590c5a87
[ "MIT" ]
null
null
null
web/controllers/page_controller.ex
tahmidsadik112/bloom
edf9995535cdb189b47addb7aee7311f590c5a87
[ "MIT" ]
null
null
null
defmodule Bloom.PageController do use Bloom.Web, :controller def index(conn, _params) do render conn, "index.html" end end
16.75
33
0.723881
73a58ec5dc28ba06c88f07012331150765e3f4a6
6,581
ex
Elixir
clients/big_query/lib/google_api/big_query/v2/model/external_data_configuration.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/big_query/lib/google_api/big_query/v2/model/external_data_configuration.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/big_query/lib/google_api/big_query/v2/model/external_data_configuration.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &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 elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.BigQuery.V2.Model.ExternalDataConfiguration do @moduledoc """ ## Attributes * `autodetect` (*type:* `boolean()`, *default:* `nil`) - Try to detect schema and format options automatically. Any option specified explicitly will be honored. * `bigtableOptions` (*type:* `GoogleApi.BigQuery.V2.Model.BigtableOptions.t`, *default:* `nil`) - [Optional] Additional options if sourceFormat is set to BIGTABLE. * `compression` (*type:* `String.t`, *default:* `nil`) - [Optional] The compression type of the data source. Possible values include GZIP and NONE. The default value is NONE. This setting is ignored for Google Cloud Bigtable, Google Cloud Datastore backups and Avro formats. * `csvOptions` (*type:* `GoogleApi.BigQuery.V2.Model.CsvOptions.t`, *default:* `nil`) - Additional properties to set if sourceFormat is set to CSV. * `googleSheetsOptions` (*type:* `GoogleApi.BigQuery.V2.Model.GoogleSheetsOptions.t`, *default:* `nil`) - [Optional] Additional options if sourceFormat is set to GOOGLE_SHEETS. * `hivePartitioningMode` (*type:* `String.t`, *default:* `nil`) - [Optional, Trusted Tester] If hive partitioning is enabled, which mode to use. Two modes are supported: - AUTO: automatically infer partition key name(s) and type(s). - STRINGS: automatic infer partition key name(s). All types are strings. Not all storage formats support hive partitioning -- requesting hive partitioning on an unsupported format will lead to an error. Note: this setting is in the process of being deprecated in favor of hivePartitioningOptions. * `hivePartitioningOptions` (*type:* `GoogleApi.BigQuery.V2.Model.HivePartitioningOptions.t`, *default:* `nil`) - [Optional, Trusted Tester] Options to configure hive partitioning support. * `ignoreUnknownValues` (*type:* `boolean()`, *default:* `nil`) - [Optional] Indicates if BigQuery should allow extra values that are not represented in the table schema. If true, the extra values are ignored. If false, records with extra columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false. The sourceFormat property determines what BigQuery treats as an extra value: CSV: Trailing columns JSON: Named values that don't match any column names Google Cloud Bigtable: This setting is ignored. Google Cloud Datastore backups: This setting is ignored. Avro: This setting is ignored. * `maxBadRecords` (*type:* `integer()`, *default:* `nil`) - [Optional] The maximum number of bad records that BigQuery can ignore when reading data. If the number of bad records exceeds this value, an invalid error is returned in the job result. This is only valid for CSV, JSON, and Google Sheets. The default value is 0, which requires that all records are valid. This setting is ignored for Google Cloud Bigtable, Google Cloud Datastore backups and Avro formats. * `schema` (*type:* `GoogleApi.BigQuery.V2.Model.TableSchema.t`, *default:* `nil`) - [Optional] The schema for the data. Schema is required for CSV and JSON formats. Schema is disallowed for Google Cloud Bigtable, Cloud Datastore backups, and Avro formats. * `sourceFormat` (*type:* `String.t`, *default:* `nil`) - [Required] The data format. For CSV files, specify "CSV". For Google sheets, specify "GOOGLE_SHEETS". For newline-delimited JSON, specify "NEWLINE_DELIMITED_JSON". For Avro files, specify "AVRO". For Google Cloud Datastore backups, specify "DATASTORE_BACKUP". [Beta] For Google Cloud Bigtable, specify "BIGTABLE". * `sourceUris` (*type:* `list(String.t)`, *default:* `nil`) - [Required] The fully-qualified URIs that point to your data in Google Cloud. For Google Cloud Storage URIs: Each URI can contain one '*' wildcard character and it must come after the 'bucket' name. Size limits related to load jobs apply to external data sources. For Google Cloud Bigtable URIs: Exactly one URI can be specified and it has be a fully specified and valid HTTPS URL for a Google Cloud Bigtable table. For Google Cloud Datastore backups, exactly one URI can be specified. Also, the '*' wildcard character is not allowed. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :autodetect => boolean(), :bigtableOptions => GoogleApi.BigQuery.V2.Model.BigtableOptions.t(), :compression => String.t(), :csvOptions => GoogleApi.BigQuery.V2.Model.CsvOptions.t(), :googleSheetsOptions => GoogleApi.BigQuery.V2.Model.GoogleSheetsOptions.t(), :hivePartitioningMode => String.t(), :hivePartitioningOptions => GoogleApi.BigQuery.V2.Model.HivePartitioningOptions.t(), :ignoreUnknownValues => boolean(), :maxBadRecords => integer(), :schema => GoogleApi.BigQuery.V2.Model.TableSchema.t(), :sourceFormat => String.t(), :sourceUris => list(String.t()) } field(:autodetect) field(:bigtableOptions, as: GoogleApi.BigQuery.V2.Model.BigtableOptions) field(:compression) field(:csvOptions, as: GoogleApi.BigQuery.V2.Model.CsvOptions) field(:googleSheetsOptions, as: GoogleApi.BigQuery.V2.Model.GoogleSheetsOptions) field(:hivePartitioningMode) field(:hivePartitioningOptions, as: GoogleApi.BigQuery.V2.Model.HivePartitioningOptions) field(:ignoreUnknownValues) field(:maxBadRecords) field(:schema, as: GoogleApi.BigQuery.V2.Model.TableSchema) field(:sourceFormat) field(:sourceUris, type: :list) end defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.ExternalDataConfiguration do def decode(value, options) do GoogleApi.BigQuery.V2.Model.ExternalDataConfiguration.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.ExternalDataConfiguration do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
82.2625
681
0.746543
73a59885b05f8d3bcba9cb9686cbaf2e70d192b1
1,902
ex
Elixir
clients/vault/lib/google_api/vault/v1/model/held_groups_query.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/vault/lib/google_api/vault/v1/model/held_groups_query.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/vault/lib/google_api/vault/v1/model/held_groups_query.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Vault.V1.Model.HeldGroupsQuery do @moduledoc """ Query options for group holds. ## Attributes - endTime (DateTime.t): The end time range for the search query. These timestamps are in GMT and rounded down to the start of the given date. Defaults to: `null`. - startTime (DateTime.t): The start time range for the search query. These timestamps are in GMT and rounded down to the start of the given date. Defaults to: `null`. - terms (String.t): The search terms for the hold. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :endTime => DateTime.t(), :startTime => DateTime.t(), :terms => any() } field(:endTime, as: DateTime) field(:startTime, as: DateTime) field(:terms) end defimpl Poison.Decoder, for: GoogleApi.Vault.V1.Model.HeldGroupsQuery do def decode(value, options) do GoogleApi.Vault.V1.Model.HeldGroupsQuery.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Vault.V1.Model.HeldGroupsQuery do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.222222
168
0.727655
73a59a5b8022b2fa959c4dbd773d95c4a7566b26
5,428
ex
Elixir
lib/weather_api/external_api/dark_sky_api.ex
vegashat/weather-api
d06ce0bf809bd98710367c459920bc5cef384f94
[ "MIT" ]
null
null
null
lib/weather_api/external_api/dark_sky_api.ex
vegashat/weather-api
d06ce0bf809bd98710367c459920bc5cef384f94
[ "MIT" ]
null
null
null
lib/weather_api/external_api/dark_sky_api.ex
vegashat/weather-api
d06ce0bf809bd98710367c459920bc5cef384f94
[ "MIT" ]
null
null
null
defmodule WeatherApi.ExternalApi.DarkSky do alias WeatherApi.Models.{Location, Weather, Forecast, Alert, Current} @dark_sky_api_key Application.get_env(:weather_api, :dark_sky_api_key) @dark_sky_url Application.get_env(:weather_api, :dark_sky_api_url) @test_data_file_path "data/weather.json" def lookup_weather(%Location{} = location) do weather = get_weather_json_data(location.latitude, location.longitude) |> do_lookup_weather(location) weather end def lookup_weather(%Location{} = location, :use_file) do get_weather_json_data_from_file() |> do_lookup_weather(location) end def do_lookup_weather(json, %Location{} = location) do weather = json |> decode() |> parse_weather() %Weather{weather | location: location} end def get_weather_json_data(lat, long) do url = "#{@dark_sky_url}/#{@dark_sky_api_key}/#{lat},#{long}?exclude=minutely,hourly" case Mojito.request(method: :get, url: url) do {:ok, response} -> response.body {:error, err} -> "Error requesting weather from Dark Sky: #{err.message}" {_, _} -> "Unexpected Response" end end defp get_weather_json_data_from_file() do File.read!(@test_data_file_path) end defp decode(json) do case Jason.decode(json, [{:keys, :atoms}]) do {:ok, data} -> data {:error, _} -> "Error parsing json data" end end defp parse_weather(json) do current = parse_current(json) forecasts = Enum.map(json[:daily][:data], &parse_forecast(&1)) %Weather{current: current, forecasts: forecasts} end def parse_current(json) do with current = json[:currently] do base = parse_base_weather(current, :current) current = %Current{base | temp: current[:temperature], feels_like: current[:apparentTemperature] } case Map.has_key?(json, :alerts) do true -> with alerts = Enum.at(json[:alerts],0) do alert = %Alert{ title: alerts[:title], severity: alerts[:severity], description: alerts[:description] } %Current{current | alert: alert} end _ -> current end end end def parse_forecast(forecast) do base_weather = parse_base_weather(forecast, :forecast) %Forecast{base_weather | temp_high: forecast[:temperatureMax], temp_low: forecast[:temperatureMin], moon_phase: forecast[:moonPhase] } end defp parse_base_weather(json, :current) do %Current{ date: convert_to_cst(json[:time]), summary: json[:summary], icon: json[:icon], humidity: json[:humidity], wind_speed: json[:windSpeed], wind_direction: wind_direction(json[:windBearing]), precip_probability: json[:precipProbability] } end defp parse_base_weather(json, :forecast) do %Forecast{ date: convert_to_cst(json[:time]), summary: json[:summary], icon: json[:icon], humidity: json[:humidity], wind_speed: json[:windSpeed], wind_direction: wind_direction(json[:windBearing]), precip_probability: json[:precipProbability] } end def convert_to_cst(unix_time) do {:ok, date} = DateTime.from_unix(unix_time) {:ok, date} = DateTime.shift_zone(date, "America/Chicago") date end def wind_direction(direction_in_degrees) do case direction_in_degrees do x when x in 348..360 -> "N" x when x in 1..11 -> "N" x when x in 11..33 -> "NNE" x when x in 33..56 -> "NE" x when x in 56..78 -> "ENE" x when x in 78..101 -> "E" x when x in 101..123 -> "ESE" x when x in 123..146 -> "SE" x when x in 146..168 -> "SSE" x when x in 168..191 -> "S" x when x in 191..213 -> "SSW" x when x in 213..236 -> "SW" x when x in 236..258 -> "WSW" x when x in 258..281 -> "W" x when x in 282..303 -> "WNW" x when x in 303..326 -> "NW" x when x in 326..348 -> "NNW" end end def moon_phase(lunation_fraction) do lunation_int = Decimal.from_float(lunation_fraction * 100) |> Decimal.round(0, :down) |> Decimal.to_integer() case lunation_int do x when x in 0..0 -> "new" x when x in 1..24 -> "waxing-crescent" x when x in 25..25 -> "first-quarter" x when x in 26..49 -> "waxing-gibbous" x when x in 50..50 -> "full-moon" x when x in 51..74 -> "waning-gibbous" x when x in 75..75 -> "last-quarter" x when x in 76..99 -> "waning-crescent" end end end
32.698795
91
0.523766
73a5cc9cd706269375acf7c5836785fff9b404b2
1,137
ex
Elixir
lib/console/commands/command.ex
pluralsh/console
38a446ce1bc2f7bc3e904fcacb102d3d57835ada
[ "Apache-2.0" ]
6
2021-11-17T21:10:49.000Z
2022-02-16T19:45:28.000Z
lib/console/commands/command.ex
pluralsh/console
38a446ce1bc2f7bc3e904fcacb102d3d57835ada
[ "Apache-2.0" ]
18
2021-11-25T04:31:06.000Z
2022-03-27T04:54:00.000Z
lib/console/commands/command.ex
pluralsh/console
38a446ce1bc2f7bc3e904fcacb102d3d57835ada
[ "Apache-2.0" ]
null
null
null
defmodule Console.Commands.Command do import Console alias Console.Services.Builds alias Console.Commands.Tee alias Console.Schema.{Build, Command} @build_key :console_build def set_build(build), do: Process.put(@build_key, build) def cmd(exec, args, dir \\ conf(:workspace_root)) do with {:ok, collectible} <- make_command(exec, args), {output, exit_code} <- System.cmd(exec, args, into: collectible, env: [{"ENABLE_COLOR", "1"}], cd: dir, stderr_to_stdout: true), do: complete(output, exit_code) end defp make_command(exec, args) do case Process.get(@build_key) do %Build{} = build -> Builds.create_command(%{command: "#{exec} #{Enum.join(args, " ")}"}, build) %Tee{} = tee -> {:ok, tee} _ -> {:ok, IO.stream(:stdio, :line)} end end defp complete(%Command{} = command, exit_code) do with {:ok, command} <- Builds.complete(command, exit_code) do case exit_code do 0 -> {:ok, command} _ -> {:error, command} end end end defp complete(result, 0), do: {:ok, result} defp complete(result, _), do: {:error, result} end
30.72973
137
0.632366
73a5da74a0978126bbe6c63c90ae5918b84308e2
718
ex
Elixir
lib/myApi_web/controllers/fallback_controller.ex
alex2chan/Phoenix-JWT-Auth-API
5313b41bb590db4c12bdc16f624c11a035d4d692
[ "MIT" ]
null
null
null
lib/myApi_web/controllers/fallback_controller.ex
alex2chan/Phoenix-JWT-Auth-API
5313b41bb590db4c12bdc16f624c11a035d4d692
[ "MIT" ]
null
null
null
lib/myApi_web/controllers/fallback_controller.ex
alex2chan/Phoenix-JWT-Auth-API
5313b41bb590db4c12bdc16f624c11a035d4d692
[ "MIT" ]
null
null
null
defmodule MyApiWeb.FallbackController do @moduledoc """ Translates controller action results into valid `Plug.Conn` responses. See `Phoenix.Controller.action_fallback/1` for more details. """ use MyApiWeb, :controller def call(conn, {:error, %Ecto.Changeset{} = changeset}) do conn |> put_status(:unprocessable_entity) |> put_view(MyApiWeb.ChangesetView) |> render("error.json", changeset: changeset) end def call(conn, {:error, :not_found}) do conn |> put_status(:not_found) |> put_view(MyApiWeb.ErrorView) |> render(:"404") end def call(conn, {:error, :unauthorized}) do conn |> put_status(:unauthorized) |> json(%{error: "Login error"}) end end
24.758621
72
0.672702
73a5e12c8c691e9af9f1b6d41cbd8cd185b4b27e
452
exs
Elixir
test/advent_of_code/day_19_test.exs
mugimaru73/adventofcode2018
24ff5b2b8327b17b3242d3167bf7cc691199da86
[ "MIT" ]
1
2018-12-03T11:24:19.000Z
2018-12-03T11:24:19.000Z
test/advent_of_code/day_19_test.exs
mugimaru73/adventofcode2018
24ff5b2b8327b17b3242d3167bf7cc691199da86
[ "MIT" ]
null
null
null
test/advent_of_code/day_19_test.exs
mugimaru73/adventofcode2018
24ff5b2b8327b17b3242d3167bf7cc691199da86
[ "MIT" ]
null
null
null
defmodule AdventOfCode.Day19Test do use ExUnit.Case, async: true import AdventOfCode.Day19 @input Enum.join( [ "#ip 0", "seti 5 0 1", "seti 6 0 2", "addi 0 1 0", "addr 1 2 3", "setr 1 0 0", "seti 8 0 4", "seti 9 0 5" ], "\n" ) test "solves part 1" do assert 6 == solve("1", @input) end end
19.652174
35
0.40708
73a5fb5e7a797e5c230f964f829b3574232ce8e0
1,579
ex
Elixir
clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/v1_disable_consumer_response.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/v1_disable_consumer_response.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/v1_disable_consumer_response.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.ServiceConsumerManagement.V1.Model.V1DisableConsumerResponse do @moduledoc """ Response message for the &#x60;DisableConsumer&#x60; method. This response message is assigned to the &#x60;response&#x60; field of the returned Operation when that operation is done. ## Attributes """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{} end defimpl Poison.Decoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.V1DisableConsumerResponse do def decode(value, options) do GoogleApi.ServiceConsumerManagement.V1.Model.V1DisableConsumerResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.V1DisableConsumerResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.088889
185
0.777074
73a60698d87170fb313fa635d03f27230fdd8508
734
exs
Elixir
apps/artemis/config/test.exs
chrislaskey/atlas_platform
969aea95814f62d3471f93000ee5ad77edb9d1bf
[ "MIT" ]
10
2019-07-05T19:59:20.000Z
2021-05-23T07:36:11.000Z
apps/artemis/config/test.exs
chrislaskey/atlas_platform
969aea95814f62d3471f93000ee5ad77edb9d1bf
[ "MIT" ]
3
2019-03-05T23:55:09.000Z
2019-05-29T13:46:34.000Z
apps/artemis/config/test.exs
chrislaskey/atlas_platform
969aea95814f62d3471f93000ee5ad77edb9d1bf
[ "MIT" ]
4
2019-07-05T20:04:08.000Z
2021-05-13T16:28:33.000Z
use Mix.Config # Set the log level # # The order from most information to least: # # :debug # :info # :warn # config :logger, level: :info config :artemis, :actions, repo_delete_all: [enabled: "false"], repo_generate_filler_data: [enabled: "false"], repo_reset_on_interval: [enabled: "false"] config :artemis, Artemis.Repo, username: System.get_env("ARTEMIS_POSTGRES_USER"), password: System.get_env("ARTEMIS_POSTGRES_PASS"), database: System.get_env("ARTEMIS_POSTGRES_DB") <> "_test", hostname: System.get_env("ARTEMIS_POSTGRES_HOST"), port: System.get_env("ARTEMIS_POSTGRES_PORT"), ssl: Enum.member?(["true", "\"true\""], System.get_env("ARTEMIS_POSTGRES_SSL_ENABLED")), pool: Ecto.Adapters.SQL.Sandbox
28.230769
90
0.726158
73a60b4fd667b6e65ecfec4433624ccd71f42d4d
444
ex
Elixir
web/helpers/session.ex
lexa62/hb
c6b2169ad3e5af546da3f7ad0d499f5d5d29d044
[ "MIT" ]
null
null
null
web/helpers/session.ex
lexa62/hb
c6b2169ad3e5af546da3f7ad0d499f5d5d29d044
[ "MIT" ]
null
null
null
web/helpers/session.ex
lexa62/hb
c6b2169ad3e5af546da3f7ad0d499f5d5d29d044
[ "MIT" ]
null
null
null
defmodule Hb.Session do alias Hb.{Repo, User} def authenticate(%{"email" => email, "password" => password}) do user = Repo.get_by(User, email: String.downcase(email)) case check_password(user, password) do true -> {:ok, user} _ -> :error end end defp check_password(user, password) do case user do nil -> false _ -> Comeonin.Bcrypt.checkpw(password, user.encrypted_password) end end end
22.2
69
0.641892
73a6219d50f12562a419ca7ca9e40f851f698c7d
4,448
exs
Elixir
test/messages.exs
sdrew/protox
c28d02f1626b5cd39bad7de2b415d20ebbdf76ee
[ "MIT" ]
18
2017-03-02T16:46:10.000Z
2019-12-07T03:31:16.000Z
test/messages.exs
sdrew/protox
c28d02f1626b5cd39bad7de2b415d20ebbdf76ee
[ "MIT" ]
8
2017-09-21T21:45:33.000Z
2020-05-13T18:54:01.000Z
test/messages.exs
sdrew/protox
c28d02f1626b5cd39bad7de2b415d20ebbdf76ee
[ "MIT" ]
2
2018-02-26T13:13:08.000Z
2020-05-12T07:01:36.000Z
defmodule Defs do use Protox.Define, enums: [ { E, [ {0, :FOO}, {1, :BAZ}, {1, :BAR}, {-1, :NEG} ] }, { F, [ {1, :ONE}, {2, :TWO} ] } ], messages: [ { Protobuf2, :proto2, [ {1, :optional, :a, {:default, 0}, :uint64}, {25, :optional, :s, {:default, :TWO}, {:enum, F}}, {26, :optional, :t, {:default, :ONE}, {:enum, F}} ] }, { Sub, :proto3, [ # tag label name kind type {1, :optional, :a, {:default, 0}, :int32}, {2, :optional, :b, {:default, ""}, :string}, {6, :optional, :c, {:default, 0}, :int64}, {7, :optional, :d, {:default, 0}, :uint32}, {8, :optional, :e, {:default, 0}, :uint64}, {9, :optional, :f, {:default, 0}, :sint64}, {13, :repeated, :g, :packed, :fixed64}, {14, :repeated, :h, :packed, :sfixed32}, {15, :repeated, :i, :packed, :double}, {16, :repeated, :j, :unpacked, :int32}, {17, :optional, :k, {:default, 0}, :fixed32}, {18, :optional, :l, {:default, 0}, :sfixed64}, {19, :optional, :m, {:default, <<>>}, :bytes}, {20, :repeated, :n, :packed, :bool}, {21, :repeated, :o, :packed, {:enum, E}}, {22, :repeated, :p, :unpacked, :bool}, {23, :repeated, :q, :unpacked, {:enum, E}}, {24, :optional, :r, {:default, :FOO}, {:enum, E}}, {27, :repeated, :u, :packed, :uint32}, {28, :repeated, :w, :packed, :sint32}, {29, :repeated, :x, :packed, :int64}, {30, :repeated, :y, :packed, :uint64}, {10_001, :optional, :z, {:default, 0}, :sint32}, {10_002, :optional, :zz, {:default, 0}, :sint64}, {12_345, nil, :map1, :map, {:sfixed64, :bytes}}, {12_346, nil, :map2, :map, {:sfixed64, :bytes}} ] }, { Msg, :proto3, [ {27, :repeated, :msg_a, :packed, :sint64}, {28, :repeated, :msg_b, :packed, :fixed32}, {29, :repeated, :msg_c, :packed, :sfixed64}, {1, :optional, :msg_d, {:default, :FOO}, {:enum, E}}, {2, :optional, :msg_e, {:default, false}, :bool}, {3, :optional, :msg_f, {:default, nil}, {:message, Sub}}, {4, :repeated, :msg_g, :packed, :int32}, {5, :optional, :msg_h, {:default, 0.0}, :double}, {6, :repeated, :msg_i, :packed, :float}, {7, :repeated, :msg_j, :unpacked, {:message, Sub}}, {8, nil, :msg_k, :map, {:int32, :string}}, {9, nil, :msg_l, :map, {:string, :double}}, {10, :optional, :msg_n, {:oneof, :msg_m}, :string}, {11, :optional, :msg_o, {:oneof, :msg_m}, {:message, Sub}}, {12, nil, :msg_p, :map, {:int32, {:enum, E}}}, {13, :optional, :msg_q, {:default, nil}, {:message, Protobuf2}}, {118, :optional, :msg_oneof_double, {:oneof, :msg_oneof_field}, :double} ] }, { Upper, :proto3, [ {1, :optional, :msg, {:default, nil}, {:message, Msg}}, {2, nil, :msg_map, :map, {:string, {:message, Msg}}}, {3, :optional, :empty, {:default, nil}, {:message, Empty}}, {4, :optional, :req, {:default, nil}, {:message, Required}} ] }, { Empty, :proto3, [] }, { Required, :proto2, [ {1, :required, :a, {:default, 0}, :int32}, {2, :optional, :b, {:default, 0}, :int32} ] }, { NoNameClash, :proto3, [ {1, :optional, :__uf__, {:default, 0}, :int32} ] }, { NestedMessage, :proto3, [ {1, :none, :a, {:default, 0}, :int32}, {2, :none, :corecursive, {:default, nil}, {:message, TestAllTypesProto3}} ] }, { TestAllTypesProto3, :proto3, [ {112, :none, :oneof_nested_message, {:oneof, :oneof_field}, {:message, NestedMessage}} ] }, { FloatPrecision, :proto3, [ {1, :optional, :a, {:default, 0.0}, :double}, {2, :optional, :b, {:default, 0.0}, :float} ] } ] end
31.323944
96
0.41884
73a66d238675547fbdd21f1cb7f35e803a4bc5b2
2,756
ex
Elixir
lib/squadster/accounts/tasks/notify.ex
Squadster/squadster-api
cf04af79317148d7a08c649d5b5d0197722acb7a
[ "MIT" ]
null
null
null
lib/squadster/accounts/tasks/notify.ex
Squadster/squadster-api
cf04af79317148d7a08c649d5b5d0197722acb7a
[ "MIT" ]
null
null
null
lib/squadster/accounts/tasks/notify.ex
Squadster/squadster-api
cf04af79317148d7a08c649d5b5d0197722acb7a
[ "MIT" ]
null
null
null
defmodule Squadster.Accounts.Tasks.Notify do use Task import Mockery.Macro alias Squadster.Formations.Squad alias Squadster.Formations.SquadMember alias Squadster.Accounts.User alias Squadster.Mailer alias Squadster.Mailer.Emails.NotifyEmail alias Squadster.Repo @bot_endpoint Application.fetch_env!(:squadster, :bot_url) <> "/message" @bot_token "ApiKey " <> Application.fetch_env!(:squadster, :bot_token) @request_headers [{"content-type", "application/json"}, {"Authorization", @bot_token}] @settings_fields [:vk_notifications_enabled, :telegram_notifications_enabled, :email_notifications_enabled] def start_link(args) do Task.start_link(__MODULE__, :notify, [args]) end def notify([message: message, target: target]), do: message |> send_to(target) def notify([message: message, target: target, options: options]), do: message |> send_to(target, options) defp send_to(message, %User{} = user) do user_with_settings = user |> Repo.preload(:settings) if user_with_settings.settings.email_notifications_enabled and user.email do user.email |> mockable(Mailer).send("Squadster notification", NotifyEmail.html_template(message, user), NotifyEmail.text_template(message, user)) end mockable(HTTPoison).post @bot_endpoint, request_body(message, user_with_settings), @request_headers end defp send_to(message, %SquadMember{user_id: user_id}) do message |> send_to(User |> Repo.get(user_id)) end defp send_to(message, %Squad{} = squad, options \\ []) do defaults = [skip_commander: false, skip_deputy: false, skip_journalist: false, skip: []] options = Keyword.merge(defaults, options) |> Enum.into(%{}) squad |> Ecto.assoc(:members) |> Repo.all |> Enum.reject(fn member -> member.user_id in options[:skip] end) |> Enum.reject(fn member -> options[:skip_commander] && member.role == :commander end) |> Enum.reject(fn member -> options[:skip_deputy] && member.role == :deputy_commander end) |> Enum.reject(fn member -> options[:skip_journalist] && member.role == :journalist end) |> Enum.each(fn member -> message |> send_to(member) end) end defp request_body(message, %User{id: id, settings: settings}) do """ { "text": "#{message}", "target": #{id}, "channels": #{settings |> user_notification_channels |> Poison.encode!} } """ end defp user_notification_channels(settings) do @settings_fields |> Enum.map(fn field -> if settings |> Map.get(field) do [channel | _] = field |> Atom.to_string |> String.split("_") channel end end) |> Enum.filter(fn channel -> !is_nil(channel) end) end end
35.792208
109
0.680334
73a6b37c07d5e7ade07fe2cae7f104d7e647850f
2,957
exs
Elixir
test/ex_doc_test.exs
kdawgwilk/ex_doc
fcfd2b9256fec710ce96d3b4a713a36cf57f34ad
[ "Apache-2.0", "CC-BY-4.0" ]
1,206
2015-01-02T02:05:12.000Z
2022-03-29T17:18:10.000Z
test/ex_doc_test.exs
kdawgwilk/ex_doc
fcfd2b9256fec710ce96d3b4a713a36cf57f34ad
[ "Apache-2.0", "CC-BY-4.0" ]
1,266
2015-01-03T03:26:04.000Z
2022-03-31T09:43:53.000Z
test/ex_doc_test.exs
elixir-lang/ex_doc
a075ba2faa48dae3d4b2cf7fcf398a6155ee0fc8
[ "Apache-2.0", "CC-BY-4.0" ]
300
2015-01-03T04:07:24.000Z
2022-03-29T08:10:56.000Z
defmodule ExDocTest do use ExUnit.Case # Simple retriever that returns whatever is passed into it defmodule IdentityRetriever do def docs_from_dir(source, config) do {source, config} end end # Simple formatter that returns whatever is passed into it defmodule IdentityFormatter do def run(modules, config) do {modules, config} end end test "build_config & normalize_options" do project = "Elixir" version = "1" opts_with_output = &[ apps: [:test_app], formatter: IdentityFormatter, retriever: IdentityRetriever, source_beam: "beam_dir", output: &1 ] {_, config} = ExDoc.generate_docs(project, version, opts_with_output.("test/tmp/ex_doc")) assert config.output == "test/tmp/ex_doc" {_, config} = ExDoc.generate_docs(project, version, opts_with_output.("test/tmp/ex_doc/")) assert config.output == "test/tmp/ex_doc" {_, config} = ExDoc.generate_docs(project, version, opts_with_output.("test/tmp/ex_doc//")) assert config.output == "test/tmp/ex_doc" end test "uses custom markdown processor" do project = "Elixir" version = "1" options = [ apps: [:test_app], formatter: IdentityFormatter, markdown_processor: Sample, output: "test/tmp/ex_doc", retriever: IdentityRetriever, source_beam: "beam_dir" ] ExDoc.generate_docs(project, version, options) assert Application.fetch_env!(:ex_doc, :markdown_processor) == {Sample, []} after Application.delete_env(:ex_doc, :markdown_processor) end test "uses custom markdown processor with custom options" do project = "Elixir" version = "1" options = [ apps: [:test_app], formatter: IdentityFormatter, markdown_processor: {Sample, [foo: :bar]}, output: "test/tmp/ex_doc", retriever: IdentityRetriever, source_beam: "beam_dir" ] ExDoc.generate_docs(project, version, options) assert Application.fetch_env!(:ex_doc, :markdown_processor) == {Sample, [foo: :bar]} after Application.delete_env(:ex_doc, :markdown_processor) end test "source_beam sets source dir" do options = [ apps: [:test_app], formatter: IdentityFormatter, retriever: IdentityRetriever, source_beam: "beam_dir" ] {{source_dir, _retr_config}, _config} = ExDoc.generate_docs("Elixir", "1", options) assert source_dir == options[:source_beam] end test "formatter module not found" do project = "Elixir" version = "1" options = [ apps: [:test_app], formatter: "pdf", retriever: IdentityRetriever, source_beam: "beam_dir" ] assert_raise RuntimeError, "formatter module \"pdf\" not found", fn -> ExDoc.generate_docs(project, version, options) end end test "version" do assert {:ok, _version} = Version.parse(ExDoc.version()) end end
26.63964
95
0.654041
73a6b55d0c7cc927c41ac3ae92f19414bcc1edee
1,539
exs
Elixir
api/knot/mix.exs
lukasz-madon/knot
4c56af2d9d73b088af9e66b87d1ce85df752ad8d
[ "MIT" ]
null
null
null
api/knot/mix.exs
lukasz-madon/knot
4c56af2d9d73b088af9e66b87d1ce85df752ad8d
[ "MIT" ]
null
null
null
api/knot/mix.exs
lukasz-madon/knot
4c56af2d9d73b088af9e66b87d1ce85df752ad8d
[ "MIT" ]
null
null
null
defmodule Knot.Mixfile do use Mix.Project def project do [app: :knot, 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: {Knot, []}, 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.037736
78
0.602989
73a6c3b7b85e5a9369849aa59955b8c90882529b
1,589
ex
Elixir
lib/elenchos_ex_web.ex
maxneuvians/elenchos_ex
03b31e848dafe12614a01104f89d9477c7b21025
[ "MIT" ]
null
null
null
lib/elenchos_ex_web.ex
maxneuvians/elenchos_ex
03b31e848dafe12614a01104f89d9477c7b21025
[ "MIT" ]
null
null
null
lib/elenchos_ex_web.ex
maxneuvians/elenchos_ex
03b31e848dafe12614a01104f89d9477c7b21025
[ "MIT" ]
null
null
null
defmodule ElenchosExWeb 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 ElenchosExWeb, :controller use ElenchosExWeb, :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: ElenchosExWeb import Plug.Conn import ElenchosExWeb.Gettext alias ElenchosExWeb.Router.Helpers, as: Routes end end def view do quote do use Phoenix.View, root: "lib/elenchos_ex_web/templates", namespace: ElenchosExWeb # Import convenience functions from controllers import Phoenix.Controller, only: [get_flash: 1, get_flash: 2, view_module: 1] import ElenchosExWeb.ErrorHelpers import ElenchosExWeb.Gettext alias ElenchosExWeb.Router.Helpers, as: Routes end end def router do quote do use Phoenix.Router import Plug.Conn import Phoenix.Controller end end def channel do quote do use Phoenix.Channel import ElenchosExWeb.Gettext end end @doc """ When used, dispatch to the appropriate controller/view/etc. """ defmacro __using__(which) when is_atom(which) do apply(__MODULE__, which, []) end end
23.716418
83
0.699182
73a6dd67408d650f4b976c8ec868c3f7001649b1
2,241
ex
Elixir
lib/pow/store/base.ex
randaalex/pow
2a8c8db4652f7cb2c58d3a897e02b1d47e76f27b
[ "MIT" ]
null
null
null
lib/pow/store/base.ex
randaalex/pow
2a8c8db4652f7cb2c58d3a897e02b1d47e76f27b
[ "MIT" ]
null
null
null
lib/pow/store/base.ex
randaalex/pow
2a8c8db4652f7cb2c58d3a897e02b1d47e76f27b
[ "MIT" ]
1
2020-07-13T01:11:17.000Z
2020-07-13T01:11:17.000Z
defmodule Pow.Store.Base do @moduledoc """ Used to set up API for key-value cache store. ## Usage defmodule MyApp.CredentialsStore do use Pow.Store.Base, ttl: :timer.minutes(30), namespace: "credentials" end """ alias Pow.{Config, Store.Backend.EtsCache} @callback put(Config.t(), binary(), any()) :: :ok @callback delete(Config.t(), binary()) :: :ok @callback get(Config.t(), binary()) :: any() | :not_found @callback keys(Config.t()) :: [any()] @doc false defmacro __using__(defaults) do quote do @behaviour unquote(__MODULE__) @spec put(Config.t(), binary(), any()) :: :ok def put(config, key, value), do: unquote(__MODULE__).put(config, backend_config(config), key, value) @spec delete(Config.t(), binary()) :: :ok def delete(config, key), do: unquote(__MODULE__).delete(config, backend_config(config), key) @spec get(Config.t(), binary()) :: any() | :not_found def get(config, key), do: unquote(__MODULE__).get(config, backend_config(config), key) @spec keys(Config.t()) :: [any()] def keys(config), do: unquote(__MODULE__).keys(config, backend_config(config)) defp backend_config(config) do [ ttl: Config.get(config, :ttl, unquote(defaults[:ttl])), namespace: Config.get(config, :namespace, unquote(defaults[:namespace])) ] end defoverridable unquote(__MODULE__) end end @doc false @spec put(Config.t(), Config.t(), binary(), any()) :: :ok def put(config, backend_config, key, value) do store(config).put(backend_config, key, value) end @doc false @spec delete(Config.t(), Config.t(), binary()) :: :ok def delete(config, backend_config, key) do store(config).delete(backend_config, key) end @doc false @spec get(Config.t(), Config.t(), binary()) :: any() | :not_found def get(config, backend_config, key) do store(config).get(backend_config, key) end @doc false @spec keys(Config.t(), Config.t()) :: [any()] def keys(config, backend_config) do store(config).keys(backend_config) end defp store(config) do Config.get(config, :backend, EtsCache) end end
28.0125
82
0.624721
73a722950128c7dab98372a475bcb7af52193abf
1,626
exs
Elixir
test/deejay/tuple_value_test.exs
ngzax/deejay
ce32449c3ba58675796ccad92be347029de280f7
[ "BSD-3-Clause" ]
null
null
null
test/deejay/tuple_value_test.exs
ngzax/deejay
ce32449c3ba58675796ccad92be347029de280f7
[ "BSD-3-Clause" ]
null
null
null
test/deejay/tuple_value_test.exs
ngzax/deejay
ce32449c3ba58675796ccad92be347029de280f7
[ "BSD-3-Clause" ]
null
null
null
defmodule DeeJayTupleValueTest do use ExSpec, async: true doctest DeeJay.TupleValue import DeeJay.TupleValue test "Is represented as a 3-valued normal Elixir tuple" do assert tuple_value(:s_id, 1) == {:s_id, :integer, 1} end describe "The first element is called the attribute" do test "attribute created using tuple_value()" do assert attribute(tuple_value(:s_id, 1)) == :s_id end test "attribute created using a valid 3-value tuple" do assert attribute({:s_id, :integer, 1}) == :s_id end # I am not sure why this passes right now, shouldn't the spec prevent it. test "returns an error if tuple is constructed incorrectly" do assert attribute({1, 1, :integer}) == 1 end end describe "The second element is called the value" do test "value created using tuple_value()" do assert value(tuple_value(:s_id, 1)) == 1 end test "value created using a valid 3-value tuple" do assert value({:s_id, :integer, 1}) == 1 end end describe "The type is inferred from the value" do it "recognizes an integer" do assert type(tuple_value(:s_id, 1)) == :integer end it "recognizes a float" do assert type(tuple_value(:s_id, 1.1)) == :float end it "recognizes a String" do assert type(tuple_value(:s_id, "Magic")) == :string end it "recognizes a Boolean" do assert type(tuple_value(:s_id, true)) == :boolean end it "returns :any for a type it doesn't recognize" do assert type(tuple_value(:s_id, {1, 2, 3})) == :any end end end
27.559322
77
0.641451
73a73673b10586096b5a6892d52b8d9fe098839e
314
ex
Elixir
lib/openflow/barrier/reply.ex
shun159/tres
1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f
[ "Beerware" ]
5
2019-05-25T02:25:13.000Z
2020-10-06T17:00:03.000Z
lib/openflow/barrier/reply.ex
shun159/tres
1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f
[ "Beerware" ]
5
2018-03-29T14:42:10.000Z
2019-11-19T07:03:09.000Z
lib/openflow/barrier/reply.ex
shun159/tres
1e3e7f78ba1aa4f184d4be70300e5f4703d50a2f
[ "Beerware" ]
1
2019-03-30T20:48:27.000Z
2019-03-30T20:48:27.000Z
defmodule Openflow.Barrier.Reply do defstruct( version: 4, xid: 0, # virtual field datapath_id: nil, # virtual field aux_id: 0 ) alias __MODULE__ def ofp_type, do: 21 def new(xid \\ 0), do: %Reply{xid: xid} def read(_), do: %Reply{} def to_binary(%Reply{}), do: <<>> end
14.952381
41
0.595541
73a767b8f4e32b3095cc5668f5bcf6cff523d29d
413
ex
Elixir
survey/lib/survey/video_cam.ex
RamanBut-Husaim/pragstudio-elixir
21c723c933966798ae944ca2fd72697e9d0f2fa2
[ "MIT" ]
null
null
null
survey/lib/survey/video_cam.ex
RamanBut-Husaim/pragstudio-elixir
21c723c933966798ae944ca2fd72697e9d0f2fa2
[ "MIT" ]
null
null
null
survey/lib/survey/video_cam.ex
RamanBut-Husaim/pragstudio-elixir
21c723c933966798ae944ca2fd72697e9d0f2fa2
[ "MIT" ]
null
null
null
defmodule Survey.VideoCam do @doc """ Simulates sending a request to an external API to get a snapshot image from a video camera. """ def get_snapshot(camera_name) do # CODE GOES HERE TO SEND A REQUEST TO THE EXTERNAL API # Sleep for 1 second to simulate that the API can be slow: :timer.sleep(1000) # Example response returned from the API: "#{camera_name}-snapshot.jpg" end end
27.533333
62
0.7046
73a78b6e184156bd13bdf8a2dcbf6bc75621ca83
488
exs
Elixir
spec/lib/errors/substitution_spec.exs
gmartsenkov/gate
67a1d9a3b0c0515312b49e9a110cb00ebc46d402
[ "MIT" ]
3
2019-11-04T21:40:10.000Z
2021-12-22T11:25:37.000Z
spec/lib/errors/substitution_spec.exs
gmartsenkov/gate
67a1d9a3b0c0515312b49e9a110cb00ebc46d402
[ "MIT" ]
null
null
null
spec/lib/errors/substitution_spec.exs
gmartsenkov/gate
67a1d9a3b0c0515312b49e9a110cb00ebc46d402
[ "MIT" ]
null
null
null
defmodule Gate.Errors.SubstitutionSpec do use ESpec describe "substitute" do subject do: described_module().substitute(text(), args()) let :text, do: "this {} proves that substitutions {}" let :args, do: ["test", "work"] it do: is_expected() |> to(eq "this test proves that substitutions work") context "when args is a single value" do let :args, do: "test" it do: is_expected() |> to(eq "this test proves that substitutions {}") end end end
27.111111
77
0.651639
73a790867b6c62e92162be8e02704e154eca5e13
1,315
ex
Elixir
apps/tai/lib/tai/symbol.ex
ihorkatkov/tai
09f9f15d2c385efe762ae138a8570f1e3fd41f26
[ "MIT" ]
276
2018-01-16T06:36:06.000Z
2021-03-20T21:48:01.000Z
apps/tai/lib/tai/symbol.ex
ihorkatkov/tai
09f9f15d2c385efe762ae138a8570f1e3fd41f26
[ "MIT" ]
78
2020-10-12T06:21:43.000Z
2022-03-28T09:02:00.000Z
apps/tai/lib/tai/symbol.ex
ihorkatkov/tai
09f9f15d2c385efe762ae138a8570f1e3fd41f26
[ "MIT" ]
43
2018-06-09T09:54:51.000Z
2021-03-07T07:35:17.000Z
defmodule Tai.Symbol do @moduledoc """ Transform symbols between tai and exchange formats """ def downcase(symbol) when is_atom(symbol) do symbol |> Atom.to_string() |> String.downcase() end def downcase(symbol) do symbol |> String.downcase() end def downcase_all(symbols) do symbols |> Enum.map(&downcase(&1)) end def upcase(symbol) when is_atom(symbol) do symbol |> Atom.to_string() |> String.upcase() end def upcase(symbol) do symbol |> String.upcase() end @spec build(String.t(), String.t()) :: atom def build(base_asset, quote_asset) when is_binary(base_asset) and is_binary(quote_asset) do "#{base_asset}_#{quote_asset}" |> String.downcase() |> String.to_atom() end def base_and_quote(symbol) when is_binary(symbol) do assets = String.split(symbol, "_") assets_count = Enum.count(assets) if assets_count == 2 do [base_asset, quote_asset] = Enum.map(assets, &String.to_atom/1) {:ok, {base_asset, quote_asset}} else {:error, :symbol_format_must_be_base_quote} end end def base_and_quote(symbol) when is_atom(symbol) do symbol |> Atom.to_string() |> base_and_quote end def base_and_quote(_), do: {:error, :symbol_must_be_an_atom_or_string} end
21.557377
72
0.659316
73a79d1d1809286d203c8344f78aea9933485cdf
163
ex
Elixir
test/support/repo.ex
zumatande/kerosene
d509ab8a96aa67fe47920e2dbbcd268a7ad14786
[ "MIT" ]
238
2016-03-10T05:22:45.000Z
2022-02-05T11:55:00.000Z
test/support/repo.ex
zumatande/kerosene
d509ab8a96aa67fe47920e2dbbcd268a7ad14786
[ "MIT" ]
53
2016-06-26T16:20:47.000Z
2021-12-23T12:41:30.000Z
test/support/repo.ex
zumatande/kerosene
d509ab8a96aa67fe47920e2dbbcd268a7ad14786
[ "MIT" ]
47
2016-03-23T09:13:25.000Z
2021-12-10T05:55:26.000Z
defmodule Kerosene.Repo do use Ecto.Repo, otp_app: :kerosene, adapter: Ecto.Adapters.Postgres use Kerosene, otp_app: :kerosene, per_page: 10 end
23.285714
49
0.705521
73a7a8b523b05327d22a7c945dccf2facbe870ea
1,279
ex
Elixir
apps/neoscan/lib/neoscan/blocks/block_gas_generation.ex
decentralisedkev/neo-scan
c8a35a0952e8c46d40365e0ac76bce361ac5e558
[ "MIT" ]
null
null
null
apps/neoscan/lib/neoscan/blocks/block_gas_generation.ex
decentralisedkev/neo-scan
c8a35a0952e8c46d40365e0ac76bce361ac5e558
[ "MIT" ]
null
null
null
apps/neoscan/lib/neoscan/blocks/block_gas_generation.ex
decentralisedkev/neo-scan
c8a35a0952e8c46d40365e0ac76bce361ac5e558
[ "MIT" ]
null
null
null
defmodule Neoscan.BlockGasGeneration do @moduledoc false @generation_amount [8, 7, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] @generation_length 22 @decrement_interval 2_000_000 @doc """ Calculate the amount of gas generated by a block """ def get_amount_generate_in_block(nil), do: nil def get_amount_generate_in_block(0), do: Enum.at(@generation_amount, 0) |> Decimal.new() def get_amount_generate_in_block(index) do if Integer.floor_div(index, @decrement_interval) > @generation_length do Decimal.new(0) else position = Integer.floor_div(index, @decrement_interval) Enum.at(@generation_amount, position) |> Decimal.new() end end def get_range_amount(min, max) do generation = for x <- 1..Enum.count(@generation_amount) do {Enum.at(@generation_amount, x - 1), (x - 1) * @decrement_interval, x * @decrement_interval - 1} end [{gas, _, rmax} | t] = Enum.filter(generation, fn {_, rmin, rmax} -> min <= rmax and max >= rmin end) [{gas, rmin, _} | t] = Enum.reverse([{gas, min, rmax} | t]) generation = Enum.reverse([{gas, rmin, max} | t]) Enum.reduce(generation, 0, fn {gas, min, max}, acc -> acc + gas * (max - min + 1) end) end end
30.452381
90
0.633307
73a7b0f7d7d3dd40b701557bcc1a40c5af6cf411
997
exs
Elixir
apps/game_of_life/mix.exs
grrrisu/thundermoon-mvp
17939d51c7b07216dfd63ba1b2ba53d56f94a48d
[ "MIT" ]
null
null
null
apps/game_of_life/mix.exs
grrrisu/thundermoon-mvp
17939d51c7b07216dfd63ba1b2ba53d56f94a48d
[ "MIT" ]
null
null
null
apps/game_of_life/mix.exs
grrrisu/thundermoon-mvp
17939d51c7b07216dfd63ba1b2ba53d56f94a48d
[ "MIT" ]
null
null
null
defmodule GameOfLife.MixProject do use Mix.Project def project do [ app: :game_of_life, version: "0.6.0", build_path: "../../_build", config_path: "../../config/config.exs", deps_path: "../../deps", lockfile: "../../mix.lock", elixir: "~> 1.12", elixirc_paths: elixirc_paths(Mix.env()), start_permanent: Mix.env() == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger], mod: {GameOfLife.Application, []} ] end # Specifies which paths to compile per environment. defp elixirc_paths(env) when env in [:test, :integration], do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Run "mix help deps" to learn about dependencies. defp deps do [ {:sim, in_umbrella: true}, {:phoenix_pubsub, "~> 2.0"}, {:credo, "~> 1.5", only: [:dev, :test], runtime: false} ] end end
24.925
88
0.583751
73a7b59abde69fbd79a9bae4f4777b8f72582399
1,120
exs
Elixir
test/index_test.exs
kjg/geef
9e9aa23af7614cb398e99fb06019884af2cbcd79
[ "MIT" ]
107
2015-01-08T12:05:20.000Z
2022-03-21T20:36:43.000Z
test/index_test.exs
kjg/geef
9e9aa23af7614cb398e99fb06019884af2cbcd79
[ "MIT" ]
9
2015-03-11T18:32:24.000Z
2020-03-29T21:08:55.000Z
test/index_test.exs
kjg/geef
9e9aa23af7614cb398e99fb06019884af2cbcd79
[ "MIT" ]
28
2015-03-03T16:01:26.000Z
2022-02-20T19:18:03.000Z
defmodule IndexTest do use ExUnit.Case use Geef alias Geef.Index import RepoHelpers setup do {repo, path} = tmp_bare() Process.link(repo) on_exit(fn -> File.rm_rf!(path) end) {:ok, [repo: repo, path: path]} end test "add an entry to the index", meta do repo = meta[:repo] content = "This is some text that will go in a file" {:ok, odb} = Repository.odb(repo) {:ok, id} = Odb.write(odb, content, :blob) assert id == Oid.parse("c300118399f01fe52b316061b5d32beb27e0adfd") {:ok, idx} = Index.new {now_mega, now_secs, _} = :os.timestamp() time = now_mega * 1000000 + now_secs entry = %Geef.Index.Entry{mode: 0o100644, id: id, path: "README", size: byte_size(content), mtime: time} :ok = Index.add(idx, entry) {:ok, tree_id} = Index.write_tree(idx, repo) expected = Oid.parse("5a20bbbf65ea75ad4d9f995d179156824ccca3a1") assert tree_id == expected {:ok, entry1} = Index.get(idx, "README", 0) # entry2 = idx["README"] # assert entry1 == entry2 assert entry1.size == byte_size(content) Repository.stop(repo) end end
25.454545
108
0.644643
73a7d1b2f72e16238c966d73a64a7a834e3cb9bf
1,206
ex
Elixir
apps/financial_system_web/lib/financial_system_web/controllers/transfer_controller.ex
juniornelson123/tech-challenge-stone
e27b767514bf42a5ade5228de56c3c7ea38459d7
[ "MIT" ]
null
null
null
apps/financial_system_web/lib/financial_system_web/controllers/transfer_controller.ex
juniornelson123/tech-challenge-stone
e27b767514bf42a5ade5228de56c3c7ea38459d7
[ "MIT" ]
2
2021-03-10T03:19:32.000Z
2021-09-02T04:33:17.000Z
apps/financial_system_web/lib/financial_system_web/controllers/transfer_controller.ex
juniornelson123/tech-challenge-stone
e27b767514bf42a5ade5228de56c3c7ea38459d7
[ "MIT" ]
null
null
null
defmodule FinancialSystemWeb.TransferController do use FinancialSystemWeb, :controller alias FinancialSystem.Transaction.Transfer alias FinancialSystem.Money alias FinancialSystem.Transaction alias FinancialSystem.Repo def index(conn, %{"account_id" => account_id}) do account = Transaction.get_account! account_id transfers = Transaction.list_transfers(account_id) |> Repo.preload([[account: :user], [items: [account_received: :user]]]) render(conn, "index.html", transfers: transfers, account: account) end def new(conn, %{"account_id" => account_id}) do account = Transaction.get_account! account_id changeset = Transaction.change_transfer(%Transfer{}) render(conn, "new.html", changeset: changeset, account: account) end def create(conn, %{"transfer" => transfer_params, "account_id" => account_id}) do # case Transaction.create_account(account_params) do # {:ok, account} -> # conn # |> put_flash(:info, "Account save") # |> redirect(to: Routes.account_path(conn, :show, account)) # {:error, changeset} -> # IO.inspect changeset # render(conn, "new.html", changeset: changeset) # end end end
37.6875
126
0.696517
73a7e83f9255b180a1da3c2f8267f37adb551f4a
1,083
ex
Elixir
lib/xeroxero/core_api/manual_journals.ex
scottmessinger/elixero
4e62c4d80d221639ba2347a563002511e8d4a6c6
[ "MIT" ]
1
2021-12-01T18:21:31.000Z
2021-12-01T18:21:31.000Z
lib/xeroxero/core_api/manual_journals.ex
scottmessinger/elixero
4e62c4d80d221639ba2347a563002511e8d4a6c6
[ "MIT" ]
null
null
null
lib/xeroxero/core_api/manual_journals.ex
scottmessinger/elixero
4e62c4d80d221639ba2347a563002511e8d4a6c6
[ "MIT" ]
1
2021-10-01T12:09:46.000Z
2021-10-01T12:09:46.000Z
defmodule XeroXero.CoreApi.ManualJournals do @resource "manualjournals" @model_module XeroXero.CoreApi.Models.ManualJournals def find(client) do XeroXero.CoreApi.Common.find(client, @resource) |> XeroXero.CoreApi.Utils.ResponseHandler.handle_response(@model_module) end def find(client, identifier) do XeroXero.CoreApi.Common.find(client, @resource, identifier) |> XeroXero.CoreApi.Utils.ResponseHandler.handle_response(@model_module) end def filter(client, filter) do XeroXero.CoreApi.Common.filter(client, @resource, filter) |> XeroXero.CoreApi.Utils.ResponseHandler.handle_response(@model_module) end def create(client, manual_journals_map) do XeroXero.CoreApi.Common.create(client, @resource, manual_journals_map) |> XeroXero.CoreApi.Utils.ResponseHandler.handle_response(@model_module) end def update(client, identifier, manual_journals_map) do XeroXero.CoreApi.Common.update(client, @resource, identifier, manual_journals_map) |> XeroXero.CoreApi.Utils.ResponseHandler.handle_response(@model_module) end end
36.1
86
0.782087
73a7f380fa2caa248a3eb25b9cd9877679749034
25,059
ex
Elixir
lib/elixir/lib/macro.ex
enokd/elixir
e39b32f235082b8a29fcb22d250c822cca98609f
[ "Apache-2.0" ]
1
2015-11-12T19:23:45.000Z
2015-11-12T19:23:45.000Z
lib/elixir/lib/macro.ex
enokd/elixir
e39b32f235082b8a29fcb22d250c822cca98609f
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/macro.ex
enokd/elixir
e39b32f235082b8a29fcb22d250c822cca98609f
[ "Apache-2.0" ]
null
null
null
import Kernel, except: [to_string: 1] defmodule Macro do @moduledoc """ Conveniences for working with macros. """ @typedoc "Abstract Syntax Tree (AST)" @type t :: expr | { t, t } | atom | number | binary | pid | fun | [t] @typedoc "Expr node (remaining ones are literals)" @type expr :: { expr | atom, Keyword.t, atom | [t] } @binary_ops [:===, :!==, :==, :!=, :<=, :>=, :&&, :||, :<>, :++, :--, :\\, :::, :<-, :.., :|>, :=~, :<, :>, :->, :+, :-, :*, :/, :=, :|, :., :and, :or, :xor, :when, :in, :inlist, :inbits, :<<<, :>>>, :|||, :&&&, :^^^, :~~~] @doc false defmacro binary_ops, do: @binary_ops @unary_ops [:!, :@, :^, :not, :+, :-, :~~~, :&] @doc false defmacro unary_ops, do: @unary_ops @spec binary_op_props(atom) :: { :left | :right, precedence :: integer } defp binary_op_props(o) do case o do o when o in [:<-, :inlist, :inbits, :\\, :::] -> {:left, 40} :| -> {:right, 50} :when -> {:right, 70} := -> {:right, 80} o when o in [:||, :|||, :or, :xor] -> {:left, 130} o when o in [:&&, :&&&, :and] -> {:left, 140} o when o in [:==, :!=, :<, :<=, :>=, :>, :=~, :===, :!==] -> {:left, 150} o when o in [:|>, :<<<, :>>>] -> {:right, 160} :in -> {:left, 170} o when o in [:++, :--, :.., :<>] -> {:right, 200} o when o in [:+, :-] -> {:left, 210} o when o in [:*, :/] -> {:left, 220} :^^^ -> {:left, 250} :. -> {:left, 310} end end @doc """ Breaks a pipeline expression into a list. Raises if the pipeline is ill-formed. """ @spec unpipe(Macro.t) :: [Macro.t] def unpipe({ :|> , _, [left, right] }) do [left|unpipe(right)] end def unpipe(other) do [other] end @doc """ Pipes `expr` into the `call_expr` as the argument in the given `position`. """ @spec pipe(Macro.t, Macro.t, integer) :: Macro.t | no_return def pipe(expr, call_args, integer \\ 0) def pipe(expr, { :&, _, _ } = call_args, _integer) do raise ArgumentError, message: "cannot pipe #{to_string expr} into #{to_string call_args}" end def pipe(expr, { call, line, atom }, integer) when is_atom(atom) do { call, line, List.insert_at([], integer, expr) } end def pipe(expr, { call, line, args }, integer) when is_list(args) do { call, line, List.insert_at(args, integer, expr) } end def pipe(expr, call_args, _integer) do raise ArgumentError, message: "cannot pipe #{to_string expr} into #{to_string call_args}" end @doc """ Recurs the quoted expression applying the given function to each metadata node. This is often useful to remove information like lines and hygienic counters from the expression for either storage or comparison. ## Examples iex> quoted = quote line: 10, do: sample() {:sample, [line: 10], []} iex> Macro.update_meta(quoted, &Keyword.delete(&1, :line)) {:sample, [], []} """ @spec update_meta(t, (Keyword.t -> Keyword.t)) :: t def update_meta(quoted, fun) def update_meta({ left, meta, right }, fun) when is_list(meta) do { update_meta(left, fun), fun.(meta), update_meta(right, fun) } end def update_meta({ left, right }, fun) do { update_meta(left, fun), update_meta(right, fun) } end def update_meta(list, fun) when is_list(list) do for x <- list, do: update_meta(x, fun) end def update_meta(other, _fun) do other end @doc """ Decomposes a local or remote call into its remote part (when provided), function name and argument list. Returns `:error` when an invalid call syntax is provided. ## Examples iex> Macro.decompose_call(quote do: foo) { :foo, [] } iex> Macro.decompose_call(quote do: foo()) { :foo, [] } iex> Macro.decompose_call(quote do: foo(1, 2, 3)) { :foo, [1, 2, 3] } iex> Macro.decompose_call(quote do: Elixir.M.foo(1, 2, 3)) { { :__aliases__, [], [:Elixir, :M] }, :foo, [1, 2, 3] } iex> Macro.decompose_call(quote do: 42) :error """ @spec decompose_call(Macro.t) :: { atom, [Macro.t] } | { Macro.t, atom, [Macro.t] } | :error def decompose_call({ { :., _, [remote, function] }, _, args }) when is_tuple(remote) or is_atom(remote), do: { remote, function, args } def decompose_call({ name, _, args }) when is_atom(name) and is_atom(args), do: { name, [] } def decompose_call({ name, _, args }) when is_atom(name) and is_list(args), do: { name, args } def decompose_call(_), do: :error @doc """ Recursively escapes a value so it can be inserted into a syntax tree. One may pass `unquote: true` to `escape/2` which leaves `unquote` statements unescaped, effectively unquoting the contents on escape. ## Examples iex> Macro.escape(:foo) :foo iex> Macro.escape({ :a, :b, :c }) { :{}, [], [:a, :b, :c] } iex> Macro.escape({ :unquote, [], [1] }, unquote: true) 1 """ @spec escape(term) :: Macro.t @spec escape(term, Keyword.t) :: Macro.t def escape(expr, opts \\ []) do elem(:elixir_quote.escape(expr, Keyword.get(opts, :unquote, false)), 0) end @doc ~S""" Unescape the given chars. This is the unescaping behaviour used by default in Elixir single- and double-quoted strings. Check `unescape_string/2` for information on how to customize the escaping map. In this setup, Elixir will escape the following: `\a`, `\b`, `\d`, `\e`, `\f`, `\n`, `\r`, `\s`, `\t` and `\v`. Octals are also escaped according to the latin1 set they represent. This function is commonly used on sigil implementations (like `~r`, `~s` and others) which receive a raw, unescaped string. ## Examples iex> Macro.unescape_string("example\\n") "example\n" In the example above, we pass a string with `\n` escaped and return a version with it unescaped. """ @spec unescape_string(String.t) :: String.t def unescape_string(chars) do :elixir_interpolation.unescape_chars(chars) end @doc ~S""" Unescape the given chars according to the map given. Check `unescape_string/1` if you want to use the same map as Elixir single- and double-quoted strings. ## Map The map must be a function. The function receives an integer representing the codepoint of the character it wants to unescape. Here is the default mapping function implemented by Elixir: def unescape_map(?a), do: ?\a def unescape_map(?b), do: ?\b def unescape_map(?d), do: ?\d def unescape_map(?e), do: ?\e def unescape_map(?f), do: ?\f def unescape_map(?n), do: ?\n def unescape_map(?r), do: ?\r def unescape_map(?s), do: ?\s def unescape_map(?t), do: ?\t def unescape_map(?v), do: ?\v def unescape_map(e), do: e If the `unescape_map` function returns `false`. The char is not escaped and `\` is kept in the char list. ## Octals Octals will by default be escaped unless the map function returns `false` for `?0`. ## Hex Hexadecimals will by default be escaped unless the map function returns `false` for `?x`. ## Examples Using the `unescape_map` function defined above is easy: Macro.unescape_string "example\\n", &unescape_map(&1) """ @spec unescape_string(String.t, (non_neg_integer -> non_neg_integer | false)) :: String.t def unescape_string(chars, map) do :elixir_interpolation.unescape_chars(chars, map) end @doc """ Unescape the given tokens according to the default map. Check `unescape_string/1` and `unescape_string/2` for more information about unescaping. Only tokens that are binaries are unescaped, all others are ignored. This function is useful when implementing your own sigils. Check the implementation of `Kernel.sigil_s/2` for examples. """ @spec unescape_tokens([Macro.t]) :: [Macro.t] def unescape_tokens(tokens) do :elixir_interpolation.unescape_tokens(tokens) end @doc """ Unescape the given tokens according to the given map. Check `unescape_tokens/1` and `unescape_string/2` for more information. """ @spec unescape_tokens([Macro.t], (non_neg_integer -> non_neg_integer | false)) :: [Macro.t] def unescape_tokens(tokens, map) do :elixir_interpolation.unescape_tokens(tokens, map) end @doc """ Converts the given expression to a binary. ## Examples iex> Macro.to_string(quote do: foo.bar(1, 2, 3)) "foo.bar(1, 2, 3)" """ @spec to_string(Macro.t) :: String.t @spec to_string(Macro.t, (Macro.t, String.t -> String.t)) :: String.t def to_string(tree, fun \\ fn(_ast, string) -> string end) # Variables def to_string({ var, _, atom } = ast, fun) when is_atom(atom) do fun.(ast, atom_to_binary(var)) end # Aliases def to_string({ :__aliases__, _, refs } = ast, fun) do fun.(ast, Enum.map_join(refs, ".", &call_to_string(&1, fun))) end # Blocks def to_string({ :__block__, _, [expr] } = ast, fun) do fun.(ast, to_string(expr, fun)) end def to_string({ :__block__, _, _ } = ast, fun) do block = adjust_new_lines block_to_string(ast, fun), "\n " fun.(ast, "(\n " <> block <> "\n)") end # Bits containers def to_string({ :<<>>, _, args } = ast, fun) do fun.(ast, case Enum.map_join(args, ", ", &to_string(&1, fun)) do "<" <> rest -> "<< <" <> rest <> " >>" rest -> "<<" <> rest <> ">>" end) end # Tuple containers def to_string({ :{}, _, args } = ast, fun) do tuple = "{" <> Enum.map_join(args, ", ", &to_string(&1, fun)) <> "}" fun.(ast, tuple) end # Map containers def to_string({ :%{}, _, args } = ast, fun) do map = "%{" <> map_to_string(args, fun) <> "}" fun.(ast, map) end def to_string({ :%, _, [structname, map] } = ast, fun) do { :%{}, _, args } = map struct = "%" <> to_string(structname, fun) <> "{" <> map_to_string(args, fun) <> "}" fun.(ast, struct) end # Fn keyword def to_string({ :fn, _, [{ :->, _, [_, tuple] }] = arrow } = ast, fun) when not is_tuple(tuple) or elem(tuple, 0) != :__block__ do fun.(ast, "fn " <> arrow_to_string(arrow, fun) <> " end") end def to_string({ :fn, _, [{ :->, _, _ }] = block } = ast, fun) do fun.(ast, "fn " <> block_to_string(block, fun) <> "\nend") end def to_string({ :fn, _, block } = ast, fun) do block = adjust_new_lines block_to_string(block, fun), "\n " fun.(ast, "fn\n " <> block <> "\nend") end # left -> right def to_string([{ :->, _, _ }|_] = ast, fun) do fun.(ast, "(" <> arrow_to_string(ast, fun, true) <> ")") end # left when right def to_string({ :when, _, [left, right] } = ast, fun) do if right != [] and Keyword.keyword?(right) do right = kw_list_to_string(right, fun) else right = fun.(ast, op_to_string(right, fun, :when, :right)) end fun.(ast, op_to_string(left, fun, :when, :left) <> " when " <> right) end # Binary ops def to_string({ op, _, [left, right] } = ast, fun) when op in unquote(@binary_ops) do fun.(ast, op_to_string(left, fun, op, :left) <> " #{op} " <> op_to_string(right, fun, op, :right)) end # Splat when def to_string({ :when, _, args } = ast, fun) do { left, right } = :elixir_utils.split_last(args) fun.(ast, "(" <> Enum.map_join(left, ", ", &to_string(&1, fun)) <> ") when " <> to_string(right, fun)) end # Unary ops def to_string({ unary, _, [{ binary, _, [_, _] } = arg] } = ast, fun) when unary in unquote(@unary_ops) and binary in unquote(@binary_ops) do fun.(ast, atom_to_binary(unary) <> "(" <> to_string(arg, fun) <> ")") end def to_string({ :not, _, [arg] } = ast, fun) do fun.(ast, "not " <> to_string(arg, fun)) end def to_string({ op, _, [arg] } = ast, fun) when op in unquote(@unary_ops) do fun.(ast, atom_to_binary(op) <> to_string(arg, fun)) end # Access def to_string({ { :., _, [Kernel, :access] }, _, [left, right] } = ast, fun) do fun.(ast, to_string(left, fun) <> to_string(right, fun)) end # All other calls def to_string({ target, _, args } = ast, fun) when is_list(args) do { list, last } = :elixir_utils.split_last(args) fun.(ast, case kw_blocks?(last) do true -> call_to_string_with_args(target, list, fun) <> kw_blocks_to_string(last, fun) false -> call_to_string_with_args(target, args, fun) end) end # Two-item tuples def to_string({ left, right }, fun) do to_string({ :{}, [], [left, right] }, fun) end # Lists def to_string(list, fun) when is_list(list) do fun.(list, cond do list == [] -> "[]" :io_lib.printable_list(list) -> "'" <> Inspect.BitString.escape(String.from_char_list!(list), ?') <> "'" Keyword.keyword?(list) -> "[" <> kw_list_to_string(list, fun) <> "]" true -> "[" <> Enum.map_join(list, ", ", &to_string(&1, fun)) <> "]" end) end # All other structures def to_string(other, fun), do: fun.(other, inspect(other, records: false)) # Block keywords @kw_keywords [:do, :catch, :rescue, :after, :else] defp kw_blocks?([_|_] = kw) do Enum.all?(kw, &match?({x, _} when x in unquote(@kw_keywords), &1)) end defp kw_blocks?(_), do: false defp module_to_string(atom, _fun) when is_atom(atom), do: inspect(atom, records: false) defp module_to_string(other, fun), do: call_to_string(other, fun) defp call_to_string(atom, _fun) when is_atom(atom), do: atom_to_binary(atom) defp call_to_string({ :., _, [arg] }, fun), do: module_to_string(arg, fun) <> "." defp call_to_string({ :., _, [left, right] }, fun), do: module_to_string(left, fun) <> "." <> call_to_string(right, fun) defp call_to_string(other, fun), do: to_string(other, fun) defp call_to_string_with_args(target, args, fun) do target = call_to_string(target, fun) args = args_to_string(args, fun) target <> "(" <> args <> ")" end defp args_to_string(args, fun) do { list, last } = :elixir_utils.split_last(args) if last != [] and Keyword.keyword?(last) do args = Enum.map_join(list, ", ", &to_string(&1, fun)) if list != [], do: args = args <> ", " args <> kw_list_to_string(last, fun) else Enum.map_join(args, ", ", &to_string(&1, fun)) end end defp kw_blocks_to_string(kw, fun) do Enum.reduce(@kw_keywords, " ", fn(x, acc) -> case Keyword.has_key?(kw, x) do true -> acc <> kw_block_to_string(x, Keyword.get(kw, x), fun) false -> acc end end) <> "end" end defp kw_block_to_string(key, value, fun) do block = adjust_new_lines block_to_string(value, fun), "\n " atom_to_binary(key) <> "\n " <> block <> "\n" end defp block_to_string([{ :->, _, _ }|_] = block, fun) do Enum.map_join(block, "\n", fn({ :->, _, [left, right] }) -> left = comma_join_or_empty_paren(left, fun, false) left <> "->\n " <> adjust_new_lines block_to_string(right, fun), "\n " end) end defp block_to_string({ :__block__, _, exprs }, fun) do Enum.map_join(exprs, "\n", &to_string(&1, fun)) end defp block_to_string(other, fun), do: to_string(other, fun) defp map_to_string([{:|, _, [update_map, update_args]}], fun) do to_string(update_map, fun) <> " | " <> map_to_string(update_args, fun) end defp map_to_string(list, fun) do cond do Keyword.keyword?(list) -> kw_list_to_string(list, fun) true -> map_list_to_string(list, fun) end end defp kw_list_to_string(list, fun) do Enum.map_join(list, ", ", fn { key, value } -> atom_to_binary(key) <> ": " <> to_string(value, fun) end) end defp map_list_to_string(list, fun) do Enum.map_join(list, ", ", fn { key, value } -> to_string(key, fun) <> " => " <> to_string(value, fun) end) end defp parenthise(expr, fun) do "(" <> to_string(expr, fun) <> ")" end defp op_to_string({ op, _, [_, _] } = expr, fun, parent_op, side) when op in unquote(@binary_ops) do { parent_assoc, parent_prec } = binary_op_props(parent_op) { _, prec } = binary_op_props(op) cond do parent_prec < prec -> to_string(expr, fun) parent_prec > prec -> parenthise(expr, fun) true -> # parent_prec == prec, so look at associativity. if parent_assoc == side do to_string(expr, fun) else parenthise(expr, fun) end end end defp op_to_string(expr, fun, _, _), do: to_string(expr, fun) defp arrow_to_string(pairs, fun, paren \\ false) do Enum.map_join(pairs, "; ", fn({ :->, _, [left, right] }) -> left = comma_join_or_empty_paren(left, fun, paren) left <> "-> " <> to_string(right, fun) end) end defp comma_join_or_empty_paren([], _fun, true), do: "() " defp comma_join_or_empty_paren([], _fun, false), do: "" defp comma_join_or_empty_paren(left, fun, _) do Enum.map_join(left, ", ", &to_string(&1, fun)) <> " " end defp adjust_new_lines(block, replacement) do for <<x <- block>>, into: "" do case x == ?\n do true -> replacement false -> <<x>> end end end @doc """ Receives an AST node and expands it once. The following contents are expanded: * Macros (local or remote); * Aliases are expanded (if possible) and return atoms; * Pseudo-variables (`__ENV__`, `__MODULE__` and `__DIR__`); * Module attributes reader (`@foo`); If the expression cannot be expanded, it returns the expression itself. Notice that `expand_once/2` performs the expansion just once and it is not recursive. Check `expand/2` for expansion until the node can no longer be expanded. ## Examples In the example below, we have a macro that generates a module with a function named `name_length` that returns the length of the module name. The value of this function will be calculated at compilation time and not at runtime. Consider the implementation below: defmacro defmodule_with_length(name, do: block) do length = length(atom_to_list(name)) quote do defmodule unquote(name) do def name_length, do: unquote(length) unquote(block) end end end When invoked like this: defmodule_with_length My.Module do def other_function, do: ... end The compilation will fail because `My.Module` when quoted is not an atom, but a syntax tree as follow: {:__aliases__, [], [:My, :Module] } That said, we need to expand the aliases node above to an atom, so we can retrieve its length. Expanding the node is not straight-forward because we also need to expand the caller aliases. For example: alias MyHelpers, as: My defmodule_with_length My.Module do def other_function, do: ... end The final module name will be `MyHelpers.Module` and not `My.Module`. With `Macro.expand/2`, such aliases are taken into consideration. Local and remote macros are also expanded. We could rewrite our macro above to use this function as: defmacro defmodule_with_length(name, do: block) do expanded = Macro.expand(name, __CALLER__) length = length(atom_to_list(expanded)) quote do defmodule unquote(name) do def name_length, do: unquote(length) unquote(block) end end end """ def expand_once(ast, env) do elem(do_expand_once(ast, env), 0) end defp do_expand_once({ :__aliases__, _, _ } = original, env) do case :elixir_aliases.expand(original, env.aliases, env.macro_aliases, env.lexical_tracker) do receiver when is_atom(receiver) -> :elixir_lexical.record_remote(receiver, env.lexical_tracker) { receiver, true } aliases -> aliases = for alias <- aliases, do: elem(do_expand_once(alias, env), 0) case :lists.all(&is_atom/1, aliases) do true -> receiver = :elixir_aliases.concat(aliases) :elixir_lexical.record_remote(receiver, env.lexical_tracker) { receiver, true } false -> { original, false } end end end # Expand @ calls defp do_expand_once({ :@, _, [{ name, _, args }] } = original, env) when is_atom(args) or args == [] do case (module = env.module) && Module.open?(module) do true -> { Module.get_attribute(module, name), true } false -> { original, false } end end # Expand pseudo-variables defp do_expand_once({ :__MODULE__, _, atom }, env) when is_atom(atom), do: { env.module, true } defp do_expand_once({ :__DIR__, _, atom }, env) when is_atom(atom), do: { :filename.dirname(env.file), true } defp do_expand_once({ :__ENV__, _, atom }, env) when is_atom(atom), do: { { :{}, [], tuple_to_list(env) }, true } defp do_expand_once({ { :., _, [{ :__ENV__, _, atom }, field] }, _, [] } = original, env) when is_atom(atom) and is_atom(field) do case :erlang.function_exported(Macro.Env, field, 1) do true -> { apply(env, field, []), true } false -> { original, false } end end # Expand possible macro import invocation defp do_expand_once({ atom, meta, context } = original, env) when is_atom(atom) and is_list(meta) and is_atom(context) do if :lists.member({ atom, Keyword.get(meta, :counter, context) }, env.vars) do { original, false } else case do_expand_once({ atom, meta, [] }, env) do { _, true } = exp -> exp { _, false } -> { original, false } end end end defp do_expand_once({ atom, meta, args } = original, env) when is_atom(atom) and is_list(args) and is_list(meta) do arity = length(args) if :elixir_import.special_form(atom, arity) do { original, false } else module = env.module extra = if function_exported?(module, :__info__, 1) do [{ module, module.__info__(:macros) }] else [] end expand = :elixir_dispatch.expand_import(meta, { atom, length(args) }, args, :elixir_env.ex_to_env(env), extra) case expand do { :ok, receiver, quoted } -> next = :elixir_counter.next { :elixir_quote.linify_with_context_counter(0, { receiver, next }, quoted), true } { :ok, _receiver } -> { original, false } :error -> { original, false } end end end # Expand possible macro require invocation defp do_expand_once({ { :., _, [left, right] }, meta, args } = original, env) when is_atom(right) do { receiver, _ } = do_expand_once(left, env) case is_atom(receiver) do false -> { original, false } true -> expand = :elixir_dispatch.expand_require(meta, receiver, { right, length(args) }, args, :elixir_env.ex_to_env(env)) case expand do { :ok, receiver, quoted } -> next = :elixir_counter.next { :elixir_quote.linify_with_context_counter(0, { receiver, next }, quoted), true } :error -> { original, false } end end end # Anything else is just returned defp do_expand_once(other, _env), do: { other, false } @doc """ Receives an AST node and expands it until it can no longer be expanded. This function uses `expand_once/2` under the hood. Check `expand_once/2` for more information and exmaples. """ def expand(tree, env) do expand_until({ tree, true }, env) end defp expand_until({ tree, true }, env) do expand_until(do_expand_once(tree, env), env) end defp expand_until({ tree, false }, _env) do tree end @doc """ Recursively traverses the quoted expression checking if all sub-terms are safe. Terms are considered safe if they represent data structures and don't actually evaluate code. Returns `:ok` unless a given term is unsafe, which is returned as `{ :unsafe, term }`. """ def safe_term(terms) do do_safe_term(terms) || :ok end defp do_safe_term({ local, _, terms }) when local in [:{}, :%{}, :__aliases__] do do_safe_term(terms) end defp do_safe_term({ unary, _, [term] }) when unary in [:+, :-] do do_safe_term(term) end defp do_safe_term({ left, right }), do: do_safe_term(left) || do_safe_term(right) defp do_safe_term(terms) when is_list(terms), do: Enum.find_value(terms, &do_safe_term(&1)) defp do_safe_term(terms) when is_tuple(terms), do: { :unsafe, terms } defp do_safe_term(_), do: nil end
31.32375
122
0.593559
73a7fcc9a41967c56cfa8d6388873c12bb373a2a
8,724
exs
Elixir
test/web/controllers/division_controller_test.exs
EDENLABLLC/prm.api
86743f26874f47ce3d48010ccf5d2cd596a3474b
[ "Apache-2.0" ]
1
2017-07-27T16:03:28.000Z
2017-07-27T16:03:28.000Z
test/web/controllers/division_controller_test.exs
EDENLABLLC/prm.api
86743f26874f47ce3d48010ccf5d2cd596a3474b
[ "Apache-2.0" ]
null
null
null
test/web/controllers/division_controller_test.exs
EDENLABLLC/prm.api
86743f26874f47ce3d48010ccf5d2cd596a3474b
[ "Apache-2.0" ]
null
null
null
defmodule PRM.Web.DivisionControllerTest do use PRM.Web.ConnCase import PRM.SimpleFactory alias PRM.Divisions.Division alias Ecto.UUID @update_attrs %{ addresses: [%{}], email: "some updated email", external_id: "some updated external_id", mountain_group: true, name: "some updated name", phones: [%{}], status: "INACTIVE", type: "ambulant_clinic", location: %{"longitude" => 50.45000, "latitude" => 30.52333} } @invalid_attrs %{ addresses: nil, email: nil, external_id: nil, mountain_group: nil, name: nil, phones: nil, type: nil } setup %{conn: conn} do {:ok, conn: put_req_header(conn, "accept", "application/json")} end test "lists all entries on index", %{conn: conn} do division() division() division() division() conn = get conn, division_path(conn, :index, ["limit": 2]) resp = json_response(conn, 200) assert Map.has_key?(resp, "paging") assert 2 == length(resp["data"]) assert resp["paging"]["has_more"] end describe "search divisions" do test "search divisions invalid legal_entity_id param", %{conn: conn} do conn = get conn, division_path(conn, :index, [legal_entity_id: "invalid"]) assert json_response(conn, 422)["errors"] != %{} end test "search divisions by legal_entity_id_1", %{conn: conn} do %Division{id: id_1, legal_entity_id: legal_entity_id_1} = division() %Division{id: id_2, legal_entity_id: legal_entity_id_2} = division() conn = get conn, division_path(conn, :index, [legal_entity_id: legal_entity_id_1]) resp = json_response(conn, 200)["data"] assert 1 == length(resp) assert id_1 == resp |> List.first() |> Map.fetch!("id") conn = get conn, division_path(conn, :index, [legal_entity_id: legal_entity_id_2]) resp = json_response(conn, 200)["data"] assert 1 == length(resp) assert id_2 == resp |> List.first() |> Map.fetch!("id") conn = get conn, division_path(conn, :index, [legal_entity_id: "2f095674-7634-4462-83f2-080fb67fac6b"]) assert json_response(conn, 200)["data"] == [] end test "search divisions by type", %{conn: conn} do %Division{id: id_1} = division("clinic") %Division{id: id_2} = division("fap") conn = get conn, division_path(conn, :index, [type: "clinic"]) resp = json_response(conn, 200)["data"] assert 1 == length(resp) assert id_1 == resp |> List.first() |> Map.fetch!("id") conn = get conn, division_path(conn, :index, [type: "fap"]) resp = json_response(conn, 200)["data"] assert 1 == length(resp) assert id_2 == resp |> List.first() |> Map.fetch!("id") conn = get conn, division_path(conn, :index, [type: "ambulant_clinic"]) assert json_response(conn, 200)["data"] == [] end test "search divisions by name part", %{conn: conn} do division() division() conn = get conn, division_path(conn, :index, [name: "some"]) resp = json_response(conn, 200)["data"] assert 2 == length(resp) conn = get conn, division_path(conn, :index, [name: "name"]) resp = json_response(conn, 200)["data"] assert 2 == length(resp) conn = get conn, division_path(conn, :index, [name: "NA"]) resp = json_response(conn, 200)["data"] assert 2 == length(resp) conn = get conn, division_path(conn, :index, [name: "invalid"]) resp = json_response(conn, 200)["data"] assert 0 == length(resp) end test "search divisions by type, name, legal_entity_id", %{conn: conn} do %Division{legal_entity_id: legal_entity_id} = division("clinic") params = [type: "clinic", name: "NAME", legal_entity_id: legal_entity_id] conn = get conn, division_path(conn, :index, params) resp = json_response(conn, 200)["data"] assert 1 == length(resp) params = [name: "INVALID", legal_entity_id: legal_entity_id] conn = get conn, division_path(conn, :index, params) resp = json_response(conn, 200)["data"] assert 0 == length(resp) end test "search divisions by ids and type", %{conn: conn} do fixture(:legal_entity) %{id: id} = division() %{id: id_2} = division("clinic") %{id: id_3} = division("clinic") ids = [id, id_2, id_3, UUID.generate()] conn = get conn, division_path(conn, :index, [ids: Enum.join(ids, ","), type: "clinic"]) resp = json_response(conn, 200) assert Map.has_key?(resp, "paging") assert 2 == length(resp["data"]) Enum.each(resp["data"], fn (%{"id" => l_id}) -> assert l_id in [id_2, id_3] end) refute resp["paging"]["has_more"] end end test "set divisions mountain group by settlement_id", %{conn: conn} do settlement_id = UUID.generate() for _ <- 1..55 do division("ambulant_clinic", settlement_id) end division() division() conn_resp = patch conn, division_path(conn, :set_mountain_group, [ mountain_group: true, settlement_id: settlement_id ]) json_response(conn_resp, 200) conn_resp = get conn, division_path(conn, :index, [limit: 100]) data = json_response(conn_resp, 200)["data"] assert 55 == data |> Enum.filter(fn(d) -> d["mountain_group"] end) |> length() end test "set divisions mountain group by invalid settlement_id", %{conn: conn} do division() division() conn = patch conn, division_path(conn, :set_mountain_group, [mountain_group: true, settlement_id: UUID.generate()]) json_response(conn, 200) conn = get conn, division_path(conn, :index) data = json_response(conn, 200)["data"] assert 0 == data |> Enum.filter(fn(d) -> d["mountain_group"] end) |> length() end test "set divisions mountain group with invalid params", %{conn: conn} do conn_resp = patch conn, division_path(conn, :set_mountain_group, [mountain_group: "ok"]) assert json_response(conn_resp, 422)["errors"] != %{} conn_resp = patch conn, division_path(conn, :set_mountain_group, [settlement_id: "ok"]) assert json_response(conn_resp, 422)["errors"] != %{} conn_resp = patch conn, division_path(conn, :set_mountain_group, []) assert json_response(conn_resp, 422)["errors"] != %{} end test "creates division and renders division when data is valid", %{conn: conn} do %{id: legal_entity_id} = fixture(:legal_entity) attr = %{ addresses: [%{}], email: "some email", external_id: "some external_id", name: "some name", phones: [%{}], type: "fap", status: "ACTIVE", legal_entity_id: legal_entity_id, location: %{"longitude" => 50.45000, "latitude" => 30.52333} } conn = post conn, division_path(conn, :create), attr assert %{"id" => id} = json_response(conn, 201)["data"] conn = get conn, division_path(conn, :show, id) assert json_response(conn, 200)["data"] == %{ "id" => id, "addresses" => [%{}], "email" => "some email", "external_id" => "some external_id", "mountain_group" => nil, "name" => "some name", "phones" => [%{}], "status" => "ACTIVE", "type" => "fap", "legal_entity_id" => legal_entity_id, "location" => %{ "longitude" => 50.45000, "latitude" => 30.52333 } } end test "does not create division and renders errors when data is invalid", %{conn: conn} do conn = post conn, division_path(conn, :create), @invalid_attrs assert json_response(conn, 422)["errors"] != %{} end test "updates chosen division and renders division when data is valid", %{conn: conn} do %Division{id: id, legal_entity_id: legal_entity_id} = division = fixture(:division) conn = put conn, division_path(conn, :update, division), @update_attrs assert %{"id" => ^id} = json_response(conn, 200)["data"] conn = get conn, division_path(conn, :show, id) assert json_response(conn, 200)["data"] == %{ "id" => id, "addresses" => [%{}], "email" => "some updated email", "external_id" => "some updated external_id", "mountain_group" => true, "name" => "some updated name", "phones" => [%{}], "type" => "ambulant_clinic", "status" => "INACTIVE", "legal_entity_id" => legal_entity_id, "location" => %{ "longitude" => 50.45000, "latitude" => 30.52333 } } end test "does not update chosen division and renders errors when data is invalid", %{conn: conn} do division = fixture(:division) conn = put conn, division_path(conn, :update, division), @invalid_attrs assert json_response(conn, 422)["errors"] != %{} end end
33.683398
119
0.618065
73a803f749228d478c6aaaf15d13b792ca8f3488
3,258
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/path_to_conversion_report_compatible_fields.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/path_to_conversion_report_compatible_fields.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/path_to_conversion_report_compatible_fields.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.DFAReporting.V33.Model.PathToConversionReportCompatibleFields do @moduledoc """ Represents fields that are compatible to be selected for a report of type "PATH_TO_CONVERSION". ## Attributes * `conversionDimensions` (*type:* `list(GoogleApi.DFAReporting.V33.Model.Dimension.t)`, *default:* `nil`) - Conversion dimensions which are compatible to be selected in the "conversionDimensions" section of the report. * `customFloodlightVariables` (*type:* `list(GoogleApi.DFAReporting.V33.Model.Dimension.t)`, *default:* `nil`) - Custom floodlight variables which are compatible to be selected in the "customFloodlightVariables" section of the report. * `kind` (*type:* `String.t`, *default:* `nil`) - The kind of resource this is, in this case dfareporting#pathToConversionReportCompatibleFields. * `metrics` (*type:* `list(GoogleApi.DFAReporting.V33.Model.Metric.t)`, *default:* `nil`) - Metrics which are compatible to be selected in the "metricNames" section of the report. * `perInteractionDimensions` (*type:* `list(GoogleApi.DFAReporting.V33.Model.Dimension.t)`, *default:* `nil`) - Per-interaction dimensions which are compatible to be selected in the "perInteractionDimensions" section of the report. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :conversionDimensions => list(GoogleApi.DFAReporting.V33.Model.Dimension.t()) | nil, :customFloodlightVariables => list(GoogleApi.DFAReporting.V33.Model.Dimension.t()) | nil, :kind => String.t() | nil, :metrics => list(GoogleApi.DFAReporting.V33.Model.Metric.t()) | nil, :perInteractionDimensions => list(GoogleApi.DFAReporting.V33.Model.Dimension.t()) | nil } field(:conversionDimensions, as: GoogleApi.DFAReporting.V33.Model.Dimension, type: :list) field(:customFloodlightVariables, as: GoogleApi.DFAReporting.V33.Model.Dimension, type: :list) field(:kind) field(:metrics, as: GoogleApi.DFAReporting.V33.Model.Metric, type: :list) field(:perInteractionDimensions, as: GoogleApi.DFAReporting.V33.Model.Dimension, type: :list) end defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.PathToConversionReportCompatibleFields do def decode(value, options) do GoogleApi.DFAReporting.V33.Model.PathToConversionReportCompatibleFields.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.PathToConversionReportCompatibleFields do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
52.548387
238
0.751074
73a8055f35e087fc2aa6d518abae295352bc0c3f
32,245
ex
Elixir
clients/speech/lib/google_api/speech/v1/api/projects.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
clients/speech/lib/google_api/speech/v1/api/projects.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
clients/speech/lib/google_api/speech/v1/api/projects.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.Speech.V1.Api.Projects do @moduledoc """ API calls for all endpoints tagged `Projects`. """ alias GoogleApi.Speech.V1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Create a custom class. ## Parameters * `connection` (*type:* `GoogleApi.Speech.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The parent resource where this custom class will be created. Format: {api_version}/projects/{project}/locations/{location}/customClasses * `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.Speech.V1.Model.CreateCustomClassRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Speech.V1.Model.CustomClass{}}` on success * `{:error, info}` on failure """ @spec speech_projects_locations_custom_classes_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Speech.V1.Model.CustomClass.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def speech_projects_locations_custom_classes_create( connection, parent, 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/{+parent}/customClasses", %{ "parent" => URI.encode(parent, &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.Speech.V1.Model.CustomClass{}]) end @doc """ Delete a custom class. ## Parameters * `connection` (*type:* `GoogleApi.Speech.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the custom class to delete. Format: {api_version}/projects/{project}/locations/{location}/customClasses/{custom_class} * `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.Speech.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec speech_projects_locations_custom_classes_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Speech.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def speech_projects_locations_custom_classes_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.Speech.V1.Model.Empty{}]) end @doc """ Get a custom class. ## Parameters * `connection` (*type:* `GoogleApi.Speech.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the custom class to retrieve. Format: {api_version}/projects/{project}/locations/{location}/customClasses/{custom_class} * `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.Speech.V1.Model.CustomClass{}}` on success * `{:error, info}` on failure """ @spec speech_projects_locations_custom_classes_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Speech.V1.Model.CustomClass.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def speech_projects_locations_custom_classes_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.Speech.V1.Model.CustomClass{}]) end @doc """ List custom classes. ## Parameters * `connection` (*type:* `GoogleApi.Speech.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The parent, which owns this collection of custom classes. Format: {api_version}/projects/{project}/locations/{location}/customClasses * `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"). * `:pageSize` (*type:* `integer()`) - The maximum number of custom classes to return. The service may return fewer than this value. If unspecified, at most 50 custom classes will be returned. The maximum value is 1000; values above 1000 will be coerced to 1000. * `:pageToken` (*type:* `String.t`) - A page token, received from a previous `ListCustomClass` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListCustomClass` must match the call that provided the page token. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Speech.V1.Model.ListCustomClassesResponse{}}` on success * `{:error, info}` on failure """ @spec speech_projects_locations_custom_classes_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Speech.V1.Model.ListCustomClassesResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def speech_projects_locations_custom_classes_list( connection, parent, 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, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+parent}/customClasses", %{ "parent" => URI.encode(parent, &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.Speech.V1.Model.ListCustomClassesResponse{}]) end @doc """ Update a custom class. ## Parameters * `connection` (*type:* `GoogleApi.Speech.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The resource name of the custom class. * `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"). * `:updateMask` (*type:* `String.t`) - The list of fields to be updated. * `:body` (*type:* `GoogleApi.Speech.V1.Model.CustomClass.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Speech.V1.Model.CustomClass{}}` on success * `{:error, info}` on failure """ @spec speech_projects_locations_custom_classes_patch( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Speech.V1.Model.CustomClass.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def speech_projects_locations_custom_classes_patch( 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, :updateMask => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> 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.Speech.V1.Model.CustomClass{}]) end @doc """ Create a set of phrase hints. Each item in the set can be a single word or a multi-word phrase. The items in the PhraseSet are favored by the recognition model when you send a call that includes the PhraseSet. ## Parameters * `connection` (*type:* `GoogleApi.Speech.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The parent resource where this phrase set will be created. Format: {api_version}/projects/{project}/locations/{location}/phraseSets * `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.Speech.V1.Model.CreatePhraseSetRequest.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Speech.V1.Model.PhraseSet{}}` on success * `{:error, info}` on failure """ @spec speech_projects_locations_phrase_sets_create( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Speech.V1.Model.PhraseSet.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def speech_projects_locations_phrase_sets_create( connection, parent, 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/{+parent}/phraseSets", %{ "parent" => URI.encode(parent, &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.Speech.V1.Model.PhraseSet{}]) end @doc """ Delete a phrase set. ## Parameters * `connection` (*type:* `GoogleApi.Speech.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the phrase set to delete. Format: {api_version}/projects/{project}/locations/{location}/phraseSets/{phrase_set} * `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.Speech.V1.Model.Empty{}}` on success * `{:error, info}` on failure """ @spec speech_projects_locations_phrase_sets_delete( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Speech.V1.Model.Empty.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def speech_projects_locations_phrase_sets_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.Speech.V1.Model.Empty{}]) end @doc """ Get a phrase set. ## Parameters * `connection` (*type:* `GoogleApi.Speech.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - Required. The name of the phrase set to retrieve. Format: {api_version}/projects/{project}/locations/{location}/phraseSets/{phrase_set} * `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.Speech.V1.Model.PhraseSet{}}` on success * `{:error, info}` on failure """ @spec speech_projects_locations_phrase_sets_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Speech.V1.Model.PhraseSet.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def speech_projects_locations_phrase_sets_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.Speech.V1.Model.PhraseSet{}]) end @doc """ List phrase sets. ## Parameters * `connection` (*type:* `GoogleApi.Speech.V1.Connection.t`) - Connection to server * `parent` (*type:* `String.t`) - Required. The parent, which owns this collection of phrase set. Format: projects/{project}/locations/{location} * `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"). * `:pageSize` (*type:* `integer()`) - The maximum number of phrase sets to return. The service may return fewer than this value. If unspecified, at most 50 phrase sets will be returned. The maximum value is 1000; values above 1000 will be coerced to 1000. * `:pageToken` (*type:* `String.t`) - A page token, received from a previous `ListPhraseSet` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListPhraseSet` must match the call that provided the page token. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Speech.V1.Model.ListPhraseSetResponse{}}` on success * `{:error, info}` on failure """ @spec speech_projects_locations_phrase_sets_list( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Speech.V1.Model.ListPhraseSetResponse.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def speech_projects_locations_phrase_sets_list( connection, parent, 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, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+parent}/phraseSets", %{ "parent" => URI.encode(parent, &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.Speech.V1.Model.ListPhraseSetResponse{}]) end @doc """ Update a phrase set. ## Parameters * `connection` (*type:* `GoogleApi.Speech.V1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The resource name of the phrase set. * `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"). * `:updateMask` (*type:* `String.t`) - The list of fields to be updated. * `:body` (*type:* `GoogleApi.Speech.V1.Model.PhraseSet.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Speech.V1.Model.PhraseSet{}}` on success * `{:error, info}` on failure """ @spec speech_projects_locations_phrase_sets_patch( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Speech.V1.Model.PhraseSet.t()} | {:ok, Tesla.Env.t()} | {:ok, list()} | {:error, any()} def speech_projects_locations_phrase_sets_patch( 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, :updateMask => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> 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.Speech.V1.Model.PhraseSet{}]) end end
43.108289
272
0.604528
73a805651150a50f845ef5c9663e566b1a7ad339
1,895
exs
Elixir
test/levenshtein_test.exs
preciz/levenshtein
adb43b9126559c5159655623d66548c66e4ea5ad
[ "MIT" ]
2
2020-02-05T00:07:17.000Z
2020-04-15T13:35:43.000Z
test/levenshtein_test.exs
preciz/levenshtein
adb43b9126559c5159655623d66548c66e4ea5ad
[ "MIT" ]
8
2019-10-08T01:13:13.000Z
2022-02-24T04:12:51.000Z
test/levenshtein_test.exs
preciz/levenshtein
adb43b9126559c5159655623d66548c66e4ea5ad
[ "MIT" ]
null
null
null
defmodule LevenshteinTest do use ExUnit.Case doctest Levenshtein test "distance" do assert Levenshtein.distance("", "") == 0 assert Levenshtein.distance("a", "a") == 0 assert Levenshtein.distance("a", "b") == 1 assert Levenshtein.distance("alma", "korte") == 5 # With empty strings assert Levenshtein.distance("", "") == 0 assert Levenshtein.distance("a", "") == 1 assert Levenshtein.distance("", "a") == 1 assert Levenshtein.distance("abc", "") == 3 assert Levenshtein.distance("", "abc") == 3 # With equal strings assert Levenshtein.distance("a", "a") == 0 assert Levenshtein.distance("abc", "abc") == 0 assert Levenshtein.distance("", "a") == 1 # Only with inserts assert Levenshtein.distance("a", "ab") == 1 assert Levenshtein.distance("b", "ab") == 1 assert Levenshtein.distance("ac", "abc") == 1 assert Levenshtein.distance("abcdefg", "xabxcdxxefxgx") == 6 # Only with deletions assert Levenshtein.distance("a", "") == 1 assert Levenshtein.distance("ab", "a") == 1 assert Levenshtein.distance("ab", "b") == 1 assert Levenshtein.distance("abc", "ac") == 1 assert Levenshtein.distance("xabxcdxxefxgx", "abcdefg") == 6 # Only with substitutions assert Levenshtein.distance("a", "b") == 1 assert Levenshtein.distance("ab", "ac") == 1 assert Levenshtein.distance("ac", "bc") == 1 assert Levenshtein.distance("abc", "axc") == 1 assert Levenshtein.distance("xabxcdxxefxgx", "1ab2cd34ef5g6") == 6 # With different operations assert Levenshtein.distance("example", "samples") == 3 assert Levenshtein.distance("sturgeon", "urgently") == 6 assert Levenshtein.distance("levenshtein", "frankenstein") == 6 assert Levenshtein.distance("distance", "difference") == 5 assert Levenshtein.distance("erlang was neat", "elixir is great") == 9 end end
41.195652
74
0.645383
73a80af6bd21ae7c1cb3b93043145d1e517f4043
593
exs
Elixir
mix.exs
adriandelisle/programming-elixir
19ad6f4504cba589e64e0ff652c41ec35e2ca5fb
[ "MIT" ]
null
null
null
mix.exs
adriandelisle/programming-elixir
19ad6f4504cba589e64e0ff652c41ec35e2ca5fb
[ "MIT" ]
null
null
null
mix.exs
adriandelisle/programming-elixir
19ad6f4504cba589e64e0ff652c41ec35e2ca5fb
[ "MIT" ]
null
null
null
defmodule ProgrammingElixir.MixProject do use Mix.Project def project do [ app: :programming_elixir, version: "0.1.0", elixir: "~> 1.10", start_permanent: Mix.env() == :prod, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ # {:dep_from_hexpm, "~> 0.3.0"}, # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} ] end end
20.448276
87
0.591906
73a852774beea86cf640294e68e2639267ba355d
2,363
ex
Elixir
apps/astarte_housekeeping_api/lib/astarte_housekeeping_api_web/controllers/fallback_controller.ex
szakhlypa/astarte
4e0152191999cf4834d57ec71bad4d4d0856971f
[ "Apache-2.0" ]
null
null
null
apps/astarte_housekeeping_api/lib/astarte_housekeeping_api_web/controllers/fallback_controller.ex
szakhlypa/astarte
4e0152191999cf4834d57ec71bad4d4d0856971f
[ "Apache-2.0" ]
null
null
null
apps/astarte_housekeeping_api/lib/astarte_housekeeping_api_web/controllers/fallback_controller.ex
szakhlypa/astarte
4e0152191999cf4834d57ec71bad4d4d0856971f
[ "Apache-2.0" ]
null
null
null
# # This file is part of Astarte. # # Copyright 2017 Ispirata Srl # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # defmodule Astarte.Housekeeping.APIWeb.FallbackController do @moduledoc """ Translates controller action results into valid `Plug.Conn` responses. See `Phoenix.Controller.action_fallback/1` for more details. """ use Astarte.Housekeeping.APIWeb, :controller alias Astarte.Housekeeping.APIWeb.ChangesetView alias Astarte.Housekeeping.APIWeb.ErrorView def call(conn, {:error, %Ecto.Changeset{} = changeset}) do conn |> put_status(:unprocessable_entity) |> put_view(ChangesetView) |> render("error.json", changeset: changeset) end def call(conn, {:error, :realm_not_found}) do conn |> put_status(:not_found) |> put_view(ErrorView) |> render(:realm_not_found) end def call(conn, {:error, :realm_deletion_disabled}) do conn |> put_status(:method_not_allowed) |> put_view(ErrorView) |> render(:realm_deletion_disabled) end def call(conn, {:error, :connected_devices_present}) do conn |> put_status(:unprocessable_entity) |> put_view(ErrorView) |> render(:connected_devices_present) end def call(conn, {:error, :not_found}) do conn |> put_status(:not_found) |> put_view(ErrorView) |> render(:"404") end def call(conn, {:error, :unauthorized}) do conn |> put_status(:unauthorized) |> put_view(ErrorView) |> render(:"401") end # This is called when no JWT token is present def auth_error(conn, {:unauthenticated, _reason}, _opts) do conn |> put_status(:unauthorized) |> put_view(ErrorView) |> render(:"401") end # In all other cases, we reply with 403 def auth_error(conn, _reason, _opts) do conn |> put_status(:forbidden) |> put_view(ErrorView) |> render(:"403") end end
26.852273
74
0.697419