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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7907bea7e7950db29a918fadef73fd0df3327ec6 | 2,498 | ex | Elixir | lib/guess_who/engine.ex | Stratus3D/guess_who | 3131e0ba8d4931030898e0e6235e377acf53a2ac | [
"MIT"
] | null | null | null | lib/guess_who/engine.ex | Stratus3D/guess_who | 3131e0ba8d4931030898e0e6235e377acf53a2ac | [
"MIT"
] | null | null | null | lib/guess_who/engine.ex | Stratus3D/guess_who | 3131e0ba8d4931030898e0e6235e377acf53a2ac | [
"MIT"
] | null | null | null | defmodule GuessWho.Engine do
alias GuessWho.{Contender, Attributes, Game, Turn}
@max_turns 50
@spec score_all_contenders() :: [{binary(), Integer.t()}]
def score_all_contenders() do
modules = Contender.all_player_modules()
names = Enum.map(modules, &(&1.name))
scores =
modules
|> Enum.map(&score_contender/1)
|> Enum.map(fn {_, _, total_score} -> total_score end)
Enum.zip(names, scores)
end
@spec score_contender(Contender.t() | Atom.t()) :: {[Game.t()], %{Attribute.character() => Integer.t()}, Integer.t()}
def score_contender(contender) do
contender = get_contender(contender)
game_logs = match_contender_against_all_characters(contender)
per_character_score =
game_logs
|> Enum.map(&{&1.character, length(&1.turns)})
|> Map.new()
total_score =
per_character_score
|> Map.values()
|> Enum.sum()
{game_logs, per_character_score, total_score}
end
@spec match_contender_against_all_characters(Contender.t() | Atom.t()) :: [Game.t()]
def match_contender_against_all_characters(contender) do
contender = get_contender(contender)
Enum.map(Attributes.characters(), &start_game(contender, &1))
end
@spec start_game(Contender.t() | Atom.t(), Attributes.character()) :: Game.t()
def start_game(contender, character) do
contender = get_contender(contender)
{outcome, turns} = do_turns(contender, character, [], 0)
Game.new(contender, character, Enum.reverse(turns), outcome)
end
defp do_turns(_, _, [%Turn{response: {:name_guessed?, true}} | _] = turns, _) do
{:success, turns}
end
defp do_turns(_, _, turns, @max_turns) do
{:failure, turns}
end
defp do_turns(contender, character, turns, count) do
turn_arguments =
case turns do
[] -> [nil, nil]
[%Turn{response: response, state: state} | _] -> [response, state]
end
{query, state} = apply(contender.module, :turn, turn_arguments)
response = Attributes.character_matches?(character, query)
do_turns(contender, character, [Turn.new(query, response, state) | turns], count + 1)
end
defp get_contender(%Contender{} = contender), do: contender
defp get_contender(contender) when is_atom(contender), do: Contender.new(contender)
defp get_contender("Elixir." <> _contender = module_string) do
module_string |> String.to_atom() |> get_contender()
end
defp get_contender(contender), do: get_contender("Elixir." <> contender)
end
| 32.025641 | 119 | 0.676141 |
790819fec2038ac86eb75fade3354a24f8f1aa43 | 601 | exs | Elixir | test/test_helper.exs | leifg/vinci | 9eb8bd37aed3dd19fc6128a2ad39f5077c01815f | [
"MIT"
] | 1 | 2015-11-12T02:54:31.000Z | 2015-11-12T02:54:31.000Z | test/test_helper.exs | leifg/vinci | 9eb8bd37aed3dd19fc6128a2ad39f5077c01815f | [
"MIT"
] | null | null | null | test/test_helper.exs | leifg/vinci | 9eb8bd37aed3dd19fc6128a2ad39f5077c01815f | [
"MIT"
] | null | null | null | Code.require_file "./support/fixtures.exs", __DIR__
Code.require_file "./support/fixtures_http.exs", __DIR__
ExUnit.start()
apisaurus_config = %{
endpoint: "http://apisaurus",
routes: %{
all: %{
method: :get,
path: "/all",
result: [Vinci.Fixtures.Dinosaur]
},
create: %{
method: :post,
path: "/dinosaurs",
result: Vinci.Fixtures.Dinosaur
},
show: %{
method: :get,
path: "/dinosaurs/:id",
result: Vinci.Fixtures.Dinosaur
},
}
}
Vinci.ConfigAgent.start_link
Vinci.ConfigAgent.add_config(:apisaurus, apisaurus_config)
| 21.464286 | 58 | 0.62396 |
79081e516a77a32af1d6e8f3f68c10393fa169b4 | 1,473 | ex | Elixir | apps/gobstopper_service/lib/gobstopper.service/token.ex | ZURASTA/gobstopper | f8d231c4459af6fa44273c3ef80857348410c70b | [
"BSD-2-Clause"
] | null | null | null | apps/gobstopper_service/lib/gobstopper.service/token.ex | ZURASTA/gobstopper | f8d231c4459af6fa44273c3ef80857348410c70b | [
"BSD-2-Clause"
] | 12 | 2017-07-24T12:29:51.000Z | 2018-04-05T03:58:10.000Z | apps/gobstopper_service/lib/gobstopper.service/token.ex | ZURASTA/gobstopper | f8d231c4459af6fa44273c3ef80857348410c70b | [
"BSD-2-Clause"
] | 4 | 2017-07-24T12:19:23.000Z | 2019-02-19T06:34:46.000Z | defmodule Gobstopper.Service.Token do
use Guardian, otp_app: :gobstopper_service
def subject_for_token(%Gobstopper.Service.Auth.Identity.Model{ identity: id }, _), do: { :ok, "Identity:#{id}" }
def subject_for_token(_, _), do: { :error, :unknown_resource }
def resource_from_claims(%{ "sub" => "Identity:" <> id }), do: { :ok, Gobstopper.Service.Repo.get_by(Gobstopper.Service.Auth.Identity.Model, identity: id) }
def resource_from_claims(_), do: { :error, :unknown_resource }
def after_encode_and_sign(resource, claims, token, _) do
case Guardian.DB.after_encode_and_sign(resource, claims["typ"], claims, token) do
{ :ok, _ } -> { :ok, token }
err -> err
end
end
def on_verify(claims, token, _) do
case Guardian.DB.on_verify(claims, token) do
{ :ok, _ } -> { :ok, claims }
err -> err
end
end
def on_refresh(old, new, _) do
case Guardian.DB.on_refresh(old, new) do
{ :ok, _, _ } -> { :ok, old, new }
err -> err
end
end
def on_revoke(claims, token, _) do
case Guardian.DB.on_revoke(claims, token) do
{ :ok, _ } -> { :ok, claims }
err -> err
end
end
def remove(token, opts \\ []) do
try do
revoke(token, opts)
rescue
_ in [ArgumentError, Poison.SyntaxError] -> { :error, :invalid_token }
end
end
end
| 32.021739 | 160 | 0.568907 |
790832cdf42ce891ad109f1af763881ebd95b59c | 1,595 | ex | Elixir | clients/network_management/lib/google_api/network_management/v1beta1/model/test_iam_permissions_response.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/network_management/lib/google_api/network_management/v1beta1/model/test_iam_permissions_response.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/network_management/lib/google_api/network_management/v1beta1/model/test_iam_permissions_response.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.NetworkManagement.V1beta1.Model.TestIamPermissionsResponse do
@moduledoc """
Response message for `TestIamPermissions` method.
## Attributes
* `permissions` (*type:* `list(String.t)`, *default:* `nil`) - A subset of `TestPermissionsRequest.permissions` that the caller is
allowed.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:permissions => list(String.t())
}
field(:permissions, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.NetworkManagement.V1beta1.Model.TestIamPermissionsResponse do
def decode(value, options) do
GoogleApi.NetworkManagement.V1beta1.Model.TestIamPermissionsResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.NetworkManagement.V1beta1.Model.TestIamPermissionsResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.229167 | 134 | 0.753605 |
79083620e474ebb1b4c4f7b2b5515965cb172700 | 573 | exs | Elixir | test/views/error_view_test.exs | erickgnavar/tweet_map | 4c8839e35dc96cd8d6ca12fb2895496f2a0c100e | [
"MIT"
] | null | null | null | test/views/error_view_test.exs | erickgnavar/tweet_map | 4c8839e35dc96cd8d6ca12fb2895496f2a0c100e | [
"MIT"
] | null | null | null | test/views/error_view_test.exs | erickgnavar/tweet_map | 4c8839e35dc96cd8d6ca12fb2895496f2a0c100e | [
"MIT"
] | null | null | null | defmodule TweetMap.ErrorViewTest do
use TweetMap.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(TweetMap.ErrorView, "404.html", []) ==
"Page not found"
end
test "render 500.html" do
assert render_to_string(TweetMap.ErrorView, "500.html", []) ==
"Server internal error"
end
test "render any other" do
assert render_to_string(TweetMap.ErrorView, "505.html", []) ==
"Server internal error"
end
end
| 26.045455 | 66 | 0.678883 |
7908530ca79826808b842ca046bf7baaeda869ff | 1,724 | exs | Elixir | priv/repo/migrations/20210124125642_create_admin_triggers.exs | feelja-tech/feelja-api | 03ce15430460cf2dac24a7740242c7e5ac5c5804 | [
"MIT"
] | null | null | null | priv/repo/migrations/20210124125642_create_admin_triggers.exs | feelja-tech/feelja-api | 03ce15430460cf2dac24a7740242c7e5ac5c5804 | [
"MIT"
] | null | null | null | priv/repo/migrations/20210124125642_create_admin_triggers.exs | feelja-tech/feelja-api | 03ce15430460cf2dac24a7740242c7e5ac5c5804 | [
"MIT"
] | null | null | null | defmodule NudgeApi.Repo.Migrations.CreateAdminTriggers do
use Ecto.Migration
def up do
# Create a function that broadcasts row changes
execute "
CREATE OR REPLACE FUNCTION broadcast_changes()
RETURNS trigger AS $$
DECLARE
current_row RECORD;
BEGIN
IF (TG_OP = 'INSERT' OR TG_OP = 'UPDATE') THEN
current_row := NEW;
ELSE
current_row := OLD;
END IF;
IF (TG_OP = 'INSERT') THEN
OLD := NEW;
END IF;
PERFORM pg_notify(
'table_changes',
json_build_object(
'table', TG_TABLE_NAME,
'type', TG_OP,
'id', current_row.id,
'new_row_data', row_to_json(NEW),
'old_row_data', row_to_json(OLD)
)::text
);
RETURN current_row;
END;
$$ LANGUAGE plpgsql;"
# Create a trigger that links USER_MATCHES ON INSERT with INITIATOR to the broadcast function
execute "DROP TRIGGER IF EXISTS notify_table_changes_trigger ON user_matches;"
execute "CREATE TRIGGER notify_table_changes_trigger AFTER INSERT ON user_matches FOR EACH ROW WHEN (NEW.initiator) EXECUTE PROCEDURE broadcast_changes();"
# Create a trigger that links MEETINGS ON UPDATE location to the broadcast function
execute "DROP TRIGGER IF EXISTS notify_table_changes_trigger ON meetings;"
execute "CREATE TRIGGER notify_table_changes_trigger AFTER UPDATE OF location ON meetings FOR EACH ROW EXECUTE PROCEDURE broadcast_changes();"
end
def down do
execute "DROP TRIGGER IF EXISTS notify_table_changes_trigger on meetings;"
execute "DROP TRIGGER IF EXISTS notify_table_changes_trigger on user_matches;"
end
end
| 35.183673 | 159 | 0.674594 |
79087b4ee8ba444af7e41f9faefedc225ac61dfd | 2,037 | ex | Elixir | lib/codes/codes_b65.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_b65.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_b65.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_B65 do
alias IcdCode.ICDCode
def _B650 do
%ICDCode{full_code: "B650",
category_code: "B65",
short_code: "0",
full_name: "Schistosomiasis due to Schistosoma haematobium [urinary schistosomiasis]",
short_name: "Schistosomiasis due to Schistosoma haematobium [urinary schistosomiasis]",
category_name: "Schistosomiasis due to Schistosoma haematobium [urinary schistosomiasis]"
}
end
def _B651 do
%ICDCode{full_code: "B651",
category_code: "B65",
short_code: "1",
full_name: "Schistosomiasis due to Schistosoma mansoni [intestinal schistosomiasis]",
short_name: "Schistosomiasis due to Schistosoma mansoni [intestinal schistosomiasis]",
category_name: "Schistosomiasis due to Schistosoma mansoni [intestinal schistosomiasis]"
}
end
def _B652 do
%ICDCode{full_code: "B652",
category_code: "B65",
short_code: "2",
full_name: "Schistosomiasis due to Schistosoma japonicum",
short_name: "Schistosomiasis due to Schistosoma japonicum",
category_name: "Schistosomiasis due to Schistosoma japonicum"
}
end
def _B653 do
%ICDCode{full_code: "B653",
category_code: "B65",
short_code: "3",
full_name: "Cercarial dermatitis",
short_name: "Cercarial dermatitis",
category_name: "Cercarial dermatitis"
}
end
def _B658 do
%ICDCode{full_code: "B658",
category_code: "B65",
short_code: "8",
full_name: "Other schistosomiasis",
short_name: "Other schistosomiasis",
category_name: "Other schistosomiasis"
}
end
def _B659 do
%ICDCode{full_code: "B659",
category_code: "B65",
short_code: "9",
full_name: "Schistosomiasis, unspecified",
short_name: "Schistosomiasis, unspecified",
category_name: "Schistosomiasis, unspecified"
}
end
end
| 33.393443 | 99 | 0.640157 |
79088cbce22a32f6cfef44a0fe0929dc93a9adc7 | 973 | exs | Elixir | apps/dockup_ui/test/services/delete_expired_deployments_service_test.exs | sleekr/dockup | 11d068879253af655ebabbd3e39cb21400c8e283 | [
"MIT"
] | 1 | 2019-08-20T07:45:10.000Z | 2019-08-20T07:45:10.000Z | apps/dockup_ui/test/services/delete_expired_deployments_service_test.exs | sleekr/dockup | 11d068879253af655ebabbd3e39cb21400c8e283 | [
"MIT"
] | null | null | null | apps/dockup_ui/test/services/delete_expired_deployments_service_test.exs | sleekr/dockup | 11d068879253af655ebabbd3e39cb21400c8e283 | [
"MIT"
] | 2 | 2019-03-08T10:51:34.000Z | 2019-08-20T07:45:13.000Z | defmodule DockupUi.DeleteExpiredDeploymentsServiceTest do
use DockupUi.ModelCase, async: true
import DockupUi.Factory
import ExUnit.CaptureIO
alias DockupUi.DeleteExpiredDeploymentsService
defmodule FakeDeleteDeploymentService do
def run(1, _callback_data) do
IO.write "Deployment deleted"
end
end
test "deletes deployments older than 1 day" do
insert_at =
DateTime.utc_now()
|> DateTime.to_naive()
|> NaiveDateTime.add(-(60 * 60 * 24 + 1))
|> DateTime.from_naive!("Etc/UTC")
insert(:deployment, %{id: 1, inserted_at: insert_at})
assert capture_io(fn ->
DeleteExpiredDeploymentsService.run(FakeDeleteDeploymentService, 1)
end) == "Deployment deleted"
end
test "does not delete deployments less than 1 day ago" do
insert(:deployment, id: 1)
assert capture_io(fn ->
DeleteExpiredDeploymentsService.run(FakeDeleteDeploymentService, 1)
end) != "Deployment deleted"
end
end
| 27.8 | 73 | 0.715313 |
79089a81319f71484dcfddab9888040dbf55ef5e | 61,210 | ex | Elixir | clients/content/lib/google_api/content/v2/api/orders.ex | chingor13/elixir-google-api | 85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/content/lib/google_api/content/v2/api/orders.ex | chingor13/elixir-google-api | 85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/api/orders.ex | chingor13/elixir-google-api | 85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.Content.V2.Api.Orders do
@moduledoc """
API calls for all endpoints tagged `Orders`.
"""
alias GoogleApi.Content.V2.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Marks an order as acknowledged.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the order.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersAcknowledgeRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersAcknowledgeResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_acknowledge(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersAcknowledgeResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_acknowledge(
connection,
merchant_id,
order_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/orders/{orderId}/acknowledge", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersAcknowledgeResponse{}])
end
@doc """
Sandbox only. Moves a test order from state "inProgress" to state "pendingShipment".
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the test order to modify.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersAdvanceTestOrderResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_advancetestorder(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersAdvanceTestOrderResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_advancetestorder(
connection,
merchant_id,
order_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/testorders/{orderId}/advance", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersAdvanceTestOrderResponse{}]
)
end
@doc """
Cancels all line items in an order, making a full refund.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the order to cancel.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersCancelRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersCancelResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_cancel(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.OrdersCancelResponse.t()} | {:error, Tesla.Env.t()}
def content_orders_cancel(connection, merchant_id, order_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/orders/{orderId}/cancel", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersCancelResponse{}])
end
@doc """
Cancels a line item, making a full refund.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the order.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersCancelLineItemRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersCancelLineItemResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_cancellineitem(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersCancelLineItemResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_cancellineitem(
connection,
merchant_id,
order_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/orders/{orderId}/cancelLineItem", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersCancelLineItemResponse{}]
)
end
@doc """
Sandbox only. Cancels a test order for customer-initiated cancellation.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the test order to cancel.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersCancelTestOrderByCustomerRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersCancelTestOrderByCustomerResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_canceltestorderbycustomer(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersCancelTestOrderByCustomerResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_canceltestorderbycustomer(
connection,
merchant_id,
order_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/testorders/{orderId}/cancelByCustomer", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersCancelTestOrderByCustomerResponse{}]
)
end
@doc """
Sandbox only. Creates a test order.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that should manage the order. This cannot be a multi-client account.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersCreateTestOrderRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersCreateTestOrderResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_createtestorder(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.OrdersCreateTestOrderResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_createtestorder(connection, merchant_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/testorders", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersCreateTestOrderResponse{}]
)
end
@doc """
Sandbox only. Creates a test return.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the order.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersCreateTestReturnRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersCreateTestReturnResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_createtestreturn(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersCreateTestReturnResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_createtestreturn(
connection,
merchant_id,
order_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/orders/{orderId}/testreturn", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersCreateTestReturnResponse{}]
)
end
@doc """
Retrieves or modifies multiple orders in a single request.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersCustomBatchRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersCustomBatchResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_custombatch(Tesla.Env.client(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.OrdersCustomBatchResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_custombatch(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/orders/batch", %{})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersCustomBatchResponse{}])
end
@doc """
Retrieves an order from your Merchant Center account.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the order.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.Order{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_get(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.Order.t()} | {:error, Tesla.Env.t()}
def content_orders_get(connection, merchant_id, order_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{merchantId}/orders/{orderId}", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.Order{}])
end
@doc """
Retrieves an order using merchant order ID.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `merchant_order_id` (*type:* `String.t`) - The merchant order ID to be looked for.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersGetByMerchantOrderIdResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_getbymerchantorderid(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersGetByMerchantOrderIdResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_getbymerchantorderid(
connection,
merchant_id,
merchant_order_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{merchantId}/ordersbymerchantid/{merchantOrderId}", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"merchantOrderId" => URI.encode(merchant_order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersGetByMerchantOrderIdResponse{}]
)
end
@doc """
Sandbox only. Retrieves an order template that can be used to quickly create a new order in sandbox.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that should manage the order. This cannot be a multi-client account.
* `template_name` (*type:* `String.t`) - The name of the template to retrieve.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:country` (*type:* `String.t`) - The country of the template to retrieve. Defaults to US.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersGetTestOrderTemplateResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_gettestordertemplate(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersGetTestOrderTemplateResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_gettestordertemplate(
connection,
merchant_id,
template_name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:country => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{merchantId}/testordertemplates/{templateName}", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"templateName" => URI.encode(template_name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersGetTestOrderTemplateResponse{}]
)
end
@doc """
Notifies that item return and refund was handled directly by merchant outside of Google payments processing (e.g. cash refund done in store).
Note: We recommend calling the returnrefundlineitem method to refund in-store returns. We will issue the refund directly to the customer. This helps to prevent possible differences arising between merchant and Google transaction records. We also recommend having the point of sale system communicate with Google to ensure that customers do not receive a double refund by first refunding via Google then via an in-store return.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the order.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersInStoreRefundLineItemRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersInStoreRefundLineItemResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_instorerefundlineitem(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersInStoreRefundLineItemResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_instorerefundlineitem(
connection,
merchant_id,
order_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/orders/{orderId}/inStoreRefundLineItem", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersInStoreRefundLineItemResponse{}]
)
end
@doc """
Lists the orders in your Merchant Center account.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:acknowledged` (*type:* `boolean()`) - Obtains orders that match the acknowledgement status. When set to true, obtains orders that have been acknowledged. When false, obtains orders that have not been acknowledged.
We recommend using this filter set to false, in conjunction with the acknowledge call, such that only un-acknowledged orders are returned.
* `:maxResults` (*type:* `integer()`) - The maximum number of orders to return in the response, used for paging. The default value is 25 orders per page, and the maximum allowed value is 250 orders per page.
* `:orderBy` (*type:* `String.t`) - Order results by placement date in descending or ascending order.
Acceptable values are:
- placedDateAsc
- placedDateDesc
* `:pageToken` (*type:* `String.t`) - The token returned by the previous request.
* `:placedDateEnd` (*type:* `String.t`) - Obtains orders placed before this date (exclusively), in ISO 8601 format.
* `:placedDateStart` (*type:* `String.t`) - Obtains orders placed after this date (inclusively), in ISO 8601 format.
* `:statuses` (*type:* `list(String.t)`) - Obtains orders that match any of the specified statuses. Multiple values can be specified with comma separation. Additionally, please note that active is a shortcut for pendingShipment and partiallyShipped, and completed is a shortcut for shipped, partiallyDelivered, delivered, partiallyReturned, returned, and canceled.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersListResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.OrdersListResponse.t()} | {:error, Tesla.Env.t()}
def content_orders_list(connection, merchant_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:acknowledged => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query,
:placedDateEnd => :query,
:placedDateStart => :query,
:statuses => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{merchantId}/orders", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersListResponse{}])
end
@doc """
Deprecated, please use returnRefundLineItem instead.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the order to refund.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersRefundRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersRefundResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_refund(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Content.V2.Model.OrdersRefundResponse.t()} | {:error, Tesla.Env.t()}
def content_orders_refund(connection, merchant_id, order_id, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/orders/{orderId}/refund", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersRefundResponse{}])
end
@doc """
Rejects return on an line item.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the order.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersRejectReturnLineItemRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersRejectReturnLineItemResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_rejectreturnlineitem(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersRejectReturnLineItemResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_rejectreturnlineitem(
connection,
merchant_id,
order_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/orders/{orderId}/rejectReturnLineItem", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersRejectReturnLineItemResponse{}]
)
end
@doc """
Returns a line item.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the order.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersReturnLineItemRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersReturnLineItemResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_returnlineitem(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersReturnLineItemResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_returnlineitem(
connection,
merchant_id,
order_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/orders/{orderId}/returnLineItem", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersReturnLineItemResponse{}]
)
end
@doc """
Returns and refunds a line item. Note that this method can only be called on fully shipped orders.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the order.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersReturnRefundLineItemRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersReturnRefundLineItemResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_returnrefundlineitem(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersReturnRefundLineItemResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_returnrefundlineitem(
connection,
merchant_id,
order_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/orders/{orderId}/returnRefundLineItem", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersReturnRefundLineItemResponse{}]
)
end
@doc """
Sets (or overrides if it already exists) merchant provided annotations in the form of key-value pairs. A common use case would be to supply us with additional structured information about a line item that cannot be provided via other methods. Submitted key-value pairs can be retrieved as part of the orders resource.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the order.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersSetLineItemMetadataRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersSetLineItemMetadataResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_setlineitemmetadata(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersSetLineItemMetadataResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_setlineitemmetadata(
connection,
merchant_id,
order_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/orders/{orderId}/setLineItemMetadata", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersSetLineItemMetadataResponse{}]
)
end
@doc """
Marks line item(s) as shipped.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the order.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersShipLineItemsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersShipLineItemsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_shiplineitems(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersShipLineItemsResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_shiplineitems(
connection,
merchant_id,
order_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/orders/{orderId}/shipLineItems", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersShipLineItemsResponse{}]
)
end
@doc """
Updates ship by and delivery by dates for a line item.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the order.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersUpdateLineItemShippingDetailsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersUpdateLineItemShippingDetailsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_updatelineitemshippingdetails(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersUpdateLineItemShippingDetailsResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_updatelineitemshippingdetails(
connection,
merchant_id,
order_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/orders/{orderId}/updateLineItemShippingDetails", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersUpdateLineItemShippingDetailsResponse{}]
)
end
@doc """
Updates the merchant order ID for a given order.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the order.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersUpdateMerchantOrderIdRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersUpdateMerchantOrderIdResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_updatemerchantorderid(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersUpdateMerchantOrderIdResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_updatemerchantorderid(
connection,
merchant_id,
order_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/orders/{orderId}/updateMerchantOrderId", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersUpdateMerchantOrderIdResponse{}]
)
end
@doc """
Updates a shipment's status, carrier, and/or tracking ID.
## Parameters
* `connection` (*type:* `GoogleApi.Content.V2.Connection.t`) - Connection to server
* `merchant_id` (*type:* `String.t`) - The ID of the account that manages the order. This cannot be a multi-client account.
* `order_id` (*type:* `String.t`) - The ID of the order.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:alt` (*type:* `String.t`) - Data format for the response.
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
* `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead.
* `:body` (*type:* `GoogleApi.Content.V2.Model.OrdersUpdateShipmentRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Content.V2.Model.OrdersUpdateShipmentResponse{}}` on success
* `{:error, info}` on failure
"""
@spec content_orders_updateshipment(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Content.V2.Model.OrdersUpdateShipmentResponse.t()}
| {:error, Tesla.Env.t()}
def content_orders_updateshipment(
connection,
merchant_id,
order_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/{merchantId}/orders/{orderId}/updateShipment", %{
"merchantId" => URI.encode(merchant_id, &URI.char_unreserved?/1),
"orderId" => URI.encode(order_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Content.V2.Model.OrdersUpdateShipmentResponse{}]
)
end
end
| 43.257951 | 428 | 0.625878 |
7908d74d5bcf8a5f4935e8eea56caa91ad24123e | 1,402 | ex | Elixir | apps/institute_web/lib/institute_web/telemetry.ex | hui-ad/institute | 28242d9d324d710a0e70678ec2d79099f1d3a98d | [
"MIT"
] | 4 | 2019-06-12T19:05:34.000Z | 2019-08-18T15:02:56.000Z | apps/institute_web/lib/institute_web/telemetry.ex | hui-ad/institute | 28242d9d324d710a0e70678ec2d79099f1d3a98d | [
"MIT"
] | 33 | 2019-06-12T18:59:21.000Z | 2021-03-31T15:45:22.000Z | apps/institute_web/lib/institute_web/telemetry.ex | hui-ad/institute | 28242d9d324d710a0e70678ec2d79099f1d3a98d | [
"MIT"
] | 1 | 2019-06-16T09:38:08.000Z | 2019-06-16T09:38:08.000Z | defmodule InstituteWeb.Telemetry do
use Supervisor
import Telemetry.Metrics
def start_link(arg) do
Supervisor.start_link(__MODULE__, arg, name: __MODULE__)
end
@impl true
def init(_arg) do
children = [
# Telemetry poller will execute the given period measurements
# every 10_000ms. Learn more here: https://hexdocs.pm/telemetry_metrics
{:telemetry_poller, measurements: periodic_measurements(), period: 10_000}
# Add reporters as children of your supervision tree.
# {Telemetry.Metrics.ConsoleReporter, metrics: metrics()}
]
Supervisor.init(children, strategy: :one_for_one)
end
def metrics do
[
# Phoenix Metrics
summary("phoenix.endpoint.stop.duration",
unit: {:native, :millisecond}
),
summary("phoenix.router_dispatch.stop.duration",
tags: [:route],
unit: {:native, :millisecond}
),
# VM Metrics
summary("vm.memory.total", unit: {:byte, :kilobyte}),
summary("vm.total_run_queue_lengths.total"),
summary("vm.total_run_queue_lengths.cpu"),
summary("vm.total_run_queue_lengths.io")
]
end
defp periodic_measurements do
[
# A module, function and arguments to be invoked periodically.
# This function must call :telemetry.execute/3 and a metric must be added above.
# {InstituteWeb, :count_users, []}
]
end
end
| 28.612245 | 86 | 0.671184 |
7908e4473529a5c8f56c740f98eb0298b4ffdd82 | 1,339 | ex | Elixir | lib/game_of_life/universe/universe.ex | rdk08/otp-game-of-life | 142740af57f9d49a05b1cf159fe00474956b696f | [
"MIT"
] | null | null | null | lib/game_of_life/universe/universe.ex | rdk08/otp-game-of-life | 142740af57f9d49a05b1cf159fe00474956b696f | [
"MIT"
] | null | null | null | lib/game_of_life/universe/universe.ex | rdk08/otp-game-of-life | 142740af57f9d49a05b1cf159fe00474956b696f | [
"MIT"
] | null | null | null | defmodule GameOfLife.Universe do
alias __MODULE__, as: Universe
defstruct cells: [],
dimensions: {0, 0}
@type t :: %Universe{cells: list(tuple), dimensions: {integer, integer}}
@spec initialize({integer, integer}) :: t
def initialize(dimensions) do
%Universe{cells: generate_cells(dimensions), dimensions: dimensions}
end
defp generate_cells({columns, rows}) do
for row <- 0..(rows - 1),
column <- 0..(columns - 1),
do: {column, row}
end
@spec get_neighbours(t, {integer, integer}) :: list({integer, integer})
def get_neighbours(%Universe{} = universe, key) do
key_diffs()
|> Enum.reject(&self_key/1)
|> Enum.map(&neighbour(&1, key))
|> Enum.reject(&outside_universe?(&1, universe))
end
defp key_diffs do
for row_diff <- [-1, 0, 1],
column_diff <- [-1, 0, 1],
do: {row_diff, column_diff}
end
defp self_key(diff), do: diff == {0, 0}
defp neighbour({column_diff, row_diff}, {column, row}) do
{column - column_diff, row - row_diff}
end
defp outside_universe?({column, row}, %Universe{dimensions: dimensions}) do
{columns, rows} = dimensions
{max_column, max_row} = {columns - 1, rows - 1}
{min_column, min_row} = {0, 0}
column > max_column or column < min_column or row > max_row or row < min_row
end
end
| 28.489362 | 80 | 0.634802 |
7908edd74c0d5927ecb04961fcc8817c6a973171 | 353 | exs | Elixir | test/test_helper.exs | longnd/elixir-gscraper | 894570afd89e54b80ca591a56a182da55ac6ee61 | [
"MIT"
] | null | null | null | test/test_helper.exs | longnd/elixir-gscraper | 894570afd89e54b80ca591a56a182da55ac6ee61 | [
"MIT"
] | 25 | 2021-03-23T07:27:21.000Z | 2021-10-31T15:09:52.000Z | test/test_helper.exs | longnd/elixir-gscraper | 894570afd89e54b80ca591a56a182da55ac6ee61 | [
"MIT"
] | null | null | null | Code.put_compiler_option(:warnings_as_errors, true)
{:ok, _} = Application.ensure_all_started(:ex_machina)
{:ok, _} = Application.ensure_all_started(:mimic)
{:ok, _} = Application.ensure_all_started(:wallaby)
ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(Gscraper.Repo, :manual)
Application.put_env(:wallaby, :base_url, GscraperWeb.Endpoint.url())
| 27.153846 | 68 | 0.773371 |
79092214ed1b374164b7aea1c6e8afdc96cb872d | 2,680 | exs | Elixir | test/cv_creator/accounts_test.exs | Foxlabsdevelopers/cv_creator | c77d52cdc67180ed369a3dbd298ca2dea5131c60 | [
"MIT"
] | null | null | null | test/cv_creator/accounts_test.exs | Foxlabsdevelopers/cv_creator | c77d52cdc67180ed369a3dbd298ca2dea5131c60 | [
"MIT"
] | 2 | 2021-05-24T21:41:25.000Z | 2021-05-25T16:02:09.000Z | test/cv_creator/accounts_test.exs | Foxlabsdevelopers/cv_creator | c77d52cdc67180ed369a3dbd298ca2dea5131c60 | [
"MIT"
] | null | null | null | defmodule CvCreator.AccountsTest do
use CvCreator.DataCase
alias CvCreator.Accounts
describe "super_users" do
alias CvCreator.Accounts.SuperUsers
@valid_attrs %{name: "some name", email: "some email", password_hash: "some password_hash"}
@update_attrs %{name: "some updated name", email: "some updated email", password_hash: "some updated password_hash"}
@invalid_attrs %{name: nil, email: nil, password_hash: nil}
def super_users_fixture(attrs \\ %{}) do
{:ok, super_users} =
attrs
|> Enum.into(@valid_attrs)
|> Accounts.create_super_users()
super_users
end
test "list_super_users/0 returns all super_users" do
super_users = super_users_fixture()
assert Accounts.list_super_users() == [super_users]
end
test "get_super_users!/1 returns the super_users with given id" do
super_users = super_users_fixture()
assert Accounts.get_super_users!(super_users.id) == super_users
end
test "create_super_users/1 with valid data creates a super_users" do
assert {:ok, %SuperUsers{} = super_users} = Accounts.create_super_users(@valid_attrs)
assert super_users.name == "some name"
assert super_users.email == "some email"
assert super_users.password_hash == "some password_hash"
end
test "create_super_users/1 with invalid data returns error changeset" do
assert {:error, %Ecto.Changeset{}} = Accounts.create_super_users(@invalid_attrs)
end
test "update_super_users/2 with valid data updates the super_users" do
super_users = super_users_fixture()
assert {:ok, %SuperUsers{} = super_users} = Accounts.update_super_users(super_users, @update_attrs)
assert super_users.name == "some updated name"
assert super_users.email == "some updated email"
assert super_users.password_hash == "some updated password_hash"
end
test "update_super_users/2 with invalid data returns error changeset" do
super_users = super_users_fixture()
assert {:error, %Ecto.Changeset{}} = Accounts.update_super_users(super_users, @invalid_attrs)
assert super_users == Accounts.get_super_users!(super_users.id)
end
test "delete_super_users/1 deletes the super_users" do
super_users = super_users_fixture()
assert {:ok, %SuperUsers{}} = Accounts.delete_super_users(super_users)
assert_raise Ecto.NoResultsError, fn -> Accounts.get_super_users!(super_users.id) end
end
test "change_super_users/1 returns a super_users changeset" do
super_users = super_users_fixture()
assert %Ecto.Changeset{} = Accounts.change_super_users(super_users)
end
end
end
| 38.84058 | 120 | 0.717537 |
79092620040178f151be9abb4d472ab8403c5ab9 | 2,737 | ex | Elixir | clients/firebase_dynamic_links/lib/google_api/firebase_dynamic_links/v1/model/device_info.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/firebase_dynamic_links/lib/google_api/firebase_dynamic_links/v1/model/device_info.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/firebase_dynamic_links/lib/google_api/firebase_dynamic_links/v1/model/device_info.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.FirebaseDynamicLinks.V1.Model.DeviceInfo do
@moduledoc """
Signals associated with the device making the request.
## Attributes
* `deviceModelName` (*type:* `String.t`, *default:* `nil`) - Device model name.
* `languageCode` (*type:* `String.t`, *default:* `nil`) - Device language code setting.
* `languageCodeFromWebview` (*type:* `String.t`, *default:* `nil`) - Device language code setting obtained by executing JavaScript code in WebView.
* `languageCodeRaw` (*type:* `String.t`, *default:* `nil`) - Device language code raw setting. iOS does returns language code in different format than iOS WebView. For example WebView returns en_US, but iOS returns en-US. Field below will return raw value returned by iOS.
* `screenResolutionHeight` (*type:* `String.t`, *default:* `nil`) - Device display resolution height.
* `screenResolutionWidth` (*type:* `String.t`, *default:* `nil`) - Device display resolution width.
* `timezone` (*type:* `String.t`, *default:* `nil`) - Device timezone setting.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:deviceModelName => String.t() | nil,
:languageCode => String.t() | nil,
:languageCodeFromWebview => String.t() | nil,
:languageCodeRaw => String.t() | nil,
:screenResolutionHeight => String.t() | nil,
:screenResolutionWidth => String.t() | nil,
:timezone => String.t() | nil
}
field(:deviceModelName)
field(:languageCode)
field(:languageCodeFromWebview)
field(:languageCodeRaw)
field(:screenResolutionHeight)
field(:screenResolutionWidth)
field(:timezone)
end
defimpl Poison.Decoder, for: GoogleApi.FirebaseDynamicLinks.V1.Model.DeviceInfo do
def decode(value, options) do
GoogleApi.FirebaseDynamicLinks.V1.Model.DeviceInfo.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.FirebaseDynamicLinks.V1.Model.DeviceInfo do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 42.107692 | 276 | 0.710632 |
79093873326f042466ac2742a309f9cb2614036a | 274 | exs | Elixir | config/config.exs | chrismo/oban | f912ccf75a1d89e02229041d578f9263d4de0232 | [
"Apache-2.0"
] | null | null | null | config/config.exs | chrismo/oban | f912ccf75a1d89e02229041d578f9263d4de0232 | [
"Apache-2.0"
] | null | null | null | config/config.exs | chrismo/oban | f912ccf75a1d89e02229041d578f9263d4de0232 | [
"Apache-2.0"
] | null | null | null | import Config
config :elixir, :time_zone_database, Tzdata.TimeZoneDatabase
config :oban, Oban.Test.Repo,
priv: "test/support/",
url: System.get_env("DATABASE_URL") || "postgres://localhost:5432/oban_test",
pool_size: 10
config :oban,
ecto_repos: [Oban.Test.Repo]
| 22.833333 | 79 | 0.737226 |
790956a89ff10e73c751984fb012c119b39d7b78 | 106,759 | ex | Elixir | clients/big_query_data_transfer/lib/google_api/big_query_data_transfer/v1/api/projects.ex | chingor13/elixir-google-api | 85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/big_query_data_transfer/lib/google_api/big_query_data_transfer/v1/api/projects.ex | chingor13/elixir-google-api | 85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b | [
"Apache-2.0"
] | null | null | null | clients/big_query_data_transfer/lib/google_api/big_query_data_transfer/v1/api/projects.ex | chingor13/elixir-google-api | 85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.BigQueryDataTransfer.V1.Api.Projects do
@moduledoc """
API calls for all endpoints tagged `Projects`.
"""
alias GoogleApi.BigQueryDataTransfer.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Returns true if valid credentials exist for the given data source and
requesting user.
Some data sources doesn't support service account, so we need to talk to
them on behalf of the end user. This API just checks whether we have OAuth
token for the particular user, which is a pre-requisite before user can
create a transfer config.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The data source in the form:
`projects/{project_id}/dataSources/{data_source_id}`
* `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.BigQueryDataTransfer.V1.Model.CheckValidCredsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.CheckValidCredsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_data_sources_check_valid_creds(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.CheckValidCredsResponse.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_data_sources_check_valid_creds(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+name}:checkValidCreds", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.CheckValidCredsResponse{}]
)
end
@doc """
Retrieves a supported data source and returns its settings,
which can be used for UI rendering.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The field will contain name of the resource requested, for example:
`projects/{project_id}/dataSources/{data_source_id}`
* `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.BigQueryDataTransfer.V1.Model.DataSource{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_data_sources_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.DataSource.t()} | {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_data_sources_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)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.DataSource{}])
end
@doc """
Lists supported data sources and returns their settings,
which can be used for UI rendering.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - The BigQuery project id for which data sources should be returned.
Must be in the form: `projects/{project_id}`
* `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()`) - Page size. The default page size is the maximum value of 1000 results.
* `:pageToken` (*type:* `String.t`) - Pagination token, which can be used to request a specific page
of `ListDataSourcesRequest` list results. For multiple-page
results, `ListDataSourcesResponse` outputs
a `next_page` token, which can be used as the
`page_token` value to request the next page of list results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListDataSourcesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_data_sources_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListDataSourcesResponse.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_data_sources_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}/dataSources", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListDataSourcesResponse{}]
)
end
@doc """
Gets information about a location.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - Resource name for the 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").
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.Location{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.Location.t()} | {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_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)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.Location{}])
end
@doc """
Lists information about the supported locations for this service.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The resource that owns the locations collection, if applicable.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:$.xgafv` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - The standard list filter.
* `:pageSize` (*type:* `integer()`) - The standard list page size.
* `:pageToken` (*type:* `String.t`) - The standard list page token.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListLocationsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListLocationsResponse.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_list(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+name}/locations", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListLocationsResponse{}]
)
end
@doc """
Returns true if valid credentials exist for the given data source and
requesting user.
Some data sources doesn't support service account, so we need to talk to
them on behalf of the end user. This API just checks whether we have OAuth
token for the particular user, which is a pre-requisite before user can
create a transfer config.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The data source in the form:
`projects/{project_id}/dataSources/{data_source_id}`
* `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.BigQueryDataTransfer.V1.Model.CheckValidCredsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.CheckValidCredsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_data_sources_check_valid_creds(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.CheckValidCredsResponse.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_data_sources_check_valid_creds(
connection,
name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+name}:checkValidCreds", %{
"name" => URI.encode(name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.CheckValidCredsResponse{}]
)
end
@doc """
Retrieves a supported data source and returns its settings,
which can be used for UI rendering.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The field will contain name of the resource requested, for example:
`projects/{project_id}/dataSources/{data_source_id}`
* `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.BigQueryDataTransfer.V1.Model.DataSource{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_data_sources_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.DataSource.t()} | {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_data_sources_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)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.DataSource{}])
end
@doc """
Lists supported data sources and returns their settings,
which can be used for UI rendering.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - The BigQuery project id for which data sources should be returned.
Must be in the form: `projects/{project_id}`
* `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()`) - Page size. The default page size is the maximum value of 1000 results.
* `:pageToken` (*type:* `String.t`) - Pagination token, which can be used to request a specific page
of `ListDataSourcesRequest` list results. For multiple-page
results, `ListDataSourcesResponse` outputs
a `next_page` token, which can be used as the
`page_token` value to request the next page of list results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListDataSourcesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_data_sources_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListDataSourcesResponse.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_data_sources_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}/dataSources", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListDataSourcesResponse{}]
)
end
@doc """
Creates a new data transfer configuration.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - The BigQuery project id where the transfer configuration should be created.
Must be in the format projects/{project_id}/locations/{location_id}
If specified location and location of the destination bigquery dataset
do not match - the request will fail.
* `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").
* `:authorizationCode` (*type:* `String.t`) - Optional OAuth2 authorization code to use with this transfer configuration.
This is required if new credentials are needed, as indicated by
`CheckValidCreds`.
In order to obtain authorization_code, please make a
request to
https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client_id=<datatransferapiclientid>&scope=<data_source_scopes>&redirect_uri=<redirect_uri>
* client_id should be OAuth client_id of BigQuery DTS API for the given
data source returned by ListDataSources method.
* data_source_scopes are the scopes returned by ListDataSources method.
* redirect_uri is an optional parameter. If not specified, then
authorization code is posted to the opener of authorization flow window.
Otherwise it will be sent to the redirect uri. A special value of
urn:ietf:wg:oauth:2.0:oob means that authorization code should be
returned in the title bar of the browser, with the page text prompting
the user to copy the code and paste it in the application.
* `:versionInfo` (*type:* `String.t`) - Optional version info. If users want to find a very recent access token,
that is, immediately after approving access, users have to set the
version_info claim in the token request. To obtain the version_info, users
must use the "none+gsession" response type. which be return a
version_info back in the authorization response which be be put in a JWT
claim in the token request.
* `:body` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_transfer_configs_create(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_transfer_configs_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,
:authorizationCode => :query,
:versionInfo => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+parent}/transferConfigs", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}]
)
end
@doc """
Deletes a data transfer configuration,
including any associated transfer runs and logs.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The field will contain name of the resource requested, for example:
`projects/{project_id}/transferConfigs/{config_id}`
* `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.BigQueryDataTransfer.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_transfer_configs_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_transfer_configs_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)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.Empty{}])
end
@doc """
Returns information about a data transfer config.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The field will contain name of the resource requested, for example:
`projects/{project_id}/transferConfigs/{config_id}`
* `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.BigQueryDataTransfer.V1.Model.TransferConfig{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_transfer_configs_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_transfer_configs_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)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}]
)
end
@doc """
Returns information about all data transfers in the project.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - The BigQuery project id for which data sources
should be returned: `projects/{project_id}`.
* `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").
* `:dataSourceIds` (*type:* `list(String.t)`) - When specified, only configurations of requested data sources are returned.
* `:pageSize` (*type:* `integer()`) - Page size. The default page size is the maximum value of 1000 results.
* `:pageToken` (*type:* `String.t`) - Pagination token, which can be used to request a specific page
of `ListTransfersRequest` list results. For multiple-page
results, `ListTransfersResponse` outputs
a `next_page` token, which can be used as the
`page_token` value to request the next page of list results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferConfigsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_transfer_configs_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferConfigsResponse.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_transfer_configs_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,
:dataSourceIds => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/transferConfigs", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferConfigsResponse{}]
)
end
@doc """
Updates a data transfer configuration.
All fields must be set, even if they are not updated.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The resource name of the transfer config.
Transfer config names have the form of
`projects/{project_id}/locations/{region}/transferConfigs/{config_id}`.
The name is automatically generated based on the config_id specified in
CreateTransferConfigRequest along with project_id and region. If config_id
is not provided, usually a uuid, even though it is not guaranteed or
required, will be generated for config_id.
* `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").
* `:authorizationCode` (*type:* `String.t`) - Optional OAuth2 authorization code to use with this transfer configuration.
If it is provided, the transfer configuration will be associated with the
authorizing user.
In order to obtain authorization_code, please make a
request to
https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client_id=<datatransferapiclientid>&scope=<data_source_scopes>&redirect_uri=<redirect_uri>
* client_id should be OAuth client_id of BigQuery DTS API for the given
data source returned by ListDataSources method.
* data_source_scopes are the scopes returned by ListDataSources method.
* redirect_uri is an optional parameter. If not specified, then
authorization code is posted to the opener of authorization flow window.
Otherwise it will be sent to the redirect uri. A special value of
urn:ietf:wg:oauth:2.0:oob means that authorization code should be
returned in the title bar of the browser, with the page text prompting
the user to copy the code and paste it in the application.
* `:updateMask` (*type:* `String.t`) - Required list of fields to be updated in this request.
* `:versionInfo` (*type:* `String.t`) - Optional version info. If users want to find a very recent access token,
that is, immediately after approving access, users have to set the
version_info claim in the token request. To obtain the version_info, users
must use the "none+gsession" response type. which be return a
version_info back in the authorization response which be be put in a JWT
claim in the token request.
* `:body` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_transfer_configs_patch(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_transfer_configs_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,
:authorizationCode => :query,
:updateMask => :query,
:versionInfo => :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)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}]
)
end
@doc """
Creates transfer runs for a time range [start_time, end_time].
For each date - or whatever granularity the data source supports - in the
range, one transfer run is created.
Note that runs are created per UTC time in the time range.
DEPRECATED: use StartManualTransferRuns instead.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Transfer configuration name in the form:
`projects/{project_id}/transferConfigs/{config_id}`.
* `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.BigQueryDataTransfer.V1.Model.ScheduleTransferRunsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ScheduleTransferRunsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_transfer_configs_schedule_runs(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ScheduleTransferRunsResponse.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_transfer_configs_schedule_runs(
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}:scheduleRuns", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ScheduleTransferRunsResponse{}]
)
end
@doc """
Start manual transfer runs to be executed now with schedule_time equal to
current time. The transfer runs can be created for a time range where the
run_time is between start_time (inclusive) and end_time (exclusive), or for
a specific run_time.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Transfer configuration name in the form:
`projects/{project_id}/transferConfigs/{config_id}`.
* `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.BigQueryDataTransfer.V1.Model.StartManualTransferRunsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.StartManualTransferRunsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_transfer_configs_start_manual_runs(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.StartManualTransferRunsResponse.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_transfer_configs_start_manual_runs(
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}:startManualRuns", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.StartManualTransferRunsResponse{}]
)
end
@doc """
Deletes the specified transfer run.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The field will contain name of the resource requested, for example:
`projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`
* `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.BigQueryDataTransfer.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_transfer_configs_runs_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_transfer_configs_runs_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)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.Empty{}])
end
@doc """
Returns information about the particular transfer run.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The field will contain name of the resource requested, for example:
`projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`
* `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.BigQueryDataTransfer.V1.Model.TransferRun{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_transfer_configs_runs_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.TransferRun.t()} | {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_transfer_configs_runs_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)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.TransferRun{}])
end
@doc """
Returns information about running and completed jobs.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Name of transfer configuration for which transfer runs should be retrieved.
Format of transfer configuration resource name is:
`projects/{project_id}/transferConfigs/{config_id}`.
* `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()`) - Page size. The default page size is the maximum value of 1000 results.
* `:pageToken` (*type:* `String.t`) - Pagination token, which can be used to request a specific page
of `ListTransferRunsRequest` list results. For multiple-page
results, `ListTransferRunsResponse` outputs
a `next_page` token, which can be used as the
`page_token` value to request the next page of list results.
* `:runAttempt` (*type:* `String.t`) - Indicates how run attempts are to be pulled.
* `:states` (*type:* `list(String.t)`) - When specified, only transfer runs with requested states are returned.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferRunsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_transfer_configs_runs_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferRunsResponse.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_transfer_configs_runs_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,
:runAttempt => :query,
:states => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/runs", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferRunsResponse{}]
)
end
@doc """
Returns user facing log messages for the data transfer run.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Transfer run name in the form:
`projects/{project_id}/transferConfigs/{config_Id}/runs/{run_id}`.
* `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").
* `:messageTypes` (*type:* `list(String.t)`) - Message types to return. If not populated - INFO, WARNING and ERROR
messages are returned.
* `:pageSize` (*type:* `integer()`) - Page size. The default page size is the maximum value of 1000 results.
* `:pageToken` (*type:* `String.t`) - Pagination token, which can be used to request a specific page
of `ListTransferLogsRequest` list results. For multiple-page
results, `ListTransferLogsResponse` outputs
a `next_page` token, which can be used as the
`page_token` value to request the next page of list results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferLogsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_locations_transfer_configs_runs_transfer_logs_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferLogsResponse.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_locations_transfer_configs_runs_transfer_logs_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,
:messageTypes => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/transferLogs", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferLogsResponse{}]
)
end
@doc """
Creates a new data transfer configuration.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - The BigQuery project id where the transfer configuration should be created.
Must be in the format projects/{project_id}/locations/{location_id}
If specified location and location of the destination bigquery dataset
do not match - the request will fail.
* `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").
* `:authorizationCode` (*type:* `String.t`) - Optional OAuth2 authorization code to use with this transfer configuration.
This is required if new credentials are needed, as indicated by
`CheckValidCreds`.
In order to obtain authorization_code, please make a
request to
https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client_id=<datatransferapiclientid>&scope=<data_source_scopes>&redirect_uri=<redirect_uri>
* client_id should be OAuth client_id of BigQuery DTS API for the given
data source returned by ListDataSources method.
* data_source_scopes are the scopes returned by ListDataSources method.
* redirect_uri is an optional parameter. If not specified, then
authorization code is posted to the opener of authorization flow window.
Otherwise it will be sent to the redirect uri. A special value of
urn:ietf:wg:oauth:2.0:oob means that authorization code should be
returned in the title bar of the browser, with the page text prompting
the user to copy the code and paste it in the application.
* `:versionInfo` (*type:* `String.t`) - Optional version info. If users want to find a very recent access token,
that is, immediately after approving access, users have to set the
version_info claim in the token request. To obtain the version_info, users
must use the "none+gsession" response type. which be return a
version_info back in the authorization response which be be put in a JWT
claim in the token request.
* `:body` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_transfer_configs_create(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_transfer_configs_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,
:authorizationCode => :query,
:versionInfo => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/{+parent}/transferConfigs", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}]
)
end
@doc """
Deletes a data transfer configuration,
including any associated transfer runs and logs.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The field will contain name of the resource requested, for example:
`projects/{project_id}/transferConfigs/{config_id}`
* `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.BigQueryDataTransfer.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_transfer_configs_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_transfer_configs_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)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.Empty{}])
end
@doc """
Returns information about a data transfer config.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The field will contain name of the resource requested, for example:
`projects/{project_id}/transferConfigs/{config_id}`
* `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.BigQueryDataTransfer.V1.Model.TransferConfig{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_transfer_configs_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_transfer_configs_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)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}]
)
end
@doc """
Returns information about all data transfers in the project.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - The BigQuery project id for which data sources
should be returned: `projects/{project_id}`.
* `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").
* `:dataSourceIds` (*type:* `list(String.t)`) - When specified, only configurations of requested data sources are returned.
* `:pageSize` (*type:* `integer()`) - Page size. The default page size is the maximum value of 1000 results.
* `:pageToken` (*type:* `String.t`) - Pagination token, which can be used to request a specific page
of `ListTransfersRequest` list results. For multiple-page
results, `ListTransfersResponse` outputs
a `next_page` token, which can be used as the
`page_token` value to request the next page of list results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferConfigsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_transfer_configs_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferConfigsResponse.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_transfer_configs_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,
:dataSourceIds => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/transferConfigs", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferConfigsResponse{}]
)
end
@doc """
Updates a data transfer configuration.
All fields must be set, even if they are not updated.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The resource name of the transfer config.
Transfer config names have the form of
`projects/{project_id}/locations/{region}/transferConfigs/{config_id}`.
The name is automatically generated based on the config_id specified in
CreateTransferConfigRequest along with project_id and region. If config_id
is not provided, usually a uuid, even though it is not guaranteed or
required, will be generated for config_id.
* `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").
* `:authorizationCode` (*type:* `String.t`) - Optional OAuth2 authorization code to use with this transfer configuration.
If it is provided, the transfer configuration will be associated with the
authorizing user.
In order to obtain authorization_code, please make a
request to
https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client_id=<datatransferapiclientid>&scope=<data_source_scopes>&redirect_uri=<redirect_uri>
* client_id should be OAuth client_id of BigQuery DTS API for the given
data source returned by ListDataSources method.
* data_source_scopes are the scopes returned by ListDataSources method.
* redirect_uri is an optional parameter. If not specified, then
authorization code is posted to the opener of authorization flow window.
Otherwise it will be sent to the redirect uri. A special value of
urn:ietf:wg:oauth:2.0:oob means that authorization code should be
returned in the title bar of the browser, with the page text prompting
the user to copy the code and paste it in the application.
* `:updateMask` (*type:* `String.t`) - Required list of fields to be updated in this request.
* `:versionInfo` (*type:* `String.t`) - Optional version info. If users want to find a very recent access token,
that is, immediately after approving access, users have to set the
version_info claim in the token request. To obtain the version_info, users
must use the "none+gsession" response type. which be return a
version_info back in the authorization response which be be put in a JWT
claim in the token request.
* `:body` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_transfer_configs_patch(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_transfer_configs_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,
:authorizationCode => :query,
:updateMask => :query,
:versionInfo => :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)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.TransferConfig{}]
)
end
@doc """
Creates transfer runs for a time range [start_time, end_time].
For each date - or whatever granularity the data source supports - in the
range, one transfer run is created.
Note that runs are created per UTC time in the time range.
DEPRECATED: use StartManualTransferRuns instead.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Transfer configuration name in the form:
`projects/{project_id}/transferConfigs/{config_id}`.
* `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.BigQueryDataTransfer.V1.Model.ScheduleTransferRunsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ScheduleTransferRunsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_transfer_configs_schedule_runs(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ScheduleTransferRunsResponse.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_transfer_configs_schedule_runs(
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}:scheduleRuns", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ScheduleTransferRunsResponse{}]
)
end
@doc """
Start manual transfer runs to be executed now with schedule_time equal to
current time. The transfer runs can be created for a time range where the
run_time is between start_time (inclusive) and end_time (exclusive), or for
a specific run_time.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Transfer configuration name in the form:
`projects/{project_id}/transferConfigs/{config_id}`.
* `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.BigQueryDataTransfer.V1.Model.StartManualTransferRunsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.StartManualTransferRunsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_transfer_configs_start_manual_runs(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.StartManualTransferRunsResponse.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_transfer_configs_start_manual_runs(
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}:startManualRuns", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.StartManualTransferRunsResponse{}]
)
end
@doc """
Deletes the specified transfer run.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The field will contain name of the resource requested, for example:
`projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`
* `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.BigQueryDataTransfer.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_transfer_configs_runs_delete(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.BigQueryDataTransfer.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_transfer_configs_runs_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)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.Empty{}])
end
@doc """
Returns information about the particular transfer run.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `name` (*type:* `String.t`) - The field will contain name of the resource requested, for example:
`projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}`
* `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.BigQueryDataTransfer.V1.Model.TransferRun{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_transfer_configs_runs_get(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.TransferRun.t()} | {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_transfer_configs_runs_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)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.TransferRun{}])
end
@doc """
Returns information about running and completed jobs.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Name of transfer configuration for which transfer runs should be retrieved.
Format of transfer configuration resource name is:
`projects/{project_id}/transferConfigs/{config_id}`.
* `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()`) - Page size. The default page size is the maximum value of 1000 results.
* `:pageToken` (*type:* `String.t`) - Pagination token, which can be used to request a specific page
of `ListTransferRunsRequest` list results. For multiple-page
results, `ListTransferRunsResponse` outputs
a `next_page` token, which can be used as the
`page_token` value to request the next page of list results.
* `:runAttempt` (*type:* `String.t`) - Indicates how run attempts are to be pulled.
* `:states` (*type:* `list(String.t)`) - When specified, only transfer runs with requested states are returned.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferRunsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_transfer_configs_runs_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferRunsResponse.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_transfer_configs_runs_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,
:runAttempt => :query,
:states => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/runs", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferRunsResponse{}]
)
end
@doc """
Returns user facing log messages for the data transfer run.
## Parameters
* `connection` (*type:* `GoogleApi.BigQueryDataTransfer.V1.Connection.t`) - Connection to server
* `parent` (*type:* `String.t`) - Transfer run name in the form:
`projects/{project_id}/transferConfigs/{config_Id}/runs/{run_id}`.
* `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").
* `:messageTypes` (*type:* `list(String.t)`) - Message types to return. If not populated - INFO, WARNING and ERROR
messages are returned.
* `:pageSize` (*type:* `integer()`) - Page size. The default page size is the maximum value of 1000 results.
* `:pageToken` (*type:* `String.t`) - Pagination token, which can be used to request a specific page
of `ListTransferLogsRequest` list results. For multiple-page
results, `ListTransferLogsResponse` outputs
a `next_page` token, which can be used as the
`page_token` value to request the next page of list results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferLogsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec bigquerydatatransfer_projects_transfer_configs_runs_transfer_logs_list(
Tesla.Env.client(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferLogsResponse.t()}
| {:error, Tesla.Env.t()}
def bigquerydatatransfer_projects_transfer_configs_runs_transfer_logs_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,
:messageTypes => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/{+parent}/transferLogs", %{
"parent" => URI.encode(parent, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.BigQueryDataTransfer.V1.Model.ListTransferLogsResponse{}]
)
end
end
| 45.468058 | 196 | 0.626252 |
7909e1d0cb8756780d7ff9f8dbdbf5bacbe6ca67 | 2,006 | exs | Elixir | src/mailer/config/prod.exs | alexjoybc/elixir-kafka-phoenix | c3d20415f980455081102f3bd4287647bf2292ba | [
"Apache-2.0"
] | null | null | null | src/mailer/config/prod.exs | alexjoybc/elixir-kafka-phoenix | c3d20415f980455081102f3bd4287647bf2292ba | [
"Apache-2.0"
] | null | null | null | src/mailer/config/prod.exs | alexjoybc/elixir-kafka-phoenix | c3d20415f980455081102f3bd4287647bf2292ba | [
"Apache-2.0"
] | null | null | null | use Mix.Config
# For production, don't forget to configure the url host
# to something meaningful, Phoenix uses this information
# when generating URLs.
#
# Note we also include the path to a cache manifest
# containing the digested version of static files. This
# manifest is generated by the `mix phx.digest` task,
# which you should run after static files are built and
# before starting your production server.
config :mailer, MailerWeb.Endpoint,
url: [host: "example.com", port: 80],
cache_static_manifest: "priv/static/cache_manifest.json"
# Do not print debug messages in production
config :logger, level: :info
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :mailer, MailerWeb.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [
# port: 443,
# cipher_suite: :strong,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH"),
# transport_options: [socket_opts: [:inet6]]
# ]
#
# The `cipher_suite` is set to `:strong` to support only the
# latest and more secure SSL ciphers. This means old browsers
# and clients may not be supported. You can set it to
# `:compatible` for wider support.
#
# `:keyfile` and `:certfile` expect an absolute path to the key
# and cert in disk or a relative path inside priv, for example
# "priv/ssl/server.key". For all supported SSL configuration
# options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1
#
# We also recommend setting `force_ssl` in your endpoint, ensuring
# no data is ever sent via http, always redirecting to https:
#
# config :mailer, MailerWeb.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# Finally import the config/prod.secret.exs which loads secrets
# and configuration from environment variables.
import_config "prod.secret.exs"
| 35.821429 | 66 | 0.713858 |
790a322b8bc8f9437c550f8f0a3032d56a428ec5 | 1,082 | ex | Elixir | lib/hunter/result.ex | jeffkreeftmeijer/hunter | a5ccf0849c8aeaee3dd90b431067924ff603a651 | [
"Apache-2.0"
] | null | null | null | lib/hunter/result.ex | jeffkreeftmeijer/hunter | a5ccf0849c8aeaee3dd90b431067924ff603a651 | [
"Apache-2.0"
] | null | null | null | lib/hunter/result.ex | jeffkreeftmeijer/hunter | a5ccf0849c8aeaee3dd90b431067924ff603a651 | [
"Apache-2.0"
] | null | null | null | defmodule Hunter.Result do
@moduledoc """
Result entity
## Fields
* `accounts` - list of matched `Hunter.Account`
* `statuses` - list of matched `Hunter.Status`
* `hashtags` - list of matched hashtags, as strings
"""
@hunter_api Hunter.Config.hunter_api()
@type t :: %__MODULE__{
accounts: [Hunter.Account.t()],
statuses: [Hunter.Status.t()],
hashtags: [String.t()]
}
@derive [Poison.Encoder]
defstruct accounts: [],
statuses: [],
hashtags: []
@doc """
Search for content
## Parameters
* `conn` - Connection credentials
* `q` - the search query, if `q` is a URL Mastodon will attempt to fetch
the provided account or status, it will do a local account and hashtag
search
* `options` - option list
## Options
* `resolve` - Whether to resolve non-local accounts
"""
@spec search(Hunter.Client.t(), String.t(), Keyword.t()) :: Hunter.Result.t()
def search(conn, query, options \\ []) do
@hunter_api.search(conn, query, options)
end
end
| 23.521739 | 79 | 0.608133 |
790a37779c1e95dac980c2f7d5d7f87f2b4aadc8 | 336 | exs | Elixir | priv/repo/migrations/20200509183314_add_oban_jobs_table.exs | isshindev/accent | ae4c13139b0a0dfd64ff536b94c940a4e2862150 | [
"BSD-3-Clause"
] | 806 | 2018-04-07T20:40:33.000Z | 2022-03-30T01:39:57.000Z | priv/repo/migrations/20200509183314_add_oban_jobs_table.exs | isshindev/accent | ae4c13139b0a0dfd64ff536b94c940a4e2862150 | [
"BSD-3-Clause"
] | 194 | 2018-04-07T13:49:37.000Z | 2022-03-30T19:58:45.000Z | priv/repo/migrations/20200509183314_add_oban_jobs_table.exs | isshindev/accent | ae4c13139b0a0dfd64ff536b94c940a4e2862150 | [
"BSD-3-Clause"
] | 89 | 2018-04-09T13:55:49.000Z | 2022-03-24T07:09:31.000Z | defmodule Accent.Repo.Migrations.AddObanJobsTable do
use Ecto.Migration
def up do
Oban.Migrations.up()
end
# We specify `version: 1` in `down`, ensuring that we'll roll all the way back down if
# necessary, regardless of which version we've migrated `up` to.
def down do
Oban.Migrations.down(version: 1)
end
end
| 24 | 88 | 0.717262 |
790a58cb5314604c528d5c1abbb9c4d12d5aa0d3 | 1,663 | ex | Elixir | lib/astarte_flow/blocks/default_blocks.ex | Annopaolo/astarte_flow | d6846917d2adb87127cb06ab6aeb11d6c0d10de8 | [
"Apache-2.0"
] | 11 | 2020-01-30T17:44:35.000Z | 2022-01-13T19:17:21.000Z | lib/astarte_flow/blocks/default_blocks.ex | Annopaolo/astarte_flow | d6846917d2adb87127cb06ab6aeb11d6c0d10de8 | [
"Apache-2.0"
] | 100 | 2020-02-11T10:01:35.000Z | 2022-02-17T10:39:35.000Z | lib/astarte_flow/blocks/default_blocks.ex | Annopaolo/astarte_flow | d6846917d2adb87127cb06ab6aeb11d6c0d10de8 | [
"Apache-2.0"
] | 7 | 2020-01-30T11:33:20.000Z | 2021-05-03T09:48:41.000Z | #
# This file is part of Astarte.
#
# Copyright 2020 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.Flow.Blocks.DefaultBlocks do
alias Astarte.Flow.Blocks.Block
# Recompile when the blocks directory changes
@external_resource "priv/blocks"
Module.register_attribute(__MODULE__, :default_blocks, accumulate: true)
default_blocks =
"#{:code.priv_dir(:astarte_flow)}/blocks/*.json"
|> Path.wildcard()
for file <- default_blocks do
%{"name" => name, "beam_module" => beam_module, "type" => type, "schema" => schema} =
file
|> File.read!()
|> Jason.decode!()
beam_module_atom = String.to_atom(beam_module)
block = %Block{name: name, beam_module: beam_module_atom, type: type, schema: schema}
# block is not a basic type, so it must be escaped to pass it to unquote
escaped_block = Macro.escape(block)
def fetch(unquote(name)) do
{:ok, unquote(escaped_block)}
end
# Accumulate blocks
@default_blocks block
end
# Fallback for non-existing blocks
def fetch(_name) do
{:error, :not_found}
end
def list do
@default_blocks
end
end
| 27.262295 | 89 | 0.706554 |
790a650226bb5152fb413f22c55f2f5a49ef0442 | 3,288 | ex | Elixir | lib/captain_hook/webhook_conversations.ex | annatel/captain_hook | e16a01107d11756d37d96d1e9092c17d9aa9260b | [
"MIT"
] | 4 | 2020-11-13T11:27:24.000Z | 2021-08-19T17:28:53.000Z | lib/captain_hook/webhook_conversations.ex | annatel/captain_hook | e16a01107d11756d37d96d1e9092c17d9aa9260b | [
"MIT"
] | null | null | null | lib/captain_hook/webhook_conversations.ex | annatel/captain_hook | e16a01107d11756d37d96d1e9092c17d9aa9260b | [
"MIT"
] | null | null | null | defmodule CaptainHook.WebhookConversations do
@moduledoc false
alias Ecto.Multi
alias CaptainHook.Sequences
alias CaptainHook.WebhookConversations.{WebhookConversation, WebhookConversationQueryable}
@default_page_number 1
@default_page_size 100
@spec list_webhook_conversations(keyword) :: [WebhookConversation.t()]
def list_webhook_conversations(opts \\ []) when is_list(opts) do
try do
opts |> webhook_conversation_queryable() |> CaptainHook.repo().all()
rescue
Ecto.Query.CastError -> []
end
end
@spec paginate_webhook_conversations(pos_integer, pos_integer, keyword) :: %{
data: [WebhookEndpoint.t()],
page_number: integer,
page_size: integer,
total: integer
}
def paginate_webhook_conversations(
page_size \\ @default_page_size,
page_number \\ @default_page_number,
opts \\ []
)
when is_integer(page_number) and is_integer(page_size) do
try do
query = opts |> webhook_conversation_queryable()
webhook_conversations =
query
|> WebhookConversationQueryable.paginate(page_size, page_number)
|> CaptainHook.repo().all()
%{
data: webhook_conversations,
page_number: page_number,
page_size: page_size,
total: CaptainHook.repo().aggregate(query, :count, :id)
}
rescue
Ecto.Query.CastError -> %{data: [], page_number: 0, page_size: 0, total: 0}
end
end
@spec get_webhook_conversation(binary, keyword) :: WebhookConversation.t() | nil
def get_webhook_conversation(id, opts \\ []) when is_binary(id) do
filters = opts |> Keyword.get(:filters, []) |> Keyword.put(:id, id)
try do
opts
|> Keyword.put(:filters, filters)
|> webhook_conversation_queryable()
|> CaptainHook.repo().one()
rescue
Ecto.Query.CastError -> nil
end
end
@spec create_webhook_conversation(map()) ::
{:ok, WebhookConversation.t()} | {:error, Ecto.Changeset.t()}
def create_webhook_conversation(attrs) when is_map(attrs) do
Multi.new()
|> Multi.run(:sequence, fn _repo, %{} ->
{:ok, Sequences.next_value!(:webhook_conversations)}
end)
|> Multi.insert(:webhook_conversation, fn %{sequence: sequence} ->
%WebhookConversation{}
|> WebhookConversation.changeset(attrs |> Map.put(:sequence, sequence))
end)
|> CaptainHook.repo().transaction()
|> case do
{:ok, %{webhook_conversation: webhook_conversation}} -> {:ok, webhook_conversation}
{:error, :webhook_conversation, error, _} -> {:error, error}
end
end
@spec conversation_succeeded?(WebhookConversation.t()) :: boolean
def conversation_succeeded?(%WebhookConversation{status: status}) do
status == WebhookConversation.statuses().succeeded
end
@spec webhook_conversation_queryable(keyword) :: Ecto.Queryable.t()
def webhook_conversation_queryable(opts) when is_list(opts) do
filters = Keyword.get(opts, :filters, [])
includes = Keyword.get(opts, :includes, [])
WebhookConversationQueryable.queryable()
|> WebhookConversationQueryable.filter(filters)
|> WebhookConversationQueryable.include(includes)
|> WebhookConversationQueryable.order_by(desc: :sequence)
end
end
| 33.212121 | 92 | 0.679745 |
790a6fdce1acff8a01dde56f14201286721f63dc | 8,367 | ex | Elixir | lib/ash/dsl/dsl.ex | smt116/ash | 880a17f197873eb1c8dc8d81a8b4d6d9cb570b3f | [
"MIT"
] | null | null | null | lib/ash/dsl/dsl.ex | smt116/ash | 880a17f197873eb1c8dc8d81a8b4d6d9cb570b3f | [
"MIT"
] | null | null | null | lib/ash/dsl/dsl.ex | smt116/ash | 880a17f197873eb1c8dc8d81a8b4d6d9cb570b3f | [
"MIT"
] | null | null | null | defmodule Ash.Dsl do
@using_schema [
single_extension_kinds: [
type: {:list, :atom},
default: [],
doc:
"The extension kinds that are allowed to have a single value. For example: `[:data_layer]`"
],
many_extension_kinds: [
type: {:list, :atom},
default: [],
doc:
"The extension kinds that can have multiple values. e.g `[notifiers: [Notifier1, Notifier2]]`"
],
untyped_extensions?: [
type: :boolean,
default: true,
doc: "Whether or not to support an `extensions` key which contains untyped extensions"
],
default_extensions: [
type: :keyword_list,
default: [],
doc: """
The extensions that are included by default. e.g `[data_layer: Default, notifiers: [Notifier1]]`
Default values for single extension kinds are overwritten if specified by the implementor, while many extension
kinds are appended to if specified by the implementor.
"""
]
]
@type entity :: %Ash.Dsl.Entity{}
@type section :: %Ash.Dsl.Section{}
@moduledoc """
The primary entry point for adding a DSL to a module.
To add a DSL to a module, add `use Ash.Dsl, ...options`. The options supported with `use Ash.Dsl` are:
#{Ash.OptionsHelpers.docs(@using_schema)}
See the callbacks defined in this module to augment the behavior/compilation of the module getting a Dsl.
"""
@type opts :: Keyword.t()
@doc """
Validate/add options. Those options will be passed to `handle_opts` and `handle_before_compile`
"""
@callback init(opts) :: {:ok, opts} | {:error, String.t() | term}
@doc """
Handle options in the context of the module. Must return a `quote` block.
If you want to persist anything in the DSL persistence layer,
use `@persist {:key, value}`. It can be called multiple times to
persist multiple times.
"""
@callback handle_opts(Keyword.t()) :: Macro.t()
@doc """
Handle options in the context of the module, after all extensions have been processed. Must return a `quote` block.
"""
@callback handle_before_compile(Keyword.t()) :: Macro.t()
defmacro __using__(opts) do
opts = Ash.OptionsHelpers.validate!(opts, @using_schema)
their_opt_schema =
Enum.map(opts[:single_extension_kinds], fn extension_kind ->
{extension_kind, type: :atom, default: opts[:default_extensions][extension_kind]}
end) ++
Enum.map(opts[:many_extension_kinds], fn extension_kind ->
{extension_kind, type: {:list, :atom}, default: []}
end)
their_opt_schema =
if opts[:untyped_extensions?] do
Keyword.put(their_opt_schema, :extensions, type: {:list, :atom})
else
their_opt_schema
end
their_opt_schema = Keyword.put(their_opt_schema, :otp_app, type: :atom)
quote bind_quoted: [
their_opt_schema: their_opt_schema,
parent_opts: opts,
parent: __CALLER__.module
],
generated: true do
require Ash.Dsl.Extension
@dialyzer {:nowarn_function, handle_opts: 1, handle_before_compile: 1}
Module.register_attribute(__MODULE__, :ash_dsl, persist: true)
Module.register_attribute(__MODULE__, :ash_default_extensions, persist: true)
Module.register_attribute(__MODULE__, :ash_extension_kinds, persist: true)
@ash_dsl true
@ash_default_extensions parent_opts[:default_extensions]
|> Keyword.values()
|> List.flatten()
@ash_extension_kinds List.wrap(parent_opts[:many_extension_kinds]) ++
List.wrap(parent_opts[:single_extension_kinds])
def init(opts), do: {:ok, opts}
def handle_opts(opts) do
quote do
end
end
def handle_before_compile(opts) do
quote do
end
end
defoverridable init: 1, handle_opts: 1, handle_before_compile: 1
defmacro __using__(opts) do
parent = unquote(parent)
parent_opts = unquote(parent_opts)
their_opt_schema = unquote(their_opt_schema)
require Ash.Dsl.Extension
{opts, extensions} =
parent_opts[:default_extensions]
|> Enum.reduce(opts, fn {key, defaults}, opts ->
Keyword.update(opts, key, defaults, fn current_value ->
cond do
key in parent_opts[:single_extension_kinds] ->
current_value || defaults
key in parent_opts[:many_extension_kinds] || key == :extensions ->
List.wrap(current_value) ++ List.wrap(defaults)
true ->
current_value
end
end)
end)
|> Ash.Dsl.expand_modules(parent_opts, __CALLER__)
opts =
opts
|> Ash.OptionsHelpers.validate!(their_opt_schema)
|> init()
|> Ash.Dsl.unwrap()
body =
quote generated: true do
parent = unquote(parent)
opts = unquote(opts)
parent_opts = unquote(parent_opts)
their_opt_schema = unquote(their_opt_schema)
@opts opts
@before_compile Ash.Dsl
@after_compile __MODULE__
@ash_is parent
@ash_parent parent
defmacro __after_compile__(_, _) do
quote do
Ash.Dsl.Extension.run_after_compile()
end
end
Module.register_attribute(__MODULE__, :persist, accumulate: true)
opts
|> @ash_parent.handle_opts()
|> Code.eval_quoted([], __ENV__)
if opts[:otp_app] do
@persist {:otp_app, opts[:otp_app]}
end
for single_extension_kind <- parent_opts[:single_extension_kinds] do
@persist {single_extension_kind, opts[single_extension_kind]}
Module.put_attribute(__MODULE__, single_extension_kind, opts[single_extension_kind])
end
for many_extension_kind <- parent_opts[:many_extension_kinds] do
@persist {many_extension_kind, opts[many_extension_kind] || []}
Module.put_attribute(
__MODULE__,
many_extension_kind,
opts[many_extension_kind] || []
)
end
end
preparations = Ash.Dsl.Extension.prepare(extensions)
[body | preparations]
end
end
end
@doc false
def unwrap({:ok, value}), do: value
def unwrap({:error, error}), do: raise(error)
@doc false
def expand_modules(opts, their_opt_schema, env) do
Enum.reduce(opts, {[], []}, fn {key, value}, {opts, extensions} ->
cond do
key in their_opt_schema[:single_extension_kinds] ->
mod = Macro.expand(value, %{env | lexical_tracker: nil})
extensions =
if Ash.Helpers.implements_behaviour?(mod, Ash.Dsl.Extension) do
[mod | extensions]
else
extensions
end
{Keyword.put(opts, key, mod), extensions}
key in their_opt_schema[:many_extension_kinds] || key == :extensions ->
mods =
value |> List.wrap() |> Enum.map(&Macro.expand(&1, %{env | lexical_tracker: nil}))
extensions =
extensions ++
Enum.filter(mods, &Ash.Helpers.implements_behaviour?(&1, Ash.Dsl.Extension))
{Keyword.put(opts, key, mods), extensions}
true ->
{Keyword.put(opts, key, value), extensions}
end
end)
end
defmacro __before_compile__(_env) do
quote unquote: false, generated: true do
@type t :: __MODULE__
require Ash.Dsl.Extension
Module.register_attribute(__MODULE__, :ash_is, persist: true)
Module.put_attribute(__MODULE__, :ash_is, @ash_is)
Ash.Dsl.Extension.set_state(@persist)
for {block, bindings} <- @ash_dsl_config[:eval] || [] do
Code.eval_quoted(block, bindings, __ENV__)
end
def ash_dsl_config do
@ash_dsl_config
end
@opts
|> @ash_parent.handle_before_compile()
|> Code.eval_quoted([], __ENV__)
end
end
def is?(module, type) do
Ash.Helpers.try_compile(module)
type in List.wrap(module.module_info(:attributes)[:ash_is])
rescue
_ ->
false
end
end
| 31.693182 | 117 | 0.606311 |
790a89da2f7aff5bb4055c3859d04f0abdc0fab1 | 668 | ex | Elixir | lib/coxir/adapters/limiter/helper.ex | satom99/coxir | 75bce94dcbe5dfa49e920d2f4ce0de224c315ce4 | [
"Apache-2.0"
] | 178 | 2018-04-08T17:11:56.000Z | 2022-03-25T15:36:41.000Z | lib/coxir/adapters/limiter/helper.ex | satom99/coxir | 75bce94dcbe5dfa49e920d2f4ce0de224c315ce4 | [
"Apache-2.0"
] | 21 | 2018-04-30T21:33:59.000Z | 2019-09-03T17:25:26.000Z | lib/coxir/adapters/limiter/helper.ex | satom99/coxir | 75bce94dcbe5dfa49e920d2f4ce0de224c315ce4 | [
"Apache-2.0"
] | 25 | 2018-04-21T19:41:03.000Z | 2021-07-24T22:40:40.000Z | defmodule Coxir.Limiter.Helper do
@moduledoc """
Common helper functions for `Coxir.Limiter` implementations.
"""
alias Coxir.Limiter
@spec time_now() :: non_neg_integer
def time_now do
DateTime.to_unix(DateTime.utc_now(), :millisecond)
end
@spec offset_now(non_neg_integer) :: non_neg_integer
def offset_now(offset \\ 0) do
time_now() + offset + offset_noise()
end
@spec wait_hit(Limiter.bucket()) :: :ok
def wait_hit(bucket) do
with {:error, timeout} <- Limiter.hit(bucket) do
Process.sleep(timeout + offset_noise())
wait_hit(bucket)
end
end
defp offset_noise do
trunc(:rand.uniform() * 500)
end
end
| 23.034483 | 62 | 0.687126 |
790a8ff26ab682996f9b332607706feab2b50e01 | 1,787 | ex | Elixir | lib/co2_offset_web.ex | styx/co2_offset | ac4b2bce8142e2d33ea089322c8dade34839448b | [
"Apache-2.0"
] | 15 | 2018-12-26T10:31:16.000Z | 2020-12-01T09:27:01.000Z | lib/co2_offset_web.ex | styx/co2_offset | ac4b2bce8142e2d33ea089322c8dade34839448b | [
"Apache-2.0"
] | 267 | 2018-12-26T07:46:17.000Z | 2020-04-04T17:05:47.000Z | lib/co2_offset_web.ex | styx/co2_offset | ac4b2bce8142e2d33ea089322c8dade34839448b | [
"Apache-2.0"
] | 1 | 2019-07-12T13:53:25.000Z | 2019-07-12T13:53:25.000Z | defmodule Co2OffsetWeb 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 Co2OffsetWeb, :controller
use Co2OffsetWeb, :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: Co2OffsetWeb
import Plug.Conn
import Co2OffsetWeb.Gettext
alias Co2OffsetWeb.Router.Helpers, as: Routes
end
end
def view do
quote do
use Phoenix.View,
root: "lib/co2_offset_web/templates",
pattern: "**/*",
namespace: Co2OffsetWeb
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_flash: 1, get_flash: 2, view_module: 1]
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
import Co2OffsetWeb.ErrorHelpers
import Co2OffsetWeb.Gettext
import Phoenix.LiveView, only: [live_render: 2, live_render: 3]
alias Co2OffsetWeb.Router.Helpers, as: Routes
end
end
def router do
quote do
use Phoenix.Router
import Plug.Conn
import Phoenix.Controller
import Phoenix.LiveView.Router
end
end
def channel do
quote do
use Phoenix.Channel
import Co2OffsetWeb.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
| 24.479452 | 83 | 0.688864 |
790a9bbb2bff9e445ece8f113643ee1133f6ac1d | 564 | ex | Elixir | live_view_studio/lib/live_view_studio/stores/store.ex | herminiotorres/pragmaticstudio | 273647694519fd4149716abf190eb8d97102f488 | [
"MIT"
] | null | null | null | live_view_studio/lib/live_view_studio/stores/store.ex | herminiotorres/pragmaticstudio | 273647694519fd4149716abf190eb8d97102f488 | [
"MIT"
] | null | null | null | live_view_studio/lib/live_view_studio/stores/store.ex | herminiotorres/pragmaticstudio | 273647694519fd4149716abf190eb8d97102f488 | [
"MIT"
] | null | null | null | defmodule LiveViewStudio.Stores.Store do
use Ecto.Schema
import Ecto.Changeset
schema "stores" do
field :city, :string
field :hours, :string
field :name, :string
field :open, :boolean, default: false
field :phone_number, :string
field :street, :string
field :zip, :string
timestamps()
end
@doc false
def changeset(store, attrs) do
store
|> cast(attrs, [:name, :street, :phone_number, :city, :zip, :open, :hours])
|> validate_required([:name, :street, :phone_number, :city, :zip, :open, :hours])
end
end
| 23.5 | 85 | 0.652482 |
790aa47f7ab28bb070754f34caf46a567a4e3023 | 143 | ex | Elixir | lib/elixirgithub/get_repos_behaviour.ex | LuizFerK/ElixirGitHub | 7db1270e296c6f0a33b7a85e80753cc010ea50af | [
"MIT"
] | 1 | 2021-11-23T16:51:04.000Z | 2021-11-23T16:51:04.000Z | lib/elixirgithub/get_repos_behaviour.ex | LuizFerK/Repositoriex | 7db1270e296c6f0a33b7a85e80753cc010ea50af | [
"MIT"
] | null | null | null | lib/elixirgithub/get_repos_behaviour.ex | LuizFerK/Repositoriex | 7db1270e296c6f0a33b7a85e80753cc010ea50af | [
"MIT"
] | null | null | null | defmodule Elixirgithub.GetReposBehaviour do
alias Elixirgithub.Error
@callback call(String.t()) :: {:ok, map()} | {:error, Error.t()}
end
| 23.833333 | 66 | 0.699301 |
790aa88d252e8c0180760c8dafe72dbb3ef0355a | 887 | ex | Elixir | package/indy-10.2.0.3/fpc/debian/prerm.ex | RonaldoSurdi/Sistema-gerenciamento-websites-delphi | 8cc7eec2d05312dc41f514bbd5f828f9be9c579e | [
"MIT"
] | 1 | 2022-02-28T11:28:18.000Z | 2022-02-28T11:28:18.000Z | package/indy-10.2.0.3/fpc/debian/prerm.ex | RonaldoSurdi/Sistema-gerenciamento-websites-delphi | 8cc7eec2d05312dc41f514bbd5f828f9be9c579e | [
"MIT"
] | null | null | null | package/indy-10.2.0.3/fpc/debian/prerm.ex | RonaldoSurdi/Sistema-gerenciamento-websites-delphi | 8cc7eec2d05312dc41f514bbd5f828f9be9c579e | [
"MIT"
] | null | null | null | #! /bin/sh
# prerm script for indy-fpc
#
# see: dh_installdeb(1)
set -e
# summary of how this script can be called:
# * <prerm> `remove'
# * <old-prerm> `upgrade' <new-version>
# * <new-prerm> `failed-upgrade' <old-version>
# * <conflictor's-prerm> `remove' `in-favour' <package> <new-version>
# * <deconfigured's-prerm> `deconfigure' `in-favour'
# <package-being-installed> <version> `removing'
# <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package
case "$1" in
remove|upgrade|deconfigure)
;;
failed-upgrade)
;;
*)
echo "prerm called with unknown argument \`$1'" >&2
exit 1
;;
esac
# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.
#DEBHELPER#
exit 0
| 22.74359 | 76 | 0.61894 |
790ad33a933fae5f28b30c9ec24e614302077e44 | 69 | ex | Elixir | lib/otp_demo_web/views/user_settings_view.ex | moroz/phoenix-totp-demo | b07b1925a1116ecbade15cb37764e4aebf442b5b | [
"MIT"
] | null | null | null | lib/otp_demo_web/views/user_settings_view.ex | moroz/phoenix-totp-demo | b07b1925a1116ecbade15cb37764e4aebf442b5b | [
"MIT"
] | null | null | null | lib/otp_demo_web/views/user_settings_view.ex | moroz/phoenix-totp-demo | b07b1925a1116ecbade15cb37764e4aebf442b5b | [
"MIT"
] | null | null | null | defmodule OtpDemoWeb.UserSettingsView do
use OtpDemoWeb, :view
end
| 17.25 | 40 | 0.826087 |
790afcbecc6944f86ef82a1bff5a30abd0e85fd6 | 1,114 | exs | Elixir | test/expat_nat_test.exs | vic/expat | 7c095187afe99b2ef6c68bd42c40164eb48d067c | [
"Apache-2.0"
] | 184 | 2016-10-16T16:07:24.000Z | 2022-03-25T01:57:06.000Z | test/expat_nat_test.exs | vic/expat | 7c095187afe99b2ef6c68bd42c40164eb48d067c | [
"Apache-2.0"
] | 3 | 2017-01-12T18:27:39.000Z | 2018-03-13T09:46:13.000Z | test/expat_nat_test.exs | vic/expat | 7c095187afe99b2ef6c68bd42c40164eb48d067c | [
"Apache-2.0"
] | 6 | 2017-01-11T19:29:28.000Z | 2018-09-04T01:06:33.000Z | defmodule Expat.NatTest do
use ExUnit.Case
use Expat
@moduledoc ~S"""
Natural numbers.
The union pattern bellow is shorthand for:
defpat nat({:nat, x})
defpat zero(nat(0))
defpat succ(nat(nat() = n))
Note that both `zero` and `succ` are just using calling
`nat` with some other pattern. Thus `zero()` builds `{:nat, 0}` and
`succ` takes a single argument `n` which must itself be also a `nat()`
See also expat_union_test.exs
"""
defpat nat
| zero(0)
| succ(nat() = n)
test "zero is a nat" do
assert nat() = zero()
end
test "succ of zero is a nat" do
assert nat() = succ(zero())
end
test "succ takes only nats" do
assert_raise MatchError, ~r/no match of right hand side value: 99/, fn ->
succ(99)
end
end
test "zero is tagged tuple" do
assert {:nat, 0} = zero()
end
test "succ of zero is tagged tuple" do
assert {:nat, {:nat, 0}} = succ(zero())
end
def to_i(zero()), do: 0
def to_i(succ(n)), do: 1 + to_i(n)
test "convert a nat to int" do
assert 3 = zero() |> succ |> succ |> succ |> to_i
end
end
| 19.892857 | 77 | 0.606822 |
790b1da01a98b4d376ea04b00f0b4b0b9e880fb1 | 201 | ex | Elixir | web/views/event_view.ex | kexoth/nlb-pipeline | 77d2c79b58e03f0326608162e9cee768362e2076 | [
"MIT"
] | 6 | 2017-06-13T19:35:05.000Z | 2020-05-05T06:50:34.000Z | web/views/event_view.ex | kexoth/nlb-pipeline | 77d2c79b58e03f0326608162e9cee768362e2076 | [
"MIT"
] | null | null | null | web/views/event_view.ex | kexoth/nlb-pipeline | 77d2c79b58e03f0326608162e9cee768362e2076 | [
"MIT"
] | 1 | 2021-09-27T11:58:11.000Z | 2021-09-27T11:58:11.000Z | defmodule NlbPipeline.EventView do
use NlbPipeline.Web, :view
def guardian_name(guardian_id) do
guardian_id
|> String.split(".")
|> Enum.map(&String.capitalize/1)
|> Enum.join(" ")
end
end
| 18.272727 | 35 | 0.701493 |
790b442831699b3edec06b40196b041836bb2a2f | 17,532 | exs | Elixir | test/phoenix/test/conn_test.exs | bhicks/phoenix | 2c43d798c184f6085cd2765d6cb2b463c87edac7 | [
"MIT"
] | null | null | null | test/phoenix/test/conn_test.exs | bhicks/phoenix | 2c43d798c184f6085cd2765d6cb2b463c87edac7 | [
"MIT"
] | null | null | null | test/phoenix/test/conn_test.exs | bhicks/phoenix | 2c43d798c184f6085cd2765d6cb2b463c87edac7 | [
"MIT"
] | null | null | null | defmodule Phoenix.Test.ConnTest.CatchAll do
def init(opts), do: opts
def call(conn, :stat), do: conn.params["action"].(conn)
def call(conn, _opts), do: Plug.Conn.assign(conn, :catch_all, true)
end
alias Phoenix.Test.ConnTest.CatchAll
defmodule Phoenix.Test.ConnTest.RedirRouter do
use Phoenix.Router
get "/", CatchAll, :foo
get "/posts/:id", CatchAll, :some_action
end
defmodule Phoenix.Test.ConnTest.Router do
use Phoenix.Router
pipeline :browser do
plug :put_bypass, :browser
end
pipeline :api do
plug :put_bypass, :api
end
scope "/" do
pipe_through :browser
get "/stat", CatchAll, :stat, private: %{route: :stat}
forward "/", CatchAll
end
def put_bypass(conn, pipeline) do
bypassed = (conn.assigns[:bypassed] || []) ++ [pipeline]
Plug.Conn.assign(conn, :bypassed, bypassed)
end
end
defmodule Phoenix.Test.ConnTest do
use ExUnit.Case, async: true
use Phoenix.ConnTest
alias Phoenix.Test.ConnTest.{Router, RedirRouter}
@moduletag :capture_log
defmodule ConnError do
defexception [message: nil, plug_status: 500]
end
Application.put_env(:phoenix, Phoenix.Test.ConnTest.Endpoint, [])
defmodule Endpoint do
use Phoenix.Endpoint, otp_app: :phoenix
def init(opts), do: opts
def call(conn, :set), do: resp(conn, 200, "ok")
def call(conn, opts) do
put_in(super(conn, opts).private[:endpoint], opts)
|> Router.call(Router.init([]))
end
end
@endpoint Endpoint
setup_all do
Logger.disable(self())
Endpoint.start_link()
:ok
end
test "build_conn/0 returns a new connection" do
conn = build_conn()
assert conn.method == "GET"
assert conn.path_info == []
assert conn.private.plug_skip_csrf_protection
assert conn.private.phoenix_recycled
end
test "build_conn/2 returns a new connection" do
conn = build_conn(:post, "/hello")
assert conn.method == "POST"
assert conn.path_info == ["hello"]
assert conn.private.plug_skip_csrf_protection
assert conn.private.phoenix_recycled
end
test "dispatch/5 with path" do
conn = post build_conn(), "/hello", foo: "bar"
assert conn.method == "POST"
assert conn.path_info == ["hello"]
assert conn.params == %{"foo" => "bar"}
assert conn.private.endpoint == []
refute conn.private.phoenix_recycled
end
test "dispatch/5 with action" do
conn = post build_conn(), :hello, %{foo: "bar"}
assert conn.method == "POST"
assert conn.path_info == []
assert conn.params == %{"foo" => "bar"}
assert conn.private.endpoint == :hello
refute conn.private.phoenix_recycled
end
test "dispatch/5 with binary body" do
assert_raise ArgumentError, fn ->
post build_conn(), :hello, "foo=bar"
end
conn =
build_conn()
|> put_req_header("content-type", "application/json")
|> post(:hello, "[1, 2, 3]")
|> Plug.Parsers.call(Plug.Parsers.init(parsers: [:json], json_decoder: Phoenix.json_library()))
assert conn.method == "POST"
assert conn.path_info == []
assert conn.params == %{"_json" => [1, 2, 3]}
end
test "dispatch/5 with recycling" do
conn =
build_conn()
|> put_req_header("hello", "world")
|> post(:hello)
assert get_req_header(conn, "hello") == ["world"]
conn =
conn
|> put_req_header("hello", "skipped")
|> post(:hello)
assert get_req_header(conn, "hello") == []
conn =
conn
|> recycle()
|> put_req_header("hello", "world")
|> post(:hello)
assert get_req_header(conn, "hello") == ["world"]
end
test "dispatch/5 with :set state automatically sends" do
conn = get build_conn(), :set
assert conn.state == :sent
assert conn.status == 200
assert conn.resp_body == "ok"
refute conn.private.phoenix_recycled
end
describe "recycle/1" do
test "relevant request headers are persisted" do
conn =
build_conn()
|> get("/")
|> put_req_header("accept", "text/html")
|> put_req_header("accept-language", "ja")
|> put_req_header("authorization", "Bearer mytoken")
|> put_req_header("hello", "world")
conn = conn |> recycle()
assert get_req_header(conn, "accept") == ["text/html"]
assert get_req_header(conn, "accept-language") == ["ja"]
assert get_req_header(conn, "authorization") == ["Bearer mytoken"]
assert get_req_header(conn, "hello") == []
end
test "host is persisted" do
conn =
build_conn(:get, "http://localhost/", nil)
|> recycle()
assert conn.host == "localhost"
end
test "cookies are persisted" do
conn =
build_conn()
|> get("/")
|> put_req_cookie("req_cookie", "req_cookie")
|> put_req_cookie("del_cookie", "del_cookie")
|> put_req_cookie("over_cookie", "pre_cookie")
|> put_resp_cookie("over_cookie", "pos_cookie")
|> put_resp_cookie("resp_cookie", "resp_cookie")
|> delete_resp_cookie("del_cookie")
conn = conn |> recycle() |> fetch_cookies()
assert conn.cookies == %{"req_cookie" => "req_cookie",
"over_cookie" => "pos_cookie",
"resp_cookie" => "resp_cookie"}
end
test "peer data is persisted" do
peer_data = %{
address: {127, 0, 0, 1},
port: 111317,
ssl_cert: <<1, 2, 3, 4>>
}
conn =
build_conn()
|> Plug.Test.put_peer_data(peer_data)
conn = conn |> recycle()
assert Plug.Conn.get_peer_data(conn) == peer_data
end
end
describe "recycle/2" do
test "custom request headers are persisted" do
conn =
build_conn()
|> get("/")
|> put_req_header("accept", "text/html")
|> put_req_header("hello", "world")
|> put_req_header("foo", "bar")
conn = conn |> recycle(~w(hello accept))
assert get_req_header(conn, "accept") == ["text/html"]
assert get_req_header(conn, "hello") == ["world"]
assert get_req_header(conn, "foo") == []
end
end
test "ensure_recycled/1" do
conn =
build_conn()
|> put_req_header("hello", "world")
|> ensure_recycled()
assert get_req_header(conn, "hello") == ["world"]
conn =
put_in(conn.private.phoenix_recycled, false)
|> ensure_recycled()
assert get_req_header(conn, "hello") == []
end
test "put_req_header/3 and delete_req_header/3" do
conn = build_conn(:get, "/")
assert get_req_header(conn, "foo") == []
conn = put_req_header(conn, "foo", "bar")
assert get_req_header(conn, "foo") == ["bar"]
conn = put_req_header(conn, "foo", "baz")
assert get_req_header(conn, "foo") == ["baz"]
conn = delete_req_header(conn, "foo")
assert get_req_header(conn, "foo") == []
end
test "put_req_cookie/3 and delete_req_cookie/2" do
conn = build_conn(:get, "/")
assert get_req_header(conn, "cookie") == []
conn = conn |> put_req_cookie("foo", "bar")
assert get_req_header(conn, "cookie") == ["foo=bar"]
conn = conn |> delete_req_cookie("foo")
assert get_req_header(conn, "cookie") == []
end
test "response/2" do
conn = build_conn(:get, "/")
assert conn |> resp(200, "ok") |> response(200) == "ok"
assert conn |> send_resp(200, "ok") |> response(200) == "ok"
assert conn |> send_resp(200, "ok") |> response(:ok) == "ok"
assert_raise RuntimeError,
~r"expected connection to have a response but no response was set/sent", fn ->
build_conn(:get, "/") |> response(200)
end
assert_raise RuntimeError,
"expected response with status 200, got: 404, with body:\n\"oops\"", fn ->
build_conn(:get, "/") |> resp(404, "oops") |> response(200)
end
assert_raise RuntimeError,
"expected response with status 200, got: 404, with body:\n<<192>>", fn ->
build_conn(:get, "/") |> resp(404, <<192>>) |> response(200)
end
end
test "html_response/2" do
assert build_conn(:get, "/") |> put_resp_content_type("text/html")
|> resp(200, "ok") |> html_response(:ok) == "ok"
assert_raise RuntimeError,
"no content-type was set, expected a html response", fn ->
build_conn(:get, "/") |> resp(200, "ok") |> html_response(200)
end
end
test "json_response/2" do
assert build_conn(:get, "/") |> put_resp_content_type("application/json")
|> resp(200, "{}") |> json_response(:ok) == %{}
assert build_conn(:get, "/") |> put_resp_content_type("application/vnd.api+json")
|> resp(200, "{}") |> json_response(:ok) == %{}
assert build_conn(:get, "/") |> put_resp_content_type("application/vnd.collection+json")
|> resp(200, "{}") |> json_response(:ok) == %{}
assert build_conn(:get, "/") |> put_resp_content_type("application/vnd.hal+json")
|> resp(200, "{}") |> json_response(:ok) == %{}
assert build_conn(:get, "/") |> put_resp_content_type("application/ld+json")
|> resp(200, "{}") |> json_response(:ok) == %{}
assert_raise RuntimeError,
"no content-type was set, expected a json response", fn ->
build_conn(:get, "/") |> resp(200, "ok") |> json_response(200)
end
assert_raise Jason.DecodeError,
"unexpected byte at position 0: 0x6F ('o')", fn ->
build_conn(:get, "/") |> put_resp_content_type("application/json")
|> resp(200, "ok") |> json_response(200)
end
assert_raise Jason.DecodeError, ~r/unexpected end of input at position 0/, fn ->
build_conn(:get, "/")
|> put_resp_content_type("application/json")
|> resp(200, "")
|> json_response(200)
end
assert_raise RuntimeError, ~s(expected response with status 200, got: 400, with body:\n) <> inspect(~s({"error": "oh oh"})), fn ->
build_conn(:get, "/")
|> put_resp_content_type("application/json")
|> resp(400, ~s({"error": "oh oh"}))
|> json_response(200)
end
end
test "text_response/2" do
assert build_conn(:get, "/") |> put_resp_content_type("text/plain")
|> resp(200, "ok") |> text_response(:ok) == "ok"
assert_raise RuntimeError,
"no content-type was set, expected a text response", fn ->
build_conn(:get, "/") |> resp(200, "ok") |> text_response(200)
end
end
test "response_content_type/2" do
conn = build_conn(:get, "/")
assert put_resp_content_type(conn, "text/html") |> response_content_type(:html) ==
"text/html; charset=utf-8"
assert put_resp_content_type(conn, "text/plain") |> response_content_type(:text) ==
"text/plain; charset=utf-8"
assert put_resp_content_type(conn, "application/json") |> response_content_type(:json) ==
"application/json; charset=utf-8"
assert_raise RuntimeError,
"no content-type was set, expected a html response", fn ->
conn |> response_content_type(:html)
end
assert_raise RuntimeError,
"expected content-type for html, got: \"text/plain; charset=utf-8\"", fn ->
put_resp_content_type(conn, "text/plain") |> response_content_type(:html)
end
end
test "redirected_to/1" do
conn =
build_conn(:get, "/")
|> put_resp_header("location", "new location")
|> send_resp(302, "foo")
assert redirected_to(conn) == "new location"
end
test "redirected_to/2" do
Enum.each 300..308, fn(status) ->
conn =
build_conn(:get, "/")
|> put_resp_header("location", "new location")
|> send_resp(status, "foo")
assert redirected_to(conn, status) == "new location"
end
end
test "redirected_to/2 with status atom" do
conn =
build_conn(:get, "/")
|> put_resp_header("location", "new location")
|> send_resp(301, "foo")
assert redirected_to(conn, :moved_permanently) == "new location"
end
test "redirected_to/2 without header" do
assert_raise RuntimeError,
"no location header was set on redirected_to", fn ->
assert build_conn(:get, "/")
|> send_resp(302, "ok")
|> redirected_to()
end
end
test "redirected_to/2 without redirection" do
assert_raise RuntimeError,
"expected redirection with status 302, got: 200", fn ->
build_conn(:get, "/")
|> put_resp_header("location", "new location")
|> send_resp(200, "ok")
|> redirected_to()
end
end
test "redirected_to/2 without response" do
assert_raise RuntimeError,
~r"expected connection to have redirected but no response was set/sent", fn ->
build_conn(:get, "/")
|> redirected_to()
end
end
describe "redirected_params/1" do
test "with matching route" do
conn =
build_conn(:get, "/")
|> RedirRouter.call(RedirRouter.init([]))
|> put_resp_header("location", "/posts/123")
|> send_resp(302, "foo")
assert redirected_params(conn) == %{id: "123"}
end
test "raises Phoenix.Router.NoRouteError for unmatched location" do
conn =
build_conn(:get, "/")
|> RedirRouter.call(RedirRouter.init([]))
|> put_resp_header("location", "/unmatched")
|> send_resp(302, "foo")
assert_raise Phoenix.Router.NoRouteError, fn ->
redirected_params(conn)
end
end
test "without redirection" do
assert_raise RuntimeError,
"expected redirection with status 302, got: 200", fn ->
build_conn(:get, "/")
|> RedirRouter.call(RedirRouter.init([]))
|> put_resp_header("location", "new location")
|> send_resp(200, "ok")
|> redirected_params()
end
end
end
test "bypass_through/3 bypasses route match and invokes pipeline" do
conn = get(build_conn(), "/")
assert conn.assigns[:catch_all]
conn =
build_conn()
|> bypass_through(Router, :browser)
|> get("/stat")
assert conn.assigns[:bypassed] == [:browser]
assert conn.private[:route] == :stat
refute conn.assigns[:catch_all]
conn =
build_conn()
|> bypass_through(Router, [:api])
|> get("/stat")
assert conn.assigns[:bypassed] == [:api]
assert conn.private[:route] == :stat
refute conn.assigns[:catch_all]
conn =
build_conn()
|> bypass_through(Router, [:browser, :api])
|> get("/stat")
assert conn.assigns[:bypassed] == [:browser, :api]
assert conn.private[:route] == :stat
refute conn.assigns[:catch_all]
end
test "bypass_through/3 with empty pipeline" do
conn =
build_conn()
|> bypass_through(Router, [])
|> get("/stat")
refute conn.assigns[:bypassed]
assert conn.private[:route] == :stat
refute conn.assigns[:catch_all]
end
test "bypass_through/2 with route pipeline" do
conn =
build_conn()
|> bypass_through(Router)
|> get("/stat")
assert conn.assigns[:bypassed] == [:browser]
assert conn.private[:route] == :stat
refute conn.assigns[:catch_all]
end
test "bypass_through/1 without router" do
conn =
build_conn()
|> bypass_through()
|> get("/stat")
refute conn.assigns[:bypassed]
assert conn.private[:route] == :stat
refute conn.assigns[:catch_all]
end
test "assert_error_sent/2 with expected error response" do
response = assert_error_sent :not_found, fn ->
get(build_conn(), "/stat", action: fn _ -> raise ConnError, plug_status: 404 end)
end
assert {404, [_h | _t], "404.html from Phoenix.ErrorView"} = response
response = assert_error_sent 400, fn ->
get(build_conn(), "/stat", action: fn _ -> raise ConnError, plug_status: 400 end)
end
assert {400, [_h | _t], "400.html from Phoenix.ErrorView"} = response
end
test "assert_error_sent/2 with status mismatch assertion" do
assert_raise ExUnit.AssertionError, ~r/expected error to be sent as 400 status, but got 500 from.*RuntimeError/s, fn ->
assert_error_sent 400, fn ->
get(build_conn(), "/stat", action: fn _conn -> raise RuntimeError end)
end
end
end
test "assert_error_sent/2 with no error" do
assert_raise ExUnit.AssertionError, ~r/expected error to be sent as 404 status, but no error happened/, fn ->
assert_error_sent 404, fn -> get(build_conn(), "/") end
end
end
test "assert_error_sent/2 with error but no response" do
assert_raise ExUnit.AssertionError, ~r/expected error to be sent as 404 status, but got an error with no response from.*RuntimeError/s, fn ->
assert_error_sent 404, fn -> raise "oops" end
end
end
test "assert_error_sent/2 with response but no error" do
assert_raise ExUnit.AssertionError, ~r/expected error to be sent as 400 status, but response sent 400 without error/, fn ->
assert_error_sent :bad_request, fn ->
get(build_conn(), "/stat", action: fn conn -> Plug.Conn.send_resp(conn, 400, "") end)
end
end
end
for method <- [:get, :post, :put, :delete] do
@method method
test "#{method} helper raises ArgumentError for mismatched conn" do
assert_raise ArgumentError, ~r/expected first argument to #{@method} to be/, fn ->
unquote(@method)("/foo/bar", %{baz: "baz"})
end
end
end
end
| 30.811951 | 145 | 0.609799 |
790b68c7bb1bc3f442a2713dd8b2c18ea84252bc | 267 | ex | Elixir | lib/ex_phone_number/constants/validation_results.ex | balena/ex_phone_number | 93a53efa03fcb821fdaacb261384b84b172428f9 | [
"MIT"
] | 3 | 2018-07-21T10:44:45.000Z | 2021-05-28T20:43:07.000Z | lib/ex_phone_number/constants/validation_results.ex | balena/ex_phone_number | 93a53efa03fcb821fdaacb261384b84b172428f9 | [
"MIT"
] | 2 | 2021-03-09T10:05:00.000Z | 2022-02-14T11:00:18.000Z | lib/ex_phone_number/constants/validation_results.ex | balena/ex_phone_number | 93a53efa03fcb821fdaacb261384b84b172428f9 | [
"MIT"
] | 1 | 2021-12-14T04:31:40.000Z | 2021-12-14T04:31:40.000Z | defmodule ExPhoneNumber.Constants.ValidationResults do
def is_possible(), do: :is_possible
def invalid_country_code(), do: :invalid_country_code
def too_short(), do: :too_short
def invalid_length(), do: :invalid_length
def too_long(), do: :too_long
end
| 22.25 | 55 | 0.756554 |
790b6f62d8ad045cd02af1511023ac35be8adefd | 2,431 | exs | Elixir | tests/lambda2.exs | JHU-PL-Lab/representation-types | 8805849eaa793692aada84c2c49fa227ed8c6387 | [
"CC-BY-4.0"
] | null | null | null | tests/lambda2.exs | JHU-PL-Lab/representation-types | 8805849eaa793692aada84c2c49fa227ed8c6387 | [
"CC-BY-4.0"
] | null | null | null | tests/lambda2.exs | JHU-PL-Lab/representation-types | 8805849eaa793692aada84c2c49fa227ed8c6387 | [
"CC-BY-4.0"
] | null | null | null |
defmodule Lambda2 do
defmodule Var do
defstruct [:id]
end
defmodule Lam do
defstruct [:id, :body]
end
defmodule Apl do
defstruct [:lhs, :rhs]
end
def var(id), do: %Var{id: id}
def lam(id, body), do: %Lam{id: id, body: body}
def apl(lhs, rhs), do: %Apl{lhs: lhs, rhs: rhs}
defprotocol Term do
def subst(term, var, val)
def eval(term)
def apply(term, arg)
end
defimpl Term, for: Var do
def subst(%Var{id: id}, id, val) do
val
end
def subst(term, _, _) do
term
end
def eval(_term) do
raise("open expression")
end
def apply(_term, _arg) do
raise("open expression")
end
end
defimpl Term, for: Lam do
def subst(term, var, val) do
%Lam{id: id, body: body} = term
if id == var do
term
else
%Lam{id: id, body: Term.subst(body, var, val)}
end
end
def eval(term) do
term
end
def apply(%Lam{id: id, body: body}, arg) do
Term.eval(Term.subst(body, id, arg))
end
end
defimpl Term, for: Apl do
def subst(term, var, val) do
%Apl{
lhs: Term.subst(term.lhs, var, val),
rhs: Term.subst(term.rhs, var, val)
}
end
def eval(term) do
lhs = Term.eval(term.lhs)
rhs = Term.eval(term.rhs)
Term.apply(lhs, rhs)
end
def apply(_term, _arg) do
raise("Cannot apply an Apl.")
end
end
def succ, do: lam(1, lam(2, lam(3,
apl(var(2), apl( apl(var(1), var(2)), var(3) ))
)))
def add, do: lam(1, lam(2,
apl( apl(var(1), succ() ), var(2) )
))
def mul, do: lam(1, lam(2, lam(3,
apl( var(1), apl(var(2), var(3)) )
)))
def pred, do: lam(1, lam(2, lam(3,
apl(
apl(
apl( var(1), lam(4, lam(5, apl(var(5), apl(var(4), var(2))))) ),
lam(6, var(3))
),
lam(6, var(6))
)
)))
def sub, do: lam(1, lam(2,
apl( apl(var(2), pred()), var(1) )
))
def church(0), do: lam(0, lam(1, var(1)))
def church(n) do
apl(succ(), church(n - 1))
end
def identity, do:
lam(0, apl( apl(var(0), succ()), church(0) ))
def get_input() do
IO.binread(:line)
|> String.trim()
|> String.to_integer
end
def main() do
n = get_input()
one = apl( apl(sub(), church(n)), church(n - 1) )
IO.puts(
inspect( Term.eval(apl(identity(), one)) )
)
end
end
Lambda2.main()
| 17.489209 | 76 | 0.523241 |
790bcc5601ced0ca3360540585db714ba0de322b | 38 | exs | Elixir | time_tracker_backend/.iex.exs | knewter/time-tracker | 1f58031112a24c26a1a54ac33105b4430a04e954 | [
"MIT"
] | 382 | 2016-08-18T07:34:27.000Z | 2021-02-25T20:46:34.000Z | time_tracker_backend/.iex.exs | knewter/time-tracker | 1f58031112a24c26a1a54ac33105b4430a04e954 | [
"MIT"
] | 1 | 2017-09-30T00:01:26.000Z | 2017-09-30T00:01:26.000Z | time_tracker_backend/.iex.exs | knewter/time-tracker | 1f58031112a24c26a1a54ac33105b4430a04e954 | [
"MIT"
] | 45 | 2016-08-30T07:34:04.000Z | 2020-01-27T11:39:26.000Z | alias TimeTrackerBackend.{Repo, User}
| 19 | 37 | 0.815789 |
790be345df9eb06a47156b82f22eee701b5784f8 | 111 | exs | Elixir | config/config.exs | frostu8/steve | 9018a3142bf4e51efc8e4dd0b307406a1075b3c8 | [
"Unlicense"
] | null | null | null | config/config.exs | frostu8/steve | 9018a3142bf4e51efc8e4dd0b307406a1075b3c8 | [
"Unlicense"
] | null | null | null | config/config.exs | frostu8/steve | 9018a3142bf4e51efc8e4dd0b307406a1075b3c8 | [
"Unlicense"
] | null | null | null | import Config
config :logger,
level: :info
config :nostrum,
num_shards: :auto
import_config "token.exs"
| 11.1 | 25 | 0.72973 |
790c0df4c5d2785c4941179ebe70cfd95e6b7398 | 355 | ex | Elixir | server/lib/tic_tac_toe_web/utils/json.ex | kasvith/tic-tac-toe | 7fcd5a7fe6052d8a4de3adf569c52c41e6c019a2 | [
"MIT"
] | 7 | 2021-01-31T20:47:02.000Z | 2022-01-05T16:02:12.000Z | server/lib/tic_tac_toe_web/utils/json.ex | kasvith/tic-tac-toe | 7fcd5a7fe6052d8a4de3adf569c52c41e6c019a2 | [
"MIT"
] | 2 | 2017-08-25T10:15:14.000Z | 2021-05-17T06:19:02.000Z | server/lib/tic_tac_toe_web/utils/json.ex | kasvith/tic-tac-toe | 7fcd5a7fe6052d8a4de3adf569c52c41e6c019a2 | [
"MIT"
] | 2 | 2021-03-26T09:18:07.000Z | 2021-05-16T22:29:50.000Z | defmodule Utils.Json do
def json_encode!(data, opts \\ []) do
Jason.encode!(data, opts)
end
def json_decode(input, opts \\ []) do
Jason.decode(input, opts)
end
defmacro wrap_data(data) do
quote do
%{data: unquote(data)}
end
end
defmacro wrap_error(err) do
quote do
%{error: unquote(err)}
end
end
end
| 16.136364 | 39 | 0.616901 |
790c1639e65c38b06f02f1e4b43a0d5fe29fc67c | 4,425 | ex | Elixir | apps/feedex_core/lib/feedex_core/ctx/news.ex | andyl/ragged | 2baab0849e2dfc068652ecb2fe88a7c6fe5437d0 | [
"MIT"
] | null | null | null | apps/feedex_core/lib/feedex_core/ctx/news.ex | andyl/ragged | 2baab0849e2dfc068652ecb2fe88a7c6fe5437d0 | [
"MIT"
] | 10 | 2021-02-08T00:01:41.000Z | 2021-05-27T12:54:28.000Z | apps/feedex_core/lib/feedex_core/ctx/news.ex | andyl/ragged | 2baab0849e2dfc068652ecb2fe88a7c6fe5437d0 | [
"MIT"
] | null | null | null | defmodule FeedexCore.Ctx.News do
@moduledoc """
Affordance for News Resources
"""
alias FeedexCore.Ctx.News.{Feed, Post}
alias FeedexCore.Ctx.Account.{ReadLog, Register, Folder}
alias FeedexCore.Repo
import Ecto.Query
# ----- feeds -----
def feed_get(id) do
Repo.get(Feed, id)
end
# ----- post query -----
def get_post(id) do
Repo.get(Post, id)
end
# ----- unread aggregates -----
def unread_aggregate_count_for(userid, type: "fld") do
from([pst, log, fee, reg, fld] in unread_aggregate_count_qry(userid),
group_by: fld.id,
select: %{fld.id => count(pst.id)}
)
|> Repo.all()
|> Enum.reduce(%{}, fn(el, acc) -> Map.merge(acc, el) end)
end
def unread_aggregate_count_for(userid, type: "reg") do
from([pst, log, fee, reg, fld] in unread_aggregate_count_qry(userid),
group_by: reg.id,
select: %{reg.id => count(pst.id)}
)
|> Repo.all()
|> Enum.reduce(%{}, fn(el, acc) -> Map.merge(acc, el) end)
end
def unread_aggregate_count_qry(userid) do
# from(pst in Post,
q1 = from(p in Post, distinct: :title, order_by: [desc: :id])
from(pst in subquery(q1),
left_join: log in ReadLog, on: pst.id == log.post_id,
join: fee in Feed , on: pst.feed_id == fee.id,
join: reg in Register , on: reg.feed_id == fee.id,
join: fld in Folder , on: reg.folder_id == fld.id,
where: fld.user_id == ^userid,
where: not fragment("? ~* ?", pst.title, fld.stopwords),
or_where: is_nil(fld.stopwords),
where: is_nil(log.id)
)
end
# ----- unread_count -----
def unread_count(uistate) do
case {uistate.reg_id, uistate.fld_id} do
{nil, nil} -> unread_count_for(uistate.usr_id)
{regid, nil} -> unread_count_for(uistate.usr_id, reg_id: regid)
{nil, fldid} -> unread_count_for(uistate.usr_id, fld_id: fldid)
end
end
# ----- unread_count_for -----
def unread_count_for(userid) do
unread_count_qry(userid) |> Repo.one()
end
def unread_count_for(userid, fld_id: fldid) do
from([pst, log, fee, reg, fld] in unread_count_qry(userid),
where: fld.id == ^fldid
) |> Repo.one()
end
def unread_count_for(userid, reg_id: regid) do
from([pst, log, fee, reg, fld] in unread_count_qry(userid),
where: reg.id == ^regid
) |> Repo.one()
end
defp unread_count_qry(userid) do
q1 = from(p in Post, distinct: :title, order_by: [desc: :id])
from(pst in subquery(q1),
left_join: log in ReadLog, on: pst.id == log.post_id,
join: fee in Feed , on: pst.feed_id == fee.id,
join: reg in Register , on: reg.feed_id == fee.id,
join: fld in Folder , on: reg.folder_id == fld.id,
where: fld.user_id == ^userid,
where: not fragment("? ~* ?", pst.title, fld.stopwords),
or_where: is_nil(fld.stopwords),
where: is_nil(log.id),
select: count(pst.id)
)
end
# ----- posts_for -----
def posts_for(userid) do
posts_qry(userid) |> Repo.all()
end
def posts_for(usrid, fld_id: fldid) do
from([pst, log, fee, reg, fld] in posts_qry(usrid),
where: fld.id == ^fldid
) |> Repo.all()
end
def posts_for(usrid, reg_id: regid) do
from([pst, log, fee, reg, fld] in posts_qry(usrid),
where: reg.id == ^regid
) |> Repo.all()
end
defp posts_qry(user_id) do
# use subquery to eliminate duplicate titles (forum posts) only show the latest
# from(pst in Post,
q1 = from(p in Post, distinct: :title, order_by: [desc: :id])
from(pst in subquery(q1),
left_join: log in ReadLog, on: pst.id == log.post_id,
join: fee in Feed , on: pst.feed_id == fee.id,
join: reg in Register , on: reg.feed_id == fee.id,
join: fld in Folder , on: reg.folder_id == fld.id,
where: fld.user_id == ^user_id,
where: not fragment("? ~* ?", pst.title, fld.stopwords),
or_where: is_nil(fld.stopwords),
order_by: [desc: pst.id],
limit: 100,
select: %{
id: pst.id,
exid: pst.exid,
title: pst.title,
body: pst.body,
author: pst.author,
link: pst.link,
fld_name: fld.name,
fld_id: fld.id,
reg_name: reg.name,
reg_id: reg.id,
updated_at: pst.updated_at,
read_log: log.id
}
)
end
end
| 29.111842 | 83 | 0.587119 |
790c5a0b9f3db9499fd465280127a2453eb67906 | 65 | exs | Elixir | priv/mock/cms_video_seeds.exs | DavidAlphaFox/coderplanets_server | 3fd47bf3bba6cc04c9a34698201a60ad2f3e8254 | [
"Apache-2.0"
] | 1 | 2019-05-07T15:03:54.000Z | 2019-05-07T15:03:54.000Z | priv/mock/cms_video_seeds.exs | DavidAlphaFox/coderplanets_server | 3fd47bf3bba6cc04c9a34698201a60ad2f3e8254 | [
"Apache-2.0"
] | null | null | null | priv/mock/cms_video_seeds.exs | DavidAlphaFox/coderplanets_server | 3fd47bf3bba6cc04c9a34698201a60ad2f3e8254 | [
"Apache-2.0"
] | null | null | null | import MastaniServer.Support.Factory
db_insert_multi(:video, 3)
| 16.25 | 36 | 0.830769 |
790c987993fdd61dd208b8725b3c20d9d16a7563 | 271 | exs | Elixir | priv/repo/migrations/20180916124042_create_categories.exs | richeterre/jumubase-phoenix | 7584f890af117d496971b5284bf9de798e22266f | [
"MIT"
] | 2 | 2019-01-20T07:03:30.000Z | 2019-04-11T10:20:14.000Z | priv/repo/migrations/20180916124042_create_categories.exs | richeterre/jumubase-phoenix | 7584f890af117d496971b5284bf9de798e22266f | [
"MIT"
] | 6 | 2018-09-20T05:52:14.000Z | 2019-04-23T19:27:39.000Z | priv/repo/migrations/20180916124042_create_categories.exs | richeterre/jumubase-phoenix | 7584f890af117d496971b5284bf9de798e22266f | [
"MIT"
] | null | null | null | defmodule Jumubase.Repo.Migrations.CreateCategories do
use Ecto.Migration
def change do
create table(:categories) do
add :name, :string
add :short_name, :string
add :genre, :string
add :type, :string
timestamps()
end
end
end
| 18.066667 | 54 | 0.653137 |
790cc501b0fb64212a36fa2146c1623039fec4bc | 1,517 | exs | Elixir | mix.exs | jrbart/ecto_shorts | bfcd5674d109bcea68e35ea6977c306b3fae8566 | [
"MIT"
] | 1 | 2022-03-25T16:51:20.000Z | 2022-03-25T16:51:20.000Z | mix.exs | jrbart/ecto_shorts | bfcd5674d109bcea68e35ea6977c306b3fae8566 | [
"MIT"
] | null | null | null | mix.exs | jrbart/ecto_shorts | bfcd5674d109bcea68e35ea6977c306b3fae8566 | [
"MIT"
] | null | null | null | defmodule EctoShorts.MixProject do
use Mix.Project
def project do
[
app: :ecto_shorts,
version: "1.1.4",
elixir: "~> 1.7",
start_permanent: Mix.env() == :prod,
deps: deps(),
description: "Helper tools for making ecto interactions more pleasant and shorter",
docs: docs(),
package: package()
]
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
[
{:ecto_sql, "~> 3.3"},
{:ex_doc, ">= 0.0.0", only: :dev}
]
end
defp package do
[
maintainers: ["Mika Kalathil"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/MikaAK/ecto_shorts"},
files: ~w(mix.exs README.md CHANGELOG.md lib config)
]
end
defp docs do
[
main: "EctoShorts",
source_url: "https://github.com/MikaAK/ecto_shorts",
groups_for_modules: [
"Main Modules": [
EctoShorts.Actions,
EctoShorts.CommonChanges
],
"Support Modules": [
EctoShorts.CommonFilters,
EctoShorts.SchemaHelpers
],
"Misc Modules": [
EctoShorts.Actions.Error,
EctoShorts.Repo
],
"Query Builder Modules": [
EctoShorts.QueryBuilder,
EctoShorts.QueryBuilder.Schema,
EctoShorts.QueryBuilder.Common
]
]
]
end
end
| 21.671429 | 89 | 0.563612 |
790d1469aca74efe3db2020a7cb32677e59cdcd4 | 1,849 | ex | Elixir | lib/ex_oneroster/web/views/org_view.ex | jrissler/ex_oneroster | cec492117bffc14aec91e2448643682ceeb449e9 | [
"Apache-2.0"
] | 3 | 2018-09-06T11:15:07.000Z | 2021-12-27T15:36:51.000Z | lib/ex_oneroster/web/views/org_view.ex | jrissler/ex_oneroster | cec492117bffc14aec91e2448643682ceeb449e9 | [
"Apache-2.0"
] | null | null | null | lib/ex_oneroster/web/views/org_view.ex | jrissler/ex_oneroster | cec492117bffc14aec91e2448643682ceeb449e9 | [
"Apache-2.0"
] | null | null | null | defmodule ExOneroster.Web.OrgView do
use ExOneroster.Web, :view
alias ExOneroster.Web.OrgView
def render("index.json", %{orgs: orgs}) do
%{org: render_many(orgs, OrgView, "org.json")}
end
def render("show.json", %{org: org}) do
%{org: render_one(org, OrgView, "org.json")}
end
def render("org.json", %{org: org}) do
parent = if org.parent, do: %{href: org_url(ExOneroster.Web.Endpoint, :show, org.parent.id), sourcedId: org.parent.sourcedId, type: org.parent.type}, else: %{}
children = org.children |> Enum.reduce([], fn(child, list) -> [%{href: org_url(ExOneroster.Web.Endpoint, :show, child.id), sourcedId: child.sourcedId, type: child.type} | list] end) |> Enum.reverse
%{
id: org.id,
sourcedId: org.sourcedId,
status: org.status,
dateLastModified: org.dateLastModified,
metadata: org.metadata,
name: org.name,
type: org.type,
identifier: org.identifier,
parent: parent,
children: children
}
end
end
# 1.1 spec response
# {
# "org": {
# "sourcedId": "<sourcedId of this org>",
# "status": "active | tobedeleted",
# "dateLastModified": "<date this ORG was last modified>",
# "name": "<name of the org>",
# "type": "school | local | state | national",
# "identifier": "<human readable identifier for this organization>",
# "parent": {
# "href": "<href to the parent org>",
# "sourcedId": "<sourcedId of the parent org>",
# "type": "org"
# },
# "children": [
# {
# "href": "<href of the first child org>",
# "sourcedId": "<sourcedId of the first child org>",
# "type": "org"
# },
# {
# "href": "<href of the n'th child org>",
# "sourcedId": "<sourcedId of the n'th child org>",
# "type": "org"
# }
# ]
# }
# }
| 31.338983 | 201 | 0.577069 |
790d1c5bc63a249d46c9073945d4587aaaf7c447 | 1,195 | ex | Elixir | apps/grapevine/lib/web/controllers/manage/client_controller.ex | oestrich/grapevine | 7fb745a3a6e4eb68bd761baa190b2df32fa1f73d | [
"MIT"
] | 107 | 2018-10-05T18:20:32.000Z | 2022-02-28T04:02:50.000Z | apps/grapevine/lib/web/controllers/manage/client_controller.ex | oestrich/grapevine | 7fb745a3a6e4eb68bd761baa190b2df32fa1f73d | [
"MIT"
] | 33 | 2018-10-05T14:11:18.000Z | 2022-02-10T22:19:18.000Z | apps/grapevine/lib/web/controllers/manage/client_controller.ex | oestrich/grapevine | 7fb745a3a6e4eb68bd761baa190b2df32fa1f73d | [
"MIT"
] | 18 | 2019-02-03T03:08:20.000Z | 2021-12-28T04:29:36.000Z | defmodule Web.Manage.ClientController do
use Web, :controller
alias GrapevineData.Games
alias GrapevineData.GameSettings
alias GrapevineData.Gauges
def show(conn, %{"game_id" => id}) do
%{current_user: user} = conn.assigns
with {:ok, game} <- Games.get(user, id) do
conn
|> assign(:game, game)
|> assign(:gauges, Gauges.for(game))
|> assign(:changeset, GameSettings.edit_client_settings(game))
|> render("show.html")
end
end
def update(conn, %{"game_id" => id, "client_settings" => params}) do
%{current_user: user} = conn.assigns
{:ok, game} = Games.get(user, id)
case GameSettings.update_client_settings(game, params) do
{:ok, _client_settings} ->
conn
|> put_flash(:info, "Updated!")
|> redirect(to: manage_game_client_path(conn, :show, game.id))
{:error, :not_found} ->
conn
|> put_flash(:info, "Updated!")
|> redirect(to: page_path(conn, :index))
{:error, changeset} ->
conn
|> assign(:game, game)
|> assign(:gauges, Gauges.for(game))
|> assign(:changeset, changeset)
|> render("show.html")
end
end
end
| 27.159091 | 70 | 0.601674 |
790d2315fbb28f6c82a14e2500bd345d7e44fb90 | 668 | exs | Elixir | mix.exs | tallakt/comb | e6660924891d88d798494ab0c5adeefb29fae8b8 | [
"Apache-2.0"
] | 38 | 2016-02-24T09:19:23.000Z | 2022-02-15T14:33:35.000Z | mix.exs | tallakt/permutations | e6660924891d88d798494ab0c5adeefb29fae8b8 | [
"Apache-2.0"
] | 1 | 2018-01-07T11:42:07.000Z | 2018-01-07T11:42:59.000Z | mix.exs | tallakt/permutations | e6660924891d88d798494ab0c5adeefb29fae8b8 | [
"Apache-2.0"
] | 10 | 2015-11-09T09:52:55.000Z | 2020-10-19T05:07:00.000Z | defmodule Comb.Mixfile do
use Mix.Project
def project do
[app: :comb,
version: "0.0.2",
elixir: "~> 1.0",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps()]
end
# Configuration for the OTP application
#
# Type `mix help compile.app` for more information
def application do
[applications: [:logger]]
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
[
]
end
end
| 19.647059 | 77 | 0.598802 |
790d3d99ee010876a763c7e8911afd2259a98106 | 750 | ex | Elixir | lib/cloak/types/encrypted_naive_date_time_field.ex | jdewar/cloak | d19bfbd06c53ce7b4f90e14ada3d134c5cb2f6b5 | [
"MIT"
] | null | null | null | lib/cloak/types/encrypted_naive_date_time_field.ex | jdewar/cloak | d19bfbd06c53ce7b4f90e14ada3d134c5cb2f6b5 | [
"MIT"
] | null | null | null | lib/cloak/types/encrypted_naive_date_time_field.ex | jdewar/cloak | d19bfbd06c53ce7b4f90e14ada3d134c5cb2f6b5 | [
"MIT"
] | null | null | null | defmodule Cloak.EncryptedNaiveDateTimeField do
@moduledoc """
An `Ecto.Type` to encrypt `NaiveDateTime` fields.
## Usage
You should create the field with the type `:binary`.
Values will be converted back to a `NaiveDateTime` on decryption.
schema "table" do
field :field_name, Cloak.EncryptedNaiveDateTimeField
end
"""
use Cloak.EncryptedField
def cast(value), do: Ecto.Type.cast(:naive_datetime, value)
def before_encrypt(value) do
case Ecto.Type.cast(:naive_datetime, value) do
{:ok, dt} -> to_string(dt)
_error -> :error
end
end
def after_decrypt(value) do
case NaiveDateTime.from_iso8601(value) do
{:ok, naive_dt} -> naive_dt
_error -> :error
end
end
end
| 22.727273 | 67 | 0.677333 |
790d4aff940a8e9fd3412d7983cc221a77448a4d | 185 | exs | Elixir | test/yaml_to_dict_test.exs | knewter/obelisk | 360425914d36c1c6094820ae035a4555a177ed00 | [
"MIT"
] | 1 | 2017-04-04T15:44:25.000Z | 2017-04-04T15:44:25.000Z | test/yaml_to_dict_test.exs | knewter/obelisk | 360425914d36c1c6094820ae035a4555a177ed00 | [
"MIT"
] | null | null | null | test/yaml_to_dict_test.exs | knewter/obelisk | 360425914d36c1c6094820ae035a4555a177ed00 | [
"MIT"
] | null | null | null | defmodule YamlToDictTest do
use ExUnit.Case
test "Can convert yaml to dict" do
assert %{a: "a", b: "b"} == Obelisk.YamlToDict.convert(%{}, [{'a', 'a'}, {'b', 'b'}])
end
end
| 20.555556 | 89 | 0.583784 |
790d57625a191d85002371936ac08bc6013bbc04 | 129 | exs | Elixir | test/custom_hooks/keyset_paginate_test.exs | dwarvesf/rummage_ecto | c05060ae3ad31e84d22adfac863ae35364603179 | [
"MIT"
] | null | null | null | test/custom_hooks/keyset_paginate_test.exs | dwarvesf/rummage_ecto | c05060ae3ad31e84d22adfac863ae35364603179 | [
"MIT"
] | null | null | null | test/custom_hooks/keyset_paginate_test.exs | dwarvesf/rummage_ecto | c05060ae3ad31e84d22adfac863ae35364603179 | [
"MIT"
] | null | null | null | defmodule Rummage.Ecto.CustomHooks.KeysetPaginateTest do
use ExUnit.Case
doctest Rummage.Ecto.CustomHooks.KeysetPaginate
end
| 25.8 | 56 | 0.852713 |
790d6b3b8bc64feb32897e1ce1684a0e80a38f7d | 3,897 | ex | Elixir | apps/snitch_core/lib/core/data/schema/taxanomy/taxon.ex | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 456 | 2018-09-20T02:40:59.000Z | 2022-03-07T08:53:48.000Z | apps/snitch_core/lib/core/data/schema/taxanomy/taxon.ex | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 273 | 2018-09-19T06:43:43.000Z | 2021-08-07T12:58:26.000Z | apps/snitch_core/lib/core/data/schema/taxanomy/taxon.ex | Acrecio/avia | 54d264fc179b5b5f17d174854bdca063e1d935e9 | [
"MIT"
] | 122 | 2018-09-26T16:32:46.000Z | 2022-03-13T11:44:19.000Z | defmodule Snitch.Data.Schema.Taxon do
@moduledoc false
use Snitch.Data.Schema
use AsNestedSet, scope: [:taxonomy_id]
import Ecto.Query
alias Snitch.Data.Schema.{Image, Taxon, Taxonomy, VariationTheme, TaxonImage}
alias Snitch.Domain.Taxonomy, as: TaxonomyDomain
@type t :: %__MODULE__{}
schema "snitch_taxons" do
field(:name, :string)
field(:lft, :integer)
field(:rgt, :integer)
field(:variation_theme_ids, {:array, :binary}, virtual: true)
field(:slug, :string)
field(:tenant, :string, virtual: true)
has_one(:taxon_image, TaxonImage, on_replace: :delete)
has_one(:image, through: [:taxon_image, :image])
many_to_many(
:variation_themes,
VariationTheme,
join_through: "snitch_taxon_themes",
on_replace: :delete
)
belongs_to(:taxonomy, Taxonomy)
belongs_to(:parent, Taxon)
timestamps()
end
@cast_fields ~w(name parent_id taxonomy_id lft rgt)
@update_fields ~w(name)
def changeset(taxon, params) do
taxon
|> cast(params, @cast_fields)
|> force_change(:name, taxon.name)
|> validate_required([:name])
|> cast_assoc(:taxon_image, with: &TaxonImage.changeset/2)
|> handle_slug
end
defp get_ancestors_slug_text(nil), do: ""
@doc """
This method returns the comma separated name of all the taxon above it till
level 1
Consider following taxonomy
Category
|-- Men
| |-- Shirt
| | |-- Full Sleeve
| | |-- Half Sleeve
| |-- T-Shirt
|-- Women
|-- Shirt
|-- T-Shirt
`Full Sleeve` Category under women it would return `Men Shirt`
"""
defp get_ancestors_slug_text(taxon_id) do
with %Taxon{} = taxon <- TaxonomyDomain.get_taxon(taxon_id),
{:ok, ancestors} <- TaxonomyDomain.get_ancestors(taxon_id) do
{_, ancestors_till_level_1} = List.pop_at(ancestors, 0)
# Here we exclude the root taxon as we don't include it in slug
taxons =
case TaxonomyDomain.is_root?(taxon) do
true -> ancestors_till_level_1
false -> ancestors_till_level_1 ++ [taxon]
end
Enum.reduce(taxons, "", fn taxon, acc ->
"#{acc} #{String.trim(taxon.name)}"
end)
end
end
defp handle_slug(%{changes: %{name: name}} = changeset) do
parent_id = changeset.data.parent_id || Map.get(changeset.changes, :parent_id, nil)
ancestors_slug_text = get_ancestors_slug_text(parent_id)
slug_text = "#{ancestors_slug_text} #{name}"
changeset
|> put_change(:slug, generate_slug(slug_text))
|> unique_constraint(:slug, message: "category with this name alreay exist")
end
def generate_slug(text), do: Slugger.slugify_downcase(text, ?_)
defp handle_slug(changeset), do: changeset
defp put_assoc_variation_theme(changeset, theme) when theme in [nil, ""] do
variation_theme_ids = Enum.map(changeset.data.variation_themes, & &1.id)
changeset
|> put_change(:variation_theme_ids, variation_theme_ids)
|> put_assoc(:variation_themes, Enum.map([], &change/1))
end
defp put_assoc_variation_theme(changeset, themes) do
themes = Repo.all(from(vt in VariationTheme, where: vt.id in ^themes))
put_assoc(changeset, :variation_themes, Enum.map(themes, &change/1))
end
def update_changeset(taxon, params) do
ids = get_variation_theme(params["variation_theme_ids"])
taxon
|> Repo.preload([:variation_themes, :taxon_image])
|> cast(params, @update_fields)
|> handle_slug
|> validate_required([:name])
|> cast_assoc(:taxon_image, with: &TaxonImage.changeset/2)
|> put_assoc_variation_theme(ids)
end
defp get_variation_theme(nil) do
nil
end
defp get_variation_theme("") do
""
end
defp get_variation_theme(variation_theme_ids) do
if is_binary(variation_theme_ids),
do: variation_theme_ids |> String.split(","),
else: variation_theme_ids
end
end
| 27.638298 | 87 | 0.677957 |
790d85169ca889cbd5d967fdba5a6bbaf1fb4dd0 | 885 | ex | Elixir | yaki_core/lib/yaki_core/files.ex | aaripurna/yaki | 42bd854d72799de748b2171badb1d047952973f1 | [
"MIT"
] | null | null | null | yaki_core/lib/yaki_core/files.ex | aaripurna/yaki | 42bd854d72799de748b2171badb1d047952973f1 | [
"MIT"
] | null | null | null | yaki_core/lib/yaki_core/files.ex | aaripurna/yaki | 42bd854d72799de748b2171badb1d047952973f1 | [
"MIT"
] | null | null | null | defmodule YakiCore.Variant do
defstruct [:name, :size]
@type t() :: %__MODULE__{
name: String.t(),
size: {height :: number(), width :: number()}
}
end
defmodule YakiCore.RawFile do
defstruct [:path, :filename, :content_type]
@type t() :: %__MODULE__{
path: String.t(),
filename: String.t(),
content_type: String.t()
}
end
defmodule YakiCore.FileVariant do
defstruct [:name, :filename, :content_type, :path, :options]
@type t() :: %__MODULE__{
name: String.t(),
filename: String.t(),
content_type: String.t(),
path: String.t(),
options: any()
}
end
defmodule YakiCore.FileOutputOne do
defstruct [:adapter, :variants]
@type t() :: %__MODULE__{
adapter: String.t(),
variants: list(YakiCore.FileVariant.t())
}
end
| 22.125 | 62 | 0.563842 |
790daa07ce5bcd7c62304f42618d88150721c2e0 | 15,175 | ex | Elixir | lib/cog/chat/adapter.ex | matusf/cog | 71708301c7dc570fb0d3498a50f47a70ef957788 | [
"Apache-2.0"
] | 1,003 | 2016-02-23T17:21:12.000Z | 2022-02-20T14:39:35.000Z | lib/cog/chat/adapter.ex | matusf/cog | 71708301c7dc570fb0d3498a50f47a70ef957788 | [
"Apache-2.0"
] | 906 | 2016-02-22T22:54:19.000Z | 2022-03-11T15:19:43.000Z | lib/cog/chat/adapter.ex | matusf/cog | 71708301c7dc570fb0d3498a50f47a70ef957788 | [
"Apache-2.0"
] | 95 | 2016-02-23T13:42:31.000Z | 2021-11-30T14:39:55.000Z | defmodule Cog.Chat.Adapter do
require Logger
use Carrier.Messaging.GenMqtt
alias Cog.Util.CacheSup
alias Cog.Util.Cache
alias Cog.Messages.ProviderRequest
alias Cog.Chat.Room
alias Cog.Chat.Message
alias Cog.Chat.User
@adapter_topic "bot/chat/adapter"
@incoming_topic "bot/chat/adapter/incoming"
@cache_name :cog_chat_adapter_cache
defstruct [:providers, :cache]
def start_link() do
GenMqtt.start_link(__MODULE__, [], name: __MODULE__)
end
def incoming_topic(), do: @incoming_topic
def mention_name(provider, handle) when is_binary(handle) do
GenMqtt.call(@adapter_topic , "mention_name", %{provider: provider, handle: handle}, :infinity)
end
def mention_name(conn, provider, handle) when is_binary(handle) do
GenMqtt.call(conn, @adapter_topic , "mention_name", %{provider: provider, handle: handle}, :infinity)
end
def display_name(provider) do
GenMqtt.call(@adapter_topic, "display_name", %{provider: provider}, :infinity)
end
def display_name(conn, provider) do
GenMqtt.call(conn, @adapter_topic, "display_name", %{provider: provider}, :infinity)
end
def lookup_user(provider, handle) when is_binary(handle) do
cache = get_cache
case cache[{provider, :user, handle}] do
nil ->
case GenMqtt.call(@adapter_topic, "lookup_user", %{provider: provider, handle: handle}, :infinity) do
{:ok, user} ->
User.from_map(user)
{:error, _}=error ->
error
end
{:ok, value} ->
User.from_map(value)
end
end
def lookup_user(conn, provider, handle) when is_binary(handle) do
cache = get_cache
case cache[{provider, :user, handle}] do
nil ->
case GenMqtt.call(conn, @adapter_topic, "lookup_user", %{provider: provider, handle: handle}, :infinity) do
{:ok, user} ->
User.from_map(user)
{:error, _}=error ->
error
end
{:ok, value} ->
User.from_map(value)
end
end
# Declaring like this so we fail quickly if lookup_room
# is called with something other than a keyword list.
def lookup_room(provider, name: name),
do: do_lookup_room(provider, name: name)
def lookup_room(provider, id: id),
do: do_lookup_room(provider, id: id)
# room_identifier should come in as a keyword list with
# either [id: id] or [name: name]
defp do_lookup_room(provider, room_identifier) do
args = Enum.into(room_identifier, %{provider: provider})
cache = get_cache
case cache[{provider, :room, room_identifier}] do
nil ->
case GenMqtt.call(@adapter_topic , "lookup_room", args, :infinity) do
{:ok, room} ->
Room.from_map(room)
{:error, _}=error ->
error
end
{:ok, value} ->
Room.from_map(value)
end
end
def list_joined_rooms(provider) do
case GenMqtt.call(@adapter_topic, "list_joined_rooms", %{provider: provider}, :infinity) do
nil ->
nil
{:ok, rooms} ->
{:ok, Enum.map(rooms, &Room.from_map!/1)}
end
end
def list_joined_rooms(conn, provider) do
case GenMqtt.call(conn, @adapter_topic, "list_joined_rooms", %{provider: provider}, :infinity) do
nil ->
nil
rooms ->
Enum.map(rooms, &Room.from_map/1)
end
end
def join(provider, room) when is_binary(room) do
GenMqtt.call(@adapter_topic, "join", %{provider: provider, room: room}, :infinity)
end
def join(conn, provider, room) when is_binary(room) do
GenMqtt.call(conn, @adapter_topic, "join", %{provider: provider, room: room}, :infinity)
end
def leave(provider, room) when is_binary(room) do
GenMqtt.call(@adapter_topic, "leave", %{provider: provider, room: room}, :infinity)
end
def leave(conn, provider, room) when is_binary(room) do
GenMqtt.call(conn, @adapter_topic, "leave", %{provider: provider, room: room}, :infinity)
end
def list_providers() do
GenMqtt.call(@adapter_topic, "list_providers", %{}, :infinity)
end
def list_providers(conn) do
GenMqtt.call(conn, @adapter_topic, "list_providers", %{}, :infinity)
end
def is_chat_provider?(name) do
{:ok, result} = GenMqtt.call(@adapter_topic, "is_chat_provider", %{name: name}, :infinity)
result
end
def is_chat_provider?(conn, name) do
{:ok, result} = GenMqtt.call(conn, @adapter_topic, "is_chat_provider", %{name: name}, :infinity)
result
end
def send(provider, target, message, metadata) do
case prepare_target(target) do
{:ok, target} ->
GenMqtt.cast(@adapter_topic, "send", %{provider: provider, target: target, message: message, metadata: metadata})
error ->
Logger.error("#{inspect error}")
error
end
end
def send(conn, provider, target, message, metadata) do
case prepare_target(target) do
{:ok, target} ->
GenMqtt.cast(conn, @adapter_topic, "send", %{provider: provider, target: target, message: message, metadata: metadata})
error ->
Logger.error("#{inspect error}")
error
end
end
##########
# Internals start here
##########
def init(conn, _) do
Logger.info("Starting")
case Application.fetch_env(:cog, __MODULE__) do
:error ->
{:stop, :missing_chat_adapter_config}
{:ok, config} ->
case Keyword.get(config, :providers) do
nil ->
Logger.error("Chat provider not specified. You must specify one of 'COG_SLACK_ENABLED' or 'COG_HIPCHAT_ENABLED' env variables")
{:stop, :missing_chat_providers}
providers ->
# TODO: validate that these providers actually implement
# the proper behavior
finish_initialization(conn, providers)
end
end
end
# RPC calls
def handle_call(_conn, @adapter_topic, _sender, "lookup_room", %{"provider" => provider, "id" => id}, state) do
{:reply, maybe_cache(with_provider(provider, state, :lookup_room, [id: id]), {provider, :room, id}, state), state}
end
def handle_call(_conn, @adapter_topic, _sender, "lookup_room", %{"provider" => provider, "name" => name}, state) do
{:reply, maybe_cache(with_provider(provider, state, :lookup_room, [name: name]), {provider, :room, name}, state), state}
end
def handle_call(_conn, @adapter_topic, _sender, "lookup_user", %{"provider" => provider,
"handle" => handle}, state) do
{:reply, maybe_cache(with_provider(provider, state, :lookup_user, [handle]), {provider, :user, handle}, state), state}
end
def handle_call(_conn, @adapter_topic, _sender, "list_joined_rooms", %{"provider" => provider}, state) do
{:reply, with_provider(provider, state, :list_joined_rooms, []), state}
end
def handle_call(_conn, @adapter_topic, _sender, "join", %{"provider" => provider,
"room" => room}, state) do
{:reply, with_provider(provider, state, :join, [room]), state}
end
def handle_call(_conn, @adapter_topic, _sender, "leave", %{"provider" => provider,
"room" => room}, state) do
{:reply, with_provider(provider, state, :leave, [room]), state}
end
def handle_call(_conn, @adapter_topic, _sender, "list_providers", %{}, state) do
{:reply, {:ok, %{providers: Enum.filter(Map.keys(state.providers), &(is_binary(&1)))}}, state}
end
def handle_call(_conn, @adapter_topic, _sender, "is_chat_provider", %{"name" => name}, state) do
# TODO: EXTRACT THIS!!!
result = name != "http"
{:reply, {:ok, result}, state}
end
def handle_call(_conn, @adapter_topic, _sender, "mention_name", %{"provider" => provider, "handle" => handle}, state) do
{:reply, with_provider(provider, state, :mention_name, [handle]), state}
end
def handle_call(_conn, @adapter_topic, _sender, "display_name", %{"provider" => provider}, state) do
{:reply, with_provider(provider, state, :display_name, []), state}
end
# Non-blocking "cast" messages
def handle_cast(_conn, @adapter_topic, "send", %{"target" => target,
"message" => message,
"provider" => provider,
"metadata" => metadata}, state) do
metadata = case metadata do
map when is_map(map) ->
case Cog.Chat.MessageMetadata.from_map(metadata) do
{:ok, metadata} ->
metadata
error ->
Logger.error("Failed to decode message metadata, continuing with an empty struct: #{inspect error}")
%Cog.Chat.MessageMetadata{}
end
_ ->
Logger.error("Expected message metadata to be a map, continuing with an empty struct.")
%Cog.Chat.MessageMetadata{}
end
case with_provider(provider, state, :send_message, [target, message, metadata]) do
:ok ->
:ok
{:error, :not_implemented} ->
Logger.error("send_message function not implemented for provider '#{provider}'! No message sent")
{:error, reason} ->
Logger.error("Failed to send message to provider #{provider}: #{inspect reason, pretty: true}")
end
{:noreply, state}
end
def handle_cast(_conn, @incoming_topic, "event", event, state) do
Logger.debug("Received chat event: #{inspect event}")
{:noreply, state}
end
def handle_cast(conn, @incoming_topic, "message", message, state) do
state = case Message.from_map(message) do
{:ok, message} ->
case is_pipeline?(message) do
{true, text} ->
if message.edited == true do
mention_name = with_provider(message.provider, state, :mention_name, [message.user.handle])
send(conn, message.provider, message.room, "#{mention_name} Executing edited command '#{text}'", %Cog.Chat.MessageMetadata{})
end
request = %ProviderRequest{
text: text, sender: message.user, room: message.room,
reply: "", id: message.id, provider: message.provider,
metadata: message.metadata,
initial_context: message.initial_context || %{}}
Connection.publish(conn, request, routed_by: "/bot/commands")
state
false ->
state
end
error ->
Logger.error("Error decoding chat message: #{inspect error} #{inspect message, pretty: true}")
state
end
{:noreply, state}
end
def handle_cast(conn, @incoming_topic, "internal", message, state) do
state = case Message.from_map(message) do
{:ok, message} ->
if message.edited == true do
mention_name = with_provider(message.provider, state, :mention_name, [message.user.handle])
send(conn, message.provider, message.room, "#{mention_name} Executing edited command '#{message.text}'", %Cog.Chat.MessageMetadata{})
end
request = %ProviderRequest{text: message.text, sender: message.user, room: message.room, reply: "", id: message.id,
provider: message.provider, initial_context: message.initial_context || %{}}
Connection.publish(conn, request, routed_by: "/bot/commands")
state
error ->
Logger.error("Error decoding chat message: #{inspect error} #{inspect message, pretty: true}")
state
end
{:noreply, state}
end
defp finish_initialization(conn, providers) do
Connection.subscribe(conn, @adapter_topic)
Connection.subscribe(conn, @incoming_topic)
case start_providers(providers, %{}) do
{:ok, providers} ->
{:ok, %__MODULE__{providers: providers, cache: get_cache()}}
error ->
error
end
end
defp start_providers([], accum), do: {:ok, accum}
defp start_providers([{name, provider}|t], accum) do
case Application.fetch_env(:cog, provider) do
:error ->
{:error, {:missing_provider_config, provider}}
{:ok, config} ->
config = [{:incoming_topic, @incoming_topic}|config]
case provider.start_link(config) do
{:ok, _} ->
Logger.info("Chat provider '#{name}' (#{provider}) initialized.")
accum = accum |> Map.put(name, provider) |> Map.put(Atom.to_string(name), provider)
start_providers(t, accum)
error ->
Logger.error("Chat provider '#{name}' (#{provider}) failed to initialize: #{inspect error}")
error
end
end
end
defp with_provider(provider, state, fun, args) when is_atom(fun) and is_list(args) do
case Map.get(state.providers, provider) do
nil ->
{:error, :unknown_provider}
provider ->
apply(provider, fun, args)
end
end
defp is_pipeline?(message) do
# The notion of "bot name" only really makes sense in the context
# of chat providers, where we can use that to determine whether or
# not a message is being addressed to the bot. For other providers
# (lookin' at you, Http.Provider), this makes no sense, because all
# messages are directed to the bot, by definition.
if message.room.is_dm == true do
{true, message.text}
else
case parse_spoken_command(message.text) do
nil ->
case parse_mention(message.text, message.bot_name) do
nil ->
false
updated ->
{true, updated}
end
updated ->
{true, updated}
end
end
end
defp parse_spoken_command(text) do
case Application.get_env(:cog, :enable_spoken_commands, true) do
false ->
nil
true ->
command_prefix = Application.get_env(:cog, :command_prefix, "!")
updated = Regex.replace(~r/^#{Regex.escape(command_prefix)}/, text, "")
case updated do
^text ->
nil
"" ->
nil
updated ->
updated
end
end
end
defp parse_mention(_text, nil), do: nil
defp parse_mention(text, bot_name) do
updated = Regex.replace(~r/^#{Regex.escape(bot_name)}/i, text, "")
if updated != text do
Regex.replace(~r/^:/, updated, "")
|> String.trim
else
nil
end
end
defp prepare_target(target) do
case Cog.Chat.Room.from_map(target) do
{:ok, room} ->
{:ok, room.id}
error ->
error
end
end
defp fetch_cache_ttl do
config = Application.get_env(:cog, __MODULE__)
Keyword.get(config, :cache_ttl, {10, :sec})
end
defp get_cache do
ttl = fetch_cache_ttl
{:ok, cache} = CacheSup.get_or_create_cache(@cache_name, ttl)
cache
end
defp maybe_cache({:ok, _}=value, key, state) do
Cache.put(state.cache, key, value)
value
end
defp maybe_cache(value, _key, _state), do: value
end
| 35.874704 | 151 | 0.608105 |
790dc74f1a1244449aa5b96fc618da1f5adbf5d3 | 6,342 | ex | Elixir | clients/cloud_private_catalog_producer/lib/google_api/cloud_private_catalog_producer/v1beta1/model/google_cloud_privatecatalogproducer_v1beta1_product.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/cloud_private_catalog_producer/lib/google_api/cloud_private_catalog_producer/v1beta1/model/google_cloud_privatecatalogproducer_v1beta1_product.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/cloud_private_catalog_producer/lib/google_api/cloud_private_catalog_producer/v1beta1/model/google_cloud_privatecatalogproducer_v1beta1_product.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.CloudPrivateCatalogProducer.V1beta1.Model.GoogleCloudPrivatecatalogproducerV1beta1Product do
@moduledoc """
The producer representation of a product which is a child resource of
`Catalog` with display metadata and a list of `Version` resources.
## Attributes
* `assetType` (*type:* `String.t`, *default:* `nil`) - Required. The type of the product asset, which cannot be changed after the
product is created. It supports the values
`google.deploymentmanager.Template` and
`google.cloudprivatecatalog.ListingOnly`. Other values will be
rejected by the server. Read only after creation.
The following fields or resource types have different validation rules
under each `asset_type` values:
* Product.display_metadata has different validation schema for each
asset type value. See its comment for details.
* Version resource isn't allowed to be added under the
`google.cloudprivatecatalog.ListingOnly` type.
* `createTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The time when the product was created.
* `displayMetadata` (*type:* `map()`, *default:* `nil`) - The user-supplied display metadata to describe the product.
The JSON schema of the metadata differs by Product.asset_type.
When the type is `google.deploymentmanager.Template`, the schema is as
follows:
```
"$schema": http://json-schema.org/draft-04/schema#
type: object
properties:
name:
type: string
minLength: 1
maxLength: 64
description:
type: string
minLength: 1
maxLength: 2048
tagline:
type: string
minLength: 1
maxLength: 100
support_info:
type: string
minLength: 1
maxLength: 2048
creator:
type: string
minLength: 1
maxLength: 100
documentation:
type: array
items:
type: object
properties:
url:
type: string
pattern:
"^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"
title:
type: string
minLength: 1
maxLength: 64
description:
type: string
minLength: 1
maxLength: 2048
required:
- name
- description
additionalProperties: false
```
When the asset type is `google.cloudprivatecatalog.ListingOnly`, the schema
is as follows:
```
"$schema": http://json-schema.org/draft-04/schema#
type: object
properties:
name:
type: string
minLength: 1
maxLength: 64
description:
type: string
minLength: 1
maxLength: 2048
tagline:
type: string
minLength: 1
maxLength: 100
support_info:
type: string
minLength: 1
maxLength: 2048
creator:
type: string
minLength: 1
maxLength: 100
documentation:
type: array
items:
type: object
properties:
url:
type: string
pattern:
"^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"
title:
type: string
minLength: 1
maxLength: 64
description:
type: string
minLength: 1
maxLength: 2048
signup_url:
type: string
pattern:
"^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"
required:
- name
- description
- signup_url
additionalProperties: false
```
* `iconUri` (*type:* `String.t`, *default:* `nil`) - Output only. The public accessible URI of the icon uploaded by
PrivateCatalogProducer.UploadIcon.
If no icon is uploaded, it will be the default icon's URI.
* `name` (*type:* `String.t`, *default:* `nil`) - Required. The resource name of the product in the format
`catalogs/{catalog_id}/products/a-z*[a-z0-9]'.
A unique identifier for the product under a catalog, which cannot
be changed after the product is created. The final
segment of the name must between 1 and 256 characters in length.
* `updateTime` (*type:* `DateTime.t`, *default:* `nil`) - Output only. The time when the product was last updated.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:assetType => String.t(),
:createTime => DateTime.t(),
:displayMetadata => map(),
:iconUri => String.t(),
:name => String.t(),
:updateTime => DateTime.t()
}
field(:assetType)
field(:createTime, as: DateTime)
field(:displayMetadata, type: :map)
field(:iconUri)
field(:name)
field(:updateTime, as: DateTime)
end
defimpl Poison.Decoder,
for:
GoogleApi.CloudPrivateCatalogProducer.V1beta1.Model.GoogleCloudPrivatecatalogproducerV1beta1Product do
def decode(value, options) do
GoogleApi.CloudPrivateCatalogProducer.V1beta1.Model.GoogleCloudPrivatecatalogproducerV1beta1Product.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.CloudPrivateCatalogProducer.V1beta1.Model.GoogleCloudPrivatecatalogproducerV1beta1Product do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.357143 | 133 | 0.599495 |
790dc79e39e02f4f8594a140a28bef199e852b5c | 872 | ex | Elixir | clients/run/lib/google_api/run/v1/metadata.ex | ukrbublik/elixir-google-api | 364cec36bc76f60bec94cbcad34844367a29d174 | [
"Apache-2.0"
] | null | null | null | clients/run/lib/google_api/run/v1/metadata.ex | ukrbublik/elixir-google-api | 364cec36bc76f60bec94cbcad34844367a29d174 | [
"Apache-2.0"
] | null | null | null | clients/run/lib/google_api/run/v1/metadata.ex | ukrbublik/elixir-google-api | 364cec36bc76f60bec94cbcad34844367a29d174 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Run.V1 do
@moduledoc """
API client metadata for GoogleApi.Run.V1.
"""
@discovery_revision "20200814"
def discovery_revision(), do: @discovery_revision
end
| 32.296296 | 74 | 0.755734 |
790dcb86ad56e04309a12b2d90c976eed3c0fc4e | 69 | exs | Elixir | test/views/layout_view_test.exs | zhangsoledad/Doom | 37ddc696e7d71c742bfc90352d76e81f2c78f5b7 | [
"MIT"
] | 6 | 2016-03-17T08:45:34.000Z | 2016-10-10T01:20:37.000Z | test/views/layout_view_test.exs | zhangsoledad/doom | 37ddc696e7d71c742bfc90352d76e81f2c78f5b7 | [
"MIT"
] | null | null | null | test/views/layout_view_test.exs | zhangsoledad/doom | 37ddc696e7d71c742bfc90352d76e81f2c78f5b7 | [
"MIT"
] | 2 | 2016-04-01T06:28:56.000Z | 2016-04-28T09:35:07.000Z | defmodule Doom.LayoutViewTest do
use Doom.ConnCase, async: true
end | 23 | 32 | 0.811594 |
790ddd0d725564dcf7729004f550db766a231cad | 2,156 | ex | Elixir | clients/assured_workloads/lib/google_api/assured_workloads/v1beta1/model/google_cloud_assuredworkloads_v1beta1_list_workloads_response.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/assured_workloads/lib/google_api/assured_workloads/v1beta1/model/google_cloud_assuredworkloads_v1beta1_list_workloads_response.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/assured_workloads/lib/google_api/assured_workloads/v1beta1/model/google_cloud_assuredworkloads_v1beta1_list_workloads_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.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1beta1ListWorkloadsResponse do
@moduledoc """
Response of ListWorkloads endpoint.
## Attributes
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - The next page token. Return empty if reached the last page.
* `workloads` (*type:* `list(GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1beta1Workload.t)`, *default:* `nil`) - List of Workloads under a given parent.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:nextPageToken => String.t(),
:workloads =>
list(
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1beta1Workload.t()
)
}
field(:nextPageToken)
field(:workloads,
as: GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1beta1Workload,
type: :list
)
end
defimpl Poison.Decoder,
for:
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1beta1ListWorkloadsResponse do
def decode(value, options) do
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1beta1ListWorkloadsResponse.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.AssuredWorkloads.V1beta1.Model.GoogleCloudAssuredworkloadsV1beta1ListWorkloadsResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.6875 | 181 | 0.747217 |
790e10e4325c4b3c9115d9f3d713a45c47b5a82f | 1,922 | ex | Elixir | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/delivery_control.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/delivery_control.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/delivery_control.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.AdExchangeBuyer.V14.Model.DeliveryControl do
@moduledoc """
## Attributes
* `creativeBlockingLevel` (*type:* `String.t`, *default:* `nil`) -
* `deliveryRateType` (*type:* `String.t`, *default:* `nil`) -
* `frequencyCaps` (*type:* `list(GoogleApi.AdExchangeBuyer.V14.Model.DeliveryControlFrequencyCap.t)`, *default:* `nil`) -
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:creativeBlockingLevel => String.t(),
:deliveryRateType => String.t(),
:frequencyCaps =>
list(GoogleApi.AdExchangeBuyer.V14.Model.DeliveryControlFrequencyCap.t())
}
field(:creativeBlockingLevel)
field(:deliveryRateType)
field(
:frequencyCaps,
as: GoogleApi.AdExchangeBuyer.V14.Model.DeliveryControlFrequencyCap,
type: :list
)
end
defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V14.Model.DeliveryControl do
def decode(value, options) do
GoogleApi.AdExchangeBuyer.V14.Model.DeliveryControl.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V14.Model.DeliveryControl do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.576271 | 126 | 0.725806 |
790e12019e65f5851fc435002bf7e0aff5e0cdd0 | 2,973 | ex | Elixir | lib/sippet/transactions/server.ex | BrendanBall/elixir-sippet | 877edcbbc8d8ba5b6b41684c20041510c410aad3 | [
"BSD-3-Clause"
] | 54 | 2017-04-26T03:15:56.000Z | 2022-02-08T00:22:11.000Z | lib/sippet/transactions/server.ex | BrendanBall/elixir-sippet | 877edcbbc8d8ba5b6b41684c20041510c410aad3 | [
"BSD-3-Clause"
] | 21 | 2017-06-19T08:00:33.000Z | 2022-01-19T10:38:11.000Z | lib/sippet/transactions/server.ex | BrendanBall/elixir-sippet | 877edcbbc8d8ba5b6b41684c20041510c410aad3 | [
"BSD-3-Clause"
] | 22 | 2017-06-19T08:15:34.000Z | 2022-03-22T13:56:20.000Z | defmodule Sippet.Transactions.Server do
@moduledoc false
alias Sippet.Message
alias Sippet.Message.{RequestLine, StatusLine}
alias Sippet.Transactions.Server.State, as: State
def receive_request(server, %Message{start_line: %RequestLine{}} = request),
do: GenStateMachine.cast(server, {:incoming_request, request})
def send_response(server, %Message{start_line: %StatusLine{}} = response),
do: GenStateMachine.cast(server, {:outgoing_response, response})
def receive_error(server, reason),
do: GenStateMachine.cast(server, {:error, reason})
def terminate(server),
do: GenStateMachine.cast(server, :terminate)
defmacro __using__(opts) do
quote location: :keep do
use GenStateMachine, callback_mode: [:state_functions, :state_enter]
alias Sippet.Transactions.Server.State
require Logger
def init(%State{key: key} = data) do
Logger.debug("server transaction #{inspect(key)} started")
initial_state = unquote(opts)[:initial_state]
{:ok, initial_state, data}
end
defp send_response(response, %State{key: key, sippet: sippet} = data) do
extras = data.extras |> Map.put(:last_response, response)
data = %{data | extras: extras}
Sippet.Router.send_transport_message(sippet, response, key)
data
end
defp receive_request(request, %State{key: key, sippet: sippet}),
do: Sippet.Router.to_core(sippet, :receive_request, [request, key])
def shutdown(reason, %State{key: key, sippet: sippet} = data) do
Logger.warn("server transaction #{inspect(key)} shutdown: #{reason}")
Sippet.Router.to_core(sippet, :receive_error, [reason, key])
{:stop, :shutdown, data}
end
def timeout(data),
do: shutdown(:timeout, data)
def reliable?(request, %State{sippet: sippet}),
do: Sippet.reliable?(sippet, request)
def unhandled_event(:cast, :terminate, %State{key: key} = data) do
Logger.debug("server transaction #{inspect(key)} terminated")
{:stop, :normal, data}
end
def unhandled_event(event_type, event_content, %State{key: key} = data) do
Logger.error([
"server transaction #{inspect(key)} got unhandled_event/3:",
" #{inspect(event_type)}, #{inspect(event_content)}, #{inspect(data)}"
])
{:stop, :shutdown, data}
end
def child_spec([%{key: server_key}, _] = args) do
%{
id: {__MODULE__, server_key},
start: {__MODULE__, :start_link, [args]},
restart: :transient
}
end
def start_link([initial_data, opts]),
do: GenStateMachine.start_link(__MODULE__, initial_data, opts)
defoverridable init: 1,
send_response: 2,
receive_request: 2,
shutdown: 2,
timeout: 1,
unhandled_event: 3
end
end
end
| 31.62766 | 80 | 0.628322 |
790e1c5eab28cf129498049b529ef3c19776c822 | 1,095 | ex | Elixir | lib/nomad_client/model/resources.ex | mrmstn/nomad_client | a586022e5eb4d166acba08b55b198ec079d4b118 | [
"Apache-2.0"
] | 8 | 2021-09-04T21:22:53.000Z | 2022-02-22T22:48:38.000Z | lib/nomad_client/model/resources.ex | mrmstn/nomad_client | a586022e5eb4d166acba08b55b198ec079d4b118 | [
"Apache-2.0"
] | null | null | null | lib/nomad_client/model/resources.ex | mrmstn/nomad_client | a586022e5eb4d166acba08b55b198ec079d4b118 | [
"Apache-2.0"
] | null | null | null | # NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
# https://openapi-generator.tech
# Do not edit the class manually.
defmodule NomadClient.Model.Resources do
@moduledoc """
"""
@derive [Poison.Encoder]
defstruct [
:CPU,
:Cores,
:MemoryMB,
:MemoryMaxMB,
:DiskMB,
:Networks,
:Devices,
:IOPS
]
@type t :: %__MODULE__{
:CPU => integer() | nil,
:Cores => integer() | nil,
:MemoryMB => integer() | nil,
:MemoryMaxMB => integer() | nil,
:DiskMB => integer() | nil,
:Networks => [NomadClient.Model.NetworkResource.t()] | nil,
:Devices => [NomadClient.Model.RequestedDevice.t()] | nil,
:IOPS => integer() | nil
}
end
defimpl Poison.Decoder, for: NomadClient.Model.Resources do
import NomadClient.Deserializer
def decode(value, options) do
value
|> deserialize(:Networks, :list, NomadClient.Model.NetworkResource, options)
|> deserialize(:Devices, :list, NomadClient.Model.RequestedDevice, options)
end
end
| 25.465116 | 91 | 0.621005 |
790e94ae4b3a421c535ec208537a4b7537b46a21 | 305 | exs | Elixir | priv/repo/migrations/20190329205033_create_chapters.exs | jeyemwey/radiator-spark | 2fba0a84eb43ab1d58e8ec58c6a07f64adf9cb9d | [
"MIT"
] | 1 | 2021-03-02T16:59:40.000Z | 2021-03-02T16:59:40.000Z | priv/repo/migrations/20190329205033_create_chapters.exs | optikfluffel/radiator | b1a1b966296fa6bf123e3a2455009ff52099ace6 | [
"MIT"
] | null | null | null | priv/repo/migrations/20190329205033_create_chapters.exs | optikfluffel/radiator | b1a1b966296fa6bf123e3a2455009ff52099ace6 | [
"MIT"
] | null | null | null | defmodule Radiator.Repo.Migrations.CreateChapters do
use Ecto.Migration
def change do
create table(:chapters) do
add :start, :integer
add :title, :text
add :link, :text
add :image, :text
add :episode_id, references(:episodes, on_delete: :nothing)
end
end
end
| 20.333333 | 65 | 0.659016 |
790eaa5779fdf7b3f1c265e78452a095d7e32e29 | 2,399 | ex | Elixir | clients/admin/lib/google_api/admin/reports_v1/model/usage_report_parameters.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/admin/lib/google_api/admin/reports_v1/model/usage_report_parameters.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/admin/lib/google_api/admin/reports_v1/model/usage_report_parameters.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.Admin.Reports_v1.Model.UsageReportParameters do
@moduledoc """
## Attributes
* `boolValue` (*type:* `boolean()`, *default:* `nil`) - Output only. Boolean value of the parameter.
* `datetimeValue` (*type:* `DateTime.t`, *default:* `nil`) - The RFC 3339 formatted value of the parameter, for example 2010-10-28T10:26:35.000Z.
* `intValue` (*type:* `String.t`, *default:* `nil`) - Output only. Integer value of the parameter.
* `msgValue` (*type:* `list(map())`, *default:* `nil`) - Output only. Nested message value of the parameter.
* `name` (*type:* `String.t`, *default:* `nil`) - The name of the parameter. For the User Usage Report parameter names, see the User Usage parameters reference.
* `stringValue` (*type:* `String.t`, *default:* `nil`) - Output only. String value of the parameter.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:boolValue => boolean() | nil,
:datetimeValue => DateTime.t() | nil,
:intValue => String.t() | nil,
:msgValue => list(map()) | nil,
:name => String.t() | nil,
:stringValue => String.t() | nil
}
field(:boolValue)
field(:datetimeValue, as: DateTime)
field(:intValue)
field(:msgValue, type: :list)
field(:name)
field(:stringValue)
end
defimpl Poison.Decoder, for: GoogleApi.Admin.Reports_v1.Model.UsageReportParameters do
def decode(value, options) do
GoogleApi.Admin.Reports_v1.Model.UsageReportParameters.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Admin.Reports_v1.Model.UsageReportParameters do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.693548 | 164 | 0.692372 |
790eb03c98d35ee2d1fd9d5afa07baff25920879 | 20,677 | ex | Elixir | lib/ecto/date_time.ex | mbuhot/ecto | e6c4c7df0af055ba4bae8737908b98ae85352d2f | [
"Apache-2.0"
] | null | null | null | lib/ecto/date_time.ex | mbuhot/ecto | e6c4c7df0af055ba4bae8737908b98ae85352d2f | [
"Apache-2.0"
] | null | null | null | lib/ecto/date_time.ex | mbuhot/ecto | e6c4c7df0af055ba4bae8737908b98ae85352d2f | [
"Apache-2.0"
] | null | null | null | # TODO: Remove Ecto.Date|Time types on Ecto v2.2
import Kernel, except: [to_string: 1]
defmodule Ecto.DateTime.Utils do
@moduledoc false
@doc "Pads with zero"
def zero_pad(val, count) do
num = Integer.to_string(val)
pad_length = max(count - byte_size(num), 0)
:binary.copy("0", pad_length) <> num
end
@doc "Converts to integer if possible"
def to_i(nil), do: nil
def to_i({int, _}) when is_integer(int), do: int
def to_i(int) when is_integer(int), do: int
def to_i(bin) when is_binary(bin) do
case Integer.parse(bin) do
{int, ""} -> int
_ -> nil
end
end
@doc "A guard to check for dates"
defmacro is_date(year, month, day) do
quote do
is_integer(unquote(year)) and unquote(month) in 1..12 and unquote(day) in 1..31
end
end
@doc "A guard to check for times"
defmacro is_time(hour, min, sec, usec \\ 0) do
quote do
unquote(hour) in 0..23 and
unquote(min) in 0..59 and
unquote(sec) in 0..59 and
unquote(usec) in 0..999_999
end
end
@doc """
Checks if the trailing part of a date/time matches ISO specs.
"""
defmacro is_iso_8601(x) do
quote do: unquote(x) in ["", "Z"]
end
@doc """
Gets microseconds from rest and validates it.
Returns nil if an invalid format is given.
"""
def usec("." <> rest) do
case parse(rest, "") do
{int, rest} when byte_size(int) > 6 and is_iso_8601(rest) ->
String.to_integer(binary_part(int, 0, 6))
{int, rest} when byte_size(int) in 1..6 and is_iso_8601(rest) ->
pad = String.duplicate("0", 6 - byte_size(int))
String.to_integer(int <> pad)
_ ->
nil
end
end
def usec(rest) when is_iso_8601(rest), do: 0
def usec(_), do: nil
@doc """
Compare two datetimes.
Receives two datetimes and compares the `t1`
against `t2` and returns `:lt`, `:eq` or `:gt`.
"""
def compare(%{__struct__: module} = t1, %{__struct__: module} = t2) do
{:ok, t1} = module.dump(t1)
{:ok, t2} = module.dump(t2)
cond do
t1 == t2 -> :eq
t1 > t2 -> :gt
true -> :lt
end
end
defp parse(<<h, t::binary>>, acc) when h in ?0..?9, do: parse(t, <<acc::binary, h>>)
defp parse(rest, acc), do: {acc, rest}
end
defmodule Ecto.Date do
import Ecto.DateTime.Utils
@doc """
Compare two dates.
Receives two dates and compares the `t1`
against `t2` and returns `:lt`, `:eq` or `:gt`.
"""
defdelegate compare(t1, t2), to: Ecto.DateTime.Utils
@moduledoc """
An Ecto type for dates.
"""
@behaviour Ecto.Type
defstruct [:year, :month, :day]
@doc """
The Ecto primitive type.
"""
def type, do: :date
@doc """
Casts the given value to date.
It supports:
* a binary in the "YYYY-MM-DD" format
* a binary in the "YYYY-MM-DD HH:MM:SS" format
(may be separated by T and/or followed by "Z", as in `2014-04-17T14:00:00Z`)
* a binary in the "YYYY-MM-DD HH:MM:SS.USEC" format
(may be separated by T and/or followed by "Z", as in `2014-04-17T14:00:00.030Z`)
* a map with `"year"`, `"month"` and `"day"` keys
with integer or binaries as values
* a map with `:year`, `:month` and `:day` keys
with integer or binaries as values
* a tuple with `{year, month, day}` as integers or binaries
* an `Ecto.Date` struct itself
"""
def cast(d), do: d |> do_cast() |> validate_cast()
@doc """
Same as `cast/1` but raises `Ecto.CastError` on invalid dates.
"""
def cast!(value) do
case cast(value) do
{:ok, date} -> date
:error -> raise Ecto.CastError, type: __MODULE__, value: value
end
end
defp do_cast(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes>>),
do: from_parts(to_i(year), to_i(month), to_i(day))
defp do_cast(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes, sep,
_hour::2-bytes, ?:, _min::2-bytes, ?:, _sec::2-bytes, _rest::binary>>) when sep in [?\s, ?T],
do: from_parts(to_i(year), to_i(month), to_i(day))
defp do_cast(%Ecto.Date{} = d),
do: {:ok, d}
defp do_cast(%{"year" => empty, "month" => empty, "day" => empty}) when empty in ["", nil],
do: {:ok, nil}
defp do_cast(%{year: empty, month: empty, day: empty}) when empty in ["", nil],
do: {:ok, nil}
defp do_cast(%{"year" => year, "month" => month, "day" => day}),
do: from_parts(to_i(year), to_i(month), to_i(day))
defp do_cast(%{year: year, month: month, day: day}),
do: from_parts(to_i(year), to_i(month), to_i(day))
defp do_cast({year, month, day}),
do: from_parts(to_i(year), to_i(month), to_i(day))
defp do_cast(_),
do: :error
defp validate_cast(:error), do: :error
defp validate_cast({:ok, nil}), do: {:ok, nil}
defp validate_cast({:ok, %{year: y, month: m, day: d} = date}) do
if :calendar.valid_date(y, m, d), do: {:ok, date}, else: :error
end
defp from_parts(year, month, day) when is_date(year, month, day) do
{:ok, %Ecto.Date{year: year, month: month, day: day}}
end
defp from_parts(_, _, _), do: :error
@doc """
Converts an `Ecto.Date` into a date triplet.
"""
def dump(%Ecto.Date{year: year, month: month, day: day}) do
{:ok, {year, month, day}}
end
def dump(_), do: :error
@doc """
Converts a date triplet into an `Ecto.Date`.
"""
def load({year, month, day}) do
{:ok, %Ecto.Date{year: year, month: month, day: day}}
end
def load(_), do: :error
@doc """
Converts `Ecto.Date` to a readable string representation.
"""
def to_string(%Ecto.Date{year: year, month: month, day: day}) do
zero_pad(year, 4) <> "-" <> zero_pad(month, 2) <> "-" <> zero_pad(day, 2)
end
@doc """
Converts `Ecto.Date` to ISO8601 representation.
"""
def to_iso8601(date) do
to_string(date)
end
@doc """
Returns an `Ecto.Date` in UTC.
"""
def utc do
{{year, month, day}, _time} = :erlang.universaltime
%Ecto.Date{year: year, month: month, day: day}
end
@doc """
Returns an Erlang date tuple from an `Ecto.Date`.
"""
def to_erl(%Ecto.Date{year: year, month: month, day: day}) do
{year, month, day}
end
@doc """
Returns an `Ecto.Date` from an Erlang date tuple.
"""
def from_erl({year, month, day}) do
%Ecto.Date{year: year, month: month, day: day}
end
end
defmodule Ecto.Time do
import Ecto.DateTime.Utils
@doc """
Compare two times.
Receives two times and compares the `t1`
against `t2` and returns `:lt`, `:eq` or `:gt`.
"""
defdelegate compare(t1, t2), to: Ecto.DateTime.Utils
@moduledoc """
An Ecto type for time.
"""
@behaviour Ecto.Type
defstruct [:hour, :min, :sec, usec: 0]
@doc """
The Ecto primitive type.
"""
def type, do: :time
@doc """
Casts the given value to time.
It supports:
* a binary in the "HH:MM:SS" format
(may be followed by "Z", as in `12:00:00Z`)
* a binary in the "HH:MM:SS.USEC" format
(may be followed by "Z", as in `12:00:00.005Z`)
* a map with `"hour"`, `"minute"` keys with `"second"` and `"microsecond"`
as optional keys and values are integers or binaries
* a map with `:hour`, `:minute` keys with `:second` and `:microsecond`
as optional keys and values are integers or binaries
* a tuple with `{hour, min, sec}` as integers or binaries
* a tuple with `{hour, min, sec, usec}` as integers or binaries
* an `Ecto.Time` struct itself
"""
def cast(<<hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes, rest::binary>>) do
if usec = usec(rest) do
from_parts(to_i(hour), to_i(min), to_i(sec), usec)
else
:error
end
end
def cast(%Ecto.Time{} = t),
do: {:ok, t}
def cast(%{"hour" => hour, "min" => min} = map),
do: from_parts(to_i(hour), to_i(min), to_i(Map.get(map, "sec", 0)), to_i(Map.get(map, "usec", 0)))
def cast(%{hour: hour, min: min} = map),
do: from_parts(to_i(hour), to_i(min), to_i(Map.get(map, :sec, 0)), to_i(Map.get(map, :usec, 0)))
def cast(%{"hour" => empty, "minute" => empty}) when empty in ["", nil],
do: {:ok, nil}
def cast(%{hour: empty, minute: empty}) when empty in ["", nil],
do: {:ok, nil}
def cast(%{"hour" => hour, "minute" => minute} = map),
do: from_parts(to_i(hour), to_i(minute), to_i(Map.get(map, "second", 0)), to_i(Map.get(map, "microsecond", 0)))
def cast(%{hour: hour, minute: minute} = map),
do: from_parts(to_i(hour), to_i(minute), to_i(Map.get(map, :second, 0)), to_i(Map.get(map, :microsecond, 0)))
def cast({hour, min, sec}),
do: from_parts(to_i(hour), to_i(min), to_i(sec), 0)
def cast({hour, min, sec, usec}),
do: from_parts(to_i(hour), to_i(min), to_i(sec), to_i(usec))
def cast(_),
do: :error
@doc """
Same as `cast/1` but raises `Ecto.CastError` on invalid times.
"""
def cast!(value) do
case cast(value) do
{:ok, time} -> time
:error -> raise Ecto.CastError, type: __MODULE__, value: value
end
end
defp from_parts(hour, min, sec, usec) when is_time(hour, min, sec, usec),
do: {:ok, %Ecto.Time{hour: hour, min: min, sec: sec, usec: usec}}
defp from_parts(_, _, _, _),
do: :error
@doc """
Converts an `Ecto.Time` into a time tuple (in the form `{hour, min, sec,
usec}`).
"""
def dump(%Ecto.Time{hour: hour, min: min, sec: sec, usec: usec}) do
{:ok, {hour, min, sec, usec}}
end
def dump(_), do: :error
@doc """
Converts a time tuple like the one returned by `dump/1` into an `Ecto.Time`.
"""
def load({hour, min, sec, usec}) do
{:ok, %Ecto.Time{hour: hour, min: min, sec: sec, usec: usec}}
end
def load({_, _, _} = time) do
{:ok, from_erl(time)}
end
def load(_), do: :error
@doc """
Converts `Ecto.Time` to a string representation.
"""
def to_string(%Ecto.Time{hour: hour, min: min, sec: sec, usec: usec}) do
str = zero_pad(hour, 2) <> ":" <> zero_pad(min, 2) <> ":" <> zero_pad(sec, 2)
if is_nil(usec) or usec == 0 do
str
else
str <> "." <> zero_pad(usec, 6)
end
end
@doc """
Converts `Ecto.Time` to its ISO 8601 representation.
"""
def to_iso8601(time) do
to_string(time)
end
@doc """
Returns an `Ecto.Time` in UTC.
`precision` can be `:sec` or `:usec.`
"""
def utc(precision \\ :sec)
def utc(:sec) do
{_, {hour, min, sec}} = :erlang.universaltime
%Ecto.Time{hour: hour, min: min, sec: sec}
end
def utc(:usec) do
now = {_, _, usec} = :os.timestamp
{_date, {hour, min, sec}} = :calendar.now_to_universal_time(now)
%Ecto.Time{hour: hour, min: min, sec: sec, usec: usec}
end
@doc """
Returns an Erlang time tuple from an `Ecto.Time`.
"""
def to_erl(%Ecto.Time{hour: hour, min: min, sec: sec}) do
{hour, min, sec}
end
@doc """
Returns an `Ecto.Time` from an Erlang time tuple.
"""
def from_erl({hour, min, sec}) do
%Ecto.Time{hour: hour, min: min, sec: sec}
end
end
defmodule Ecto.DateTime do
import Ecto.DateTime.Utils
@unix_epoch :calendar.datetime_to_gregorian_seconds {{1970, 1, 1}, {0, 0, 0}}
@doc """
Compare two datetimes.
Receives two datetimes and compares the `t1`
against `t2` and returns `:lt`, `:eq` or `:gt`.
"""
defdelegate compare(t1, t2), to: Ecto.DateTime.Utils
@moduledoc """
An Ecto type that includes a date and a time.
"""
@behaviour Ecto.Type
defstruct [:year, :month, :day, :hour, :min, :sec, usec: 0]
@doc """
The Ecto primitive type.
"""
def type, do: :naive_datetime
@doc """
Casts the given value to datetime.
It supports:
* a binary in the "YYYY-MM-DD HH:MM:SS" format
(may be separated by T and/or followed by "Z", as in `2014-04-17T14:00:00Z`)
* a binary in the "YYYY-MM-DD HH:MM:SS.USEC" format
(may be separated by T and/or followed by "Z", as in `2014-04-17T14:00:00.030Z`)
* a map with `"year"`, `"month"`,`"day"`, `"hour"`, `"minute"` keys
with `"second"` and `"microsecond"` as optional keys and values are integers or binaries
* a map with `:year`, `:month`,`:day`, `:hour`, `:minute` keys
with `:second` and `:microsecond` as optional keys and values are integers or binaries
* a tuple with `{{year, month, day}, {hour, min, sec}}` as integers or binaries
* a tuple with `{{year, month, day}, {hour, min, sec, usec}}` as integers or binaries
* an `Ecto.DateTime` struct itself
"""
def cast(dt), do: dt |> do_cast() |> validate_cast()
@doc """
Same as `cast/1` but raises `Ecto.CastError` on invalid datetimes.
"""
def cast!(value) do
case cast(value) do
{:ok, datetime} -> datetime
:error -> raise Ecto.CastError, type: __MODULE__, value: value
end
end
defp do_cast(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes, sep,
hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes, rest::binary>>) when sep in [?\s, ?T] do
if usec = usec(rest) do
from_parts(to_i(year), to_i(month), to_i(day),
to_i(hour), to_i(min), to_i(sec), usec)
else
:error
end
end
defp do_cast(%Ecto.DateTime{} = dt) do
{:ok, dt}
end
defp do_cast(%{"year" => year, "month" => month, "day" => day, "hour" => hour, "min" => min} = map) do
from_parts(to_i(year), to_i(month), to_i(day),
to_i(hour), to_i(min), to_i(Map.get(map, "sec", 0)),
to_i(Map.get(map, "usec", 0)))
end
defp do_cast(%{year: year, month: month, day: day, hour: hour, min: min} = map) do
from_parts(to_i(year), to_i(month), to_i(day),
to_i(hour), to_i(min), to_i(Map.get(map, :sec, 0)),
to_i(Map.get(map, :usec, 0)))
end
defp do_cast(%{"year" => empty, "month" => empty, "day" => empty,
"hour" => empty, "minute" => empty}) when empty in ["", nil] do
{:ok, nil}
end
defp do_cast(%{year: empty, month: empty, day: empty,
hour: empty, minute: empty}) when empty in ["", nil] do
{:ok, nil}
end
defp do_cast(%{"year" => year, "month" => month, "day" => day, "hour" => hour, "minute" => min} = map) do
from_parts(to_i(year), to_i(month), to_i(day),
to_i(hour), to_i(min), to_i(Map.get(map, "second", 0)),
to_i(Map.get(map, "microsecond", 0)))
end
defp do_cast(%{year: year, month: month, day: day, hour: hour, minute: min} = map) do
from_parts(to_i(year), to_i(month), to_i(day),
to_i(hour), to_i(min), to_i(Map.get(map, :second, 0)),
to_i(Map.get(map, :microsecond, 0)))
end
defp do_cast({{year, month, day}, {hour, min, sec}}) do
from_parts(to_i(year), to_i(month), to_i(day),
to_i(hour), to_i(min), to_i(sec), 0)
end
defp do_cast({{year, month, day}, {hour, min, sec, usec}}) do
from_parts(to_i(year), to_i(month), to_i(day),
to_i(hour), to_i(min), to_i(sec), to_i(usec))
end
defp do_cast(_) do
:error
end
defp validate_cast(:error), do: :error
defp validate_cast({:ok, nil}), do: {:ok, nil}
defp validate_cast({:ok, %{year: y, month: m, day: d} = datetime}) do
if :calendar.valid_date(y, m, d), do: {:ok, datetime}, else: :error
end
defp from_parts(year, month, day, hour, min, sec, usec)
when is_date(year, month, day) and is_time(hour, min, sec, usec) do
{:ok, %Ecto.DateTime{year: year, month: month, day: day, hour: hour, min: min, sec: sec, usec: usec}}
end
defp from_parts(_, _, _, _, _, _, _), do: :error
@doc """
Converts an `Ecto.DateTime` into a `{date, time}` tuple.
"""
def dump(%Ecto.DateTime{year: year, month: month, day: day, hour: hour, min: min, sec: sec, usec: usec}) do
{:ok, {{year, month, day}, {hour, min, sec, usec}}}
end
def dump(_), do: :error
@doc """
Converts a `{date, time}` tuple into an `Ecto.DateTime`.
"""
def load({{_, _, _}, {_, _, _, _}} = datetime) do
{:ok, erl_load(datetime)}
end
def load({{_, _, _}, {_, _, _}} = datetime) do
{:ok, from_erl(datetime)}
end
def load(_), do: :error
@doc """
Converts `Ecto.DateTime` into an `Ecto.Date`.
"""
def to_date(%Ecto.DateTime{year: year, month: month, day: day}) do
%Ecto.Date{year: year, month: month, day: day}
end
@doc """
Converts `Ecto.DateTime` into an `Ecto.Time`.
"""
def to_time(%Ecto.DateTime{hour: hour, min: min, sec: sec, usec: usec}) do
%Ecto.Time{hour: hour, min: min, sec: sec, usec: usec}
end
@doc """
Converts the given `Ecto.Date` into `Ecto.DateTime` with the time being
00:00:00.
"""
def from_date(%Ecto.Date{year: year, month: month, day: day}) do
%Ecto.DateTime{year: year, month: month, day: day,
hour: 0, min: 0, sec: 0, usec: 0}
end
@doc """
Converts the given `Ecto.Date` and `Ecto.Time` into `Ecto.DateTime`.
"""
def from_date_and_time(%Ecto.Date{year: year, month: month, day: day},
%Ecto.Time{hour: hour, min: min, sec: sec, usec: usec}) do
%Ecto.DateTime{year: year, month: month, day: day,
hour: hour, min: min, sec: sec, usec: usec}
end
@doc """
Converts `Ecto.DateTime` to its string representation.
"""
def to_string(%Ecto.DateTime{year: year, month: month, day: day, hour: hour, min: min, sec: sec, usec: usec}) do
str = zero_pad(year, 4) <> "-" <> zero_pad(month, 2) <> "-" <> zero_pad(day, 2) <> " " <>
zero_pad(hour, 2) <> ":" <> zero_pad(min, 2) <> ":" <> zero_pad(sec, 2)
if is_nil(usec) or usec == 0 do
str
else
str <> "." <> zero_pad(usec, 6)
end
end
@doc """
Converts `Ecto.DateTime` to its ISO 8601 representation
without timezone specification.
"""
def to_iso8601(%Ecto.DateTime{year: year, month: month, day: day,
hour: hour, min: min, sec: sec, usec: usec}) do
str = zero_pad(year, 4) <> "-" <> zero_pad(month, 2) <> "-" <> zero_pad(day, 2) <> "T" <>
zero_pad(hour, 2) <> ":" <> zero_pad(min, 2) <> ":" <> zero_pad(sec, 2)
if is_nil(usec) or usec == 0 do
str
else
str <> "." <> zero_pad(usec, 6)
end
end
@doc """
Returns an `Ecto.DateTime` in UTC.
`precision` can be `:sec` or `:usec`.
"""
def utc(precision \\ :sec) do
autogenerate(precision)
end
@doc """
Returns an Erlang datetime tuple from an `Ecto.DateTime`.
"""
def to_erl(%Ecto.DateTime{year: year, month: month, day: day, hour: hour, min: min, sec: sec}) do
{{year, month, day}, {hour, min, sec}}
end
@doc """
Returns an `Ecto.DateTime` from an Erlang datetime tuple.
"""
def from_erl({{year, month, day}, {hour, min, sec}}) do
%Ecto.DateTime{year: year, month: month, day: day,
hour: hour, min: min, sec: sec}
end
def from_unix!(integer, unit) do
total = System.convert_time_unit(integer, unit, :microseconds)
microsecond = rem(total, 1_000_000)
{{year, month, day}, {hour, minute, second}} =
:calendar.gregorian_seconds_to_datetime(@unix_epoch + div(total, 1_000_000))
%Ecto.DateTime{year: year, month: month, day: day,
hour: hour, min: minute, sec: second, usec: microsecond}
end
# Callback invoked by autogenerate fields.
@doc false
def autogenerate(precision \\ :sec)
def autogenerate(:sec) do
{date, {h, m, s}} = :erlang.universaltime
erl_load({date, {h, m, s, 0}})
end
def autogenerate(:usec) do
timestamp = {_, _, usec} = :os.timestamp
{date, {h, m, s}} = :calendar.now_to_datetime(timestamp)
erl_load({date, {h, m, s, usec}})
end
defp erl_load({{year, month, day}, {hour, min, sec, usec}}) do
%Ecto.DateTime{year: year, month: month, day: day,
hour: hour, min: min, sec: sec, usec: usec}
end
end
defimpl String.Chars, for: [Ecto.DateTime, Ecto.Date, Ecto.Time] do
def to_string(dt) do
@for.to_string(dt)
end
end
defimpl Inspect, for: [Ecto.DateTime, Ecto.Date, Ecto.Time] do
@inspected inspect(@for)
def inspect(dt, _opts) do
"#" <> @inspected <> "<" <> @for.to_string(dt) <> ">"
end
end
defimpl Ecto.DataType, for: Ecto.DateTime do
def dump(%Ecto.DateTime{year: year, month: month, day: day,
hour: hour, min: min, sec: sec, usec: usec}) do
{:ok, {{year, month, day}, {hour, min, sec, usec}}}
end
end
defimpl Ecto.DataType, for: Ecto.Date do
def dump(%Ecto.Date{year: year, month: month, day: day}) do
{:ok, {year, month, day}}
end
end
defimpl Ecto.DataType, for: Ecto.Time do
def dump(%Ecto.Time{hour: hour, min: min, sec: sec, usec: usec}) do
{:ok, {hour, min, sec, usec}}
end
end
if Code.ensure_loaded?(Poison) do
defimpl Poison.Encoder, for: [Ecto.Date, Ecto.Time, Ecto.DateTime] do
def encode(dt, _opts), do: <<?", @for.to_iso8601(dt)::binary, ?">>
end
end
| 30.053779 | 115 | 0.594477 |
790f0944192b68e6873b3ad3a06b4f958ffc1536 | 4,402 | exs | Elixir | test/validation/point_polygon_b_test.exs | codabrink/topo | f1ca4b7fe337a67285ee4c65a34fb521b119342c | [
"MIT"
] | 110 | 2016-05-05T21:09:19.000Z | 2022-03-08T05:22:16.000Z | test/validation/point_polygon_b_test.exs | codabrink/topo | f1ca4b7fe337a67285ee4c65a34fb521b119342c | [
"MIT"
] | 15 | 2016-12-01T00:32:11.000Z | 2022-01-18T13:56:37.000Z | test/validation/point_polygon_b_test.exs | codabrink/topo | f1ca4b7fe337a67285ee4c65a34fb521b119342c | [
"MIT"
] | 24 | 2016-09-19T20:06:50.000Z | 2021-06-16T06:41:10.000Z | defmodule Intersect.Validation.PointPolygonBTest do
use ExUnit.Case
@tag :validation
test "11-001 - PA - point contained in simple polygon" do
a = "POINT (100 100)" |> Geo.WKT.decode!()
b = "POLYGON ((50 50, 200 50, 200 200, 50 200, 50 50))" |> Geo.WKT.decode!()
assert Topo.intersects?(a, b) == true
assert Topo.intersects?(b, a) == true
assert Topo.disjoint?(a, b) == false
assert Topo.disjoint?(b, a) == false
assert Topo.contains?(a, b) == false
assert Topo.within?(a, b) == true
assert Topo.equals?(a, b) == false
assert Topo.equals?(b, a) == false
end
@tag :validation
test "11-001 - PA - point contained in simple polygon (float)" do
a = "POINT(100.0 100.0)" |> Geo.WKT.decode!()
b = "POLYGON((50.0 50.0,200.0 50.0,200.0 200.0,50.0 200.0,50.0 50.0))" |> Geo.WKT.decode!()
assert Topo.intersects?(a, b) == true
assert Topo.intersects?(b, a) == true
assert Topo.disjoint?(a, b) == false
assert Topo.disjoint?(b, a) == false
assert Topo.contains?(a, b) == false
assert Topo.within?(a, b) == true
assert Topo.equals?(a, b) == false
assert Topo.equals?(b, a) == false
end
@tag :validation
test "11-002 - mPmA - points on I, B and E of touching triangles" do
a =
"MULTIPOLYGON (((120 320, 180 200, 240 320, 120 320)),((180 200, 240 80, 300 200, 180 200)))"
|> Geo.WKT.decode!()
b = "MULTIPOINT (120 320, 180 260, 180 320, 180 200, 300 200, 200 220)" |> Geo.WKT.decode!()
assert Topo.intersects?(a, b) == true
assert Topo.intersects?(b, a) == true
assert Topo.disjoint?(a, b) == false
assert Topo.disjoint?(b, a) == false
assert Topo.contains?(a, b) == false
assert Topo.within?(a, b) == false
assert Topo.equals?(a, b) == false
assert Topo.equals?(b, a) == false
end
@tag :validation
test "11-002 - mPmA - points on I, B and E of touching triangles (float)" do
a =
"MULTIPOLYGON(((120.0 320.0,180.0 200.0,240.0 320.0,120.0 320.0)),((180.0 200.0,240.0 80.0,300.0 200.0,180.0 200.0)))"
|> Geo.WKT.decode!()
b =
"MULTIPOINT(120.0 320.0,180.0 260.0,180.0 320.0,180.0 200.0,300.0 200.0,200.0 220.0)"
|> Geo.WKT.decode!()
assert Topo.intersects?(a, b) == true
assert Topo.intersects?(b, a) == true
assert Topo.disjoint?(a, b) == false
assert Topo.disjoint?(b, a) == false
assert Topo.contains?(a, b) == false
assert Topo.within?(a, b) == false
assert Topo.equals?(a, b) == false
assert Topo.equals?(b, a) == false
end
@tag :validation
test "11-003 - mPmA - points on I, B and E of concentric doughnuts" do
a =
"MULTIPOLYGON (((120 80, 420 80, 420 340, 120 340, 120 80),(160 300, 160 120, 380 120, 380 300, 160 300)),((200 260, 200 160, 340 160, 340 260, 200 260),(240 220, 240 200, 300 200, 300 220, 240 220)))"
|> Geo.WKT.decode!()
b =
"MULTIPOINT (200 360, 420 340, 400 100, 340 120, 200 140, 200 160, 220 180, 260 200, 200 360, 420 340, 400 100, 340 120, 200 140, 200 160, 220 180, 260 200)"
|> Geo.WKT.decode!()
assert Topo.intersects?(a, b) == true
assert Topo.intersects?(b, a) == true
assert Topo.disjoint?(a, b) == false
assert Topo.disjoint?(b, a) == false
assert Topo.contains?(a, b) == false
assert Topo.within?(a, b) == false
assert Topo.equals?(a, b) == false
assert Topo.equals?(b, a) == false
end
@tag :validation
test "11-003 - mPmA - points on I, B and E of concentric doughnuts (float)" do
a =
"MULTIPOLYGON(((120.0 80.0,420.0 80.0,420.0 340.0,120.0 340.0,120.0 80.0),(160.0 300.0,160.0 120.0,380.0 120.0,380.0 300.0,160.0 300.0)),((200.0 260.0,200.0 160.0,340.0 160.0,340.0 260.0,200.0 260.0),(240.0 220.0,240.0 200.0,300.0 200.0,300.0 220.0,240.0 220.0)))"
|> Geo.WKT.decode!()
b =
"MULTIPOINT(200.0 360.0,420.0 340.0,400.0 100.0,340.0 120.0,200.0 140.0,200.0 160.0,220.0 180.0,260.0 200.0,200.0 360.0,420.0 340.0,400.0 100.0,340.0 120.0,200.0 140.0,200.0 160.0,220.0 180.0,260.0 200.0)"
|> Geo.WKT.decode!()
assert Topo.intersects?(a, b) == true
assert Topo.intersects?(b, a) == true
assert Topo.disjoint?(a, b) == false
assert Topo.disjoint?(b, a) == false
assert Topo.contains?(a, b) == false
assert Topo.within?(a, b) == false
assert Topo.equals?(a, b) == false
assert Topo.equals?(b, a) == false
end
end
| 39.303571 | 270 | 0.604271 |
790f11be9f5c09a43bc91c5ca81c66920bbb90a4 | 22,346 | exs | Elixir | test/myxql_test.exs | maartenvanvliet/myxql | 70629ac855cd7bf9a5dbaa3a1a828a7da68c15e6 | [
"Apache-2.0"
] | null | null | null | test/myxql_test.exs | maartenvanvliet/myxql | 70629ac855cd7bf9a5dbaa3a1a828a7da68c15e6 | [
"Apache-2.0"
] | null | null | null | test/myxql_test.exs | maartenvanvliet/myxql | 70629ac855cd7bf9a5dbaa3a1a828a7da68c15e6 | [
"Apache-2.0"
] | 1 | 2022-02-01T15:13:09.000Z | 2022-02-01T15:13:09.000Z | defmodule MyXQLTest do
use ExUnit.Case, async: true
import ExUnit.CaptureLog
@opts TestHelper.opts()
describe "connect" do
@tag ssl: true
test "connect with bad SSL opts" do
assert capture_log(fn ->
opts = [ssl: true, ssl_opts: [ciphers: [:bad]]] ++ @opts
assert_start_and_killed(opts)
end) =~ "** (DBConnection.ConnectionError) Invalid TLS option: {ciphers,[bad]}"
end
test "connect with host down" do
assert capture_log(fn ->
opts = [port: 9999] ++ @opts
assert_start_and_killed(opts)
end) =~ "(DBConnection.ConnectionError) connection refused"
end
@tag requires_otp_19: true
test "connect using default protocol (:socket)" do
opts =
@opts
|> Keyword.delete(:hostname)
|> Keyword.delete(:port)
|> Keyword.delete(:socket)
{:ok, conn} = MyXQL.start_link(opts)
MyXQL.query!(conn, "SELECT 1")
end
@tag requires_otp_19: true
test "connect using UNIX domain socket" do
socket = System.get_env("MYSQL_UNIX_PORT") || "/tmp/mysql.sock"
opts =
@opts
|> Keyword.delete(:port)
|> Keyword.put(:hostname, "intentionally_bad_host")
|> Keyword.merge(socket: socket)
{:ok, conn} = MyXQL.start_link(opts)
MyXQL.query!(conn, "SELECT 1")
end
@tag requires_otp_19: true
test "connect using bad UNIX domain socket" do
opts =
@opts
|> Keyword.delete(:hostname)
|> Keyword.delete(:port)
|> Keyword.merge(socket: "/bad")
assert capture_log(fn ->
assert_start_and_killed(opts)
end) =~ "** (DBConnection.ConnectionError) no such file or directory \"/bad\""
end
@tag capture_log: true
test "connect with SSL but without starting :ssl" do
Application.stop(:ssl)
assert_raise RuntimeError,
~r"cannot be established because `:ssl` application is not started",
fn ->
opts = [ssl: true] ++ @opts
MyXQL.start_link(opts)
end
after
Application.ensure_all_started(:ssl)
end
test "custom socket options" do
opts = [socket_options: [buffer: 4]] ++ @opts
{:ok, conn} = MyXQL.start_link(opts)
MyXQL.query!(conn, "SELECT 1, 2, NOW()")
MyXQL.prepare_execute!(conn, "", "SELECT 1, 2, NOW()")
end
test "after_connect callback" do
pid = self()
opts = [after_connect: fn conn -> send(pid, {:connected, conn}) end] ++ @opts
MyXQL.start_link(opts)
assert_receive {:connected, _}
end
test "handshake timeout" do
%{port: port} =
start_fake_server(fn _ ->
Process.sleep(:infinity)
end)
opts = [port: port, handshake_timeout: 5] ++ @opts
assert capture_log(fn ->
assert_start_and_killed(opts)
end) =~ "timed out because it was handshaking for longer than 5ms"
end
end
describe "query" do
setup [:connect, :truncate]
test "default to binary protocol", c do
self = self()
{:ok, _} = MyXQL.query(c.conn, "SELECT 42", [], log: &send(self, &1))
assert_received %DBConnection.LogEntry{} = entry
assert %MyXQL.Query{} = entry.query
end
test "binary: query with params", c do
assert {:ok, %MyXQL.Result{rows: [[6]]}} = MyXQL.query(c.conn, "SELECT ? * ?", [2, 3])
end
test "binary: iodata", c do
statement = ["SELECT", [" ", ["42"]]]
assert {:ok, %{rows: [[42]]}} =
MyXQL.query(c.conn, statement, [], query_type: :binary, log: &send(self(), &1))
assert_received %DBConnection.LogEntry{} = entry
assert %MyXQL.Query{} = entry.query
end
test "text: iodata", c do
statement = ["SELECT", [" ", ["42"]]]
assert {:ok, %{rows: [[42]]}} =
MyXQL.query(c.conn, statement, [], query_type: :text, log: &send(self(), &1))
assert_received %DBConnection.LogEntry{} = entry
assert %MyXQL.TextQuery{} = entry.query
end
test "non preparable statement", c do
self = self()
log = &send(self, &1)
assert {:ok, %MyXQL.Result{}} =
MyXQL.query(c.conn, "BEGIN", [], query_type: :text, log: log)
assert_receive %DBConnection.LogEntry{query: %MyXQL.TextQuery{}}
assert {:error, %MyXQL.Error{mysql: %{code: 1295, name: :ER_UNSUPPORTED_PS}}} =
MyXQL.query(c.conn, "BEGIN", [], query_type: :binary, log: log)
assert_receive %DBConnection.LogEntry{query: %MyXQL.Query{}}
assert {:ok, %MyXQL.Result{}} =
MyXQL.query(c.conn, "BEGIN", [], query_type: :binary_then_text, log: log)
assert_receive %DBConnection.LogEntry{query: %MyXQL.Query{}}
end
for protocol <- [:binary, :text] do
@protocol protocol
test "#{@protocol}: invalid query", c do
assert {:error, %MyXQL.Error{mysql: %{name: :ER_BAD_FIELD_ERROR}}} =
MyXQL.query(c.conn, "SELECT bad", [], query_type: @protocol)
end
test "#{@protocol}: query with multiple rows", c do
%MyXQL.Result{num_rows: 2} =
MyXQL.query!(c.conn, "INSERT INTO integers VALUES (10), (20)", [], query_type: @protocol)
assert {:ok, %MyXQL.Result{columns: ["x"], rows: [[10], [20]]}} =
MyXQL.query(c.conn, "SELECT * FROM integers")
end
test "#{@protocol}: many rows", c do
num = 10_000
values = Enum.map_join(1..num, ", ", &"(#{&1})")
result =
MyXQL.query!(c.conn, "INSERT INTO integers VALUES " <> values, [], query_type: @protocol)
assert result.num_rows == num
result = MyXQL.query!(c.conn, "SELECT x FROM integers")
assert List.flatten(result.rows) == Enum.to_list(1..num)
assert result.num_rows == num
end
end
end
describe "prepared queries" do
setup [:connect, :truncate]
test "prepare_execute", c do
assert {:ok, %MyXQL.Query{}, %MyXQL.Result{rows: [[6]]}} =
MyXQL.prepare_execute(c.conn, "", "SELECT ? * ?", [2, 3])
end
test "prepare and then execute", c do
{:ok, query} = MyXQL.prepare(c.conn, "", "SELECT ? * ?")
assert query.num_params == 2
assert {:ok, _, %MyXQL.Result{rows: [[6]]}} = MyXQL.execute(c.conn, query, [2, 3])
end
test "query is re-prepared if executed after being closed", c do
{:ok, query1} = MyXQL.prepare(c.conn, "", "SELECT 42")
assert {:ok, _, %MyXQL.Result{rows: [[42]]}} = MyXQL.execute(c.conn, query1, [])
:ok = MyXQL.close(c.conn, query1)
assert {:ok, query2, %MyXQL.Result{rows: [[42]]}} = MyXQL.execute(c.conn, query1, [])
assert query1.ref == query2.ref
assert query1.statement_id != query2.statement_id
end
test "query is re-prepared if executed from different connection", c do
conn1 = c.conn
{:ok, query1} = MyXQL.prepare(conn1, "", "SELECT 42")
{:ok, conn2} = MyXQL.start_link(@opts)
{:ok, query2, %{rows: [[42]]}} = MyXQL.execute(conn2, query1, [])
assert query1.ref == query2.ref
assert query1.statement_id != query2.statement_id
end
# This test is just describing existing behaviour, we may want to change it in the future.
test "prepared query is not re-prepared after schema change", c do
MyXQL.query!(c.conn, "CREATE TABLE test_prepared_schema_change (x integer)")
MyXQL.query!(c.conn, "INSERT INTO test_prepared_schema_change VALUES (1)")
{:ok, query} = MyXQL.prepare(c.conn, "", "SELECT * FROM test_prepared_schema_change")
MyXQL.query!(c.conn, "ALTER TABLE test_prepared_schema_change ADD y integer DEFAULT 2")
{:ok, query2, result} = MyXQL.execute(c.conn, query, [])
assert result.rows == [[1, 2]]
assert query.ref == query2.ref
after
MyXQL.query!(c.conn, "DROP TABLE IF EXISTS test_prepared_schema_change")
end
test "query not properly prepared", c do
assert_raise ArgumentError, ~r"has not been prepared", fn ->
query = %MyXQL.Query{statement: "SELECT 1", ref: nil, num_params: 0}
MyXQL.execute(c.conn, query, [])
end
assert_raise ArgumentError, ~r"has not been prepared", fn ->
query = %MyXQL.Query{statement: "SELECT 1", ref: make_ref(), num_params: nil}
MyXQL.execute(c.conn, query, [])
end
end
test "invalid params", c do
assert_raise ArgumentError, ~r"expected params count: 2, got values: \[1\]", fn ->
MyXQL.query(c.conn, "SELECT ? * ?", [1])
end
end
test "graceful handling of encode errors", c do
assert_raise Jason.EncodeError, fn ->
MyXQL.query!(c.conn, "SELECT ?", [%{a: <<232>>}])
end
assert_raise Jason.EncodeError, fn ->
MyXQL.query!(c.conn, "SELECT ?", [%{a: <<232>>}])
end
end
test "many rows", c do
num = 10_000
values = Enum.map_join(1..num, ", ", &"(#{&1})")
result = MyXQL.query!(c.conn, "INSERT INTO integers VALUES " <> values)
assert result.num_rows == num
{_query, result} = MyXQL.prepare_execute!(c.conn, "", "SELECT x FROM integers")
assert List.flatten(result.rows) == Enum.to_list(1..num)
assert result.num_rows == num
end
test "named and unnamed queries" do
# {:ok, pid} = MyXQL.start_link(@opts ++ [prepare: :named])
# {:ok, query} = MyXQL.prepare(pid, "1", "SELECT 1")
# {:ok, query2, _} = MyXQL.execute(pid, query, [])
# assert query == query2
# {:ok, query3, _} = MyXQL.execute(pid, query, [])
# assert query == query3
# # unnamed queries are closed
# {:ok, query} = MyXQL.prepare(pid, "", "SELECT 1")
# {:ok, query2, _} = MyXQL.execute(pid, query, [])
# assert query == query2
# {:ok, query3, _} = MyXQL.execute(pid, query, [])
# assert query2.ref == query3.ref
# assert query2.statement_id != query3.statement_id
{:ok, pid} = MyXQL.start_link(@opts ++ [prepare: :unnamed])
{:ok, query} = MyXQL.prepare(pid, "1", "SELECT 1")
{:ok, query2, _} = MyXQL.execute(pid, query, [])
assert query == query2
{:ok, query3, _} = MyXQL.execute(pid, query, [])
assert query2.ref == query3.ref
assert query2.statement_id != query3.statement_id
end
test "statement cache", c do
self = self()
MyXQL.query!(c.conn, "SELECT 1024", [], cache_statement: "select1024", log: &send(self, &1))
assert_receive %DBConnection.LogEntry{} = entry
{:ok, query1, _result} = entry.result
MyXQL.query!(c.conn, "SELECT 1024", [], cache_statement: "select1024", log: &send(self, &1))
assert_receive %DBConnection.LogEntry{} = entry
{:ok, query2, _result} = entry.result
assert query2.statement_id == query1.statement_id
end
test "disconnect on errors" do
Process.flag(:trap_exit, true)
{:ok, pid} = MyXQL.start_link([disconnect_on_error_codes: [:ER_DUP_ENTRY]] ++ @opts)
assert capture_log(fn ->
MyXQL.transaction(pid, fn conn ->
MyXQL.query(conn, "INSERT INTO uniques VALUES (1), (1)")
assert_receive {:EXIT, ^pid, :killed}, 500
end)
end) =~ "disconnected: ** (MyXQL.Error) (1062) (ER_DUP_ENTRY)"
end
end
describe "transactions" do
setup [:connect, :truncate]
test "commit", c do
assert %MyXQL.Result{rows: [[0]]} = MyXQL.query!(c.conn, "SELECT COUNT(1) FROM integers")
self = self()
{:ok, :success} =
MyXQL.transaction(
c.conn,
fn conn ->
MyXQL.query!(conn, "INSERT INTO integers VALUES (10)", [], log: &send(self(), &1))
MyXQL.query!(conn, "INSERT INTO integers VALUES (20)", [], log: &send(self(), &1))
:success
end,
log: &send(self, &1)
)
assert %MyXQL.Result{rows: [[2]]} = MyXQL.query!(c.conn, "SELECT COUNT(1) FROM integers")
assert_receive %DBConnection.LogEntry{} = begin_entry
assert_receive %DBConnection.LogEntry{} = query1_entry
assert_receive %DBConnection.LogEntry{} = query2_entry
assert_receive %DBConnection.LogEntry{} = commit_entry
assert begin_entry.call == :begin
assert begin_entry.query == :begin
assert {:ok, _, %MyXQL.Result{}} = begin_entry.result
assert query1_entry.call == :prepare_execute
assert query2_entry.call == :prepare_execute
assert commit_entry.call == :commit
assert commit_entry.query == :commit
assert {:ok, %MyXQL.Result{}} = commit_entry.result
end
test "rollback", c do
self = self()
assert %MyXQL.Result{rows: [[0]]} = MyXQL.query!(c.conn, "SELECT COUNT(1) FROM integers")
reason = make_ref()
{:error, ^reason} =
MyXQL.transaction(
c.conn,
fn conn ->
MyXQL.query!(conn, "INSERT INTO integers VALUES (10)", [], log: &send(self, &1))
MyXQL.rollback(conn, reason)
end,
log: &send(self(), &1)
)
assert %MyXQL.Result{rows: [[0]]} = MyXQL.query!(c.conn, "SELECT COUNT(1) FROM integers")
assert_receive %DBConnection.LogEntry{} = begin_entry
assert_receive %DBConnection.LogEntry{} = query_entry
assert_receive %DBConnection.LogEntry{} = rollback_entry
assert begin_entry.call == :begin
assert begin_entry.query == :begin
assert query_entry.call == :prepare_execute
assert rollback_entry.call == :rollback
assert rollback_entry.query == :rollback
end
test "status", c do
MyXQL.query!(c.conn, "SELECT 1")
assert DBConnection.status(c.conn) == :idle
reason = make_ref()
{:error, ^reason} =
MyXQL.transaction(c.conn, fn conn ->
assert DBConnection.status(conn) == :transaction
assert {:error, %MyXQL.Error{mysql: %{name: :ER_DUP_ENTRY}}} =
MyXQL.query(conn, "INSERT INTO uniques VALUES (1), (1)")
MyXQL.rollback(conn, reason)
end)
assert DBConnection.status(c.conn) == :idle
MyXQL.query!(c.conn, "SELECT 1")
end
end
describe "stream" do
setup [:connect, :truncate]
test "empty", c do
{:ok, results} =
MyXQL.transaction(c.conn, fn conn ->
stream = MyXQL.stream(conn, "SELECT * FROM integers")
Enum.to_list(stream)
end)
assert [
%{rows: [], num_rows: 0},
%{rows: [], num_rows: 0}
] = results
# try again for the same query
{:ok, results} =
MyXQL.transaction(c.conn, fn conn ->
stream = MyXQL.stream(conn, "SELECT * FROM integers")
Enum.to_list(stream)
end)
assert [
%{rows: [], num_rows: 0},
%{rows: [], num_rows: 0}
] = results
end
test "few rows", c do
MyXQL.query!(c.conn, "INSERT INTO integers VALUES (1), (2), (3), (4), (5)")
{:ok, results} =
MyXQL.transaction(c.conn, fn conn ->
stream = MyXQL.stream(conn, "SELECT * FROM integers", [], max_rows: 2)
Enum.to_list(stream)
end)
assert [
%{rows: [], num_rows: 0},
%{rows: [[1], [2]]},
%{rows: [[3], [4]]},
%{rows: [[5]]}
] = results
end
test "few rows with no leftovers", c do
MyXQL.query!(c.conn, "INSERT INTO integers VALUES (1), (2), (3), (4)")
{:ok, results} =
MyXQL.transaction(c.conn, fn conn ->
stream = MyXQL.stream(conn, "SELECT * FROM integers", [], max_rows: 2)
Enum.to_list(stream)
end)
assert [
%{rows: [], num_rows: 0},
%{rows: [[1], [2]]},
%{rows: [[3], [4]]},
%{rows: []}
] = results
end
test "many rows", c do
num = 10_000
values = Enum.map_join(1..10_000, ", ", &"(#{&1})")
MyXQL.query!(c.conn, "INSERT INTO integers VALUES " <> values)
{:ok, results} =
MyXQL.transaction(c.conn, fn conn ->
stream = MyXQL.stream(conn, "SELECT * FROM integers")
Enum.to_list(stream)
end)
[first | results] = results
assert %{rows: [], num_rows: 0} = first
assert length(results) == 21
assert results |> Enum.map(& &1.rows) |> List.flatten() == Enum.to_list(1..num)
end
test "multiple streams", c do
MyXQL.query!(c.conn, "INSERT INTO integers VALUES (1), (2), (3), (4), (5)")
{:ok, results} =
MyXQL.transaction(c.conn, fn conn ->
odd =
MyXQL.stream(conn, "SELECT * FROM integers WHERE x % 2 != 0", [], max_rows: 2)
|> Stream.flat_map(& &1.rows)
even =
MyXQL.stream(conn, "SELECT * FROM integers WHERE x % 2 = 0", [], max_rows: 2)
|> Stream.flat_map(& &1.rows)
Enum.zip(odd, even)
end)
assert results == [{[1], [2]}, {[3], [4]}]
end
test "bad query", c do
assert_raise MyXQL.Error, ~r"\(1054\) \(ER_BAD_FIELD_ERROR\)", fn ->
MyXQL.transaction(c.conn, fn conn ->
stream = MyXQL.stream(conn, "SELECT bad")
Enum.to_list(stream)
end)
end
end
test "invalid params", c do
assert_raise ArgumentError, ~r"expected params count: 2, got values: \[1\]", fn ->
MyXQL.transaction(c.conn, fn conn ->
stream = MyXQL.stream(conn, "SELECT ? * ?", [1])
Enum.to_list(stream)
end)
end
end
test "with prepared query", c do
MyXQL.query!(c.conn, "INSERT INTO integers VALUES (1), (2), (3), (4), (5)")
{:ok, query} = MyXQL.prepare(c.conn, "", "SELECT * FROM integers")
{:ok, result} =
MyXQL.transaction(c.conn, fn conn ->
stream = MyXQL.stream(conn, query, [], max_rows: 2)
Enum.to_list(stream)
end)
assert [
%{rows: [], num_rows: 0},
%{rows: [[1], [2]]},
%{rows: [[3], [4]]},
%{rows: [[5]]}
] = result
end
test "on another connection", c do
MyXQL.query!(c.conn, "INSERT INTO integers VALUES (1), (2), (3), (4), (5)")
{:ok, query} = MyXQL.prepare(c.conn, "", "SELECT * FROM integers")
{:ok, conn2} = MyXQL.start_link(@opts)
{:ok, results} =
MyXQL.transaction(conn2, fn conn ->
MyXQL.stream(conn, query) |> Enum.to_list()
end)
assert [
%{rows: [], num_rows: 0},
%{rows: [[1], [2], [3], [4], [5]]}
] = results
end
end
describe "stored procedures" do
setup :connect
test "text query", c do
assert %MyXQL.Result{rows: [[1]]} =
MyXQL.query!(c.conn, "CALL single_procedure()", [], query_type: :text)
assert %MyXQL.Result{rows: [[1]]} =
MyXQL.query!(c.conn, "CALL single_procedure()", [], query_type: :text)
assert_raise RuntimeError, "returning multiple results is not yet supported", fn ->
assert %MyXQL.Result{rows: [[1]]} = MyXQL.query!(c.conn, "CALL multi_procedure()")
end
end
test "prepared query", c do
assert {_, %MyXQL.Result{rows: [[1]]}} =
MyXQL.prepare_execute!(c.conn, "", "CALL single_procedure()")
assert {_, %MyXQL.Result{rows: [[1]]}} =
MyXQL.prepare_execute!(c.conn, "", "CALL single_procedure()")
assert_raise RuntimeError, "returning multiple results is not yet supported", fn ->
MyXQL.prepare_execute!(c.conn, "", "CALL multi_procedure()")
end
end
test "stream procedure with single result", c do
statement = "CALL single_procedure()"
{:ok, result} =
MyXQL.transaction(c.conn, fn conn ->
stream = MyXQL.stream(conn, statement, [], max_rows: 2)
Enum.to_list(stream)
end)
assert [%MyXQL.Result{rows: [[1]]}] = result
end
test "stream procedure with multiple results", c do
statement = "CALL multi_procedure()"
assert_raise RuntimeError, "returning multiple results is not yet supported", fn ->
MyXQL.transaction(c.conn, fn conn ->
stream = MyXQL.stream(conn, statement, [], max_rows: 2)
Enum.to_list(stream)
end)
end
end
end
@tag :skip
describe "idle ping" do
test "query before and after" do
opts = [backoff_type: :stop, idle_interval: 1] ++ @opts
{:ok, pid} = MyXQL.start_link(opts)
assert {:ok, _} = MyXQL.query(pid, "SELECT 42")
Process.sleep(5)
assert {:ok, _} = MyXQL.query(pid, "SELECT 42")
Process.sleep(5)
assert {:ok, _} = MyXQL.query(pid, "SELECT 42")
end
test "socket receive timeout" do
Process.flag(:trap_exit, true)
opts = [backoff_type: :stop, idle_interval: 1, ping_timeout: 0] ++ @opts
{:ok, pid} = MyXQL.start_link(opts)
assert capture_log(fn ->
assert_receive {:EXIT, ^pid, :killed}, 500
end) =~ "disconnected: ** (DBConnection.ConnectionError) timeout"
end
end
test "warnings" do
after_connect = fn conn ->
MyXQL.query!(conn, "SET SESSION sql_mode = 'ERROR_FOR_DIVISION_BY_ZERO'")
end
{:ok, conn} = MyXQL.start_link([after_connect: after_connect] ++ @opts)
assert %MyXQL.Result{num_warnings: 1, rows: [[nil]]} = MyXQL.query!(conn, "SELECT 1/0")
end
defp assert_start_and_killed(opts) do
Process.flag(:trap_exit, true)
case MyXQL.start_link(opts) do
{:ok, pid} -> assert_receive {:EXIT, ^pid, :killed}, 500
{:error, :killed} -> :ok
end
end
defp connect(c) do
{:ok, conn} = MyXQL.start_link(@opts)
Map.put(c, :conn, conn)
end
defp truncate(c) do
MyXQL.query!(c.conn, "TRUNCATE TABLE integers")
c
end
defp start_fake_server(fun) do
{:ok, listen_socket} = :gen_tcp.listen(0, mode: :binary, active: false)
{:ok, port} = :inet.port(listen_socket)
{:ok, pid} =
Task.start_link(fn ->
{:ok, accept_socket} = :gen_tcp.accept(listen_socket)
fun.(%{accept_socket: accept_socket, listen_socket: listen_socket})
end)
%{pid: pid, port: port}
end
end
| 32.33864 | 99 | 0.569319 |
790f182e2de13f88cb24d2a063114572be1361a8 | 1,638 | ex | Elixir | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/seller.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/seller.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v14/model/seller.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.AdExchangeBuyer.V14.Model.Seller do
@moduledoc """
## Attributes
* `accountId` (*type:* `String.t`, *default:* `nil`) - The unique id for the seller. The seller fills in this field. The seller account id is then available to buyer in the product.
* `subAccountId` (*type:* `String.t`, *default:* `nil`) - Optional sub-account id for the seller.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:accountId => String.t(),
:subAccountId => String.t()
}
field(:accountId)
field(:subAccountId)
end
defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V14.Model.Seller do
def decode(value, options) do
GoogleApi.AdExchangeBuyer.V14.Model.Seller.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V14.Model.Seller do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.76 | 185 | 0.725275 |
790f494e7f38cf161e6318e6d7239a9f4c64a58a | 1,538 | ex | Elixir | lib/fish_web/views/error_helpers.ex | wdiechmann/fish | b63fe109bbfc1cbe515ac31f9adcd9b57c6b21c8 | [
"MIT"
] | 1 | 2021-02-09T23:49:40.000Z | 2021-02-09T23:49:40.000Z | lib/fish_web/views/error_helpers.ex | wdiechmann/fish | b63fe109bbfc1cbe515ac31f9adcd9b57c6b21c8 | [
"MIT"
] | null | null | null | lib/fish_web/views/error_helpers.ex | wdiechmann/fish | b63fe109bbfc1cbe515ac31f9adcd9b57c6b21c8 | [
"MIT"
] | null | null | null | defmodule FishWeb.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: "invalid-feedback",
phx_feedback_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(FishWeb.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(FishWeb.Gettext, "errors", msg, opts)
end
end
end
| 32.041667 | 73 | 0.663199 |
790f545c28dcd64076e21dc36da1b84757e098c6 | 6,292 | ex | Elixir | lib/result/helpers.ex | joevandyk/result | b516f0440ca41f0a68fbd2f66064b1bca70bd1d9 | [
"MIT"
] | null | null | null | lib/result/helpers.ex | joevandyk/result | b516f0440ca41f0a68fbd2f66064b1bca70bd1d9 | [
"MIT"
] | null | null | null | lib/result/helpers.ex | joevandyk/result | b516f0440ca41f0a68fbd2f66064b1bca70bd1d9 | [
"MIT"
] | null | null | null | defmodule Brex.Result.Helpers do
@moduledoc """
Tools for modifying the reason in `error` tuples.
"""
import Brex.Result.Base
alias Brex.Result.Base
require Logger
@type s(x) :: Base.s(x)
@type t(x) :: Base.t(x)
@type p() :: Base.p()
@type s() :: Base.s()
@type t() :: Base.t()
@doc """
Wraps a naked `:error` atom in a tuple with the given reason.
Leaves success values and `error` tuples unchanged.
## Examples:
iex> :error
...> |> normalize_error(:parsing_failure)
{:error, :parsing_failure}
iex> {:ok, 2}
...> |> normalize_error()
{:ok, 2}
"""
@doc since: "0.3.0"
@spec normalize_error(any, any) :: t()
def normalize_error(x, reason \\ :normalized) do
case x do
:error -> {:error, reason}
{:error, _r} -> x
{:ok, _val} -> x
:ok -> :ok
end
end
@doc """
Lifts a value into a success tuple unless:
1) the value matches the second argument
2) when applied to the value, the second argument function returns `true`
In those cases an `error` tuple is returned with either
1) the third argument as the reason
2) the third argument function applied to the value, as the reason
`lift/3` is lazy, this means third argument will only be evaluated when necessary.
## Examples:
iex> nil
...> |> lift(nil, :not_found)
{:error, :not_found}
iex> 2
...> |> lift(nil, :not_found)
{:ok, 2}
iex> "test"
...> |> lift(&(&1 == "test"), fn x -> {:oops, x <> "ed"} end)
{:error, {:oops, "tested"}}
## Typespec:
lift(a | b, b | (a | b -> boolean), c | (a | b -> c)) :: s(a) when a: var, b: var, c: var
"""
@doc updated: "0.2.0"
@doc since: "0.1.0"
defmacro lift(val, p, f) do
quote do
p = unquote(p)
val = unquote(val)
# check if the value passes satisfies the predicate or matches the second argument.
match = if is_function(p), do: p.(val), else: val == p
if match do
f = unquote(f)
# lift to error tuple on match
{:error, if(is_function(f), do: f.(val), else: f)}
else
# ok tuple otherwise
{:ok, val}
end
end
end
@doc """
Applies the function to the reason in an `error` tuple.
Leaves success unchanged.
## Example:
iex> account_name = "test"
...> {:error, :not_found}
...> |> map_error(fn r -> {r, account_name} end)
{:error, {:not_found, "test"}}
"""
@doc since: "0.1.0"
@spec map_error(t(a), (any -> any)) :: t(a) when a: var
def map_error({:error, r}, f), do: error(f.(r))
def map_error({:ok, _val} = ma, _), do: ma
def map_error(:ok, _), do: :ok
@doc """
Replaces the reason in an `error` tuple.
Leaves success unchanged.
Lazy. Only evaluates the second argument if necessary.
## Example:
iex> account_name = "test"
...> {:error, :not_found}
...> |> mask_error({:nonexistent_account, account_name})
{:error, {:nonexistent_account, "test"}}
## Typespec:
mask_error(t(a), any) :: t(a) when a: var
"""
@doc updated: "0.2.0"
@doc since: "0.1.0"
defmacro mask_error(ma, term) do
quote do
case unquote(ma) do
{:error, _} -> {:error, unquote(term)}
{:ok, val} -> {:ok, val}
:ok -> :ok
end
end
end
@doc """
Logs on `error`, does nothing on success.
## Example:
{:error, :not_found}
|> log_error("There was an error", level: :info, metadata: "some meta")
"""
@doc updated: "0.2.0"
@doc since: "0.1.0"
# TODO: refine the type of second argument
@spec log_error(t(a), String.t() | (any -> any), Keyword.t()) :: t(a) when a: var
def log_error(ma, chardata_or_fun, opts \\ [])
def log_error({:error, r} = ma, chardata_or_fun, opts) when is_binary(chardata_or_fun) do
# default to :error level
{level, metadata} = Keyword.pop(opts, :level, :error)
log_fn =
case level do
:debug -> &Logger.debug/2
:info -> &Logger.info/2
:warn -> &Logger.warn/2
:error -> &Logger.error/2
end
log_fn.(chardata_or_fun, [reason: "#{r}"] ++ metadata)
ma
end
def log_error({:ok, _val} = ma, _, _), do: ma
def log_error(:ok, _, _), do: :ok
@doc """
Converts a matching error to `:ok`
An error matches if the reason is equal to the supplied atom or the reason passes the predicate.
Leaves success and other errors unchanged.
## Examples:
iex> {:error, :already_completed}
...> |> convert_error(:already_completed)
:ok
iex> {:error, :already_completed}
...> |> convert_error(fn r -> r == :already_completed end)
:ok
"""
@doc updated: "0.2.0"
@doc since: "0.1.0"
@spec convert_error(t(a), (any -> boolean) | any) :: t(a) when a: var
def convert_error({:error, r} = ma, p) when is_function(p) do
if p.(r), do: :ok, else: ma
end
def convert_error({:error, r} = ma, term) do
if r == term, do: :ok, else: ma
end
def convert_error({:ok, _val} = ma, _p), do: ma
def convert_error(:ok, _p), do: :ok
@doc """
Converts a matching error to a success with the given value or function.
An error matches if the reason is equal to the supplied atom or the reason passes the predicate.
Leaves success and other errors unchanged.
Lazy. Only evaluates the second argument if necessary.
## Examples:
iex> {:error, :already_completed}
...> |> convert_error(:already_completed, "submitted")
{:ok, "submitted"}
iex> {:error, "test"}
...> |> convert_error(&(&1 == "test"), fn r -> {:ok, r <> "ed"} end)
{:ok, "tested"}
## Typespec:
convert_error(t(), (any -> boolean) | any, b | (any -> t(b))) :: t(b) when b: var
"""
@doc updated: "0.2.0"
@doc since: "0.1.0"
defmacro convert_error(ma, p, f) do
quote do
ma = unquote(ma)
p = unquote(p)
case ma do
{:error, r} ->
match = if is_function(p), do: p.(r), else: r == p
if match do
f = unquote(f)
# convert to ok tuple with new value.
if is_function(f), do: f.(r), else: {:ok, f}
else
ma
end
{:ok, _v} ->
ma
:ok ->
ma
end
end
end
end
| 24.771654 | 98 | 0.561189 |
790f67bcf8d0a947f3bd25aa593474a261c2473d | 2,569 | ex | Elixir | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/route_condition.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/route_condition.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/route_condition.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudRun.V1alpha1.Model.RouteCondition do
@moduledoc """
RouteCondition defines a readiness condition for a Route.
## Attributes
* `lastTransitionTime` (*type:* `DateTime.t`, *default:* `nil`) - Last time the condition transitioned from one status to another. +optional
* `message` (*type:* `String.t`, *default:* `nil`) - Human-readable message indicating details about last transition. +optional
* `reason` (*type:* `String.t`, *default:* `nil`) - One-word CamelCase reason for the condition's last transition. +optional
* `severity` (*type:* `String.t`, *default:* `nil`) - How to interpret failures of this condition, one of Error, Warning, Info +optional
* `status` (*type:* `String.t`, *default:* `nil`) - Status of the condition, one of "True", "False", "Unknown".
* `type` (*type:* `String.t`, *default:* `nil`) - RouteConditionType is used to communicate the status of the reconciliation process. See also: https://github.com/knative/serving/blob/master/docs/spec/errors.md#error-conditions-and-reporting Types include: "Ready".
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:lastTransitionTime => DateTime.t(),
:message => String.t(),
:reason => String.t(),
:severity => String.t(),
:status => String.t(),
:type => String.t()
}
field(:lastTransitionTime, as: DateTime)
field(:message)
field(:reason)
field(:severity)
field(:status)
field(:type)
end
defimpl Poison.Decoder, for: GoogleApi.CloudRun.V1alpha1.Model.RouteCondition do
def decode(value, options) do
GoogleApi.CloudRun.V1alpha1.Model.RouteCondition.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudRun.V1alpha1.Model.RouteCondition do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 41.435484 | 269 | 0.705333 |
790f6c7b32dfa6b2fe1db25e2919b5bc6b5d7ae5 | 2,374 | ex | Elixir | lib/hl7/2.5.1/segments/om1.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | lib/hl7/2.5.1/segments/om1.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | lib/hl7/2.5.1/segments/om1.ex | calvinb/elixir-hl7 | 5e953fa11f9184857c0ec4dda8662889f35a6bec | [
"Apache-2.0"
] | null | null | null | defmodule HL7.V2_5_1.Segments.OM1 do
@moduledoc false
require Logger
alias HL7.V2_5_1.{DataTypes}
use HL7.Segment,
fields: [
segment: nil,
sequence_number_test_observation_master_file: nil,
producers_service_test_observation_id: DataTypes.Ce,
permitted_data_types: nil,
specimen_required: nil,
producer_id: DataTypes.Ce,
observation_description: nil,
other_service_test_observation_ids_for_the_observation: DataTypes.Ce,
other_names: nil,
preferred_report_name_for_the_observation: nil,
preferred_short_name_or_mnemonic_for_observation: nil,
preferred_long_name_for_the_observation: nil,
orderability: nil,
identity_of_instrument_used_to_perform_this_study: DataTypes.Ce,
coded_representation_of_method: DataTypes.Ce,
portable_device_indicator: nil,
observation_producing_department_section: DataTypes.Ce,
telephone_number_of_section: DataTypes.Xtn,
nature_of_service_test_observation: nil,
report_subheader: DataTypes.Ce,
report_display_order: nil,
date_time_stamp_for_any_change_in_definition_for_the_observation: DataTypes.Ts,
effective_date_time_of_change: DataTypes.Ts,
typical_turn_around_time: nil,
processing_time: nil,
processing_priority: nil,
reporting_priority: nil,
outside_sites_where_observation_may_be_performed: DataTypes.Ce,
address_of_outside_sites: DataTypes.Xad,
phone_number_of_outside_site: DataTypes.Xtn,
confidentiality_code: DataTypes.Cwe,
observations_required_to_interpret_the_observation: DataTypes.Ce,
interpretation_of_observations: nil,
contraindications_to_observations: DataTypes.Ce,
reflex_tests_observations: DataTypes.Ce,
rules_that_trigger_reflex_testing: nil,
fixed_canned_message: DataTypes.Ce,
patient_preparation: nil,
procedure_medication: DataTypes.Ce,
factors_that_may_affect_the_observation: nil,
service_test_observation_performance_schedule: nil,
description_of_test_methods: nil,
kind_of_quantity_observed: DataTypes.Ce,
point_versus_interval: DataTypes.Ce,
challenge_information: nil,
relationship_modifier: DataTypes.Ce,
target_anatomic_site_of_test: DataTypes.Ce,
modality_of_imaging_measurement: DataTypes.Ce
]
end
| 40.237288 | 85 | 0.768745 |
790f7c6a81198b68640398cec116dbebd38a7a3e | 2,788 | ex | Elixir | lib/codes/codes_f65.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_f65.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_f65.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_F65 do
alias IcdCode.ICDCode
def _F650 do
%ICDCode{full_code: "F650",
category_code: "F65",
short_code: "0",
full_name: "Fetishism",
short_name: "Fetishism",
category_name: "Fetishism"
}
end
def _F651 do
%ICDCode{full_code: "F651",
category_code: "F65",
short_code: "1",
full_name: "Transvestic fetishism",
short_name: "Transvestic fetishism",
category_name: "Transvestic fetishism"
}
end
def _F652 do
%ICDCode{full_code: "F652",
category_code: "F65",
short_code: "2",
full_name: "Exhibitionism",
short_name: "Exhibitionism",
category_name: "Exhibitionism"
}
end
def _F653 do
%ICDCode{full_code: "F653",
category_code: "F65",
short_code: "3",
full_name: "Voyeurism",
short_name: "Voyeurism",
category_name: "Voyeurism"
}
end
def _F654 do
%ICDCode{full_code: "F654",
category_code: "F65",
short_code: "4",
full_name: "Pedophilia",
short_name: "Pedophilia",
category_name: "Pedophilia"
}
end
def _F6550 do
%ICDCode{full_code: "F6550",
category_code: "F65",
short_code: "50",
full_name: "Sadomasochism, unspecified",
short_name: "Sadomasochism, unspecified",
category_name: "Sadomasochism, unspecified"
}
end
def _F6551 do
%ICDCode{full_code: "F6551",
category_code: "F65",
short_code: "51",
full_name: "Sexual masochism",
short_name: "Sexual masochism",
category_name: "Sexual masochism"
}
end
def _F6552 do
%ICDCode{full_code: "F6552",
category_code: "F65",
short_code: "52",
full_name: "Sexual sadism",
short_name: "Sexual sadism",
category_name: "Sexual sadism"
}
end
def _F6581 do
%ICDCode{full_code: "F6581",
category_code: "F65",
short_code: "81",
full_name: "Frotteurism",
short_name: "Frotteurism",
category_name: "Frotteurism"
}
end
def _F6589 do
%ICDCode{full_code: "F6589",
category_code: "F65",
short_code: "89",
full_name: "Other paraphilias",
short_name: "Other paraphilias",
category_name: "Other paraphilias"
}
end
def _F659 do
%ICDCode{full_code: "F659",
category_code: "F65",
short_code: "9",
full_name: "Paraphilia, unspecified",
short_name: "Paraphilia, unspecified",
category_name: "Paraphilia, unspecified"
}
end
end
| 26.301887 | 53 | 0.560617 |
790f890cf39967b7d69dc60cf654b1dc6a16c32f | 216 | exs | Elixir | scripts/scrapers/config/config.exs | codeselfstudy/codeselfstudy | fdfec5c9e3639b54d02c94c66b032373e1520026 | [
"BSD-3-Clause"
] | 8 | 2020-01-15T19:24:35.000Z | 2021-07-23T06:12:56.000Z | scripts/scrapers/config/config.exs | codeselfstudy/codeselfstudy | fdfec5c9e3639b54d02c94c66b032373e1520026 | [
"BSD-3-Clause"
] | 64 | 2020-01-26T00:17:38.000Z | 2021-03-21T02:42:38.000Z | scripts/scrapers/config/config.exs | codeselfstudy/codeselfstudy | fdfec5c9e3639b54d02c94c66b032373e1520026 | [
"BSD-3-Clause"
] | 2 | 2020-02-01T01:07:33.000Z | 2020-02-01T21:34:34.000Z | use Mix.Config
# I didn't figure out hound yet.
# https://github.com/HashNuke/hound/blob/master/notes/configuring-hound.md
config :hound, port: 5555, retries: 3, browser: "firefox"
import_config "#{Mix.env()}.exs"
| 27 | 74 | 0.731481 |
790f94805245c139c65b162de72313c06d93f06f | 869 | exs | Elixir | config/config.exs | cncgl/phoenix-sample | 81b1c807a40e972df93ccc4063395ddf48bf4e2e | [
"MIT"
] | 1 | 2016-01-01T12:55:25.000Z | 2016-01-01T12:55:25.000Z | config/config.exs | cncgl/phoenix-todo | 81b1c807a40e972df93ccc4063395ddf48bf4e2e | [
"MIT"
] | 1 | 2015-09-10T13:41:51.000Z | 2015-09-10T13:41:51.000Z | config/config.exs | cncgl/phoenix-todo | 81b1c807a40e972df93ccc4063395ddf48bf4e2e | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
use Mix.Config
# Configures the endpoint
config :hello_phoenix, HelloPhoenix.Endpoint,
url: [host: "localhost"],
root: Path.dirname(__DIR__),
secret_key_base: "HaGdDgQjfjI3DS+zSKG0fDNM8yIp/Tq7PGCzlAWntRT6/X2xXUl49ioEFPMPZ03T",
render_errors: [accepts: ~w(html json)],
pubsub: [name: HelloPhoenix.PubSub,
adapter: Phoenix.PubSub.PG2]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"
| 34.76 | 86 | 0.759494 |
790fd2d56e3a238d0b2e73e44e9c63f84093c43a | 647 | ex | Elixir | lib/tanks_web/controllers/game_controller.ex | marcinbiegun/elixir-tanks | 29a3beef303825a137249c8ae0a3ff21c33d9a1c | [
"MIT"
] | null | null | null | lib/tanks_web/controllers/game_controller.ex | marcinbiegun/elixir-tanks | 29a3beef303825a137249c8ae0a3ff21c33d9a1c | [
"MIT"
] | null | null | null | lib/tanks_web/controllers/game_controller.ex | marcinbiegun/elixir-tanks | 29a3beef303825a137249c8ae0a3ff21c33d9a1c | [
"MIT"
] | null | null | null | defmodule TanksWeb.GameController do
use TanksWeb, :controller
def index(conn, _params) do
games = Tanks.GameServer.all()
render(conn, "index.html", games: games)
end
def show(conn, %{"id" => game_id} = _params) do
game = Tanks.GameServer.get(game_id)
render(conn, "show.html", game: game)
end
def create(conn, _params) do
game_id = Utils.Crypto.random_id()
level = 1
Tanks.GameServer.create(game_id, level)
conn |> redirect(to: "/games") |> halt()
end
def delete(conn, %{"id" => game_id} = _params) do
Tanks.GameServer.delete(game_id)
conn |> redirect(to: "/games") |> halt()
end
end
| 24.884615 | 51 | 0.647604 |
790ff98e59da11c3e58f7ffc84c1a074fb511ddf | 3,716 | ex | Elixir | apps/fz_http/test/support/test_helpers.ex | kaku-io/firezone | 685da0064727df27e444fe4da2be20efe96af9cd | [
"Apache-2.0"
] | null | null | null | apps/fz_http/test/support/test_helpers.ex | kaku-io/firezone | 685da0064727df27e444fe4da2be20efe96af9cd | [
"Apache-2.0"
] | null | null | null | apps/fz_http/test/support/test_helpers.ex | kaku-io/firezone | 685da0064727df27e444fe4da2be20efe96af9cd | [
"Apache-2.0"
] | null | null | null | defmodule FzHttp.TestHelpers do
@moduledoc """
Test setup helpers
"""
alias FzHttp.{
ConnectivityChecksFixtures,
DevicesFixtures,
Repo,
RulesFixtures,
SessionsFixtures,
Users,
Users.User,
UsersFixtures
}
def restore_env(key, val, cb) do
old = Application.fetch_env!(:fz_http, key)
Application.put_env(:fz_http, key, val)
cb.(fn -> Application.put_env(:fz_http, key, old) end)
end
def clear_users do
Repo.delete_all(User)
end
def create_device_with_config_token(tags) do
device =
if tags[:unauthed] || is_nil(tags[:user_id]) do
DevicesFixtures.device_with_config_token()
else
DevicesFixtures.device_with_config_token(%{user_id: tags[:user_id]})
end
{:ok, device: device}
end
def create_device(tags) do
device =
if tags[:unauthed] || is_nil(tags[:user_id]) do
DevicesFixtures.device()
else
DevicesFixtures.device(%{user_id: tags[:user_id]})
end
{:ok, device: device}
end
def create_other_user_device(_) do
user_id = UsersFixtures.user(%{role: :unprivileged, email: "other_user@test"}).id
device =
DevicesFixtures.device(%{
user_id: user_id,
name: "other device",
public_key: "other-pubkey",
private_key: "other-privkey"
})
{:ok, other_device: device}
end
def create_connectivity_checks(_tags) do
connectivity_checks =
Enum.map(1..5, fn _i ->
ConnectivityChecksFixtures.connectivity_check_fixture()
end)
{:ok, connectivity_checks: connectivity_checks}
end
def create_devices(tags) do
user_id =
if tags[:unathed] || is_nil(tags[:user_id]) do
UsersFixtures.user().id
else
tags[:user_id]
end
devices =
Enum.map(1..5, fn num ->
DevicesFixtures.device(%{
name: "device #{num}",
public_key: "#{num}",
private_key: "#{num}",
user_id: user_id
})
end)
{:ok, devices: devices}
end
def create_user(_) do
user = UsersFixtures.user()
{:ok, user: user}
end
def create_session(_) do
session = SessionsFixtures.session()
{:ok, session: session}
end
def create_accept_rule(_) do
rule = RulesFixtures.rule(%{action: :accept})
{:ok, rule: rule}
end
def create_drop_rule(_) do
rule = RulesFixtures.rule(%{action: :drop})
{:ok, rule: rule}
end
def create_rule(_) do
rule = RulesFixtures.rule(%{})
{:ok, rule: rule}
end
def create_rule6(_) do
rule = RulesFixtures.rule6(%{})
{:ok, rule6: rule}
end
def create_rule4(_) do
rule = RulesFixtures.rule4(%{})
{:ok, rule4: rule}
end
@doc """
XXX: Mimic a more realistic setup.
"""
def create_rules(_) do
rules =
1..5
|> Enum.map(fn num ->
destination = "#{num}.#{num}.#{num}.0/24"
RulesFixtures.rule(%{destination: destination})
end)
{:ok, rules: rules}
end
def create_user_with_valid_sign_in_token(_) do
{:ok, user: %User{} = UsersFixtures.user(Users.sign_in_keys())}
end
def create_user_with_expired_sign_in_token(_) do
expired = DateTime.add(DateTime.utc_now(), -1 * 86_401)
params = %{Users.sign_in_keys() | sign_in_token_created_at: expired}
{:ok, user: %User{} = UsersFixtures.user(params)}
end
def create_users(%{count: count}) do
users =
Enum.map(1..count, fn i ->
UsersFixtures.user(%{email: "userlist#{i}@test"})
end)
{:ok, users: users}
end
def create_users(_), do: create_users(%{count: 5})
def clear_users(_) do
{count, _result} = Repo.delete_all(User)
{:ok, count: count}
end
end
| 22.119048 | 85 | 0.618676 |
791016d5074e3e85a27a07c7c76d51b48545cf3a | 10,882 | ex | Elixir | deps/ecto/lib/ecto/changeset/relation.ex | scouten/crash_esqlite_case | 986f0b0721399c7ed520f6b9df133980906e3f51 | [
"MIT"
] | null | null | null | deps/ecto/lib/ecto/changeset/relation.ex | scouten/crash_esqlite_case | 986f0b0721399c7ed520f6b9df133980906e3f51 | [
"MIT"
] | null | null | null | deps/ecto/lib/ecto/changeset/relation.ex | scouten/crash_esqlite_case | 986f0b0721399c7ed520f6b9df133980906e3f51 | [
"MIT"
] | null | null | null | defmodule Ecto.Changeset.Relation do
@moduledoc false
alias Ecto.Changeset
alias Ecto.Association.NotLoaded
@type t :: %{cardinality: :one | :many,
on_replace: :raise | :mark_as_invalid | atom,
relationship: :parent | :child,
owner: atom,
related: atom,
field: atom}
@doc """
Builds the related model.
"""
@callback build(t) :: Ecto.Schema.t
@doc """
Returns empty container for relation.
"""
def empty(%{cardinality: cardinality}), do: do_empty(cardinality)
defp do_empty(:one), do: nil
defp do_empty(:many), do: []
@doc """
Checks if the container can be considered empty.
"""
def empty?(%{cardinality: _}, %NotLoaded{}), do: true
def empty?(%{cardinality: :many}, []), do: true
def empty?(%{cardinality: :one}, nil), do: true
def empty?(%{}, _), do: false
@doc """
Applies related changeset changes
"""
def apply_changes(%{cardinality: :one}, nil) do
nil
end
def apply_changes(%{cardinality: :one}, changeset) do
apply_changes(changeset)
end
def apply_changes(%{cardinality: :many}, changesets) do
for changeset <- changesets,
model = apply_changes(changeset),
do: model
end
defp apply_changes(%Changeset{action: :delete}), do: nil
defp apply_changes(changeset), do: Changeset.apply_changes(changeset)
@doc """
Loads the relation with the given model.
Loading will fail if the asociation is not loaded but the model is.
"""
def load!(%{__meta__: %{state: :built}}, %NotLoaded{__cardinality__: cardinality}) do
do_empty(cardinality)
end
def load!(model, %NotLoaded{__field__: field}) do
raise "attempting to cast or change association `#{field}` " <>
"from `#{inspect model.__struct__}` that was not loaded. Please preload your " <>
"associations before casting or changing the model"
end
def load!(_model, loaded), do: loaded
@doc """
Casts related according to the `on_cast` function.
"""
def cast(%{cardinality: :one} = relation, nil, current, _on_cast) do
case current && on_replace(relation, current) do
:error -> :error
_ -> {:ok, nil, true, is_nil(current)}
end
end
def cast(%{cardinality: :many} = relation, params, current, on_cast) when is_map(params) do
params =
params
|> Enum.sort_by(&elem(&1, 0))
|> Enum.map(&elem(&1, 1))
cast(relation, params, current, on_cast)
end
def cast(%{related: mod} = relation, params, current, on_cast) do
pks = primary_keys!(mod)
cast_or_change(relation, params, current, struct_pk(mod, pks),
param_pk(mod, pks), &do_cast(relation, &1, &2, &3, on_cast))
end
defp do_cast(meta, params, nil, allowed_actions, on_cast) do
{:ok,
on_cast.(meta.__struct__.build(meta), params)
|> put_new_action(:insert)
|> check_action!(allowed_actions)}
end
defp do_cast(relation, nil, current, _allowed_actions, _on_cast) do
on_replace(relation, current)
end
defp do_cast(_meta, params, struct, allowed_actions, on_cast) do
{:ok,
on_cast.(struct, params)
|> put_new_action(:update)
|> check_action!(allowed_actions)}
end
@doc """
Wraps related models in changesets.
"""
def change(%{cardinality: :one} = relation, nil, current) do
case current && on_replace(relation, current) do
:error -> :error
_ -> {:ok, nil, true, is_nil(current)}
end
end
def change(%{related: mod} = relation, value, current) do
get_pks = struct_pk(mod, primary_keys!(mod))
cast_or_change(relation, value, current, get_pks, get_pks,
&do_change(relation, &1, &2, &3))
end
# This may be an insert or an update, get all fields.
defp do_change(_relation, changeset_or_struct, nil, _allowed_actions) do
changeset = Changeset.change(changeset_or_struct)
%{model: %{__meta__: %{state: state}}} = changeset
action =
case state do
:built -> :insert
:loaded -> :update
:deleted -> :delete
end
{:ok, put_new_action(changeset, action)}
end
defp do_change(relation, nil, current, _allowed_actions) do
on_replace(relation, current)
end
defp do_change(_relation, %Changeset{model: current} = changeset, current, allowed_actions) do
{:ok, put_new_action(changeset, :update) |> check_action!(allowed_actions)}
end
defp do_change(%{field: field}, %Changeset{}, _current, _allowed_actions) do
raise "cannot change `#{field}` because given changeset has a different " <>
"embed/association than the one specified in the parent struct"
end
defp do_change(%{field: field}, _struct, _current, _allowed_actions) do
raise "cannot change `#{field}` with a struct because another " <>
"embed/association is set in parent struct, use a changeset instead"
end
@doc """
Handles the changeset or model when being replaced.
"""
def on_replace(%{on_replace: :mark_as_invalid}, _changeset_or_model) do
:error
end
def on_replace(%{on_replace: :raise, field: name, owner: owner}, _) do
raise """
you are attempting to change relation #{inspect name} of
#{inspect owner}, but there is missing data.
If you are attempting to update an existing entry, please make sure
you include the entry primary key (ID) alongside the data.
If you have a relationship with many children, at least the same N
children must be given on update. By default it is not possible to
orphan embed nor associated records, attempting to do so results in
this error message.
It is possible to change this behaviour by setting `:on_replace` when
defining the relation. See `Ecto.Changeset`'s section on related data
for more info.
"""
end
def on_replace(_relation, changeset_or_model) do
{:ok, Changeset.change(changeset_or_model) |> put_new_action(:replace)}
end
defp cast_or_change(%{cardinality: :one} = relation, value, current, current_pks,
new_pks, fun) when is_map(value) or is_nil(value) do
single_change(relation, value, current_pks, new_pks, fun, current)
end
defp cast_or_change(%{cardinality: :many}, value, current, current_pks,
new_pks, fun) when is_list(value) do
map_changes(value, current_pks, new_pks, fun, current)
end
defp cast_or_change(_, _, _, _, _, _), do: :error
# single change
defp single_change(_relation, nil, _current_pks, _new_pks, fun, current) do
single_change(nil, current, fun, [:update, :delete], false)
end
defp single_change(_relation, new, _current_pks, _new_pks, fun, nil) do
single_change(new, nil, fun, [:insert], false)
end
defp single_change(relation, new, current_pks, new_pks, fun, current) do
if new_pks.(new) == current_pks.(current) do
single_change(new, current, fun, [:update, :delete], true)
else
case on_replace(relation, current) do
{:ok, _} -> single_change(new, nil, fun, [:insert], false)
:error -> :error
end
end
end
defp single_change(new, current, fun, allowed_actions, skippable?) do
case fun.(new, current, allowed_actions) do
{:ok, changeset} ->
{:ok, changeset, changeset.valid?, skippable? and skip?(changeset)}
:error ->
:error
end
end
# map changes
defp map_changes(list, current_pks, new_pks, fun, current) do
map_changes(list, new_pks, fun, process_current(current, current_pks), [], true, true)
end
defp map_changes([], _pks, fun, current, acc, valid?, skip?) do
current_models = Enum.map(current, &elem(&1, 1))
reduce_delete_changesets(current_models, fun, Enum.reverse(acc), valid?, skip?)
end
defp map_changes([map | rest], new_pks, fun, current, acc, valid?, skip?) when is_map(map) do
pk_values = new_pks.(map)
{model, current, allowed_actions} =
case Map.fetch(current, pk_values) do
{:ok, model} ->
{model, Map.delete(current, pk_values), [:update, :delete]}
:error ->
{nil, current, [:insert]}
end
case fun.(map, model, allowed_actions) do
{:ok, changeset} ->
map_changes(rest, new_pks, fun, current, [changeset | acc],
valid? && changeset.valid?, (model != nil) and skip? and skip?(changeset))
:error ->
:error
end
end
defp map_changes(_params, _pks, _fun, _current, _acc, _valid?, _skip?) do
:error
end
defp reduce_delete_changesets([], _fun, acc, valid?, skip?) do
{:ok, acc, valid?, skip?}
end
defp reduce_delete_changesets([model | rest], fun, acc, valid?, _skip?) do
case fun.(nil, model, [:update, :delete]) do
{:ok, changeset} ->
reduce_delete_changesets(rest, fun, [changeset | acc],
valid? && changeset.valid?, false)
:error ->
:error
end
end
# helpers
defp check_action!(changeset, allowed_actions) do
action = changeset.action
cond do
action in allowed_actions ->
changeset
action == :insert ->
raise "cannot #{action} related #{inspect changeset.model} " <>
"because it is already associated to the given struct"
true ->
raise "cannot #{action} related #{inspect changeset.model} because " <>
"it already exists and it is not currently associated to the " <>
"given struct. Ecto forbids casting existing records through " <>
"the association field for security reasons. Instead, set " <>
"the foreign key value accordingly"
end
end
defp process_current(nil, _get_pks),
do: %{}
defp process_current(current, get_pks) do
Enum.reduce(current, %{}, fn model, acc ->
Map.put(acc, get_pks.(model), model)
end)
end
defp struct_pk(_mod, pks) do
fn
%Changeset{model: model} -> Enum.map(pks, &Map.get(model, &1))
model -> Enum.map(pks, &Map.get(model, &1))
end
end
defp param_pk(mod, pks) do
pks = Enum.map(pks, &{Atom.to_string(&1), mod.__schema__(:type, &1)})
fn params ->
Enum.map pks, fn {key, type} ->
original = Map.get(params, key)
case Ecto.Type.cast(type, original) do
{:ok, value} -> value
:error -> original
end
end
end
end
defp primary_keys!(module) do
case module.__schema__(:primary_key) do
[] -> raise Ecto.NoPrimaryKeyFieldError, model: module
pks -> pks
end
end
defp put_new_action(%{action: action} = changeset, new_action) when is_nil(action),
do: Map.put(changeset, :action, new_action)
defp put_new_action(changeset, _new_action),
do: changeset
defp skip?(%{valid?: true, changes: empty, action: :update}) when empty == %{},
do: true
defp skip?(_changeset),
do: false
end
| 31.360231 | 96 | 0.64308 |
7910199695d57e507f784626851fbd7845abfedd | 6,457 | ex | Elixir | lib/rihanna/job.ex | antonioparisi/rihanna | 81aca463419111aa3e761dbbd5862ac986d3ec7a | [
"MIT"
] | null | null | null | lib/rihanna/job.ex | antonioparisi/rihanna | 81aca463419111aa3e761dbbd5862ac986d3ec7a | [
"MIT"
] | null | null | null | lib/rihanna/job.ex | antonioparisi/rihanna | 81aca463419111aa3e761dbbd5862ac986d3ec7a | [
"MIT"
] | null | null | null | defmodule Rihanna.Job do
require Logger
@type result :: any
@type reason :: any
@type t :: %__MODULE__{}
@callback perform(arg :: any) :: :ok | {:ok, result} | :error | {:error, reason}
@moduledoc """
A behaviour for Rihanna jobs.
You must implement `c:Rihanna.Job.perform/1` in your job, and it must return
one of the following values:
- `:ok`
- `{:ok, result}`
- `:error`
- `{:error, reason}`
You can define your job like the example below:
```
defmodule MyApp.MyJob do
@behaviour Rihanna.Job
# NOTE: `perform/1` is a required callback. It takes exactly one argument. To
# pass multiple arguments, wrap them in a list and destructure in the
# function head as in this example
def perform([arg1, arg2]) do
success? = do_some_work(arg1, arg2)
if success? do
# job completed successfully
:ok
else
# job execution failed
{:error, :failed}
end
end
end
"""
@fields [
:id,
:term,
:enqueued_at,
:failed_at,
:fail_reason
]
defstruct @fields
@doc false
def start(job) do
GenServer.call(Rihanna.JobManager, job)
end
@doc false
def enqueue(term) do
serialized_term = :erlang.term_to_binary(term)
now = DateTime.utc_now()
%{rows: [job]} =
Postgrex.query!(
Rihanna.Job.Postgrex,
"""
INSERT INTO "#{table()}" (term, enqueued_at)
VALUES ($1, $2)
RETURNING #{sql_fields()}
""",
[serialized_term, now]
)
{:ok, from_sql(job)}
end
@doc false
def from_sql(rows = [row | _]) when is_list(rows) and is_list(row) do
for row <- rows, do: from_sql(row)
end
@doc false
def from_sql([
id,
serialized_term,
enqueued_at,
failed_at,
fail_reason
]) do
%__MODULE__{
id: id,
term: :erlang.binary_to_term(serialized_term),
enqueued_at: enqueued_at,
failed_at: failed_at,
fail_reason: fail_reason
}
end
@doc false
def from_sql([]), do: []
@doc false
def retry_failed(pg \\ Rihanna.Job.Postgrex, job_id)
when (is_pid(pg) or is_atom(pg)) and is_integer(job_id) do
now = DateTime.utc_now()
result =
Postgrex.query!(
pg,
"""
UPDATE "#{table()}"
SET
failed_at = NULL,
fail_reason = NULL,
enqueued_at = $1
WHERE
failed_at IS NOT NULL AND id = $2
""",
[now, job_id]
)
case result.num_rows do
0 ->
{:error, :job_not_found}
1 ->
{:ok, :retried}
end
end
@doc false
def lock(pg) when is_pid(pg) do
lock(pg, [])
end
@doc false
def lock(pg, exclude_ids) when is_pid(pg) and is_list(exclude_ids) do
case lock(pg, 1, exclude_ids) do
[job] ->
job
[] ->
nil
end
end
# This query is at the heart of the how the dispatcher pulls jobs from the queue.
#
# It is heavily inspired by a similar query in Que: https://github.com/chanks/que/blob/0.x/lib/que/sql.rb#L5
#
# There are some minor additions:
#
# I could not find any easy way to check if one particular advisory lock is
# already held by the current session, so each dispatcher must pass in a list
# of ids for jobs which are currently already working so those can be excluded.
#
# We also use a FOR UPDATE SKIP LOCKED since this causes the query to skip
# jobs that were completed (and deleted) by another session in the time since
# the table snapshot was taken. In rare cases under high concurrency levels,
# leaving this out can result in double executions.
@doc false
def lock(pg, n) do
lock(pg, n, [])
end
@doc false
def lock(_, 0, _) do
[]
end
@doc false
def lock(pg, n, exclude_ids)
when is_pid(pg) and is_integer(n) and n > 0 and is_list(exclude_ids) do
table = table()
lock_jobs = """
WITH RECURSIVE jobs AS (
SELECT (j).*, pg_try_advisory_lock($1::integer, (j).id) AS locked
FROM (
SELECT j
FROM #{table} AS j
WHERE NOT (id = ANY($3))
AND failed_at IS NULL
ORDER BY enqueued_at, j.id
FOR UPDATE OF j SKIP LOCKED
LIMIT 1
) AS t1
UNION ALL (
SELECT (j).*, pg_try_advisory_lock($1::integer, (j).id) AS locked
FROM (
SELECT (
SELECT j
FROM #{table} AS j
WHERE NOT (id = ANY($3))
AND failed_at IS NULL
AND (j.enqueued_at, j.id) > (jobs.enqueued_at, jobs.id)
ORDER BY enqueued_at, j.id
FOR UPDATE OF j SKIP LOCKED
LIMIT 1
) AS j
FROM jobs
WHERE jobs.id IS NOT NULL
LIMIT 1
) AS t1
)
)
SELECT id, term, enqueued_at, failed_at, fail_reason
FROM jobs
WHERE locked
LIMIT $2
"""
%{rows: rows} = Postgrex.query!(pg, lock_jobs, [classid(), n, exclude_ids])
Rihanna.Job.from_sql(rows)
end
@doc false
def mark_successful(pg, job_id) when is_pid(pg) and is_integer(job_id) do
%{num_rows: num_rows} =
Postgrex.query!(
pg,
"""
DELETE FROM "#{table()}"
WHERE id = $1;
""",
[job_id]
)
release_lock(pg, job_id)
{:ok, num_rows}
end
@doc false
def mark_failed(pg, job_id, now, fail_reason) when is_pid(pg) and is_integer(job_id) do
%{num_rows: num_rows} =
Postgrex.query!(
pg,
"""
UPDATE "#{table()}"
SET
failed_at = $1,
fail_reason = $2
WHERE
id = $3
""",
[now, fail_reason, job_id]
)
release_lock(pg, job_id)
{:ok, num_rows}
end
@doc """
The name of the jobs table.
"""
@spec table() :: String.t()
def table() do
Rihanna.Config.jobs_table_name()
end
@doc false
def classid() do
Rihanna.Config.pg_advisory_lock_class_id()
end
defp release_lock(pg, job_id) when is_pid(pg) and is_integer(job_id) do
%{rows: [[true]]} =
Postgrex.query!(
pg,
"""
SELECT pg_advisory_unlock($1, $2);
""",
[classid(), job_id]
)
end
defp sql_fields() do
@fields
|> Enum.map(&to_string/1)
|> Enum.join(", ")
end
end
| 22.342561 | 110 | 0.560012 |
791059d154259c09364bb1314baa1630d4e14a54 | 40,965 | ex | Elixir | lib/ecto/type.ex | samuelpordeus/ecto | c66ab5f89ef348c7f520f427001c33d95a78bd2e | [
"Apache-2.0"
] | null | null | null | lib/ecto/type.ex | samuelpordeus/ecto | c66ab5f89ef348c7f520f427001c33d95a78bd2e | [
"Apache-2.0"
] | null | null | null | lib/ecto/type.ex | samuelpordeus/ecto | c66ab5f89ef348c7f520f427001c33d95a78bd2e | [
"Apache-2.0"
] | null | null | null | defmodule Ecto.Type do
@moduledoc """
Defines functions and the `Ecto.Type` behaviour for implementing
custom types.
A custom type expects 4 functions to be implemented, all documented
and described below. We also provide two examples of how custom
types can be used in Ecto to augment existing types or providing
your own types.
Note: `nil` values are always bypassed and cannot be handled by
custom types.
## Example
Imagine you want to store an URI struct as part of a schema in an
url-shortening service. There isn't an Ecto field type to support
that value at runtime, therefore a custom one is needed.
You also want to query not only by the full url, but for example
by specific ports used. This is possible by putting the URI data
into a map field instead of just storing the plain
string representation.
from s in ShortUrl,
where: fragment("?->>? ILIKE ?", s.original_url, "port", "443")
So the custom type does need to handle the conversion from
external data to runtime data (`c:cast/1`) as well as
transforming that runtime data into the `:map` Ecto native type and
back (`c:dump/1` and `c:load/1`).
defmodule EctoURI do
use Ecto.Type
def type, do: :map
# Provide custom casting rules.
# Cast strings into the URI struct to be used at runtime
def cast(uri) when is_binary(uri) do
{:ok, URI.parse(uri)}
end
# Accept casting of URI structs as well
def cast(%URI{} = uri), do: {:ok, uri}
# Everything else is a failure though
def cast(_), do: :error
# When loading data from the database, we are guaranteed to
# receive a map (as databases are strict) and we will
# just put the data back into an URI struct to be stored
# in the loaded schema struct.
def load(data) when is_map(data) do
data =
for {key, val} <- data do
{String.to_existing_atom(key), val}
end
{:ok, struct!(URI, data)}
end
# When dumping data to the database, we *expect* an URI struct
# but any value could be inserted into the schema struct at runtime,
# so we need to guard against them.
def dump(%URI{} = uri), do: {:ok, Map.from_struct(uri)}
def dump(_), do: :error
end
Now we can use our new field type above in our schemas:
defmodule ShortUrl do
use Ecto.Schema
schema "posts" do
field :original_url, EctoURI
end
end
"""
import Kernel, except: [match?: 2]
@doc false
defmacro __using__(_opts) do
quote location: :keep do
@behaviour Ecto.Type
def embed_as(_), do: :self
def equal?(term1, term2), do: term1 == term2
defoverridable [embed_as: 1, equal?: 2]
end
end
@typedoc "An Ecto type, primitive or custom."
@type t :: primitive | custom
@typedoc "Primitive Ecto types (handled by Ecto)."
@type primitive :: base | composite
@typedoc "Custom types are represented by user-defined modules."
@type custom :: module
@type base :: :integer | :float | :boolean | :string | :map |
:binary | :decimal | :id | :binary_id |
:utc_datetime | :naive_datetime | :date | :time | :any |
:utc_datetime_usec | :naive_datetime_usec | :time_usec
@type composite :: {:array, t} | {:map, t} | private_composite
@typep private_composite :: {:maybe, t} | {:embed, Ecto.Embedded.t} | {:in, t}
@base ~w(
integer float decimal boolean string map binary id binary_id any
utc_datetime naive_datetime date time
utc_datetime_usec naive_datetime_usec time_usec
)a
@composite ~w(array map in embed param)a
@doc """
Returns the underlying schema type for the custom type.
For example, if you want to provide your own date
structures, the type function should return `:date`.
Note this function is not required to return Ecto primitive
types, the type is only required to be known by the adapter.
"""
@callback type :: t
@doc """
Casts the given input to the custom type.
This callback is called on external input and can return any type,
as long as the `dump/1` function is able to convert the returned
value into an Ecto native type. There are two situations where
this callback is called:
1. When casting values by `Ecto.Changeset`
2. When passing arguments to `Ecto.Query`
When returning `{:error, keyword()}`, the returned keyword list
will be preserved in the changeset errors, similar to
`Changeset.add_error/4`. Passing a `:message` key, will override
the default message. It is not possible to override the `:type` key.
For `{:array, CustomType}` or `{:map, CustomType}` the returned
keyword list will be erased and the default error will be shown.
"""
@callback cast(term) :: {:ok, term} | {:error, keyword()} | :error
@doc """
Loads the given term into a custom type.
This callback is called when loading data from the database and
receives an Ecto native type. It can return any type, as long as
the `dump/1` function is able to convert the returned value back
into an Ecto native type.
"""
@callback load(term) :: {:ok, term} | :error
@doc """
Dumps the given term into an Ecto native type.
This callback is called with any term that was stored in the struct
and it needs to validate them and convert it to an Ecto native type.
"""
@callback dump(term) :: {:ok, term} | :error
@doc """
Checks if two terms are semantically equal.
"""
@callback equal?(term, term) :: boolean
@doc """
Dictates how the type should be treated inside embeds.
By default, the type is sent as itself, without calling
dumping to keep the higher level representation. But
it can be set to `:dump` to it is dumped before encoded.
"""
@callback embed_as(format :: atom) :: :self | :dump
## Functions
@doc """
Checks if we have a primitive type.
iex> primitive?(:string)
true
iex> primitive?(Another)
false
iex> primitive?({:array, :string})
true
iex> primitive?({:array, Another})
true
"""
@spec primitive?(t) :: boolean
def primitive?({composite, _}) when composite in @composite, do: true
def primitive?(base) when base in @base, do: true
def primitive?(_), do: false
@doc """
Checks if the given atom can be used as composite type.
iex> composite?(:array)
true
iex> composite?(:string)
false
"""
@spec composite?(atom) :: boolean
def composite?(atom), do: atom in @composite
@doc """
Checks if the given atom can be used as base type.
iex> base?(:string)
true
iex> base?(:array)
false
iex> base?(Custom)
false
"""
@spec base?(atom) :: boolean
def base?(atom), do: atom in @base
@doc """
Gets how the type is treated inside embeds for the given format.
See `c:embed_as/1`.
"""
def embed_as({composite, _}, _format) when composite in @composite, do: :self
def embed_as(base, _format) when base in @base, do: :self
def embed_as(mod, format) do
if loaded_and_exported?(mod, :embed_as, 1) do
mod.embed_as(format)
else
:self
end
end
@doc """
Retrieves the underlying schema type for the given, possibly custom, type.
iex> type(:string)
:string
iex> type(Ecto.UUID)
:uuid
iex> type({:array, :string})
{:array, :string}
iex> type({:array, Ecto.UUID})
{:array, :uuid}
iex> type({:map, Ecto.UUID})
{:map, :uuid}
"""
@spec type(t) :: t
def type(type)
def type({:array, type}), do: {:array, type(type)}
def type({:map, type}), do: {:map, type(type)}
def type(type) do
if primitive?(type) do
type
else
type.type
end
end
@doc """
Checks if a given type matches with a primitive type
that can be found in queries.
iex> match?(:string, :any)
true
iex> match?(:any, :string)
true
iex> match?(:string, :string)
true
iex> match?({:array, :string}, {:array, :any})
true
iex> match?(Ecto.UUID, :uuid)
true
iex> match?(Ecto.UUID, :string)
false
"""
@spec match?(t, primitive) :: boolean
def match?(schema_type, query_type) do
if primitive?(schema_type) do
do_match?(schema_type, query_type)
else
do_match?(schema_type.type, query_type)
end
end
defp do_match?(_left, :any), do: true
defp do_match?(:any, _right), do: true
defp do_match?({outer, left}, {outer, right}), do: match?(left, right)
defp do_match?({:array, :any}, {:embed, %{cardinality: :many}}), do: true
defp do_match?(:decimal, type) when type in [:float, :integer], do: true
defp do_match?(:binary_id, :binary), do: true
defp do_match?(:id, :integer), do: true
defp do_match?(type, type), do: true
defp do_match?(:naive_datetime, {:param, :any_datetime}), do: true
defp do_match?(:naive_datetime_usec, {:param, :any_datetime}), do: true
defp do_match?(:utc_datetime, {:param, :any_datetime}), do: true
defp do_match?(:utc_datetime_usec, {:param, :any_datetime}), do: true
defp do_match?(_, _), do: false
@doc """
Dumps a value to the given type.
Opposite to casting, dumping requires the returned value
to be a valid Ecto type, as it will be sent to the
underlying data store.
iex> dump(:string, nil)
{:ok, nil}
iex> dump(:string, "foo")
{:ok, "foo"}
iex> dump(:integer, 1)
{:ok, 1}
iex> dump(:integer, "10")
:error
iex> dump(:binary, "foo")
{:ok, "foo"}
iex> dump(:binary, 1)
:error
iex> dump({:array, :integer}, [1, 2, 3])
{:ok, [1, 2, 3]}
iex> dump({:array, :integer}, [1, "2", 3])
:error
iex> dump({:array, :binary}, ["1", "2", "3"])
{:ok, ["1", "2", "3"]}
"""
@spec dump(t, term) :: {:ok, term} | :error
def dump(_type, nil) do
{:ok, nil}
end
def dump({:maybe, type}, value) do
case dump(type, value) do
{:ok, _} = ok -> ok
:error -> {:ok, value}
end
end
def dump(type, value) do
dump_fun(type).(value)
end
@doc """
Dumps a value to the given type.
This function behaves the same as `dump/2`, except for composite types
the given `dumper` function is used.
"""
@spec dump(t, term, (t, term -> {:ok, term} | :error)) :: {:ok, term} | :error
def dump(_type, nil, _dumper) do
{:ok, nil}
end
def dump({:maybe, type}, value, dumper) do
case dump(type, value, dumper) do
{:ok, _} = ok -> ok
:error -> {:ok, value}
end
end
def dump({:embed, embed}, value, dumper) do
dump_embed(embed, value, dumper)
end
def dump({:in, type}, value, dumper) do
case dump({:array, type}, value, dumper) do
{:ok, value} -> {:ok, {:in, value}}
:error -> :error
end
end
def dump({:map, type}, value, dumper) when is_map(value) do
map(Map.to_list(value), type, dumper, %{})
end
def dump({:array, type}, value, dumper) do
array(value, type, dumper, [])
end
def dump(type, value, _) do
dump_fun(type).(value)
end
defp dump_fun(:integer), do: &same_integer/1
defp dump_fun(:float), do: &dump_float/1
defp dump_fun(:boolean), do: &same_boolean/1
defp dump_fun(:map), do: &same_map/1
defp dump_fun(:string), do: &same_binary/1
defp dump_fun(:binary), do: &same_binary/1
defp dump_fun(:id), do: &same_integer/1
defp dump_fun(:binary_id), do: &same_binary/1
defp dump_fun(:any), do: &{:ok, &1}
defp dump_fun(:decimal), do: &same_decimal/1
defp dump_fun(:date), do: &same_date/1
defp dump_fun(:time), do: &dump_time/1
defp dump_fun(:time_usec), do: &dump_time_usec/1
defp dump_fun(:naive_datetime), do: &dump_naive_datetime/1
defp dump_fun(:naive_datetime_usec), do: &dump_naive_datetime_usec/1
defp dump_fun(:utc_datetime), do: &dump_utc_datetime/1
defp dump_fun(:utc_datetime_usec), do: &dump_utc_datetime_usec/1
defp dump_fun({:param, :any_datetime}), do: &dump_any_datetime/1
defp dump_fun({:array, type}), do: &array(&1, dump_fun(type), [])
defp dump_fun({:map, type}), do: &map(&1, dump_fun(type), %{})
defp dump_fun(mod) when is_atom(mod), do: &mod.dump(&1)
defp same_integer(term) when is_integer(term), do: {:ok, term}
defp same_integer(_), do: :error
defp dump_float(term) when is_float(term), do: {:ok, term}
defp dump_float(_), do: :error
defp same_boolean(term) when is_boolean(term), do: {:ok, term}
defp same_boolean(_), do: :error
defp same_binary(term) when is_binary(term), do: {:ok, term}
defp same_binary(_), do: :error
defp same_map(term) when is_map(term), do: {:ok, term}
defp same_map(_), do: :error
defp same_decimal(term) when is_integer(term), do: {:ok, Decimal.new(term)}
defp same_decimal(term) when is_float(term), do: {:ok, Decimal.from_float(term)}
defp same_decimal(%Decimal{} = term), do: {:ok, check_decimal!(term)}
defp same_decimal(_), do: :error
defp same_date(%Date{} = term), do: {:ok, term}
defp same_date(_), do: :error
defp dump_time(%Time{} = term), do: {:ok, check_no_usec!(term, :time)}
defp dump_time(_), do: :error
defp dump_time_usec(%Time{} = term), do: {:ok, check_usec!(term, :time_usec)}
defp dump_time_usec(_), do: :error
defp dump_any_datetime(%NaiveDateTime{} = term), do: {:ok, term}
defp dump_any_datetime(%DateTime{} = term), do: {:ok, term}
defp dump_any_datetime(_), do: :error
defp dump_naive_datetime(%NaiveDateTime{} = term), do:
{:ok, check_no_usec!(term, :naive_datetime)}
defp dump_naive_datetime(_), do: :error
defp dump_naive_datetime_usec(%NaiveDateTime{} = term),
do: {:ok, check_usec!(term, :naive_datetime_usec)}
defp dump_naive_datetime_usec(_), do: :error
defp dump_utc_datetime(%DateTime{} = datetime) do
kind = :utc_datetime
{:ok, datetime |> check_utc_timezone!(kind) |> check_no_usec!(kind)}
end
defp dump_utc_datetime(_), do: :error
defp dump_utc_datetime_usec(%DateTime{} = datetime) do
kind = :utc_datetime_usec
{:ok, datetime |> check_utc_timezone!(kind) |> check_usec!(kind)}
end
defp dump_utc_datetime_usec(_), do: :error
defp dump_embed(%{cardinality: :one, related: schema, field: field},
value, fun) when is_map(value) do
{:ok, dump_embed(field, schema, value, schema.__schema__(:dump), fun)}
end
defp dump_embed(%{cardinality: :many, related: schema, field: field},
value, fun) when is_list(value) do
types = schema.__schema__(:dump)
{:ok, Enum.map(value, &dump_embed(field, schema, &1, types, fun))}
end
defp dump_embed(_embed, _value, _fun) do
:error
end
defp dump_embed(_field, schema, %{__struct__: schema} = struct, types, dumper) do
Enum.reduce(types, %{}, fn {field, {source, type}}, acc ->
value = Map.get(struct, field)
case dumper.(type, value) do
{:ok, value} ->
Map.put(acc, source, value)
:error ->
raise ArgumentError, "cannot dump `#{inspect value}` as type #{inspect type} " <>
"for field `#{field}` in schema #{inspect schema}"
end
end)
end
defp dump_embed(field, _schema, value, _types, _fun) do
raise ArgumentError, "cannot dump embed `#{field}`, invalid value: #{inspect value}"
end
@doc """
Loads a value with the given type.
iex> load(:string, nil)
{:ok, nil}
iex> load(:string, "foo")
{:ok, "foo"}
iex> load(:integer, 1)
{:ok, 1}
iex> load(:integer, "10")
:error
"""
@spec load(t, term) :: {:ok, term} | :error
def load({:embed, embed}, value) do
load_embed(embed, value, &load/2)
end
def load(_type, nil) do
{:ok, nil}
end
def load({:maybe, type}, value) do
case load(type, value) do
{:ok, _} = ok -> ok
:error -> {:ok, value}
end
end
def load(type, value) do
load_fun(type).(value)
end
@doc """
Loads a value with the given type.
This function behaves the same as `load/2`, except for composite types
the given `loader` function is used.
"""
@spec load(t, term, (t, term -> {:ok, term} | :error)) :: {:ok, term} | :error
def load({:embed, embed}, value, loader) do
load_embed(embed, value, loader)
end
def load(_type, nil, _loader) do
{:ok, nil}
end
def load({:maybe, type}, value, loader) do
case load(type, value, loader) do
{:ok, _} = ok -> ok
:error -> {:ok, value}
end
end
def load({:map, type}, value, loader) when is_map(value) do
map(Map.to_list(value), type, loader, %{})
end
def load({:array, type}, value, loader) do
array(value, type, loader, [])
end
def load(type, value, _loader) do
load_fun(type).(value)
end
defp load_fun(:integer), do: &same_integer/1
defp load_fun(:float), do: &load_float/1
defp load_fun(:boolean), do: &same_boolean/1
defp load_fun(:map), do: &same_map/1
defp load_fun(:string), do: &same_binary/1
defp load_fun(:binary), do: &same_binary/1
defp load_fun(:id), do: &same_integer/1
defp load_fun(:binary_id), do: &same_binary/1
defp load_fun(:any), do: &{:ok, &1}
defp load_fun(:decimal), do: &same_decimal/1
defp load_fun(:date), do: &same_date/1
defp load_fun(:time), do: &load_time/1
defp load_fun(:time_usec), do: &load_time_usec/1
defp load_fun(:naive_datetime), do: &load_naive_datetime/1
defp load_fun(:naive_datetime_usec), do: &load_naive_datetime_usec/1
defp load_fun(:utc_datetime), do: &load_utc_datetime/1
defp load_fun(:utc_datetime_usec), do: &load_utc_datetime_usec/1
defp load_fun({:array, type}), do: &array(&1, load_fun(type), [])
defp load_fun({:map, type}), do: &map(&1, load_fun(type), %{})
defp load_fun(mod) when is_atom(mod), do: &mod.load(&1)
defp load_float(term) when is_float(term), do: {:ok, term}
defp load_float(term) when is_integer(term), do: {:ok, :erlang.float(term)}
defp load_float(_), do: :error
defp load_time(%Time{} = time), do: {:ok, truncate_usec(time)}
defp load_time(_), do: :error
defp load_time_usec(%Time{} = time), do: {:ok, pad_usec(time)}
defp load_time_usec(_), do: :error
# This is a downcast, which is always fine, and in case
# we try to send a naive datetime where a datetime is expected,
# the adapter will either explicitly error (Postgres) or it will
# accept the data (MySQL), which is fine as we always assume UTC
defp load_naive_datetime(%DateTime{} = datetime),
do: {:ok, datetime |> check_utc_timezone!(:naive_datetime) |> DateTime.to_naive() |> truncate_usec()}
defp load_naive_datetime(%NaiveDateTime{} = naive_datetime),
do: {:ok, truncate_usec(naive_datetime)}
defp load_naive_datetime(_), do: :error
defp load_naive_datetime_usec(%DateTime{} = datetime),
do: {:ok, datetime |> check_utc_timezone!(:naive_datetime_usec) |> DateTime.to_naive() |> pad_usec()}
defp load_naive_datetime_usec(%NaiveDateTime{} = naive_datetime),
do: {:ok, pad_usec(naive_datetime)}
defp load_naive_datetime_usec(_), do: :error
# This is an upcast but because we assume the database
# is always in UTC, we can perform it.
defp load_utc_datetime(%NaiveDateTime{} = naive_datetime),
do: {:ok, naive_datetime |> truncate_usec() |> DateTime.from_naive!("Etc/UTC")}
defp load_utc_datetime(%DateTime{} = datetime),
do: {:ok, datetime |> check_utc_timezone!(:utc_datetime) |> truncate_usec()}
defp load_utc_datetime(_),
do: :error
defp load_utc_datetime_usec(%NaiveDateTime{} = naive_datetime),
do: {:ok, naive_datetime |> pad_usec() |> DateTime.from_naive!("Etc/UTC")}
defp load_utc_datetime_usec(%DateTime{} = datetime),
do: {:ok, datetime |> check_utc_timezone!(:utc_datetime_usec) |> pad_usec()}
defp load_utc_datetime_usec(_),
do: :error
defp load_embed(%{cardinality: :one}, nil, _fun), do: {:ok, nil}
defp load_embed(%{cardinality: :one, related: schema, field: field},
value, fun) when is_map(value) do
{:ok, load_embed(field, schema, value, fun)}
end
defp load_embed(%{cardinality: :many}, nil, _fun), do: {:ok, []}
defp load_embed(%{cardinality: :many, related: schema, field: field},
value, fun) when is_list(value) do
{:ok, Enum.map(value, &load_embed(field, schema, &1, fun))}
end
defp load_embed(_embed, _value, _fun) do
:error
end
defp load_embed(_field, schema, value, loader) when is_map(value) do
Ecto.Schema.Loader.unsafe_load(schema, value, loader)
end
defp load_embed(field, _schema, value, _fun) do
raise ArgumentError, "cannot load embed `#{field}`, invalid value: #{inspect value}"
end
@doc """
Casts a value to the given type.
`cast/2` is used by the finder queries and changesets to cast outside values to
specific types.
Note that nil can be cast to all primitive types as data stores allow nil to be
set on any column.
NaN and infinite decimals are not supported, use custom types instead.
iex> cast(:any, "whatever")
{:ok, "whatever"}
iex> cast(:any, nil)
{:ok, nil}
iex> cast(:string, nil)
{:ok, nil}
iex> cast(:integer, 1)
{:ok, 1}
iex> cast(:integer, "1")
{:ok, 1}
iex> cast(:integer, "1.0")
:error
iex> cast(:id, 1)
{:ok, 1}
iex> cast(:id, "1")
{:ok, 1}
iex> cast(:id, "1.0")
:error
iex> cast(:float, 1.0)
{:ok, 1.0}
iex> cast(:float, 1)
{:ok, 1.0}
iex> cast(:float, "1")
{:ok, 1.0}
iex> cast(:float, "1.0")
{:ok, 1.0}
iex> cast(:float, "1-foo")
:error
iex> cast(:boolean, true)
{:ok, true}
iex> cast(:boolean, false)
{:ok, false}
iex> cast(:boolean, "1")
{:ok, true}
iex> cast(:boolean, "0")
{:ok, false}
iex> cast(:boolean, "whatever")
:error
iex> cast(:string, "beef")
{:ok, "beef"}
iex> cast(:binary, "beef")
{:ok, "beef"}
iex> cast(:decimal, Decimal.new("1.0"))
{:ok, Decimal.new("1.0")}
iex> cast({:array, :integer}, [1, 2, 3])
{:ok, [1, 2, 3]}
iex> cast({:array, :integer}, ["1", "2", "3"])
{:ok, [1, 2, 3]}
iex> cast({:array, :string}, [1, 2, 3])
:error
iex> cast(:string, [1, 2, 3])
:error
"""
@spec cast(t, term) :: {:ok, term} | {:error, keyword()} | :error
def cast({:embed, type}, value), do: cast_embed(type, value)
def cast({:in, _type}, nil), do: :error
def cast(_type, nil), do: {:ok, nil}
def cast({:maybe, type}, value) do
case cast(type, value) do
{:ok, _} = ok -> ok
_ -> {:ok, value}
end
end
def cast(type, value) do
cast_fun(type).(value)
end
defp cast_fun(:integer), do: &cast_integer/1
defp cast_fun(:float), do: &cast_float/1
defp cast_fun(:boolean), do: &cast_boolean/1
defp cast_fun(:map), do: &cast_map/1
defp cast_fun(:string), do: &cast_binary/1
defp cast_fun(:binary), do: &cast_binary/1
defp cast_fun(:id), do: &cast_integer/1
defp cast_fun(:binary_id), do: &cast_binary/1
defp cast_fun(:any), do: &{:ok, &1}
defp cast_fun(:decimal), do: &cast_decimal/1
defp cast_fun(:date), do: &cast_date/1
defp cast_fun(:time), do: &maybe_truncate_usec(cast_time(&1))
defp cast_fun(:time_usec), do: &maybe_pad_usec(cast_time(&1))
defp cast_fun(:naive_datetime), do: &maybe_truncate_usec(cast_naive_datetime(&1))
defp cast_fun(:naive_datetime_usec), do: &maybe_pad_usec(cast_naive_datetime(&1))
defp cast_fun(:utc_datetime), do: &maybe_truncate_usec(cast_utc_datetime(&1))
defp cast_fun(:utc_datetime_usec), do: &maybe_pad_usec(cast_utc_datetime(&1))
defp cast_fun({:param, :any_datetime}), do: &cast_any_datetime(&1)
defp cast_fun({:in, type}), do: &array(&1, cast_fun(type), [])
defp cast_fun({:array, type}), do: &array(&1, cast_fun(type), [])
defp cast_fun({:map, type}), do: &map(&1, cast_fun(type), %{})
defp cast_fun(mod) when is_atom(mod), do: &mod.cast(&1)
defp cast_integer(term) when is_binary(term) do
case Integer.parse(term) do
{integer, ""} -> {:ok, integer}
_ -> :error
end
end
defp cast_integer(term) when is_integer(term), do: {:ok, term}
defp cast_integer(_), do: :error
defp cast_float(term) when is_binary(term) do
case Float.parse(term) do
{float, ""} -> {:ok, float}
_ -> :error
end
end
defp cast_float(term) when is_float(term), do: {:ok, term}
defp cast_float(term) when is_integer(term), do: {:ok, :erlang.float(term)}
defp cast_float(_), do: :error
defp cast_boolean(term) when term in ~w(true 1), do: {:ok, true}
defp cast_boolean(term) when term in ~w(false 0), do: {:ok, false}
defp cast_boolean(term) when is_boolean(term), do: {:ok, term}
defp cast_boolean(_), do: :error
defp cast_binary(term) when is_binary(term), do: {:ok, term}
defp cast_binary(_), do: :error
defp cast_map(term) when is_map(term), do: {:ok, term}
defp cast_map(_), do: :error
defp cast_decimal(term) when is_binary(term) do
case Decimal.parse(term) do
{:ok, decimal} -> check_decimal(decimal)
:error -> :error
end
end
defp cast_decimal(term) do
same_decimal(term)
end
defp cast_embed(%{cardinality: :one}, nil), do: {:ok, nil}
defp cast_embed(%{cardinality: :one, related: schema}, %{__struct__: schema} = struct) do
{:ok, struct}
end
defp cast_embed(%{cardinality: :many}, nil), do: {:ok, []}
defp cast_embed(%{cardinality: :many, related: schema}, value) when is_list(value) do
if Enum.all?(value, &Kernel.match?(%{__struct__: ^schema}, &1)) do
{:ok, value}
else
:error
end
end
defp cast_embed(_embed, _value) do
:error
end
## Adapter related
@doc false
def adapter_autogenerate(adapter, type) do
type
|> type()
|> adapter.autogenerate()
end
@doc false
def adapter_load(_adapter, {:embed, embed}, nil) do
load_embed(embed, nil, &load/2)
end
def adapter_load(_adapter, _type, nil) do
{:ok, nil}
end
def adapter_load(adapter, {:maybe, type}, value) do
case adapter_load(adapter, type, value) do
{:ok, _} = ok -> ok
:error -> {:ok, value}
end
end
def adapter_load(adapter, type, value) do
if of_base_type?(type, value) do
{:ok, value}
else
process_loaders(adapter.loaders(type(type), type), {:ok, value}, adapter)
end
end
defp process_loaders(_, :error, _adapter),
do: :error
defp process_loaders([fun|t], {:ok, value}, adapter) when is_function(fun),
do: process_loaders(t, fun.(value), adapter)
defp process_loaders([type|t], {:ok, value}, adapter),
do: process_loaders(t, load(type, value, &adapter_load(adapter, &1, &2)), adapter)
defp process_loaders([], {:ok, _} = acc, _adapter),
do: acc
@doc false
def adapter_dump(_adapter, type, nil),
do: dump(type, nil)
def adapter_dump(adapter, {:maybe, type}, value) do
case adapter_dump(adapter, type, value) do
{:ok, _} = ok -> ok
:error -> {:ok, value}
end
end
def adapter_dump(adapter, type, value),
do: process_dumpers(adapter.dumpers(type(type), type), {:ok, value}, adapter)
defp process_dumpers(_, :error, _adapter),
do: :error
defp process_dumpers([fun|t], {:ok, value}, adapter) when is_function(fun),
do: process_dumpers(t, fun.(value), adapter)
defp process_dumpers([type|t], {:ok, value}, adapter),
do: process_dumpers(t, dump(type, value, &adapter_dump(adapter, &1, &2)), adapter)
defp process_dumpers([], {:ok, _} = acc, _adapter),
do: acc
## Date
defp cast_date(binary) when is_binary(binary) do
case Date.from_iso8601(binary) do
{:ok, _} = ok ->
ok
{:error, _} ->
case NaiveDateTime.from_iso8601(binary) do
{:ok, naive_datetime} -> {:ok, NaiveDateTime.to_date(naive_datetime)}
{:error, _} -> :error
end
end
end
defp cast_date(%{"year" => empty, "month" => empty, "day" => empty}) when empty in ["", nil],
do: {:ok, nil}
defp cast_date(%{year: empty, month: empty, day: empty}) when empty in ["", nil],
do: {:ok, nil}
defp cast_date(%{"year" => year, "month" => month, "day" => day}),
do: cast_date(to_i(year), to_i(month), to_i(day))
defp cast_date(%{year: year, month: month, day: day}),
do: cast_date(to_i(year), to_i(month), to_i(day))
defp cast_date(_),
do: :error
defp cast_date(year, month, day) when is_integer(year) and is_integer(month) and is_integer(day) do
case Date.new(year, month, day) do
{:ok, _} = ok -> ok
{:error, _} -> :error
end
end
defp cast_date(_, _, _),
do: :error
## Time
defp cast_time(<<hour::2-bytes, ?:, minute::2-bytes>>),
do: cast_time(to_i(hour), to_i(minute), 0, nil)
defp cast_time(binary) when is_binary(binary) do
case Time.from_iso8601(binary) do
{:ok, _} = ok -> ok
{:error, _} -> :error
end
end
defp cast_time(%{"hour" => empty, "minute" => empty}) when empty in ["", nil],
do: {:ok, nil}
defp cast_time(%{hour: empty, minute: empty}) when empty in ["", nil],
do: {:ok, nil}
defp cast_time(%{"hour" => hour, "minute" => minute} = map),
do: cast_time(to_i(hour), to_i(minute), to_i(Map.get(map, "second")), to_i(Map.get(map, "microsecond")))
defp cast_time(%{hour: hour, minute: minute, second: second, microsecond: {microsecond, precision}}),
do: cast_time(to_i(hour), to_i(minute), to_i(second), {to_i(microsecond), to_i(precision)})
defp cast_time(%{hour: hour, minute: minute} = map),
do: cast_time(to_i(hour), to_i(minute), to_i(Map.get(map, :second)), to_i(Map.get(map, :microsecond)))
defp cast_time(_),
do: :error
defp cast_time(hour, minute, sec, usec) when is_integer(usec) do
cast_time(hour, minute, sec, {usec, 6})
end
defp cast_time(hour, minute, sec, nil) do
cast_time(hour, minute, sec, {0, 0})
end
defp cast_time(hour, minute, sec, {usec, precision})
when is_integer(hour) and is_integer(minute) and
(is_integer(sec) or is_nil(sec)) and is_integer(usec) and is_integer(precision) do
case Time.new(hour, minute, sec || 0, {usec, precision}) do
{:ok, _} = ok -> ok
{:error, _} -> :error
end
end
defp cast_time(_, _, _, _) do
:error
end
defp cast_any_datetime(%DateTime{} = datetime), do: cast_utc_datetime(datetime)
defp cast_any_datetime(other), do: cast_naive_datetime(other)
## Naive datetime
defp cast_naive_datetime("-" <> rest) do
with {:ok, naive_datetime} <- cast_naive_datetime(rest) do
{:ok, %{naive_datetime | year: naive_datetime.year * -1}}
end
end
defp cast_naive_datetime(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes, sep, hour::2-bytes, ?:, minute::2-bytes>>)
when sep in [?\s, ?T] do
case NaiveDateTime.new(to_i(year), to_i(month), to_i(day), to_i(hour), to_i(minute), 0) do
{:ok, _} = ok -> ok
_ -> :error
end
end
defp cast_naive_datetime(binary) when is_binary(binary) do
case NaiveDateTime.from_iso8601(binary) do
{:ok, _} = ok -> ok
{:error, _} -> :error
end
end
defp cast_naive_datetime(%{"year" => empty, "month" => empty, "day" => empty,
"hour" => empty, "minute" => empty}) when empty in ["", nil],
do: {:ok, nil}
defp cast_naive_datetime(%{year: empty, month: empty, day: empty,
hour: empty, minute: empty}) when empty in ["", nil],
do: {:ok, nil}
defp cast_naive_datetime(%{} = map) do
with {:ok, date} <- cast_date(map),
{:ok, time} <- cast_time(map) do
case NaiveDateTime.new(date, time) do
{:ok, _} = ok -> ok
{:error, _} -> :error
end
end
end
defp cast_naive_datetime(_) do
:error
end
## UTC datetime
defp cast_utc_datetime("-" <> rest) do
with {:ok, utc_datetime} <- cast_utc_datetime(rest) do
{:ok, %{utc_datetime | year: utc_datetime.year * -1}}
end
end
defp cast_utc_datetime(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes, sep, hour::2-bytes, ?:, minute::2-bytes>>)
when sep in [?\s, ?T] do
case NaiveDateTime.new(to_i(year), to_i(month), to_i(day), to_i(hour), to_i(minute), 0) do
{:ok, naive_datetime} -> {:ok, DateTime.from_naive!(naive_datetime, "Etc/UTC")}
_ -> :error
end
end
defp cast_utc_datetime(binary) when is_binary(binary) do
case DateTime.from_iso8601(binary) do
{:ok, datetime, _offset} -> {:ok, datetime}
{:error, :missing_offset} ->
case NaiveDateTime.from_iso8601(binary) do
{:ok, naive_datetime} -> {:ok, DateTime.from_naive!(naive_datetime, "Etc/UTC")}
{:error, _} -> :error
end
{:error, _} -> :error
end
end
defp cast_utc_datetime(%DateTime{time_zone: "Etc/UTC"} = datetime), do: {:ok, datetime}
defp cast_utc_datetime(%DateTime{} = datetime) do
case (datetime |> DateTime.to_unix(:microsecond) |> DateTime.from_unix(:microsecond)) do
{:ok, _} = ok -> ok
{:error, _} -> :error
end
end
defp cast_utc_datetime(value) do
case cast_naive_datetime(value) do
{:ok, %NaiveDateTime{} = naive_datetime} ->
{:ok, DateTime.from_naive!(naive_datetime, "Etc/UTC")}
{:ok, _} = ok ->
ok
:error ->
:error
end
end
@doc """
Checks if two terms are equal.
Depending on the given `type` performs a structural or semantical comparison.
## Examples
iex> equal?(:integer, 1, 1)
true
iex> equal?(:decimal, Decimal.new("1"), Decimal.new("1.00"))
true
"""
@spec equal?(t, term, term) :: boolean
def equal?(_, nil, nil), do: true
def equal?(type, term1, term2) do
if fun = equal_fun(type) do
fun.(term1, term2)
else
term1 == term2
end
end
defp equal_fun(nil), do: nil
defp equal_fun(:decimal), do: &equal_decimal?/2
defp equal_fun(t) when t in [:time, :time_usec], do: &equal_time?/2
defp equal_fun(t) when t in [:utc_datetime, :utc_datetime_usec], do: &equal_utc_datetime?/2
defp equal_fun(t) when t in [:naive_datetime, :naive_datetime_usec], do: &equal_naive_datetime?/2
defp equal_fun(t) when t in @base, do: nil
defp equal_fun({:array, type}) do
if fun = equal_fun(type) do
&equal_list?(fun, &1, &2)
end
end
defp equal_fun({:map, type}) do
if fun = equal_fun(type) do
&equal_map?(fun, &1, &2)
end
end
defp equal_fun(mod) when is_atom(mod) do
if loaded_and_exported?(mod, :equal?, 2) do
&mod.equal?/2
end
end
defp equal_decimal?(%Decimal{} = a, %Decimal{} = b), do: Decimal.equal?(a, b)
defp equal_decimal?(_, _), do: false
defp equal_time?(%Time{} = a, %Time{} = b), do: Time.compare(a, b) == :eq
defp equal_time?(_, _), do: false
defp equal_utc_datetime?(%DateTime{} = a, %DateTime{} = b), do: DateTime.compare(a, b) == :eq
defp equal_utc_datetime?(_, _), do: false
defp equal_naive_datetime?(%NaiveDateTime{} = a, %NaiveDateTime{} = b),
do: NaiveDateTime.compare(a, b) == :eq
defp equal_naive_datetime?(_, _),
do: false
defp equal_list?(fun, [nil | xs], [nil | ys]), do: equal_list?(fun, xs, ys)
defp equal_list?(fun, [x | xs], [y | ys]), do: fun.(x, y) and equal_list?(fun, xs, ys)
defp equal_list?(_fun, [], []), do: true
defp equal_list?(_fun, _, _), do: false
defp equal_map?(_fun, map1, map2) when map_size(map1) != map_size(map2) do
false
end
defp equal_map?(fun, %{} = map1, %{} = map2) do
equal_map?(fun, Map.to_list(map1), map2)
end
defp equal_map?(fun, [{key, nil} | tail], other_map) do
case other_map do
%{^key => nil} -> equal_map?(fun, tail, other_map)
_ -> false
end
end
defp equal_map?(fun, [{key, val} | tail], other_map) do
case other_map do
%{^key => other_val} -> fun.(val, other_val) and equal_map?(fun, tail, other_map)
_ -> false
end
end
defp equal_map?(_fun, [], _) do
true
end
defp equal_map?(_fun, _, _) do
false
end
## Helpers
# Checks if a value is of the given primitive type.
defp of_base_type?(:any, _), do: true
defp of_base_type?(:id, term), do: is_integer(term)
defp of_base_type?(:float, term), do: is_float(term)
defp of_base_type?(:integer, term), do: is_integer(term)
defp of_base_type?(:boolean, term), do: is_boolean(term)
defp of_base_type?(:binary, term), do: is_binary(term)
defp of_base_type?(:string, term), do: is_binary(term)
defp of_base_type?(:map, term), do: is_map(term) and not Map.has_key?(term, :__struct__)
defp of_base_type?(:decimal, value), do: Kernel.match?(%Decimal{}, value)
defp of_base_type?(:date, value), do: Kernel.match?(%Date{}, value)
defp of_base_type?(_, _), do: false
# nil always passes through
defp array([nil | t], fun, acc) do
array(t, fun, [nil | acc])
end
defp array([h | t], fun, acc) do
case fun.(h) do
{:ok, h} -> array(t, fun, [h | acc])
:error -> :error
{:error, _custom_errors} -> :error
end
end
defp array([], _fun, acc) do
{:ok, Enum.reverse(acc)}
end
defp array(_, _, _) do
:error
end
defp map(map, fun, acc) when is_map(map) do
map(Map.to_list(map), fun, acc)
end
# nil always passes through
defp map([{key, nil} | t], fun, acc) do
map(t, fun, Map.put(acc, key, nil))
end
defp map([{key, value} | t], fun, acc) do
case fun.(value) do
{:ok, value} -> map(t, fun, Map.put(acc, key, value))
:error -> :error
{:error, _custom_errors} -> :error
end
end
defp map([], _fun, acc) do
{:ok, acc}
end
defp map(_, _, _) do
:error
end
defp array([h | t], type, fun, acc) do
case fun.(type, h) do
{:ok, h} -> array(t, type, fun, [h | acc])
:error -> :error
end
end
defp array([], _type, _fun, acc) do
{:ok, Enum.reverse(acc)}
end
defp array(_, _, _, _) do
:error
end
defp map([{key, value} | t], type, fun, acc) do
case fun.(type, value) do
{:ok, value} -> map(t, type, fun, Map.put(acc, key, value))
:error -> :error
end
end
defp map([], _type, _fun, acc) do
{:ok, acc}
end
defp map(_, _, _, _) do
:error
end
defp to_i(nil), do: nil
defp to_i(int) when is_integer(int), do: int
defp to_i(bin) when is_binary(bin) do
case Integer.parse(bin) do
{int, ""} -> int
_ -> nil
end
end
@compile {:inline, loaded_and_exported?: 3}
# TODO: Remove this function when all Ecto types have been updated.
defp loaded_and_exported?(module, fun, arity) do
if :erlang.module_loaded(module) or Code.ensure_loaded?(module) do
function_exported?(module, fun, arity)
else
raise ArgumentError, "cannot use #{inspect(module)} as Ecto.Type, module is not available"
end
end
defp maybe_truncate_usec({:ok, struct}), do: {:ok, truncate_usec(struct)}
defp maybe_truncate_usec(:error), do: :error
defp maybe_pad_usec({:ok, struct}), do: {:ok, pad_usec(struct)}
defp maybe_pad_usec(:error), do: :error
defp truncate_usec(nil), do: nil
defp truncate_usec(%{microsecond: {0, 0}} = struct), do: struct
defp truncate_usec(struct), do: %{struct | microsecond: {0, 0}}
defp pad_usec(nil), do: nil
defp pad_usec(%{microsecond: {_, 6}} = struct), do: struct
defp pad_usec(%{microsecond: {microsecond, _}} = struct),
do: %{struct | microsecond: {microsecond, 6}}
defp check_utc_timezone!(%{time_zone: "Etc/UTC"} = datetime, _kind), do: datetime
defp check_utc_timezone!(datetime, kind) do
raise ArgumentError,
"#{inspect kind} expects the time zone to be \"Etc/UTC\", got `#{inspect(datetime)}`"
end
defp check_usec!(%{microsecond: {_, 6}} = datetime, _kind), do: datetime
defp check_usec!(datetime, kind) do
raise ArgumentError,
"#{inspect(kind)} expects microsecond precision, got: #{inspect(datetime)}"
end
defp check_no_usec!(%{microsecond: {0, 0}} = datetime, _kind), do: datetime
defp check_no_usec!(%struct{} = datetime, kind) do
raise ArgumentError, """
#{inspect(kind)} expects microseconds to be empty, got: #{inspect(datetime)}
Use `#{inspect(struct)}.truncate(#{kind}, :second)` (available in Elixir v1.6+) to remove microseconds.
"""
end
defp check_decimal(%Decimal{coef: coef}) when coef in [:inf, :qNaN, :sNaN], do: :error
defp check_decimal(%Decimal{} = decimal), do: {:ok, decimal}
defp check_decimal!(decimal) do
case check_decimal(decimal) do
{:ok, decimal} ->
decimal
:error ->
raise ArgumentError, """
#{inspect(decimal)} is not allowed for type :decimal
`+Infinity`, `-Infinity`, and `NaN` values are not supported, even though the `Decimal` library handles them. \
To support them, you can create a custom type.
"""
end
end
end
| 30.457249 | 124 | 0.62717 |
7910636f3866b50e9e996a43c089dba1d981e2ce | 69 | exs | Elixir | chapter3/challenges/mealcon/test/test_helper.exs | mCodex/rocketseat-ignite-elixir | bdb48db778c36b2325c75a41b4d6f7ef77b03cf5 | [
"MIT"
] | 1 | 2021-07-23T19:48:27.000Z | 2021-07-23T19:48:27.000Z | chapter3/challenges/mealcon/test/test_helper.exs | mCodex/rocketseat-ignite-elixir | bdb48db778c36b2325c75a41b4d6f7ef77b03cf5 | [
"MIT"
] | null | null | null | chapter3/challenges/mealcon/test/test_helper.exs | mCodex/rocketseat-ignite-elixir | bdb48db778c36b2325c75a41b4d6f7ef77b03cf5 | [
"MIT"
] | null | null | null | ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(Mealcon.Repo, :manual)
| 23 | 53 | 0.782609 |
7910668d2f2b812655a72116f010f4f89b80b426 | 2,629 | ex | Elixir | clients/translate/lib/google_api/translate/v3/model/translation.ex | jechol/elixir-google-api | 0290b683dfc6491ca2ef755a80bc329378738d03 | [
"Apache-2.0"
] | null | null | null | clients/translate/lib/google_api/translate/v3/model/translation.ex | jechol/elixir-google-api | 0290b683dfc6491ca2ef755a80bc329378738d03 | [
"Apache-2.0"
] | null | null | null | clients/translate/lib/google_api/translate/v3/model/translation.ex | jechol/elixir-google-api | 0290b683dfc6491ca2ef755a80bc329378738d03 | [
"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.Translate.V3.Model.Translation do
@moduledoc """
A single translation response.
## Attributes
* `detectedLanguageCode` (*type:* `String.t`, *default:* `nil`) - The BCP-47 language code of source text in the initial request, detected automatically, if no source language was passed within the initial request. If the source language was passed, auto-detection of the language does not occur and this field is empty.
* `glossaryConfig` (*type:* `GoogleApi.Translate.V3.Model.TranslateTextGlossaryConfig.t`, *default:* `nil`) - The `glossary_config` used for this translation.
* `model` (*type:* `String.t`, *default:* `nil`) - Only present when `model` is present in the request. `model` here is normalized to have project number. For example: If the `model` requested in TranslationTextRequest is `projects/{project-id}/locations/{location-id}/models/general/nmt` then `model` here would be normalized to `projects/{project-number}/locations/{location-id}/models/general/nmt`.
* `translatedText` (*type:* `String.t`, *default:* `nil`) - Text translated into the target language.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:detectedLanguageCode => String.t() | nil,
:glossaryConfig => GoogleApi.Translate.V3.Model.TranslateTextGlossaryConfig.t() | nil,
:model => String.t() | nil,
:translatedText => String.t() | nil
}
field(:detectedLanguageCode)
field(:glossaryConfig, as: GoogleApi.Translate.V3.Model.TranslateTextGlossaryConfig)
field(:model)
field(:translatedText)
end
defimpl Poison.Decoder, for: GoogleApi.Translate.V3.Model.Translation do
def decode(value, options) do
GoogleApi.Translate.V3.Model.Translation.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Translate.V3.Model.Translation do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 46.946429 | 405 | 0.736021 |
791068c6f43717eda8c24ff417148c397b3c0886 | 32,689 | ex | Elixir | lib/sparql/functions/builtins.ex | marcelotto/sparql-ex | 7bf939a2b0eec7e1096f6fdb999b07757995c145 | [
"MIT"
] | 23 | 2018-09-25T21:09:35.000Z | 2020-05-14T16:28:22.000Z | lib/sparql/functions/builtins.ex | marcelotto/sparql-ex | 7bf939a2b0eec7e1096f6fdb999b07757995c145 | [
"MIT"
] | 2 | 2018-06-01T20:47:48.000Z | 2019-03-05T23:20:34.000Z | lib/sparql/functions/builtins.ex | marcelotto/sparql-ex | 7bf939a2b0eec7e1096f6fdb999b07757995c145 | [
"MIT"
] | 2 | 2019-12-13T19:20:54.000Z | 2019-12-20T08:23:21.000Z | defmodule SPARQL.Functions.Builtins do
require Logger
alias RDF.{IRI, BlankNode, Literal, XSD, NS}
# Value equality
# - <https://www.w3.org/TR/sparql11-query/#OperatorMapping>
# - <https://www.w3.org/TR/sparql11-query/#func-RDFterm-equal>
def call(:=, [left, right], _) do
left |> RDF.Term.equal_value?(right) |> ebv()
end
# Value inequality
# - <https://www.w3.org/TR/sparql11-query/#OperatorMapping>
# - <https://www.w3.org/TR/sparql11-query/#func-RDFterm-equal>
def call(:!=, [left, right], _) do
left |> RDF.Term.equal_value?(right) |> fn_not()
end
# sameTerm equality
# - <https://www.w3.org/TR/sparql11-query/#func-sameTerm>
def call(:sameTerm, [left, right], _) do
left |> RDF.Term.equal?(right) |> ebv()
end
# Less-than operator
# - <https://www.w3.org/TR/sparql11-query/#OperatorMapping>
def call(:<, [%Literal{} = left, %Literal{} = right], _) do
case Literal.compare(left, right) do
:lt -> true
nil -> nil
_ -> false
end
|> ebv()
end
def call(:<, _, _), do: :error
# Greater-than operator
# - <https://www.w3.org/TR/sparql11-query/#OperatorMapping>
def call(:>, [%Literal{} = left, %Literal{} = right], _) do
case Literal.compare(left, right) do
:gt -> true
nil -> nil
_ -> false
end
|> ebv()
end
def call(:>, _, _), do: :error
# Greater-or-equal operator
# - <https://www.w3.org/TR/sparql11-query/#OperatorMapping>
def call(:>=, [%Literal{} = left, %Literal{} = right], _) do
case Literal.compare(left, right) do
:gt -> XSD.true
:eq -> XSD.true
:lt -> XSD.false
_ -> :error
end
end
def call(:>=, _, _), do: :error
# Less-or-equal operator
# - <https://www.w3.org/TR/sparql11-query/#OperatorMapping>
def call(:<=, [%Literal{} = left, %Literal{} = right], _) do
case Literal.compare(left, right) do
:lt -> XSD.true
:eq -> XSD.true
:gt -> XSD.false
_ -> :error
end
end
def call(:<=, _, _), do: :error
# Logical `NOT`
#
# Returns `RDF.XSD.true` if the effective boolean value of the given argument is
# `RDF.XSD.false`, or `RDF.XSD.false` if it is `RDF.XSD.true`. Otherwise it returns `error`.
#
# - <http://www.w3.org/TR/xpath-functions/#func-not>
def call(:!, [argument], _) do
fn_not(argument)
end
# Numeric unary plus
# - <http://www.w3.org/TR/xpath-functions/#func-numeric-unary-plus>
def call(:+, [number], _) do
if XSD.Numeric.datatype?(number) do
number
else
:error
end
end
# Numeric unary minus
# - <http://www.w3.org/TR/xpath-functions/#func-numeric-unary-minus>
def call(:-, [number], _) do
if XSD.Numeric.datatype?(number) do
XSD.Numeric.multiply(number, -1)
else
:error
end
end
# Numeric addition
# - <http://www.w3.org/TR/xpath-functions/#func-numeric-add>
def call(:+, [left, right], _) do
XSD.Numeric.add(left, right) || :error
end
# Numeric subtraction
# - <http://www.w3.org/TR/xpath-functions/#func-numeric-subtract>
def call(:-, [left, right], _) do
XSD.Numeric.subtract(left, right) || :error
end
# Numeric multiplication
# - <http://www.w3.org/TR/xpath-functions/#func-numeric-multiply>
def call(:*, [left, right], _) do
XSD.Numeric.multiply(left, right) || :error
end
# Numeric division
# - <http://www.w3.org/TR/xpath-functions/#func-numeric-divide>
def call(:/, [left, right], _) do
XSD.Numeric.divide(left, right) || :error
end
# Checks if the given argument is an IRI.
# - <https://www.w3.org/TR/sparql11-query/#func-isIRI>
def call(:isIRI, [%IRI{}], _), do: XSD.true
def call(:isIRI, [:error], _), do: :error
def call(:isIRI, _, _), do: XSD.false
# Checks if the given argument is an IRI.
# - <https://www.w3.org/TR/sparql11-query/#func-isIRI>
def call(:isURI, args, execution), do: call(:isIRI, args, execution)
# Checks if the given argument is a blank node.
# - <https://www.w3.org/TR/sparql11-query/#func-isBlank>
def call(:isBLANK, [%BlankNode{}], _), do: XSD.true
def call(:isBLANK, [:error], _), do: :error
def call(:isBLANK, _, _), do: XSD.false
# Checks if the given argument is a RDF literal.
# - <https://www.w3.org/TR/sparql11-query/#func-isLiteral>
def call(:isLITERAL, [%Literal{}], _), do: XSD.true
def call(:isLITERAL, [:error], _), do: :error
def call(:isLITERAL, _, _), do: XSD.false
# Checks if the given argument is a RDF literal with a numeric datatype.
# - <https://www.w3.org/TR/sparql11-query/#func-isNumeric>
def call(:isNUMERIC, [%Literal{} = literal], _) do
if XSD.Numeric.datatype?(literal) and Literal.valid?(literal) do
XSD.true
else
XSD.false
end
end
def call(:isNUMERIC, [:error], _), do: :error
def call(:isNUMERIC, _, _), do: XSD.false
# Returns the lexical form of a literal or the codepoint representation of an IRI
# - <https://www.w3.org/TR/sparql11-query/#func-str>
def call(:STR, [%Literal{} = literal], _), do: literal |> to_string() |> XSD.string()
def call(:STR, [%IRI{} = iri], _), do: iri |> to_string() |> XSD.string()
def call(:STR, _, _), do: :error
# Returns the language tag of language tagged literal.
#
# It returns `~L""` if the given literal has no language tag. Note that the RDF
# data model does not include literals with an empty language tag.
#
# - <https://www.w3.org/TR/sparql11-query/#func-lang>
def call(:LANG, [%Literal{} = literal], _),
do: literal |> Literal.language() |> to_string() |> XSD.string()
def call(:LANG, _, _), do: :error
# Returns the datatype IRI of a literal.
# - <https://www.w3.org/TR/sparql11-query/#func-datatype>
def call(:DATATYPE, [%Literal{} = literal], _), do: Literal.datatype_id(literal)
def call(:DATATYPE, _, _), do: :error
# Constructs a literal with lexical form and type as specified by the arguments.
# - <https://www.w3.org/TR/sparql11-query/#func-strdt>
def call(:STRDT, [%Literal{literal: %XSD.String{}} = literal, %IRI{} = datatype], _) do
literal |> Literal.lexical() |> Literal.new(datatype: datatype)
end
def call(:STRDT, _, _), do: :error
# Constructs a literal with lexical form and language tag as specified by the arguments.
# - <https://www.w3.org/TR/sparql11-query/#func-strlang>
def call(:STRLANG, [%Literal{literal: %XSD.String{}} = lexical_form_literal,
%Literal{literal: %XSD.String{}} = language_literal], _) do
language = language_literal |> to_string() |> String.trim()
if language != "" do
RDF.LangString.new(to_string(lexical_form_literal), language: language)
else
:error
end
end
def call(:STRLANG, _, _), do: :error
# Constructs an IRI from the given string argument.
#
# It constructs an IRI by resolving the string argument (see RFC 3986 and RFC 3987
# or any later RFC that supersedes RFC 3986 or RFC 3987). The IRI is resolved
# against the base IRI of the query and must result in an absolute IRI.
#
# - <https://www.w3.org/TR/sparql11-query/#func-iri>
def call(:IRI, [%Literal{literal: %XSD.String{}} = literal], execution) do
literal |> to_string() |> IRI.absolute(Map.get(execution, :base)) || :error
end
def call(:IRI, [%IRI{} = iri], _), do: iri
def call(:IRI, _, _), do: :error
# Checks if the given argument is an IRI.
#
# Alias for `IRI`.
#
# - <https://www.w3.org/TR/sparql11-query/#func-isIRI>
def call(:URI, args, execution), do: call(:IRI, args, execution)
# Constructs a blank node.
#
# The constructed blank node is distinct from all blank nodes in the dataset
# being queried and distinct from all blank nodes created by calls to this
# constructor for other query solutions.
#
# If the no argument form is used, every call results in a distinct blank node.
# If the form with a simple literal is used, every call results in distinct
# blank nodes for different simple literals, and the same blank node for calls
# with the same simple literal within expressions for one solution mapping.
#
# - <https://www.w3.org/TR/sparql11-query/#func-bnode>
def call(:BNODE, [], %{bnode_generator: generator}) do
BlankNode.Generator.generate(generator)
end
def call(:BNODE, [%Literal{literal: %XSD.String{}} = literal],
%{bnode_generator: generator, solution_id: solution_id}) do
BlankNode.Generator.generate_for(generator, {solution_id, to_string(literal)})
end
def call(:BNODE, _, _), do: :error
# Return a fresh IRI from the UUID URN scheme.
#
# Each call of UUID() returns a different UUID.
#
# Currently, UUID v4 ids according to RFC 4122 are produced.
#
# - <https://www.w3.org/TR/sparql11-query/#func-uuid>
def call(:UUID, [], _), do: uuid(:urn) |> IRI.new()
def call(:UUID, _, _), do: :error
# Return a string literal that is the scheme specific part of UUID.
#
# Currently, UUID v4 ids according to RFC 4122 are produced.
#
# - <https://www.w3.org/TR/sparql11-query/#func-struuid>
def call(:STRUUID, [], _), do: uuid(:default) |> XSD.string()
def call(:STRUUID, _, _), do: :error
# Returns an `xsd:integer` equal to the length in characters of the lexical form of a literal.
# - <https://www.w3.org/TR/sparql11-query/#func-strlen>
# - <http://www.w3.org/TR/xpath-functions/#func-string-length>
def call(:STRLEN, [%Literal{literal: %datatype{}} = literal], _)
when datatype in [XSD.String, RDF.LangString],
do: literal |> to_string() |> String.length() |> XSD.integer()
def call(:STRLEN, _, _), do: :error
# Returns a portion of a string .
#
# The arguments startingLoc and length may be derived types of `xsd:integer`. The
# index of the first character in a strings is 1.
#
# Returns a literal of the same kind (simple literal, literal with language tag,
# xsd:string typed literal) as the source input parameter but with a lexical form
# formed from the substring of the lexical form of the source.
#
# The substr function corresponds to the XPath `fn:substring` function.
#
# - <https://www.w3.org/TR/sparql11-query/#func-substr>
# - <http://www.w3.org/TR/xpath-functions/#func-substring>
def call(:SUBSTR, [%Literal{literal: %source_datatype{}} = source, %Literal{} = starting_loc], _)
when source_datatype in [XSD.String, RDF.LangString] do
if XSD.Integer.valid?(starting_loc) do
Literal.update(source, fn source_string ->
String.slice(source_string, (XSD.Integer.value(starting_loc) - 1) .. -1)
end)
else
:error
end
end
def call(:SUBSTR, [%Literal{literal: %source_datatype{}} = source,
%Literal{} = starting_loc, %Literal{} = length], _)
when source_datatype in [XSD.String, RDF.LangString] do
if XSD.Integer.valid?(starting_loc) and XSD.Integer.valid?(length) do
Literal.update(source, fn source_string ->
String.slice(source_string, (XSD.Integer.value(starting_loc) - 1), XSD.Integer.value(length))
end)
else
:error
end
end
def call(:SUBSTR, _, _), do: :error
# Returns a string literal whose lexical form is the upper case of the lexcial form of the argument.
#
# The UCASE function corresponds to the XPath `fn:upper-case` function.
#
# - <https://www.w3.org/TR/sparql11-query/#func-ucase>
# - <http://www.w3.org/TR/xpath-functions/#func-upper-case>
def call(:UCASE, [%Literal{literal: %datatype{}} = str], _)
when datatype in [XSD.String, RDF.LangString] do
Literal.update(str, &String.upcase/1)
end
def call(:UCASE, _, _), do: :error
# Returns a string literal whose lexical form is the lower case of the lexcial form of the argument.
#
# The LCASE function corresponds to the XPath `fn:lower-case` function.
#
# - <https://www.w3.org/TR/sparql11-query/#func-lcase>
# - <http://www.w3.org/TR/xpath-functions/#func-lower-case>
def call(:LCASE, [%Literal{literal: %datatype{}} = str], _)
when datatype in [XSD.String, RDF.LangString] do
Literal.update(str, &String.downcase/1)
end
def call(:LCASE, _, _), do: :error
# Returns true if the lexical form of arg1 starts with the lexical form of arg2, otherwise it returns false.
#
# The STRSTARTS function corresponds to the XPath `fn:starts-with` function.
#
# The arguments must be `compatible_arguments?/2` otherwise `:error` is returned.
#
# - <https://www.w3.org/TR/sparql11-query/#func-strstarts>
# - <http://www.w3.org/TR/xpath-functions/#func-starts-with>
def call(:STRSTARTS, [arg1, arg2], _) do
if compatible_arguments?(arg1, arg2) do
if arg1 |> to_string() |> String.starts_with?(to_string(arg2)) do
XSD.true
else
XSD.false
end
else
:error
end
end
def call(:STRSTARTS, _, _), do: :error
# Returns true if the lexical form of arg1 ends with the lexical form of arg2, otherwise it returns false.
#
# The STRENDS function corresponds to the XPath `fn:ends-with` function.
#
# The arguments must be `compatible_arguments?/2` otherwise `:error` is returned.
#
# - <https://www.w3.org/TR/sparql11-query/#func-strends>
# - <http://www.w3.org/TR/xpath-functions/#func-ends-with>
def call(:STRENDS, [arg1, arg2], _) do
if compatible_arguments?(arg1, arg2) do
if arg1 |> to_string() |> String.ends_with?(to_string(arg2)) do
XSD.true
else
XSD.false
end
else
:error
end
end
def call(:STRENDS, _, _), do: :error
# Returns true if the lexical form of arg1 contains the lexical form of arg2, otherwise it returns false.
#
# The CONTAINS function corresponds to the XPath `fn:contains` function.
#
# The arguments must be `compatible_arguments?/2` otherwise `:error` is returned.
#
# - <https://www.w3.org/TR/sparql11-query/#func-contains>
# - <http://www.w3.org/TR/xpath-functions/#func-contains>
def call(:CONTAINS, [arg1, arg2], _) do
if compatible_arguments?(arg1, arg2) do
if arg1 |> to_string() |> String.contains?(to_string(arg2)) do
XSD.true
else
XSD.false
end
else
:error
end
end
def call(:CONTAINS, _, _), do: :error
# Returns the substring of the lexical form of arg1 that precedes the first occurrence of the lexical form of arg2.
#
# The STRBEFORE function corresponds to the XPath `fn:substring-before` function.
#
# The arguments must be `compatible_arguments?/2` otherwise `:error` is returned.
#
# For compatible arguments, if the lexical part of the second argument occurs as
# a substring of the lexical part of the first argument, the function returns a
# literal of the same kind as the first argument arg1 (simple literal, plain
# literal same language tag, xsd:string). The lexical form of the result is the
# substring of the lexical form of arg1 that precedes the first occurrence of
# the lexical form of arg2. If the lexical form of arg2 is the empty string,
# this is considered to be a match and the lexical form of the result is the
# empty string.
#
# If there is no such occurrence, an empty simple literal is returned.
#
# - <https://www.w3.org/TR/sparql11-query/#func-strbefore>
# - <http://www.w3.org/TR/xpath-functions/#func-substring-before>
def call(:STRBEFORE, [arg1, arg2], _) do
cond do
not compatible_arguments?(arg1, arg2) -> :error
Literal.lexical(arg2) == "" -> Literal.update(arg1, fn _ -> "" end)
true ->
case String.split(Literal.lexical(arg1), Literal.lexical(arg2), parts: 2) do
[left, _] -> Literal.update(arg1, fn _ -> left end)
[_] -> Literal.new("")
end
end
end
def call(:STRBEFORE, _, _), do: :error
# Returns the substring of the lexical form of arg1 that follows the first occurrence of the lexical form of arg2.
#
# The STRAFTER function corresponds to the XPath `fn:substring-before` function.
#
# The arguments must be `compatible_arguments?/2` otherwise `:error` is returned.
#
# For compatible arguments, if the lexical part of the second argument occurs as
# a substring of the lexical part of the first argument, the function returns a
# literal of the same kind as the first argument arg1 (simple literal, plain
# literal same language tag, xsd:string). The lexical form of the result is the
# substring of the lexical form of arg1 that precedes the first occurrence of
# the lexical form of arg2. If the lexical form of arg2 is the empty string,
# this is considered to be a match and the lexical form of the result is the
# lexical form of arg1.
#
# If there is no such occurrence, an empty simple literal is returned.
#
# - <https://www.w3.org/TR/sparql11-query/#func-strafter>
# - <http://www.w3.org/TR/xpath-functions/#func-substring-after>
def call(:STRAFTER, [arg1, arg2], _) do
cond do
not compatible_arguments?(arg1, arg2) -> :error
Literal.lexical(arg2) == "" -> arg1
true ->
case String.split(Literal.lexical(arg1), Literal.lexical(arg2), parts: 2) do
[_, right] -> Literal.update(arg1, fn _ -> right end)
[_] -> Literal.new("")
end
end
end
def call(:STRAFTER, _, _), do: :error
# Returns a simple literal with the lexical form obtained from the lexical form of its input after translating reserved characters according to the fn:encode-for-uri function.
#
# The ENCODE_FOR_URI function corresponds to the XPath `fn:encode-for-uri` function.
#
# - <https://www.w3.org/TR/sparql11-query/#func-encode>
# - <http://www.w3.org/TR/xpath-functions/#func-encode-for-uri>
def call(:ENCODE_FOR_URI, [%Literal{literal: %datatype{}} = str], _)
when datatype in [XSD.String, RDF.LangString] do
str
|> to_string()
|> URI.encode(&URI.char_unreserved?/1)
|> Literal.new()
end
def call(:ENCODE_FOR_URI, _, _), do: :error
# Returns a string literal with the lexical form being obtained by concatenating the lexical forms of its inputs.
#
# If all input literals are typed literals of type `xsd:string`, then the returned
# literal is also of type `xsd:string`, if all input literals are plain literals
# with identical language tag, then the returned literal is a plain literal with
# the same language tag, in all other cases, the returned literal is a simple literal.
#
# The CONCAT function corresponds to the XPath `fn:concat` function.
#
# - <https://www.w3.org/TR/sparql11-query/#func-concat>
# - <http://www.w3.org/TR/xpath-functions/#func-concat>
def call(:CONCAT, [], _), do: XSD.string("")
def call(:CONCAT, [%Literal{literal: %datatype{}} = first |rest], _)
when datatype in [XSD.String, RDF.LangString] do
rest
|> Enum.reduce_while({to_string(first), Literal.language(first)}, fn
%Literal{literal: %datatype{}} = str, {acc, language}
when datatype in [XSD.String, RDF.LangString] ->
{:cont, {
acc <> to_string(str),
if language && language == Literal.language(str) do
language
else
nil
end
}
}
_, _ ->
{:halt, :error}
end)
|> case do
{str, nil} -> XSD.string(str)
{str, language} -> RDF.lang_string(str, language: language)
_ -> :error
end
end
def call(:CONCAT, _, _), do: :error
# Checks if a language tagged string literal or language tag matches a language range.
#
# The check is performed per the basic filtering scheme defined in
# [RFC4647](http://www.ietf.org/rfc/rfc4647.txt) section 3.3.1.
# A language range is a basic language range per _Matching of Language Tags_ in
# RFC4647 section 2.1.
# A language range of `"*"` matches any non-empty language-tag string.
#
# - <https://www.w3.org/TR/sparql11-query/#func-langMatches>
def call(:LANGMATCHES, [%Literal{literal: %XSD.String{value: language_tag}},
%Literal{literal: %XSD.String{value: language_range}}], _) do
if RDF.LangString.match_language?(language_tag, language_range) do
XSD.true
else
XSD.false
end
end
def call(:LANGMATCHES, _, _), do: :error
# Matches text against a regular expression pattern.
#
# The regular expression language is defined in _XQuery 1.0 and XPath 2.0 Functions and Operators_.
#
# - <https://www.w3.org/TR/sparql11-query/#func-regex>
# - <https://www.w3.org/TR/xpath-functions/#func-matches>
def call(:REGEX, [text, pattern], _), do: match_regex(text, pattern, XSD.string(""))
def call(:REGEX, [text, pattern, flags], _), do: match_regex(text, pattern, flags)
def call(:REGEX, _, _), do: :error
# Replaces each non-overlapping occurrence of the regular expression pattern with the replacement string.
#
# Regular expression matching may involve modifier flags. See REGEX.
#
# - <https://www.w3.org/TR/sparql11-query/#func-replace>
# - <http://www.w3.org/TR/xpath-functions/#func-replace>
def call(:REPLACE, [text, pattern, replacement], _),
do: replace_regex(text, pattern, replacement, XSD.string(""))
def call(:REPLACE, [text, pattern, replacement, flags], _),
do: replace_regex(text, pattern, replacement, flags)
def call(:REPLACE, _, _), do: :error
# Returns the absolute value of the argument.
#
# If the argument is not a numeric value `:error` is returned.
#
# - <https://www.w3.org/TR/sparql11-query/#func-abs>
# - <http://www.w3.org/TR/xpath-functions/#func-abs>
def call(:ABS, [%Literal{} = literal], _) do
XSD.Numeric.abs(literal) || :error
end
def call(:ABS, _, _), do: :error
# Rounds a value to a specified number of decimal places, rounding upwards if two such values are equally near.
#
# The function returns the nearest (that is, numerically closest) value to the
# given literal value that is a multiple of ten to the power of minus `precision`.
# If two such values are equally near (for example, if the fractional part in the
# literal value is exactly .5), the function returns the one that is closest to
# positive infinity.
#
# If the argument is not a numeric value `:error` is returned.
#
# - <https://www.w3.org/TR/sparql11-query/#func-round>
# - <http://www.w3.org/TR/xpath-functions/#func-round>
def call(:ROUND, [%Literal{} = literal], _) do
XSD.Numeric.round(literal) || :error
end
def call(:ROUND, _, _), do: :error
# Rounds a numeric value upwards to a whole number.
#
# If the argument is not a numeric value `:error` is returned.
#
# - <https://www.w3.org/TR/sparql11-query/#func-ceil>
# - <http://www.w3.org/TR/xpath-functions/#func-ceil>
def call(:CEIL, [%Literal{} = literal], _) do
XSD.Numeric.ceil(literal) || :error
end
def call(:CEIL, _, _), do: :error
# Rounds a numeric value downwards to a whole number.
#
# If the argument is not a numeric value `:error` is returned.
#
# - <https://www.w3.org/TR/sparql11-query/#func-floor>
# - <http://www.w3.org/TR/xpath-functions/#func-floor>
def call(:FLOOR, [%Literal{} = literal], _) do
XSD.Numeric.floor(literal) || :error
end
def call(:FLOOR, _, _), do: :error
# Returns a pseudo-random number between 0 (inclusive) and 1.0e0 (exclusive).
# - <https://www.w3.org/TR/sparql11-query/#idp2130040>
def call(:RAND, [], _) do
:rand.uniform() |> XSD.double()
end
def call(:RAND, _, _), do: :error
# Returns an XSD dateTime value for the current query execution.
#
# All calls to this function in any one query execution return the same value.
#
# - <https://www.w3.org/TR/sparql11-query/#func-now>
def call(:NOW, [], %{time: time}) do
XSD.date_time(time)
end
def call(:NOW, _, _), do: :error
# Returns the year part of the given datetime as an integer.
# - <https://www.w3.org/TR/sparql11-query/#func-year>
# - <https://www.w3.org/TR/xpath-functions/#func-year-from-dateTime>
def call(:YEAR, [%Literal{literal: %XSD.DateTime{} = literal}], _) do
naive_datetime_part(literal, :year)
end
def call(:YEAR, _, _), do: :error
# Returns the month part of the given datetime as an integer.
# - <https://www.w3.org/TR/sparql11-query/#func-month>
# - <https://www.w3.org/TR/xpath-functions/#func-month-from-dateTime>
def call(:MONTH, [%Literal{literal: %XSD.DateTime{} = literal}], _) do
naive_datetime_part(literal, :month)
end
def call(:MONTH, _, _), do: :error
# Returns the day part of the given datetime as an integer.
# - <https://www.w3.org/TR/sparql11-query/#func-day>
# - <https://www.w3.org/TR/xpath-functions/#func-day-from-dateTime>
def call(:DAY, [%Literal{literal: %XSD.DateTime{} = literal}], _) do
naive_datetime_part(literal, :day)
end
def call(:DAY, _, _), do: :error
# Returns the hours part of the given datetime as an integer.
# - <https://www.w3.org/TR/sparql11-query/#func-hours>
# - <https://www.w3.org/TR/xpath-functions/#func-hours-from-dateTime>
def call(:HOURS, [%Literal{literal: %XSD.DateTime{} = literal}], _) do
naive_datetime_part(literal, :hour)
end
def call(:HOURS, _, _), do: :error
# Returns the minutes part of the given datetime as an integer.
# - <https://www.w3.org/TR/sparql11-query/#func-minutes>
# - <https://www.w3.org/TR/xpath-functions/#func-minutes-from-dateTime>
def call(:MINUTES, [%Literal{literal: %XSD.DateTime{} = literal}], _) do
naive_datetime_part(literal, :minute)
end
def call(:MINUTES, _, _), do: :error
# Returns the seconds part of the given datetime as a decimal.
# - <https://www.w3.org/TR/sparql11-query/#func-seconds>
# - <https://www.w3.org/TR/xpath-functions/#func-seconds-from-dateTime>
def call(:SECONDS, [%Literal{literal: %XSD.DateTime{} = literal}], _) do
if XSD.DateTime.valid?(literal) do
case literal.value.microsecond do
{_, 0} ->
literal.value.second
|> to_string() # This is needed to get the lexical integer form; required for the SPARQL 1.1 test suite
|> XSD.decimal()
{microsecond, _} ->
%Decimal{coef: microsecond, exp: -6}
|> Decimal.add(literal.value.second)
|> XSD.decimal()
_ ->
:error
end
else
:error
end
end
def call(:SECONDS, _, _), do: :error
# Returns the timezone part of the given datetime as an `xsd:dayTimeDuration` literal.
#
# Returns `:error` if there is no timezone.
#
# - <https://www.w3.org/TR/sparql11-query/#func-timezone>
# - <http://www.w3.org/TR/xpath-functions/#func-timezone-from-dateTime>
def call(:TIMEZONE, [%Literal{literal: %XSD.DateTime{} = literal}], _) do
literal
|> XSD.DateTime.tz()
|> tz_duration()
|| :error
end
def call(:TIMEZONE, _, _), do: :error
# Returns the timezone part of a given datetime as a simple literal or the empty string if there is no timezone.
# - <https://www.w3.org/TR/sparql11-query/#func-tz>
def call(:TZ, [%Literal{literal: %XSD.DateTime{} = literal}], _) do
if tz = XSD.DateTime.tz(literal) do
XSD.string(tz)
else
:error
end
end
def call(:TZ, _, _), do: :error
# Returns the MD5 checksum, as a hex digit string.
# - <https://www.w3.org/TR/sparql11-query/#func-md5>
def call(:MD5, [%Literal{literal: %XSD.String{}} = literal], _) do
hash(:md5, Literal.value(literal))
end
def call(:MD5, _, _), do: :error
# Returns the SHA1 checksum, as a hex digit string.
# - <https://www.w3.org/TR/sparql11-query/#func-sha1>
def call(:SHA1, [%Literal{literal: %XSD.String{}} = literal], _) do
hash(:sha, Literal.value(literal))
end
def call(:SHA1, _, _), do: :error
@doc """
Returns the SHA256 checksum, as a hex digit string.
- <https://www.w3.org/TR/sparql11-query/#func-sha256>
"""
def call(:SHA256, [%Literal{literal: %XSD.String{}} = literal], _) do
hash(:sha256, Literal.value(literal))
end
def call(:SHA256, _, _), do: :error
# Returns the SHA384 checksum, as a hex digit string.
# - <https://www.w3.org/TR/sparql11-query/#fun c-sha384>
def call(:SHA384, [%Literal{literal: %XSD.String{}} = literal], _) do
hash(:sha384, Literal.value(literal))
end
def call(:SHA384, _, _), do: :error
# Returns the SHA512 checksum, as a hex digit string.
# - <https://www.w3.org/TR/sparql11-query/#func-sha512>
def call(:SHA512, [%Literal{literal: %XSD.String{}} = literal], _) do
hash(:sha512, Literal.value(literal))
end
def call(:SHA512, _, _), do: :error
defp hash(type, value) do
:crypto.hash(type, value)
|> Base.encode16()
|> String.downcase()
|> XSD.string()
end
defp match_regex(%Literal{literal: %datatype{}} = text,
%Literal{literal: %XSD.String{}} = pattern,
%Literal{literal: %XSD.String{}} = flags)
when datatype in [XSD.String, RDF.LangString] do
text
|> Literal.matches?(pattern, flags)
|> ebv()
rescue
_error -> :error
end
defp match_regex(_, _, _), do: :error
defp replace_regex(%Literal{literal: %datatype{}} = text,
%Literal{literal: %XSD.String{} = pattern},
%Literal{literal: %XSD.String{} = replacement},
%Literal{literal: %XSD.String{} = flags})
when datatype in [XSD.String, RDF.LangString] do
case XSD.Utils.Regex.xpath_pattern(pattern.value, flags.value) do
{:regex, regex} ->
Literal.update(text, fn text_value ->
String.replace(text_value, regex, xpath_to_erlang_regex_variables(replacement.value))
end)
{:q, pattern} ->
Literal.update(text, fn text_value ->
String.replace(text_value, pattern, replacement.value)
end)
{:qi, _pattern} ->
Logger.error "The combination of the q and the i flag is currently not supported in REPLACE"
:error
_ ->
:error
end
end
defp replace_regex(_, _, _, _), do: :error
defp xpath_to_erlang_regex_variables(text) do
String.replace(text, ~r/(?<!\\)\$/, "\\")
end
defp naive_datetime_part(%XSD.DateTime{value: %DateTime{} = datetime,
uncanonical_lexical: nil}, field) do
datetime
|> Map.get(field)
|> XSD.integer()
end
defp naive_datetime_part(%XSD.DateTime{value: %NaiveDateTime{} = datetime}, field) do
datetime
|> Map.get(field)
|> XSD.integer()
end
defp naive_datetime_part(literal, field) do
with {:ok, datetime} <-
literal
|> XSD.DateTime.lexical()
|> NaiveDateTime.from_iso8601()
do
datetime
|> Map.get(field)
|> XSD.integer()
else
_ -> :error
end
end
defp tz_duration(""), do: nil
defp tz_duration("Z"), do: day_time_duration("PT0S")
defp tz_duration(tz) do
[_, sign, hours, minutes] = Regex.run(~r/\A(?:([\+\-])(\d{2}):(\d{2}))\Z/, tz)
sign = if sign == "-", do: "-", else: ""
hours = String.trim_leading(hours, "0") <> "H"
minutes = if minutes != "00", do: (minutes <> "M"), else: ""
day_time_duration(sign <> "PT" <> hours <> minutes)
end
# TODO: This is just a preliminary implementation until we have a proper XSD.Duration datatype
defp day_time_duration(value) do
Literal.new(value, datatype: NS.XSD.dayTimeDuration)
end
@doc """
Argument Compatibility Rules
see <https://www.w3.org/TR/sparql11-query/#func-arg-compatibility>
"""
def compatible_arguments?(arg1, arg2)
# The arguments are simple literals or literals typed as xsd:string
def compatible_arguments?(%Literal{literal: %XSD.String{}},
%Literal{literal: %XSD.String{}}), do: true
# The first argument is a plain literal with language tag and the second argument is a simple literal or literal typed as xsd:string
def compatible_arguments?(%Literal{literal: %RDF.LangString{}},
%Literal{literal: %XSD.String{}}), do: true
# The arguments are plain literals with identical language tags
def compatible_arguments?(%Literal{literal: %RDF.LangString{language: language}},
%Literal{literal: %RDF.LangString{language: language}}), do: true
def compatible_arguments?(_, _), do: false
defp ebv(value), do: XSD.Boolean.ebv(value) || :error
defp fn_not(value), do: XSD.Boolean.fn_not(value) || :error
defp uuid(format), do: UUID.uuid4(format)
end
| 36.080574 | 177 | 0.644253 |
79108332a05cd14e147ce6230d0e6157f0eff8af | 1,287 | ex | Elixir | lib/ueberauth_heroku_example/endpoint.ex | maxbeizer/ueberauth_heroku_example | e0dce54d9dee70be28ca25422cd2d4a59571248b | [
"MIT"
] | null | null | null | lib/ueberauth_heroku_example/endpoint.ex | maxbeizer/ueberauth_heroku_example | e0dce54d9dee70be28ca25422cd2d4a59571248b | [
"MIT"
] | null | null | null | lib/ueberauth_heroku_example/endpoint.ex | maxbeizer/ueberauth_heroku_example | e0dce54d9dee70be28ca25422cd2d4a59571248b | [
"MIT"
] | null | null | null | defmodule UeberauthHerokuExample.Endpoint do
use Phoenix.Endpoint, otp_app: :ueberauth_heroku_example
socket "/socket", UeberauthHerokuExample.UserSocket
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phoenix.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/", from: :ueberauth_heroku_example, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
end
plug Plug.RequestId
plug Plug.Logger
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
plug Plug.MethodOverride
plug Plug.Head
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
plug Plug.Session,
store: :cookie,
key: "_ueberauth_heroku_example_key",
signing_salt: "RmJQweJb"
plug UeberauthHerokuExample.Router
end
| 29.930233 | 69 | 0.73582 |
7910bf5f58af4accf20064a13ef215425a8f9577 | 2,697 | ex | Elixir | clients/content/lib/google_api/content/v21/model/account_status.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v21/model/account_status.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v21/model/account_status.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.Content.V21.Model.AccountStatus do
@moduledoc """
The status of an account, i.e., information about its products, which is computed offline and not returned immediately at insertion time.
## Attributes
* `accountId` (*type:* `String.t`, *default:* `nil`) - The ID of the account for which the status is reported.
* `accountLevelIssues` (*type:* `list(GoogleApi.Content.V21.Model.AccountStatusAccountLevelIssue.t)`, *default:* `nil`) - A list of account level issues.
* `kind` (*type:* `String.t`, *default:* `content#accountStatus`) - Identifies what kind of resource this is. Value: the fixed string "content#accountStatus".
* `products` (*type:* `list(GoogleApi.Content.V21.Model.AccountStatusProducts.t)`, *default:* `nil`) - List of product-related data by channel, destination, and country. Data in this field may be delayed by up to 30 minutes.
* `websiteClaimed` (*type:* `boolean()`, *default:* `nil`) - Whether the account's website is claimed or not.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:accountId => String.t(),
:accountLevelIssues =>
list(GoogleApi.Content.V21.Model.AccountStatusAccountLevelIssue.t()),
:kind => String.t(),
:products => list(GoogleApi.Content.V21.Model.AccountStatusProducts.t()),
:websiteClaimed => boolean()
}
field(:accountId)
field(:accountLevelIssues,
as: GoogleApi.Content.V21.Model.AccountStatusAccountLevelIssue,
type: :list
)
field(:kind)
field(:products, as: GoogleApi.Content.V21.Model.AccountStatusProducts, type: :list)
field(:websiteClaimed)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V21.Model.AccountStatus do
def decode(value, options) do
GoogleApi.Content.V21.Model.AccountStatus.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V21.Model.AccountStatus do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 41.492308 | 228 | 0.720801 |
7910c02368fd9473b9d02cc32829fbd996da94d1 | 230 | ex | Elixir | lib/phone/nanp/tc.ex | davidkovsky/phone | 83108ab1042efe62778c7363f5d02ef888883408 | [
"Apache-2.0"
] | 97 | 2016-04-05T13:08:41.000Z | 2021-12-25T13:08:34.000Z | lib/phone/nanp/tc.ex | davidkovsky/phone | 83108ab1042efe62778c7363f5d02ef888883408 | [
"Apache-2.0"
] | 70 | 2016-06-14T00:56:00.000Z | 2022-02-10T19:43:14.000Z | lib/phone/nanp/tc.ex | davidkovsky/phone | 83108ab1042efe62778c7363f5d02ef888883408 | [
"Apache-2.0"
] | 31 | 2016-04-21T22:26:12.000Z | 2022-01-24T21:40:00.000Z | defmodule Phone.NANP.TC do
@moduledoc false
use Helper.Country
def regex, do: ~r/^(1)(649)([2-9].{6})$/
def country, do: "Turks and Caicos Islands"
def a2, do: "TC"
def a3, do: "TCA"
matcher(:regex, ["1649"])
end
| 17.692308 | 45 | 0.613043 |
7910d373fc315d335249687d81abf8b834efcc61 | 578 | exs | Elixir | priv/repo/migrations/20170620214154_create_change_management_parameter.exs | no0x9d/chankins | b4fd37d3145a001e4ebbe86eea91742d5a812858 | [
"MIT"
] | null | null | null | priv/repo/migrations/20170620214154_create_change_management_parameter.exs | no0x9d/chankins | b4fd37d3145a001e4ebbe86eea91742d5a812858 | [
"MIT"
] | null | null | null | priv/repo/migrations/20170620214154_create_change_management_parameter.exs | no0x9d/chankins | b4fd37d3145a001e4ebbe86eea91742d5a812858 | [
"MIT"
] | null | null | null | defmodule Chankins.Repo.Migrations.CreateChankins.ChangeManagement.Parameter do
use Ecto.Migration
def change do
create table(:change_management_parameters) do
add :key, :string
add :value, :string
add :group, :string
add :version_id, references(:change_management_versions, on_delete: :nothing)
add :feature_id, references(:change_management_features, on_delete: :nothing)
timestamps()
end
create index(:change_management_parameters, [:version_id])
create index(:change_management_parameters, [:feature_id])
end
end
| 30.421053 | 83 | 0.738754 |
7910d43bd213ba16da6543fb3c6f94ac87c92e93 | 2,064 | ex | Elixir | lib/codes/codes_p14.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_p14.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_p14.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_P14 do
alias IcdCode.ICDCode
def _P140 do
%ICDCode{full_code: "P140",
category_code: "P14",
short_code: "0",
full_name: "Erb's paralysis due to birth injury",
short_name: "Erb's paralysis due to birth injury",
category_name: "Erb's paralysis due to birth injury"
}
end
def _P141 do
%ICDCode{full_code: "P141",
category_code: "P14",
short_code: "1",
full_name: "Klumpke's paralysis due to birth injury",
short_name: "Klumpke's paralysis due to birth injury",
category_name: "Klumpke's paralysis due to birth injury"
}
end
def _P142 do
%ICDCode{full_code: "P142",
category_code: "P14",
short_code: "2",
full_name: "Phrenic nerve paralysis due to birth injury",
short_name: "Phrenic nerve paralysis due to birth injury",
category_name: "Phrenic nerve paralysis due to birth injury"
}
end
def _P143 do
%ICDCode{full_code: "P143",
category_code: "P14",
short_code: "3",
full_name: "Other brachial plexus birth injuries",
short_name: "Other brachial plexus birth injuries",
category_name: "Other brachial plexus birth injuries"
}
end
def _P148 do
%ICDCode{full_code: "P148",
category_code: "P14",
short_code: "8",
full_name: "Birth injuries to other parts of peripheral nervous system",
short_name: "Birth injuries to other parts of peripheral nervous system",
category_name: "Birth injuries to other parts of peripheral nervous system"
}
end
def _P149 do
%ICDCode{full_code: "P149",
category_code: "P14",
short_code: "9",
full_name: "Birth injury to peripheral nervous system, unspecified",
short_name: "Birth injury to peripheral nervous system, unspecified",
category_name: "Birth injury to peripheral nervous system, unspecified"
}
end
end
| 33.836066 | 85 | 0.625969 |
791117797cb414d820731f02a0337a567d63fd65 | 1,506 | ex | Elixir | horas_trabalhadas_elixir/lib/horas_trabalhadas_elixir/utils/time_utils.ex | hbobenicio/elixir-examples | a116955b6e180f295dde5a41bd729fcd5d69857e | [
"Apache-2.0"
] | null | null | null | horas_trabalhadas_elixir/lib/horas_trabalhadas_elixir/utils/time_utils.ex | hbobenicio/elixir-examples | a116955b6e180f295dde5a41bd729fcd5d69857e | [
"Apache-2.0"
] | null | null | null | horas_trabalhadas_elixir/lib/horas_trabalhadas_elixir/utils/time_utils.ex | hbobenicio/elixir-examples | a116955b6e180f295dde5a41bd729fcd5d69857e | [
"Apache-2.0"
] | null | null | null | defmodule HorasTrabalhadasElixir.Utils.TimeUtils do
@moduledoc """
Utilitário para tratamento de cálculos que envolvem tempo.
"""
@spec diferenca_horas(number, number) :: number
def diferenca_horas(h1, h2) do
entrada = parse_horas_em_minutos(h1)
saida = parse_horas_em_minutos(h2)
hours_from_minutes(saida - entrada)
end
@doc """
Converte horas em minutos.
## Exemplos
iex> minutes_from_hours 1
60.0
"""
@spec minutes_from_hours(number) :: number
def minutes_from_hours(hours) do
hours * 60.0
end
@doc """
Converte minutos em horas (numérico).
## Exemplos
iex> hours_from_minutes 60
1.0
"""
@spec hours_from_minutes(number) :: number
def hours_from_minutes(minutes) do
minutes / 60.0
end
@doc """
Converte minutos em horas (String).
## Exemplos
iex> parse_horas_em_minutos "01:30"
90.0
"""
@spec parse_horas_em_minutos(String.t) :: number
def parse_horas_em_minutos(strHora) do
[horas, minutos] = strHora
|> String.split(":")
|> Enum.map(&String.to_integer/1)
minutes_from_hours(horas) + minutos
end
@doc """
Trunca o número em apenas 2 casas decimais e
formata-o para apresentação como um valor temporal.
## Exemplos
iex> fmt_tempo 3.1415
"3.14"
iex> fmt_tempo 3.149
"3.14"
"""
@spec fmt_tempo(number) :: String.t
def fmt_tempo(tempo) when is_number(tempo) do
tempo
|> Float.floor(2)
|> to_string
end
end
| 19.558442 | 60 | 0.656042 |
79113a45ceaf1de91c9f0e605aa31196c7eec064 | 1,990 | ex | Elixir | clients/dns/lib/google_api/dns/v1/model/resource_record_sets_list_response.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/dns/lib/google_api/dns/v1/model/resource_record_sets_list_response.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/dns/lib/google_api/dns/v1/model/resource_record_sets_list_response.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.DNS.V1.Model.ResourceRecordSetsListResponse do
@moduledoc """
## Attributes
* `header` (*type:* `GoogleApi.DNS.V1.Model.ResponseHeader.t`, *default:* `nil`) -
* `kind` (*type:* `String.t`, *default:* `dns#resourceRecordSetsListResponse`) - Type of resource.
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) -
* `rrsets` (*type:* `list(GoogleApi.DNS.V1.Model.ResourceRecordSet.t)`, *default:* `nil`) -
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:header => GoogleApi.DNS.V1.Model.ResponseHeader.t(),
:kind => String.t(),
:nextPageToken => String.t(),
:rrsets => list(GoogleApi.DNS.V1.Model.ResourceRecordSet.t())
}
field(:header, as: GoogleApi.DNS.V1.Model.ResponseHeader)
field(:kind)
field(:nextPageToken)
field(:rrsets, as: GoogleApi.DNS.V1.Model.ResourceRecordSet, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.DNS.V1.Model.ResourceRecordSetsListResponse do
def decode(value, options) do
GoogleApi.DNS.V1.Model.ResourceRecordSetsListResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DNS.V1.Model.ResourceRecordSetsListResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.535714 | 102 | 0.713568 |
7911433d918cf1d5cd187df4586c506b695053d5 | 1,621 | ex | Elixir | Library/Recursive/queens.ex | Theopse/Functions | 3858d47c3e0b31170d3070a150bc79be991ac1f7 | [
"BSD-2-Clause"
] | null | null | null | Library/Recursive/queens.ex | Theopse/Functions | 3858d47c3e0b31170d3070a150bc79be991ac1f7 | [
"BSD-2-Clause"
] | null | null | null | Library/Recursive/queens.ex | Theopse/Functions | 3858d47c3e0b31170d3070a150bc79be991ac1f7 | [
"BSD-2-Clause"
] | null | null | null | # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
# This File if From Theopse ([email protected])
# Licensed under BSD-2-Caluse
# File: queens.ex (Functions/Library/Recursive/queens.ex)
# Content: Queens
# Copyright (c) 2020 Theopse Organization All rights reserved
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
defmodule Functions.Recursive do
@moduledoc """
Recursive Functions
"""
@doc """
Queens
## Examples
iex> Functions.Recursive.queens(4)
[{1, 3, 0, 2}, {2, 0, 3, 1}]
"""
@spec queens(pos_integer, [integer()]) :: [{integer()}]
def queens(num \\ 8, state \\ [])
def queens(num, state) when is_list(state) and is_integer(num) and num >= 4 do
length = :erlang.length(state)
next =
state
|> case do
[] ->
0..(num - 1)
state ->
0..(num - 1)
|> Enum.filter(fn pos ->
state
|> Enum.with_index()
|> Enum.any?(fn {item, i} ->
pos == item || abs(item - pos) == length - i
end)
|> Kernel.==(false)
end)
end
if length == num - 1 do
next
|> Enum.map(&{&1})
else
fun = fn
[], result, _ ->
result
[pos | next], result, fun ->
queen = queens(num, state ++ [pos])
newFun = fn
[], result, _ ->
result
[head | tail], result, newFun ->
newFun.(tail, result ++ [head |> Tuple.insert_at(0,pos)], newFun)
end
result = newFun.(queen, result, newFun)
fun.(next, result, fun)
end
fun.(next |> Enum.to_list(), [], fun)
end
end
end
| 21.905405 | 99 | 0.483035 |
791160b4f07a636b8c7371feb58692ef62a74fb8 | 1,999 | ex | Elixir | lib/live_view_demo/code_breaker.ex | manojsamanta/codebreaker-prototype | 14d521db45784dee692de9e7252dd6a54bb793bb | [
"MIT"
] | null | null | null | lib/live_view_demo/code_breaker.ex | manojsamanta/codebreaker-prototype | 14d521db45784dee692de9e7252dd6a54bb793bb | [
"MIT"
] | null | null | null | lib/live_view_demo/code_breaker.ex | manojsamanta/codebreaker-prototype | 14d521db45784dee692de9e7252dd6a54bb793bb | [
"MIT"
] | null | null | null | defmodule LiveViewDemo.CodeBreaker do
@moduledoc """
The CodeBreaker context.
"""
import Ecto.Query, warn: false
alias LiveViewDemo.CodeBreaker.Game
alias LiveViewDemo.CodeBreaker.Turn
@colorlist ~w(a b c d e f)a
def create_game_for_user(user_id, %{colors: colors}) do
game_id = UUID.uuid4()
game = %Game{
id: game_id,
user_uid: user_id,
colors: colors,
solution: generate_solution(colors),
current_guess: Enum.map(1..colors, fn _ -> :x end),
turns: []
}
{:ok, game}
end
def generate_solution(colors) do
Enum.reduce(1..colors, [], fn _, a -> [Enum.random(@colorlist) | a] end)
end
def evaluate(guess, solution, colors) do
it_colors = colors - 1
solution = Enum.reduce(0..it_colors, solution, &exact_checker(&1, &2, guess))
solution = Enum.reduce(0..it_colors, solution, &partial_checker(&1, &2, guess))
exacts = Enum.count(solution, fn p -> p == :exact end)
partials = Enum.count(solution, fn p -> p == :partial end)
results = map_pegs(exacts, :b) ++ map_pegs(partials, :w)
%Turn{guess: guess, result: results}
end
def exact_checker(i, s, guess) do
if Enum.at(guess, i) == Enum.at(s, i) do
List.replace_at(s, i, :exact)
else
s
end
end
def partial_checker(i, s, guess) do
if Enum.member?(s, Enum.at(guess, i)) && Enum.at(s, i) != :exact do
targ = Enum.at(guess, i)
spot = Enum.find_index(s, fn i -> i == targ end)
List.replace_at(s, spot, :partial)
else
s
end
end
def map_pegs(0, _), do: []
def map_pegs(i, peg), do: Enum.map(1..i, fn _ -> peg end)
def find_exact_matches(results, [], []), do: results
def find_exact_matches(results, [g_peg | g_others], [s_peg | s_others]) do
results =
if g_peg == s_peg do
[:b | results]
else
results
end
find_exact_matches(results, g_others, s_others)
end
def find_partial_matches(results, _, _), do: results
end
| 24.378049 | 83 | 0.618809 |
79116c532435cf5a07e790606d01fdcf892be2ab | 1,685 | ex | Elixir | clients/storage/lib/google_api/storage/v1/model/bucket_logging.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/storage/lib/google_api/storage/v1/model/bucket_logging.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/storage/lib/google_api/storage/v1/model/bucket_logging.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.Storage.V1.Model.BucketLogging do
@moduledoc """
The bucket's logging configuration, which defines the destination bucket and optional name prefix for the current bucket's logs.
## Attributes
* `logBucket` (*type:* `String.t`, *default:* `nil`) - The destination bucket where the current bucket's logs should be placed.
* `logObjectPrefix` (*type:* `String.t`, *default:* `nil`) - A prefix for log object names.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:logBucket => String.t(),
:logObjectPrefix => String.t()
}
field(:logBucket)
field(:logObjectPrefix)
end
defimpl Poison.Decoder, for: GoogleApi.Storage.V1.Model.BucketLogging do
def decode(value, options) do
GoogleApi.Storage.V1.Model.BucketLogging.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Storage.V1.Model.BucketLogging do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.7 | 131 | 0.730564 |
791172290ff8cc8f8cea7925acbf4ad5da7a4ca4 | 69 | ex | Elixir | lib/supply_chain_web/views/sign_view.ex | BailianBlockchain/Bailian_Supply_Chain | 8341e974b133c86f48488cb52ec4b3b281a99eb5 | [
"MIT"
] | 5 | 2020-12-10T07:24:18.000Z | 2021-12-15T08:26:05.000Z | lib/supply_chain_web/views/sign_view.ex | BailianBlockchain/Bailian_Supply_Chain | 8341e974b133c86f48488cb52ec4b3b281a99eb5 | [
"MIT"
] | null | null | null | lib/supply_chain_web/views/sign_view.ex | BailianBlockchain/Bailian_Supply_Chain | 8341e974b133c86f48488cb52ec4b3b281a99eb5 | [
"MIT"
] | 2 | 2020-12-12T17:06:13.000Z | 2021-04-09T02:12:31.000Z | defmodule SupplyChainWeb.SignView do
use SupplyChainWeb, :view
end
| 17.25 | 36 | 0.826087 |
7911727d0d7a362f88b6ca0558c2a03b185d92e7 | 4,645 | exs | Elixir | test/gettext/merger_test.exs | stephenmoloney/gettext | 4b9a0fd71e6ebdfa3ae3fb63c657b67e8745faa1 | [
"Apache-2.0"
] | null | null | null | test/gettext/merger_test.exs | stephenmoloney/gettext | 4b9a0fd71e6ebdfa3ae3fb63c657b67e8745faa1 | [
"Apache-2.0"
] | null | null | null | test/gettext/merger_test.exs | stephenmoloney/gettext | 4b9a0fd71e6ebdfa3ae3fb63c657b67e8745faa1 | [
"Apache-2.0"
] | null | null | null | defmodule Gettext.MergerTest do
use ExUnit.Case, async: true
alias Gettext.Merger
alias Gettext.PO
alias Gettext.PO.Translation
@opts fuzzy: true, fuzzy_threshold: 0.8
@pot_path "../../tmp/" |> Path.expand(__DIR__) |> Path.relative_to_cwd
test "merge/2: headers from the old file are kept" do
old_po = %PO{headers: [~S(Language: it\n)]}
new_pot = %PO{headers: ["foo"]}
assert Merger.merge(old_po, new_pot, @opts).headers == old_po.headers
end
test "merge/2: obsolete translations are discarded (even the manually entered ones)" do
old_po = %PO{
translations: [
%Translation{msgid: "obs_auto", msgstr: "foo", references: [{"foo.ex", 1}]},
%Translation{msgid: "obs_manual", msgstr: "foo", references: []},
%Translation{msgid: "tomerge", msgstr: "foo"},
],
}
new_pot = %PO{translations: [%Translation{msgid: "tomerge", msgstr: ""}]}
assert %PO{translations: [t]} = Merger.merge(old_po, new_pot, @opts)
assert %Translation{msgid: "tomerge", msgstr: "foo"} = t
end
test "merge/2: when translations match, the msgstr of the old one is preserved" do
# Note that the msgstr of the new one must be empty as the new one comes
# from a POT file.
old_po = %PO{translations: [%Translation{msgid: "foo", msgstr: "bar"}]}
new_pot = %PO{translations: [%Translation{msgid: "foo", msgstr: ""}]}
assert %PO{translations: [t]} = Merger.merge(old_po, new_pot, @opts)
assert t.msgstr == "bar"
end
test "merge/2: when translations match, existing translator comments are preserved" do
# Note that the new translation should not have any translator comments
# (comes from a POT file).
old_po = %PO{translations: [%Translation{msgid: "foo", comments: ["# existing comment"]}]}
new_pot = %PO{translations: [%Translation{msgid: "foo", comments: ["# new comment"]}]}
assert %PO{translations: [t]} = Merger.merge(old_po, new_pot, @opts)
assert t.comments == ["# existing comment"]
end
test "merge/2: when translations match, existing extracted comments are replaced by new ones" do
old_po = %PO{translations: [%Translation{msgid: "foo", extracted_comments: ["#. existing comment", "#. other existing comment"]}]}
new_pot = %PO{translations: [%Translation{msgid: "foo", extracted_comments: ["#. new comment"]}]}
assert %PO{translations: [t]} = Merger.merge(old_po, new_pot, @opts)
assert t.extracted_comments == ["#. new comment"]
end
test "merge/2: when translations match, existing references are replaced by new ones" do
old_po = %PO{translations: [%Translation{msgid: "foo", references: [{"foo.ex", 1}]}]}
new_pot = %PO{translations: [%Translation{msgid: "foo", references: [{"bar.ex", 1}]}]}
assert %PO{translations: [t]} = Merger.merge(old_po, new_pot, @opts)
assert t.references == [{"bar.ex", 1}]
end
test "merge/2: new translations are fuzzy matched against obsolete translations" do
old_po = %PO{translations: [%Translation{msgid: "hello world!", msgstr: ["foo"]}]}
new_pot = %PO{translations: [%Translation{msgid: "hello worlds!"}]}
assert %PO{translations: [t]} = Merger.merge(old_po, new_pot, @opts)
assert MapSet.member?(t.flags, "fuzzy")
assert t.msgid == "hello worlds!"
assert t.msgstr == ["foo"]
end
test "merge/2: exact matches have precedence over fuzzy matches" do
old_po = %PO{translations: [%Translation{msgid: "hello world!", msgstr: ["foo"]},
%Translation{msgid: "hello worlds!", msgstr: ["bar"]}]}
new_pot = %PO{translations: [%Translation{msgid: "hello world!"}]}
# Let's check that the "hello worlds!" translation is discarded even if it's
# a fuzzy match for "hello world!".
assert %PO{translations: [t]} = Merger.merge(old_po, new_pot, @opts)
refute MapSet.member?(t.flags, "fuzzy")
assert t.msgid == "hello world!"
assert t.msgstr == ["foo"]
end
test "new_po_file/2" do
pot_path = Path.join(@pot_path, "new_po_file.pot")
new_po_path = Path.join(@pot_path, "it/LC_MESSAGES/new_po_file.po")
write_file pot_path, """
## Stripme!
# A comment
msgid "foo"
msgstr "bar"
"""
merged = Merger.new_po_file(new_po_path, pot_path) |> IO.iodata_to_binary()
assert String.ends_with?(merged, ~S"""
msgid ""
msgstr ""
"Language: it\n"
# A comment
msgid "foo"
msgstr "bar"
""")
assert String.starts_with?(merged, "## `msgid`s in this file come from POT")
end
defp write_file(path, contents) do
path |> Path.dirname |> File.mkdir_p!
File.write!(path, contents)
end
end
| 37.764228 | 134 | 0.651668 |
7911d24e3275553701b520e5201b701843bfc977 | 680 | ex | Elixir | lib/esx/transport/selector.ex | gor181/esx | 8cc247ff92e2dac7f4ee4601298521622597f10c | [
"MIT"
] | 27 | 2017-03-21T15:42:07.000Z | 2021-10-18T21:15:53.000Z | lib/esx/transport/selector.ex | ikeikeikeike/es | f38d6576e9bce466b91e4d75ed2c690756db6fb0 | [
"MIT"
] | 2 | 2017-06-03T19:25:13.000Z | 2019-06-05T00:06:48.000Z | lib/esx/transport/selector.ex | ikeikeikeike/es | f38d6576e9bce466b91e4d75ed2c690756db6fb0 | [
"MIT"
] | 4 | 2017-10-08T20:17:14.000Z | 2021-05-24T11:22:13.000Z | defmodule ESx.Transport.Selector do
defmodule Base do
@callback select(conns :: List.t()) :: ESx.Transport.Connection.t() | {:error, term}
end
defmodule Random do
@moduledoc "Random Selector"
@behaviour Base
def select(conns) do
Enum.random(conns)
end
end
defmodule RoundRobin do
@moduledoc "RoundRobin Selector"
@behaviour Base
use ESx.Transport.Statex, current: 0
def select(conns) do
s = state()
next =
if s.current >= length(conns) - 1 do
0
else
1 + s.current
end
conn = Enum.at(conns, next)
set_state!(:current, next)
conn
end
end
end
| 17.894737 | 88 | 0.594118 |
7911e249d38089b6bb55af7eb0b012ae645ba0a5 | 380 | ex | Elixir | apps/ello_feeds/web/views/error_view.ex | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 16 | 2017-06-21T21:31:20.000Z | 2021-05-09T03:23:26.000Z | apps/ello_feeds/web/views/error_view.ex | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 25 | 2017-06-07T12:18:28.000Z | 2018-06-08T13:27:43.000Z | apps/ello_feeds/web/views/error_view.ex | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 3 | 2018-06-14T15:34:07.000Z | 2022-02-28T21:06:13.000Z | defmodule Ello.Feeds.ErrorView do
use Ello.Feeds.Web, :view
def render("404.html", _assigns) do
"Page not found"
end
def render("500.html", _assigns) do
"Internal server error"
end
# In case no render clause matches or no
# template is found, let's render it as 500
def template_not_found(_template, assigns) do
render "500.html", assigns
end
end
| 21.111111 | 47 | 0.697368 |
7912023df402ccc65fe74fb3e63b7a3e971e72a1 | 879 | ex | Elixir | test/support/conn_case.ex | youknowcast/aiit_sp_challenge4 | a5811675b77f4c496c9456a74e986ba1cfd8ef2f | [
"MIT"
] | 4 | 2019-04-07T17:43:10.000Z | 2020-07-07T21:32:44.000Z | test/support/conn_case.ex | youknowcast/aiit_sp_challenge4 | a5811675b77f4c496c9456a74e986ba1cfd8ef2f | [
"MIT"
] | 10 | 2020-07-17T03:55:57.000Z | 2022-01-09T18:33:29.000Z | test/support/conn_case.ex | youknowcast/aiit_sp_challenge4 | a5811675b77f4c496c9456a74e986ba1cfd8ef2f | [
"MIT"
] | 3 | 2019-09-09T15:21:41.000Z | 2020-07-07T21:35:07.000Z | defmodule HelloWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
use Phoenix.ConnTest
alias HelloWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint HelloWeb.Endpoint
end
end
setup _tags do
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 26.636364 | 59 | 0.726962 |
79124135f70d14f27744d8b8e84bba6904f55b0d | 1,738 | ex | Elixir | lib/maxmind_csv/schema/city_block_decimal.ex | elixir-geolix/adapter_maxmind_csv | 0ef4109ef23cc61c62134b7bef4a8249d1a7c37e | [
"Apache-2.0"
] | 1 | 2020-06-20T14:40:16.000Z | 2020-06-20T14:40:16.000Z | lib/maxmind_csv/schema/city_block_decimal.ex | elixir-geolix/adapter_maxmind_csv | 0ef4109ef23cc61c62134b7bef4a8249d1a7c37e | [
"Apache-2.0"
] | null | null | null | lib/maxmind_csv/schema/city_block_decimal.ex | elixir-geolix/adapter_maxmind_csv | 0ef4109ef23cc61c62134b7bef4a8249d1a7c37e | [
"Apache-2.0"
] | null | null | null | defmodule Geolix.Adapter.MaxMindCSV.Schema.CityBlockDecimal do
@moduledoc """
Sample `Ecto.Schema` to use with the adapter for city databases (blocks).
Table name: `geolix_maxmind_csv_city_blocks_decimal`.
Preloads: `Geolix.Adapter.MaxMindCSV.Schema.CityLocation`
"""
use Ecto.Schema
import Ecto.Query, only: [preload: 2, where: 3]
alias Geolix.Adapter.MaxMindCSV.IP
alias Geolix.Adapter.MaxMindCSV.Schema.CityLocation
@behaviour Geolix.Adapter.MaxMindCSV.Block
@primary_key false
schema "geolix_maxmind_csv_city_blocks_decimal" do
field :network_start_integer, :decimal, primary_key: true
field :network_last_integer, :decimal, primary_key: true
field :geoname_id, :integer
field :registered_country_geoname_id, :integer
field :represented_country_geoname_id, :integer
field :is_anonymous_proxy, :boolean
field :is_satellite_provider, :boolean
field :postal_code, :string
field :latitude, :decimal
field :longitude, :decimal
field :accuracy_radius, :integer
has_one :location, CityLocation,
references: :geoname_id,
foreign_key: :geoname_id
has_one :location_registered, CityLocation,
references: :registered_country_geoname_id,
foreign_key: :geoname_id
has_one :location_represented, CityLocation,
references: :represented_country_geoname_id,
foreign_key: :geoname_id
end
@impl Geolix.Adapter.MaxMindCSV.Block
def find(ip, repo) do
ip_integer = IP.to_integer(ip)
__MODULE__
|> where(
[b],
b.network_start_integer <= ^ip_integer and b.network_last_integer >= ^ip_integer
)
|> preload([:location, :location_registered, :location_represented])
|> repo.one()
end
end
| 28.966667 | 86 | 0.737054 |
79124c463f81bc06a01bde9ce937e4889e21682b | 330 | exs | Elixir | test/rewind_web/live/page_live_test.exs | fremantle-industries/rewind | 1818fe1704cb303e09108cbb5e669e673685fb62 | [
"MIT"
] | 2 | 2021-09-18T09:15:13.000Z | 2022-03-16T09:29:37.000Z | test/rewind_web/live/page_live_test.exs | fremantle-industries/rewind | 1818fe1704cb303e09108cbb5e669e673685fb62 | [
"MIT"
] | null | null | null | test/rewind_web/live/page_live_test.exs | fremantle-industries/rewind | 1818fe1704cb303e09108cbb5e669e673685fb62 | [
"MIT"
] | null | null | null | defmodule RewindWeb.PageLiveTest do
use RewindWeb.ConnCase
import Phoenix.LiveViewTest
test "disconnected and connected render", %{conn: conn} do
{:ok, page_live, disconnected_html} = live(conn, "/")
assert disconnected_html =~ "Welcome to Phoenix!"
assert render(page_live) =~ "Welcome to Phoenix!"
end
end
| 27.5 | 60 | 0.724242 |
79126398e6fd57e0231b0bb8c017669f61839904 | 6,589 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/attached_disk.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/attached_disk.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/model/attached_disk.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 "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.Compute.V1.Model.AttachedDisk do
@moduledoc """
An instance-attached disk resource.
## Attributes
- autoDelete (boolean()): Specifies whether the disk will be auto-deleted when the instance is deleted (but not when the disk is detached from the instance). Defaults to: `null`.
- boot (boolean()): Indicates that this is a boot disk. The virtual machine will use the first partition of the disk for its root filesystem. Defaults to: `null`.
- deviceName (String.t): Specifies a unique device name of your choice that is reflected into the /dev/disk/by-id/google-* tree of a Linux operating system running within the instance. This name can be used to reference the device for mounting, resizing, and so on, from within the instance. If not specified, the server chooses a default device name to apply to this disk, in the form persistent-disks-x, where x is a number assigned by Google Compute Engine. This field is only applicable for persistent disks. Defaults to: `null`.
- diskEncryptionKey (CustomerEncryptionKey): Encrypts or decrypts a disk using a customer-supplied encryption key. If you are creating a new disk, this field encrypts the new disk using an encryption key that you provide. If you are attaching an existing disk that is already encrypted, this field decrypts the disk using the customer-supplied encryption key. If you encrypt a disk using a customer-supplied key, you must provide the same key again when you attempt to use this resource at a later time. For example, you must provide the key when you create a snapshot or an image from the disk or when you attach the disk to a virtual machine instance. If you do not provide an encryption key, then the disk will be encrypted using an automatically generated key and you do not need to provide a key to use the disk later. Instance templates do not store customer-supplied encryption keys, so you cannot use your own keys to encrypt disks in a managed instance group. Defaults to: `null`.
- guestOsFeatures ([GuestOsFeature]): A list of features to enable on the guest operating system. Applicable only for bootable images. Read Enabling guest operating system features to see a list of available options. Defaults to: `null`.
- index (integer()): [Output Only] A zero-based index to this disk, where 0 is reserved for the boot disk. If you have many disks attached to an instance, each disk would have a unique index number. Defaults to: `null`.
- initializeParams (AttachedDiskInitializeParams): [Input Only] Specifies the parameters for a new disk that will be created alongside the new instance. Use initialization parameters to create boot disks or local SSDs attached to the new instance. This property is mutually exclusive with the source property; you can only define one or the other, but not both. Defaults to: `null`.
- interface (String.t): Specifies the disk interface to use for attaching this disk, which is either SCSI or NVME. The default is SCSI. Persistent disks must always use SCSI and the request will fail if you attempt to attach a persistent disk in any other format than SCSI. Local SSDs can use either NVME or SCSI. For performance characteristics of SCSI over NVMe, see Local SSD performance. Defaults to: `null`.
- Enum - one of [NVME, SCSI]
- kind (String.t): [Output Only] Type of the resource. Always compute#attachedDisk for attached disks. Defaults to: `null`.
- licenses ([String.t]): [Output Only] Any valid publicly visible licenses. Defaults to: `null`.
- mode (String.t): The mode in which to attach this disk, either READ_WRITE or READ_ONLY. If not specified, the default is to attach the disk in READ_WRITE mode. Defaults to: `null`.
- Enum - one of [READ_ONLY, READ_WRITE]
- source (String.t): Specifies a valid partial or full URL to an existing Persistent Disk resource. When creating a new instance, one of initializeParams.sourceImage or disks.source is required except for local SSD. If desired, you can also attach existing non-root persistent disks using this property. This field is only applicable for persistent disks. Note that for InstanceTemplate, specify the disk name, not the URL for the disk. Defaults to: `null`.
- type (String.t): Specifies the type of the disk, either SCRATCH or PERSISTENT. If not specified, the default is PERSISTENT. Defaults to: `null`.
- Enum - one of [PERSISTENT, SCRATCH]
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:autoDelete => any(),
:boot => any(),
:deviceName => any(),
:diskEncryptionKey => GoogleApi.Compute.V1.Model.CustomerEncryptionKey.t(),
:guestOsFeatures => list(GoogleApi.Compute.V1.Model.GuestOsFeature.t()),
:index => any(),
:initializeParams => GoogleApi.Compute.V1.Model.AttachedDiskInitializeParams.t(),
:interface => any(),
:kind => any(),
:licenses => list(any()),
:mode => any(),
:source => any(),
:type => any()
}
field(:autoDelete)
field(:boot)
field(:deviceName)
field(:diskEncryptionKey, as: GoogleApi.Compute.V1.Model.CustomerEncryptionKey)
field(:guestOsFeatures, as: GoogleApi.Compute.V1.Model.GuestOsFeature, type: :list)
field(:index)
field(:initializeParams, as: GoogleApi.Compute.V1.Model.AttachedDiskInitializeParams)
field(:interface)
field(:kind)
field(:licenses, type: :list)
field(:mode)
field(:source)
field(:type)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.AttachedDisk do
def decode(value, options) do
GoogleApi.Compute.V1.Model.AttachedDisk.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.AttachedDisk do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 75.735632 | 995 | 0.746851 |
791267997cb4aa557ae98a10ce340f77e254aa87 | 5,236 | ex | Elixir | lib/oli/utils/slug.ex | jrissler/oli-torus | 747f9e4360163d76a6ca5daee3aab1feab0c99b1 | [
"MIT"
] | 1 | 2022-03-17T20:35:47.000Z | 2022-03-17T20:35:47.000Z | lib/oli/utils/slug.ex | jrissler/oli-torus | 747f9e4360163d76a6ca5daee3aab1feab0c99b1 | [
"MIT"
] | 9 | 2021-11-02T16:52:09.000Z | 2022-03-25T15:14:01.000Z | lib/oli/utils/slug.ex | marc-hughes/oli-torus-1 | aa3c9bb2d91b678a365be839761eaf86c60ee35c | [
"MIT"
] | null | null | null | defmodule Oli.Utils.Slug do
@chars "abcdefghijklmnopqrstuvwxyz1234567890" |> String.split("", trim: true)
@doc """
Updates the slug from the title for a table if the title has not
been set or if it has changed.
"""
def update_on_change(changeset, table) do
case changeset.valid? do
# We only have to consider changing the slug if this is a valid changeset
true ->
case Ecto.Changeset.get_change(changeset, :title) do
# if we aren't changing the title, we don't have to even consider
# changing the slug
nil ->
changeset
# if we are changing the title, we need to consider whether or not
# this is for a new revision or this is an update for an existing one
title ->
case Ecto.Changeset.get_change(changeset, :id) do
# This is a changeset for the creation of a new revision
nil -> handle_creation(changeset, table, title)
# This is a changeset for an update
_ -> handle_update(changeset, table, title)
end
end
_ ->
changeset
end
end
def handle_creation(changeset, table, title) do
# get the previous revision id out of the changeset
case Ecto.Changeset.get_change(changeset, :previous_revision_id) do
# if there isn't a previous, we must set the slug
nil ->
Ecto.Changeset.put_change(changeset, :slug, generate(table, title))
# There is a previous, so fetch it
id ->
case Ecto.Adapters.SQL.query(
Oli.Repo,
"SELECT slug, title FROM #{table} WHERE id = $1;",
[id]
) do
# If the previous slug's title matches the current title, we reuse
# the slug from that previous
{:ok, %{rows: [[slug, ^title]]}} -> Ecto.Changeset.put_change(changeset, :slug, slug)
# Otherwise, create a new slug
_ -> Ecto.Changeset.put_change(changeset, :slug, generate(table, title))
end
end
end
def handle_update(changeset, table, title) do
Ecto.Changeset.put_change(changeset, :slug, generate(table, title))
end
@doc """
Generates a slug once, but then guarantee that it never changes
on future title changes.
"""
def update_never(changeset, table) do
case changeset.valid? do
true ->
case Ecto.Changeset.get_field(changeset, :slug) do
nil ->
Ecto.Changeset.put_change(
changeset,
:slug,
generate(table, Ecto.Changeset.get_field(changeset, :title))
)
_ ->
changeset
end
_ ->
changeset
end
end
def update_never_seedless(changeset, table) do
if not changeset.valid? or !is_nil(Ecto.Changeset.get_field(changeset, :slug)) do
changeset
else
Ecto.Changeset.put_change(
changeset,
:slug,
generate_seedless(table)
)
end
end
def generate_seedless(table) do
unique_slug(table, fn -> random_string(5) end)
end
@doc """
Generates a unique slug for the table using the title provided
"""
def generate(table, title) do
unique_slug(table, slugify(title), 0, 10)
end
@doc """
Given a title and an attempt number, generates a slug candidate that might not be unique.
"""
def generate_nth(title, n) do
slugify(title) <> suffix(n)
end
def str(length) do
"_" <> random_string(length)
end
def random_string(length) do
Enum.reduce(1..length, [], fn _i, acc ->
[Enum.random(@chars) | acc]
end)
|> Enum.join("")
end
def slugify(nil), do: ""
def slugify(title) do
String.downcase(title, :default)
|> String.trim()
|> String.replace(" ", "_")
|> alpha_numeric_only()
|> URI.encode_www_form()
|> String.slice(0, 30)
end
defp unique_slug(table, generate_candidate) when is_function(generate_candidate) do
_unique_slug_helper(table, generate_candidate, 0)
end
defp unique_slug(_table, "", _attempt, _max_attempts), do: ""
defp unique_slug(_table, _title, attempt, max_attempts) when attempt == max_attempts, do: ""
defp unique_slug(table, title, attempt, max_attempts) do
candidate = title <> suffix(attempt)
case check_unique_slug(table, candidate) do
{:ok, slug} -> slug
:error -> unique_slug(table, title, attempt + 1, max_attempts)
end
end
defp _unique_slug_helper(table, generate_candidate, count) do
if count > 100 do
""
else
case check_unique_slug(table, generate_candidate.()) do
{:ok, slug} -> slug
:error -> _unique_slug_helper(table, generate_candidate, count + 1)
end
end
end
defp check_unique_slug(table, candidate) do
query =
Ecto.Adapters.SQL.query(
Oli.Repo,
"SELECT * FROM #{table} WHERE slug = $1;",
[candidate]
)
case query do
{:ok, %{num_rows: 0}} -> {:ok, candidate}
{:ok, _results} -> :error
end
end
def alpha_numeric_only(str) do
String.replace(str, ~r/[^A-Za-z0-9_]+/, "")
end
defp suffix(0), do: ""
defp suffix(n) when n < 5, do: str(5)
defp suffix(_), do: str(10)
end
| 28.150538 | 95 | 0.615355 |
7912879ce0f8b2e6b9cacf2f60d647f0273a7b99 | 193,490 | ex | Elixir | clients/dataproc/lib/google_api/dataproc/v1/api/projects.ex | chingor13/elixir-google-api | 85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/dataproc/lib/google_api/dataproc/v1/api/projects.ex | chingor13/elixir-google-api | 85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b | [
"Apache-2.0"
] | null | null | null | clients/dataproc/lib/google_api/dataproc/v1/api/projects.ex | chingor13/elixir-google-api | 85e13fa25c4c9f4618bb463ab4c79245fc6d2a7b | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.Dataproc.V1.Api.Projects do
@moduledoc """
API calls for all endpoints tagged `Projects`.
"""
alias GoogleApi.Dataproc.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.
* `locations_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `autoscaling_policies_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.GetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_locations_autoscaling_policies_get_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_locations_autoscaling_policies_get_iam_policy(
connection,
projects_id,
locations_id,
autoscaling_policies_id,
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/projects/{projectsId}/locations/{locationsId}/autoscalingPolicies/{autoscalingPoliciesId}:getIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"autoscalingPoliciesId" => URI.encode(autoscaling_policies_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Policy{}])
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.
* `locations_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `autoscaling_policies_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_locations_autoscaling_policies_set_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_locations_autoscaling_policies_set_iam_policy(
connection,
projects_id,
locations_id,
autoscaling_policies_id,
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/projects/{projectsId}/locations/{locationsId}/autoscalingPolicies/{autoscalingPoliciesId}:setIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"autoscalingPoliciesId" => URI.encode(autoscaling_policies_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Policy{}])
end
@doc """
Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error.Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.
* `locations_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `autoscaling_policies_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_locations_autoscaling_policies_test_iam_permissions(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse.t()}
| {:error, Tesla.Env.t()}
def dataproc_projects_locations_autoscaling_policies_test_iam_permissions(
connection,
projects_id,
locations_id,
autoscaling_policies_id,
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/projects/{projectsId}/locations/{locationsId}/autoscalingPolicies/{autoscalingPoliciesId}:testIamPermissions",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"autoscalingPoliciesId" => URI.encode(autoscaling_policies_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse{}]
)
end
@doc """
Creates new workflow template.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. Required. The "resource name" of the region, as described in https://cloud.google.com/apis/design/resource_names of the form projects/{project_id}/regions/{region}
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.WorkflowTemplate.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.WorkflowTemplate{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_locations_workflow_templates_create(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.WorkflowTemplate.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_locations_workflow_templates_create(
connection,
projects_id,
locations_id,
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/projects/{projectsId}/locations/{locationsId}/workflowTemplates", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.WorkflowTemplate{}])
end
@doc """
Deletes a workflow template. It does not cancel in-progress workflows.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The "resource name" of the workflow template, as described in https://cloud.google.com/apis/design/resource_names of the form projects/{project_id}/regions/{region}/workflowTemplates/{template_id}
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `workflow_templates_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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").
* `:version` (*type:* `integer()`) - Optional. The version of workflow template to delete. If specified, will only delete the template if the current server version matches specified version.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_locations_workflow_templates_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_locations_workflow_templates_delete(
connection,
projects_id,
locations_id,
workflow_templates_id,
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,
:version => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/workflowTemplates/{workflowTemplatesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"workflowTemplatesId" => URI.encode(workflow_templates_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Empty{}])
end
@doc """
Retrieves the latest workflow template.Can retrieve previously instantiated template by specifying optional version parameter.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The "resource name" of the workflow template, as described in https://cloud.google.com/apis/design/resource_names of the form projects/{project_id}/regions/{region}/workflowTemplates/{template_id}
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `workflow_templates_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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").
* `:version` (*type:* `integer()`) - Optional. The version of workflow template to retrieve. Only previously instatiated versions can be retrieved.If unspecified, retrieves the current version.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.WorkflowTemplate{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_locations_workflow_templates_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.WorkflowTemplate.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_locations_workflow_templates_get(
connection,
projects_id,
locations_id,
workflow_templates_id,
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,
:version => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/workflowTemplates/{workflowTemplatesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"workflowTemplatesId" => URI.encode(workflow_templates_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.WorkflowTemplate{}])
end
@doc """
Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.
* `locations_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `workflow_templates_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.GetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_locations_workflow_templates_get_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_locations_workflow_templates_get_iam_policy(
connection,
projects_id,
locations_id,
workflow_templates_id,
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/projects/{projectsId}/locations/{locationsId}/workflowTemplates/{workflowTemplatesId}:getIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"workflowTemplatesId" => URI.encode(workflow_templates_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Policy{}])
end
@doc """
Instantiates a template and begins execution.The returned Operation can be used to track execution of workflow by polling operations.get. The Operation will complete when entire workflow is finished.The running workflow can be aborted via operations.cancel. This will cause any inflight jobs to be cancelled and workflow-owned clusters to be deleted.The Operation.metadata will be WorkflowMetadata.On successful completion, Operation.response will be Empty.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The "resource name" of the workflow template, as described in https://cloud.google.com/apis/design/resource_names of the form projects/{project_id}/regions/{region}/workflowTemplates/{template_id}
* `locations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `workflow_templates_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.InstantiateWorkflowTemplateRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_locations_workflow_templates_instantiate(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_locations_workflow_templates_instantiate(
connection,
projects_id,
locations_id,
workflow_templates_id,
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/projects/{projectsId}/locations/{locationsId}/workflowTemplates/{workflowTemplatesId}:instantiate",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"workflowTemplatesId" => URI.encode(workflow_templates_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Operation{}])
end
@doc """
Instantiates a template and begins execution.This method is equivalent to executing the sequence CreateWorkflowTemplate, InstantiateWorkflowTemplate, DeleteWorkflowTemplate.The returned Operation can be used to track execution of workflow by polling operations.get. The Operation will complete when entire workflow is finished.The running workflow can be aborted via operations.cancel. This will cause any inflight jobs to be cancelled and workflow-owned clusters to be deleted.The Operation.metadata will be WorkflowMetadata.On successful completion, Operation.response will be Empty.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. Required. The "resource name" of the workflow template region, as described in https://cloud.google.com/apis/design/resource_names of the form projects/{project_id}/regions/{region}
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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").
* `:requestId` (*type:* `String.t`) - Optional. A tag that prevents multiple concurrent workflow instances with the same tag from running. This mitigates risk of concurrent instances started due to retries.It is recommended to always set this value to a UUID (https://en.wikipedia.org/wiki/Universally_unique_identifier).The tag must contain only letters (a-z, A-Z), numbers (0-9), underscores (_), and hyphens (-). The maximum length is 40 characters.
* `:body` (*type:* `GoogleApi.Dataproc.V1.Model.WorkflowTemplate.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_locations_workflow_templates_instantiate_inline(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_locations_workflow_templates_instantiate_inline(
connection,
projects_id,
locations_id,
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,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/workflowTemplates:instantiateInline",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Operation{}])
end
@doc """
Lists workflows that match the specified filter in the request.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. Required. The "resource name" of the region, as described in https://cloud.google.com/apis/design/resource_names of the form projects/{project_id}/regions/{region}
* `locations_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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()`) - Optional. The maximum number of results to return in each response.
* `:pageToken` (*type:* `String.t`) - Optional. The page token, returned by a previous call, to request the next page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.ListWorkflowTemplatesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_locations_workflow_templates_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Dataproc.V1.Model.ListWorkflowTemplatesResponse.t()}
| {:error, Tesla.Env.t()}
def dataproc_projects_locations_workflow_templates_list(
connection,
projects_id,
locations_id,
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/projects/{projectsId}/locations/{locationsId}/workflowTemplates", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Dataproc.V1.Model.ListWorkflowTemplatesResponse{}]
)
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.
* `locations_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `workflow_templates_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_locations_workflow_templates_set_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_locations_workflow_templates_set_iam_policy(
connection,
projects_id,
locations_id,
workflow_templates_id,
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/projects/{projectsId}/locations/{locationsId}/workflowTemplates/{workflowTemplatesId}:setIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"workflowTemplatesId" => URI.encode(workflow_templates_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Policy{}])
end
@doc """
Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error.Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.
* `locations_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `workflow_templates_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_locations_workflow_templates_test_iam_permissions(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse.t()}
| {:error, Tesla.Env.t()}
def dataproc_projects_locations_workflow_templates_test_iam_permissions(
connection,
projects_id,
locations_id,
workflow_templates_id,
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/projects/{projectsId}/locations/{locationsId}/workflowTemplates/{workflowTemplatesId}:testIamPermissions",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"workflowTemplatesId" => URI.encode(workflow_templates_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse{}]
)
end
@doc """
Updates (replaces) workflow template. The updated template must contain version that matches the current server version.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `template.name`. Output only. The "resource name" of the template, as described in https://cloud.google.com/apis/design/resource_names of the form projects/{project_id}/regions/{region}/workflowTemplates/{template_id}
* `locations_id` (*type:* `String.t`) - Part of `template.name`. See documentation of `projectsId`.
* `workflow_templates_id` (*type:* `String.t`) - Part of `template.name`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.WorkflowTemplate.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.WorkflowTemplate{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_locations_workflow_templates_update(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.WorkflowTemplate.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_locations_workflow_templates_update(
connection,
projects_id,
locations_id,
workflow_templates_id,
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(:put)
|> Request.url(
"/v1/projects/{projectsId}/locations/{locationsId}/workflowTemplates/{workflowTemplatesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"locationsId" => URI.encode(locations_id, &URI.char_unreserved?/1),
"workflowTemplatesId" => URI.encode(workflow_templates_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.WorkflowTemplate{}])
end
@doc """
Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.
* `regions_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `autoscaling_policies_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.GetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_autoscaling_policies_get_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_autoscaling_policies_get_iam_policy(
connection,
projects_id,
regions_id,
autoscaling_policies_id,
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/projects/{projectsId}/regions/{regionsId}/autoscalingPolicies/{autoscalingPoliciesId}:getIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"autoscalingPoliciesId" => URI.encode(autoscaling_policies_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Policy{}])
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.
* `regions_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `autoscaling_policies_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_autoscaling_policies_set_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_autoscaling_policies_set_iam_policy(
connection,
projects_id,
regions_id,
autoscaling_policies_id,
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/projects/{projectsId}/regions/{regionsId}/autoscalingPolicies/{autoscalingPoliciesId}:setIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"autoscalingPoliciesId" => URI.encode(autoscaling_policies_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Policy{}])
end
@doc """
Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error.Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.
* `regions_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `autoscaling_policies_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_autoscaling_policies_test_iam_permissions(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse.t()}
| {:error, Tesla.Env.t()}
def dataproc_projects_regions_autoscaling_policies_test_iam_permissions(
connection,
projects_id,
regions_id,
autoscaling_policies_id,
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/projects/{projectsId}/regions/{regionsId}/autoscalingPolicies/{autoscalingPoliciesId}:testIamPermissions",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"autoscalingPoliciesId" => URI.encode(autoscaling_policies_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse{}]
)
end
@doc """
Creates a cluster in a project.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Required. The ID of the Google Cloud Platform project that the cluster belongs to.
* `region` (*type:* `String.t`) - Required. The Cloud Dataproc region in which to handle the request.
* `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").
* `:requestId` (*type:* `String.t`) - Optional. A unique id used to identify the request. If the server receives two CreateClusterRequest requests with the same id, then the second request will be ignored and the first google.longrunning.Operation created and stored in the backend is returned.It is recommended to always set this value to a UUID (https://en.wikipedia.org/wiki/Universally_unique_identifier).The id must contain only letters (a-z, A-Z), numbers (0-9), underscores (_), and hyphens (-). The maximum length is 40 characters.
* `:body` (*type:* `GoogleApi.Dataproc.V1.Model.Cluster.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_clusters_create(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_clusters_create(
connection,
project_id,
region,
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,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/v1/projects/{projectId}/regions/{region}/clusters", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Operation{}])
end
@doc """
Deletes a cluster in a project.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Required. The ID of the Google Cloud Platform project that the cluster belongs to.
* `region` (*type:* `String.t`) - Required. The Cloud Dataproc region in which to handle the request.
* `cluster_name` (*type:* `String.t`) - Required. The cluster name.
* `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").
* `:clusterUuid` (*type:* `String.t`) - Optional. Specifying the cluster_uuid means the RPC should fail (with error NOT_FOUND) if cluster with specified UUID does not exist.
* `:requestId` (*type:* `String.t`) - Optional. A unique id used to identify the request. If the server receives two DeleteClusterRequest requests with the same id, then the second request will be ignored and the first google.longrunning.Operation created and stored in the backend is returned.It is recommended to always set this value to a UUID (https://en.wikipedia.org/wiki/Universally_unique_identifier).The id must contain only letters (a-z, A-Z), numbers (0-9), underscores (_), and hyphens (-). The maximum length is 40 characters.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_clusters_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_clusters_delete(
connection,
project_id,
region,
cluster_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,
:clusterUuid => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/v1/projects/{projectId}/regions/{region}/clusters/{clusterName}", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1),
"clusterName" => URI.encode(cluster_name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Operation{}])
end
@doc """
Gets cluster diagnostic information. After the operation completes, the Operation.response field contains DiagnoseClusterOutputLocation.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Required. The ID of the Google Cloud Platform project that the cluster belongs to.
* `region` (*type:* `String.t`) - Required. The Cloud Dataproc region in which to handle the request.
* `cluster_name` (*type:* `String.t`) - Required. The cluster name.
* `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.Dataproc.V1.Model.DiagnoseClusterRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_clusters_diagnose(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_clusters_diagnose(
connection,
project_id,
region,
cluster_name,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/v1/projects/{projectId}/regions/{region}/clusters/{clusterName}:diagnose",
%{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1),
"clusterName" => URI.encode(cluster_name, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Operation{}])
end
@doc """
Gets the resource representation for a cluster in a project.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Required. The ID of the Google Cloud Platform project that the cluster belongs to.
* `region` (*type:* `String.t`) - Required. The Cloud Dataproc region in which to handle the request.
* `cluster_name` (*type:* `String.t`) - Required. The cluster name.
* `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.Dataproc.V1.Model.Cluster{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_clusters_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Cluster.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_clusters_get(
connection,
project_id,
region,
cluster_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/projects/{projectId}/regions/{region}/clusters/{clusterName}", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1),
"clusterName" => URI.encode(cluster_name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Cluster{}])
end
@doc """
Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.
* `regions_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `clusters_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.GetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_clusters_get_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_clusters_get_iam_policy(
connection,
projects_id,
regions_id,
clusters_id,
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/projects/{projectsId}/regions/{regionsId}/clusters/{clustersId}:getIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"clustersId" => URI.encode(clusters_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Policy{}])
end
@doc """
Lists all regions/{region}/clusters in a project.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Required. The ID of the Google Cloud Platform project that the cluster belongs to.
* `region` (*type:* `String.t`) - Required. The Cloud Dataproc region in which to handle the request.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:$.xgafv` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - Optional. A filter constraining the clusters to list. Filters are case-sensitive and have the following syntax:field = value AND field = value ...where field is one of status.state, clusterName, or labels.[KEY], and [KEY] is a label key. value can be * to match all values. status.state can be one of the following: ACTIVE, INACTIVE, CREATING, RUNNING, ERROR, DELETING, or UPDATING. ACTIVE contains the CREATING, UPDATING, and RUNNING states. INACTIVE contains the DELETING and ERROR states. clusterName is the name of the cluster provided at creation time. Only the logical AND operator is supported; space-separated items are treated as having an implicit AND operator.Example filter:status.state = ACTIVE AND clusterName = mycluster AND labels.env = staging AND labels.starred = *
* `:pageSize` (*type:* `integer()`) - Optional. The standard List page size.
* `:pageToken` (*type:* `String.t`) - Optional. The standard List page token.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.ListClustersResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_clusters_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.ListClustersResponse.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_clusters_list(
connection,
project_id,
region,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/projects/{projectId}/regions/{region}/clusters", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.ListClustersResponse{}])
end
@doc """
Updates a cluster in a project.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Required. The ID of the Google Cloud Platform project the cluster belongs to.
* `region` (*type:* `String.t`) - Required. The Cloud Dataproc region in which to handle the request.
* `cluster_name` (*type:* `String.t`) - Required. The cluster name.
* `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").
* `:gracefulDecommissionTimeout` (*type:* `String.t`) - Optional. Timeout for graceful YARN decomissioning. Graceful decommissioning allows removing nodes from the cluster without interrupting jobs in progress. Timeout specifies how long to wait for jobs in progress to finish before forcefully removing nodes (and potentially interrupting jobs). Default timeout is 0 (for forceful decommission), and the maximum allowed timeout is 1 day.Only supported on Dataproc image versions 1.2 and higher.
* `:requestId` (*type:* `String.t`) - Optional. A unique id used to identify the request. If the server receives two UpdateClusterRequest requests with the same id, then the second request will be ignored and the first google.longrunning.Operation created and stored in the backend is returned.It is recommended to always set this value to a UUID (https://en.wikipedia.org/wiki/Universally_unique_identifier).The id must contain only letters (a-z, A-Z), numbers (0-9), underscores (_), and hyphens (-). The maximum length is 40 characters.
* `:updateMask` (*type:* `String.t`) - Required. Specifies the path, relative to Cluster, of the field to update. For example, to change the number of workers in a cluster to 5, the update_mask parameter would be specified as config.worker_config.num_instances, and the PATCH request body would specify the new value, as follows:
{
"config":{
"workerConfig":{
"numInstances":"5"
}
}
}
Similarly, to change the number of preemptible workers in a cluster to 5, the update_mask parameter would be config.secondary_worker_config.num_instances, and the PATCH request body would be set as follows:
{
"config":{
"secondaryWorkerConfig":{
"numInstances":"5"
}
}
}
<strong>Note:</strong> Currently, only the following fields can be updated:<table> <tbody> <tr> <td><strong>Mask</strong></td> <td><strong>Purpose</strong></td> </tr> <tr> <td><strong><em>labels</em></strong></td> <td>Update labels</td> </tr> <tr> <td><strong><em>config.worker_config.num_instances</em></strong></td> <td>Resize primary worker group</td> </tr> <tr> <td><strong><em>config.secondary_worker_config.num_instances</em></strong></td> <td>Resize secondary worker group</td> </tr> </tbody> </table>
* `:body` (*type:* `GoogleApi.Dataproc.V1.Model.Cluster.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_clusters_patch(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_clusters_patch(
connection,
project_id,
region,
cluster_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,
:gracefulDecommissionTimeout => :query,
:requestId => :query,
:updateMask => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/v1/projects/{projectId}/regions/{region}/clusters/{clusterName}", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1),
"clusterName" => URI.encode(cluster_name, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Operation{}])
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.
* `regions_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `clusters_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_clusters_set_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_clusters_set_iam_policy(
connection,
projects_id,
regions_id,
clusters_id,
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/projects/{projectsId}/regions/{regionsId}/clusters/{clustersId}:setIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"clustersId" => URI.encode(clusters_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Policy{}])
end
@doc """
Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error.Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.
* `regions_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `clusters_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_clusters_test_iam_permissions(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse.t()}
| {:error, Tesla.Env.t()}
def dataproc_projects_regions_clusters_test_iam_permissions(
connection,
projects_id,
regions_id,
clusters_id,
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/projects/{projectsId}/regions/{regionsId}/clusters/{clustersId}:testIamPermissions",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"clustersId" => URI.encode(clusters_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse{}]
)
end
@doc """
Starts a job cancellation request. To access the job resource after cancellation, call regions/{region}/jobs.list or regions/{region}/jobs.get.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Required. The ID of the Google Cloud Platform project that the job belongs to.
* `region` (*type:* `String.t`) - Required. The Cloud Dataproc region in which to handle the request.
* `job_id` (*type:* `String.t`) - Required. The job ID.
* `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.Dataproc.V1.Model.CancelJobRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Job{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_jobs_cancel(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Job.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_jobs_cancel(
connection,
project_id,
region,
job_id,
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/projects/{projectId}/regions/{region}/jobs/{jobId}:cancel", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1),
"jobId" => URI.encode(job_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Job{}])
end
@doc """
Deletes the job from the project. If the job is active, the delete fails, and the response returns FAILED_PRECONDITION.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Required. The ID of the Google Cloud Platform project that the job belongs to.
* `region` (*type:* `String.t`) - Required. The Cloud Dataproc region in which to handle the request.
* `job_id` (*type:* `String.t`) - Required. The job ID.
* `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.Dataproc.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_jobs_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_jobs_delete(
connection,
project_id,
region,
job_id,
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/projects/{projectId}/regions/{region}/jobs/{jobId}", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1),
"jobId" => URI.encode(job_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Empty{}])
end
@doc """
Gets the resource representation for a job in a project.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Required. The ID of the Google Cloud Platform project that the job belongs to.
* `region` (*type:* `String.t`) - Required. The Cloud Dataproc region in which to handle the request.
* `job_id` (*type:* `String.t`) - Required. The job ID.
* `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.Dataproc.V1.Model.Job{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_jobs_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Job.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_jobs_get(
connection,
project_id,
region,
job_id,
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/projects/{projectId}/regions/{region}/jobs/{jobId}", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1),
"jobId" => URI.encode(job_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Job{}])
end
@doc """
Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.
* `regions_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `jobs_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.GetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_jobs_get_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_jobs_get_iam_policy(
connection,
projects_id,
regions_id,
jobs_id,
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/projects/{projectsId}/regions/{regionsId}/jobs/{jobsId}:getIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"jobsId" => URI.encode(jobs_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Policy{}])
end
@doc """
Lists regions/{region}/jobs in a project.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Required. The ID of the Google Cloud Platform project that the job belongs to.
* `region` (*type:* `String.t`) - Required. The Cloud Dataproc region in which to handle the request.
* `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").
* `:clusterName` (*type:* `String.t`) - Optional. If set, the returned jobs list includes only jobs that were submitted to the named cluster.
* `:filter` (*type:* `String.t`) - Optional. A filter constraining the jobs to list. Filters are case-sensitive and have the following syntax:field = value AND field = value ...where field is status.state or labels.[KEY], and [KEY] is a label key. value can be * to match all values. status.state can be either ACTIVE or NON_ACTIVE. Only the logical AND operator is supported; space-separated items are treated as having an implicit AND operator.Example filter:status.state = ACTIVE AND labels.env = staging AND labels.starred = *
* `:jobStateMatcher` (*type:* `String.t`) - Optional. Specifies enumerated categories of jobs to list. (default = match ALL jobs).If filter is provided, jobStateMatcher will be ignored.
* `:pageSize` (*type:* `integer()`) - Optional. The number of results to return in each response.
* `:pageToken` (*type:* `String.t`) - Optional. The page token, returned by a previous call, to request the next page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.ListJobsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_jobs_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.ListJobsResponse.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_jobs_list(
connection,
project_id,
region,
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,
:clusterName => :query,
:filter => :query,
:jobStateMatcher => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/projects/{projectId}/regions/{region}/jobs", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.ListJobsResponse{}])
end
@doc """
Updates a job in a project.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Required. The ID of the Google Cloud Platform project that the job belongs to.
* `region` (*type:* `String.t`) - Required. The Cloud Dataproc region in which to handle the request.
* `job_id` (*type:* `String.t`) - Required. The job ID.
* `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`) - Required. Specifies the path, relative to <code>Job</code>, of the field to update. For example, to update the labels of a Job the <code>update_mask</code> parameter would be specified as <code>labels</code>, and the PATCH request body would specify the new value. <strong>Note:</strong> Currently, <code>labels</code> is the only field that can be updated.
* `:body` (*type:* `GoogleApi.Dataproc.V1.Model.Job.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Job{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_jobs_patch(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Job.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_jobs_patch(
connection,
project_id,
region,
job_id,
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/projects/{projectId}/regions/{region}/jobs/{jobId}", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1),
"jobId" => URI.encode(job_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Job{}])
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.
* `regions_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `jobs_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_jobs_set_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_jobs_set_iam_policy(
connection,
projects_id,
regions_id,
jobs_id,
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/projects/{projectsId}/regions/{regionsId}/jobs/{jobsId}:setIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"jobsId" => URI.encode(jobs_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Policy{}])
end
@doc """
Submits a job to a cluster.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `project_id` (*type:* `String.t`) - Required. The ID of the Google Cloud Platform project that the job belongs to.
* `region` (*type:* `String.t`) - Required. The Cloud Dataproc region in which to handle the request.
* `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.Dataproc.V1.Model.SubmitJobRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Job{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_jobs_submit(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Job.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_jobs_submit(
connection,
project_id,
region,
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/projects/{projectId}/regions/{region}/jobs:submit", %{
"projectId" => URI.encode(project_id, &URI.char_unreserved?/1),
"region" => URI.encode(region, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Job{}])
end
@doc """
Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error.Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.
* `regions_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `jobs_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_jobs_test_iam_permissions(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse.t()}
| {:error, Tesla.Env.t()}
def dataproc_projects_regions_jobs_test_iam_permissions(
connection,
projects_id,
regions_id,
jobs_id,
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/projects/{projectsId}/regions/{regionsId}/jobs/{jobsId}:testIamPermissions",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"jobsId" => URI.encode(jobs_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse{}]
)
end
@doc """
Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns google.rpc.Code.UNIMPLEMENTED. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to Code.CANCELLED.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the operation resource to be cancelled.
* `regions_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `operations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_operations_cancel(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_operations_cancel(
connection,
projects_id,
regions_id,
operations_id,
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(:post)
|> Request.url(
"/v1/projects/{projectsId}/regions/{regionsId}/operations/{operationsId}:cancel",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"operationsId" => URI.encode(operations_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Empty{}])
end
@doc """
Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns google.rpc.Code.UNIMPLEMENTED.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the operation resource to be deleted.
* `regions_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `operations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_operations_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_operations_delete(
connection,
projects_id,
regions_id,
operations_id,
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/projects/{projectsId}/regions/{regionsId}/operations/{operationsId}", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"operationsId" => URI.encode(operations_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Empty{}])
end
@doc """
Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the operation resource.
* `regions_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `operations_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_operations_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_operations_get(
connection,
projects_id,
regions_id,
operations_id,
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/projects/{projectsId}/regions/{regionsId}/operations/{operationsId}", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"operationsId" => URI.encode(operations_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Operation{}])
end
@doc """
Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.
* `regions_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `operations_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.GetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_operations_get_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_operations_get_iam_policy(
connection,
projects_id,
regions_id,
operations_id,
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/projects/{projectsId}/regions/{regionsId}/operations/{operationsId}:getIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"operationsId" => URI.encode(operations_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Policy{}])
end
@doc """
Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns UNIMPLEMENTED.NOTE: the name binding allows API services to override the binding to use different resource name schemes, such as users/*/operations. To override the binding, API services can add a binding such as "/v1/{name=users/*}/operations" to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. The name of the operation's parent resource.
* `regions_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `optional_params` (*type:* `keyword()`) - Optional parameters
* `:$.xgafv` (*type:* `String.t`) - V1 error format.
* `:access_token` (*type:* `String.t`) - OAuth access token.
* `:alt` (*type:* `String.t`) - Data format for response.
* `:callback` (*type:* `String.t`) - JSONP
* `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response.
* `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
* `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user.
* `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks.
* `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart").
* `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart").
* `:filter` (*type:* `String.t`) - The standard list filter.
* `:pageSize` (*type:* `integer()`) - The standard list page size.
* `:pageToken` (*type:* `String.t`) - The standard list page token.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.ListOperationsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_operations_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Dataproc.V1.Model.ListOperationsResponse.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_operations_list(
connection,
projects_id,
regions_id,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:"$.xgafv" => :query,
:access_token => :query,
:alt => :query,
:callback => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:uploadType => :query,
:upload_protocol => :query,
:filter => :query,
:pageSize => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/v1/projects/{projectsId}/regions/{regionsId}/operations", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.ListOperationsResponse{}])
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.
* `regions_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `operations_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_operations_set_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_operations_set_iam_policy(
connection,
projects_id,
regions_id,
operations_id,
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/projects/{projectsId}/regions/{regionsId}/operations/{operationsId}:setIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"operationsId" => URI.encode(operations_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Policy{}])
end
@doc """
Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error.Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.
* `regions_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `operations_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_operations_test_iam_permissions(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse.t()}
| {:error, Tesla.Env.t()}
def dataproc_projects_regions_operations_test_iam_permissions(
connection,
projects_id,
regions_id,
operations_id,
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/projects/{projectsId}/regions/{regionsId}/operations/{operationsId}:testIamPermissions",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"operationsId" => URI.encode(operations_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse{}]
)
end
@doc """
Creates new workflow template.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. Required. The "resource name" of the region, as described in https://cloud.google.com/apis/design/resource_names of the form projects/{project_id}/regions/{region}
* `regions_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.WorkflowTemplate.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.WorkflowTemplate{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_workflow_templates_create(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.WorkflowTemplate.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_workflow_templates_create(
connection,
projects_id,
regions_id,
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/projects/{projectsId}/regions/{regionsId}/workflowTemplates", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.WorkflowTemplate{}])
end
@doc """
Deletes a workflow template. It does not cancel in-progress workflows.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The "resource name" of the workflow template, as described in https://cloud.google.com/apis/design/resource_names of the form projects/{project_id}/regions/{region}/workflowTemplates/{template_id}
* `regions_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `workflow_templates_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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").
* `:version` (*type:* `integer()`) - Optional. The version of workflow template to delete. If specified, will only delete the template if the current server version matches specified version.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Empty{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_workflow_templates_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Empty.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_workflow_templates_delete(
connection,
projects_id,
regions_id,
workflow_templates_id,
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,
:version => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url(
"/v1/projects/{projectsId}/regions/{regionsId}/workflowTemplates/{workflowTemplatesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"workflowTemplatesId" => URI.encode(workflow_templates_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Empty{}])
end
@doc """
Retrieves the latest workflow template.Can retrieve previously instantiated template by specifying optional version parameter.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The "resource name" of the workflow template, as described in https://cloud.google.com/apis/design/resource_names of the form projects/{project_id}/regions/{region}/workflowTemplates/{template_id}
* `regions_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `workflow_templates_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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").
* `:version` (*type:* `integer()`) - Optional. The version of workflow template to retrieve. Only previously instatiated versions can be retrieved.If unspecified, retrieves the current version.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.WorkflowTemplate{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_workflow_templates_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.WorkflowTemplate.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_workflow_templates_get(
connection,
projects_id,
regions_id,
workflow_templates_id,
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,
:version => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url(
"/v1/projects/{projectsId}/regions/{regionsId}/workflowTemplates/{workflowTemplatesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"workflowTemplatesId" => URI.encode(workflow_templates_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.WorkflowTemplate{}])
end
@doc """
Gets the access control policy for a resource. Returns an empty policy if the resource exists and does not have a policy set.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.
* `regions_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `workflow_templates_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.GetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_workflow_templates_get_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_workflow_templates_get_iam_policy(
connection,
projects_id,
regions_id,
workflow_templates_id,
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/projects/{projectsId}/regions/{regionsId}/workflowTemplates/{workflowTemplatesId}:getIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"workflowTemplatesId" => URI.encode(workflow_templates_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Policy{}])
end
@doc """
Instantiates a template and begins execution.The returned Operation can be used to track execution of workflow by polling operations.get. The Operation will complete when entire workflow is finished.The running workflow can be aborted via operations.cancel. This will cause any inflight jobs to be cancelled and workflow-owned clusters to be deleted.The Operation.metadata will be WorkflowMetadata.On successful completion, Operation.response will be Empty.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `name`. Required. The "resource name" of the workflow template, as described in https://cloud.google.com/apis/design/resource_names of the form projects/{project_id}/regions/{region}/workflowTemplates/{template_id}
* `regions_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `workflow_templates_id` (*type:* `String.t`) - Part of `name`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.InstantiateWorkflowTemplateRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_workflow_templates_instantiate(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_workflow_templates_instantiate(
connection,
projects_id,
regions_id,
workflow_templates_id,
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/projects/{projectsId}/regions/{regionsId}/workflowTemplates/{workflowTemplatesId}:instantiate",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"workflowTemplatesId" => URI.encode(workflow_templates_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Operation{}])
end
@doc """
Instantiates a template and begins execution.This method is equivalent to executing the sequence CreateWorkflowTemplate, InstantiateWorkflowTemplate, DeleteWorkflowTemplate.The returned Operation can be used to track execution of workflow by polling operations.get. The Operation will complete when entire workflow is finished.The running workflow can be aborted via operations.cancel. This will cause any inflight jobs to be cancelled and workflow-owned clusters to be deleted.The Operation.metadata will be WorkflowMetadata.On successful completion, Operation.response will be Empty.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. Required. The "resource name" of the workflow template region, as described in https://cloud.google.com/apis/design/resource_names of the form projects/{project_id}/regions/{region}
* `regions_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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").
* `:requestId` (*type:* `String.t`) - Optional. A tag that prevents multiple concurrent workflow instances with the same tag from running. This mitigates risk of concurrent instances started due to retries.It is recommended to always set this value to a UUID (https://en.wikipedia.org/wiki/Universally_unique_identifier).The tag must contain only letters (a-z, A-Z), numbers (0-9), underscores (_), and hyphens (-). The maximum length is 40 characters.
* `:body` (*type:* `GoogleApi.Dataproc.V1.Model.WorkflowTemplate.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_workflow_templates_instantiate_inline(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_workflow_templates_instantiate_inline(
connection,
projects_id,
regions_id,
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,
:requestId => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url(
"/v1/projects/{projectsId}/regions/{regionsId}/workflowTemplates:instantiateInline",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Operation{}])
end
@doc """
Lists workflows that match the specified filter in the request.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `parent`. Required. The "resource name" of the region, as described in https://cloud.google.com/apis/design/resource_names of the form projects/{project_id}/regions/{region}
* `regions_id` (*type:* `String.t`) - Part of `parent`. See documentation of `projectsId`.
* `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()`) - Optional. The maximum number of results to return in each response.
* `:pageToken` (*type:* `String.t`) - Optional. The page token, returned by a previous call, to request the next page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.ListWorkflowTemplatesResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_workflow_templates_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Dataproc.V1.Model.ListWorkflowTemplatesResponse.t()}
| {:error, Tesla.Env.t()}
def dataproc_projects_regions_workflow_templates_list(
connection,
projects_id,
regions_id,
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/projects/{projectsId}/regions/{regionsId}/workflowTemplates", %{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Dataproc.V1.Model.ListWorkflowTemplatesResponse{}]
)
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.
* `regions_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `workflow_templates_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.SetIamPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_workflow_templates_set_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_workflow_templates_set_iam_policy(
connection,
projects_id,
regions_id,
workflow_templates_id,
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/projects/{projectsId}/regions/{regionsId}/workflowTemplates/{workflowTemplatesId}:setIamPolicy",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"workflowTemplatesId" => URI.encode(workflow_templates_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.Policy{}])
end
@doc """
Returns permissions that a caller has on the specified resource. If the resource does not exist, this will return an empty set of permissions, not a NOT_FOUND error.Note: This operation is designed to be used for building permission-aware UIs and command-line tools, not for authorization checking. This operation may "fail open" without warning.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `resource`. REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.
* `regions_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `workflow_templates_id` (*type:* `String.t`) - Part of `resource`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.TestIamPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_workflow_templates_test_iam_permissions(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse.t()}
| {:error, Tesla.Env.t()}
def dataproc_projects_regions_workflow_templates_test_iam_permissions(
connection,
projects_id,
regions_id,
workflow_templates_id,
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/projects/{projectsId}/regions/{regionsId}/workflowTemplates/{workflowTemplatesId}:testIamPermissions",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"workflowTemplatesId" => URI.encode(workflow_templates_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(
opts ++ [struct: %GoogleApi.Dataproc.V1.Model.TestIamPermissionsResponse{}]
)
end
@doc """
Updates (replaces) workflow template. The updated template must contain version that matches the current server version.
## Parameters
* `connection` (*type:* `GoogleApi.Dataproc.V1.Connection.t`) - Connection to server
* `projects_id` (*type:* `String.t`) - Part of `template.name`. Output only. The "resource name" of the template, as described in https://cloud.google.com/apis/design/resource_names of the form projects/{project_id}/regions/{region}/workflowTemplates/{template_id}
* `regions_id` (*type:* `String.t`) - Part of `template.name`. See documentation of `projectsId`.
* `workflow_templates_id` (*type:* `String.t`) - Part of `template.name`. See documentation of `projectsId`.
* `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.Dataproc.V1.Model.WorkflowTemplate.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Dataproc.V1.Model.WorkflowTemplate{}}` on success
* `{:error, info}` on failure
"""
@spec dataproc_projects_regions_workflow_templates_update(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Dataproc.V1.Model.WorkflowTemplate.t()} | {:error, Tesla.Env.t()}
def dataproc_projects_regions_workflow_templates_update(
connection,
projects_id,
regions_id,
workflow_templates_id,
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(:put)
|> Request.url(
"/v1/projects/{projectsId}/regions/{regionsId}/workflowTemplates/{workflowTemplatesId}",
%{
"projectsId" => URI.encode(projects_id, &URI.char_unreserved?/1),
"regionsId" => URI.encode(regions_id, &URI.char_unreserved?/1),
"workflowTemplatesId" => URI.encode(workflow_templates_id, &URI.char_unreserved?/1)
}
)
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Dataproc.V1.Model.WorkflowTemplate{}])
end
end
| 48.578961 | 826 | 0.626368 |
79128ff2306d75e3d15e27e45a74f57333089fb5 | 19,979 | ex | Elixir | lib/mint/web_socket.ex | hkrutzer/mint_web_socket | 213bdc56addbc3d7b5344d14b6e194cc1ca3024f | [
"Apache-2.0"
] | null | null | null | lib/mint/web_socket.ex | hkrutzer/mint_web_socket | 213bdc56addbc3d7b5344d14b6e194cc1ca3024f | [
"Apache-2.0"
] | null | null | null | lib/mint/web_socket.ex | hkrutzer/mint_web_socket | 213bdc56addbc3d7b5344d14b6e194cc1ca3024f | [
"Apache-2.0"
] | null | null | null | defmodule Mint.WebSocket do
@moduledoc """
HTTP/1 and HTTP/2 WebSocket support for the Mint functional HTTP client
Like Mint, `Mint.WebSocket` provides a functional, process-less interface
for operating a WebSocket connection. Prospective Mint.WebSocket users
may wish to first familiarize themselves with `Mint.HTTP`.
Mint.WebSocket is not fully spec-conformant on its own. Runtime behaviors
such as responding to pings with pongs must be implemented by the user of
Mint.WebSocket.
## Usage
A connection formed with `Mint.HTTP.connect/4` can be upgraded to a WebSocket
connection with `upgrade/5`.
```elixir
{:ok, conn} = Mint.HTTP.connect(:http, "localhost", 9_000)
{:ok, conn, ref} = Mint.WebSocket.upgrade(:ws, conn, "/", [])
```
`upgrade/5` sends an upgrade request to the remote server. The WebSocket
connection is then built by awaiting the HTTP response from the server.
```elixir
http_reply_message = receive(do: (message -> message))
{:ok, conn, [{:status, ^ref, status}, {:headers, ^ref, resp_headers}, {:done, ^ref}]} =
Mint.WebSocket.stream(conn, http_reply_message)
{:ok, conn, websocket} =
Mint.WebSocket.new(conn, ref, status, resp_headers)
```
Once the WebSocket connection has been established, use the `websocket`
data structure to encode and decode frames with `encode/2` and `decode/2`,
and send and stream messages with `stream_request_body/3` and `stream/2`.
For example, one may send a "hello world" text frame across a connection
like so:
```elixir
{:ok, websocket, data} = Mint.WebSocket.encode(websocket, {:text, "hello world"})
{:ok, conn} = Mint.WebSocket.stream_request_body(conn, ref, data)
```
Say that the remote is echoing messages. Use `stream/2` and `decode/2` to
decode a received WebSocket frame:
```elixir
echo_message = receive(do: (message -> message))
{:ok, conn, [{:data, ^ref, data}]} = Mint.WebSocket.stream(conn, echo_message)
{:ok, websocket, [{:text, "hello world"}]} = Mint.WebSocket.decode(websocket, data)
```
## HTTP/2 Support
Mint.WebSocket supports WebSockets over HTTP/2 as defined in rfc8441.
rfc8441 is an extension to the HTTP/2 specification. At the time of
writing, very few HTTP/2 server libraries support or enable HTTP/2
WebSockets by default.
`upgrade/5` works on both HTTP/1 and HTTP/2 connections. In order to select
HTTP/2, the `:http2` protocol should be explicitly selected in
`Mint.HTTP.connect/4`.
```elixir
{:ok, conn} =
Mint.HTTP.connect(:http, "websocket.example", 80, protocols: [:http2])
:http2 = Mint.HTTP.protocol(conn)
{:ok, conn, ref} = Mint.WebSocket.upgrade(:ws, conn, "/", [])
```
If the server does not support the extended CONNECT method needed to bootstrap
WebSocket connections over HTTP/2, `upgrade/4` will return an error tuple
with the `:extended_connect_disabled` error reason.
```elixir
{:error, conn, %Mint.WebSocketError{reason: :extended_connect_disabled}}
```
Why use HTTP/2 for WebSocket connections in the first place? HTTP/2
can multiplex many requests over the same connection, which can
reduce the latency incurred by forming new connections for each request.
A WebSocket connection only occupies one stream of a HTTP/2 connection, so
even if an HTTP/2 connection has an open WebSocket communication, it can be
used to transport more requests.
## WebSocket Secure
Encryption of connections is handled by Mint functions. To start a WSS
connection, select `:https` as the scheme in `Mint.HTTP.connect/4`:
```elixir
{:ok, conn} = Mint.HTTP.connect(:https, "websocket.example", 443)
```
And pass the `:wss` scheme to `upgrade/5`. See the Mint documentation
on SSL for more information.
## Extensions
The WebSocket protocol allows for _extensions_. Extensions act as a
middleware for encoding and decoding frames. For example "permessage-deflate"
compresses and decompresses the body of data frames, which minifies the amount
of bytes which must be sent over the network.
See `Mint.WebSocket.Extension` for more information about extensions and
`Mint.WebSocket.PerMessageDeflate` for information about the
"permessage-deflate" extension.
"""
alias __MODULE__.{Utils, Extension, Frame}
alias Mint.{WebSocketError, WebSocket.UpgradeFailureError}
alias Mint.{HTTP1, HTTP2}
import Mint.HTTP, only: [get_private: 2, put_private: 3, protocol: 1]
@typedoc """
An immutable data structure representing a WebSocket connection
"""
@opaque t :: %__MODULE__{
extensions: [Extension.t()],
fragment: tuple(),
private: map(),
buffer: binary()
}
defstruct extensions: [],
fragment: nil,
private: %{},
buffer: <<>>
@type error :: Mint.Types.error() | WebSocketError.t() | UpgradeFailureError.t()
@typedoc """
Shorthand notations for control frames
* `:ping` - shorthand for `{:ping, ""}`
* `:pong` - shorthand for `{:pong, ""}`
* `:close` - shorthand for `{:close, nil, nil}`
These may be passed to `encode/2`. Frames decoded with `decode/2` are always
in `t:frame/0` format.
"""
@type shorthand_frame :: :ping | :pong | :close
@typedoc """
A WebSocket frame
* `{:binary, binary}` - a frame containing binary data. Binary frames
can be used to send arbitrary binary data such as a PDF.
* `{:text, text}` - a frame containing string data. Text frames must be
valid utf8. Elixir has wonderful support for utf8: `String.valid?/1`
can detect valid and invalid utf8.
* `{:ping, binary}` - a control frame which the server should respond to
with a pong. The binary data must be echoed in the pong response.
* `{:pong, binary}` - a control frame which forms a reply to a ping frame.
Pings and pongs may be used to check the a connection is alive or to
estimate latency.
* `{:close, code, reason}` - a control frame used to request that a connection
be closed or to acknowledgee a close frame send by the server.
These may be passed to `encode/2` or returned from `decode/2`.
## Close frames
In order to close a WebSocket connection gracefully, either the client or
server sends a close frame. Then the other endpoint responds with a
close with code `1_000` and then closes the TCP connection. This can be
accomplished in Mint.WebSocket like so:
```elixir
{:ok, websocket, data} = Mint.WebSocket.encode(websocket, :close)
{:ok, conn} = Mint.WebSocket.stream_request_body(conn, ref, data)
close_response = receive(do: (message -> message))
{:ok, conn, [{:data, ^ref, data}]} = Mint.WebSocket.stream(conn, close_response)
{:ok, websocket, [{:close, 1_000, ""}]} = Mint.WebSocket.decode(websocket, data)
Mint.HTTP.close(conn)
```
[rfc6455
section 7.4.1](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1)
documents codes which may be used in the `code` element.
"""
@type frame ::
{:text, String.t()}
| {:binary, binary()}
| {:ping, binary()}
| {:pong, binary()}
| {:close, code :: non_neg_integer() | nil, reason :: binary() | nil}
@doc """
Requests that a connection be upgraded to the WebSocket protocol
This function wraps `Mint.HTTP.request/5` to provide a single interface
for bootstrapping an upgrade for HTTP/1 and HTTP/2 connections.
For HTTP/1 connections, this function performs a GET request with
WebSocket-specific headers. For HTTP/2 connections, this function performs
an extended CONNECT request which opens a stream to be used for the WebSocket
connection.
The `scheme` argument should be either `:ws` or `:wss`, using `:ws` for
connections established by passing `:http` to `Mint.HTTP.connect/4` and
`:wss` corresponding to `:https`.
## Options
* `:extensions` - a list of extensions to negotiate. See the extensions
section below.
## Extensions
Extensions should be declared by passing the `:extensions` option in the
`opts` keyword list. Note that in the WebSocket protocol, extensions are
negotiated: the client proposes a list of extensions and the server may
accept any (or none) of them. See `Mint.WebSocket.Extension` for more
information about extension negotiation.
Extensions may be passed as a list of `Mint.WebSocket.Extension` structs
or with the following shorthand notations:
* `module` - shorthand for `{module, []}`
* `{module, params}` - shorthand for `{module, params, []}`
* `{module, params, opts}` - a shorthand which is expanded to a
`Mint.WebSocket.Extension` struct
## Examples
```elixir
{:ok, conn} = Mint.HTTP.connect(:http, "localhost", 9_000)
{:ok, conn, ref} =
Mint.WebSocket.upgrade(:ws, conn, "/", [], extensions: [Mint.WebSocket.PerMessageDeflate])
# or provide params:
{:ok, conn, ref} =
Mint.WebSocket.upgrade(
:ws,
conn,
"/",
[],
extensions: [{Mint.WebSocket.PerMessageDeflate, [:client_max_window_bits]]}]
)
```
"""
@spec upgrade(
scheme :: :ws | :wss,
conn :: Mint.HTTP.t(),
path :: String.t(),
headers :: Mint.Types.headers(),
opts :: Keyword.t()
) :: {:ok, Mint.HTTP.t(), Mint.Types.request_ref()} | {:error, Mint.HTTP.t(), error()}
def upgrade(scheme, conn, path, headers, opts \\ []) when scheme in ~w[ws wss]a do
conn = put_private(conn, :scheme, scheme)
do_upgrade(scheme, Mint.HTTP.protocol(conn), conn, path, headers, opts)
end
defp do_upgrade(_scheme, :http1, conn, path, headers, opts) do
nonce = Utils.random_nonce()
extensions = get_extensions(opts)
conn =
conn
|> put_private(:sec_websocket_key, nonce)
|> put_private(:extensions, extensions)
headers = Utils.headers({:http1, nonce}, extensions) ++ headers
Mint.HTTP1.request(conn, "GET", path, headers, nil)
end
defp do_upgrade(scheme, :http2, conn, path, headers, opts) do
if HTTP2.get_server_setting(conn, :enable_connect_protocol) == true do
extensions = get_extensions(opts)
conn = put_private(conn, :extensions, extensions)
headers =
[
{":scheme", if(scheme == :ws, do: "http", else: "https")},
{":path", path},
{":protocol", "websocket"}
| headers
] ++ Utils.headers(:http2, extensions)
Mint.HTTP2.request(conn, "CONNECT", path, headers, :stream)
else
{:error, conn, %WebSocketError{reason: :extended_connect_disabled}}
end
end
@doc """
Creates a new WebSocket data structure given the server's reply to the
upgrade request
This function will setup any extensions accepted by the server using
the `c:Mint.WebSocket.Extension.init/2` callback.
## Options
* `:mode` - (default: `:active`) either `:active` or `:passive`. This
corresponds to the same option in `Mint.HTTP.connect/4`.
## Examples
```elixir
http_reply = receive(do: (message -> message))
{:ok, conn, [{:status, ^ref, status}, {:headers, ^ref, headers}, {:done, ^ref}]} =
Mint.WebSocket.stream(conn, http_reply)
{:ok, conn, websocket} =
Mint.WebSocket.new(:ws, conn, ref, status, resp_headers)
```
"""
@spec new(
Mint.HTTP.t(),
reference(),
Mint.Types.status(),
Mint.Types.headers()
) ::
{:ok, Mint.HTTP.t(), t()} | {:error, Mint.HTTP.t(), error()}
def new(conn, request_ref, status, response_headers, opts \\ []) do
websockets = [request_ref | get_private(conn, :websockets) || []]
conn =
conn
|> put_private(:websockets, websockets)
|> put_private(:mode, Keyword.get(opts, :mode, :active))
do_new(protocol(conn), conn, status, response_headers)
end
defp do_new(:http1, conn, status, headers) when status != 101 do
error = %UpgradeFailureError{status_code: status, headers: headers}
{:error, conn, error}
end
defp do_new(:http1, conn, _status, response_headers) do
with :ok <- Utils.check_accept_nonce(get_private(conn, :sec_websocket_key), response_headers),
{:ok, extensions} <-
Extension.accept_extensions(get_private(conn, :extensions), response_headers) do
{:ok, conn, %__MODULE__{extensions: extensions}}
else
{:error, reason} -> {:error, conn, reason}
end
end
defp do_new(:http2, conn, status, response_headers)
when status in 200..299 do
with {:ok, extensions} <-
Extension.accept_extensions(get_private(conn, :extensions), response_headers) do
{:ok, conn, %__MODULE__{extensions: extensions}}
end
end
defp do_new(:http2, conn, status, headers) do
error = %UpgradeFailureError{status_code: status, headers: headers}
{:error, conn, error}
end
@doc """
A wrapper around `Mint.HTTP.stream/2` for streaming HTTP and WebSocket
messages
This function does not decode WebSocket frames. Instead, once a WebSocket
connection has been established, decode any `{:data, request_ref, data}`
frames with `decode/2`.
This function is a drop-in replacement for `Mint.HTTP.stream/2` which
enables streaming WebSocket data after the bootstrapping HTTP/1 connection
has concluded. It decodes both WebSocket and regular HTTP messages.
## Examples
message = receive(do: (message -> message))
{:ok, conn, [{:data, ^websocket_ref, data}]} =
Mint.WebSocket.stream(conn, message)
{:ok, websocket, [{:text, "hello world!"}]} =
Mint.WebSocket.decode(websocket, data)
"""
@spec stream(Mint.HTTP.t(), term()) ::
{:ok, Mint.HTTP.t(), [Mint.Types.response()]}
| {:error, Mint.HTTP.t(), Mint.Types.error(), [Mint.Types.response()]}
| :unknown
def stream(conn, message) do
with :http1 <- protocol(conn),
# HTTP/1 only allows one WebSocket per connection
[request_ref] <- get_private(conn, :websockets) do
stream_http1(conn, request_ref, message)
else
_ -> Mint.HTTP.stream(conn, message)
end
end
# we take manual control of the :gen_tcp and :ssl messages in HTTP/1 because
# we have taken over the transport
defp stream_http1(conn, request_ref, message) do
socket = HTTP1.get_socket(conn)
tag = if get_private(conn, :scheme) == :ws, do: :tcp, else: :ssl
case message do
{^tag, ^socket, data} ->
reset_mode(conn, [{:data, request_ref, data}])
_ ->
HTTP1.stream(conn, message)
end
end
defp reset_mode(conn, responses) do
module = if get_private(conn, :scheme) == :ws, do: :inet, else: :ssl
with :active <- get_private(conn, :mode),
{:error, reason} <- module.setopts(HTTP1.get_socket(conn), active: :once) do
{:error, conn, %Mint.TransportError{reason: reason}, responses}
else
_ -> {:ok, conn, responses}
end
end
@doc """
Receives data from the socket
This function is used instead of `stream/2` when the connection is
in `:passive` mode. You must pass the `mode: :passive` option to
`new/5` in order to use `recv/3`.
This function wraps `Mint.HTTP.recv/3`. See the `Mint.HTTP.recv/3`
documentation for more information.
## Examples
{:ok, conn, [{:data, ^ref, data}]} = Mint.WebSocket.recv(conn, 0, 5_000)
{:ok, websocket, [{:text, "hello world!"}]} =
Mint.WebSocket.decode(websocket, data)
"""
@spec recv(Mint.HTTP.t(), non_neg_integer(), timeout()) ::
{:ok, Mint.HTTP.t(), [Mint.Types.response()]}
| {:error, t(), Mint.Types.error(), [Mint.Types.response()]}
def recv(conn, byte_count, timeout) do
with :http1 <- protocol(conn),
[request_ref] <- get_private(conn, :websockets) do
recv_http1(conn, request_ref, byte_count, timeout)
else
_ -> Mint.HTTP.recv(conn, byte_count, timeout)
end
end
defp recv_http1(conn, request_ref, byte_count, timeout) do
module = if get_private(conn, :scheme) == :ws, do: :gen_tcp, else: :ssl
socket = HTTP1.get_socket(conn)
case module.recv(socket, byte_count, timeout) do
{:ok, data} ->
{:ok, conn, [{:data, request_ref, data}]}
{:error, error} ->
{:error, conn, error, []}
end
end
@doc """
Streams chunks of data on the connection
`stream_request_body/3` should be used to send encoded data on an
established WebSocket connection that has already been upgraded with
`upgrade/5`.
This function is a wrapper around `Mint.HTTP.stream_request_body/3`. It
delegates to that function unless the `request_ref` belongs to an HTTP/1
WebSocket connection. When the request is an HTTP/1 WebSocket, this
function allows sending data on a request which Mint considers to be
closed, but is actually a valid WebSocket connection.
See the `Mint.HTTP.stream_request_body/3` documentation for more
information.
## Examples
{:ok, websocket, data} = Mint.WebSocket.encode(websocket, {:text, "hello world!"})
{:ok, conn} = Mint.WebSocket.stream_request_body(conn, websocket_ref, data)
"""
@spec stream_request_body(
Mint.HTTP.t(),
Mint.Types.request_ref(),
iodata() | :eof | {:eof, trailing_headers :: Mint.Types.headers()}
) :: {:ok, Mint.HTTP.t()} | {:error, Mint.HTTP.t(), error()}
def stream_request_body(conn, request_ref, data) do
with :http1 <- protocol(conn),
[^request_ref] <- get_private(conn, :websockets),
data when is_binary(data) or is_list(data) <- data do
stream_request_body_http1(conn, data)
else
_ -> Mint.HTTP.stream_request_body(conn, request_ref, data)
end
end
defp stream_request_body_http1(conn, data) do
transport = if get_private(conn, :scheme) == :ws, do: :gen_tcp, else: :ssl
case transport.send(Mint.HTTP1.get_socket(conn), data) do
:ok -> {:ok, conn}
{:error, reason} -> {:error, conn, %Mint.TransportError{reason: reason}}
end
end
@doc """
Encodes a frame into a binary
The resulting binary may be sent with `stream_request_body/3`.
This function will invoke the `c:Mint.WebSocket.Extension.encode/2` callback
for any accepted extensions.
## Examples
```elixir
{:ok, websocket, data} = Mint.WebSocket.encode(websocket, {:text, "hello world"})
{:ok, conn} = Mint.WebSocket.stream_request_body(conn, websocket_ref, data)
```
"""
@spec encode(t(), shorthand_frame() | frame()) :: {:ok, t(), binary()} | {:error, t(), any()}
defdelegate encode(websocket, frame), to: Frame
@doc """
Decodes a binary into a list of frames
The binary may received from the connection with `Mint.HTTP.stream/2`.
This function will invoke the `c:Mint.WebSocket.Extension.decode/2` callback
for any accepted extensions.
## Examples
```elixir
message = receive(do: (message -> message))
{:ok, conn, [{:data, ^ref, data}]} = Mint.HTTP.stream(conn, message)
{:ok, websocket, frames} = Mint.WebSocket.decode(websocket, data)
```
"""
@spec decode(t(), data :: binary()) ::
{:ok, t(), [frame() | {:error, term()}]} | {:error, t(), any()}
defdelegate decode(websocket, data), to: Frame
defp get_extensions(opts) do
opts
|> Keyword.get(:extensions, [])
|> Enum.map(fn
module when is_atom(module) ->
%Extension{module: module, name: module.name()}
{module, params} ->
%Extension{module: module, name: module.name(), params: normalize_params(params)}
{module, params, opts} ->
%Extension{
module: module,
name: module.name(),
params: normalize_params(params),
opts: opts
}
%Extension{} = extension ->
update_in(extension.params, &normalize_params/1)
end)
end
defp normalize_params(params) do
params
|> Enum.map(fn
{_key, false} -> nil
{key, value} -> {to_string(key), to_string(value)}
key -> {to_string(key), "true"}
end)
|> Enum.reject(&is_nil/1)
end
end
| 34.565744 | 98 | 0.662145 |
7912dbe4f7501bc701adad953cdc27e27b4c47ae | 584 | ex | Elixir | elixir/day3/states/lib/video_store.ex | hemslo/seven-in-seven | 5c772abf8e0887675e56a9478be663807c79c3a8 | [
"MIT"
] | null | null | null | elixir/day3/states/lib/video_store.ex | hemslo/seven-in-seven | 5c772abf8e0887675e56a9478be663807c79c3a8 | [
"MIT"
] | null | null | null | elixir/day3/states/lib/video_store.ex | hemslo/seven-in-seven | 5c772abf8e0887675e56a9478be663807c79c3a8 | [
"MIT"
] | null | null | null | defmodule VideoStore do
def renting(video) do
vid = log video, "Renting #{video.title}"
%{vid | times_rented: (video.times_rented + 1)}
end
def returning(video), do: log( video, "Returning #{video.title}" )
def losing(video), do: log( video, "Losing #{video.title}" )
def finding(video), do: log( video, "Finding #{video.title}" )
def before_rent(video), do: log( video, "Before renting #{video.title}" )
def after_rent(video), do: log( video, "After renting #{video.title}" )
def log(video, message) do
%{video | log: [message|video.log]}
end
end
| 27.809524 | 75 | 0.652397 |
7912ece6d4089bf550d8a6d0f60d80489256825a | 1,373 | exs | Elixir | mix.exs | aditya7iyengar/bamboohr_api | e45a54e32cc6231b12de2bb42cd6569fcb7d4858 | [
"MIT"
] | null | null | null | mix.exs | aditya7iyengar/bamboohr_api | e45a54e32cc6231b12de2bb42cd6569fcb7d4858 | [
"MIT"
] | null | null | null | mix.exs | aditya7iyengar/bamboohr_api | e45a54e32cc6231b12de2bb42cd6569fcb7d4858 | [
"MIT"
] | null | null | null | defmodule BamboohrApi.MixProject do
use Mix.Project
@version "0.0.1"
@source "https://github.com/aditya7iyengar/bamboohr_api"
@description """
An Elixir wrapper around the BambooHR REST API
"""
def project do
[
app: :bamboohr_api,
description: @description,
deps: deps(),
docs: [
# The main page in the docs
main: "BamboohrApi",
extras: ["README.md"]
],
elixir: "~> 1.10",
homepage_url: @source,
name: "BambooHR API",
package: package(),
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
],
source_url: @source,
start_permanent: Mix.env() == :prod,
test_coverage: [tool: ExCoveralls],
version: @version
]
end
def application do
[
extra_applications: [:logger]
]
end
def package do
[
files: ["lib", "mix.exs", "README.md"],
maintainers: ["Adi Iyengar"],
licenses: ["MIT"],
links: %{"Github" => @source}
]
end
defp deps do
[
{:excoveralls, "~> 0.13.2", only: :test},
{:exvcr, "~> 0.11.2", only: :test},
{:ex_doc, "~> 0.22.6", only: :dev, runtime: false},
{:hackney, "~> 1.16.0"},
{:jason, "~> 1.2.2"},
{:tesla, "~> 1.3.3"}
]
end
end
| 21.793651 | 58 | 0.529497 |