{"size":7444,"ext":"ex","lang":"Elixir","max_stars_count":12.0,"content":"#\n# This file is part of Astarte.\n#\n# Copyright 2017 Ispirata Srl\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\ndefmodule Astarte.VMQ.Plugin do\n @moduledoc \"\"\"\n Documentation for Astarte.VMQ.Plugin.\n \"\"\"\n\n alias Astarte.VMQ.Plugin.Config\n alias Astarte.VMQ.Plugin.AMQPClient\n\n @max_rand trunc(:math.pow(2, 32) - 1)\n\n def auth_on_register(_peer, _subscriber_id, :undefined, _password, _cleansession) do\n # If it doesn't have a username we let someone else decide\n :next\n end\n\n def auth_on_register(_peer, {mountpoint, _client_id}, username, _password, _cleansession) do\n if !String.contains?(username, \"\/\") do\n # Not a device, let someone else decide\n :next\n else\n subscriber_id = {mountpoint, username}\n # TODO: we probably want some of these values to be configurable in some way\n {:ok,\n [\n subscriber_id: subscriber_id,\n max_inflight_messages: 100,\n max_message_rate: 10000,\n max_message_size: 65535,\n retry_interval: 20000,\n upgrade_qos: false\n ]}\n end\n end\n\n def auth_on_publish(\n _username,\n {_mountpoint, client_id},\n _qos,\n topic_tokens,\n _payload,\n _isretain\n ) do\n cond do\n # Not a device, let someone else decide\n !String.contains?(client_id, \"\/\") ->\n :next\n\n # Device auth\n String.split(client_id, \"\/\") == Enum.take(topic_tokens, 2) ->\n :ok\n\n true ->\n {:error, :unauthorized}\n end\n end\n\n def auth_on_subscribe(_username, {_mountpoint, client_id}, topics) do\n if !String.contains?(client_id, \"\/\") do\n # Not a device, let someone else decide\n :next\n else\n client_id_tokens = String.split(client_id, \"\/\")\n\n authorized_topics =\n Enum.filter(topics, fn {topic_tokens, _qos} ->\n client_id_tokens == Enum.take(topic_tokens, 2)\n end)\n\n case authorized_topics do\n [] -> {:error, :unauthorized}\n authorized_topics -> {:ok, authorized_topics}\n end\n end\n end\n\n def disconnect_client(client_id, discard_state) do\n opts =\n if discard_state do\n [:do_cleanup]\n else\n []\n end\n\n mountpoint = ''\n subscriber_id = {mountpoint, client_id}\n\n case :vernemq_dev_api.disconnect_by_subscriber_id(subscriber_id, opts) do\n :ok ->\n :ok\n\n :not_found ->\n {:error, :not_found}\n end\n end\n\n def on_client_gone({_mountpoint, client_id}) do\n publish_event(client_id, \"disconnection\", now_us_x10_timestamp())\n end\n\n def on_client_offline({_mountpoint, client_id}) do\n publish_event(client_id, \"disconnection\", now_us_x10_timestamp())\n end\n\n def on_register({ip_addr, _port}, {_mountpoint, client_id}, _username) do\n with [realm, device_id] <- String.split(client_id, \"\/\") do\n # Start the heartbeat\n setup_heartbeat_timer(realm, device_id, self())\n\n timestamp = now_us_x10_timestamp()\n\n ip_string =\n ip_addr\n |> :inet.ntoa()\n |> to_string()\n\n publish_event(client_id, \"connection\", timestamp, x_astarte_remote_ip: ip_string)\n else\n # Not a device, ignoring it\n _ ->\n :ok\n end\n end\n\n def on_publish(_username, {_mountpoint, client_id}, _qos, topic_tokens, payload, _isretain) do\n with [realm, device_id] <- String.split(client_id, \"\/\") do\n timestamp = now_us_x10_timestamp()\n\n case topic_tokens do\n [^realm, ^device_id] ->\n publish_introspection(realm, device_id, payload, timestamp)\n\n [^realm, ^device_id, \"control\" | control_path_tokens] ->\n control_path = \"\/\" <> Enum.join(control_path_tokens, \"\/\")\n publish_control_message(realm, device_id, control_path, payload, timestamp)\n\n [^realm, ^device_id, interface | path_tokens] ->\n path = \"\/\" <> Enum.join(path_tokens, \"\/\")\n publish_data(realm, device_id, interface, path, payload, timestamp)\n end\n else\n # Not a device, ignoring it\n _ ->\n :ok\n end\n end\n\n def handle_heartbeat(realm, device_id, session_pid) do\n if Process.alive?(session_pid) do\n publish_heartbeat(realm, device_id)\n\n setup_heartbeat_timer(realm, device_id, session_pid)\n else\n # The session is not alive anymore, just stop\n :ok\n end\n end\n\n defp setup_heartbeat_timer(realm, device_id, session_pid) do\n args = [realm, device_id, session_pid]\n interval = Config.device_heartbeat_interval_ms() |> randomize_interval(0.25)\n {:ok, _timer} = :timer.apply_after(interval, __MODULE__, :handle_heartbeat, args)\n\n :ok\n end\n\n defp randomize_interval(interval, tolerance) do\n multiplier = 1 + (tolerance * 2 * :random.uniform() - tolerance)\n\n (interval * multiplier)\n |> Float.round()\n |> trunc()\n end\n\n defp publish_introspection(realm, device_id, payload, timestamp) do\n publish(realm, device_id, payload, \"introspection\", timestamp)\n end\n\n defp publish_data(realm, device_id, interface, path, payload, timestamp) do\n additional_headers = [x_astarte_interface: interface, x_astarte_path: path]\n\n publish(realm, device_id, payload, \"data\", timestamp, additional_headers)\n end\n\n defp publish_control_message(realm, device_id, control_path, payload, timestamp) do\n additional_headers = [x_astarte_control_path: control_path]\n\n publish(realm, device_id, payload, \"control\", timestamp, additional_headers)\n end\n\n defp publish_event(client_id, event_string, timestamp, additional_headers \\\\ []) do\n with [realm, device_id] <- String.split(client_id, \"\/\") do\n publish(realm, device_id, \"\", event_string, timestamp, additional_headers)\n else\n # Not a device, ignoring it\n _ ->\n :ok\n end\n end\n\n defp publish_heartbeat(realm, device_id) do\n timestamp = now_us_x10_timestamp()\n\n publish(realm, device_id, \"\", \"heartbeat\", timestamp)\n end\n\n defp publish(realm, device_id, payload, event_string, timestamp, additional_headers \\\\ []) do\n headers =\n [\n x_astarte_vmqamqp_proto_ver: 1,\n x_astarte_realm: realm,\n x_astarte_device_id: device_id,\n x_astarte_msg_type: event_string\n ] ++ additional_headers\n\n message_id = generate_message_id(realm, device_id, timestamp)\n sharding_key = {realm, device_id}\n\n :ok =\n AMQPClient.publish(payload,\n headers: headers,\n message_id: message_id,\n timestamp: timestamp,\n sharding_key: sharding_key\n )\n end\n\n defp now_us_x10_timestamp do\n DateTime.utc_now()\n |> DateTime.to_unix(:microsecond)\n |> Kernel.*(10)\n end\n\n defp generate_message_id(realm, device_id, timestamp) do\n realm_trunc = String.slice(realm, 0..63)\n device_id_trunc = String.slice(device_id, 0..15)\n timestamp_hex_str = Integer.to_string(timestamp, 16)\n rnd = Enum.random(0..@max_rand) |> Integer.to_string(16)\n\n \"#{realm_trunc}-#{device_id_trunc}-#{timestamp_hex_str}-#{rnd}\"\n end\nend\n","avg_line_length":28.6307692308,"max_line_length":96,"alphanum_fraction":0.6656367544} {"size":1155,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"# This file is responsible for configuring your application\n# and its dependencies with the aid of the Mix.Config module.\nuse Mix.Config\n\n# This configuration is loaded before any dependency and is restricted\n# to this project. If another project depends on this project, this\n# file won't be loaded nor affect the parent project. For this reason,\n# if you want to provide default values for your application for\n# 3rd-party users, it should be done in your \"mix.exs\" file.\n\n# You can configure your application as:\n#\n# config :db_administration_tool, key: :value\n#\n# and access this configuration in your application as:\n#\n# Application.get_env(:db_administration_tool, :key)\n#\n# You can also configure a 3rd-party app:\n#\n# config :logger, level: :info\n#\n\n# It is also possible to import configuration files, relative to this\n# directory. For example, you can emulate configuration per environment\n# by uncommenting the line below and defining dev.exs, test.exs and such.\n# Configuration from the imported file will override the ones defined\n# here (which is why it is important to import them last).\n#\n# import_config \"#{Mix.env()}.exs\"\n","avg_line_length":37.2580645161,"max_line_length":73,"alphanum_fraction":0.7567099567} {"size":110,"ext":"ex","lang":"Elixir","max_stars_count":16.0,"content":"defmodule Default do\n def go(x \\\\ 42_000), do: x\n\n def gogo(a, x \\\\ 666_000, y \\\\ 1_000), do: a + x + y\nend\n","avg_line_length":18.3333333333,"max_line_length":54,"alphanum_fraction":0.5727272727} {"size":3698,"ext":"ex","lang":"Elixir","max_stars_count":8.0,"content":"defmodule Core.Validators.Reference do\n @moduledoc \"\"\"\n Validates reference existance\n \"\"\"\n\n alias Core.CapitationContractRequests\n alias Core.ContractRequests.CapitationContractRequest\n alias Core.ContractRequests.ReimbursementContractRequest\n alias Core.Divisions\n alias Core.Divisions.Division\n alias Core.Employees\n alias Core.Employees.Employee\n alias Core.LegalEntities\n alias Core.LegalEntities.LegalEntity\n alias Core.MedicalPrograms\n alias Core.MedicalPrograms.MedicalProgram\n alias Core.Medications\n alias Core.Medications.Medication\n alias Core.Persons\n alias Core.ReimbursementContractRequests\n alias Core.ValidationError\n alias Core.Validators.Error\n\n @ops_api Application.get_env(:core, :api_resolvers)[:ops]\n\n def validate(type, nil) do\n error(type)\n end\n\n def validate(type, id), do: validate(type, id, nil)\n\n def validate(:medication_request = type, id, path) do\n with {:ok, %{\"data\" => [medication_request]}} <- @ops_api.get_medication_requests(%{\"id\" => id}, []) do\n {:ok, medication_request}\n else\n _ -> error(type, path)\n end\n end\n\n def validate(:employee = type, id, path) do\n with %Employee{} = employee <- Employees.get_by_id(id) do\n {:ok, employee}\n else\n _ -> error(type, path)\n end\n end\n\n def validate(:division = type, id, path) do\n with %Division{} = division <- Divisions.get_by_id(id),\n {:status, true} <- {:status, division.status == Division.status(:active)} do\n {:ok, division}\n else\n {:status, _} -> error_status(type, path)\n _ -> error(type, path)\n end\n end\n\n def validate(:medical_program = type, id, path) do\n with %MedicalProgram{} = medical_program <- MedicalPrograms.get_by_id(id) do\n {:ok, medical_program}\n else\n _ -> error(type, path)\n end\n end\n\n def validate(:legal_entity = type, id, path) do\n with %LegalEntity{} = legal_entity <- LegalEntities.get_by_id(id),\n {:status, true} <-\n {:status, legal_entity.status in [LegalEntity.status(:active), LegalEntity.status(:suspended)]} do\n {:ok, legal_entity}\n else\n {:status, _} -> error_status(type, path)\n _ -> error(type, path)\n end\n end\n\n def validate(:person = type, id, path) do\n with {:ok, person} <- Persons.get_by_id(id) do\n {:ok, person}\n else\n _ -> error(type, path)\n end\n end\n\n def validate(:medication = type, id, path) do\n with %Medication{} = medication <- Medications.get_medication_by_id(id) do\n {:ok, medication}\n else\n _ -> error(type, path)\n end\n end\n\n # TODO: rename everywhere\n def validate(:contract_request = type, id, path) do\n with %CapitationContractRequest{} = contract_request <- CapitationContractRequests.get_by_id(id) do\n {:ok, contract_request}\n else\n _ -> error(type, path)\n end\n end\n\n def validate(:reimbursement_contract_request = type, id, path) do\n with %ReimbursementContractRequest{} = contract_request <- ReimbursementContractRequests.get_by_id(id) do\n {:ok, contract_request}\n else\n _ -> error(type, path)\n end\n end\n\n defp error(type, path \\\\ nil) when is_atom(type) do\n description =\n type\n |> to_string()\n |> String.capitalize()\n |> String.replace(\"_\", \" \")\n\n path = path || \"$.#{type}_id\"\n Error.dump(%ValidationError{description: \"#{description} not found\", path: path})\n end\n\n defp error_status(type, path) when is_atom(type) do\n description =\n type\n |> to_string()\n |> String.capitalize()\n |> String.replace(\"_\", \" \")\n\n path = path || \"$.#{type}_id\"\n Error.dump(%ValidationError{description: \"#{description} is not active\", path: path})\n end\nend\n","avg_line_length":28.0151515152,"max_line_length":109,"alphanum_fraction":0.6595457004} {"size":278,"ext":"ex","lang":"Elixir","max_stars_count":null,"content":"defmodule Jeff.Reply.KeypadData do\n @moduledoc \"\"\"\n Keypad Data Report\n\n OSDP v2.2 Specification Reference: 7.12\n \"\"\"\n\n defstruct [:reader, :count, :keys]\n\n def decode(<>) do\n %__MODULE__{reader: reader, count: count, keys: keys}\n end\nend\n","avg_line_length":19.8571428571,"max_line_length":57,"alphanum_fraction":0.6798561151} {"size":1292,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"Logger.configure_backend(:console, colors: [enabled: false])\nExUnit.start(trace: \"--trace\" in System.argv())\n\n# Beam files compiled on demand\npath = Path.expand(\"..\/tmp\/beams\", __DIR__)\nFile.rm_rf!(path)\nFile.mkdir_p!(path)\nCode.prepend_path(path)\n\ndefmodule CabbageTestHelper do\n import ExUnit.CaptureIO\n\n def run(filters \\\\ [], cases \\\\ [])\n\n def run(filters, module) do\n {add_module, load_module, result_fix} = versioned_callbacks()\n\n Enum.each(module, add_module)\n load_module.()\n\n opts =\n ExUnit.configuration()\n |> Keyword.merge(filters)\n |> Keyword.merge(colors: [enabled: false])\n\n output = capture_io(fn -> Process.put(:capture_result, ExUnit.Runner.run(opts, nil)) end)\n {result_fix.(Process.get(:capture_result)), output}\n end\n\n defp versioned_callbacks() do\n System.version()\n |> Version.compare(\"1.6.0\")\n |> case do\n :lt -> {&ExUnit.Server.add_sync_case\/1, &ExUnit.Server.cases_loaded\/0, &fix_13_elixir_test_result\/1}\n _ -> {&ExUnit.Server.add_sync_module\/1, &ExUnit.Server.modules_loaded\/0, &fix_17_elixir_test_result\/1}\n end\n end\n\n defp fix_17_elixir_test_result(result), do: result\n\n defp fix_13_elixir_test_result(result) do\n Map.merge(result, %{excluded: Map.get(result, :skipped, 0), skipped: 0})\n end\nend\n","avg_line_length":28.7111111111,"max_line_length":108,"alphanum_fraction":0.6981424149} {"size":251,"ext":"exs","lang":"Elixir","max_stars_count":4.0,"content":"Code.require_file \"test_helper.exs\", __DIR__\n\ndefmodule MixTest do\n use MixTest.Case\n\n test :shell do\n assert Mix.shell == Mix.Shell.Process\n end\n\n test :env do\n assert Mix.env == :dev\n Mix.env(:prod)\n assert Mix.env == :prod\n end\nend","avg_line_length":16.7333333333,"max_line_length":44,"alphanum_fraction":0.6693227092} {"size":141,"ext":"exs","lang":"Elixir","max_stars_count":null,"content":"defmodule JorbDemoTest do\n use ExUnit.Case\n doctest JorbDemo\n\n test \"greets the world\" do\n assert JorbDemo.hello() == :world\n end\nend\n","avg_line_length":15.6666666667,"max_line_length":37,"alphanum_fraction":0.7163120567} {"size":1370,"ext":"ex","lang":"Elixir","max_stars_count":17.0,"content":"defmodule SurfaceBootstrap.Form.NumberInput do\n @moduledoc \"\"\"\n The number input element as defined here:\n - https:\/\/hexdocs.pm\/phoenix_html\/Phoenix.HTML.Form.html#number_input\/3\n - https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTML\/Element\/input\/number\n \"\"\"\n\n use Surface.Component\n use SurfaceBootstrap.Form.TextInputBase\n\n alias Surface.Components.Form.NumberInput\n\n @doc \"Largest number allowed, as enforced by client browser. Not validated by Elixir.\"\n prop max, :integer\n\n @doc \"Smallest number allowed, as enforced by client browser. Not validated by Elixir.\"\n prop min, :integer\n\n @doc \"A stepping interval to use when using up and down arrows to adjust the value, as well as for validation\"\n prop step, :integer\n\n def render(assigns) do\n ~F\"\"\"\n \n {raw(optional_div(assigns))}\n