code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
defmodule Statifier.Codec.YAML.Walker do @moduledoc """ Helper for walking a YAML document and dispatching events to a handler to process elements as they are found. See `:xmerl_sax_parser` for reference implementation this is emulating. """ @type element :: %{optional(String.t()) => any()} @typedoc """ The initital state passed to `event_fun` """ @type event_state :: any() @typedoc """ This function will be called with events everytime a new map or list is encountered while walking the document. It is expected to return the `event_state` for the next event. """ @type event_fun :: function() @type event :: {:start_element, list_or_map_name :: String.t(), attributes :: element()} | {:end_element, list_or_map_name :: String.t()} @type walker_opts :: [event_state: event_state(), event_fun: function()] @spec walk(String.t(), walker_opts()) :: {:ok, any()} | {:error, any()} @doc """ Takes yaml string and starts processing it by calling `event_fun` defined in `opts` with each start and end of processing maps or lists. """ def walk(yaml, opts) do initial_state = Keyword.get(opts, :event_state, nil) processor = Keyword.get(opts, :event_fun) {:ok, do_walk(yaml, {processor, initial_state})} end defp do_walk(yaml, {processor, state}) when is_map(yaml) do Enum.reduce( yaml, state, fn # New map we are seeing {key, map}, state when is_map(map) -> # starting element state = processor.({:start_element, key, map}, state) # Walk it recursively state = do_walk(map, {processor, state}) # Done walking element processor.({:end_element, key}, state) # new list of possible elements {key, list}, state when is_list(list) -> Enum.reduce(list, state, fn element, state -> # Starting processing list state = processor.({:start_element, key, element}, state) # Walk it recursively state = do_walk(element, {processor, state}) # Done walking element processor.({:end_element, key}, state) end) {_key, _non_list_or_map}, state -> state end ) end end
impl/ex/lib/codec/yaml/walker.ex
0.822581
0.550426
walker.ex
starcoder
defmodule Jan.Registry do @moduledoc """ This module is responsible for storing and retrieving a process for a given room. We have a process for each room, and use the room id to identify them. When a new room is created, we add a new entry in this `Map`, using the room id as the key and the pid as a value. """ use GenServer import Kernel, except: [send: 2] # API def start_link do GenServer.start_link(__MODULE__, nil, name: :process_registry) end def whereis_name(room_id) do GenServer.call(:process_registry, {:whereis_name, room_id}) end def register_name(room_id, pid) do GenServer.call(:process_registry, {:register_name, room_id, pid}) end def unregister_name(room_id) do GenServer.cast(:process_registry, {:unregister_name, room_id}) end def send(room_id, message) do case whereis_name(room_id) do :undefined -> {:badarg, {room_id, message}} pid -> Kernel.send(pid, message) pid end end def registered_rooms do rooms = GenServer.call(:process_registry, :registered_rooms) keys = Map.keys(rooms) Keyword.get_values(keys, :game_server) end # SERVER def init(_) do {:ok, Map.new} end def handle_call({:whereis_name, room_id}, _from, state) do {:reply, Map.get(state, room_id, :undefined), state} end def handle_call({:register_name, room_id, pid}, _from, state) do case Map.get(state, room_id) do nil -> Process.monitor(pid) {:reply, :yes, Map.put(state, room_id, pid)} _ -> {:reply, :no, state} end end def handle_info({:DOWN, _, :process, pid, _}, state) do new_state = deregister_pid(state, pid) {:noreply, new_state} end def handle_call(:registered_rooms, _from, state) do {:reply, state, state} end def handle_cast({:unregister_name, room_id}, state) do {:noreply, Map.delete(state, room_id)} end defp deregister_pid(state, pid) do Enum.reduce( state, state, fn ({registered_alias, registered_process}, registry_acc) when registered_process == pid -> Map.delete(registry_acc, registered_alias) (_, registry_acc) -> registry_acc end ) end end
lib/jan/registry.ex
0.663669
0.442155
registry.ex
starcoder
defmodule OptionEx do @moduledoc """ OptionEx is a module for handling functions returning a `t:OptionEx.t/0`. This module is inspired by the f# Option module, and [Railway Oriented Programming](https://fsharpforfunandprofit.com/rop/) as explained by <NAME>. This module is intended to make working with `nil` values more safe and convenient. For splitting tracks based on ok or error return values see [ResultEx](https://hexdocs.pm/result_ex/ResultEx.html#content). The Option type consists of either a {:some, term} where the term represents a value, or the :none atom representing the lack of a value. By replacing optional nil values with an `t:OptionEx.t/0`, it is no longer needed to match nil value cases. By using `OptionEx.map/2` or `OptionEx.bind/2` the function passed as second argument will only be executed when a value is present. By using `OptionEx.or_else/2` or `OptionEx.or_else_with/2` it is possible to add a default value, or behaviour to be executed only in case there is no value. ## Examples iex> find_by_id = fn ...> 1 -> nil ...> x -> %{id: x} ...> end ...> ...> find_by_id.(2) ...> |> OptionEx.return() {:some, %{id: 2}} ...> ...> find_by_id.(1) ...> |> OptionEx.return() :none ...> ...> find_by_id.(2) ...> |> OptionEx.return() ...> |> OptionEx.map(fn record -> record.id end) ...> |> OptionEx.map(&(&1 + 1)) ...> |> OptionEx.bind(find_by_id) {:some, %{id: 3}} ...> ...> find_by_id.(1) ...> |> OptionEx.return() ...> |> OptionEx.map(fn record -> record.id end) ...> |> OptionEx.map(&(&1 + 1)) ...> |> OptionEx.bind(find_by_id) :none ...> ...> find_by_id.(2) ...> |> OptionEx.return() ...> |> OptionEx.or_else_with(fn -> find_by_id.(0) end) %{id: 2} ...> ...> find_by_id.(1) ...> |> OptionEx.return() ...> |> OptionEx.or_else_with(fn -> find_by_id.(0) end) %{id: 0} """ @typedoc """ Data structure representing an Option. When the Option is containing a value, the value is wrapped in a tuple with the atom :some as its first element. When the Option is empty, it is represented as the single atom :none. """ @type t :: {:some, term} | :none @doc """ Elevates a value to an `t:OptionEx.t/0` type. If nil is passed, an empty `t:OptionEx.t/0` will be returned. ## Examples iex> OptionEx.return(1) {:some, 1} iex> OptionEx.return(nil) :none """ @spec return(term) :: t def return(nil), do: :none def return(value), do: {:some, value} @doc """ Runs a function against the `t:OptionEx.t/0` value. ## Examples iex> option = {:some, 1} ...> OptionEx.map(option, &(&1 + 1)) {:some, 2} iex> option = :none ...> OptionEx.map(option, &(&1 + 1)) :none """ @spec map(t, (term -> term)) :: t def map({:some, value}, fun) do {:some, fun.(value)} end def map(:none, _), do: :none @doc """ Partially applies `OptionEx.map/2` with the passed function. """ @spec map((term -> term)) :: (t -> t) def map(fun) do fn option -> map(option, fun) end end @doc """ Executes or partially executes the function given as value of the first `t:OptionEx.t/0`, and applies it with the value of the second `t:OptionEx.t/0`. If the function has an arity greater than 1, the returned `t:OptionEx.t/0` value will be the function partially applied. (The function name is 'appl' rather than 'apply' to prevent import conflicts with 'Kernel.apply') ## Examples iex> value_option = {:some, 1} ...> function_option = {:some, fn value -> value + 1 end} ...> OptionEx.appl(function_option, value_option) {:some, 2} iex> {:some, fn value1, value2, value3 -> value1 + value2 + value3 end} ...> |> OptionEx.appl({:some, 1}) ...> |> OptionEx.appl({:some, 2}) ...> |> OptionEx.appl({:some, 3}) {:some, 6} iex> :none ...> |> OptionEx.appl({:some, 1}) ...> |> OptionEx.appl({:some, 1}) ...> |> OptionEx.appl({:some, 1}) :none iex> {:some, fn value1, value2, value3 -> value1 + value2 + value3 end} ...> |> OptionEx.appl({:some, 1}) ...> |> OptionEx.appl({:some, 1}) ...> |> OptionEx.appl(:none) :none """ @spec appl(t, t) :: t def appl({:some, fun}, {:some, value}) do case :erlang.fun_info(fun, :arity) do {_, 0} -> :none _ -> {:some, curry(fun, value)} end end def appl(:none, _), do: :none def appl(_, :none), do: :none @doc """ Applies a function with the value of the `t:OptionEx.t/0`. The passed function is expected to return an `t:OptionEx.t/0`. This can be useful for chaining functions that elevate values into options together. ## Examples iex> head = fn ...> [] -> :none ...> list -> {:some, hd(list)} ...> end ...> head.([[4]]) ...> |> OptionEx.bind(head) {:some, 4} iex> head = fn ...> [] -> :none ...> list -> {:some, hd(list)} ...> end ...> head.([[]]) ...> |> OptionEx.bind(head) :none """ @spec bind(t, (term -> t)) :: t def bind({:some, value}, fun) do fun.(value) end def bind(:none, _), do: :none @doc """ Partially applies `OptionEx.bind/2` with the passed function. """ @spec bind((term -> t)) :: (t -> t) def bind(fun) do fn option -> bind(option, fun) end end @doc """ Unwraps the `t:OptionEx.t/0` to return its value. Throws an error if the `t:OptionEx.t/0` is :none. ## Examples iex> OptionEx.return(5) ...> |> OptionEx.unwrap!() 5 """ @spec unwrap!(t) :: term def unwrap!({:some, value}), do: value def unwrap!(:none), do: throw("OptionEx.unwrap!: The option has no value") @doc """ Unwraps the `t:OptionEx.t/0` to return its value. The second argument will be a specific error message to throw when the `t:OptionEx.t/0` is empty. ## Examples iex> OptionEx.return(5) ...> |> OptionEx.expect!("The value was not what was expected") 5 """ @spec expect!(t, String.t()) :: term def expect!({:some, value}, _), do: value def expect!(_, message), do: throw(message) @doc """ Unwraps the `t:OptionEx.t/0` to return its value. If the `t:OptionEx.t/0` is empty, it will return the default value passed as second argument instead. ## Examples iex> OptionEx.return(5) ...> |> OptionEx.or_else(4) 5 iex> :none ...> |> OptionEx.or_else(4) 4 """ @spec or_else(t, term) :: term def or_else({:some, value}, _), do: value def or_else(_, default), do: default @doc """ Unwraps the `t:OptionEx.t/0` to return its value. If the `t:OptionEx.t/0` is empty, the given function will be applied instead. ## Examples iex> OptionEx.return(5) ...> |> OptionEx.or_else_with(fn -> 4 end) 5 iex> :none ...> |> OptionEx.or_else_with(fn -> 4 end) 4 """ @spec or_else_with(t, (() -> term)) :: term def or_else_with({:some, value}, _), do: value def or_else_with(:none, fun), do: fun.() @doc """ Attempts to generate a different option wrapped value by executing the function passed, if the `t:OptionEx.t/0` is empty. If the original `t:OptionEx.t/0` contains a value, the `t:OptionEx.t/0` is returned without unwrapping the value. The passed function is expected to return a `t:OptionEx.t/0`. ## Examples iex> attempt_to_get_data = fn -> :none end ...> successfully_get_data = fn -> {:some, :data} end ...> ...> attempt_to_get_data.() ...> |> OptionEx.or_try(attempt_to_get_data) ...> |> OptionEx.or_try(successfully_get_data) ...> |> OptionEx.or_try(attempt_to_get_data) {:some, :data} """ @spec or_try(t, (() -> t)) :: t def or_try({:some, value}, _), do: {:some, value} def or_try(:none, fun), do: fun.() @doc """ Flatten nested `t:OptionEx.t/0`s into one `t:OptionEx.t/0`. ## Examples iex> OptionEx.return(5) ...> |> OptionEx.return() ...> |> OptionEx.return() ...> |> OptionEx.flatten() {:some, 5} iex> {:some, {:some, :none}} ...> |> OptionEx.flatten() :none """ @spec flatten(t) :: t def flatten({:some, {:some, _} = inner_result}) do flatten(inner_result) end def flatten({_, :none}), do: :none def flatten({:some, _} = result), do: result def flatten(:none), do: :none @doc """ Flattens an `t:Enum.t/0` of `t:OptionEx.t/0`s into an `t:OptionEx.t/0` of enumerables. ## Examples iex> [{:some, 1}, {:some, 2}, {:some, 3}] ...> |> OptionEx.flatten_enum() {:some, [1, 2, 3]} iex> [{:some, 1}, :none, {:some, 3}] ...> |> OptionEx.flatten_enum() :none iex> %{a: {:some, 1}, b: {:some, 2}, c: {:some, 3}} ...> |> OptionEx.flatten_enum() {:some, %{a: 1, b: 2, c: 3}} iex> %{a: {:some, 1}, b: :none, c: {:some, 3}} ...> |> OptionEx.flatten_enum() :none """ @spec flatten_enum(Enum.t()) :: t def flatten_enum(%{} = enum) do Enum.reduce(enum, {:some, %{}}, fn {key, {:some, value}}, {:some, result} -> Map.put(result, key, value) |> return _, :none -> :none {_, :none}, _ -> :none end) end def flatten_enum(enum) when is_list(enum) do Enum.reduce(enum, {:some, []}, fn {:some, value}, {:some, result} -> {:some, [value | result]} _, :none -> :none :none, _ -> :none end) |> map(&Enum.reverse/1) end def flatten_enum(_), do: :none @doc """ Filters an `t:Enum.t/0` from all :none values. ## Examples iex> [{:some, 1}, :none, {:some, 3}] ...> |> OptionEx.filter_enum() [{:some, 1}, {:some, 3}] iex> %{a: {:some, 1}, b: :none, c: {:some, 3}} ...> |> OptionEx.filter_enum() %{a: {:some, 1}, c: {:some, 3}} """ @spec filter_enum(Enum.t()) :: Enum.t() def filter_enum(%{} = enum) do Enum.reduce(enum, %{}, fn {key, {:some, _} = option}, result -> Map.put(result, key, option) _, result -> result end) end def filter_enum(enum) when is_list(enum) do Enum.filter(enum, &to_bool/1) end @doc """ Converts an `t:OptionEx.t/0` to a result type. ## Examples iex> OptionEx.to_result({:some, 5}) {:ok, 5} ...> OptionEx.to_result(:none) {:error, "OptionEx.to_result: The option was empty"} """ @spec to_result(t) :: {:ok, term} | {:error, String.t()} def to_result({:some, value}), do: {:ok, value} def to_result(:none), do: {:error, "OptionEx.to_result: The option was empty"} @doc """ Converts an `t:OptionEx.t/0` to a Result type, specifying the error reason in case the `t:OptionEx.t/0` is empty. The Result type consists of an {:ok, term} tuple, or an {:error, term} tuple. ## Examples iex> OptionEx.to_result({:some, 5}, :unexpected_empty_value) {:ok, 5} ...> OptionEx.to_result(:none, :unexpected_empty_value) {:error, :unexpected_empty_value} """ @spec to_result(t, term) :: {:ok, term} | {:error, term} def to_result({:some, value}, _), do: {:ok, value} def to_result(:none, reason), do: {:error, reason} @doc """ Converts an `t:OptionEx.t/0` to a bool, ignoring the inner value. ## Examples iex> OptionEx.to_bool({:some, 5}) true ...> OptionEx.to_bool(:none) false """ @spec to_bool(t) :: boolean def to_bool({:some, _}), do: true def to_bool(:none), do: false @doc """ Creates an `t:OptionEx.t/0` from a boolean, and the specified value. If the boolean is true, an option with the value is returned. If the boolean is false, :none is returned. ## Examples iex> OptionEx.from_bool(true, :unit) {:some, :unit} iex> OptionEx.from_bool(false, :unit) :none """ @spec from_bool(boolean, term) :: t def from_bool(true, value), do: {:some, value} def from_bool(false, _), do: :none @spec curry(fun, term) :: term defp curry(fun, arg1), do: apply_curry(fun, [arg1]) @spec apply_curry(fun, [term]) :: term defp apply_curry(fun, args) do {_, arity} = :erlang.fun_info(fun, :arity) if arity == length(args) do apply(fun, Enum.reverse(args)) else fn arg -> apply_curry(fun, [arg | args]) end end end end
lib/option_ex.ex
0.894637
0.610221
option_ex.ex
starcoder
defmodule Model.Alert do @moduledoc """ An `effect` on the provided service (`informed_entity`) described by a `banner`, `header`, and `description` that is active for one or more periods (`active_period`) caused by a `cause`. The alert has a `lifecycle` that can be read by humans in its `timeframe`. The overall alert can be read by huamns (`service_effect`). See [GTFS Realtime `FeedMessage` `FeedEntity` `Alert`](https://github.com/google/transit/blob/master/gtfs-realtime/spec/en/reference.md#message-alert) """ use Recordable, [ :id, :effect, :cause, :url, :header, :short_header, :description, :created_at, :updated_at, :severity, :service_effect, :timeframe, :lifecycle, :banner, active_period: [], informed_entity: [] ] @typedoc """ An activity affected by an alert. | Value | Description | |----------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `"BOARD"` | Boarding a vehicle. Any passenger trip includes boarding a vehicle and exiting from a vehicle. | | `"BRINGING_BIKE"` | Bringing a bicycle while boarding or exiting. | | `"EXIT"` | Exiting from a vehicle (disembarking). Any passenger trip includes boarding a vehicle and exiting a vehicle. | | `"PARK_CAR"` | Parking a car at a garage or lot in a station. | | `"RIDE"` | Riding through a stop without boarding or exiting.. Not every passenger trip will include this -- a passenger may board at one stop and exit at the next stop. | | `"STORE_BIKE"` | Storing a bicycle at a station. | | `"USING_ESCALATOR"` | Using an escalator while boarding or exiting (should only be used for customers who specifically want to avoid stairs.) | | `"USING_WHEELCHAIR"` | Using a wheelchair while boarding or exiting. Note that this applies to something that specifically affects customers who use a wheelchair to board or exit; a delay should not include this as an affected activity unless it specifically affects customers using wheelchairs. | """ @type activity :: String.t() # \ is included at end of lines still in the same paragraph, so that formatting is correct in both earmark for ex_doc # AND CommonMark for Swagger @typedoc """ Activities affected by this alert. If an entity is a station platform, and the alert only impacts those boarding at that platform and no one else, and \ the activity `"BOARD"` represents customers boarding at the informed entity, then the entity includes `activities` \ `["BOARD"]`. If the alert affected customers exiting at the platform too, then `activities` is `["BOARD", "EXIT"]`. It should be noted that the `activities` array includes activities that are specifically affected. Thus if there \ were activities `"BOARD"`, `"EXIT"`, and `"USING_WHEELCHAIR"` [to board or exit], and a station were closed, then \ the `activities` array would include `"BOARD"` and `"EXIT"` but it would not be necessary to include the activity \ `"USING_WHEELCHAIR"`. Any rider entering the station who is `"USING_WHEELCHAIR"` is also a rider who `"BOARD"`s. \ Using a wheelchair to board is not specifically affected. """ @type activities :: [activity] @typedoc """ An entity affected by an alert. At least one of the fields other than `activities` will be \ non-null. The affected entity is the intersection of these fields, not the union: if `stop` \ and `route` both have values, the alert does not affect the entire route. See [GTFS Realtime `FeedMessage` `FeedEntity` `Alert` `EntitySelector`](https://github.com/google/transit/blob/master/gtfs-realtime/spec/en/reference.md#message-entityselector). * `activities` - The activities affected. * `direction_id` - The direction of the affected `trip`. See \ [GTFS `trips.txt` `direction_id`](https://github.com/google/transit/blob/master/gtfs/spec/en/reference.md#tripstxt). * `facility` - The facility affected. * `route` - The route affected. See \ [GTFS `routes.txt` `route_id`](https://github.com/google/transit/blob/master/gtfs/spec/en/reference.md#routestxt) * `route_type` - The type of route affected. If present alone, indicates the entire mode of transit is affected. See \ [GTFS `routes.txt` `route_type`](https://github.com/google/transit/blob/master/gtfs/spec/en/reference.md#routestxt) * `stop` - The stop affected. See \ [GTFS `stops.txt` `stop_id`](https://github.com/google/transit/blob/master/gtfs/spec/en/reference.md#stopstxt) * `trip` - The trip affected. See \ [GTFS `trips.txt` `trip_id`](https://github.com/google/transit/blob/master/gtfs/spec/en/reference.md#tripstxt) """ @type informed_entity :: %{ optional(:activities) => activities, optional(:direction_id) => Model.Direction.id(), optional(:facility) => Model.Facility.id(), optional(:route) => Model.Route.id(), optional(:route_type) => Model.Route.route_type(), optional(:stop) => Model.Stop.id(), optional(:trip) => Model.Trip.id() } @cause_enum ~w( ACCIDENT AMTRAK AN_EARLIER_MECHANICAL_PROBLEM AN_EARLIER_SIGNAL_PROBLEM AUTOS_IMPEDING_SERVICE COAST_GUARD_RESTRICTION CONGESTION CONSTRUCTION CROSSING_MALFUNCTION DEMONSTRATION DISABLED_BUS DISABLED_TRAIN DRAWBRIDGE_BEING_RAISED ELECTRICAL_WORK FIRE FOG FREIGHT_TRAIN_INTERFERENCE HAZMAT_CONDITION HEAVY_RIDERSHIP HIGH_WINDS HOLIDAY HURRICANE ICE_IN_HARBOR MAINTENANCE MECHANICAL_PROBLEM MEDICAL_EMERGENCY PARADE POLICE_ACTION POWER_PROBLEM SEVERE_WEATHER SIGNAL_PROBLEM SLIPPERY_RAIL SNOW SPECIAL_EVENT SPEED_RESTRICTION SWITCH_PROBLEM TIE_REPLACEMENT TRACK_PROBLEM TRACK_WORK TRAFFIC UNRULY_PASSENGER WEATHER ) @typedoc """ | Value | |-------| #{Enum.map_join(@cause_enum, "\n", &"| `\"#{&1}\"` |")} See [GTFS Realtime `FeedMessage` `FeedEntity` `Alert` `Cause`](https://github.com/google/transit/blob/master/gtfs-realtime/spec/en/reference.md#enum-cause) """ @type cause :: String.t() @typedoc """ Time when the alert should be shown to the user. If missing, the alert will be shown as long as it appears in the feed. If multiple ranges are given, the alert will be shown during all of them. * `{DateTime.t, DateTime.t}` - a bound interval * `{DateTime.t, nil}` - an interval that started in the past and has not ended yet and is not planned to end anytime * `{nil, DateTime.t}` an interval that has existed for all time until the end time. See [GTFS Realtime `FeedMessage` `FeedEntity` `Alert` `TimeRange`](https://github.com/google/transit/blob/master/gtfs-realtime/spec/en/reference.md#message-timerange) """ @type datetime_pair :: {DateTime.t(), DateTime.t()} | {DateTime.t(), nil} | {nil, DateTime.t()} @effect_enum ~w( ACCESS_ISSUE ADDITIONAL_SERVICE AMBER_ALERT BIKE_ISSUE CANCELLATION DELAY DETOUR DOCK_CLOSURE DOCK_ISSUE ELEVATOR_CLOSURE ESCALATOR_CLOSURE EXTRA_SERVICE FACILITY_ISSUE MODIFIED_SERVICE NO_SERVICE OTHER_EFFECT PARKING_CLOSURE PARKING_ISSUE POLICY_CHANGE SCHEDULE_CHANGE SERVICE_CHANGE SHUTTLE SNOW_ROUTE STATION_CLOSURE STATION_ISSUE STOP_CLOSURE STOP_MOVE STOP_MOVED SUMMARY SUSPENSION TRACK_CHANGE UNKNOWN_EFFECT ) @typedoc """ | Value | |-------| #{Enum.map_join(@effect_enum, "\n", &"| `\"#{&1}\"` |")} See [GTFS Realtime `FeedMessage` `FeedEntity` `Alert` `effect`](https://github.com/google/transit/blob/master/gtfs-realtime/spec/en/reference.md#message-alert) """ @type effect :: String.t() @type id :: String.t() @typedoc """ Identifies whether alert is a new or old, in effect or upcoming. | Value | |----------------------| | `"NEW"` | | `"ONGOING"` | | `"ONGOING_UPCOMING"` | | `"UPCOMING"` | """ @type lifecycle :: String.t() @typedoc """ How severe the alert it from least (`0`) to most (`10`) severe. """ @type severity :: 0..10 @typedoc """ * `:id` - Unique ID * `:active_period` - See `t:datetime_pair/0` for individual entries in list. * `:banner` - Set if alert is meant to be displayed prominently, such as the top of every page. * `:cause` - Cause of the alert. See `t:cause/0` for all names and values. * `:create` - When the alert was created, which is completely unrelarted to the `active_period`s. * `:description` - This plain-text string will be formatted as the body of the alert (or shown on an explicit "expand" request by the user). The information in the description should add to the information of the header. See [GTFS Realtime `FeedMessage` `FeedEntity` `Alert` `description_text`](https://github.com/google/transit/blob/master/gtfs-realtime/spec/en/reference.md#message-alert) * `:effect` - The effect of this problem on the affected entity. See [GTFS Realtime `FeedMessage` `FeedEntity` `Alert` `effect`](https://github.com/google/transit/blob/master/gtfs-realtime/spec/en/reference.md#message-alert) * `:header` - This plain-text string will be highlighted, for example in boldface. See [GTFS Realtime `FeedMessage` `FeedEntity` `Alert` `header_text`](https://github.com/google/transit/blob/master/gtfs-realtime/spec/en/reference.md#message-alert) * `:informed_entity` - Entities whose users we should notify of this alert. See [GTFS Realtime `FeedMessage` `FeedEntity` `Alert` `informed_entity`](https://github.com/google/transit/blob/master/gtfs-realtime/spec/en/reference.md#message-alert) * `:lifecycle` - Enumeration of where the alert is in its lifecycle. See `t:lifecycle/0`. * `:service_effect` - Summarizes the service and the impact to that service. * `:severity` - Servity of the alert. See `t:severity/0`. * `:short_header` - A shortened version of `:header`. * `:timeframe` - Summarizes when an alert is in effect. * `:updated_at` - The last time this alert was updated. * `:url` - A URL for extra details, such as outline construction or maintenance plans. """ @type t :: %__MODULE__{ id: id, active_period: [datetime_pair], banner: String.t() | nil, cause: cause, created_at: DateTime.t(), description: String.t(), effect: effect, header: String.t(), informed_entity: [informed_entity], lifecycle: lifecycle, service_effect: String.t(), severity: severity, short_header: String.t(), timeframe: String.t(), updated_at: DateTime.t(), url: String.t() } @doc false def cause_enum, do: @cause_enum @doc false def effect_enum, do: @effect_enum end
apps/model/lib/model/alert.ex
0.889198
0.644358
alert.ex
starcoder
defmodule Yacto.Migration.Migrator do require Logger @spec migrated_versions(Ecto.Repo.t(), atom, module) :: [integer] def migrated_versions(repo, app, schema) do verbose_schema_migration(repo, "retrieve migrated versions", fn -> Yacto.Migration.SchemaMigration.ensure_schema_migrations_table!(repo) Yacto.Migration.SchemaMigration.migrated_versions(repo, app, schema) end) end defp difference_migration(migrations, versions) do migrations |> Enum.filter(fn migration -> !Enum.member?(versions, migration.version) end) end @doc """ Runs an up migration on the given repository. ## Options * `:log` - the level to use for logging of migration instructions. Defaults to `:info`. Can be any of `Logger.level/0` values or a boolean. * `:log_sql` - the level to use for logging of SQL instructions. Defaults to `false`. Can be any of `Logger.level/0` values or a boolean. * `:prefix` - the prefix to run the migrations on * `:dynamic_repo` - the name of the Repo supervisor process. See `c:Ecto.Repo.put_dynamic_repo/1`. * `:strict_version_order` - abort when applying a migration with old timestamp """ def up(app, repo, schemas, migrations, opts \\ []) do sorted_migrations = case Yacto.Migration.Util.sort_migrations(migrations) do {:error, errors} -> for error <- errors do Logger.error(error) end raise inspect(errors) {:ok, sorted_migrations} -> sorted_migrations end for schema <- schemas do if Yacto.Migration.Util.allow_migrate?(schema, repo) do versions = migrated_versions(repo, app, schema) need_migrations = difference_migration(sorted_migrations, versions) for migration <- need_migrations do do_up(app, repo, schema, migration.module, opts) end end end :ok end defp do_up(app, repo, schema, migration, opts) do async_migrate_maybe_in_transaction(app, repo, schema, migration, :up, opts, fn -> attempt(repo, schema, migration, :forward, :up, :up, opts) || attempt(repo, schema, migration, :forward, :change, :up, opts) || {:error, Ecto.MigrationError.exception( "#{inspect(migration)} does not implement a `up/0` or `change/0` function" )} end) end defp async_migrate_maybe_in_transaction(app, repo, schema, migration, _direction, _opts, fun) do parent = self() ref = make_ref() dynamic_repo = repo.get_dynamic_repo() task = Task.async(fn -> run_maybe_in_transaction(parent, ref, repo, dynamic_repo, schema, migration, fun) end) if migrated_successfully?(ref, task.pid) do try do # The table with schema migrations can only be updated from # the parent process because it has a lock on the table verbose_schema_migration(repo, "update schema migrations", fn -> Yacto.Migration.SchemaMigration.up(repo, app, schema, migration.__migration_version__()) end) catch kind, error -> Task.shutdown(task, :brutal_kill) :erlang.raise(kind, error, System.stacktrace()) end end send(task.pid, ref) Task.await(task, :infinity) end defp migrated_successfully?(ref, pid) do receive do {^ref, :ok} -> true {^ref, _} -> false {:EXIT, ^pid, _} -> false end end defp run_maybe_in_transaction(parent, ref, repo, dynamic_repo, _schema, migration, fun) do repo.put_dynamic_repo(dynamic_repo) if migration.__migration__[:disable_ddl_transaction] || not repo.__adapter__.supports_ddl_transaction? do send_and_receive(parent, ref, fun.()) else {:ok, result} = repo.transaction( fn -> send_and_receive(parent, ref, fun.()) end, log: false, timeout: :infinity ) result end catch kind, reason -> send_and_receive(parent, ref, {kind, reason, System.stacktrace()}) end defp send_and_receive(parent, ref, value) do send(parent, {ref, value}) receive do: (^ref -> value) end defp verbose_schema_migration(repo, reason, fun) do try do fun.() rescue error -> Logger.error("Could not #{reason} for #{repo}.") reraise error, System.stacktrace() end end defp attempt(repo, schema, migration, direction, operation, reference, opts) do if Code.ensure_loaded?(migration) and function_exported?(migration, operation, 1) do run(repo, schema, migration, direction, operation, reference, opts) :ok end end # Ecto.Migration.Runner.run defp run(repo, schema, migration, direction, operation, migrator_direction, opts) do version = migration.__migration_version__() level = Keyword.get(opts, :log, :info) sql = Keyword.get(opts, :log_sql, false) log = %{level: level, sql: sql} args = [self(), repo, migration, direction, migrator_direction, log] {:ok, runner} = Supervisor.start_child(Ecto.Migration.Supervisor, args) Ecto.Migration.Runner.metadata(runner, opts) log(level, "== Running #{version} #{inspect(migration)}.#{operation}/0 #{direction}") {time, _} = :timer.tc(fn -> perform_operation(repo, schema, migration, operation) end) log(level, "== Migrated #{version} in #{inspect(div(time, 100_000) / 10)}s") Ecto.Migration.Runner.stop() end defp perform_operation(repo, schema, migration, operation) do if function_exported?(repo, :in_transaction?, 0) and repo.in_transaction?() do if function_exported?(migration, :after_begin, 0) do migration.after_begin() end result = apply(migration, operation, [schema]) if function_exported?(migration, :before_commit, 0) do migration.before_commit() end result else apply(migration, operation, [schema]) end Ecto.Migration.Runner.flush() end defp log(false, _msg), do: :ok defp log(level, msg), do: Logger.log(level, msg) end
lib/yacto/migration/migrator.ex
0.687105
0.461441
migrator.ex
starcoder
defmodule Supervisor.Behaviour do @moduledoc """ This module is a convenience to define Supervisor callbacks in Elixir. By using this module, you get the module behaviour automatically tagged as `:supervisor` and some helper functions are imported to make defining supervisors easier. For more information on supervisors, please check the remaining functions defined in this module or refer to the following: http://www.erlang.org/doc/man/supervisor.html http://www.erlang.org/doc/design_principles/sup_princ.html http://learnyousomeerlang.com/supervisors ## Example defmodule ExUnit.Sup do use Supervisor.Behaviour def init(user_options) do tree = [ worker(ExUnit.Runner, [user_options]) ] supervise(tree, strategy: :one_for_one) end end { :ok, pid } = :supervisor.start_link(MyServer, []) """ @doc false defmacro __using__(_) do quote location: :keep do @behaviour :supervisor import unquote(__MODULE__) end end @doc """ Receives a list of children (worker or supervisors) to supervise and a set of options. Returns a tuple containing the supervisor specification. ## Examples supervise children, strategy: :one_for_one ## Options * `:strategy` - the restart strategy option It can be either `:one_for_one`, `:rest_for_one`, `:one_for_all` and `:simple_one_for_one`; * `:max_restarts` - the maximum amount of restarts allowed in a time frame. Defaults to 5; * `:max_seconds` - the time frame in which max_restarts applies. Defaults to 5; The `:strategy` option is required and by default maximum 5 restarts are allowed in 5 seconds. ## Strategies * `:one_for_one` - If a child process terminates, only that process is restarted; * `:one_for_all` - If a child process terminates, all other child processes are terminated and then all child processes, including the terminated one, are restarted; * `:rest_for_one` - If a child process terminates, the "rest" of the child processes, i.e. the child processes after the terminated process in start order, are terminated. Then the terminated child process and the rest of the child processes are restarted; * `:simple_one_for_one` - Similar to `:one_for_one` but suits better when dynamically attaching children; """ def supervise(children, options) do unless strategy = options[:strategy] do raise ArgumentError, message: "expected :strategy option to be given to supervise" end maxR = Keyword.get(options, :max_restarts, 5) maxS = Keyword.get(options, :max_seconds, 5) { :ok, { { strategy, maxR, maxS }, children } } end @child_doc """ ## Options * `:id` - a name used to identify the child specification internally by the supervisor. Defaults to the module name; * `:function` - the function to invoke on the child to start it. Defaults to `:start_link`; * `:restart` - defines when the child process should restart. Defaults to `:permanent`; * `:shutdown` - defines how a child process should be terminated. Defaults to `5000` for a worker and `:infinity` for a supervisor; * `:modules` - it should be a list with one element `[module]`, where module is the name of the callback module only if the child process is a supervisor, `gen_server` or `gen_fsm`. If the child process is a gen_event, modules should be `:dynamic`. Defaults to a list with the given module; ## Restart values The following restart values are supported: * `:permanent` - the child process is always restarted; * `:temporary` - the child process is never restarted (not even when the supervisor's strategy is `:rest_for_one` or `:one_for_all`); * `:transient` - the child process is restarted only if it terminates abnormally, i.e. with another exit reason than `:normal`, `:shutdown` or `{ :shutdown, term }`; ## Shutdown values The following shutdown values are supported: * `:brutal_kill` - the child process is unconditionally terminated using `exit(child, :kill)`; * `:infinity` - if the child process is a supervisor, it is a mechanism to give the subtree enough time to shutdown. It can also be used with workers with care; * Finally, it can also be any integer meaning that the supervisor tells the child process to terminate by calling `exit(child, :shutdown)` and then waits for an exit signal back. If no exit signal is received within the specified time (in miliseconds), the child process is unconditionally terminated using `exit(child, :kill)`; """ @doc """ Defines the given `module` as a worker which will be started with the given arguments. worker ExUnit.Runner, [], restart: :permanent By default, the function `:start_link` is invoked on the given module. #{@child_doc} """ def worker(module, args, options // []) do child(:worker, module, args, options) end @doc """ Defines the given `module` as a supervisor which will be started with the given arguments. supervisor ExUnit.Runner, [], restart: :permanent By default, the function `:start_link` is invoked on the given module. #{@child_doc} """ def supervisor(module, args, options // []) do options = Keyword.update(options, :shutdown, :infinity, fn(x) -> x end) child(:supervisor, module, args, options) end defp child(type, module, args, options) do id = Keyword.get(options, :id, module) modules = Keyword.get(options, :modules, [module]) function = Keyword.get(options, :function, :start_link) restart = Keyword.get(options, :restart, :permanent) shutdown = Keyword.get(options, :shutdown, 5000) { id, { module, function, args }, restart, shutdown, type, modules } end end
lib/elixir/lib/supervisor/behaviour.ex
0.8308
0.603348
behaviour.ex
starcoder
defmodule SimpleMqtt.Subscriptions do alias SimpleMqtt.Topics @moduledoc """ Represents collection of subscribed topics for multiple processes. """ @type subscriptions :: %{} @doc """ Creates new subscriptions collection. """ @spec new() :: subscriptions() def new() do Map.new() end @doc """ Adds a new subscription to the collection. If the same pid was already registered, the topics will be merged. """ @spec subscribe(subscriptions(), pid(), [String.t()]) :: :error | subscriptions() def subscribe(subscriptions, pid, topics) do with {:ok, parsed_topics} <- parse_subscribed_topics(topics) do new_set = MapSet.new(parsed_topics) Map.update(subscriptions, pid, new_set, fn existing_set -> MapSet.union(existing_set, new_set) end) else :error -> :error end end @doc """ Removes topics from the subscription. """ @spec unsubscribe(subscriptions(), pid(), [String.t()] | :all) :: :error | {:empty, subscriptions()} | {:not_empty, subscriptions()} def unsubscribe(subscriptions, pid, :all) do {:empty, Map.delete(subscriptions, pid)} end def unsubscribe(subscriptions, pid, topics) do with {:ok, parsed_topics} <- parse_subscribed_topics(topics), {:ok, existing_topics} <- Map.fetch(subscriptions, pid) do {_, updated} = parsed_topics|> Enum.map_reduce(existing_topics, fn item, acc -> {item, MapSet.delete(acc, item)} end) case Enum.count(updated) do 0 -> {:empty, Map.delete(subscriptions, pid)} _ -> {:not_empty, Map.put(subscriptions, pid, updated)} end else :error -> :error end end @spec list_matched(subscriptions(), String.t) :: :error | [pid()] @doc """ Returns pids for all processes that subscribed to topics that match the given published topic. """ def list_matched(subscriptions, topic) do case Topics.parse_published_topic(topic) do {:ok, published_topic} -> subscriptions |> Stream.flat_map(fn {pid, subscribed_topics} -> Enum.map(subscribed_topics, fn t-> {pid, t} end) end) |> Stream.filter(fn {_, t} -> Topics.matches?(published_topic, t) end) |> Stream.map(fn {pid, _} -> pid end) |> Enum.uniq() :error -> :error end end defp parse_subscribed_topics(topics, result \\ []) defp parse_subscribed_topics([], result), do: {:ok, result} defp parse_subscribed_topics([first | rest], result) do case Topics.parse_subscribed_topic(first) do {:ok, parsed_topic} -> parse_subscribed_topics(rest, [parsed_topic | result]) :error -> :error end end end
lib/subscriptions.ex
0.81582
0.416559
subscriptions.ex
starcoder
defmodule RMQ.Consumer do @moduledoc ~S""" RabbitMQ Consumer. ## Configuration * `:connection` - the connection module which implements `RMQ.Connection` behaviour. Defaults to `RMQ.Connection`; * `:queue` - the name of the queue to consume. Will be created if does not exist. Also can be a tuple `{queue, options}`. See the options for `AMQP.Queue.declare/3`; * `:exchange` - the name of the exchange to which `queue` should be bound. Also can be a tuple `{exchange, type, options}`. See the options for `AMQP.Exchange.declare/4`. Defaults to `""`; * `:routing_key` - queue binding key. Defaults to `queue`; Will be created if does not exist. Defaults to `""`; * `:dead_letter` - defines if the consumer should setup deadletter exchange and queue. Defaults to `true`; * `:dead_letter_queue` - the name of dead letter queue. Also can be a tuple `{queue, options}`. See the options for `AMQP.Queue.declare/3`. Defaults to `"#{queue}_error"`.; * `:dead_letter_exchange` - the name of the exchange to which `dead_letter_queue` should be bound. Also can be a tuple `{type, exchange}` or `{type, exchange, options}`. See the options for `AMQP.Exchange.declare/4`. Defaults to `"#{exchange}.dead-letter"`; * `:dead_letter_routing_key` - routing key for dead letter messages. Defaults to `queue`; * `:prefetch_count` - sets the message prefetch count. Defaults to `10`; * `:consumer_tag` - consumer tag. Defaults to a current module name; * `:reconnect_interval` - a reconnect interval in milliseconds. It can be also a function that accepts the current connection attempt as a number and returns a new interval. Defaults to `5000`; ## Examples defmodule MyApp.Consumer do use RMQ.Consumer, queue: {"my-app-consumer-queue", durable: true}, exchange: {"my-exchange", :direct, durable: true} @impl RMQ.Consumer def consume(chan, payload, meta) do # do something with the payload ack(chan, meta.delivery_tag) end end defmodule MyApp.Consumer2 do use RMQ.Consumer @impl RMQ.Consumer def config do [ queue: System.fetch_env!("QUEUE_NAME"), reconnect_interval: fn attempt -> attempt * 1000 end, ] end @impl RMQ.Consumer def consume(chan, payload, meta) do # do something with the payload ack(chan, meta.delivery_tag) end end """ use RMQ.Logger import RMQ.Utils @defaults [ connection: RMQ.Connection, exchange: "", dead_letter: true, prefetch_count: 10, reconnect_interval: 5000 ] @doc """ A callback for consuming a message. Keep in mind that the consumed message needs to be explicitly acknowledged via `AMQP.Basic.ack/3` or rejected via `AMQP.Basic.reject/3`. For convenience, these functions are imported and are available for use directly. `RMQ.Utils.reply/4` is imported as well which is convenient for the case when the consumer implements RPC. """ @callback consume(chan :: AMQP.Channel.t(), payload :: any(), meta :: map()) :: any() @doc """ A callback for dynamic configuration. """ @callback config() :: keyword() @doc """ Does all the job on preparing the queue. Whenever you need full control over configuring the queue you can implement this callback and use `AMQP` library directly. See `setup_queue/2` for the default implementation. """ @callback setup_queue(chan :: AMQP.Channel.t(), config :: keyword()) :: :ok @doc false def start_link(module, opts) do GenServer.start_link(module, module, Keyword.put_new(opts, :name, module)) end @doc false def init(_module, _arg) do Process.flag(:trap_exit, true) send(self(), {:init, 1}) {:ok, %{chan: nil, config: %{}}} end @doc false def handle_info(module, {:init, attempt}, state) do config = module_config(module) with {:ok, conn} <- config[:connection].get_connection(), {:ok, chan} <- AMQP.Channel.open(conn) do Process.monitor(chan.pid) module.setup_queue(chan, config) log_info("Ready") {:noreply, %{state | config: config, chan: chan}} else error -> time = reconnect_interval(config[:reconnect_interval], attempt) log_error("No connection: #{inspect(error)}. Retrying in #{time}ms") Process.send_after(self(), {:init, attempt + 1}, time) {:noreply, %{state | config: config}} end end # Confirmation sent by the broker after registering this process as a consumer def handle_info(_module, {:basic_consume_ok, _meta}, state) do {:noreply, state} end # Sent by the broker when the consumer is unexpectedly cancelled (such as after a queue deletion) def handle_info(_module, {:basic_cancel, _meta}, state) do {:stop, :normal, state} end # Confirmation sent by the broker to the consumer process after a Basic.cancel def handle_info(_module, {:basic_cancel_ok, _meta}, state) do {:noreply, state} end def handle_info(module, {:basic_deliver, payload, meta}, %{chan: chan} = state) do module.consume(chan, payload, meta) {:noreply, state} end def handle_info(module, {:DOWN, _ref, :process, _pid, reason}, state) do log_error(module, "Connection lost: #{inspect(reason)}. Reconnecting...") send(self(), {:init, 1}) {:noreply, %{state | chan: nil}} end @doc false def terminate(_module, _reason, %{chan: chan}) do close_channel(chan) end @doc """ The default implementation for `c:setup_queue/2` callback. """ @spec setup_queue(chan :: AMQP.Channel.t(), config :: keyword()) :: :ok def setup_queue(chan, config) do {xch, xch_type, xch_opts} = normalize_exchange(config[:exchange]) {q, q_opts} = normalize_queue(config[:queue]) dl_args = setup_dead_letter(chan, config) q_opts = Keyword.update(q_opts, :arguments, dl_args, &(dl_args ++ &1)) {:ok, %{queue: q}} = AMQP.Queue.declare(chan, q, q_opts) # the exchange "" is the default exchange and cannot be declared this way unless xch == "" do :ok = AMQP.Exchange.declare(chan, xch, xch_type, xch_opts) :ok = AMQP.Queue.bind(chan, q, xch, routing_key: config[:routing_key]) end :ok = AMQP.Basic.qos(chan, prefetch_count: config[:prefetch_count]) {:ok, _} = AMQP.Basic.consume(chan, q, nil, consumer_tag: config[:consumer_tag]) :ok end defp setup_dead_letter(chan, config) do if config[:dead_letter] do {xch, xch_type, xch_opts} = normalize_exchange(config[:dead_letter_exchange]) {q, q_opts} = normalize_queue(config[:dead_letter_queue]) {:ok, %{queue: q}} = AMQP.Queue.declare(chan, q, q_opts) :ok = AMQP.Exchange.declare(chan, xch, xch_type, xch_opts) :ok = AMQP.Queue.bind(chan, q, xch) [ {"x-dead-letter-exchange", :longstr, xch}, {"x-dead-letter-routing-key", :longstr, config[:dead_letter_routing_key]} ] else [] end end defp module_config(module) do config = Keyword.merge(@defaults, module.config()) {q, q_opts} = Keyword.fetch!(config, :queue) |> normalize_queue() {xch, xch_type, xch_opts} = Keyword.fetch!(config, :exchange) |> normalize_exchange() dl_xch_name = String.replace_prefix("#{xch}.dead-letter", ".", "") # by default for the dead-letter exchange use the same type and the same `:durable` option # as for the main exchange. When the `:durable` option isn't set explicitly, we determine it # based on the main exchange. The default exchange `""` is always durable. dl_xch = {dl_xch_name, xch_type, durable: Keyword.get(xch_opts, :durable, xch == "")} # by default for the dead-letter queue use the same `:durable` option as for the main queue dl_q = {"#{q}_error", durable: Keyword.get(q_opts, :durable, false)} config |> Keyword.put_new(:routing_key, q) |> Keyword.put_new(:dead_letter_routing_key, q) |> Keyword.put_new(:dead_letter_exchange, dl_xch) |> Keyword.put_new(:dead_letter_queue, dl_q) |> Keyword.put_new(:consumer_tag, to_string(module)) end defmacro __using__(opts \\ []) do quote location: :keep do use GenServer import RMQ.Utils, only: [ack: 3, ack: 2, reply: 4, reply: 3] import AMQP.Basic, only: [reject: 3, reject: 2, publish: 5, publish: 4] @behaviour RMQ.Consumer @config unquote(opts) def start_link(opts), do: RMQ.Consumer.start_link(__MODULE__, opts) @impl RMQ.Consumer def setup_queue(chan, config), do: RMQ.Consumer.setup_queue(chan, config) @impl RMQ.Consumer def config, do: @config @impl GenServer def init(arg), do: RMQ.Consumer.init(__MODULE__, arg) @impl GenServer def handle_info(msg, state), do: RMQ.Consumer.handle_info(__MODULE__, msg, state) @impl GenServer def terminate(reason, state), do: RMQ.Consumer.terminate(__MODULE__, reason, state) defoverridable config: 0, setup_queue: 2 end end end
lib/rmq/consumer.ex
0.881761
0.455925
consumer.ex
starcoder
defmodule Scrivener.HTML.SEO do import Phoenix.HTML.Tag, only: [tag: 2] import Scrivener.HTML.Helper, only: [fetch_options: 2] alias Scrivener.Page @defaults Scrivener.HTML.defaults() @moduledoc """ SEO related functions for pagination. See [Indicating paginated content to Google](https://web.archive.org/web/20190217083902/https://support.google.com/webmasters/answer/1663744?hl=en) for more information. """ @doc """ Produces the value for a `rel` attribute in an `<a>` tag. Returns either `"next"`, `"prev"` or `"canonical"`. iex> Scrivener.HTML.SEO.rel(%Scrivener.Page{page_number: 5}, 4) "prev" iex> Scrivener.HTML.SEO.rel(%Scrivener.Page{page_number: 5}, 6) "next" iex> Scrivener.HTML.SEO.rel(%Scrivener.Page{page_number: 5}, 8) "canonical" `Scrivener.HTML.pagination/2` will use this module to add `rel` attribute to each link. """ def rel(%Page{page_number: current_page}, page_number) when current_page + 1 == page_number, do: "next" def rel(%Page{page_number: current_page}, page_number) when current_page - 1 == page_number, do: "prev" def rel(_page, _page_number), do: "canonical" @doc ~S""" Produces `<link/>` tags for putting in the `<head>` to help SEO. The arguments passed in are the same as `Scrivener.HTML.pagination/2`. See [SEO Tags in Phoenix](http://blog.danielberkompas.com/2016/01/28/seo-tags-in-phoenix.html) to know about how to do that. iex> Scrivener.HTML.SEO.header_links(%Scrivener.Page{total_pages: 10, page_number: 3}) |> Phoenix.HTML.safe_to_string "<link href=\"?page=2\" rel=\"prev\">\n<link href=\"?page=4\" rel=\"next\">" """ def header_links(page, opts \\ []) def header_links(%Page{page_number: 1} = page, opts) do next_header_link(page, opts) end def header_links( %Page{total_pages: page_number, page_number: page_number} = page, opts ) do prev_header_link(page, opts) end def header_links(%Page{} = page, opts) do {:safe, prev} = prev_header_link(page, opts) {:safe, next} = next_header_link(page, opts) {:safe, [prev, "\n", next]} end defp href(_page, opts, page_number) do options = fetch_options(opts, @defaults) path = options[:path] page_param = options[:page_param] url_params = Keyword.drop(opts, Keyword.keys(@defaults)) params = case page_number > 1 do true -> [{page_param, page_number}] false -> [] end ++ url_params query = URI.encode_query(params) "#{path}?#{query}" end defp prev_header_link(page, opts) do page_number = page.page_number - 1 href = href(page, opts, page_number) tag(:link, href: href, rel: rel(page, page_number)) end defp next_header_link(page, opts) do page_number = page.page_number + 1 href = href(page, opts, page_number) tag(:link, href: href, rel: rel(page, page_number)) end end
lib/scrivener/html/seo.ex
0.688573
0.429788
seo.ex
starcoder
defmodule Exemvi.QR.MP do alias Exemvi.QR.MP.Object, as: MPO @moduledoc """ This module contains core functions for Merchant-Presented Mode QR Code """ @doc """ Validate whole QR Code Returns either: - `{:ok, qr_code}` where `qr_code` is the QR Code orginally supplied to the function - `{:error, reasons}` where `reasons` is a list of validation error reasons as atoms """ def validate_qr(qr) do qr_format_indicator = String.slice(qr, 0, 6) qr_length = String.length(qr) without_checksum = String.slice(qr, 0, qr_length - 4) qr_checksum = String.slice(qr, qr_length - 4, 4) expected_checksum = Exemvi.CRC.checksum_hex(without_checksum) all_ok = qr_format_indicator == "000201" all_ok = all_ok and qr_checksum == expected_checksum if all_ok do {:ok, qr} else {:error, [Exemvi.Error.invalid_qr]} end end def parse_to_objects({:ok, qr}) do parse_to_objects(qr) end def parse_to_objects({:error, reasons}) do {:error, reasons} end @doc """ Parse QR Code into data objects Returns either: - `{:ok, objects}` where `objects` is a list of `Exemvi.MP.Object` structs - `{:error, reasons}` where `reasons` is a list of error reasons as atoms """ def parse_to_objects(qr) do case parse_to_objects_rest(:root, qr, []) do {:ok, objects} -> {:ok, objects} {:error, reasons} -> {:error, reasons} end end def validate_objects({:ok, objects}) do validate_objects(objects) end def validate_objects({:error, reasons}) do {:error, reasons} end @doc """ Validate data objects Returns either: - `{:ok, objects}` where `objects` is the objects originally supplied to the function - `{:error, reasons}` where `reasons` is a list of validation error reasons as atoms """ def validate_objects(objects) do reasons = validate_all_objects_rest(:root, objects, []) if Enum.count(reasons) == 0 do {:ok, objects} else {:error, reasons} end end defp parse_to_objects_rest(_template, "", objects) do {:ok, objects} end defp parse_to_objects_rest(template, qr_rest, objects) do id_raw = qr_rest |> String.slice(0, 2) id_atom = MPO.id_atoms(template)[id_raw] value_length_raw = qr_rest |> String.slice(2, 2) value_length = case Integer.parse(value_length_raw) do {i, ""} -> i _ -> 0 end cond do id_atom == nil -> {:error, [Exemvi.Error.invalid_object_id]} value_length == 0 -> {:error, [Exemvi.Error.invalid_value_length]} true -> value = String.slice(qr_rest, 4, value_length) qr_rest_next = String.slice(qr_rest, (4 + value_length)..-1) is_template = MPO.specs(template)[id_atom][:is_template] maybe_object = case is_template do false -> {:ok, %MPO{id: id_raw, value: value}} true -> case parse_to_objects_rest(id_atom, value, []) do {:ok, inner_objects} -> {:ok, %MPO{id: id_raw, objects: inner_objects}} {:error, reasons} -> {:error, reasons} end end case maybe_object do {:error, reasons} -> {:error, reasons} {:ok, object} -> objects = objects ++ [object] parse_to_objects_rest(template, qr_rest_next, objects) end end end defp validate_all_objects_rest(template, all_objects, reasons) do mandatory_reasons = validate_objects_exist(template, all_objects) reasons = reasons ++ mandatory_reasons orphaned_reasons = validate_objects_have_parents(template, all_objects) reasons = reasons ++ orphaned_reasons object_reasons = validate_object_rest(template, all_objects, reasons) reasons ++ object_reasons end defp validate_objects_exist(template, all_objects) do mandatory_ids = MPO.specs(template) |> Enum.filter(fn {_, v} -> v[:must] == true and v[:must_alias] == nil end) |> Enum.map(fn {k, _} -> k end) supplied_ids = all_objects |> Enum.map(fn x -> MPO.id_atoms(template)[x.id] end) |> Enum.map(fn x -> MPO.specs(template)[x][:must_alias] || x end) id_exists = fn all_ids, id_to_check, reasons -> if Enum.member?(all_ids, id_to_check) do reasons else reasons ++ [Exemvi.Error.missing_object_id(id_to_check)] end end reasons = Enum.reduce( mandatory_ids, [], fn mandatory_id, reason_acc -> id_exists.(supplied_ids, mandatory_id, reason_acc) end) if Enum.count(reasons) == 0 do [] else reasons end end defp validate_objects_have_parents(template, all_objects) do supplied_ids = Enum.map( all_objects, fn x -> MPO.id_atoms(template)[x.id] end) spec_child_ids = MPO.specs(template) |> Enum.filter(fn {_, v} -> v[:parent] != nil end) |> Enum.map(fn {k, _} -> k end) supplied_child_ids = spec_child_ids |> Enum.filter(fn x -> Enum.member?(supplied_ids, x) end) orphaned_ids = supplied_child_ids |> Enum.filter(fn x -> not Enum.member?(supplied_ids, MPO.specs(template)[x][:parent]) end) if Enum.count(orphaned_ids) == 0 do [] else Enum.map(orphaned_ids, fn x -> Exemvi.Error.orphaned_object(x) end) end end defp validate_object_rest(_template, [], reasons) do reasons end defp validate_object_rest(template, objects_rest, reasons) do [object | objects_rest_next] = objects_rest value_reasons = validate_object_value(template, object) reasons = reasons ++ value_reasons template_reasons = cond do Enum.count(value_reasons) == 0 and object.objects != nil -> id_atom = MPO.id_atoms(template)[object.id] validate_all_objects_rest(id_atom, object.objects, reasons) true -> [] end reasons = reasons ++ template_reasons validate_object_rest(template, objects_rest_next, reasons) end defp validate_object_value(template, object) do id_atom = MPO.id_atoms(template)[object.id] spec = MPO.specs(template)[id_atom] if spec[:is_template] do [] else object_value = object.value || "" actual_len = String.length(object_value) len_is_ok = actual_len >= spec[:min_len] and actual_len <= spec[:max_len] format_is_ok = case spec[:regex] do nil -> true _ -> String.match?(object_value, spec[:regex]) end if len_is_ok and format_is_ok do [] else [Exemvi.Error.invalid_object_value(id_atom)] end end end end
lib/exemvi/qr/mp/mp.ex
0.853837
0.66488
mp.ex
starcoder
defmodule AWS.EFS do @moduledoc """ Amazon Elastic File System Amazon Elastic File System (Amazon EFS) provides simple, scalable file storage for use with Amazon EC2 instances in the AWS Cloud. With Amazon EFS, storage capacity is elastic, growing and shrinking automatically as you add and remove files, so your applications have the storage they need, when they need it. For more information, see the [User Guide](https://docs.aws.amazon.com/efs/latest/ug/api-reference.html). """ @doc """ Creates an EFS access point. An access point is an application-specific view into an EFS file system that applies an operating system user and group, and a file system path, to any file system request made through the access point. The operating system user and group override any identity information provided by the NFS client. The file system path is exposed as the access point's root directory. Applications using the access point can only access data in its own directory and below. To learn more, see [Mounting a File System Using EFS Access Points](https://docs.aws.amazon.com/efs/latest/ug/efs-access-points.html). This operation requires permissions for the `elasticfilesystem:CreateAccessPoint` action. """ def create_access_point(client, input, options \\ []) do path_ = "/2015-02-01/access-points" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Creates a new, empty file system. The operation requires a creation token in the request that Amazon EFS uses to ensure idempotent creation (calling the operation with same creation token has no effect). If a file system does not currently exist that is owned by the caller's AWS account with the specified creation token, this operation does the following: <ul> <li> Creates a new, empty file system. The file system will have an Amazon EFS assigned ID, and an initial lifecycle state `creating`. </li> <li> Returns with the description of the created file system. </li> </ul> Otherwise, this operation returns a `FileSystemAlreadyExists` error with the ID of the existing file system. <note> For basic use cases, you can use a randomly generated UUID for the creation token. </note> The idempotent operation allows you to retry a `CreateFileSystem` call without risk of creating an extra file system. This can happen when an initial call fails in a way that leaves it uncertain whether or not a file system was actually created. An example might be that a transport level timeout occurred or your connection was reset. As long as you use the same creation token, if the initial call had succeeded in creating a file system, the client can learn of its existence from the `FileSystemAlreadyExists` error. <note> The `CreateFileSystem` call returns while the file system's lifecycle state is still `creating`. You can check the file system creation status by calling the `DescribeFileSystems` operation, which among other things returns the file system state. </note> This operation also takes an optional `PerformanceMode` parameter that you choose for your file system. We recommend `generalPurpose` performance mode for most file systems. File systems using the `maxIO` performance mode can scale to higher levels of aggregate throughput and operations per second with a tradeoff of slightly higher latencies for most file operations. The performance mode can't be changed after the file system has been created. For more information, see [Amazon EFS: Performance Modes](https://docs.aws.amazon.com/efs/latest/ug/performance.html#performancemodes.html). After the file system is fully created, Amazon EFS sets its lifecycle state to `available`, at which point you can create one or more mount targets for the file system in your VPC. For more information, see `CreateMountTarget`. You mount your Amazon EFS file system on an EC2 instances in your VPC by using the mount target. For more information, see [Amazon EFS: How it Works](https://docs.aws.amazon.com/efs/latest/ug/how-it-works.html). This operation requires permissions for the `elasticfilesystem:CreateFileSystem` action. """ def create_file_system(client, input, options \\ []) do path_ = "/2015-02-01/file-systems" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Creates a mount target for a file system. You can then mount the file system on EC2 instances by using the mount target. You can create one mount target in each Availability Zone in your VPC. All EC2 instances in a VPC within a given Availability Zone share a single mount target for a given file system. If you have multiple subnets in an Availability Zone, you create a mount target in one of the subnets. EC2 instances do not need to be in the same subnet as the mount target in order to access their file system. For more information, see [Amazon EFS: How it Works](https://docs.aws.amazon.com/efs/latest/ug/how-it-works.html). In the request, you also specify a file system ID for which you are creating the mount target and the file system's lifecycle state must be `available`. For more information, see `DescribeFileSystems`. In the request, you also provide a subnet ID, which determines the following: <ul> <li> VPC in which Amazon EFS creates the mount target </li> <li> Availability Zone in which Amazon EFS creates the mount target </li> <li> IP address range from which Amazon EFS selects the IP address of the mount target (if you don't specify an IP address in the request) </li> </ul> After creating the mount target, Amazon EFS returns a response that includes, a `MountTargetId` and an `IpAddress`. You use this IP address when mounting the file system in an EC2 instance. You can also use the mount target's DNS name when mounting the file system. The EC2 instance on which you mount the file system by using the mount target can resolve the mount target's DNS name to its IP address. For more information, see [How it Works: Implementation Overview](https://docs.aws.amazon.com/efs/latest/ug/how-it-works.html#how-it-works-implementation). Note that you can create mount targets for a file system in only one VPC, and there can be only one mount target per Availability Zone. That is, if the file system already has one or more mount targets created for it, the subnet specified in the request to add another mount target must meet the following requirements: <ul> <li> Must belong to the same VPC as the subnets of the existing mount targets </li> <li> Must not be in the same Availability Zone as any of the subnets of the existing mount targets </li> </ul> If the request satisfies the requirements, Amazon EFS does the following: <ul> <li> Creates a new mount target in the specified subnet. </li> <li> Also creates a new network interface in the subnet as follows: <ul> <li> If the request provides an `IpAddress`, Amazon EFS assigns that IP address to the network interface. Otherwise, Amazon EFS assigns a free address in the subnet (in the same way that the Amazon EC2 `CreateNetworkInterface` call does when a request does not specify a primary private IP address). </li> <li> If the request provides `SecurityGroups`, this network interface is associated with those security groups. Otherwise, it belongs to the default security group for the subnet's VPC. </li> <li> Assigns the description `Mount target *fsmt-id* for file system *fs-id* ` where ` *fsmt-id* ` is the mount target ID, and ` *fs-id* ` is the `FileSystemId`. </li> <li> Sets the `requesterManaged` property of the network interface to `true`, and the `requesterId` value to `EFS`. </li> </ul> Each Amazon EFS mount target has one corresponding requester-managed EC2 network interface. After the network interface is created, Amazon EFS sets the `NetworkInterfaceId` field in the mount target's description to the network interface ID, and the `IpAddress` field to its address. If network interface creation fails, the entire `CreateMountTarget` operation fails. </li> </ul> <note> The `CreateMountTarget` call returns only after creating the network interface, but while the mount target state is still `creating`, you can check the mount target creation status by calling the `DescribeMountTargets` operation, which among other things returns the mount target state. </note> We recommend that you create a mount target in each of the Availability Zones. There are cost considerations for using a file system in an Availability Zone through a mount target created in another Availability Zone. For more information, see [Amazon EFS](http://aws.amazon.com/efs/). In addition, by always using a mount target local to the instance's Availability Zone, you eliminate a partial failure scenario. If the Availability Zone in which your mount target is created goes down, then you can't access your file system through that mount target. This operation requires permissions for the following action on the file system: <ul> <li> `elasticfilesystem:CreateMountTarget` </li> </ul> This operation also requires permissions for the following Amazon EC2 actions: <ul> <li> `ec2:DescribeSubnets` </li> <li> `ec2:DescribeNetworkInterfaces` </li> <li> `ec2:CreateNetworkInterface` </li> </ul> """ def create_mount_target(client, input, options \\ []) do path_ = "/2015-02-01/mount-targets" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Creates or overwrites tags associated with a file system. Each tag is a key-value pair. If a tag key specified in the request already exists on the file system, this operation overwrites its value with the value provided in the request. If you add the `Name` tag to your file system, Amazon EFS returns it in the response to the `DescribeFileSystems` operation. This operation requires permission for the `elasticfilesystem:CreateTags` action. """ def create_tags(client, file_system_id, input, options \\ []) do path_ = "/2015-02-01/create-tags/#{URI.encode(file_system_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 204) end @doc """ Deletes the specified access point. After deletion is complete, new clients can no longer connect to the access points. Clients connected to the access point at the time of deletion will continue to function until they terminate their connection. This operation requires permissions for the `elasticfilesystem:DeleteAccessPoint` action. """ def delete_access_point(client, access_point_id, input, options \\ []) do path_ = "/2015-02-01/access-points/#{URI.encode(access_point_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes a file system, permanently severing access to its contents. Upon return, the file system no longer exists and you can't access any contents of the deleted file system. You can't delete a file system that is in use. That is, if the file system has any mount targets, you must first delete them. For more information, see `DescribeMountTargets` and `DeleteMountTarget`. <note> The `DeleteFileSystem` call returns while the file system state is still `deleting`. You can check the file system deletion status by calling the `DescribeFileSystems` operation, which returns a list of file systems in your account. If you pass file system ID or creation token for the deleted file system, the `DescribeFileSystems` returns a `404 FileSystemNotFound` error. </note> This operation requires permissions for the `elasticfilesystem:DeleteFileSystem` action. """ def delete_file_system(client, file_system_id, input, options \\ []) do path_ = "/2015-02-01/file-systems/#{URI.encode(file_system_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes the `FileSystemPolicy` for the specified file system. The default `FileSystemPolicy` goes into effect once the existing policy is deleted. For more information about the default file system policy, see [Using Resource-based Policies with EFS](https://docs.aws.amazon.com/efs/latest/ug/res-based-policies-efs.html). This operation requires permissions for the `elasticfilesystem:DeleteFileSystemPolicy` action. """ def delete_file_system_policy(client, file_system_id, input, options \\ []) do path_ = "/2015-02-01/file-systems/#{URI.encode(file_system_id)}/policy" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 200) end @doc """ Deletes the specified mount target. This operation forcibly breaks any mounts of the file system by using the mount target that is being deleted, which might disrupt instances or applications using those mounts. To avoid applications getting cut off abruptly, you might consider unmounting any mounts of the mount target, if feasible. The operation also deletes the associated network interface. Uncommitted writes might be lost, but breaking a mount target using this operation does not corrupt the file system itself. The file system you created remains. You can mount an EC2 instance in your VPC by using another mount target. This operation requires permissions for the following action on the file system: <ul> <li> `elasticfilesystem:DeleteMountTarget` </li> </ul> <note> The `DeleteMountTarget` call returns while the mount target state is still `deleting`. You can check the mount target deletion by calling the `DescribeMountTargets` operation, which returns a list of mount target descriptions for the given file system. </note> The operation also requires permissions for the following Amazon EC2 action on the mount target's network interface: <ul> <li> `ec2:DeleteNetworkInterface` </li> </ul> """ def delete_mount_target(client, mount_target_id, input, options \\ []) do path_ = "/2015-02-01/mount-targets/#{URI.encode(mount_target_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes the specified tags from a file system. If the `DeleteTags` request includes a tag key that doesn't exist, Amazon EFS ignores it and doesn't cause an error. For more information about tags and related restrictions, see [Tag Restrictions](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) in the *AWS Billing and Cost Management User Guide*. This operation requires permissions for the `elasticfilesystem:DeleteTags` action. """ def delete_tags(client, file_system_id, input, options \\ []) do path_ = "/2015-02-01/delete-tags/#{URI.encode(file_system_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 204) end @doc """ Returns the description of a specific Amazon EFS access point if the `AccessPointId` is provided. If you provide an EFS `FileSystemId`, it returns descriptions of all access points for that file system. You can provide either an `AccessPointId` or a `FileSystemId` in the request, but not both. This operation requires permissions for the `elasticfilesystem:DescribeAccessPoints` action. """ def describe_access_points(client, access_point_id \\ nil, file_system_id \\ nil, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/2015-02-01/access-points" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"NextToken", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"MaxResults", max_results} | query_] else query_ end query_ = if !is_nil(file_system_id) do [{"FileSystemId", file_system_id} | query_] else query_ end query_ = if !is_nil(access_point_id) do [{"AccessPointId", access_point_id} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Returns the backup policy for the specified EFS file system. """ def describe_backup_policy(client, file_system_id, options \\ []) do path_ = "/2015-02-01/file-systems/#{URI.encode(file_system_id)}/backup-policy" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Returns the `FileSystemPolicy` for the specified EFS file system. This operation requires permissions for the `elasticfilesystem:DescribeFileSystemPolicy` action. """ def describe_file_system_policy(client, file_system_id, options \\ []) do path_ = "/2015-02-01/file-systems/#{URI.encode(file_system_id)}/policy" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Returns the description of a specific Amazon EFS file system if either the file system `CreationToken` or the `FileSystemId` is provided. Otherwise, it returns descriptions of all file systems owned by the caller's AWS account in the AWS Region of the endpoint that you're calling. When retrieving all file system descriptions, you can optionally specify the `MaxItems` parameter to limit the number of descriptions in a response. Currently, this number is automatically set to 10. If more file system descriptions remain, Amazon EFS returns a `NextMarker`, an opaque token, in the response. In this case, you should send a subsequent request with the `Marker` request parameter set to the value of `NextMarker`. To retrieve a list of your file system descriptions, this operation is used in an iterative process, where `DescribeFileSystems` is called first without the `Marker` and then the operation continues to call it with the `Marker` parameter set to the value of the `NextMarker` from the previous response until the response has no `NextMarker`. The order of file systems returned in the response of one `DescribeFileSystems` call and the order of file systems returned across the responses of a multi-call iteration is unspecified. This operation requires permissions for the `elasticfilesystem:DescribeFileSystems` action. """ def describe_file_systems(client, creation_token \\ nil, file_system_id \\ nil, marker \\ nil, max_items \\ nil, options \\ []) do path_ = "/2015-02-01/file-systems" headers = [] query_ = [] query_ = if !is_nil(max_items) do [{"MaxItems", max_items} | query_] else query_ end query_ = if !is_nil(marker) do [{"Marker", marker} | query_] else query_ end query_ = if !is_nil(file_system_id) do [{"FileSystemId", file_system_id} | query_] else query_ end query_ = if !is_nil(creation_token) do [{"CreationToken", creation_token} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Returns the current `LifecycleConfiguration` object for the specified Amazon EFS file system. EFS lifecycle management uses the `LifecycleConfiguration` object to identify which files to move to the EFS Infrequent Access (IA) storage class. For a file system without a `LifecycleConfiguration` object, the call returns an empty array in the response. This operation requires permissions for the `elasticfilesystem:DescribeLifecycleConfiguration` operation. """ def describe_lifecycle_configuration(client, file_system_id, options \\ []) do path_ = "/2015-02-01/file-systems/#{URI.encode(file_system_id)}/lifecycle-configuration" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Returns the security groups currently in effect for a mount target. This operation requires that the network interface of the mount target has been created and the lifecycle state of the mount target is not `deleted`. This operation requires permissions for the following actions: <ul> <li> `elasticfilesystem:DescribeMountTargetSecurityGroups` action on the mount target's file system. </li> <li> `ec2:DescribeNetworkInterfaceAttribute` action on the mount target's network interface. </li> </ul> """ def describe_mount_target_security_groups(client, mount_target_id, options \\ []) do path_ = "/2015-02-01/mount-targets/#{URI.encode(mount_target_id)}/security-groups" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Returns the descriptions of all the current mount targets, or a specific mount target, for a file system. When requesting all of the current mount targets, the order of mount targets returned in the response is unspecified. This operation requires permissions for the `elasticfilesystem:DescribeMountTargets` action, on either the file system ID that you specify in `FileSystemId`, or on the file system of the mount target that you specify in `MountTargetId`. """ def describe_mount_targets(client, access_point_id \\ nil, file_system_id \\ nil, marker \\ nil, max_items \\ nil, mount_target_id \\ nil, options \\ []) do path_ = "/2015-02-01/mount-targets" headers = [] query_ = [] query_ = if !is_nil(mount_target_id) do [{"MountTargetId", mount_target_id} | query_] else query_ end query_ = if !is_nil(max_items) do [{"MaxItems", max_items} | query_] else query_ end query_ = if !is_nil(marker) do [{"Marker", marker} | query_] else query_ end query_ = if !is_nil(file_system_id) do [{"FileSystemId", file_system_id} | query_] else query_ end query_ = if !is_nil(access_point_id) do [{"AccessPointId", access_point_id} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Returns the tags associated with a file system. The order of tags returned in the response of one `DescribeTags` call and the order of tags returned across the responses of a multiple-call iteration (when using pagination) is unspecified. This operation requires permissions for the `elasticfilesystem:DescribeTags` action. """ def describe_tags(client, file_system_id, marker \\ nil, max_items \\ nil, options \\ []) do path_ = "/2015-02-01/tags/#{URI.encode(file_system_id)}/" headers = [] query_ = [] query_ = if !is_nil(max_items) do [{"MaxItems", max_items} | query_] else query_ end query_ = if !is_nil(marker) do [{"Marker", marker} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Lists all tags for a top-level EFS resource. You must provide the ID of the resource that you want to retrieve the tags for. This operation requires permissions for the `elasticfilesystem:DescribeAccessPoints` action. """ def list_tags_for_resource(client, resource_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/2015-02-01/resource-tags/#{URI.encode(resource_id)}" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"NextToken", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"MaxResults", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Modifies the set of security groups in effect for a mount target. When you create a mount target, Amazon EFS also creates a new network interface. For more information, see `CreateMountTarget`. This operation replaces the security groups in effect for the network interface associated with a mount target, with the `SecurityGroups` provided in the request. This operation requires that the network interface of the mount target has been created and the lifecycle state of the mount target is not `deleted`. The operation requires permissions for the following actions: <ul> <li> `elasticfilesystem:ModifyMountTargetSecurityGroups` action on the mount target's file system. </li> <li> `ec2:ModifyNetworkInterfaceAttribute` action on the mount target's network interface. </li> </ul> """ def modify_mount_target_security_groups(client, mount_target_id, input, options \\ []) do path_ = "/2015-02-01/mount-targets/#{URI.encode(mount_target_id)}/security-groups" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 204) end @doc """ Updates the file system's backup policy. Use this action to start or stop automatic backups of the file system. """ def put_backup_policy(client, file_system_id, input, options \\ []) do path_ = "/2015-02-01/file-systems/#{URI.encode(file_system_id)}/backup-policy" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 200) end @doc """ Applies an Amazon EFS `FileSystemPolicy` to an Amazon EFS file system. A file system policy is an IAM resource-based policy and can contain multiple policy statements. A file system always has exactly one file system policy, which can be the default policy or an explicit policy set or updated using this API operation. When an explicit policy is set, it overrides the default policy. For more information about the default file system policy, see [Default EFS File System Policy](https://docs.aws.amazon.com/efs/latest/ug/iam-access-control-nfs-efs.html#default-filesystempolicy). This operation requires permissions for the `elasticfilesystem:PutFileSystemPolicy` action. """ def put_file_system_policy(client, file_system_id, input, options \\ []) do path_ = "/2015-02-01/file-systems/#{URI.encode(file_system_id)}/policy" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 200) end @doc """ Enables lifecycle management by creating a new `LifecycleConfiguration` object. A `LifecycleConfiguration` object defines when files in an Amazon EFS file system are automatically transitioned to the lower-cost EFS Infrequent Access (IA) storage class. A `LifecycleConfiguration` applies to all files in a file system. Each Amazon EFS file system supports one lifecycle configuration, which applies to all files in the file system. If a `LifecycleConfiguration` object already exists for the specified file system, a `PutLifecycleConfiguration` call modifies the existing configuration. A `PutLifecycleConfiguration` call with an empty `LifecyclePolicies` array in the request body deletes any existing `LifecycleConfiguration` and disables lifecycle management. In the request, specify the following: <ul> <li> The ID for the file system for which you are enabling, disabling, or modifying lifecycle management. </li> <li> A `LifecyclePolicies` array of `LifecyclePolicy` objects that define when files are moved to the IA storage class. The array can contain only one `LifecyclePolicy` item. </li> </ul> This operation requires permissions for the `elasticfilesystem:PutLifecycleConfiguration` operation. To apply a `LifecycleConfiguration` object to an encrypted file system, you need the same AWS Key Management Service (AWS KMS) permissions as when you created the encrypted file system. """ def put_lifecycle_configuration(client, file_system_id, input, options \\ []) do path_ = "/2015-02-01/file-systems/#{URI.encode(file_system_id)}/lifecycle-configuration" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 200) end @doc """ Creates a tag for an EFS resource. You can create tags for EFS file systems and access points using this API operation. This operation requires permissions for the `elasticfilesystem:TagResource` action. """ def tag_resource(client, resource_id, input, options \\ []) do path_ = "/2015-02-01/resource-tags/#{URI.encode(resource_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Removes tags from an EFS resource. You can remove tags from EFS file systems and access points using this API operation. This operation requires permissions for the `elasticfilesystem:UntagResource` action. """ def untag_resource(client, resource_id, input, options \\ []) do path_ = "/2015-02-01/resource-tags/#{URI.encode(resource_id)}" headers = [] {query_, input} = [ {"TagKeys", "tagKeys"}, ] |> AWS.Request.build_params(input) request(client, :delete, path_, query_, headers, input, options, 200) end @doc """ Updates the throughput mode or the amount of provisioned throughput of an existing file system. """ def update_file_system(client, file_system_id, input, options \\ []) do path_ = "/2015-02-01/file-systems/#{URI.encode(file_system_id)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 202) end @spec request(AWS.Client.t(), binary(), binary(), list(), list(), map(), list(), pos_integer()) :: {:ok, Poison.Parser.t(), Poison.Response.t()} | {:error, Poison.Parser.t()} | {:error, HTTPoison.Error.t()} defp request(client, method, path, query, headers, input, options, success_status_code) do client = %{client | service: "elasticfilesystem"} host = build_host("elasticfilesystem", client) url = host |> build_url(path, client) |> add_query(query) additional_headers = [{"Host", host}, {"Content-Type", "application/x-amz-json-1.1"}] headers = AWS.Request.add_headers(additional_headers, headers) payload = encode_payload(input) headers = AWS.Request.sign_v4(client, method, url, headers, payload) perform_request(method, url, payload, headers, options, success_status_code) end defp perform_request(method, url, payload, headers, options, nil) do case HTTPoison.request(method, url, payload, headers, options) do {:ok, %HTTPoison.Response{status_code: 200, body: ""} = response} -> {:ok, response} {:ok, %HTTPoison.Response{status_code: status_code, body: body} = response} when status_code == 200 or status_code == 202 or status_code == 204 -> {:ok, Poison.Parser.parse!(body, %{}), response} {:ok, %HTTPoison.Response{body: body}} -> error = Poison.Parser.parse!(body, %{}) {:error, error} {:error, %HTTPoison.Error{reason: reason}} -> {:error, %HTTPoison.Error{reason: reason}} end end defp perform_request(method, url, payload, headers, options, success_status_code) do case HTTPoison.request(method, url, payload, headers, options) do {:ok, %HTTPoison.Response{status_code: ^success_status_code, body: ""} = response} -> {:ok, %{}, response} {:ok, %HTTPoison.Response{status_code: ^success_status_code, body: body} = response} -> {:ok, Poison.Parser.parse!(body, %{}), response} {:ok, %HTTPoison.Response{body: body}} -> error = Poison.Parser.parse!(body, %{}) {:error, error} {:error, %HTTPoison.Error{reason: reason}} -> {:error, %HTTPoison.Error{reason: reason}} end end defp build_host(_endpoint_prefix, %{region: "local"}) do "localhost" end defp build_host(endpoint_prefix, %{region: region, endpoint: endpoint}) do "#{endpoint_prefix}.#{region}.#{endpoint}" end defp build_url(host, path, %{:proto => proto, :port => port}) do "#{proto}://#{host}:#{port}#{path}" end defp add_query(url, []) do url end defp add_query(url, query) do querystring = AWS.Util.encode_query(query) "#{url}?#{querystring}" end defp encode_payload(input) do if input != nil, do: Poison.Encoder.encode(input, %{}), else: "" end end
lib/aws/efs.ex
0.893555
0.637539
efs.ex
starcoder
defmodule Request.Validator.Plug do alias Plug.Conn alias Ecto.Changeset alias Request.Validator alias Request.Validator.{DefaultRules, Rules, Rules.Array, Rules.Map_} import Plug.Conn @doc ~S""" Init the Request.Validator.Plug with an optional error callback and handlers with their corresponding request validator module. ```elixir plug Request.Validator.Plug, register: App.Requests.RegisterRequest, on_error: fn conn, errors -> json_resp(conn, "Handle your errors: #{inspect errors}") end ``` """ def init(opts) when is_map(opts), do: init(Keyword.new(opts)) def init(opts) do opts |> Keyword.put_new(:on_error, &Validator.Plug.on_error/2) end @doc ~S""" The default callback to be invoked when there is a param that fails validation. """ def on_error(conn, errors) do json_resp(conn, 422, %{message: "Unprocessable entity", errors: errors}) |> halt() end defp unauthorized(conn) do json_resp(conn, 403, %{message: "Forbidden"}) |> halt end @doc ~S""" Performs validations on `conn.params` If all validations are successful returns the connection struct Otherwise returns an error map in the following structure: `%{param: ["some error", ...]}` Will call the given `on_error` callback in case some validation failed """ def call(conn, opts) do with action <- Map.get(conn.private, :phoenix_action), request_validator <- get_validator(opts, action) do case request_validator do nil -> conn _ -> validate(Conn.fetch_query_params(conn), request_validator, opts[:on_error]) end end end defp get_validator(opt, key) when is_map(opt), do: Map.get(opt, key) defp get_validator(opt, key) when is_list(opt), do: Keyword.get(opt, key) defp validate(conn, module, on_error) do module = load_module(module) rules = cond do function_exported?(module, :rules, 1) -> module.rules(conn) function_exported?(module, :rules, 0) -> module.rules() end errors = collect_errors(conn.params, rules) cond do not module.authorize(conn) -> unauthorized(conn) Enum.empty?(errors) -> conn true -> on_error.(conn, errors) end end defp collect_errors(_, %Ecto.Changeset{} = changeset) do Changeset.traverse_errors(changeset, fn {key, errors} -> Enum.reduce(errors, key, fn {key, value}, acc -> String.replace(acc, "%{#{key}}", to_string(value)) end) end) end defp collect_errors(params, validations) do Enum.reduce(validations, %{}, errors_collector(params)) end defp errors_collector(params) do fn {field, %Rules.Bail{rules: rules}}, acc -> value = Map.get(params, to_string(field)) result = Enum.find_value(rules, nil, fn callback -> case run_rule(callback, value, field, params, acc) do :ok -> nil a -> a end end) case is_binary(result) do true -> Map.put(acc, field, [result]) _ -> acc end {field, %Array{attrs: rules}}, acc -> value = Map.get(params, to_string(field)) with true <- is_list(value), result <- Enum.map(value, &collect_errors(&1, rules)) do # result <- Enum.reject(result, &Enum.empty?/1) do result = result |> Enum.map(fn val -> index = Enum.find_index(result, &(val == &1)) if Enum.empty?(val) do nil else {index, val} end end) |> Enum.reject(&is_nil/1) |> Enum.reduce(%{}, fn {index, errors}, acc -> errors = errors |> Enum.map(fn {key, val} -> {"#{field}.#{index}.#{key}", val} end) |> Enum.into(%{}) Map.merge(acc, errors) end) Map.merge(acc, result) else _ -> Map.put(acc, field, ["This field is expected to be an array."]) end {field, %Map_{attrs: rules, nullable: nullable}}, acc -> value = Map.get(params, to_string(field)) with %{} <- value, result <- collect_errors(value, rules), {true, _} <- {Enum.empty?(result), result} do acc else {false, result} -> result = result |> Enum.map(fn {key, val} -> {"#{field}.#{key}", val} end) |> Enum.into(%{}) Map.merge(acc, result) val -> cond do nullable && is_nil(val) -> acc true -> Map.put(acc, field, ["This field is expected to be a map."]) end end {field, vf}, acc -> value = Map.get(params, to_string(field)) case run_rules(vf, value, field, params, acc) do {:error, errors} -> Map.put(acc, field, errors) _ -> acc end end end defp run_rule(callback, value, field, fields, errors) do opts = [field: field, fields: fields, errors: errors] module = rules_module() {callback, args} = case callback do cb when is_atom(cb) -> {cb, [value, opts]} {cb, params} when is_atom(cb) -> {cb, [value, params, opts]} end case apply(module, :run_rule, [callback] ++ args) do :ok -> true {:error, msg} -> msg end end defp run_rules(rules, value, field, fields, errors) do results = Enum.map(rules, fn callback -> run_rule(callback, value, field, fields, errors) end) |> Enum.filter(&is_binary/1) if Enum.empty?(results), do: nil, else: {:error, results} end defp json_resp(conn, status, body) do conn |> put_resp_header("content-type", "application/json") |> send_resp(status, json_library().encode_to_iodata!(body)) end defp json_library do Application.get_env(:request_validator, :json_library, Jason) end defp load_module(module) do case Code.ensure_loaded(module) do {:module, mod} -> mod {:error, reason} -> raise ArgumentError, "Could not load #{module}, reason: #{reason}" end end defp rules_module, do: Application.get_env(:request_validator, :rules_module, DefaultRules) end
lib/plug.ex
0.734215
0.455804
plug.ex
starcoder
defmodule Lab42.StateMachine.Runner do use Lab42.StateMachine.Types @moduledoc """ Runs the state machine by finding and executing transitions """ @doc false @spec run( state_t(), list(), list(), any(), transition_map_t() ) :: result_t() def run(current_state, input, result, data, state_definitions) def run(current_state, [], result, data, _), do: {current_state, Enum.reverse(result), data} def run(current_state, input, result, data, states) do # insp {:run, current_state, input, result, data} case Map.get(states, current_state) do nil -> {:error, "No transitions found for current state", current_state} transitions -> _run_transitions(current_state, transitions, input, result, data, states) end end @doc """ Convenience transformer function to stop the state machine, can be used with the atom `:halt` """ @spec halt_transfo( any() ) :: :halt def halt_transfo(_), do: :halt @doc """ Convenience function to push an input to the output without changing it, can be used with the atom `:id` in the transformer position of a transition, e.g. `{~r{alpha}, :id, fn count, _ -> count + 1 end}` """ @spec ident_transfo( match_t() ) :: any() def ident_transfo({_, line}), do: line @doc """ Convenience function to not change the data. It can be used with the atom `:id` in the updater position of a transition, e.g. `{~r{alpha}, fn {_, line} -> String.reverse(line), :id}` """ @spec ident_updater( any(), any() ) :: any() def ident_updater(data, _), do: data @doc """ Convenience function to ignore an input, it can be used with the atom `:ignore` in the transformer position of a transition, e.g. `{~r{alpha}, :ignore, fn count, _ -> count + 1 end}` """ @spec ignore_input( any() ) :: :ignore def ignore_input(_), do: :ignore @spec _execute_transition( transition_t(), any(), any(), any() ) :: {state_t(), any(), any()} defp _execute_transition(transition, matches, input, data) defp _execute_transition({_, transformer, updater, new_state}, matches, input, data) do transformed = transformer.({matches, input}) updated = updater.(data, {matches, input}) {new_state, transformed, updated} end @spec _match_trigger( trigger_t(), any() ) :: any() defp _match_trigger(trigger, input) defp _match_trigger(true, _), do: [] defp _match_trigger(fn_trigger, input) when is_function(fn_trigger), do: fn_trigger.(input) defp _match_trigger(rgx_trigger, input), do: Regex.run(rgx_trigger, input) @spec _normalize_transition( incomplete_transition_t(), state_t() ) :: transition_t() defp _normalize_transition(transition, current_state) defp _normalize_transition({trigger}, current_state), do: {trigger, &ident_transfo/1, &ident_updater/2, current_state} defp _normalize_transition({trigger, f1}, current_state), do: _replace_symbolic_fns({trigger, f1, &ident_updater/2, current_state}) defp _normalize_transition({trigger, f1, f2}, current_state), do: _replace_symbolic_fns({trigger, f1, f2, current_state}) defp _normalize_transition(already_normalized, _current_state), do: _replace_symbolic_fns(already_normalized) @predefined_transformers %{ halt: &__MODULE__.halt_transfo/1, id: &__MODULE__.ident_transfo/1, ignore: &__MODULE__.ignore_input/1, } @predefined_updaters %{ id: &__MODULE__.ident_updater/2 } @spec _replace_symbolic_fns( incomplete_transition_t() ) :: transition_t() defp _replace_symbolic_fns(transition) defp _replace_symbolic_fns({trigger, f1, f2, state}) when is_atom(f1) do _replace_symbolic_fns({trigger, Map.fetch!(@predefined_transformers, f1), f2, state}) end defp _replace_symbolic_fns({trigger, f1, f2, state}) when is_atom(f2) do _replace_symbolic_fns({trigger, f1, Map.fetch!(@predefined_updaters, f2), state}) end defp _replace_symbolic_fns(really_ok_now), do: really_ok_now @spec _run_normalized_transitions( state_t(), normalized_transitions_t(), list(), list(), any(), map() ) :: result_t() defp _run_normalized_transitions(current_state, transitions, input, result, data, states) defp _run_normalized_transitions(current_state, [{trigger,_,_,_}=tran|trans], [input|rest], result, data, states) do # insp {:run_norm, current_state, tran, input, result, data} if matches = _match_trigger(trigger, input) do _execute_transition(tran, matches, input, data) |> _loop(rest, result, states) else _run_transitions(current_state, trans, [input|rest], result, data, states) end end @spec _run_transitions( state_t(), list(incomplete_transition_t()), list(), list(), any(), map() ) :: result_t() defp _run_transitions(current_state, transitions, input, result, data, states) defp _run_transitions(current_state, [], [input|_], _result, _data, _states) do # It is preferable to not allow this, so that an explicit `true` trigger needs to be # defined. One might later add an option `default_copy: true` to shorten the transition # definitions if so is wished. {:error, "No trigger matched the current input #{inspect input}", current_state} end defp _run_transitions(current_state, [tran|trans], input, result, data, states) do # insp {:run_tr, current_state, tran, input, result, data} _run_normalized_transitions(current_state, [_normalize_transition(tran, current_state)|trans], input, result, data, states) end @spec _loop( {state_t(), any(), any()}, list(), list(), map() ) :: result_t() defp _loop(new_data_triple, rest, result, states) defp _loop({new_state, :halt, updated}, _rest, result, _states) do # Trigger halt with empty input run(new_state, [], result, updated, %{}) end defp _loop({new_state, {:halt, value}, updated}, _rest, result, _states) do # Trigger halt with empty input run(new_state, [], [value|result], updated, %{}) end defp _loop({new_state, :ignore, updated}, rest, result, states) do run(new_state, rest, result, updated, states) end defp _loop({new_state, {:push, transformed}, updated}, rest, result, states) do run(new_state, rest, [transformed|result], updated, states) end defp _loop({new_state, transformed, updated}, rest, result, states) do run(new_state, rest, [transformed|result], updated, states) end # TODO: Remove for release # defp insp(data) do # if System.get_env("DEBUG") do # IO.inspect data # end # end end
lib/lab42/state_machine/runner.ex
0.832883
0.635491
runner.ex
starcoder
require Math defmodule BloomFilter do @moduledoc """ Bloom Filter implementation in Elixir. Bloom filters are probabilistic data structures designed to efficiently tell you whether an element is present in a set. ## Usage Example iex> f = BloomFilter.new 100, 0.001 iex> f = BloomFilter.add(f, 42) iex> BloomFilter.has?(f, 42) true """ defstruct [:bits, :num_bits, :capacity, :error_rate, :hash_functions] @type bit :: 0 | 1 @type hash_func :: (any -> pos_integer) @type t :: %BloomFilter{ bits: [bit, ...], num_bits: pos_integer, capacity: pos_integer, error_rate: float, hash_functions: [hash_func, ...] } @doc """ Creates a new bloom filter, given an estimated number of elements and a desired error rate (0.0..1). """ @spec new(pos_integer, float) :: t def new(capacity, error_rate) when error_rate > 0 and error_rate < 1 do {m, k, _} = optimize(capacity, error_rate) bits = for _ <- 1..m, do: 0 hash_functions = make_hashes(m, k) %BloomFilter{ bits: bits, num_bits: m, capacity: capacity, error_rate: error_rate, hash_functions: hash_functions } end @doc """ Checks whether a given item is likely to exist in the set. """ @spec has?(t, any) :: boolean def has?(%BloomFilter{bits: bits, hash_functions: hash_functions}, item) do item_bits = hash(hash_functions, item) item_bits |> Enum.map(fn x -> Enum.at(bits, x) end) |> Enum.all?(fn x -> x == 1 end) end @doc """ Adds a given item to the set. """ @spec add(t, any) :: t def add(%BloomFilter{bits: bits, hash_functions: hash_functions} = bloom, item) do item_bits = hash(hash_functions, item) new_bits = item_bits |> Enum.reduce(bits, fn index, vector -> List.replace_at(vector, index, 1) end) %{bloom | bits: new_bits} end @doc """ Approximates the number of items in the filter. """ @spec count(t) :: float def count(%BloomFilter{bits: bits, num_bits: num_bits, hash_functions: hash_functions}) do num_truthy_bits = Enum.count(bits, fn x -> x == 1 end) approximate_size(num_bits, Enum.count(hash_functions), num_truthy_bits) end # Approximates the number of items in the filter with m bits, k hash functions, # and x bits set to 1. # https://en.wikipedia.org/wiki/Bloom_filter#Approximating_the_number_of_items_in_a_Bloom_filter @spec approximate_size(pos_integer, pos_integer, non_neg_integer) :: float defp approximate_size(m, k, x) do -(m * Math.log(1 - x / m, Math.e())) / k end # Calculates the false positive rate given m bits, n elements, and k hash functions # https://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives @spec false_positive_rate(pos_integer, pos_integer, number) :: float defp false_positive_rate(m, n, k) do Math.pow(1 - Math.pow(Math.e(), -k * (n + 0.5) / (m - 1)), k) end # Calculates the optimal number of hash functions k given m bits and capacity n # https://en.wikipedia.org/wiki/Bloom_filter#Optimal_number_of_hash_functions @spec optimal_hash_functions(pos_integer, pos_integer) :: float defp optimal_hash_functions(m, n) do m / n * Math.log(Math.e(), 2) end # Calculates optimal bloom filter size m and number of hash functions k @spec optimize(pos_integer, float) :: {pos_integer, pos_integer, float} defp optimize(n, error_rate) do optimize_values(n, n * 4, 2, error_rate) end # Recursively calculates the optimal bloom filter parameters until the desired # error rate is attained @spec optimize_values(pos_integer, pos_integer, number, float) :: {pos_integer, integer, float} defp optimize_values(n, m, k, required_error_rate) do error_rate = false_positive_rate(m, n, k) acceptable_error_rate? = error_rate < required_error_rate cond do acceptable_error_rate? -> {m, k |> Float.ceil() |> round, error_rate} true -> optimize_values(n, m * 2, optimal_hash_functions(m * 2, n), error_rate) end end # Generates k hash functions @spec make_hashes(pos_integer, pos_integer) :: [hash_func, ...] defp make_hashes(m, k) do Enum.map(1..k, fn i -> make_hash_i(i, m) end) end # Generates a new i-th hash function for a filter of size m bits # https://en.wikipedia.org/wiki/Double_hashing # https://en.wikipedia.org/wiki/Fowler-Noll-Vo_hash_function @spec make_hash_i(pos_integer, pos_integer) :: hash_func defp make_hash_i(i, m) do fn item -> rem( :erlang.phash2(item, Math.pow(2, 32)) + i * FNV.FNV1a.hash(Kernel.inspect(item), 128), m ) end end # Returns a list of the result of applying every function in hash_functions to item @spec hash([hash_func, ...], any) :: [pos_integer, ...] defp hash(hash_functions, item) do Enum.map(hash_functions, fn h -> h.(item) end) end end
lib/bloom_filter.ex
0.934163
0.656163
bloom_filter.ex
starcoder
defmodule Tanx.ContinuousGame.Impl do @default_player_timeout 60.0 defstruct( maze: nil, player_timeout: @default_player_timeout, player_handles: %{}, players: %{}, player_id_map: %{} ) end defimpl Tanx.Game.Variant, for: Tanx.ContinuousGame.Impl do require Logger @tank_starting_armor 2.0 @tank_explosion_intensity 1.0 @tank_explosion_radius 1.0 @tank_explosion_length 0.6 @missile_velocity 10.0 @missile_impact_intensity 1.0 @missile_explosion_intensity 0.25 @missile_explosion_radius 0.5 @missile_explosion_length 0.4 @self_destruct_explosion_intensity 4.0 @self_destruct_explosion_radius 2.5 @self_destruct_explosion_length 1.0 @power_up_lifetime 10.0 alias Tanx.ContinuousGame.Impl alias Tanx.ContinuousGame.Player alias Tanx.ContinuousGame.PlayerPrivate alias Tanx.ContinuousGame.PlayersChanged def init_arena(data, _time) do arena = Tanx.ContinuousGame.Mazes.get(data.maze) %Tanx.Game.Arena{arena | tanks: %{}, missiles: %{}, explosions: %{}, power_ups: %{}} end def control(data, arena, _time, {:view_static}) do view = %Tanx.ContinuousGame.StaticView{ size: arena.size, walls: arena.walls, entry_points: arena.entry_points } {{:ok, view}, data, [], []} end def control(data, _arena, _time, {:view_players, player_handle}) do view = %Tanx.ContinuousGame.PlayerListView{ players: data.players, cur_player: Map.get(data.player_handles, player_handle) } {{:ok, view}, data, [], []} end def control(data, arena, time, {:view_arena, player_handle}) do player_handles = data.player_handles player_private = Map.get(player_handles, player_handle) view = %Tanx.ContinuousGame.ArenaView{ entry_points: arena.entry_points, tanks: arena.tanks, missiles: arena.missiles, explosions: arena.explosions, power_ups: arena.power_ups, players: data.players, cur_player: player_private } new_data = if player_private == nil do data else new_player_private = %PlayerPrivate{player_private | last_seen_at: time} new_player_handles = Map.put(player_handles, player_handle, new_player_private) %Impl{data | player_handles: new_player_handles} end {{:ok, view}, new_data, [], []} end def control(data, _arena, time, {:add_player, name}) do player_handles = data.player_handles players = data.players player_handle = Tanx.Util.ID.create("H", player_handles, 8) player_id = Tanx.Util.ID.create("P", players) player = %Player{name: name, joined_at: time} player_private = %PlayerPrivate{player_id: player_id, last_seen_at: time} new_players = Map.put(players, player_id, player) new_player_handles = Map.put(player_handles, player_handle, player_private) new_player_id_map = Map.put(data.player_id_map, player_id, player_handle) data = %Impl{ data | player_handles: new_player_handles, players: new_players, player_id_map: new_player_id_map } notification = %PlayersChanged{players: new_players} {{:ok, player_handle}, data, [], [notification]} end def control(data, _arena, _time, {:remove_player, player_handle}) do if Map.has_key?(data.player_handles, player_handle) do {new_data, commands, notification} = remove_player(data, player_handle, [], nil) notifications = if notification, do: [notification], else: [] {{:ok, player_handle}, new_data, commands, notifications} else {{:error, :player_not_found, [player_handle: player_handle]}, data, [], []} end end def control(data, _arena, _time, {:rename_player, player_handle, name}) do player_handles = data.player_handles players = data.players if Map.has_key?(player_handles, player_handle) do player_private = Map.fetch!(player_handles, player_handle) player_id = player_private.player_id player = Map.fetch!(players, player_id) new_player = %Player{player | name: name} new_players = Map.put(players, player_id, new_player) new_data = %Impl{data | players: new_players} event = %PlayersChanged{players: new_players} {{:ok, player_handle}, new_data, [], [event]} else {{:error, :player_not_found, [player_handle: player_handle]}, data, [], []} end end def control(data, _arena, _time, {:start_tank, player_handle, entry_point_name}) do player_handles = data.player_handles if Map.has_key?(player_handles, player_handle) do player_private = Map.fetch!(player_handles, player_handle) tank_id = player_private.tank_id player_id = player_private.player_id case tank_id do nil -> new_player_private = %PlayerPrivate{player_private | tank_id: true} new_player_handles = Map.put(player_handles, player_handle, new_player_private) command = %Tanx.Game.Commands.CreateTank{ entry_point_name: entry_point_name, armor: @tank_starting_armor, max_armor: @tank_starting_armor, explosion_intensity: @tank_explosion_intensity, explosion_radius: @tank_explosion_radius, explosion_length: @tank_explosion_length, data: %{player_id: player_id}, event_data: %{player_handle: player_handle} } {:ok, %Impl{data | player_handles: new_player_handles}, [command], []} true -> {{:error, :tank_being_created, [player_handle: player_handle]}, data, [], []} id -> {{:error, :tank_already_present, [player_handle: player_handle, tank_id: id]}, data, [], []} end else {{:error, :player_not_found, [player_handle: player_handle]}, data, [], []} end end def control(data, _arena, time, {:control_tank, player_handle, :fire, true}) do player_handles = data.player_handles if Map.has_key?(player_handles, player_handle) do player_private = Map.fetch!(player_handles, player_handle) tank_id = player_private.tank_id reloaded_at = player_private.reloaded_at cond do reloaded_at > time -> {{:error, :tank_not_loaded, [time_needed: reloaded_at - time]}, data, [], []} tank_id == nil || tank_id == true -> {{:error, :tank_not_found, [player_handle: player_handle]}, data, [], []} true -> command = %Tanx.Game.Commands.FireMissile{ tank_id: tank_id, velocity: @missile_velocity, bounce: player_private.bounce, impact_intensity: @missile_impact_intensity, explosion_intensity: @missile_explosion_intensity, explosion_radius: @missile_explosion_radius, explosion_length: @missile_explosion_length, chain_data: %{originator_id: player_private.player_id} } new_player_private = %PlayerPrivate{ player_private | reloaded_at: time + player_private.reload_length } new_player_handles = Map.put(player_handles, player_handle, new_player_private) {:ok, %Impl{data | player_handles: new_player_handles}, [command], []} end else {{:error, :player_not_found, [player_handle: player_handle]}, data, [], []} end end def control(data, _arena, _time, {:control_tank, _player_handle, :fire, false}) do {:ok, data, [], []} end def control(data, _arena, _time, {:control_tank, player_handle, button, is_down}) do player_handles = data.player_handles if Map.has_key?(player_handles, player_handle) do player_private = Map.fetch!(player_handles, player_handle) tank_id = player_private.tank_id if tank_id == nil || tank_id == true do {{:error, :tank_not_found, [player_handle: player_handle]}, data, [], []} else new_player_private = Map.put(player_private, button, is_down) velocity = calc_velocity( new_player_private.forward, new_player_private.backward, new_player_private.forward_speed, new_player_private.backward_speed ) angular_velocity = calc_angular_velocity( new_player_private.left, new_player_private.right, new_player_private.angular_speed ) command = %Tanx.Game.Commands.SetTankVelocity{ id: tank_id, velocity: velocity, angular_velocity: angular_velocity } new_player_handles = Map.put(player_handles, player_handle, new_player_private) {:ok, %Impl{data | player_handles: new_player_handles}, [command], []} end else {{:error, :player_not_found, [player_handle: player_handle]}, data, [], []} end end def control(data, _arena, _time, {:destruct_tank, player_handle}) do player_handles = data.player_handles if Map.has_key?(player_handles, player_handle) do player_private = Map.fetch!(player_handles, player_handle) tank_id = player_private.tank_id if tank_id == nil || tank_id == true do {{:error, :tank_not_found, [player_handle: player_handle]}, data, [], []} else command = %Tanx.Game.Commands.ExplodeTank{ id: tank_id, explosion_intensity: @self_destruct_explosion_intensity, explosion_radius: @self_destruct_explosion_radius, explosion_length: @self_destruct_explosion_length, chain_data: %{originator_id: player_private.player_id} } {:ok, data, [command], []} end else {{:error, :player_not_found, [player_handle: player_handle]}, data, [], []} end end def event(data, %Tanx.Game.Events.ArenaUpdated{time: time}) do timeout = data.player_timeout {data, commands, notification} = Enum.reduce(data.player_handles, {data, [], nil}, fn {ph, pp}, {d, c, n} -> if time - pp.last_seen_at > timeout do remove_player(d, ph, c, n) else {d, c, n} end end) notifications = if notification, do: [notification], else: [] {data, commands, notifications} end def event(data, %Tanx.Game.Events.TankCreated{ id: tank_id, event_data: %{player_handle: player_handle} }) do player_handles = data.player_handles player_private = Map.fetch!(player_handles, player_handle) new_player_private = %PlayerPrivate{player_private | tank_id: tank_id} new_player_handles = Map.put(player_handles, player_handle, new_player_private) {%Impl{data | player_handles: new_player_handles}, [], []} end def event(data, %Tanx.Game.Events.TankDeleted{event_data: %{deleting_player_id: player_id}}) do new_players = Map.delete(data.players, player_id) notification = %PlayersChanged{players: new_players} {%Impl{data | players: new_players}, [], [notification]} end def event(data, %Tanx.Game.Events.TankDeleted{ tank: tank, event_data: %{originator_id: originator_id} }) do owner_id = tank.data[:player_id] players = data.players player_id_map = data.player_id_map player_handles = data.player_handles if Map.has_key?(player_id_map, owner_id) do owner_handle = Map.fetch!(player_id_map, owner_id) owner_private = Map.fetch!(player_handles, owner_handle) new_owner_private = %PlayerPrivate{owner_private | tank_id: nil, bounce: 0} new_player_handles = Map.put(player_handles, owner_handle, new_owner_private) owner = Map.fetch!(players, owner_id) new_owner = %Player{owner | deaths: owner.deaths + 1} new_players = Map.put(players, owner_id, new_owner) new_players = if originator_id == owner_id do new_players else originator = Map.fetch!(new_players, originator_id) new_originator = %Player{originator | kills: originator.kills + 1} Map.put(new_players, originator_id, new_originator) end new_data = %Impl{data | player_handles: new_player_handles, players: new_players} cmd = create_random_powerup(tank.pos) notification = %PlayersChanged{players: new_players} {new_data, [cmd], [notification]} else {data, [], []} end end def event(data, %Tanx.Game.Events.PowerUpCollected{ tank: tank, power_up: %Tanx.Game.Arena.PowerUp{data: %{type: :bounce}} }) do owner_id = tank.data[:player_id] player_id_map = data.player_id_map player_handles = data.player_handles if Map.has_key?(player_id_map, owner_id) do owner_handle = Map.fetch!(player_id_map, owner_id) owner_private = Map.fetch!(player_handles, owner_handle) new_owner_private = %PlayerPrivate{owner_private | bounce: 1} new_player_handles = Map.put(player_handles, owner_handle, new_owner_private) new_data = %Impl{data | player_handles: new_player_handles} {new_data, [], []} else {data, [], []} end end def event(data, _event) do {data, [], []} end def stats(data, _arena, _time) do %{player_count: Enum.count(data.player_handles)} end def stop(_data, _arena, _time) do %{} end defp remove_player(data, player_handle, cur_commands, cur_notification) do player_private = Map.fetch!(data.player_handles, player_handle) tank_id = player_private.tank_id player_id = player_private.player_id new_player_handles = Map.delete(data.player_handles, player_handle) players = data.players {new_players, commands, notification} = case tank_id do nil -> new_players = Map.delete(players, player_id) new_notification = %PlayersChanged{players: new_players} {new_players, cur_commands, new_notification} false -> cmd = %Tanx.Game.Commands.DeleteTank{ query: %{player_id: player_id}, event_data: %{deleting_player_id: player_id} } {players, [cmd | cur_commands], cur_notification} id -> cmd = %Tanx.Game.Commands.DeleteTank{ id: id, event_data: %{deleting_player_id: player_id} } {players, [cmd | cur_commands], cur_notification} end new_player_id_map = Map.delete(data.player_id_map, player_id) new_data = %Impl{ data | players: new_players, player_handles: new_player_handles, player_id_map: new_player_id_map } {new_data, commands, notification} end defp calc_velocity(true, false, forward_speed, _back_speed), do: forward_speed defp calc_velocity(false, true, _forward_speed, back_speed), do: -back_speed defp calc_velocity(_forward, _back, _forward_speed, _back_speed), do: 0.0 defp calc_angular_velocity(true, false, angular_speed), do: angular_speed defp calc_angular_velocity(false, true, angular_speed), do: -angular_speed defp calc_angular_velocity(_left, _right, _angular_speed), do: 0.0 defp create_random_powerup(pos) do case :rand.uniform(2) do 1 -> create_health_powerup(pos) 2 -> create_bounce_powerup(pos) end end defp create_health_powerup(pos) do tank_modifier = fn t, _p -> %Tanx.Game.Arena.Tank{t | armor: min(t.max_armor, t.armor + 1.0)} end %Tanx.Game.Commands.CreatePowerUp{ pos: pos, expires_in: @power_up_lifetime, tank_modifier: tank_modifier, data: %{type: :health} } end defp create_bounce_powerup(pos) do %Tanx.Game.Commands.CreatePowerUp{ pos: pos, expires_in: @power_up_lifetime, data: %{type: :bounce} } end end
apps/tanx/lib/tanx/continuous_game/impl.ex
0.53607
0.454593
impl.ex
starcoder
defmodule Burrito.Versions.ReleaseFile do @moduledoc """ This module provides some helpful functions for requesting, parsing and sorting release files. A release file is a simplistic JSON format that contains the releases of an app, where to fetch them, and some release notes. (And any other information you want to store in there!) Example Release File: ```json { "app_name": "example_cli_app", "releases": [ { "version": "0.2.0", "notes": "This new version is new and exciting, we promise!", "urls": { "win64": "https://example.com/releases/0.2.0/example_cli_app_win64.exe", "darwin": "https://example.com/releases/0.2.0/example_cli_app_linux", "linux": "https://example.com/releases/0.2.0/example_cli_app_darwin" } }, { "version": "0.1.5", "notes": "This new version is new and exciting, we promise!", "urls": { "win64": "https://example.com/releases/0.1.5/example_cli_app_win64.exe", "darwin": "https://example.com/releases/0.1.5/example_cli_app_linux", "linux": "https://example.com/releases/0.1.5/example_cli_app_darwin" } } ] } ``` The only required parts of a release JSON file is: * `"app_name"` and `"releases"` keys must be present at the top-level object * `"releases"` must be a list of objects that have a `"version"` key that contains a semver string Here's the minimal JSON Schema for a release file: ```json { "$schema": "http://json-schema.org/draft-07/schema", "required": [ "app_name", "releases" ], "type": "object", "properties": { "app_name": { "type": "string" }, "releases": { "type": "array", "additionalItems": true, "items": { "anyOf": [ { "default": {}, "required": [ "version" ], "type": "object", "properties": { "version": { "title": "The version schema", "type": "string" } }, "additionalProperties": true } ] } } }, "additionalProperties": true } ``` You can customize everything else to your liking! To use the functions in this module, you simply upload this to some HTTP server, and call ```elixir {:ok, release_map} = fetch_releases_from_url(release_url) maybe_new_release = get_new_version(release_map, current_semver_version_string) ``` Which will return either the release map data of a newer release, or `nil` if there is no newer release. """ def fetch_releases_from_url(url, req_options \\ []) when is_binary(url) do Req.get!(url, req_options).body end @spec get_new_version(map(), String.t()) :: map() | nil def get_new_version(release_map, current_version_string) do with {:ok, curr_version} <- Version.parse(current_version_string), %{} = newer_version <- find_newer_version(curr_version, release_map) do newer_version else _ -> nil end end defp find_newer_version(%Version{} = curr_version, release_map) do releases = Map.get(release_map, "releases", []) newer_release = Enum.filter(releases, fn release -> this_version = Map.get(release, "version", "0.0.0") |> Version.parse!() Version.compare(curr_version, this_version) == :lt end) |> Enum.sort_by(fn r -> r["version"] |> Version.parse!() end, {:desc, Version}) |> List.first() newer_release end end
lib/versions/release_file.ex
0.741674
0.784649
release_file.ex
starcoder
defmodule Day2 do def data do "inputs/02.txt" |> File.read!() |> String.split("\n", trim: true) end def run(validator) when validator in [Day2.PasswordValidator1, Day2.PasswordValidator2] do Enum.count(data(), fn line -> line |> validator.validate() |> Map.get(:valid?) end) end defmodule Validator do defstruct [:num1, :num2, :password, :required_char, valid?: true] @callback validate(String.t()) :: %{valid?: boolean()} def extract(line) do [num1_num2, <<required_char::bytes-size(1)>> <> ":", password] = String.split(line) [num1, num2] = String.split(num1_num2, "-") %__MODULE__{ num1: String.to_integer(num1), num2: String.to_integer(num2), password: password, required_char: required_char } end end defmodule PasswordValidator1 do @behaviour Validator @impl Validator def validate(line) when is_bitstring(line), do: validate(Day2.Validator.extract(line)) def validate(%{num1: min, num2: max, password: password, required_char: required_char} = validator) do char_frequency = frequency(password, required_char) cond do char_frequency >= min and char_frequency <= max -> %{validator | valid?: true} true -> %{validator | valid?: false} end end defp frequency(password, char) do password |> String.graphemes() |> Enum.frequencies() |> Map.get(char) end end defmodule PasswordValidator2 do @behaviour Validator @impl Validator def validate(line) when is_bitstring(line), do: validate(Day2.Validator.extract(line)) def validate(%{required_char: required_char, password: password, num1: num1, num2: num2} = validator) when is_struct(validator) do case valid?(required_char, String.at(password, num1 - 1), String.at(password, num2 - 1)) do true -> %Day2.Validator{valid?: true} _ -> %Day2.Validator{valid?: false} end end defp valid?(required_char, pos_1, pos_2) when pos_1 == required_char and pos_2 != required_char, do: true defp valid?(required_char, pos_1, pos_2) when pos_1 != required_char and pos_2 == required_char, do: true defp valid?(_required_char, _pos_1, _pos_2), do: false end end # Day2.run(Day2.PasswordValidator1) |> IO.inspect(label: "count") # Day2.run(Day2.PasswordValidator2) |> IO.inspect(label: "count")
lib/Day2.ex
0.725065
0.523968
Day2.ex
starcoder
defmodule Jaxon.Decoders.Query do alias Jaxon.ParseError @query_object 0 @query_array 1 @key 2 @reduce 3 @object 4 @query_key 5 @array 6 @query 7 @skip 8 @skip_value 9 def query(_event_stream, []) do raise(ArgumentError, "Empty query given") end def query(event_stream, query) do event_stream |> Stream.transform({[], [], [:root], {[], query}}, fn events, {tail, stack, path, query} -> (tail ++ events) |> continue(stack, path, [], query) |> case do {:yield, tail, stack, path, acc, query} -> {:lists.reverse(acc), {tail, stack, path, query}} {:error, error} -> raise error end end) end defp continue([], stack, path, acc, query) do {:yield, [], stack, path, acc, query} end defp continue(e, stack, path, acc, query) do case stack do stack = [@query_object | _] -> query_object(e, stack, path, acc, query) stack = [@query_array | _] -> query_array(e, stack, path, acc, query) [@key | stack] -> key(e, stack, path, acc, query) [@reduce | stack] -> reduce_value(e, stack, path, acc, query) [@object | stack] -> object(e, stack, path, acc, query) [@query_key | stack] -> query_key(e, stack, path, acc, query) [@array | stack] -> array(e, stack, path, acc, query) [@query | stack] -> query_value(e, stack, path, acc, query) stack = [@skip | _] -> skip(e, stack, path, acc, query) [@skip_value | stack] -> skip_value(e, stack, path, acc, query) [] -> value(e, stack, path, acc, query) end end defp is_match?([q | rest], key) do if is_match?(q, key) do true else is_match?(rest, key) end end defp is_match?([], _), do: false defp is_match?(key, key), do: true defp is_match?(:all, _), do: true defp is_match?({min, max}, key) when key >= min and key < max, do: true defp is_match?(_, _), do: false defp value(e, stack, path = [key | _], acc, query = {prev, [q | next]}) do case {is_match?(q, key), next} do {true, []} -> reduce_value(e, stack, path, acc, query) {true, next} -> query_value(e, stack, path, acc, {[q | prev], next}) {false, _} -> skip_value(e, stack, path, acc, query) end end # ----- QUERY VALUE defp query_value(e, stack, path, acc, query) do case e do [] -> {:yield, [], [@query | stack], path, acc, query} [:start_object | e] -> query_object(e, [@query_object | stack], [nil | path], acc, query) [:start_array | e] -> query_array(e, [@query_array | stack], [nil | path], acc, query) [e | _] -> {:error, ParseError.unexpected_event(e, [:value])} end end defp query_array([:comma | _], _stack, [nil | _path], _acc, _query) do {:error, ParseError.unexpected_event(:comma, [:value, :end_array])} end defp query_array([:comma | e], stack, [key | path], acc, query) do value(e, stack, [key + 1 | path], acc, query) end defp query_array( [:end_array | e], [@query_array | stack], [_key | path], acc, {[q | prev], next} ) do continue(e, stack, path, acc, {prev, [q | next]}) end defp query_array([], stack, path, acc, query) do {:yield, [], stack, path, acc, query} end defp query_array(e, stack, [nil | path], acc, query) do value(e, stack, [0 | path], acc, query) end defp query_object([:comma | _], _stack, [nil | _path], _acc, _query) do {:error, ParseError.unexpected_event(:comma, [:key, :end_object])} end defp query_object([:comma | e], stack, path, acc, query) do query_key(e, stack, path, acc, query) end defp query_object( [:end_object | e], [@query_object | stack], [_key | path], acc, {[q | prev], next} ) do continue(e, stack, path, acc, {prev, [q | next]}) end defp query_object([], stack, path, acc, query) do {:yield, [], stack, path, acc, query} end defp query_object(e, stack, path = [nil | _], acc, query) do query_key(e, stack, path, acc, query) end defp query_object([e | _], _stack, [nil | _path], _acc, _query) do {:error, ParseError.unexpected_event(e, [:key, :end_object])} end defp query_object([e | _], _stack, _path, _acc, _query) do {:error, ParseError.unexpected_event(e, [:comma, :end_object])} end defp query_key([{:string, key}, :colon | e], stack, [_key | path], acc, query) do value(e, stack, [key | path], acc, query) end defp query_key(e = [{:string, _key}], stack, path, acc, query) do {:yield, e, [@query_key | stack], path, acc, query} end defp query_key(e = [], stack, path, acc, query) do {:yield, e, [@query_key | stack], path, acc, query} end defp query_key([e | _], _stack, _path, _acc, _query) do {:error, ParseError.unexpected_event(e, [:key])} end # ---- REDUCE VALUE defp reduce_value(e, stack, path, acc, query) do case e do [] -> {:yield, [], [@reduce | stack], path, acc, query} [:start_object | e] -> object(e, [[] | stack], [nil | path], acc, query) [:start_array | e] -> array(e, [[] | stack], [nil | path], acc, query) [{type, value} | e] when type in ~w(string decimal integer boolean)a -> add_value(e, stack, path, acc, query, value) [nil | e] -> add_value(e, stack, path, acc, query, nil) [e | _] -> {:error, ParseError.unexpected_event(e, [:value])} end end defp add_value(e, [object | stack], path = [key | _], acc, query, value) when is_binary(key) and is_list(object) do object(e, [[{key, value} | object] | stack], path, acc, query) end defp add_value(e, [object | stack], path = [key | _], acc, query, value) when is_integer(key) and is_list(object) do array(e, [[value | object] | stack], path, acc, query) end defp add_value(e, stack, path, acc, query, value) do continue(e, stack, path, [value | acc], query) end defp array([:comma | _], _stack, [nil | _path], _acc, _query) do {:error, ParseError.unexpected_event(:comma, [:value, :end_array])} end defp array([:comma | e], stack, [key | path], acc, query) do reduce_value(e, stack, [key + 1 | path], acc, query) end defp array([:end_array | e], [array | stack], [_key | path], acc, query) when is_list(array) do add_value(e, stack, path, acc, query, :lists.reverse(array)) end defp array([], stack, path, acc, query) do {:yield, [], [@array | stack], path, acc, query} end defp array(e, stack, [nil | path], acc, query) do reduce_value(e, stack, [0 | path], acc, query) end defp object([:comma | _], _stack, [nil | _path], _acc, _query) do {:error, ParseError.unexpected_event(:comma, [:key, :end_object])} end defp object([:comma | e], stack, path, acc, query) do key(e, stack, path, acc, query) end defp object([:end_object | e], [object | stack], [_key | path], acc, query) when is_list(object) do add_value(e, stack, path, acc, query, :maps.from_list(object)) end defp object([], stack, path, acc, query) do {:yield, [], [@object | stack], path, acc, query} end defp object(e, stack, path = [nil | _], acc, query) do key(e, stack, path, acc, query) end defp object([e | _], _stack, [nil | _path], _acc, _query) do {:error, ParseError.unexpected_event(e, [:key, :end_object])} end defp object([e | _], _stack, _path, _acc, _query) do {:error, ParseError.unexpected_event(e, [:comma, :end_object])} end defp key([{:string, key}, :colon | e], stack, [_key | path], acc, query) do reduce_value(e, stack, [key | path], acc, query) end defp key(e = [{:string, _key}], stack, path, acc, query) do {:yield, e, [@key | stack], path, acc, query} end defp key(e = [], stack, path, acc, query) do {:yield, e, [@key | stack], path, acc, query} end defp key([e | _], _stack, _path, _acc, _query) do {:error, ParseError.unexpected_event(e, [:key])} end defp skip_value(e, stack, path, acc, query) do case e do [] -> {:yield, [], [@skip_value | stack], path, acc, query} [:start_object | e] -> skip(e, [@skip | stack], path, acc, query) [:start_array | e] -> skip(e, [@skip | stack], path, acc, query) [{type, _} | e] when type in ~w(string decimal integer boolean)a -> continue(e, stack, path, acc, query) [nil | e] -> continue(e, stack, path, acc, query) [_ | rest] -> skip(rest, stack, path, acc, query) end end # ---- SKIP VALUE defp skip([:end_object | e], [@skip | stack], path, acc, query) do skip(e, stack, path, acc, query) end defp skip([:end_array | e], [@skip | stack], path, acc, query) do skip(e, stack, path, acc, query) end defp skip([:start_array | e], stack, path, acc, query) do skip(e, [@skip | stack], path, acc, query) end defp skip([:start_object | e], stack, path, acc, query) do skip(e, [@skip | stack], path, acc, query) end defp skip([_ | e], stack = [@skip | _], path, acc, query) do skip(e, stack, path, acc, query) end defp skip([], stack = [@skip | _], path, acc, query) do {:yield, [], stack, path, acc, query} end defp skip(e, stack, path, acc, query) do continue(e, stack, path, acc, query) end end
lib/jaxon/decoders/query.ex
0.682468
0.579579
query.ex
starcoder
defmodule GenStage.PartitionDispatcher do @moduledoc """ A dispatcher that sends events according to partitions. Keep in mind that, if partitions are not evenly distributed, a backed-up partition will slow all other ones. ## Options The partition dispatcher accepts the following options on initialization: * `:partitions` - the number of partitions to dispatch to. It may be an integer with a total number of partitions, where each partition is named from 0 up to `integer - 1`. For example, `partitions: 4` will contain 4 partitions named 0, 1, 2 and 3. It may also be an enumerable that specifies the name of every partition. For instance, `partitions: [:odd, :even]` will build two partitions, named `:odd` and `:even`. * `:hash` - the hashing algorithm, which receives the event and returns a tuple with two elements, the event to be dispatched as first argument and the partition as second. The partition must be one of the partitions specified in `:partitions` above. The default uses `fn event -> {event, :erlang.phash2(event, Enum.count(partitions))} end` on the event to select the partition. ### Examples To start a producer with four partitions named 0, 1, 2 and 3: {:producer, state, dispatcher: {GenStage.PartitionDispatcher, partitions: 0..3}} To start a producer with two partitions named `:odd` and `:even`: {:producer, state, dispatcher: {GenStage.PartitionDispatcher, partitions: [:odd, :even]}} ## Subscribe options When subscribing to a `GenStage` with a partition dispatcher the following option is required: * `:partition` - the name of the partition. The partition must be one of the partitions specified in `:partitions` above. ### Examples The partition function can be given either on `init`'s subscribe_to: {:consumer, :ok, subscribe_to: [{producer, partition: 0}]} Or when calling `sync_subscribe`: GenStage.sync_subscribe(consumer, to: producer, partition: 0) """ @behaviour GenStage.Dispatcher @init {nil, nil, 0} require Logger @doc false def init(opts) do partitions = case Keyword.get(opts, :partitions) do nil -> raise ArgumentError, "the enumerable of :partitions is required when using the partition dispatcher" partitions when is_integer(partitions) -> 0..(partitions - 1) partitions -> partitions end hash_present? = Keyword.has_key?(opts, :hash) partitions = for partition <- partitions, into: %{} do if not hash_present? and not is_integer(partition) do raise ArgumentError, "when :partitions contains partitions that are not integers, you have to pass " <> "in the :hash option as well" end Process.put(partition, []) {partition, @init} end size = map_size(partitions) hash = Keyword.get(opts, :hash, &hash(&1, size)) {:ok, {make_ref(), hash, 0, 0, partitions, %{}, %{}}} end defp hash(event, range) do {event, :erlang.phash2(event, range)} end @doc false def info(msg, {tag, hash, waiting, pending, partitions, references, infos}) do info = make_ref() {partitions, queued} = Enum.reduce(partitions, {partitions, []}, fn {partition, {pid, ref, queue}}, {partitions, queued} when not is_integer(queue) -> {Map.put(partitions, partition, {pid, ref, :queue.in({tag, info}, queue)}), [partition | queued]} _, {partitions, queued} -> {partitions, queued} end) infos = case queued do [] -> send(self(), msg) infos _ -> Map.put(infos, info, {msg, queued}) end {:ok, {tag, hash, waiting, pending, partitions, references, infos}} end @doc false def subscribe(opts, {pid, ref}, {tag, hash, waiting, pending, partitions, references, infos}) do partition = Keyword.get(opts, :partition) case partitions do %{^partition => {nil, nil, demand_or_queue}} -> partitions = Map.put(partitions, partition, {pid, ref, demand_or_queue}) references = Map.put(references, ref, partition) {:ok, 0, {tag, hash, waiting, pending, partitions, references, infos}} %{^partition => {pid, _, _}} -> raise ArgumentError, "the partition #{partition} is already taken by #{inspect(pid)}" _ when is_nil(partition) -> raise ArgumentError, "the :partition option is required when subscribing to a producer with partition dispatcher" _ -> keys = Map.keys(partitions) raise ArgumentError, ":partition must be one of #{inspect(keys)}, got: #{partition}" end end @doc false def cancel({_, ref}, {tag, hash, waiting, pending, partitions, references, infos}) do {partition, references} = Map.pop(references, ref) {_pid, _ref, demand_or_queue} = Map.get(partitions, partition) partitions = Map.put(partitions, partition, @init) case demand_or_queue do demand when is_integer(demand) -> {:ok, 0, {tag, hash, waiting, pending + demand, partitions, references, infos}} queue -> {length, infos} = clear_queue(queue, tag, partition, 0, infos) {:ok, length, {tag, hash, waiting + length, pending, partitions, references, infos}} end end @doc false def ask(counter, {_, ref}, {tag, hash, waiting, pending, partitions, references, infos}) do partition = Map.fetch!(references, ref) {pid, ref, demand_or_queue} = Map.fetch!(partitions, partition) {demand_or_queue, infos} = case demand_or_queue do demand when is_integer(demand) -> {demand + counter, infos} queue -> send_from_queue(queue, tag, pid, ref, partition, counter, [], infos) end partitions = Map.put(partitions, partition, {pid, ref, demand_or_queue}) already_sent = min(pending, counter) demand = counter - already_sent pending = pending - already_sent {:ok, demand, {tag, hash, waiting + demand, pending, partitions, references, infos}} end defp send_from_queue(queue, _tag, pid, ref, _partition, 0, acc, infos) do maybe_send(acc, pid, ref) {queue, infos} end defp send_from_queue(queue, tag, pid, ref, partition, counter, acc, infos) do case :queue.out(queue) do {{:value, {^tag, info}}, queue} -> maybe_send(acc, pid, ref) infos = maybe_info(infos, info, partition) send_from_queue(queue, tag, pid, ref, partition, counter, [], infos) {{:value, event}, queue} -> send_from_queue(queue, tag, pid, ref, partition, counter - 1, [event | acc], infos) {:empty, _queue} -> maybe_send(acc, pid, ref) {counter, infos} end end defp clear_queue(queue, tag, partition, counter, infos) do case :queue.out(queue) do {{:value, {^tag, info}}, queue} -> clear_queue(queue, tag, partition, counter, maybe_info(infos, info, partition)) {{:value, _}, queue} -> clear_queue(queue, tag, partition, counter + 1, infos) {:empty, _queue} -> {counter, infos} end end # Important: events must be in reverse order defp maybe_send([], _pid, _ref), do: :ok defp maybe_send(events, pid, ref), do: Process.send(pid, {:"$gen_consumer", {self(), ref}, :lists.reverse(events)}, [:noconnect]) defp maybe_info(infos, info, partition) do case infos do %{^info => {msg, [^partition]}} -> send(self(), msg) Map.delete(infos, info) %{^info => {msg, partitions}} -> Map.put(infos, info, {msg, List.delete(partitions, partition)}) end end @doc false def dispatch(events, _length, {tag, hash, waiting, pending, partitions, references, infos}) do {deliver_now, deliver_later, waiting} = split_events(events, waiting, []) for event <- deliver_now do {event, partition} = hash.(event) case :erlang.get(partition) do :undefined -> Logger.error(fn -> "Unknown partition #{inspect(partition)} computed for GenStage/Flow event " <> "#{inspect(event)}. The known partitions are #{inspect(Map.keys(partitions))}. " <> "See the :partitions option to set your own. This event has been discarded." end) current -> Process.put(partition, [event | current]) end end partitions = partitions |> :maps.to_list() |> dispatch_per_partition() |> :maps.from_list() {:ok, deliver_later, {tag, hash, waiting, pending, partitions, references, infos}} end defp split_events(events, 0, acc), do: {:lists.reverse(acc), events, 0} defp split_events([], counter, acc), do: {:lists.reverse(acc), [], counter} defp split_events([event | events], counter, acc), do: split_events(events, counter - 1, [event | acc]) defp dispatch_per_partition([{partition, {pid, ref, demand_or_queue} = value} | rest]) do case Process.put(partition, []) do [] -> [{partition, value} | dispatch_per_partition(rest)] events -> events = :lists.reverse(events) {events, demand_or_queue} = case demand_or_queue do demand when is_integer(demand) -> split_into_queue(events, demand, []) queue -> {[], put_into_queue(events, queue)} end maybe_send(events, pid, ref) [{partition, {pid, ref, demand_or_queue}} | dispatch_per_partition(rest)] end end defp dispatch_per_partition([]) do [] end defp split_into_queue(events, 0, acc), do: {acc, put_into_queue(events, :queue.new())} defp split_into_queue([], counter, acc), do: {acc, counter} defp split_into_queue([event | events], counter, acc), do: split_into_queue(events, counter - 1, [event | acc]) defp put_into_queue(events, queue) do Enum.reduce(events, queue, &:queue.in/2) end end
deps/gen_stage/lib/gen_stage/dispatchers/partition_dispatcher.ex
0.897393
0.67141
partition_dispatcher.ex
starcoder
defmodule Kaffe.Producer do @moduledoc """ The producer pulls in values from the Kaffe producer configuration: - `heroku_kafka_env` - endpoints and SSL configuration will be pulled from ENV - `endpoints` - plaintext Kafka endpoints - `topics` - a list of Kafka topics to prep for producing - `partition_strategy` - the strategy to use when selecting the next partition. Default `:md5`. - `:md5`: provides even and deterministic distrbution of the messages over the available partitions based on an MD5 hash of the key - `:random` - Select a random partition - function - Pass a function as an argument that accepts five arguments and returns the partition number to use for the message - `topic, current_partition, partitions_count, key, value` Clients can also specify a partition directly when producing. Currently only synchronous production is supported. """ @kafka Application.get_env(:kaffe, :kafka_mod, :brod) require Logger ## ------------------------------------------------------------------------- ## public api ## ------------------------------------------------------------------------- def start_producer_client do @kafka.start_client(config().endpoints, client_name(), config().producer_config) end @doc """ Synchronously produce the `messages` to `topic` `messages` must be a list of `{key, value}` tuples Returns: * `:ok` on successfully producing each message * `{:error, reason}` for any error """ def produce_sync(topic, message_list) when is_list(message_list) do produce_list(topic, message_list, global_partition_strategy()) end @doc """ Synchronously produce the given `key`/`value` to the first Kafka topic. This is a simpler way to produce if you've only given Producer a single topic for production and don't want to specify the topic for each call. Returns: * `:ok` on successfully producing the message * `{:error, reason}` for any error """ def produce_sync(key, value) do topic = config().topics |> List.first produce(topic, key, value) end @doc """ Synchronously produce the `message_list` to `topic`/`partition` `message_list` must be a list of `{key, value}` tuples Returns: * `:ok` on successfully producing each message * `{:error, reason}` for any error """ def produce_sync(topic, partition, message_list) when is_list(message_list) do produce_list(topic, message_list, fn _, _, _, _ -> partition end) end @doc """ Synchronously produce the `key`/`value` to `topic` See `produce_sync/2` for returns. """ def produce_sync(topic, key, value) do produce(topic, key, value) end @doc """ Synchronously produce the given `key`/`value` to the `topic`/`partition` See `produce_sync/2` for returns. """ def produce_sync(topic, partition, key, value) do @kafka.produce_sync(client_name(), topic, partition, key, value) end ## ------------------------------------------------------------------------- ## internal ## ------------------------------------------------------------------------- defp produce_list(topic, message_list, partition_strategy) when is_list(message_list) do Logger.debug "event#produce_list topic=#{topic}" message_list |> group_by_partition(topic, partition_strategy) |> produce_list_to_topic(topic) end defp produce(topic, key, value) do {:ok, partitions_count} = @kafka.get_partitions_count(client_name(), topic) partition = choose_partition(topic, partitions_count, key, value, global_partition_strategy()) Logger.debug "event#produce topic=#{topic} key=#{key} partitions_count=#{partitions_count} selected_partition=#{partition}" @kafka.produce_sync(client_name(), topic, partition, key, value) end defp group_by_partition(messages, topic, partition_strategy) do {:ok, partitions_count} = @kafka.get_partitions_count(client_name(), topic) messages |> Enum.group_by(fn ({key, message}) -> choose_partition(topic, partitions_count, key, message, partition_strategy) end) end defp produce_list_to_topic(message_list, topic) do message_list |> Enum.reduce_while(:ok, fn ({partition, messages}, :ok) -> Logger.debug "event#produce_list_to_topic topic=#{topic} partition=#{partition}" case @kafka.produce_sync(client_name(), topic, partition, "ignored", messages) do :ok -> {:cont, :ok} {:error, _reason} = error -> {:halt, error} end end) end defp choose_partition(_topic, partitions_count, _key, _value, :random) do Kaffe.PartitionSelector.random(partitions_count) end defp choose_partition(_topic, partitions_count, key, _value, :md5) do Kaffe.PartitionSelector.md5(key, partitions_count) end defp choose_partition(topic, partitions_count, key, value, fun) when is_function(fun) do fun.(topic, partitions_count, key, value) end defp client_name do config().client_name end defp global_partition_strategy do config().partition_strategy end defp config do Kaffe.Config.Producer.configuration end end
lib/kaffe/producer.ex
0.882066
0.637482
producer.ex
starcoder
defmodule Issues.TableFormatter do import Enum, only: [each: 2, map: 2, map_join: 3, max: 1] @doc """ Takes a list of row data, where each row is a HashDict, and a list of headers. Prints a table to STDOUT of the data from each row identified by each header. That is, each header identifies a column, and those columns are extracted and printed from the rows. We calculate the width of each column to fit the longest element in that column. """ def print_table_for_columns(rows, headers) do data_by_columns = split_into_columns(rows, headers) column_widths = widths_of(data_by_columns) format = format_for(column_widths) puts_one_line_in_colums(headers, format) IO.puts(separator(column_widths)) puts_in_columns(data_by_columns, format) end @doc """ Given a list of rows, where each row contains a keyed list of columns, return a list containing lists of the data in each column. The `headers` parameter contains the list of columns to extract ## Example iex> list = [Enum.into([{"a", "1"},{"b", "2"},{"c", "3"}], Map.new), ...> Enum.into([{"a", "4"},{"b", "5"},{"c", "6"}], Map.new)] iex> Issues.TableFormatter.split_into_columns(list, [ "a", "b", "c" ]) [ ["1", "4"], ["2", "5"], ["3", "6"] ] """ def split_into_columns(rows, headers) do for header <- headers do for row <- rows, do: printable(row[header]) end end @doc """ Return a binary (string) version of our parameter. ## Example iex> Issues.TableFormatter.printable("a") "a" iex> Issues.TableFormatter.printable(99) "99" """ def printable(str) when is_binary(str), do: str def printable(str), do: to_string(str) @doc """ Given a list containing sublists, where each sublist contains the data for a column, return a list containing the maximum width of each column ## Example iex> data = [ [ "cat", "wombat", "elk"], ["mongoose", "ant", "gnu"]] iex> Issues.TableFormatter.widths_of(data) [ 6, 8 ] """ def widths_of(columns) do for column <- columns, do: column |> map(&String.length/1) |> max end @doc """ Return a format string that hard codes the widths of a set of columns. We put `" | "` between each column. ## Example iex> widths = [5,6,99] iex> Issues.TableFormatter.format_for(widths) "~-5s | ~-6s | ~-99s~n" """ def format_for(column_widths) do map_join(column_widths, " | ", fn width -> "~-#{width}s" end) <> "~n" end @doc """ Generate the line that goes below the column headings. It is a string of hyphens, with + signs where the vertical bar between the columns goes. ## Example iex> widths = [5,6,9] iex> Issues.TableFormatter.separator(widths) "------+--------+----------" """ def separator(column_widths) do map_join(column_widths, "-+-", fn width -> List.duplicate("-", width) end) end @doc """ Given a list containing rows of data, a list containing the header selectors, and a format string, write the extracted data under control of the format string. """ def puts_in_columns(data_by_columns, format) do data_by_columns |> List.zip() |> map(&Tuple.to_list/1) |> each(&puts_one_line_in_colums(&1, format)) end def puts_one_line_in_colums(fields, format) do :io.format(format, fields) end end
issues/lib/issues/table_formatter.ex
0.857709
0.791217
table_formatter.ex
starcoder
defmodule Tirexs.Search.Aggs do @moduledoc false @note """ It helps provide aggregated data based on a search query. It is based on simple building blocks called aggregations, that can be composed in order to build complex summaries of the data. """ use Tirexs.DSL.Logic alias Tirexs.{Query.Filter} @doc false defmacro aggs([do: block]) do [aggs: extract(block)] end @doc false def transpose(block) do case block do {:term_stats, _, [a,b]} -> term_stats(a, b) {:terms, _, [params]} -> terms(params) {:term, _, [field, value]} -> term(field, value) {:stats, _, [params]} -> stats(params) {:histogram, _, [params]} -> histogram(params) {:date_histogram, _, [params]} -> date_histogram(params) {:geo_distance, _, [params]} -> geo_distance(params) {:range, _, [params]} -> range(params) {:nested, _, [params]} -> nested(params) {name, _, [params]} -> _aggs(name, params[:do]) {name, _, params} -> _aggs(name, params) end end @doc false def term_stats(terms, stats) do [tags: [terms: terms, aggs: [{to_atom("#{stats[:field]}_stats"), [stats: stats]}]]] end @doc false def terms(terms) do [terms: terms] end @doc false def term(field, value) do [term: [{to_atom(field), value}]] end @doc false def stats(stats) do [aggs: [{to_atom("#{stats[:field]}_stats"), [stats: stats]}]] end @doc false def histogram(options) do [histogram: options] end @doc false def date_histogram(options) do [date_histogram: options] end @doc false def geo_distance(options) do [geo_distance: options] end @doc false def range(options) do [range: options] end @doc false def nested(params) do [nested: params] end @doc false def _aggs(params) when is_tuple(params) do routers(:aggs, params) end defp _aggs(name, params) when is_tuple(params) do routers(name, params) end defp routers(name, body) when is_tuple(body) do case body do {:__block__, _, params} -> [ {to_atom(name), extract(params)} ] {:filter, _, [params]} -> [ {to_atom(name), Filter._filter(params[:do])} ] _ -> [ {to_atom(name), extract(body)} ] end end end
lib/tirexs/search/aggs.ex
0.572364
0.566798
aggs.ex
starcoder
defmodule Day17 do @moduledoc """ Advent of Code 2019 Day 17: Set and Forget I have no idea why Part 2 doesn't work. It actually does work (answer: 597517) with continuous video feed turned on, but not when it's turned off. Too lazy to debug this atm. """ alias Day17.{Part1, Part2} def get_program() do Path.join(__DIR__, "inputs/day17.txt") |> File.read!() |> String.trim() |> String.split(",") |> Enum.map(&String.to_integer/1) end def execute() do program = get_program() IO.puts("Part 1: #{Part1.run(program)}") IO.puts("Part 2: #{Part2.run(program)}") end end defmodule Day17.Part1 do def run(program) do program |> compute_camera_output() |> convert_to_coords() |> compute_alignment_parameters() |> Stream.map(fn {x, y} -> x * y end) |> Enum.sum() end def compute_camera_output(program) do GenServer.start_link(Intcode, program, name: Computer17) output = accumulate_output() GenServer.stop(Computer17) output end def accumulate_output() do case GenServer.call(Computer17, {:run, []}) do {:exit, _} -> [] {:output, code} -> [code | accumulate_output()] end end def convert_to_coords(scaffolding) do # Treating everything besides a dot and a newline as scaffolding. scaffolding |> Enum.reduce({MapSet.new(), {0, 0}}, fn char, {coords, {x, y}} -> case char do c when c in [?#, ?^, ?>, ?v, ?<] -> {MapSet.put(coords, {x, y}), {x + 1, y}} ?. -> {coords, {x + 1, y}} ?\n -> {coords, {0, y + 1}} end end) |> (&elem(&1, 0)).() end def compute_alignment_parameters(coords) do coords |> Enum.filter(fn {x, y} -> [{x - 1, y}, {x, y + 1}, {x + 1, y}, {x, y - 1}] |> Enum.all?(fn neighbor -> MapSet.member?(coords, neighbor) end) end) end end defmodule Day17.Part2 do alias Day17.Part1 def run(program) do output = program |> Part1.compute_camera_output() start_coord = output |> get_start_coord() coords = output |> Part1.convert_to_coords() compute_path(start_coord, coords) |> split_path_into_functions() |> execute_robot(program) end def get_start_coord([char | scaffolding], {x, y} \\ {0, 0}) do case char do ?^ -> {{x, y}, :up} ?> -> {{x, y}, :right} ?v -> {{x, y}, :down} ?< -> {{x, y}, :left} c when c in [?#, ?.] -> get_start_coord(scaffolding, {x + 1, y}) ?\n -> get_start_coord(scaffolding, {x, y + 1}) end end def compute_path({start_coord, start_dir}, coords) do opposite_dir = compute_opposite_dir(start_dir) prev_coord = move_coord(start_coord, opposite_dir) case find_next_direction(start_coord, coords, prev_coord) do nil -> [] adja_dir -> turn = compute_turning_direction(start_dir, adja_dir) {new_coord, dist} = compute_walking_distance(start_coord, adja_dir, coords) turn ++ [dist | compute_path({new_coord, adja_dir}, coords)] end end def find_next_direction({x, y}, coords, prev_coord) do [:up, :right, :down, :left] |> Enum.find(fn dir -> adja_coord = move_coord({x, y}, dir) MapSet.member?(coords, adja_coord) && prev_coord != adja_coord end) end @dir_num_vals %{ :up => 0, :right => 1, :down => 2, :left => 3 } def compute_turning_direction(start_dir, adja_dir) do diff = (@dir_num_vals[adja_dir] - @dir_num_vals[start_dir]) |> Integer.mod(4) case diff do 0 -> [] 1 -> ["R"] 2 -> ["R", "R"] 3 -> ["L"] end end def compute_walking_distance({x, y}, dir, coords, dist \\ 0) do new_coord = move_coord({x, y}, dir) if !MapSet.member?(coords, new_coord) do {{x, y}, dist} else compute_walking_distance(new_coord, dir, coords, dist + 1) end end def move_coord({x, y}, dir) do case dir do :up -> {x, y - 1} :right -> {x + 1, y} :down -> {x, y + 1} :left -> {x - 1, y} end end def compute_opposite_dir(dir) do case dir do :up -> :down :down -> :up :right -> :left :left -> :right end end @doc """ A brute-force function splitter. We need to satisfy the following requirements: - Three functions - Max function length of 20 - Entire path encoded into <=20 functions """ def split_path_into_functions(path, fn_lens \\ {1, 1, 1}) do {f1_len, f2_len, f3_len} = fn_lens {f1, rem} = Enum.split(path, f1_len) {rem, _} = trim_functions(rem, [f1]) {f2, rem} = Enum.split(rem, f2_len) {rem, _} = trim_functions(rem, [f1, f2]) f3 = Enum.take(rem, f3_len) {rem, main} = trim_functions(path, [f1, f2, f3]) cond do rem == [] && length(main) <= 20 -> {main, [f1, f2, f3]} f3_len == 20 && f2_len == 20 && f1_len == 20 -> raise "well something's wrong" f3_len == 20 && f2_len == 20 -> split_path_into_functions(path, {f1_len + 1, 1, 1}) f3_len == 20 -> split_path_into_functions(path, {f1_len, f2_len + 1, 1}) true -> split_path_into_functions(path, {f1_len, f2_len, f3_len + 1}) end end @indices %{ 0 => "A", 1 => "B", 2 => "C" } def trim_functions(path, functions, main \\ []) do {path, main_new} = functions |> Enum.with_index() |> Enum.reduce({path, main}, fn {func, index}, {path, main} -> {prefix, remainder} = Enum.split(path, length(func)) if func == prefix do {remainder, main ++ [@indices[index]]} else {path, main} end end) if main != main_new, do: trim_functions(path, functions, main_new), else: {path, main} end def execute_robot({main, [f1, f2, f3]}, program) do program = List.replace_at(program, 0, 2) input = [main, f1, f2, f3, ["n"]] |> Enum.map(&Enum.join(&1, ",")) |> Enum.map(&(&1 <> "\n")) |> Enum.join() |> to_charlist() GenServer.start_link(Intcode, program, name: Computer17_2) space_dust = Intcode.run_computer(Computer17_2, input) GenServer.stop(Computer17_2) space_dust end end
lib/day17.ex
0.623262
0.577019
day17.ex
starcoder
defmodule CrissCrossDHT.Server.Utils do require Logger @moduledoc false @doc ~S""" This function gets a tuple as IP address and a port and returns a string which contains the IPv4 or IPv6 address and port in the following format: "127.0.0.1:6881". ## Example iex> CrissCrossDHT.Server.Utils.tuple_to_ipstr({127, 0, 0, 1}, 6881) "127.0.0.1:6881" """ @aad "AES256GCM" @schnorr_context "CrissCross-DHT" def parse_conn_string(from) do {l, r} = case from do "[" <> rest -> [l, r] = String.split(rest, "]:", parts: 2) {l, r} _ -> [l, r] = String.split(from, ":", parts: 2) {l, r} end {:ok, addr} = :inet.parse_address(String.to_charlist(l)) port = String.to_integer(r) {addr, port} end def tuple_to_ipstr({:stream, s, ipstr}, nil) do ipstr end def tuple_to_ipstr({oct1, oct2, oct3, oct4}, port) do "#{oct1}.#{oct2}.#{oct3}.#{oct4}:#{port}" end def tuple_to_ipstr(ipv6_addr, port) when tuple_size(ipv6_addr) == 8 do ip_str = String.duplicate("~4.16.0B:", 8) ## remove last ":" of the string |> String.slice(0..-2) |> :io_lib.format(Tuple.to_list(ipv6_addr)) |> List.to_string() "[#{ip_str}]:#{port}" end def resolve_hostnames(list, inet), do: resolve_hostnames(list, inet, []) def resolve_hostnames([], _inet, result), do: result def resolve_hostnames([{id, host, port} | tail], inet, result) when is_tuple(host) do resolve_hostnames(tail, inet, result ++ [{id, host, port}]) end def resolve_hostnames([{id, host, port} | tail], inet, result) when is_binary(host) do case :inet.getaddr(String.to_charlist(host), inet) do {:ok, ip_addr} -> resolve_hostnames(tail, inet, result ++ [{id, ip_addr, port}]) {:error, code} -> Logger.error("Couldn't resolve the hostname: #{host} (reason: #{code})") resolve_hostnames(tail, inet, result) end end @doc ~S""" This function generates a 256 bit (32 byte) random node id as a binary. """ @spec gen_node_id :: Types.node_id() def gen_node_id do :rand.seed(:exs64, :os.timestamp()) s = Stream.repeatedly(fn -> :rand.uniform(255) end) |> Enum.take(40) |> :binary.list_to_bin() hash(s) end def gen_cypher do :rand.seed(:exs64, :os.timestamp()) s = Stream.repeatedly(fn -> :rand.uniform(255) end) |> Enum.take(500) |> :binary.list_to_bin() # hash(s) :crypto.hash(:sha3_256, s) end @compile {:inline, hash: 1} def hash(s, max_size \\ 32) do size = byte_size(s) if size < max_size do <<0x01, size::integer-size(8)>> <> s else {:ok, hash} = Multihash.encode(:blake2s, :crypto.hash(:blake2s, s)) hash end end def simple_hash(s), do: :crypto.hash(:blake2s, s) @doc """ TODO """ def gen_secret, do: gen_node_id() def config(config, :bootstrap_nodes) do Map.get(config, :bootstrap_nodes, []) |> Enum.map(fn node -> host = case node do %{host: host} when is_binary(host) -> host _ -> raise "Bootstrap configured without host" end port = case node do %{port: port} when is_number(port) -> port _ -> raise "Bootstrap configured without port" end node_id = case node do %{node_id: node_id} when is_binary(node_id) -> decode_human!(node_id) _ -> raise "Bootstrap configured without node_id" end {node_id, host, port} end) end def config(config, value, ret \\ nil), do: Map.get(config, value, ret) def load_cluster({k, config}) do pub_key = case config do %{public_key: pub} when not is_nil(pub) -> {:ok, pub_key} = load_public_key(decode_human!(pub)) pub_key _ -> raise "Cluster #{k} configured without public key" end priv_key = case config do %{private_key: priv} when not is_nil(priv) -> {:ok, priv_key} = load_private_key(decode_human!(priv)) priv_key _ -> nil end cypher = case config do %{secret: secret} when not is_nil(secret) -> decode_human!(secret) _ -> raise "Cluster #{k} configured without secret" end max_ttl = case config do %{max_ttl: max_ttl} when is_number(max_ttl) and max_ttl >= -1 -> max_ttl _ -> raise "Cluster #{k} configured without max_ttl" end max_transfer = case config do %{max_transfer: max_transfer} when is_number(max_transfer) and max_transfer >= -1 -> if max_transfer == -1 do 4_294_967_295 else max_transfer end _ -> raise "Cluster #{k} configured without max_transfer" end {decode_human!(k), %{ max_ttl: max_ttl, max_transfer: max_transfer, cypher: cypher, public_key: pub_key, private_key: priv_key }} end def encrypt(secret, payload) do do_encrypt(payload, secret) end def decrypt(payload, secret) do do_decrypt(payload, secret) end def verify_signature(nil, _value, _signature), do: false def verify_signature(pub_key, msg, signature) do case ExSchnorr.verify(pub_key, msg, signature, @schnorr_context) do {:ok, true} -> true _e -> false end end def sign(msg, priv_key) do ExSchnorr.sign(priv_key, msg, @schnorr_context) end defp do_encrypt(val, key) do iv = :crypto.strong_rand_bytes(32) {ciphertext, tag} = :crypto.crypto_one_time_aead(:aes_256_gcm, key, iv, to_string(val), @aad, true) iv <> tag <> ciphertext end defp do_decrypt(ciphertext, key) do <<iv::binary-32, tag::binary-16, ciphertext::binary>> = ciphertext :crypto.crypto_one_time_aead(:aes_256_gcm, key, iv, ciphertext, @aad, tag, false) end def wrap(header, body) do ["0A", header, body] end def unwrap("0A" <> <<cluster_header::binary-size(34), body::binary>>) do {cluster_header, body} end def encode_human(bin) do Base58.encode(bin) end def decode_human!(bin) do Base58.decode(bin) end def combine_to_sign(list) do list |> Enum.map(&to_string(&1)) |> Enum.join(".") end def name_from_private_rsa_key(priv_key) do {:ok, pub_key} = ExSchnorr.public_from_private(priv_key) name_from_public_key(pub_key) end def name_from_public_key(pub_key) do {:ok, encoded} = ExSchnorr.public_to_bytes(pub_key) hash(hash(encoded)) end def check_generation(storage_mod, storage_pid, cluster, name, generation) do case storage_mod.get_name(storage_pid, cluster, name) do {_value, saved_gen} -> saved_gen < generation _ -> true end end def load_public_key(s) do case ExSchnorr.public_from_bytes(s) do {:ok, c} -> {:ok, c} e -> case CrissCrossDHT.NameWatcher.get_name(s) do %{public_key: k} -> {:ok, k} _ -> e end end end def load_private_key(s) do case ExSchnorr.private_from_bytes(s) do {:ok, c} -> {:ok, c} e -> case CrissCrossDHT.NameWatcher.get_name(s) do %{private_key: k} -> {:ok, k} _ -> e end end end def check_ttl(%{max_ttl: -1}, _), do: true def check_ttl(%{max_ttl: mx}, ttl), do: adjust_ttl(mx) + 60_000 >= ttl def adjust_ttl(ttl) do case ttl do -1 -> -1 _ -> :os.system_time(:millisecond) + ttl end end end
lib/criss_cross_dht/server/utils.ex
0.700485
0.502869
utils.ex
starcoder
defmodule Merkel.BinaryNode do alias Merkel.BinaryNode, as: Node # The node has a hash, a search_key, a height key # For leaf nodes the key and value fields are used, otherwise they are nil # For inner nodes the two child fields left and right are used, otherwise they are nil # This allows us to use pattern matching to select correct node type # instead using an extra type field or creating two node types defstruct key_hash: nil, search_key: nil, key: nil, value: nil, height: -1, left: nil, right: nil @type t :: %__MODULE__{} @display_skey_first_n_bytes 2 @display_hash_first_n_bytes 4 @doc "Provides dump of node info for root node" @spec root_info(t) :: tuple def root_info(%Node{} = node) do skey = trunc_search_key(node.search_key) {node.key_hash, skey, node.height, node.left, node.right} end @doc "Provides raw dump of all Node info" @spec dump(t) :: tuple def dump(%Node{} = node) do # Provide raw tuple dump of fields {node.key_hash, node.search_key, node.key, node.value, node.height, node.left, node.right} end @doc "Provides node info to be used in Inspect protocol implementation" @spec info(t) :: tuple # Inner node def info(%Node{key_hash: hash, left: l, right: r} = node) when is_binary(hash) and not is_nil(l) and not is_nil(r) do # Truncate the hash so it's easier to read as well as the search key hash_head = trunc_hash_key(hash) skey = trunc_search_key(node.search_key) {"#{hash_head}..", skey, node.height, node.left, node.right} end # Leaf node def info(%Node{key_hash: hash, left: nil, right: nil} = node) when is_binary(hash) do # Truncate the hash so it's easier to read hash_head = trunc_hash_key(hash) {"#{hash_head}..", node.search_key, node.height} end def trunc_hash_key(seq) when is_binary(seq) do <<seq_head::binary-size(@display_hash_first_n_bytes)>> <> _rest = seq seq_head end def trunc_search_key(seq) when is_binary(seq) do size = byte_size(seq) head = case size < @display_skey_first_n_bytes do true -> <<search_head::binary-size(size)>> <> _rest = seq search_head false -> <<search_head::binary-size(@display_skey_first_n_bytes)>> <> _rest = seq search_head end # Only prepend and append patterns if we have a utf8 string case String.printable?(head) do true -> "<=#{head}..>" false -> head end end # Allows users to inspect this module type in a controlled manner defimpl Inspect do import Inspect.Algebra def inspect(t, opts) do info = Inspect.Tuple.inspect(Node.info(t), opts) concat(["", info, ""]) end end end
lib/merkel/node.ex
0.709321
0.49469
node.ex
starcoder
defmodule Assert do @moduledoc """ Assert the data type of environment variables at compile time """ @doc ~S""" ## Examples iex> System.put_env("NOT_INT", "123") iex> Assert.init("./test/assertions/1_assertions.txt") ** (RuntimeError) Expected environment variable NOT_INT to be type float. iex> System.put_env("NOT_FLOAT", "1.23") iex> Assert.init("./test/assertions/2_assertions.txt") ** (RuntimeError) Expected environment variable NOT_FLOAT to be type integer. iex> System.put_env("NOT_STRING", "str") iex> Assert.init("./test/assertions/3_assertions.txt") ** (RuntimeError) Expected environment variable NOT_STRING to be type boolean. iex> System.put_env("NOT_BOOL", "true") iex> Assert.init("./test/assertions/4_assertions.txt") ** (RuntimeError) Expected environment variable NOT_BOOL to be type binary. iex> System.put_env("BOOL", "true") iex> Assert.init("./test/assertions/5_assertions.txt") :ok iex> System.put_env("JSON", "{\"key\": \"value\"}") iex> Assert.init("./test/assertions/6_assertions.txt") :ok """ import Const @spec init(String.t) :: :ok def init(file \\ "assertions.txt"), do: get_file(file) # -- Private -- @spec get_file(String.t) :: :ok defp get_file(file) do file |> File.stream! |> Stream.map(fn line -> parse_assertion(line) end) |> Stream.each(fn args -> assert(args) end) |> Stream.run end @spec parse_assertion(String.t) :: {String.t, String.t, String.t, String.t} defp parse_assertion(str) do str |> String.trim_trailing |> String.split(" ") |> List.to_tuple end @spec assert({String.t, String.t, String.t, String.t}) :: :ok defp assert({var, _is, "not", "nil"}), do: fetch!(var) defp assert({var, is, "type", "string"}), do: assert({var, is, "type", "binary"}) defp assert({var, _is, "type", value}) do case apply(Kernel, "is_#{value}" |> String.to_atom(), [fetch!(var)]) do false -> raise "Expected environment variable #{var} to be type #{value}." true -> :ok end end defp assert(_), do: :ok end
lib/assert.ex
0.808559
0.47524
assert.ex
starcoder
defprotocol Numy.Vc do @moduledoc """ Interface to immutable Vector. """ @doc "Make a clone" def clone(v) @doc "Assign 0.0 to each element of the vector." def assign_zeros(v) @doc "Assign 1.0 to each element of the vector." def assign_ones(v) @doc "Assign random values to the elements." def assign_random(v) @doc "Assign some value to all elements." def assign_all(v, val) @doc "Return true if vector is empty." def empty?(v) @doc "Return size/length of the vector." def size(v) @doc "Get data as a list" def data(v, nelm \\ -1) @doc "Get value of N-th element by index, return default in case of error." def at(v, index, default \\ nil) @doc "Check if elements of 2 vectors are practically the same." def equal?(v1,v2) @doc "Add 2 vectors, cᵢ ← aᵢ + bᵢ" def add(v1, v2) @doc "Subtract one vector from other, cᵢ ← aᵢ - bᵢ" def sub(v1, v2) @doc "Multiply 2 vectors, cᵢ ← aᵢ×bᵢ" def mul(v1, v2) @doc "Divide 2 vectors, cᵢ ← aᵢ÷bᵢ" def div(v1, v2) @doc "Multiply each element by a constant, aᵢ ← aᵢ×scale_factor" def scale(v, factor) @doc "Add a constant to each element, aᵢ ← aᵢ + offset" def offset(v, off) @doc "Change sign of each element, aᵢ ← -aᵢ" def negate(v) @doc "Dot product of 2 vectors, ∑aᵢ×bᵢ" def dot(v1, v2) @doc "Sum of all elements, ∑aᵢ" def sum(v) @doc "Average (∑aᵢ)/length" def mean(v) @doc "Return max value" def max(v) @doc "Return min value" def min(v) @doc "Return index of max value" def max_index(v) @doc "Return index of min value" def min_index(v) @doc "Step function, aᵢ ← 0 if aᵢ < 0 else 1" def apply_heaviside(v, cutoff \\ 0.0) @doc "f(x) = 1/(1 + e⁻ˣ)" def apply_sigmoid(v) @doc "Sort elements" def sort(v) @doc "Reverse" def reverse(v) @doc "Concatenate 2 vectors" def concat(v1,v2) @doc "Find value in vector, returns position, -1 if could not find" def find(v,val) @doc "Return true if vector contains the value" def contains?(v,val) @doc "√x₀² + x₁² + ... + xₙ²" def norm2(v) @doc """ iex(2)> Numy.Lapack.Vector.new(-3..3) |> Numy.Vc.pow2 #Vector<size=7, [9.0, 4.0, 1.0, 0.0, 1.0, 4.0, 9.0]> """ def pow2(v) def pow(v,p) @doc """ iex(1)> Numy.Lapack.Vector.new(-3..3) |> Numy.Vc.abs #Vector<size=7, [3.0, 2.0, 1.0, 0.0, 1.0, 2.0, 3.0]> """ def abs(v) end defprotocol Numy.Vcm do @moduledoc """ Interface to mutable Vector. Native objects do not follow Elixir/Erlang model where an object is always immutable. We purposefully allow native objects to be mutable in order to get better performance in numerical computing. """ @doc """ Mutate a vector by adding other to it, v1 = v1 + v2. Return mutated vector. """ def add!(v1, v2) def sub!(v1, v2) def mul!(v1, v2) def div!(v1, v2) @doc "Multiply each element by a constant, aᵢ ← aᵢ×scale_factor" def scale!(v, factor) @doc "Add a constant to each element, aᵢ ← aᵢ + offset" def offset!(v, off) @doc "Change sign of each element, aᵢ ← -aᵢ" def negate!(v) @doc "Step function, aᵢ ← 0 if aᵢ < 0 else 1" def apply_heaviside!(v, cutoff \\ 0.0) @doc "f(x) = 1/(1 + e⁻ˣ)" def apply_sigmoid!(v) @doc "Sort elements of vector in-place" def sort!(v) @doc "Reverse elements of vector in-place" def reverse!(v) @doc "Set N-th element to a new value" def set_at!(v, index, val) @doc "aᵢ ← aᵢ×factor_a + bᵢ×factor_b" def axpby!(v1, v2, f1, f2) def abs!(v) def pow2!(v) def pow!(v,p) end
lib/vector/vc.ex
0.848753
0.557002
vc.ex
starcoder
defmodule Expat.Macro do @moduledoc """ Expat internals for working with Macro.t() """ && false alias Expat, as: E @doc "Defines a named pattern" @spec define_pattern(defm :: :defmacro | :defmacrop, E.pattern()) :: E.pattern() def define_pattern(defm, pattern) def define_pattern(defm, {:|, _, [head, alts]}) do define_union_pattern(defm, union_head(head), collect_alts(alts)) end def define_pattern(defm, pattern) do define_simple_pattern(defm, pattern) end @doc "Expands a pattern" @spec expand(pattern :: E.pattern(), opts :: list) :: Macro.t() def expand(pattern, opts) when is_list(opts) do binds = Keyword.delete(opts, :_) expat_opts = Keyword.get_values(opts, :_) |> Enum.concat() name = pattern_name(pattern) counter = :erlang.unique_integer([:positive]) pattern = pattern |> remove_line |> set_expansion_counter(counter, name) guard = pattern_guard(pattern) value = pattern |> pattern_value |> bind(binds) |> make_under # remove names bound on this expansion bounds = bound_names_in_ast(value) # only delete the first to allow sub expansions take the rest binds = Enum.reduce(bounds, binds, &Keyword.delete_first(&2, &1)) opts = [_: expat_opts] ++ binds {value, guard} = expand_arg_collecting_guard(value, guard, opts) result = (guard && {:when, [context: Elixir], [value, guard]}) || value code = cond do expat_opts[:escape] -> Macro.escape(result) expat_opts[:build] && guard -> quote do fn -> case unquote(value) do x when unquote(guard) -> x end end.() end :else -> result end if expat_opts[:show], do: show(code) code end def expand_inside(expr, opts) do Macro.postwalk(expr, &do_expand_inside(&1, opts)) end ## Private parts bellow defp do_expand_inside({defn, c, [head, rest]}, opts) when defn == :def or defn == :defp or defn == :defmacro or defn == :defmacrop do args = pattern_args(head) guard = pattern_guard(head) {args, guard} = expand_args_collecting_guard(args, guard, opts) head = head |> update_pattern_guard(fn _ -> guard end) |> update_pattern_args(fn _ -> args end) {defn, c, [head, rest]} end defp do_expand_inside({:fn, c, clauses}, opts) do clauses = clauses |> Enum.map(fn {:->, a, [[e], body]} -> {:->, a, [[expand_calls_inside(e, opts)], body]} end) {:fn, c, clauses} end defp do_expand_inside({:case, c, [v, [do: clauses]]}, opts) do clauses = clauses |> Enum.map(fn {:->, a, [[e], body]} -> {:->, a, [[expand_calls_inside(e, opts)], body]} end) {:case, c, [v, [do: clauses]]} end defp do_expand_inside({:with, c, clauses}, opts) do clauses = clauses |> Enum.map(fn {:<-, a, [p, e]} -> {:<-, a, [expand_calls_inside(p, opts), e]} x -> x end) {:with, c, clauses} end defp do_expand_inside(ast, _opts), do: ast defp expand_args_collecting_guard(args, guard, opts) do Enum.map_reduce(args, guard, fn arg, guard -> expand_arg_collecting_guard(arg, guard, opts) end) end defp expand_arg_collecting_guard(ast, guard, opts) do expand_calls_collect({ast, {true, guard}}, opts) end defp expand_calls_collect({ast, {false, final}}, _), do: {ast, final} defp expand_calls_collect({ast, {true, initial}}, opts) do env = Keyword.get(opts, :_, []) |> Keyword.get(:env, __ENV__) Macro.traverse(ast, {false, initial}, fn x, y -> {x, y} end, fn x = {c, m, args}, y = {_, acc} when is_list(args) -> if to_string(c) =~ ~R/^[a-z]/ do expat_opts = [_: [escape: true]] args = args |> Enum.reverse() |> case do [o | rest] when is_list(o) -> if Keyword.keyword?(o) do [expat_opts ++ o] ++ rest else [expat_opts, o] ++ rest end x -> [expat_opts] ++ x end |> Enum.reverse() {c, m, args} |> Code.eval_quoted([], env) |> elem(0) |> collect_guard(acc) |> (fn {x, y} -> {x, {true, y}} end).() else {x, y} end x, y -> {x, y} end) |> expand_calls_collect(opts) end defp collect_guard({:when, _, [expr, guard]}, prev) do {expr, and_guard(prev, guard)} end defp collect_guard(expr, guard) do {expr, guard} end defp and_guard(nil, guard), do: guard defp and_guard(a, b), do: quote(do: unquote(a) and unquote(b)) defp expand_calls_inside(ast, opts) do {expr, guard} = case ast do {:when, _, [ast, guard]} -> expand_arg_collecting_guard(ast, guard, opts) _ -> expand_arg_collecting_guard(ast, nil, opts) end (guard && {:when, [], [expr, guard]}) || expr end @doc "Make underable variables an underscore to be ignored" && false defp make_under(pattern) do Macro.prewalk(pattern, fn v = {_, m, _} -> (m[:underable] && {:_, [], nil}) || v x -> x end) end @doc "Mark variables in pattern that are not used in guards" && false defp mark_non_guarded(pattern) do vars_in_guards = pattern |> pattern_guard |> ast_variables value = pattern |> pattern_value |> Macro.prewalk(fn v = {_, [{:underable, true} | _], _} -> v v = {n, m, c} when is_atom(n) and is_atom(c) -> unless Enum.member?(vars_in_guards, v) do {n, [underable: true] ++ m, c} else v end x -> x end) pattern |> update_pattern_value(fn _ -> value end) end @doc "Marks all variables with the name they can be bound to" && false defp mark_bindable(pattern) do Macro.prewalk(pattern, fn {a, m, c} when is_atom(a) and is_atom(c) -> if to_string(a) =~ ~r/^_/ do {a, m, c} else {a, [bindable: a] ++ m, c} end x -> x end) end defp ast_variables(nil), do: [] defp ast_variables(ast) do {_, acc} = Macro.traverse(ast, [], fn x, y -> {x, y} end, fn v = {n, _, c}, acc when is_atom(n) and is_atom(c) -> {v, [v] ++ acc} ast, acc -> {ast, acc} end) acc |> Stream.uniq_by(fn {a, _, _} -> a end) |> Enum.reverse() end defp bind(pattern, binds) do pattern |> Macro.prewalk(fn x = {_, [{:bound, _} | _], _} -> x {a, m = [{:bindable, b} | _], c} -> case List.keyfind(binds, b, 0) do nil -> {a, m, c} {_, var = {vn, vm, vc}} when is_atom(vn) and is_atom(vc) -> if m[:underable] do {vn, [bound: b] ++ vm, vc} else {:=, [bound: b], [var, {a, [bound: b] ++ m, c}]} end {_, expr} -> if m[:underable] do expr else {:=, [bound: b], [{a, [bound: b] ++ m, c}, expr]} end end x -> x end) end defp update_pattern_value(pattern, up) when is_function(up, 1) do update_pattern_head(pattern, fn {name, c, [value]} -> {name, c, [up.(value)]} end) end defp pattern_value(pattern) do {_, _, [value]} = pattern |> pattern_head value end defp pattern_args(pattern) do {_, _, args} = pattern |> pattern_head args end defp update_pattern_args(pattern, up) when is_function(up, 1) do update_pattern_head(pattern, fn {name, c, args} -> {name, c, up.(args)} end) end defp update_pattern_guard(pattern, up) when is_function(up, 1) do case pattern do {:when, x, [head, guard]} -> new_guard = up.(guard) if new_guard do {:when, x, [head, new_guard]} else head end head -> new_guard = up.(nil) if new_guard do {:when, [context: Elixir], [head, new_guard]} else head end end end defp pattern_guard(pattern) do case pattern do {:when, _, [_head, guard]} -> guard _ -> nil end end defp update_pattern_head(pattern, up) when is_function(up, 1) do case pattern do {:when, x, [head, guard]} -> {:when, x, [up.(head), guard]} head -> up.(head) end end defp pattern_head(pattern) do case pattern do {:when, _, [head, _guard]} -> head head -> head end end defp pattern_name(pattern) do {name, _, _} = pattern |> pattern_head name end defp meta_in_ast(ast, key) do {_, acc} = Macro.traverse(ast, [], fn ast = {_, m, _}, acc -> (m[key] && {ast, [m[key]] ++ acc}) || {ast, acc} ast, acc -> {ast, acc} end, fn x, y -> {x, y} end) acc |> Stream.uniq() |> Enum.reverse() end defp bindable_names_in_ast(ast) do ast |> meta_in_ast(:bindable) end defp bound_names_in_ast(ast) do ast |> meta_in_ast(:bound) end def show(ast) do IO.puts(Macro.to_string(ast)) ast end defp remove_line(ast) do Macro.postwalk(ast, &Macro.update_meta(&1, fn x -> Keyword.delete(x, :line) end)) end defp set_expansion_counter(ast, counter, pattern_name) do Macro.postwalk(ast, fn s = {x, m, y} when is_atom(x) and is_atom(y) -> cond do match?("_" <> _, to_string(x)) -> s m[:bindable] && !m[:expat_pattern] -> {x, m ++ [counter: counter, expat_pattern: pattern_name], y} :else -> s end x -> x end) end defp pattern_bang(defm, name, escaped, arg_names, opts) do vars = arg_names |> Enum.map(&Macro.var(&1, __MODULE__)) argt = vars |> Enum.map(fn name -> quote do: unquote(name) :: any end) kw = Enum.zip([arg_names, vars]) bang = :"#{name}!" quote do @doc """ Builds data using the `#{unquote(name)}` pattern. See `#{unquote(name)}/0`. """ @spec unquote(bang)(unquote_splicing(argt)) :: any unquote(defm)(unquote(bang)(unquote_splicing(vars))) do opts = unquote(kw) ++ [_: [build: true]] ++ unquote(opts) Expat.Macro.expand(unquote(escaped), opts) end end end defp pattern_zero(defm, name, pattern, escaped, arg_names, opts) do doc = pattern_zero_doc(name, pattern, arg_names) quote do @doc unquote(doc) unquote(defm)(unquote(name)()) do Expat.Macro.expand(unquote(escaped), unquote(opts)) end end end defp pattern_zero_doc(name, pattern, arg_names) do value = pattern |> pattern_value guard = pattern |> pattern_guard code = cond do guard -> {:when, [], [value, guard]} true -> value end |> Macro.to_string() first_name = arg_names |> List.first() """ Expands the `#{name}` pattern. #{code} ## Binding Variables The following variables can be bound by giving them to `#{name}` as keys on its last argument Keyword. #{arg_names |> Enum.map(&":#{&1}") |> Enum.join(", ")} For example: #{name}(#{first_name}: x) Where `x` can be any value, variable in your scope or another pattern expansion. Not mentioned variables will be unbound and replaced by an `_` at expansion site. Likewise, calling `#{name}()` with no argumens will replace all its variables with `_`. ## Positional Variables `#{name}` variables can also be bound by position, provided the last them is not a Keyword. For example: #{name}(#{Enum.join(arg_names, ", ")}, bindings = []) ## Bang Constructor The `#{name}!` constructor can be used to build data and make sure the guards are satisfied. Note that this macro can only be used as an expression and not as a matching pattern. For example: #{name}!(#{Enum.join(arg_names, ", ")}) """ end defp pattern_defs(defm, name, escaped, arg_names, opts) do arities = 0..length(arg_names) Enum.map(arities, fn n -> args = arg_names |> Enum.take(n) last = arg_names |> Enum.at(n) vars = args |> Enum.map(&Macro.var(&1, __MODULE__)) argt = vars |> Enum.map(fn name -> quote do: unquote(name) :: any end) kw = Enum.zip([args, vars]) quote do @doc """ Expands the `#{unquote(name)}` pattern. See `#{unquote(name)}/0`. """ @spec unquote(name)(unquote_splicing(argt), bindings :: keyword) :: any unquote(defm)(unquote(name)(unquote_splicing(vars), bindings)) unquote(defm)(unquote(name)(unquote_splicing(vars), opts)) do opts = (Keyword.keyword?(opts) && opts) || [{unquote(last), opts}] opts = unquote(kw) ++ opts ++ unquote(opts) Expat.Macro.expand(unquote(escaped), opts) end end end) end defp define_simple_pattern(defm, pattern) do name = pattern_name(pattern) bindable = pattern |> mark_non_guarded |> mark_bindable escaped = bindable |> Macro.escape() opts = quote do [_: [env: __CALLER__, name: unquote(name)]] end arg_names = bindable |> pattern_args |> bindable_names_in_ast defs = pattern_defs(defm, name, escaped, arg_names, opts) zero = pattern_zero(defm, name, pattern, escaped, arg_names, opts) bang = pattern_bang(defm, name, escaped, arg_names, opts) defs = [bang, zero] ++ defs {:__block__, [], defs} end defp collect_alts({:|, _, [a, b]}) do [a | collect_alts(b)] end defp collect_alts(x) do [x] end defp union_head({name, _, x}) when is_atom(name) and (is_atom(x) or [] == x) do # foo({:foo, foo}) {name, [], [{name, {name, [], nil}}]} end defp union_head(head), do: head defp define_union_pattern(defm, head, alts) do head_name = pattern_name(head) head_pats = define_simple_pattern(defm, head) alts_pats = alts |> Enum.map(fn alt -> alt = update_pattern_args(alt, &[{head_name, [], &1}]) define_simple_pattern(defm, alt) end) {:__block__, [], [head_pats, alts_pats]} end end
lib/expat/macro.ex
0.613121
0.413832
macro.ex
starcoder
defmodule AWS do @moduledoc """ AWS provides an API to talk with Amazon Web Services. Each module in this project corresponds with an AWS service, and they can be used by calling the functions of those modules. For example, "AWS DynamoDB" operations can be found in `AWS.DynamoDB` module. First we need to setup a `AWS.Client` structure with credentials and details about the region we want to use. client = %AWS.Client{ access_key_id: "<access-key-id>", secret_access_key: "<secret-access-key>", region: "us-east-1" } Alternatively you can create a `client` with `AWS.Client.create/3`. So we pass this client struct to our service modules: {:ok, result, _http_response} = AWS.Kinesis.list_streams(client, %{}) The second argument in this case is the `input` which is a map with the parameters for [this operation](https://docs.aws.amazon.com/kinesis/latest/APIReference/API_ListStreams.html). Another example is the upload of a given file to `AWS.S3` using `AWS.S3.put_object/5`: client = AWS.Client.create("your-access-key-id", "your-secret-access-key", "us-east-1") file = File.read!("./tmp/your-file.txt") md5 = :crypto.hash(:md5, file) |> Base.encode64() AWS.S3.put_object(client, "your-bucket-name", "foo/your-file-on-s3.txt", %{"Body" => file, "ContentMD5" => md5}) You can find more details about those parameters in the [AWS API reference](https://docs.aws.amazon.com/index.html). ## Custom HTTP client and JSON/XML parsers You can customize your HTTP client or the module responsible for parsing and encoding JSON or XML by using options for the `AWS.Client`. By default, AWS Elixir uses hackney for the HTTP client, Jason for JSON, and a custom module for XML that is written on top of xmlerl. For more details, check `AWS.Client` documentation. """ defmodule ServiceMetadata do @moduledoc """ It is a struct containing AWS service metadata. Each service module has a function that returns its metadata. """ defstruct abbreviation: nil, api_version: nil, content_type: nil, credential_scope: nil, endpoint_prefix: nil, global?: nil, protocol: nil, service_id: nil, signature_version: nil, signing_name: nil, target_prefix: nil end end
lib/aws.ex
0.860516
0.434701
aws.ex
starcoder
defmodule ExCoveralls.Local do @moduledoc """ Locally displays the result to screen. """ defmodule Count do @moduledoc """ Stores count information for calculating coverage values. """ defstruct lines: 0, relevant: 0, covered: 0 end @doc """ Provides an entry point for the module. """ def execute(stats, options \\ []) do print_summary(stats, options) if options[:detail] == true do source(stats, options[:filter]) |> IO.puts end ExCoveralls.Stats.ensure_minimum_coverage(stats) end @doc """ Format the source code with color for the files that matches with the specified patterns. """ def source(stats, _patterns = nil), do: source(stats) def source(stats, _patterns = []), do: source(stats) def source(stats, patterns) do Enum.filter(stats, fn(stat) -> String.contains?(stat[:name], patterns) end) |> source end def source(stats) do stats |> Enum.map(&format_source/1) |> Enum.join("\n") end @doc """ Prints summary statistics for given coverage. """ def print_summary(stats, options \\ []) do enabled = ExCoveralls.Settings.get_print_summary table_enabled = ExCoveralls.Settings.get_print_summary_table cond do enabled and table_enabled -> file_width = ExCoveralls.Settings.get_file_col_width IO.puts "----------------" IO.puts print_string("~-6s ~-#{file_width}s ~8s ~8s ~8s", ["COV", "FILE", "LINES", "RELEVANT", "MISSED"]) coverage(stats, options ++ [list_files: true]) |> IO.puts IO.puts "----------------" enabled -> coverage(stats, options) |> IO.puts end end defp format_source(stat) do "\n\e[33m--------#{stat[:name]}--------\e[m\n" <> colorize(stat) end defp colorize(%{name: _name, source: source, coverage: coverage}) do lines = String.split(source, "\n") Enum.zip(lines, coverage) |> Enum.map(&do_colorize/1) |> Enum.join("\n") end defp do_colorize({line, coverage}) do case coverage do nil -> line 0 -> "\e[31m#{line}\e[m" _ -> "\e[32m#{line}\e[m" end end @doc """ Format the source coverage stats into string. """ def coverage(stats, options \\ []) do count_info = Enum.map(stats, fn(stat) -> [stat, calculate_count(stat[:coverage])] end) count_info = sort(count_info, options) case options[:list_files] do true -> Enum.join(format_body(count_info), "\n") <> "\n" _ -> "" end <> format_total(count_info) end defp sort(count_info, options) do if options[:sort] do sort_order = parse_sort_options(options) flattened = Enum.map(count_info, fn original -> [stat, count] = original %{ "cov" => get_coverage(count), "file" => stat[:name], "lines" => count.lines, "relevant" => count.relevant, "missed" => count.relevant - count.covered, :_original => original } end) sorted = Enum.reduce(sort_order, flattened, fn {key, comparator}, acc -> Enum.sort(acc, fn(x, y) -> args = [x[key], y[key]] apply(Kernel, comparator, args) end) end) Enum.map(sorted, fn flattened -> flattened[:_original] end) else Enum.sort(count_info, fn([x, _], [y, _]) -> x[:name] <= y[:name] end) end end defp parse_sort_options(options) do sort_order = options[:sort] |> String.split(",") |> Enum.reverse() Enum.map(sort_order, fn sort_chunk -> case String.split(sort_chunk, ":") do [key, "asc"] -> {key, :<=} [key, "desc"] -> {key, :>=} [key] -> {key, :>=} end end) end defp format_body(info) do Enum.map(info, &format_info/1) end defp format_info([stat, count]) do coverage = get_coverage(count) file_width = ExCoveralls.Settings.get_file_col_width print_string("~5.1f% ~-#{file_width}s ~8w ~8w ~8w", [coverage, stat[:name], count.lines, count.relevant, count.relevant - count.covered]) end defp format_total(info) do totals = Enum.reduce(info, %Count{}, fn([_, count], acc) -> append(count, acc) end) coverage = get_coverage(totals) print_string("[TOTAL] ~5.1f%", [coverage]) end defp append(a, b) do %Count{ lines: a.lines + b.lines, relevant: a.relevant + b.relevant, covered: a.covered + b.covered } end defp get_coverage(count) do case count.relevant do 0 -> default_coverage_value() _ -> (count.covered / count.relevant) * 100 end end defp default_coverage_value do options = ExCoveralls.Settings.get_coverage_options case Map.fetch(options, "treat_no_relevant_lines_as_covered") do {:ok, false} -> 0.0 _ -> 100.0 end end @doc """ Calucate count information from thhe coverage stats. """ def calculate_count(coverage) do do_calculate_count(coverage, 0, 0, 0) end defp do_calculate_count([], lines, relevant, covered) do %Count{lines: lines, relevant: relevant, covered: covered} end defp do_calculate_count([h|t], lines, relevant, covered) do case h do nil -> do_calculate_count(t, lines + 1, relevant, covered) 0 -> do_calculate_count(t, lines + 1, relevant + 1, covered) n when is_number(n) -> do_calculate_count(t, lines + 1, relevant + 1, covered + 1) _ -> raise "Invalid data - #{h}" end end defp print_string(format, params) do char_list = :io_lib.format(format, params) List.to_string(char_list) end end
lib/excoveralls/local.ex
0.619701
0.46393
local.ex
starcoder
defmodule Chain do @moduledoc """ Chain is inspired by the Railway programming and JavaScript well known Promise API. Its purpose is to ease the construction of multi-step data processing in a more readable manner than using elixir native `with` macro. Chain is more flexible than a `with` macro as the error recovery can be placed where you want. Chains can be passed as parameters like `Ecto.Multi` objects, and called once (synchronously) using `&Chain.run/1` A Chain is composed of steps, that are run only when `Chain.run(chain)` is called. A step can be of four types : - next: a step that represents the happy path, it receives the previous result that was a success. i.e. either a `{:ok, result}` or anything that is not `{:error, reason}`. It receives the unwrapped result (not `{:ok, result}`) as only argument. - recover: a step that a standard deviance from the happy path, it receives the previous result that was an error. i.e. a `{:error, reason}` tuple. It receives the unwrapped reason (not `{:error, reason}`) as only argument. - capture: a step that an unexpected deviance from the happy path. Useful in only special cases. (equivalent to try / rescue) It receives the error that was raised in any previous step, and if the function is of arity 2, also the stacktrace. - next_map: a step that receives the previous result, and does an operation like a map, but for function that returns :ok/:error tuples. Returns the enumerable with mapped values. Execution stops at first error tuple, error tuple that is passed to the rest of the chain steps. """ defstruct initial_value: nil, options: nil, steps: [] @doc """ Initialize a new Chain with an initial value and options for the chain execution. - To add success steps to the chain call `&Chain.next/2` or `&Chain.next_map/2`. - To add recover steps to the chain call `&Chain.recover/2`. - To add capture steps to the chain call `&Chain.capture/2`. The result wil be automatically wrapped in a `{:ok, value}` if the result is neither `{:ok, value}` nor `{:error, reason}`. If the initial value is either a `value` or `{:ok, value}`, it will go the nearest next step. If the initial value is `{:error, reason}` then the `reason` will be passed to the next recover step. """ def new(initial_value \\ nil, opts \\ []) do %Chain{initial_value: initial_value, options: opts} end @doc """ Adds a step to the chain. A next step is a function of arity 1. It takes the result of the previous step as parameter, and its result will be the parameter of the following step. """ def next(%Chain{} = chain, function) when is_function(function, 1) do new_step = Chain.Step.new_success_step(function) %Chain{chain | steps: [new_step | chain.steps]} end @doc """ Adds a recover step to the chain. A recover step is a function of arity 1. It takes the reason of the previous step that returned `{:error, reason}` as parameter, and its result will be the parameter of the following step. """ def recover(%Chain{} = chain, function) when is_function(function, 1) do new_step = Chain.Step.new_recover_step(function) %Chain{chain | steps: [new_step | chain.steps]} end @doc """ Adds a capture step to the chain. A capture step is a function of arity 1 or 2. If the function is of arity 1, it receives the error that was raised, if the arity is 2 the function receives the raised error and the stacktrace captured when the error was raised. """ def capture(%Chain{} = chain, function) when is_function(function, 1) or is_function(function, 2) do new_step = Chain.Step.new_capture_step(function) %Chain{chain | steps: [new_step | chain.steps]} end @doc """ Adds a next map step to the chain. A next_map takes an enumerable as entry and maps over all elements with the provided function. If the map functions returns an error tuple, the execution stops and that error is given to the following steps. The same rules apply to the function return values as for next step. (i.e. can be a ok tuple, an error tuple, a Chain Struct, or anything else which will be considered as a ok value) ``` [1, 2, 3] |> Chain.new() |> Chain.next_map(fn value -> {:ok, value + 1} end) |> Chain.run() # {:ok, [2, 3, 4]} ``` """ def next_map(%Chain{} = chain, function) when is_function(function, 1) do map_function = fn enumerable -> enumerable |> Enum.reduce(Chain.new([]), fn element, chain -> chain |> Chain.next(fn mapped_enumerable -> element |> Chain.new() |> Chain.next(function) |> Chain.next(fn mapped_element -> mapped_enumerable ++ [mapped_element] end) end) end) |> Chain.run() end new_step = Chain.Step.new_success_step(map_function) %Chain{chain | steps: [new_step | chain.steps]} end @doc """ Executes the chain. Returns the result from the last function executed. (either a `{:ok, value}` or a `{:error, reason}` if a failure was not recovered, and raises if one of the steps raised an error and no capture step rescued it) """ def run(%Chain{} = chain) do chain.steps |> Enum.reverse() |> Enum.reduce(normalize_result(chain.initial_value), &run_step/2) |> manage_raised_error_case() end defp manage_raised_error_case({:ok, result}), do: {:ok, result} defp manage_raised_error_case({:error, reason}), do: {:error, reason} defp manage_raised_error_case({:raised_error, error, stacktrace}), do: reraise(error, stacktrace) defp run_step(%Chain.Step{} = step, previous_result) do success_type = Chain.Step.success_type() recover_type = Chain.Step.recover_type() capture_type = Chain.Step.capture_type() case {step.type, previous_result} do {^success_type, {:ok, value}} -> run_step_function(step, value) {^recover_type, {:error, reason}} -> run_step_function(step, reason) {^capture_type, {:raised_error, error, stacktrace}} -> run_capture_step_function(step, error, stacktrace) _ -> previous_result end end defp run_step_function(step, value) do try do step.function.(value) |> normalize_result() rescue e -> {:raised_error, e, __STACKTRACE__} end end defp run_capture_step_function(step, error, stacktrace) do {:arity, arity} = Function.info(step.function, :arity) try do case arity do 1 -> step.function.(error) 2 -> step.function.(error, stacktrace) end |> normalize_result() rescue e -> {:raised_error, e, __STACKTRACE__} end end defp normalize_result(result) do case result do {:ok, value} -> {:ok, value} {:error, reason} -> {:error, reason} {:raised_error, error, stacktrace} -> {:raised_error, error, stacktrace} %Chain{} = chain -> Chain.run(chain) value -> {:ok, value} end end end
lib/chain.ex
0.850887
0.949201
chain.ex
starcoder
defmodule MMDB2Encoder.Data do @moduledoc false # standard data types @binary 2 @bytes 4 @extended 0 # extended data types @extended_boolean 7 @extended_cache_container 5 @extended_end_marker 6 @type datatype :: :binary | :boolean | :bytes | :cache_container | :end_marker @type valuetype :: binary | boolean | :cache_container | :end_marker @doc """ Encodes a value with automatic type selection. """ @spec encode(value :: valuetype) :: <<_::8>> def encode(value) when is_binary(value), do: encode(:binary, value) def encode(value) when is_boolean(value), do: encode(:boolean, value) def encode(:cache_container), do: encode(:cache_container, :cache_container) def encode(:end_marker), do: encode(:end_marker, :end_marker) @doc """ Encodes a value to the appropriate MMDB2 representation. """ @spec encode(type :: datatype, value :: valuetype) :: <<_::8>> def encode(:binary, ""), do: <<@binary::size(3), 0::size(5)>> def encode(:binary, binary) when is_binary(binary) and byte_size(binary) >= 65_821, do: <<@binary::size(3), 31::size(5), byte_size(binary) - 65_821::size(24), binary::binary>> def encode(:binary, binary) when is_binary(binary) and byte_size(binary) >= 285, do: <<@binary::size(3), 30::size(5), byte_size(binary) - 285::size(16), binary::binary>> def encode(:binary, binary) when is_binary(binary) and byte_size(binary) >= 29, do: <<@binary::size(3), 29::size(5), byte_size(binary) - 29::size(8), binary::binary>> def encode(:binary, binary) when is_binary(binary), do: <<@binary::size(3), byte_size(binary)::size(5), binary::binary>> def encode(:boolean, true), do: <<@extended::size(3), 1::size(5), @extended_boolean>> def encode(:boolean, false), do: <<@extended::size(3), 0::size(5), @extended_boolean>> def encode(:bytes, ""), do: <<@bytes::size(3), 0::size(5)>> def encode(:bytes, bytes) when is_binary(bytes) and byte_size(bytes) >= 65_821, do: <<@bytes::size(3), 31::size(5), byte_size(bytes) - 65_821::size(24), bytes::binary>> def encode(:bytes, bytes) when is_binary(bytes) and byte_size(bytes) >= 285, do: <<@bytes::size(3), 30::size(5), byte_size(bytes) - 285::size(16), bytes::binary>> def encode(:bytes, bytes) when is_binary(bytes) and byte_size(bytes) >= 29, do: <<@bytes::size(3), 29::size(5), byte_size(bytes) - 29::size(8), bytes::binary>> def encode(:bytes, bytes) when is_binary(bytes), do: <<@bytes::size(3), byte_size(bytes)::size(5), bytes::binary>> def encode(:cache_container, :cache_container), do: <<@extended::size(3), 0::size(5), @extended_cache_container>> def encode(:end_marker, :end_marker), do: <<@extended::size(3), 0::size(5), @extended_end_marker>> end
lib/mmdb2_encoder/data.ex
0.85558
0.502869
data.ex
starcoder
defmodule Day16 do def version_sum(str) do str |> parse() |> then(fn %{version: v} -> v end) end def parse(str) when is_binary(str) do str |> String.split("", trim: true) |> Enum.map(&String.to_integer(&1, 16)) |> Enum.map(&Integer.digits(&1, 2)) |> Enum.flat_map(&pad/1) |> parse |> elem(1) end def parse([v1, v2, v3, 1, 0, 0 | rest]) do version = Integer.undigits([v1, v2, v3], 2) type_id = 4 {bits, value} = parse_literal(rest, []) {bits, %{version: version, type_id: type_id, value: fn -> value end}} end def parse([v1, v2, v3, id1, id2, id3, 0 | rest]) do version = Integer.undigits([v1, v2, v3], 2) type_id = Integer.undigits([id1, id2, id3], 2) {value, rest} = Enum.split(rest, 15) length = Integer.undigits(value, 2) {raw, rest} = Enum.split(rest, length) ops = raw |> parse_all([]) version_sum = ops |> Enum.map(fn %{version: v} -> v end) |> Enum.reduce(version, &Kernel.+/2) value = ops |> value_fn(type_id) {rest, %{version: version_sum, type_id: type_id, value: value}} end def parse([v1, v2, v3, id1, id2, id3, 1 | rest]) do version = Integer.undigits([v1, v2, v3], 2) type_id = Integer.undigits([id1, id2, id3], 2) {value, rest} = Enum.split(rest, 11) count = Integer.undigits(value, 2) {rest, ops} = parse_n(rest, count, []) version_sum = ops |> Enum.map(fn %{version: v} -> v end) |> Enum.reduce(version, &Kernel.+/2) {rest, %{version: version_sum, type_id: type_id, value: value_fn(ops, type_id)}} end def compute(str) when is_binary(str) do str |> parse() |> then(fn %{value: v} -> v.() end) end def value_fn(ops, 0), do: values(ops, fn acc -> Enum.reduce(acc, &Kernel.+/2) end) def value_fn(ops, 1), do: values(ops, fn acc -> Enum.reduce(acc, &Kernel.*/2) end) def value_fn(ops, 2), do: values(ops, fn acc -> Enum.min(acc) end) def value_fn(ops, 3), do: values(ops, fn acc -> Enum.max(acc) end) def value_fn(ops, 5), do: values(ops, fn [a, b] when a > b -> 1 _ -> 0 end) def value_fn(ops, 6), do: values(ops, fn [a, b] when a < b -> 1 _ -> 0 end) def value_fn(ops, 7), do: values(ops, fn [a, a] -> 1 _ -> 0 end) defp values(ops, func) do fn -> ops |> Enum.map(fn %{value: v} -> v.() end) |> func.() end end defp parse_n(bits, 0, instrs), do: {bits, Enum.reverse(instrs)} defp parse_n(bits, n, instrs) do {bits, op} = parse(bits) parse_n(bits, n - 1, [op | instrs]) end defp parse_all([], instrs), do: Enum.reverse(instrs) defp parse_all(bits, instrs) do {bits, op} = parse(bits) parse_all(bits, [op | instrs]) end defp parse_literal([1, v1, v2, v3, v4 | rest], value), do: parse_literal(rest, [v4, v3, v2, v1 | value]) defp parse_literal([0, v1, v2, v3, v4 | rest], value) do value = [v4, v3, v2, v1 | value] |> Enum.reverse() |> Integer.undigits(2) {rest, value} end defp pad([a]), do: [0, 0, 0, a] defp pad([a, b]), do: [0, 0, a, b] defp pad([a, b, c]), do: [0, a, b, c] defp pad([a, b, c, d]), do: [a, b, c, d] end
year_2021/lib/day_16.ex
0.594551
0.558327
day_16.ex
starcoder
defmodule Protobuf.Encoder do import Protobuf.WireTypes import Bitwise, only: [bsr: 2, band: 2, bsl: 2, bor: 2] alias Protobuf.{MessageProps, FieldProps} @spec encode(atom, struct, keyword) :: iodata def encode(mod, struct, opts) do case struct do %{__struct__: _} -> encode(struct, opts) _ -> encode(mod.new(struct), opts) end end @spec encode(struct, keyword) :: iodata def encode(%mod{} = struct, opts \\ []) do res = encode!(struct, mod.__message_props__()) case Keyword.fetch(opts, :iolist) do {:ok, true} -> res _ -> IO.iodata_to_binary(res) end end @spec encode!(struct, MessageProps.t()) :: iodata def encode!(struct, %{field_props: field_props} = props) do syntax = props.syntax oneofs = oneof_actual_vals(props, struct) encode_fields(Map.values(field_props), syntax, struct, oneofs, []) |> Enum.reverse() catch {e, msg, st} -> reraise e, msg, st end def encode_fields([], _, _, _, acc) do acc end def encode_fields([prop | tail], syntax, struct, oneofs, acc) do %{name_atom: name, oneof: oneof, enum?: is_enum, type: type} = prop val = if oneof do oneofs[name] else case struct do %{^name => v} -> v _ -> nil end end if skip_field?(syntax, val, prop) || (is_enum && !oneof && is_enum_default(type, val)) do encode_fields(tail, syntax, struct, oneofs, acc) else acc = [encode_field(class_field(prop), val, prop) | acc] encode_fields(tail, syntax, struct, oneofs, acc) end rescue error -> stacktrace = System.stacktrace() msg = "Got error when encoding #{inspect(struct.__struct__)}##{prop.name_atom}: #{ Exception.format(:error, error) }" throw({Protobuf.EncodeError, [message: msg], stacktrace}) end @doc false def skip_field?(syntax, val, prop) def skip_field?(_, [], _), do: true def skip_field?(_, v, _) when map_size(v) == 0, do: true def skip_field?(:proto2, nil, %{optional?: true}), do: true def skip_field?(:proto3, nil, _), do: true def skip_field?(:proto3, 0, %{oneof: nil}), do: true def skip_field?(:proto3, 0.0, %{oneof: nil}), do: true def skip_field?(:proto3, "", %{oneof: nil}), do: true def skip_field?(:proto3, false, %{oneof: nil}), do: true def skip_field?(_, _, _), do: false @spec encode_field(atom, any, FieldProps.t()) :: iodata def encode_field(:normal, val, %{encoded_fnum: fnum, type: type, repeated?: is_repeated}) do repeated_or_not(val, is_repeated, fn v -> [fnum, encode_type(type, v)] end) end def encode_field( :embedded, val, %{encoded_fnum: fnum, repeated?: is_repeated, map?: is_map, type: type} = prop ) do repeated = is_repeated || is_map repeated_or_not(val, repeated, fn v -> v = if is_map, do: struct(prop.type, %{key: elem(v, 0), value: elem(v, 1)}), else: v # so that oneof {:atom, v} can be encoded encoded = encode(type, v, []) byte_size = byte_size(encoded) [fnum, encode_varint(byte_size), encoded] end) end def encode_field(:packed, val, %{type: type, encoded_fnum: fnum}) do encoded = Enum.map(val, fn v -> encode_type(type, v) end) byte_size = IO.iodata_length(encoded) [fnum, encode_varint(byte_size), encoded] end @spec class_field(map) :: atom def class_field(%{wire_type: wire_delimited(), embedded?: true}) do :embedded end def class_field(%{repeated?: true, packed?: true}) do :packed end def class_field(_) do :normal end @spec encode_fnum(integer, integer) :: iodata def encode_fnum(fnum, wire_type) do fnum |> bsl(3) |> bor(wire_type) |> encode_varint end @spec encode_type(atom, any) :: iodata def encode_type(:int32, n) when n >= -0x80000000 and n <= 0x7FFFFFFF, do: encode_varint(n) def encode_type(:int64, n) when n >= -0x8000000000000000 and n <= 0x7FFFFFFFFFFFFFFF, do: encode_varint(n) def encode_type(:string, n), do: encode_type(:bytes, n) def encode_type(:uint32, n) when n >= 0 and n <= 0xFFFFFFFF, do: encode_varint(n) def encode_type(:uint64, n) when n >= 0 and n <= 0xFFFFFFFFFFFFFFFF, do: encode_varint(n) def encode_type(:bool, true), do: encode_varint(1) def encode_type(:bool, false), do: encode_varint(0) def encode_type({:enum, type}, n) when is_atom(n), do: n |> type.value() |> encode_varint() def encode_type({:enum, _}, n), do: encode_varint(n) def encode_type(:float, :infinity), do: <<0, 0, 128, 127>> def encode_type(:float, :negative_infinity), do: <<0, 0, 128, 255>> def encode_type(:float, :nan), do: <<0, 0, 192, 127>> def encode_type(:float, n), do: <<n::32-float-little>> def encode_type(:double, :infinity), do: <<0, 0, 0, 0, 0, 0, 240, 127>> def encode_type(:double, :negative_infinity), do: <<0, 0, 0, 0, 0, 0, 240, 255>> def encode_type(:double, :nan), do: <<1, 0, 0, 0, 0, 0, 248, 127>> def encode_type(:double, n), do: <<n::64-float-little>> def encode_type(:bytes, n) do bin = IO.iodata_to_binary(n) len = bin |> byte_size |> encode_varint <<len::binary, bin::binary>> end def encode_type(:sint32, n) when n >= -0x80000000 and n <= 0x7FFFFFFF, do: n |> encode_zigzag |> encode_varint def encode_type(:sint64, n) when n >= -0x8000000000000000 and n <= 0x7FFFFFFFFFFFFFFF, do: n |> encode_zigzag |> encode_varint def encode_type(:fixed64, n) when n >= 0 and n <= 0xFFFFFFFFFFFFFFFF, do: <<n::64-little>> def encode_type(:sfixed64, n) when n >= -0x8000000000000000 and n <= 0x7FFFFFFFFFFFFFFF, do: <<n::64-signed-little>> def encode_type(:fixed32, n) when n >= 0 and n <= 0xFFFFFFFF, do: <<n::32-little>> def encode_type(:sfixed32, n) when n >= -0x80000000 and n <= 0x7FFFFFFF, do: <<n::32-signed-little>> def encode_type(type, n) do raise Protobuf.TypeEncodeError, message: "#{inspect(n)} is invalid for type #{type}" end @spec encode_zigzag(integer) :: integer def encode_zigzag(val) when val >= 0, do: val * 2 def encode_zigzag(val) when val < 0, do: val * -2 - 1 @spec encode_varint(integer) :: iodata def encode_varint(n) when n < 0 do <<n::64-unsigned-native>> = <<n::64-signed-native>> encode_varint(n) end def encode_varint(n) when n <= 127 do <<n>> end def encode_varint(n) do [<<1::1, band(n, 127)::7>> | encode_varint(bsr(n, 7))] |> IO.iodata_to_binary() end @spec wire_type(atom) :: integer def wire_type(:int32), do: wire_varint() def wire_type(:int64), do: wire_varint() def wire_type(:uint32), do: wire_varint() def wire_type(:uint64), do: wire_varint() def wire_type(:sint32), do: wire_varint() def wire_type(:sint64), do: wire_varint() def wire_type(:bool), do: wire_varint() def wire_type({:enum, _}), do: wire_varint() def wire_type(:enum), do: wire_varint() def wire_type(:fixed64), do: wire_64bits() def wire_type(:sfixed64), do: wire_64bits() def wire_type(:double), do: wire_64bits() def wire_type(:string), do: wire_delimited() def wire_type(:bytes), do: wire_delimited() def wire_type(:fixed32), do: wire_32bits() def wire_type(:sfixed32), do: wire_32bits() def wire_type(:float), do: wire_32bits() def wire_type(mod) when is_atom(mod), do: wire_delimited() defp repeated_or_not(val, repeated, func) do if repeated do Enum.map(val, func) else func.(val) end end defp is_enum_default({_, type}, v) when is_atom(v), do: type.value(v) == 0 defp is_enum_default({_, _}, v) when is_integer(v), do: v == 0 defp is_enum_default({_, _}, _), do: false defp oneof_actual_vals( %{field_tags: field_tags, field_props: field_props, oneof: oneof}, struct ) do Enum.reduce(oneof, %{}, fn {field, index}, acc -> case Map.get(struct, field, nil) do {f, val} -> %{oneof: oneof} = field_props[field_tags[f]] if oneof != index do raise Protobuf.EncodeError, message: ":#{f} doesn't belongs to #{inspect(struct.__struct__)}##{field}" else Map.put(acc, f, val) end nil -> acc _ -> raise Protobuf.EncodeError, message: "#{inspect(struct.__struct__)}##{field} should be {key, val} or nil" end end) end end
lib/protobuf/encoder.ex
0.800419
0.434821
encoder.ex
starcoder
defmodule X509.SignatureAlgorithm do @moduledoc false import X509.ASN1 # Returns a signature algorithm record for the given public key type and hash # algorithm; this is essentially the reverse of # `:public_key.pkix_sign_types/1` def new(hash, signature, type \\ :SignatureAlgorithm) def new(hash, rsa_private_key(), type) do new(hash, :rsa, type) end def new(hash, ec_private_key(), type) do new(hash, :ecdsa, type) end def new(hash, signature, :SignatureAlgorithm) do {oid, parameters} = algorithm(hash, signature) signature_algorithm(algorithm: oid, parameters: parameters) end def new(hash, signature, :CertificationRequest_signatureAlgorithm) do {oid, parameters} = algorithm(hash, signature) certification_request_signature_algorithm(algorithm: oid, parameters: parameters) end def new(hash, signature, :AlgorithmIdentifier) do # The AlgorithmIdentifier encoder in OTP's :public_key expects the # parameters to be passed in as a raw binary DER, rather than an ASN.1 # OpenType record case algorithm(hash, signature) do {oid, {:asn1_OPENTYPE, parameters_der}} -> algorithm_identifier(algorithm: oid, parameters: parameters_der) {oid, :asn1_NOVALUE} -> algorithm_identifier(algorithm: oid) end end defp algorithm(:md5, :rsa), do: {oid(:md5WithRSAEncryption), null()} defp algorithm(:sha, :rsa), do: {oid(:sha1WithRSAEncryption), null()} defp algorithm(:sha, :ecdsa), do: {oid(:"ecdsa-with-SHA1"), :asn1_NOVALUE} defp algorithm(:sha224, :rsa), do: {oid(:sha224WithRSAEncryption), null()} defp algorithm(:sha224, :ecdsa), do: {oid(:"ecdsa-with-SHA224"), :asn1_NOVALUE} defp algorithm(:sha256, :rsa), do: {oid(:sha256WithRSAEncryption), null()} defp algorithm(:sha256, :ecdsa), do: {oid(:"ecdsa-with-SHA256"), :asn1_NOVALUE} defp algorithm(:sha384, :rsa), do: {oid(:sha384WithRSAEncryption), null()} defp algorithm(:sha384, :ecdsa), do: {oid(:"ecdsa-with-SHA384"), :asn1_NOVALUE} defp algorithm(:sha512, :rsa), do: {oid(:sha512WithRSAEncryption), null()} defp algorithm(:sha512, :ecdsa), do: {oid(:"ecdsa-with-SHA512"), :asn1_NOVALUE} defp algorithm(hash, :rsa) do raise ArgumentError, "Unsupported hashing algorithm for RSA signing: #{inspect(hash)}" end defp algorithm(hash, :ecdsa) do raise ArgumentError, "Unsupported hashing algorithm for ECDSA signing: #{inspect(hash)}" end end
lib/x509/signature_algorithm.ex
0.838415
0.508422
signature_algorithm.ex
starcoder
defmodule JTIRegister.ETS do @default_cleanup_interval 15 @moduledoc """ Implementation of the `JTIRegister` behaviour relying on ETS Stores the JTIs in an ETS table. It is therefore **not** distributed and not suitable when having more than one node. Uses monotonic time, so that erroneous server time does not result in JTIs not being deleted. ## Options - `:cleanup_interval`: the interval between cleanups of the underlying ETS table in seconds. Defaults to #{@default_cleanup_interval} ## Starting the register In your `MyApp.Application` module, add: children = [ JTIRegister.ETS ] or children = [ {JTIRegister.ETS, cleanup_interval: 30} ] """ @behaviour JTIRegister use GenServer @impl JTIRegister def start_link(opts \\ []) do GenServer.start_link(__MODULE__, opts, name: __MODULE__) end @impl JTIRegister def register(jti, exp) do expires_in = exp - now() exp_monotonic = now_monotonic() + expires_in GenServer.cast(__MODULE__, {:add_jti, {jti, exp_monotonic}}) end @impl JTIRegister def registered?(jti) do now_monotonic = now_monotonic() case :ets.lookup(__MODULE__, jti) do [{_jti, exp_monotonic}] when exp_monotonic > now_monotonic -> true _ -> false end end @impl GenServer def init(opts) do schedule_cleanup(opts) :ets.new(__MODULE__, [:named_table, :set, :protected]) {:ok, opts} end @impl GenServer def handle_cast({:add_jti, {jti, exp_monotonic}}, state) do :ets.insert(__MODULE__, {jti, exp_monotonic}) {:noreply, state} end @impl GenServer def handle_info(:cleanup, state) do cleanup() schedule_cleanup(state) {:noreply, state} end defp cleanup() do match_spec = [ { {:_, :"$1"}, [{:<, :"$1", now_monotonic()}], [true] } ] :ets.select_delete(__MODULE__, match_spec) end defp schedule_cleanup(state) do interval = (state[:cleanup_interval] || @default_cleanup_interval) * 1000 Process.send_after(self(), :cleanup, interval) end defp now(), do: System.system_time(:second) defp now_monotonic(), do: System.monotonic_time(:second) end
lib/jti_register/ets.ex
0.785473
0.467696
ets.ex
starcoder
defmodule Mix.Tasks.Hex.Organization do use Mix.Task @shortdoc "Manages Hex.pm organizations" @moduledoc """ Manages the list of authorized Hex.pm organizations. Organizations is a feature of Hex.pm to host and manage private packages. See <https://hex.pm/docs/private> for more information. By default you will be authorized to all your applications when running `mix hex.user auth` and this is the recommended approach. This task is mainly provided for a CI and build systems where access to an organization is needed without authorizing a user. By authorizing a new organization a new key is created for fetching packages from the organizations repository and the repository key is stored on the local machine. To use a package from an organization add `organization: "my_organization"` to the dependency declaration in `mix.exs`: {:plug, "~> 1.0", organization: "my_organization"} ## Authorize an organization This command will generate an API key used to authenticate access to the organization. See the `hex.user` tasks to list and control all your active API keys. $ mix hex.organization auth ORGANIZATION [--key KEY] [--key-name KEY_NAME] ## Deauthorize and remove an organization $ mix hex.organization deauth NAME ## List all authorized organizations This command will only list organizations you have authorized with this task, it will not list organizations you have access to by having authorized with `mix hex.user auth`. $ mix hex.organization list ## Generate organization key This command is useful to pre-generate keys for use with `mix hex.organization auth ORGANIZATION --key KEY` on CI servers or similar systems. It returns the hash of the generated key that you can pass to `auth ORGANIZATION --key KEY`. Unlike the `hex.user key` commands, a key generated with this command is owned by the organization directly, and not the user that generated it. This makes it ideal for shared environments such as CI where you don't want to give access to user-specific resources and the user's organization membership status won't affect key. By default this command sets the `repository` permission which allows read-only access to the repository, it can be overridden with the `--permission` flag. $ mix hex.organization key ORGANIZATION generate [--key-name KEY_NAME] [--permission PERMISSION] ## Revoke key Removes given key from organization. The key can no longer be used to authenticate API requests. $ mix hex.organization key ORGANIZATION revoke KEY_NAME ## Revoke all keys Revoke all keys from the organization. $ mix hex.organization key ORGANIZATION revoke --all ## List keys Lists all keys associated with the organization. $ mix hex.organization key ORGANIZATION list ## Command line options * `--key KEY` - Hash of key used to authenticate HTTP requests to repository, if omitted will generate a new key with your account credentials. This flag is useful if you have a key pre-generated with `mix hex.organization key` and want to authenticate on a CI server or similar system * `--key-name KEY_NAME` - By default Hex will base the key name on your machine's hostname and the organization name, use this option to give your own name. * `--permission PERMISSION` - Sets the permissions on the key, this option can be given multiple times, possibly values are: * `api:read` - API read access. * `api:write` - API write access. * `repository` - Access to the organization's repository (this is the default permission). """ @behaviour Hex.Mix.TaskDescription @switches [ all: :boolean, key_name: :string, key: :string, permission: [:string, :keep] ] @impl true def run(args) do Hex.start() {opts, args} = Hex.OptionParser.parse!(args, switches: @switches) case args do ["auth", name] -> auth(name, opts) ["deauth", name] -> deauth(name) ["key", name, "generate"] -> key_generate(name, opts) ["key", name, "revoke", key_name] -> key_revoke(name, key_name) ["key", name, "revoke"] -> if opts[:all], do: key_revoke_all(name), else: invalid_args() ["key", name, "list"] -> key_list(name) ["list"] -> list() _ -> invalid_args() end end @impl true def tasks() do [ {"auth ORGANIZATION", "Authorize an organization"}, {"deauth ORGANIZATION", "Deauthorize and remove organization"}, {"list", "List all authorized organizations"}, {"key ORGANIZATION generate", "Generate organization key"}, {"key ORGANIZATION revoke KEY_NAME", "Revoke key"}, {"key ORGANIZATION revoke --all", "Revoke all keys"}, {"key ORGANIZATION list", "List keys"} ] end defp invalid_args() do Mix.raise(""" Invalid arguments, expected one of: mix hex.organization auth ORGANIZATION mix hex.organization deauth ORGANIZATION mix hex.organization list mix hex.organization key ORGANIZATION generate mix hex.organization key ORGANIZATION revoke KEY_NAME mix hex.organization key ORGANIZATION revoke --all mix hex.organization key ORGANIZATION list """) end defp auth(organization, opts) do key = opts[:key] key = if key do test_key(key, organization) key else key_name = Mix.Tasks.Hex.repository_key_name(organization, opts[:key_name]) permissions = [%{"domain" => "repository", "resource" => organization}] auth = Mix.Tasks.Hex.auth_info(:write) case Mix.Tasks.Hex.generate_user_key(key_name, permissions, auth) do {:ok, key} -> key :error -> nil end end if key do Mix.Tasks.Hex.auth_organization("hexpm:#{organization}", key) end end defp deauth(name) do Hex.State.fetch!(:repos) |> Map.delete("hexpm:#{name}") |> Hex.Config.update_repos() end defp key_revoke_all(organization) do auth = Mix.Tasks.Hex.auth_info(:write) Hex.Shell.info("Revoking all keys...") case Hex.API.Key.Organization.delete_all(organization, auth) do {:ok, {code, _body, _headers}} when code in 200..299 -> :ok other -> Hex.Shell.error("Key revocation failed") Hex.Utils.print_error_result(other) end end defp key_revoke(organization, key) do auth = Mix.Tasks.Hex.auth_info(:write) Hex.Shell.info("Revoking key #{key}...") case Hex.API.Key.Organization.delete(organization, key, auth) do {:ok, {code, _body, _headers}} when code in 200..299 -> :ok other -> Hex.Shell.error("Key revocation failed") Hex.Utils.print_error_result(other) end end # TODO: print permissions defp key_list(organization) do auth = Mix.Tasks.Hex.auth_info(:read) case Hex.API.Key.Organization.get(organization, auth) do {:ok, {code, body, _headers}} when code in 200..299 -> values = Enum.map(body, fn %{"name" => name, "inserted_at" => time} -> [name, time] end) Mix.Tasks.Hex.print_table(["Name", "Created at"], values) other -> Hex.Shell.error("Key fetching failed") Hex.Utils.print_error_result(other) end end defp key_generate(organization, opts) do key_name = Mix.Tasks.Hex.general_key_name(opts[:key_name]) default_permission = [%{"domain" => "repository", "resource" => organization}] permissions = Keyword.get_values(opts, :permission) permissions = Mix.Tasks.Hex.convert_permissions(permissions) || default_permission result = Mix.Tasks.Hex.generate_organization_key( organization, key_name, permissions ) case result do {:ok, secret} -> Hex.Shell.info(secret) :error -> :ok end end defp list() do Enum.each(Hex.State.fetch!(:repos), fn {name, _repo} -> case String.split(name, ":", parts: 2) do ["hexpm", name] -> Hex.Shell.info(name) _ -> :ok end end) end defp test_key(key, name) do case Hex.API.Auth.get("repository", name, key: key) do {:ok, {code, _body, _}} when code in 200..299 -> :ok other -> Hex.Utils.print_error_result(other) Mix.raise("Failed to authenticate against organization repository with given key") end end end
lib/mix/tasks/hex.organization.ex
0.832339
0.431165
hex.organization.ex
starcoder
defmodule Andy.GM.CourseOfAction do @moduledoc "A course of action is a sequence of named Intentions meant to be realized as Intents in an attempt to validate some activation of a conjecture" require Logger alias Andy.GM.{ GenerativeModelDef, CourseOfAction, Conjecture, ConjectureActivation, Efficacy, Round, Belief, Intention, PubSub, State } alias Andy.Intent import Andy.GM.Utils, only: [info: 1] alias __MODULE__ @max_coa_index 4 defstruct conjecture_activation: nil, intention_names: [] def of_type?( %CourseOfAction{ conjecture_activation: %ConjectureActivation{ conjecture: %Conjecture{name: coa_conjecture_name} }, intention_names: coa_intention_names }, {conjecture_name, _}, intention_names ) do # ordering of intentions matters! coa_conjecture_name == conjecture_name and coa_intention_names == intention_names end def empty?(%CourseOfAction{ intention_names: coa_intention_names }) do Enum.count(coa_intention_names) == 0 end def execute_intentions(intentions, belief_values, [round | _previous_rounds] = rounds, state) do Logger.info( "#{info(state)}: Executing intentions #{inspect(intentions)} given belief values #{ inspect(belief_values) }" ) Enum.reduce( intentions, round, fn intention, %Round{intents: intents} = acc -> intent_valuation = intention.valuator.(belief_values) if intent_valuation == nil do # a nil-valued intent is a noop intent, Logger.info( "#{info(state)}: Noop intention #{inspect(intention)}. Null intent valuation." ) acc else # execute valued intent %{value: intent_value, duration: duration} = intent_valuation intent = Intent.new( about: intention.intent_name, value: intent_value, duration: duration ) if not (Intention.not_repeatable?(intention) and would_be_repeated?(intent, rounds)) do PubSub.notify_intended(intent) %Round{acc | intents: [intent | intents]} else acc end end end ) end # Would an intent be repeated (does the latest remembered intent about the same thing, executed in # this or prior rounds, have the same value)? defp would_be_repeated?(%Intent{about: about, value: value}, rounds) do Enum.reduce_while( rounds, false, fn %Round{intents: intents}, _ -> case Enum.find(intents, &(&1.about == about)) do nil -> {:cont, false} %Intent{value: intent_value} -> {:halt, intent_value == value} end end ) end # Select a course of action for a conjecture # Returns {selected_course_of_action, updated_coa_index, new_coa?} or nil if no CoA def possible_courses_of_actions(conjecture_activations, state) do Enum.reduce( conjecture_activations, [], fn conjecture_activation, acc -> if ConjectureActivation.intention_domain_empty?(conjecture_activation) do acc else if ConjectureActivation.goal?(conjecture_activation) do if ConjectureActivation.achieved_now?(conjecture_activation, state) do Logger.info( "#{info(state)}: Goal achieved for #{inspect(conjecture_activation)}. Nothing to do." ) acc else # keep trying to achieve the goal case select_course_of_action(conjecture_activation, state) do nil -> acc coa -> [coa | acc] end end # opinion else if ConjectureActivation.believed_now?(conjecture_activation, state) do # keep trying to confirm the opinion case select_course_of_action(conjecture_activation, state) do nil -> acc coa -> [coa | acc] end else acc end end end end ) end # Select a course of action for a conjecture # Returns {selected_course_of_action, updated_coa_index, new_coa?} or nil if no CoA defp select_course_of_action( %ConjectureActivation{} = conjecture_activation, %State{ efficacies: efficacies, courses_of_action_indices: courses_of_action_indices } = state ) do Logger.info( "#{info(state)}: Selecting a course of action for conjecture activation #{ inspect(conjecture_activation) }" ) conjecture_activation_subject = ConjectureActivation.subject(conjecture_activation) # Create an untried CoA (shortest possible), give it a hypothetical efficacy (= average efficacy) and add it to the candidates coa_index = Map.get(courses_of_action_indices, conjecture_activation_subject, 0) # Can be nil if the coa_index duplicates a COA at an earlier index because of non-repeatable intentions maybe_untried_coa = new_course_of_action( conjecture_activation, coa_index, state ) # Collect as candidates all tried CoAs for similar conjecture activations (same subject) # when satisfaction of the conjecture was the same as now (goal achieved/opinion believed vs not) # => [{CoA, degree_of_efficacy}, ...] satisfied? = ConjectureActivation.satisfied_now?(conjecture_activation, state) tried = Map.get(efficacies, conjecture_activation_subject, []) |> Enum.filter(fn %Efficacy{when_already_satisfied?: when_already_satisfied?} -> when_already_satisfied? == satisfied? end) |> Enum.map( &{%CourseOfAction{ conjecture_activation: conjecture_activation, intention_names: &1.intention_names }, &1.degree} ) average_efficacy = Efficacy.average_efficacy(tried) # Candidates CoA are the previously tried CoAs plus a new one given the average efficacy of the other candidates. candidates = if maybe_untried_coa == nil or CourseOfAction.empty?(maybe_untried_coa) or course_of_action_already_tried?(maybe_untried_coa, tried) do if tried == [], do: Logger.info("#{info(state)}: Empty tried CoAs and no new untried CoA!") tried else [{maybe_untried_coa, average_efficacy} | tried] end # Normalize efficacies (sum = 1.0) |> Efficacy.normalize_efficacies() # Pick a CoA randomly, favoring higher efficacy case pick_course_of_action(candidates, state) do nil -> Logger.info("#{info(state)}: No CoA was picked") nil course_of_action -> # Move the CoA index if we picked an untried CoA new_coa? = course_of_action == maybe_untried_coa # Are all intentions in the domain of the activated conjecture non-repeatable? all_non_repeatable? = all_non_repeatable_intentions?(conjecture_activation, state) updated_coa_index = if (maybe_untried_coa == nil and not all_non_repeatable?) or new_coa? do min(coa_index + 1, @max_coa_index) else coa_index end {course_of_action, updated_coa_index, new_coa?} end end defp course_of_action_already_tried?(maybe_untried_coa, tried) do tried_coas = Enum.map(tried, fn {coa, _efficacy} -> coa end) maybe_untried_coa in tried_coas end defp new_course_of_action( conjecture_activation, courses_of_action_index, state ) when courses_of_action_index >= @max_coa_index do Logger.info("#{info(state)}: Max COA index reached for #{inspect(conjecture_activation)}") nil end defp new_course_of_action( %ConjectureActivation{conjecture: %Conjecture{intention_domain: intention_domain}} = conjecture_activation, courses_of_action_index, %State{gm_def: gm_def} = state ) do Logger.info( "#{info(state)}: Creating a candidate new COA for #{inspect(conjecture_activation)}" ) # Convert the index into a list of indices e.g. 5 -> [1,1] , 5th CoA (0-based index) in an intention domain of 3 actions index_list = index_list(courses_of_action_index, intention_domain) Logger.info( "#{info(state)}: index_list = #{inspect(index_list)}, intention_domain = #{ inspect(intention_domain) }" ) intention_names = Enum.reduce( index_list, [], fn i, acc -> [Enum.at(intention_domain, i) | acc] end ) unduplicated_intention_names = GenerativeModelDef.unduplicate_intentions(gm_def, intention_names) # Note: intention_names are reversed, unduplicated_intention_names are un-reversed # Should never happen if Enum.count(unduplicated_intention_names) == 0, do: Logger.warn("#{info(state)}: Empty intention names for new CoA") index_of_coa = index_of_coa(unduplicated_intention_names, intention_domain) if(index_of_coa < courses_of_action_index) do Logger.info( "#{info(state)}: Already tried #{inspect(unduplicated_intention_names)} (#{index_of_coa} < #{ courses_of_action_index })" ) nil else if all_noops?(unduplicated_intention_names, conjecture_activation, state) do Logger.info("#{info(state)}: Noop #{inspect(unduplicated_intention_names)}. No new CoA.") nil else new_coa = %CourseOfAction{ conjecture_activation: conjecture_activation, intention_names: unduplicated_intention_names } Logger.info("#{info(state)}: Candidate new COA #{inspect(new_coa)}") new_coa end end end defp all_noops?(intention_names, conjecture_activation, state) when is_list(intention_names) do %Round{beliefs: beliefs} = Round.current_round(state) case Enum.find( beliefs, &(Belief.subject(&1) == ConjectureActivation.subject(conjecture_activation)) ) do nil -> Logger.warn("#{info(state)}: No belief found for #{inspect(conjecture_activation)}") true %Belief{} = belief -> Enum.all?(intention_names, &noop?(&1, belief, state)) end end defp noop?(intention_name, %Belief{values: belief_values}, %State{gm_def: gm_def}) do intentions = GenerativeModelDef.intentions(gm_def, intention_name) Enum.all?(intentions, &(&1.valuator.(belief_values) == nil)) end defp index_list(courses_of_action_index, [_intention_name]) do for _n <- 0..courses_of_action_index, do: 0 end defp index_list(courses_of_action_index, intention_domain) do Integer.to_string(courses_of_action_index, Enum.count(intention_domain)) |> String.to_charlist() |> Enum.map(&List.to_string([&1])) |> Enum.map(&String.to_integer(&1)) end defp index_of_coa(names, [_name]) do Enum.count(names) - 1 end defp index_of_coa(names, domain) do {index, ""} = Enum.map(names, &Enum.find_index(domain, fn x -> x == &1 end)) |> Enum.map(&"#{&1}") |> Enum.join("") |> Integer.parse(Enum.count(domain)) index end # Randomly pick a course of action with a probability proportional to its degree of efficacy defp pick_course_of_action([], _state) do nil end defp pick_course_of_action([{coa, _degree}], _state) do coa end defp pick_course_of_action(candidate_courses_of_action, state) do Logger.info("#{info(state)}: Picking a COA among #{inspect(candidate_courses_of_action)}") {ranges_reversed, _} = Enum.reduce( candidate_courses_of_action, {[], 0}, fn {_coa, degree}, {ranges_acc, top_acc} -> {[top_acc + degree | ranges_acc], top_acc + degree} end ) ranges = Enum.reverse(ranges_reversed) Logger.info( "Ranges = #{inspect(ranges)} for courses of action #{inspect(candidate_courses_of_action)}" ) random = Enum.random(0..999) / 1000 index = Enum.find(0..(Enum.count(ranges) - 1), &(random < Enum.at(ranges, &1))) {coa, _efficacy} = Enum.at(candidate_courses_of_action, index) Logger.info("#{info(state)}: Picked COA #{inspect(coa)}") coa end defp all_non_repeatable_intentions?(conjecture_activation, %State{gm_def: gm_def}) do intention_names = ConjectureActivation.intention_domain(conjecture_activation) Enum.all?(intention_names, &GenerativeModelDef.non_repeatable_intentions?(gm_def, &1)) end end defimpl Inspect, for: Andy.GM.CourseOfAction do def inspect(coa, _opts) do "#{inspect(coa.intention_names)} for #{inspect(coa.conjecture_activation)}" end end
lib/andy/gm/course_of_action.ex
0.672654
0.575886
course_of_action.ex
starcoder
defmodule Farmbot.Serial.Gcode.Parser do @moduledoc """ Parses farmbot_arduino_firmware G-Codes. """ @spec parse_code(binary) :: {binary, tuple} # / ??? def parse_code("R00 Q" <> tag), do: {tag, :idle} def parse_code("R01 Q" <> tag), do: {tag, :received} def parse_code("R02 Q" <> tag), do: {tag, :done} def parse_code("R03 Q" <> tag), do: {tag, :error} def parse_code("R04 Q" <> tag), do: {tag, :busy} # TODO(Connor) Fix these def parse_code("R05" <> _r), do: {nil, :dont_handle_me} # Dont care about this. def parse_code("R06 " <> r), do: parse_report_calibration(r) def parse_code("R21 " <> params), do: parse_pvq(params, :report_parameter_value) def parse_code("R31 " <> params), do: parse_pvq(params, :report_status_value) def parse_code("R41 " <> params), do: parse_pvq(params, :report_pin_value) def parse_code("R81 " <> params), do: parse_end_stops(params) def parse_code("R82 " <> params), do: parse_report_current_position(params) def parse_code("R83 " <> v), do: parse_version(v) def parse_code("R99 " <> message) do {nil, {:debug_message, message}} end def parse_code("Command" <> _), do: {nil, :dont_handle_me} # I think this is a bug def parse_code(code) do {:unhandled_gcode, code} end @spec parse_report_calibration(binary) :: {binary, {:report_calibration, binary, binary}} defp parse_report_calibration(r) do [axis_and_status | [q]] = String.split(r, " Q") <<a :: size(8), b :: size(8)>> = axis_and_status case b do 48 -> {q, {:report_calibration, <<a>>, :idle}} 49 -> {q, {:report_calibration, <<a>>, :home}} 50 -> {q, {:report_calibration, <<a>>, :end}} end end @spec parse_version(binary) :: {binary, {:report_software_version, binary}} defp parse_version(version) do [derp | [code]] = String.split(version, " Q") {code, {:report_software_version, derp}} end @doc ~S""" Parses R82 codes Example: iex> Gcode.parse_report_current_position("X34 Y756 Z23") {:report_current_position, 34, 756, 23, "0"} """ @lint false @spec parse_report_current_position(binary) :: {binary, {:report_current_position, binary, binary, binary}} def parse_report_current_position(position) when is_bitstring(position), do: position |> String.split(" ") |> do_parse_pos defp do_parse_pos(["X" <> x, "Y" <> y, "Z" <> z, "Q" <> tag]) do {tag, {:report_current_position, String.to_integer(x), String.to_integer(y), String.to_integer(z)}} end @doc ~S""" Parses End Stops. I don't think we actually use these yet. Example: iex> Gcode.parse_end_stops("XA1 XB1 YA0 YB1 ZA0 ZB1 Q123") {:reporting_end_stops, "1", "1", "0", "1", "0", "1", "123"} """ @spec parse_end_stops(binary) :: {:reporting_end_stops, binary, binary, binary, binary, binary, binary, binary} def parse_end_stops( << "XA", xa :: size(8), 32, "XB", xb :: size(8), 32, "YA", ya :: size(8), 32, "YB", yb :: size(8), 32, "ZA", za :: size(8), 32, "ZB", zb :: size(8), 32, "Q", tag :: binary >>), do: {tag, {:reporting_end_stops, xa |> pes, xb |> pes, ya |> pes, yb |> pes, za |> pes, zb |> pes}} @spec pes(48 | 49) :: 0 | 1 # lol defp pes(48), do: 0 defp pes(49), do: 1 @doc ~S""" common function for report_(something)_value from gcode. Example: iex> Gcode.parse_pvq("P20 V100", :report_parameter_value) {:report_parameter_value, "20" ,"100", "0"} Example: iex> Gcode.parse_pvq("P20 V100 Q12", :report_parameter_value) {:report_parameter_value, "20" ,"100", "12"} """ @lint false @spec parse_pvq(binary, :report_parameter_value) :: {:report_parameter_value, atom, integer, String.t} def parse_pvq(params, :report_parameter_value) when is_bitstring(params), do: params |> String.split(" ") |> do_parse_params @lint false def parse_pvq(params, human_readable_param_name) when is_bitstring(params) and is_atom(human_readable_param_name), do: params |> String.split(" ") |> do_parse_pvq(human_readable_param_name) defp do_parse_pvq([p, v, q], human_readable_param_name) do [_, rp] = String.split(p, "P") [_, rv] = String.split(v, "V") [_, rq] = String.split(q, "Q") {rq, {human_readable_param_name, String.to_integer(rp), String.to_integer(rv)}} end defp do_parse_params([p, v, q]) do [_, rp] = String.split(p, "P") [_, rv] = String.split(v, "V") [_, rq] = String.split(q, "Q") {rq, {:report_parameter_value, parse_param(rp), String.to_integer(rv)}} end @doc ~S""" Parses farmbot_arduino_firmware params. If we want the name of param "0"\n Example: iex> Gcode.parse_param("0") :param_version Example: iex> Gcode.parse_param(0) :param_version If we want the integer of param :param_version\n Example: iex> Gcode.parse_param(:param_version) 0 Example: iex> Gcode.parse_param("param_version") 0 """ @spec parse_param(binary | integer) :: atom | nil def parse_param("0"), do: :param_version def parse_param("11"), do: :movement_timeout_x def parse_param("12"), do: :movement_timeout_y def parse_param("13"), do: :movement_timeout_z def parse_param("21"), do: :movement_invert_endpoints_x def parse_param("22"), do: :movement_invert_endpoints_y def parse_param("23"), do: :movement_invert_endpoints_z def parse_param("25"), do: :movement_enable_endpoints_x def parse_param("26"), do: :movement_enable_endpoints_y def parse_param("27"), do: :movement_enable_endpoints_z def parse_param("31"), do: :movement_invert_motor_x def parse_param("32"), do: :movement_invert_motor_y def parse_param("33"), do: :movement_invert_motor_z def parse_param("36"), do: :moevment_secondary_motor_x def parse_param("37"), do: :movement_secondary_motor_invert_x def parse_param("41"), do: :movement_steps_acc_dec_x def parse_param("42"), do: :movement_steps_acc_dec_y def parse_param("43"), do: :movement_steps_acc_dec_z def parse_param("51"), do: :movement_home_up_x def parse_param("52"), do: :movement_home_up_y def parse_param("53"), do: :movement_home_up_z def parse_param("61"), do: :movement_min_spd_x def parse_param("62"), do: :movement_min_spd_y def parse_param("63"), do: :movement_min_spd_z def parse_param("71"), do: :movement_max_spd_x def parse_param("72"), do: :movement_max_spd_y def parse_param("73"), do: :movement_max_spd_z def parse_param("101"), do: :encoder_enabled_x def parse_param("102"), do: :encoder_enabled_y def parse_param("103"), do: :encoder_enabled_z def parse_param("105"), do: :encoder_type_x def parse_param("106"), do: :encoder_type_y def parse_param("107"), do: :encoder_type_z def parse_param("111"), do: :encoder_missed_steps_max_x def parse_param("112"), do: :encoder_missed_steps_max_y def parse_param("113"), do: :encoder_missed_steps_max_z def parse_param("115"), do: :encoder_scaling_x def parse_param("116"), do: :encoder_scaling_y def parse_param("117"), do: :encoder_scaling_z def parse_param("121"), do: :encoder_missed_steps_decay_x def parse_param("122"), do: :encoder_missed_steps_decay_y def parse_param("123"), do: :encoder_missed_steps_decay_z def parse_param("141"), do: :movement_axis_nr_steps_x def parse_param("142"), do: :movement_axis_nr_steps_y def parse_param("143"), do: :movement_axis_nr_steps_z def parse_param("201"), do: :pin_guard_1_pin_nr def parse_param("202"), do: :pin_guard_1_pin_time_out def parse_param("203"), do: :pin_guard_1_active_state def parse_param("205"), do: :pin_guard_2_pin_nr def parse_param("206"), do: :pin_guard_2_pin_time_out def parse_param("207"), do: :pin_guard_2_active_state def parse_param("211"), do: :pin_guard_3_pin_nr def parse_param("212"), do: :pin_guard_3_pin_time_out def parse_param("213"), do: :pin_guard_3_active_state def parse_param("215"), do: :pin_guard_4_pin_nr def parse_param("216"), do: :pin_guard_4_pin_time_out def parse_param("217"), do: :pin_guard_4_active_state def parse_param("221"), do: :pin_guard_5_pin_nr def parse_param("222"), do: :pin_guard_5_time_out def parse_param("223"), do: :pin_guard_5_active_state @lint false def parse_param(param) when is_integer(param), do: parse_param("#{param}") @spec parse_param(atom) :: integer | nil def parse_param(:param_version), do: 0 def parse_param(:movement_timeout_x), do: 11 def parse_param(:movement_timeout_y), do: 12 def parse_param(:movement_timeout_z), do: 13 def parse_param(:movement_invert_endpoints_x), do: 21 def parse_param(:movement_invert_endpoints_y), do: 22 def parse_param(:movement_invert_endpoints_z), do: 23 def parse_param(:movement_invert_motor_x), do: 31 def parse_param(:movement_invert_motor_y), do: 32 def parse_param(:movement_invert_motor_z), do: 33 def parse_param(:movement_enable_endpoints_x), do: 25 def parse_param(:movement_enable_endpoints_y), do: 26 def parse_param(:movement_enable_endpoints_z), do: 27 def parse_param(:moevment_secondary_motor_x), do: 36 def parse_param(:movement_secondary_motor_invert_x), do: 37 def parse_param(:movement_steps_acc_dec_x), do: 41 def parse_param(:movement_steps_acc_dec_y), do: 42 def parse_param(:movement_steps_acc_dec_z), do: 43 def parse_param(:movement_home_up_x), do: 51 def parse_param(:movement_home_up_y), do: 52 def parse_param(:movement_home_up_z), do: 53 def parse_param(:movement_min_spd_x), do: 61 def parse_param(:movement_min_spd_y), do: 62 def parse_param(:movement_min_spd_z), do: 63 def parse_param(:movement_max_spd_x), do: 71 def parse_param(:movement_max_spd_y), do: 72 def parse_param(:movement_max_spd_z), do: 73 def parse_param(:encoder_enabled_x), do: 101 def parse_param(:encoder_enabled_y), do: 102 def parse_param(:encoder_enabled_z), do: 103 def parse_param(:encoder_type_x), do: 105 def parse_param(:encoder_type_y), do: 106 def parse_param(:encoder_type_z), do: 107 def parse_param(:encoder_missed_steps_max_x), do: 111 def parse_param(:encoder_missed_steps_max_y), do: 112 def parse_param(:encoder_missed_steps_max_z), do: 113 def parse_param(:encoder_scaling_x), do: 115 def parse_param(:encoder_scaling_y), do: 116 def parse_param(:encoder_scaling_z), do: 117 def parse_param(:encoder_missed_steps_decay_x), do: 121 def parse_param(:encoder_missed_steps_decay_y), do: 122 def parse_param(:encoder_missed_steps_decay_z), do: 123 def parse_param(:movement_axis_nr_steps_x), do: 141 def parse_param(:movement_axis_nr_steps_y), do: 142 def parse_param(:movement_axis_nr_steps_z), do: 143 def parse_param(:pin_guard_1_pin_nr), do: 201 def parse_param(:pin_guard_1_pin_time_out), do: 202 def parse_param(:pin_guard_1_active_state), do: 203 def parse_param(:pin_guard_2_pin_nr), do: 205 def parse_param(:pin_guard_2_pin_time_out), do: 206 def parse_param(:pin_guard_2_active_state), do: 207 def parse_param(:pin_guard_3_pin_nr), do: 211 def parse_param(:pin_guard_3_pin_time_out), do: 212 def parse_param(:pin_guard_3_active_state), do: 213 def parse_param(:pin_guard_4_pin_nr), do: 215 def parse_param(:pin_guard_4_pin_time_out), do: 216 def parse_param(:pin_guard_4_active_state), do: 217 def parse_param(:pin_guard_5_pin_nr), do: 221 def parse_param(:pin_guard_5_time_out), do: 222 def parse_param(:pin_guard_5_active_state), do: 223 def parse_param(param_string) when is_bitstring(param_string), do: param_string |> String.to_atom |> parse_param def parse_param(uhh) do require Logger Logger.error("LOOK AT ME IM IMPORTANT: #{inspect uhh}") nil end end
lib/serial/gcode/parser.ex
0.508788
0.463869
parser.ex
starcoder
defmodule Nostrum.Struct.Emoji do @moduledoc ~S""" Struct representing a Discord emoji. ## Mentioning Emojis in Messages A `Nostrum.Struct.Emoji` can be mentioned in message content using the `String.Chars` protocol or `mention/1`. ```Elixir emoji = %Nostrum.Struct.Emoji{id: 437093487582642177, name: "foxbot"} Nostrum.Api.create_message!(184046599834435585, "#{emoji}") %Nostrum.Struct.Message{content: "<:foxbot:437093487582642177>"} emoji = %Nostrum.Struct.Emoji{id: 436885297037312001, name: "tealixir"} Nostrum.Api.create_message!(280085880452939778, "#{Nostrum.Struct.Emoji.mention(emoji)}") %Nostrum.Struct.Message{content: "<:tealixir:436885297037312001>"} ``` ## Using Emojis in the Api A `Nostrum.Struct.Emoji` can be used in `Nostrum.Api` by using its api name or the struct itself. ```Elixir emoji = %Nostrum.Struct.Emoji{id: 436885297037312001, name: "tealixir"} Nostrum.Api.create_reaction(381889573426429952, 436247584349356032, Nostrum.Struct.Emoji.api_name(emoji)) {:ok} emoji = %Nostrum.Struct.Emoji{id: 436189601820966923, name: "elixir"} Nostrum.Api.create_reaction(381889573426429952, 436247584349356032, emoji) {:ok} ``` See `t:Nostrum.Struct.Emoji.api_name/0` for more information. """ alias Nostrum.{Constants, Snowflake, Util} alias Nostrum.Struct.User defstruct [ :id, :name, :user, :require_colons, :managed, :animated, :roles ] defimpl String.Chars do def to_string(emoji), do: @for.mention(emoji) end @typedoc ~S""" Emoji string to be used with the Discord API. Some API endpoints take an `emoji`. If it is a custom emoji, it must be structured as `"id:name"`. If it is an unicode emoji, it can be structured as any of the following: * `"name"` * A base 16 unicode emoji string. `api_name/1` is a convenience function that returns a `Nostrum.Struct.Emoji`'s api name. ## Examples ```Elixir # Custom Emojis "nostrum:431890438091489" # Unicode Emojis "👍" "\xF0\x9F\x98\x81" "\u2b50" ``` """ @type api_name :: String.t() @typedoc "Id of the emoji" @type id :: Snowflake.t() | nil @typedoc "Name of the emoji" @type name :: String.t() @typedoc "Roles this emoji is whitelisted to" @type roles :: [Snowflake.t()] | nil @typedoc "User that created this emoji" @type user :: User.t() | nil @typedoc "Whether this emoji must be wrapped in colons" @type require_colons :: boolean | nil @typedoc "Whether this emoji is managed" @type managed :: boolean | nil @typedoc "Whether this emoji is animated" @type animated :: boolean | nil @type t :: %__MODULE__{ id: id, name: name, roles: roles, user: user, require_colons: require_colons, managed: managed, animated: animated } @doc ~S""" Formats an `Nostrum.Struct.Emoji` into a mention. ## Examples ```Elixir iex> emoji = %Nostrum.Struct.Emoji{name: "👍"} ...> Nostrum.Struct.Emoji.mention(emoji) "👍" iex> emoji = %Nostrum.Struct.Emoji{id: 436885297037312001, name: "tealixir"} ...> Nostrum.Struct.Emoji.mention(emoji) "<:tealixir:436885297037312001>" iex> emoji = %Nostrum.Struct.Emoji{id: 437016804309860372, name: "blobseizure", animated: true} ...> Nostrum.Struct.Emoji.mention(emoji) "<a:blobseizure:437016804309860372>" ``` """ @spec mention(t) :: String.t() def mention(emoji) def mention(%__MODULE__{id: nil, name: name}), do: name def mention(%__MODULE__{animated: true, id: id, name: name}), do: "<a:#{name}:#{id}>" def mention(%__MODULE__{id: id, name: name}), do: "<:#{name}:#{id}>" @doc ~S""" Formats an emoji struct into its `t:Nostrum.Struct.Emoji.api_name/0`. ## Examples ```Elixir iex> emoji = %Nostrum.Struct.Emoji{name: "⭐"} ...> Nostrum.Struct.Emoji.api_name(emoji) "⭐" iex> emoji = %Nostrum.Struct.Emoji{id: 437093487582642177, name: "foxbot"} ...> Nostrum.Struct.Emoji.api_name(emoji) "foxbot:437093487582642177" ``` """ @spec api_name(t) :: api_name def api_name(emoji) def api_name(%__MODULE__{id: nil, name: name}), do: name def api_name(%__MODULE__{id: id, name: name}), do: "#{name}:#{id}" @doc """ Returns the url of a custom emoji's image. If the emoji is not a custom one, returns `nil`. ## Examples ```Elixir iex> emoji = %Nostrum.Struct.Emoji{id: 450225070569291776} iex> Nostrum.Struct.Emoji.image_url(emoji) "https://cdn.discordapp.com/emojis/450225070569291776.png" iex> emoji = %Nostrum.Struct.Emoji{id: 406140226998894614, animated: true} iex> Nostrum.Struct.Emoji.image_url(emoji) "https://cdn.discordapp.com/emojis/406140226998894614.gif" iex> emoji = %Nostrum.Struct.Emoji{id: nil, name: "⭐"} iex> Nostrum.Struct.Emoji.image_url(emoji) nil ``` """ @spec image_url(t) :: String.t() | nil def image_url(emoji) def image_url(%__MODULE__{id: nil}), do: nil def image_url(%__MODULE__{animated: true, id: id}), do: URI.encode(Constants.cdn_url() <> Constants.cdn_emoji(id, "gif")) def image_url(%__MODULE__{id: id}), do: URI.encode(Constants.cdn_url() <> Constants.cdn_emoji(id, "png")) @doc false def p_encode do %__MODULE__{} end @doc false def to_struct(map) do new = map |> Map.new(fn {k, v} -> {Util.maybe_to_atom(k), v} end) |> Map.update(:id, nil, &Util.cast(&1, Snowflake)) |> Map.update(:roles, nil, &Util.cast(&1, {:list, Snowflake})) |> Map.update(:user, nil, &Util.cast(&1, {:struct, User})) struct(__MODULE__, new) end end
lib/nostrum/struct/emoji.ex
0.884564
0.571886
emoji.ex
starcoder
defmodule ExExport do @show_definitions Application.get_env(:ex_export, :show_definitions, false) @moduledoc """ This module inspects another module for public functions and generates the defdelegate needed to add them to the local modules name space """ @doc """ require in the module and them call export for each module you want to import. The function list automatically filters out functions that start with an underscore ## Examples defmodule Sample do require ExExport alias Sample.Actions.Greet ExExport.export(Greet) ExExport.export(Sample.Actions.Farewell) end ## Options * `:only` - (since v0.2.0) a list of [function: arity] only matching functions will be delegated * `:exclude` - (since v0.2.0) a list of [function: arity] matching functions will *NOT* be delegated * `:delegate` - (since v0.3.0) (default false) true/false default true - true means that it will use defdelegate - false it builds a local function and maps it manually. ## See the Output In the configuration file for the environment you wish to render the data attributes, you can set the `show_definitions` to true. This will output the code that is being injected in a readable form. This can be useful if you get warnings like (Cannot match because already defined) ```elixir config :ex_export, :show_definitions, true ``` """ defmacro export(module, opts \\ []) do # resolved_module = Macro.expand(module, __CALLER__) resolved_module = case module do {:__aliases__, _, parts} -> resolve_module_name(parts, __CALLER__.aliases) _ -> raise "Don't know how to handle #{inspect(module)}" end # IO.inspect(module,label: "Original Module") # IO.inspect(__CALLER__.aliases, label: "Caller") only = get_keyword(opts, :only) exclude = get_keyword(opts, :exclude) if exclude && only do raise ArgumentError, message: ":only and :exclude are mutually exclusive" end ExExport.output_definition("<<<<< Exporting To #{inspect(__CALLER__.context_modules)}>>>>") try do resolved_module.__info__(:functions) |> Enum.map( fn {func, arity} -> if not private_func(func) and included(func, arity, only) and not_excluded(func, arity, exclude) do use_delegate(func, build_args(arity), resolved_module) else ExExport.output_definition("Skipping #{func}/#{arity}") end end ) rescue e in UndefinedFunctionError -> IO.puts( "ExExport doesn't support aliasing - you must use the canonical name of the module. This prevents the need for a compile time dependency." ) raise e end end def show_definitions?, do: @show_definitions def output_definition(msg) do case show_definitions?() do true -> IO.puts(msg) _ -> nil end end defp resolve_module_name(parts, aliases) do # IO.inspect(parts, label: "Parts") # IO.inspect(aliases, label: "Aliases") cond do Enum.count(aliases) > 0 && Enum.count(parts) == 1 -> case find_alias(Enum.at(parts, 0), aliases) do nil -> Enum.at(parts, 0) result -> result end true -> ["Elixir" | parts] |> Enum.join(".") |> String.to_atom() end end defp find_alias(key, aliases) do case Enum.find( aliases, fn {alias_key, _module} -> # IO.puts("Comparing #{key} to #{alias_key}") "Elixir.#{key}" == "#{alias_key}" end ) do nil -> nil {_, module} -> module end end defp get_keyword(list, label, default \\ nil) do case Keyword.fetch(list, label) do :error -> default {:ok, val} -> val end end defp private_func(func) do String.at("#{func}", 0) == "_" end defp included(_func, _arity, nil), do: true defp included(func, arity, only) do found?(func, arity, only) end defp not_excluded(_func, _arity, nil), do: true defp not_excluded(func, arity, exclude) do if found?(func, arity, exclude), do: false, else: true end defp found?(func, arity, list) do result = list |> Enum.find_index( fn {f, a} -> f == func and a == arity end ) |> is_nil !result end defp build_args(0), do: [] defp build_args(arity) do Enum.to_list(1..arity) |> Enum.map(fn idx -> "arg#{idx}" end) end defp use_delegate(func, args, resolved_module) do str_args = Enum.join(args, ",") {:ok, func_args} = Code.string_to_quoted("#{func}(#{str_args})") output_definition("defdelegate #{func}(#{str_args}), to: #{resolved_module}") quote do defdelegate unquote(func_args), to: unquote(resolved_module) end end end
lib/ex_export.ex
0.691602
0.789761
ex_export.ex
starcoder
defmodule Alchemy.Permissions do @moduledoc """ This module contains useful functions for working for the permission bitsets discord provides. To combine the permissions of an overwrite with the permissions of a role, the bitwise `|||` can be used. ## Example Usage ```elixir Cogs.def perms(role_name) do {:ok, guild} = Cogs.guild() role = hd Enum.filter(guild.roles, & &1.name == role_name) Cogs.say(inspect Permissions.to_list(role.permission)) end ``` This simple command prints out the list of permissions a role has avaiable. ## Permission List - `:create_instant_invite` Allows the creation of instant invites. - `:kick_members` Allows the kicking of members. - `:ban_members` Allows the banning of members. - `:administrator` Allows all permissions, and bypasses channel overwrites. - `:manage_channels` Allows management and editing of channels. - `:manage_guild` Allows management and editing of the guild. - `:add_reactions` Allows adding reactions to message. - `:view_audit_log` Allows for viewing of audit logs. - `:read_messages` Allows reading messages in a channel. Without this, the user won't even see the channel. - `:send_messages` Allows sending messages in a channel. - `:send_tts_messages` Allows sending text to speech messages. - `:manage_messages` Allows for deletion of other user messages. - `:embed_links` Links sent with this permission will be embedded automatically - `:attach_files` Allows the user to send files, and images - `:read_message_history` Allows the user to read the message history of a channel - `:mention_everyone` Allows the user to mention the special `@everyone` and `@here` tags - `:use_external_emojis` Allows the user to use emojis from other servers. - `:connect` Allows the user to connect to a voice channel. - `:speak` Allows the user to speak in a voice channel. - `:mute_members` Allows the user to mute members in a voice channel. - `:deafen_members` Allows the user to deafen members in a voice channel. - `:move_members` Allows the user to move members between voice channels. - `:use_vad` Allows the user to use voice activity detection in a voice channel - `:change_nickname` Allows the user to change his own nickname. - `:manage_nicknames` Allows for modification of other user nicknames. - `:manage_roles` Allows for management and editing of roles. - `:manage_webhooks` Allows for management and editing of webhooks. - `:manage_emojis` Allows for management and editing of emojis. """ alias Alchemy.Guild use Bitwise @perms [ :create_instant_invite, :kick_members, :ban_members, :administrator, :manage_channels, :manage_guild, :add_reactions, :view_audit_log, :read_messages, :send_messages, :send_tts_messages, :manage_messages, :embed_links, :attach_files, :read_message_history, :mention_everyone, :use_external_emojis, :connect, :speak, :mute_members, :deafen_members, :move_members, :use_vad, :change_nickname, :manage_nicknames, :manage_roles, :manage_webhooks, :manage_emojis ] @perm_map Stream.zip(@perms, Enum.map(0..28, &(1 <<< &1))) |> Enum.into(%{}) @type permission :: atom @doc """ Converts a permission bitset into a legible list of atoms. For checking if a specific permission is in that list, use `contains?/2` instead. ## Examples ```elixir permissions = Permissions.to_list(role.permissions) ``` """ @spec to_list(Integer) :: [permission] def to_list(bitset) do bitset |> Integer.to_charlist(2) |> Enum.reverse |> Stream.zip(@perms) |> Enum.reduce([], fn # 49 represents 1, 48 represents 0. CharLists are weird... {49, perm}, acc -> [perm | acc] {48, _}, acc -> acc end) end @doc """ Checks for the presence of a permission in a permission bitset. This should be preferred over using `:perm in Permissions.to_list(x)` because this works directly using bitwise operations, and is much more efficient then going through the permissions. ## Examples ```elixir Permissions.contains?(role.permissions, :manage_roles) ``` """ @spec contains?(Integer, permission) :: Boolean def contains?(bitset, permission) when permission in @perms do (bitset &&& @perm_map[:administrator]) != 0 or (bitset &&& @perm_map[permission]) != 0 end def contains?(_, permission) do raise ArgumentError, message: "#{permission} is not a valid permisson." <> "See documentation for a list of permissions." end @doc """ Gets the actual permissions of a member in a guild channel. This will error if the channel_id passed isn't in the guild. This will mismatch if the wrong structs are passed, or if the guild doesn't have a channel field. """ def channel_permissions(%Guild.GuildMember{} = member, %Guild{channels: cs} = guild, channel_id) do highest_role = Guild.highest_role(guild, member) channel = Enum.find(cs, & &1.id == channel_id) case channel do nil -> {:error, "#{channel_id} is not a channel in this guild"} _ -> {:ok, (highest_role.permissions ||| channel.overwrite.allow) &&& (~~~(channel.overwrite.deny))} end end @doc """ Banged version of `channel_permissions/3` """ def channel_permissions!(%Guild.GuildMember{} = member, %Guild{} = guild, channel_id) do case channel_permissions(member, guild, channel_id) do {:error, s} -> raise ArgumentError, message: s {:ok, perms} -> perms end end end
lib/Structs/permissions.ex
0.888442
0.878419
permissions.ex
starcoder
defmodule FloUI.Scrollable.Drag do @moduledoc """ Module for handling the drag controllability for `Scenic.Scrollable` components. """ alias Scenic.Math.Vector2 alias Scenic.Math @typedoc """ Atom representing a mouse button. """ @type mouse_button :: 0 | 1 | 2 @typedoc """ Data structure with settings that dictate the behaviour of the drag controllability. It consists of a list with `t:Scenic.Scrollable.Drag.mouse_button/0`s which specify the buttons with which the user can drag the `Scenic.Scrollable` component. By default, drag functionality is disabled. """ @type settings :: %{ mouse_buttons: [mouse_button] } @typedoc """ Shorthand for `t:Scenic.Math.vector_2/0`. Consists of a tuple containing the x and y numeric values. """ @type v2 :: Math.vector_2() @typedoc """ Atom representing what state the drag functionality is currently in. The drag state can be 'idle' or 'dragging'. """ @type drag_state :: :idle | :dragging @typedoc """ The state containing the necessary information to enable the drag functionality. """ @type t :: %__MODULE__{ enabled_buttons: [mouse_button], drag_state: drag_state, drag_start_content_position: v2, drag_start: v2, current: v2 } defstruct enabled_buttons: [], drag_state: :idle, drag_start_content_position: {0, 0}, drag_start: {0, 0}, current: {0, 0} # This constant specifies the factor with which the speed based on the last drag distance is multiplied after the drag has ended. This is to make the drag scroll experience feel more smooth. @drag_stop_speed_amplifier 3 @doc """ Initialize the `t:Scenic.Scrollable.Drag.t/0` state by passing in the `t:Scenic.Scrollable.Drag.settings/0` settings object. When nil is passed, the default settings will be used. """ @spec init(nil | settings) :: t def init(nil) do %__MODULE__{} end def init(settings) do enabled_buttons = settings[:mouse_buttons] || [] %__MODULE__{ enabled_buttons: enabled_buttons } end @doc """ Find out if the user is currently dragging the `Scenic.Scrollable` component. """ @spec dragging?(t) :: boolean def dragging?(%{drag_state: :idle}), do: false def dragging?(%{drag_state: :dragging}), do: true @doc """ Calculate the new scroll position based on the current drag state. The result will be wrapped in an. """ @spec new_position(t) :: v2 def new_position(%{ drag_state: :dragging, drag_start_content_position: drag_start_content_position, drag_start: drag_start, current: current }) do current |> Vector2.sub(drag_start) |> Vector2.add(drag_start_content_position) end def new_position(%{current: current}), do: current @doc """ Get the position of the users cursor during the previous update. Returns an the coordinate. """ @spec last_position(t) :: v2 def last_position(%{current: current}), do: current @doc """ Update the `t:Scenic.Scrollable.Drag.t/0` based on the pressed mouse button, mouse position, and the position of the scrollable content. """ @spec handle_mouse_click(t, mouse_button, v2, v2) :: t def handle_mouse_click(state, button, point, content_position) do if Enum.member?(state.enabled_buttons, button), do: start_drag(state, point, content_position), else: state end @doc """ Update the `t:Scenic.Scrollable.Drag.t/0` based on the new cursor position the user has moved to. """ @spec handle_mouse_move(t, v2) :: t def handle_mouse_move(%{drag_state: :idle} = state, _), do: state def handle_mouse_move(state, point), do: drag(state, point) @doc """ Update the `t:Scenic.Scrollable.Drag.t/0` based on the released mouse button and mouse position. """ @spec handle_mouse_release(t, mouse_button, v2) :: t def handle_mouse_release(state, button, point) do if Enum.member?(state.enabled_buttons, button), do: stop_drag(state, point), else: state end @doc """ Increases the current scroll speed, intended to be called when the user stops dragging. The increase in speed is intended to make the drag experience more smooth. """ @spec amplify_speed(t, v2) :: v2 def amplify_speed(_, speed), do: Vector2.mul(speed, @drag_stop_speed_amplifier) # Update the `t:Scenic.Scrollable.Drag.t` state with the necessary positional and status defining values when the user starts dragging. @spec start_drag(t, v2, v2) :: t defp start_drag(state, point, content_position) do state |> Map.put(:drag_state, :dragging) |> Map.put(:drag_start_content_position, content_position) |> Map.put(:drag_start, point) |> Map.put(:current, point) end # Update the `t:Scenic.Scrollable.Drag.t` with the necessary positional values when the user procs a mouse move event while dragging. @spec drag(t, v2) :: t defp drag(state, point) do state |> Map.put(:current, point) end # Update the `t:Scenic.Scrollable.Drag.t` with the necessary state defining values when the user stops dragging. @spec stop_drag(t, v2) :: t defp stop_drag(state, _) do state |> Map.put(:drag_state, :idle) end end
lib/scrollable/utility/drag.ex
0.886629
0.713955
drag.ex
starcoder
defmodule Pummpcomm.Session.PumpFake do use GenServer @moduledoc """ Fakes `Pummpcomm.Session` """ def start_link(_pump_serial, local_timezone) do GenServer.start_link(__MODULE__, local_timezone, name: __MODULE__) end def init(local_timezone) do {:ok, local_timezone} end def get_current_cgm_page do {:ok, %{glucose: 32, isig: 32, page_number: 10}} end def get_model_number, do: {:ok, 722} def read_bg_targets, do: {:ok, %{units: "mg/dL", targets: [%{bg_high: 120, bg_low: 80, start: ~T[00:00:00]}]}} def read_carb_ratios, do: {:ok, %{units: :grams, schedule: [%{ratio: 15.0, start: ~T[00:00:00]}]}} def read_cgm_page(page), do: GenServer.call(__MODULE__, {:read_cgm_page, page}) def read_history_page(page), do: GenServer.call(__MODULE__, {:read_history_page, page}) def read_insulin_sensitivities, do: {:ok, units: "mg/dL", sensitivities: [%{sensitivity: 40, start: ~T[00:00:00]}]} def read_settings, do: {:ok, insulin_action_curve_hours: 3, max_basal: 3.0, max_bolus: 15.0, selected_basal_profile: :standard} def read_std_basal_profile, do: {:ok, %{schedule: [%{rate: 1.4, start: ~T[00:00:00]}]}} def read_temp_basal, do: {:ok, %{type: :absolute, units_per_hour: 3.0, duration: 30}} def read_time, do: {:ok, Timex.now()} def set_temp_basal(units_per_hour: units_per_hour, duration_minutes: duration, type: type) do {:ok, %{type: type, units_per_hour: units_per_hour, duration: duration}} end def write_cgm_timestamp, do: :ok def handle_call({:read_cgm_page, 10}, _from, local_timezone) do {:reply, fake_rolling_cgm(local_timezone), local_timezone} end def handle_call({:read_history_page, 0}, _from, local_timezone) do {:reply, fake_rolling_history(local_timezone), local_timezone} end def fake_rolling_history(local_timezone) do today_midnight = local_timezone |> Timex.now() |> Timex.to_date() |> Timex.to_naive_datetime() yesterday_midnight = today_midnight |> Timex.shift(days: -1) yesterday = history_entries() |> Enum.reverse() |> offset_and_trim_history(yesterday_midnight, local_timezone) today = history_entries() |> Enum.reverse() |> offset_and_trim_history(today_midnight, local_timezone) {:ok, yesterday ++ today} end defp offset_and_trim_history(entries, date_offset, local_timezone) do now = local_timezone |> Timex.now() |> DateTime.to_naive() entries |> Enum.map(fn entry = {entry_type, entry_data} -> case Map.get(entry_data, :timestamp) do nil -> entry timestamp -> day_offset = Timex.diff(date_offset, timestamp |> Timex.to_date(), :days) {entry_type, %{entry_data | timestamp: Timex.shift(timestamp, days: day_offset)}} end end) |> Enum.filter(fn {entry_type, entry_data} -> case Map.get(entry_data, :timestamp) do nil -> entry_type != :null_byte timestamp -> Timex.before?(timestamp, now) end end) end # returns between 1-2 days of actual cgm data time shifted so that it's realistic def fake_rolling_cgm(local_timezone) do today_midnight = local_timezone |> Timex.now() |> Timex.to_date() |> Timex.to_naive_datetime() yesterday_midnight = today_midnight |> Timex.shift(days: -1) yesterday = sgv_entries() |> Enum.reverse() |> offset_and_trim_cgm(yesterday_midnight, local_timezone) today = sgv_entries() |> Enum.reverse() |> offset_and_trim_cgm(today_midnight, local_timezone) {:ok, yesterday ++ today} end defp offset_and_trim_cgm(entries, date_offset, local_timezone) do now = local_timezone |> Timex.now() |> DateTime.to_naive() entries |> Enum.map(fn entry = {entry_type, entry_data} -> case Map.get(entry_data, :timestamp) do nil -> entry timestamp -> day_offset = Timex.diff(date_offset, timestamp |> Timex.to_date(), :days) {entry_type, %{entry_data | timestamp: Timex.shift(timestamp, days: day_offset)}} end end) |> Enum.filter(fn {entry_type, entry_data} -> case Map.get(entry_data, :timestamp) do nil -> entry_type != :null_byte timestamp -> Timex.before?(timestamp, now) end end) end defp history_entries do [ {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 45, 185, 23, 83, 18>>, timestamp: ~N[2018-02-19 23:57:45]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 45, 185, 23, 83, 18, 0>>, timestamp: ~N[2018-02-19 23:57:45] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 44, 173, 23, 83, 18>>, timestamp: ~N[2018-02-19 23:45:44]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 44, 173, 23, 83, 18, 0>>, timestamp: ~N[2018-02-19 23:45:44] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 34, 162, 23, 83, 18>>, timestamp: ~N[2018-02-19 23:34:34]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 34, 162, 23, 83, 18, 0>>, timestamp: ~N[2018-02-19 23:34:34] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 46, 134, 23, 83, 18>>, timestamp: ~N[2018-02-19 23:06:46]}}, {:temp_basal, %{ rate: 1.1, rate_type: :absolute, raw: <<51, 44, 46, 134, 23, 83, 18, 0>>, timestamp: ~N[2018-02-19 23:06:46] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 35, 183, 22, 83, 18>>, timestamp: ~N[2018-02-19 22:55:35]}}, {:temp_basal, %{ rate: 1.05, rate_type: :absolute, raw: <<51, 42, 35, 183, 22, 83, 18, 0>>, timestamp: ~N[2018-02-19 22:55:35] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 59, 167, 22, 83, 18>>, timestamp: ~N[2018-02-19 22:39:59]}}, {:temp_basal, %{ rate: 1.05, rate_type: :absolute, raw: <<51, 42, 59, 167, 22, 83, 18, 0>>, timestamp: ~N[2018-02-19 22:39:59] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 59, 150, 22, 83, 18>>, timestamp: ~N[2018-02-19 22:22:59]}}, {:temp_basal, %{ rate: 1.05, rate_type: :absolute, raw: <<51, 42, 59, 150, 22, 83, 18, 0>>, timestamp: ~N[2018-02-19 22:22:59] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 54, 133, 22, 83, 18>>, timestamp: ~N[2018-02-19 22:05:54]}}, {:temp_basal, %{ rate: 1.05, rate_type: :absolute, raw: <<51, 42, 54, 133, 22, 83, 18, 0>>, timestamp: ~N[2018-02-19 22:05:54] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 46, 168, 21, 83, 18>>, timestamp: ~N[2018-02-19 21:40:46]}}, {:temp_basal, %{ rate: 3.5, rate_type: :absolute, raw: <<51, 140, 46, 168, 21, 83, 18, 0>>, timestamp: ~N[2018-02-19 21:40:46] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 31, 158, 21, 83, 18>>, timestamp: ~N[2018-02-19 21:30:31]}}, {:temp_basal, %{ rate: 1.05, rate_type: :absolute, raw: <<51, 42, 31, 158, 21, 83, 18, 0>>, timestamp: ~N[2018-02-19 21:30:31] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 52, 157, 21, 83, 18>>, timestamp: ~N[2018-02-19 21:29:52]}}, {:temp_basal, %{ rate: 3.5, rate_type: :absolute, raw: <<51, 140, 52, 157, 21, 83, 18, 0>>, timestamp: ~N[2018-02-19 21:29:52] }}, {:bolus_normal, %{ amount: 4.0, duration: 0, programmed: 4.0, raw: <<1, 40, 40, 0, 17, 151, 85, 19, 18>>, timestamp: ~N[2018-02-19 21:23:17], type: :normal }}, {:bolus_wizard_estimate, %{ bg: 280, bg_target_high: 110, bg_target_low: 90, bolus_estimate: 0.0, carb_ratio: 6, carbohydrates: 0, correction_estimate: 5.6, food_estimate: 0.0, insulin_sensitivity: 30, raw: <<91, 24, 17, 151, 21, 19, 18, 0, 81, 6, 30, 90, 56, 0, 0, 0, 81, 0, 0, 110>>, timestamp: ~N[2018-02-19 21:23:17], unabsorbed_insulin_total: 8.1 }}, {:bg_received, %{ amount: 280, meter_link_id: "C1774D", raw: <<63, 35, 46, 150, 21, 115, 18, 193, 119, 77>>, timestamp: ~N[2018-02-19 21:22:46] }}, {:cal_bg_for_ph, %{amount: 280, raw: <<10, 24, 46, 150, 53, 115, 146>>, timestamp: ~N[2018-02-19 21:22:46]}}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 9, 146, 21, 83, 18>>, timestamp: ~N[2018-02-19 21:18:09]}}, {:temp_basal, %{ rate: 1.05, rate_type: :absolute, raw: <<51, 42, 9, 146, 21, 83, 18, 0>>, timestamp: ~N[2018-02-19 21:18:09] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 29, 180, 20, 83, 18>>, timestamp: ~N[2018-02-19 20:52:29]}}, {:temp_basal, %{ rate: 1.1, rate_type: :absolute, raw: <<51, 44, 29, 180, 20, 83, 18, 0>>, timestamp: ~N[2018-02-19 20:52:29] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 49, 169, 20, 83, 18>>, timestamp: ~N[2018-02-19 20:41:49]}}, {:temp_basal, %{ rate: 1.05, rate_type: :absolute, raw: <<51, 42, 49, 169, 20, 83, 18, 0>>, timestamp: ~N[2018-02-19 20:41:49] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 54, 153, 20, 83, 18>>, timestamp: ~N[2018-02-19 20:25:54]}}, {:temp_basal, %{ rate: 1.05, rate_type: :absolute, raw: <<51, 42, 54, 153, 20, 83, 18, 0>>, timestamp: ~N[2018-02-19 20:25:54] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 45, 137, 20, 83, 18>>, timestamp: ~N[2018-02-19 20:09:45]}}, {:temp_basal, %{ rate: 1.05, rate_type: :absolute, raw: <<51, 42, 45, 137, 20, 83, 18, 0>>, timestamp: ~N[2018-02-19 20:09:45] }}, {:bolus_normal, %{ amount: 11.6, duration: 0, programmed: 11.6, raw: <<1, 116, 116, 0, 49, 129, 84, 19, 18>>, timestamp: ~N[2018-02-19 20:01:49], type: :normal }}, {:bolus_wizard_estimate, %{ bg: 0, bg_target_high: 110, bg_target_low: 90, bolus_estimate: 11.6, carb_ratio: 6, carbohydrates: 70, correction_estimate: 0.0, food_estimate: 11.6, insulin_sensitivity: 25, raw: <<91, 0, 49, 129, 20, 19, 18, 70, 80, 6, 25, 90, 0, 116, 0, 0, 0, 0, 116, 110>>, timestamp: ~N[2018-02-19 20:01:49], unabsorbed_insulin_total: 0.0 }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 37, 179, 19, 83, 18>>, timestamp: ~N[2018-02-19 19:51:37]}}, {:temp_basal, %{ rate: 2.25, rate_type: :absolute, raw: <<51, 90, 37, 179, 19, 83, 18, 0>>, timestamp: ~N[2018-02-19 19:51:37] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 42, 175, 19, 83, 18>>, timestamp: ~N[2018-02-19 19:47:42]}}, {:temp_basal, %{ rate: 1.05, rate_type: :absolute, raw: <<51, 42, 42, 175, 19, 83, 18, 0>>, timestamp: ~N[2018-02-19 19:47:42] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 8, 175, 19, 83, 18>>, timestamp: ~N[2018-02-19 19:47:08]}}, {:temp_basal, %{ rate: 1.7, rate_type: :absolute, raw: <<51, 68, 8, 175, 19, 83, 18, 0>>, timestamp: ~N[2018-02-19 19:47:08] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 23, 143, 19, 83, 18>>, timestamp: ~N[2018-02-19 19:15:23]}}, {:temp_basal, %{ rate: 3.3, rate_type: :absolute, raw: <<51, 132, 23, 143, 19, 83, 18, 0>>, timestamp: ~N[2018-02-19 19:15:23] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 1, 138, 19, 83, 18>>, timestamp: ~N[2018-02-19 19:10:01]}}, {:temp_basal, %{ rate: 2.55, rate_type: :absolute, raw: <<51, 102, 1, 138, 19, 83, 18, 0>>, timestamp: ~N[2018-02-19 19:10:01] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 0, 132, 19, 83, 18>>, timestamp: ~N[2018-02-19 19:04:00]}}, {:temp_basal, %{ rate: 1.05, rate_type: :absolute, raw: <<51, 42, 0, 132, 19, 83, 18, 0>>, timestamp: ~N[2018-02-19 19:04:00] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 18, 181, 18, 83, 18>>, timestamp: ~N[2018-02-19 18:53:18]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 18, 181, 18, 83, 18, 0>>, timestamp: ~N[2018-02-19 18:53:18] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 53, 167, 18, 83, 18>>, timestamp: ~N[2018-02-19 18:39:53]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 53, 167, 18, 83, 18, 0>>, timestamp: ~N[2018-02-19 18:39:53] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 21, 156, 18, 83, 18>>, timestamp: ~N[2018-02-19 18:28:21]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 21, 156, 18, 83, 18, 0>>, timestamp: ~N[2018-02-19 18:28:21] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 7, 147, 18, 83, 18>>, timestamp: ~N[2018-02-19 18:19:07]}}, {:temp_basal, %{ rate: 3.5, rate_type: :absolute, raw: <<51, 140, 7, 147, 18, 83, 18, 0>>, timestamp: ~N[2018-02-19 18:19:07] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 46, 141, 18, 83, 18>>, timestamp: ~N[2018-02-19 18:13:46]}}, {:temp_basal, %{ rate: 1.0, rate_type: :absolute, raw: <<51, 40, 46, 141, 18, 83, 18, 0>>, timestamp: ~N[2018-02-19 18:13:46] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 25, 136, 18, 83, 18>>, timestamp: ~N[2018-02-19 18:08:25]}}, {:temp_basal, %{ rate: 2.55, rate_type: :absolute, raw: <<51, 102, 25, 136, 18, 83, 18, 0>>, timestamp: ~N[2018-02-19 18:08:25] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 33, 130, 18, 83, 18>>, timestamp: ~N[2018-02-19 18:02:33]}}, {:temp_basal, %{ rate: 1.05, rate_type: :absolute, raw: <<51, 42, 33, 130, 18, 83, 18, 0>>, timestamp: ~N[2018-02-19 18:02:33] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 40, 185, 17, 83, 18>>, timestamp: ~N[2018-02-19 17:57:40]}}, {:temp_basal, %{ rate: 3.05, rate_type: :absolute, raw: <<51, 122, 40, 185, 17, 83, 18, 0>>, timestamp: ~N[2018-02-19 17:57:40] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 20, 159, 17, 83, 18>>, timestamp: ~N[2018-02-19 17:31:20]}}, {:temp_basal, %{ rate: 3.5, rate_type: :absolute, raw: <<51, 140, 20, 159, 17, 83, 18, 0>>, timestamp: ~N[2018-02-19 17:31:20] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 10, 147, 17, 83, 18>>, timestamp: ~N[2018-02-19 17:19:10]}}, {:temp_basal, %{ rate: 1.05, rate_type: :absolute, raw: <<51, 42, 10, 147, 17, 83, 18, 0>>, timestamp: ~N[2018-02-19 17:19:10] }}, {:prime, %{ amount: 0.5, prime_type: :fixed, programmed_amount: 0.5, raw: <<3, 0, 5, 0, 5, 5, 144, 17, 19, 18>>, timestamp: ~N[2018-02-19 17:16:05] }}, {:prime, %{ amount: 9.6, prime_type: :manual, programmed_amount: 0.0, raw: <<3, 0, 0, 0, 96, 16, 143, 49, 19, 18>>, timestamp: ~N[2018-02-19 17:15:16] }}, {:pump_rewind, %{raw: <<33, 0, 26, 139, 17, 19, 18>>, timestamp: ~N[2018-02-19 17:11:26]}}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 15, 136, 17, 83, 18>>, timestamp: ~N[2018-02-19 17:08:15]}}, {:temp_basal, %{ rate: 2.55, rate_type: :absolute, raw: <<51, 102, 15, 136, 17, 83, 18, 0>>, timestamp: ~N[2018-02-19 17:08:15] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 51, 131, 17, 83, 18>>, timestamp: ~N[2018-02-19 17:03:51]}}, {:temp_basal, %{ rate: 1.65, rate_type: :absolute, raw: <<51, 66, 51, 131, 17, 83, 18, 0>>, timestamp: ~N[2018-02-19 17:03:51] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 23, 179, 16, 83, 18>>, timestamp: ~N[2018-02-19 16:51:23]}}, {:temp_basal, %{ rate: 3.05, rate_type: :absolute, raw: <<51, 122, 23, 179, 16, 83, 18, 0>>, timestamp: ~N[2018-02-19 16:51:23] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 8, 169, 16, 83, 18>>, timestamp: ~N[2018-02-19 16:41:08]}}, {:temp_basal, %{ rate: 0.95, rate_type: :absolute, raw: <<51, 38, 8, 169, 16, 83, 18, 0>>, timestamp: ~N[2018-02-19 16:41:08] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 36, 162, 16, 83, 18>>, timestamp: ~N[2018-02-19 16:34:36]}}, {:temp_basal, %{ rate: 2.95, rate_type: :absolute, raw: <<51, 118, 36, 162, 16, 83, 18, 0>>, timestamp: ~N[2018-02-19 16:34:36] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 36, 147, 16, 83, 18>>, timestamp: ~N[2018-02-19 16:19:36]}}, {:temp_basal, %{ rate: 0.95, rate_type: :absolute, raw: <<51, 38, 36, 147, 16, 83, 18, 0>>, timestamp: ~N[2018-02-19 16:19:36] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 21, 144, 16, 83, 18>>, timestamp: ~N[2018-02-19 16:16:21]}}, {:temp_basal, %{ rate: 2.45, rate_type: :absolute, raw: <<51, 98, 21, 144, 16, 83, 18, 0>>, timestamp: ~N[2018-02-19 16:16:21] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 54, 137, 16, 83, 18>>, timestamp: ~N[2018-02-19 16:09:54]}}, {:temp_basal, %{ rate: 0.95, rate_type: :absolute, raw: <<51, 38, 54, 137, 16, 83, 18, 0>>, timestamp: ~N[2018-02-19 16:09:54] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 24, 131, 16, 83, 18>>, timestamp: ~N[2018-02-19 16:03:24]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 24, 131, 16, 83, 18, 0>>, timestamp: ~N[2018-02-19 16:03:24] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 21, 181, 15, 83, 18>>, timestamp: ~N[2018-02-19 15:53:21]}}, {:temp_basal, %{ rate: 0.95, rate_type: :absolute, raw: <<51, 38, 21, 181, 15, 83, 18, 0>>, timestamp: ~N[2018-02-19 15:53:21] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 53, 172, 15, 83, 18>>, timestamp: ~N[2018-02-19 15:44:53]}}, {:temp_basal, %{ rate: 3.5, rate_type: :absolute, raw: <<51, 140, 53, 172, 15, 83, 18, 0>>, timestamp: ~N[2018-02-19 15:44:53] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 46, 166, 15, 83, 18>>, timestamp: ~N[2018-02-19 15:38:46]}}, {:temp_basal, %{ rate: 0.95, rate_type: :absolute, raw: <<51, 38, 46, 166, 15, 83, 18, 0>>, timestamp: ~N[2018-02-19 15:38:46] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 17, 156, 15, 83, 18>>, timestamp: ~N[2018-02-19 15:28:17]}}, {:temp_basal, %{ rate: 3.2, rate_type: :absolute, raw: <<51, 128, 17, 156, 15, 83, 18, 0>>, timestamp: ~N[2018-02-19 15:28:17] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 24, 155, 15, 83, 18>>, timestamp: ~N[2018-02-19 15:27:24]}}, {:temp_basal, %{ rate: 2.55, rate_type: :absolute, raw: <<51, 102, 24, 155, 15, 83, 18, 0>>, timestamp: ~N[2018-02-19 15:27:24] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 44, 148, 15, 83, 18>>, timestamp: ~N[2018-02-19 15:20:44]}}, {:temp_basal, %{ rate: 0.95, rate_type: :absolute, raw: <<51, 38, 44, 148, 15, 83, 18, 0>>, timestamp: ~N[2018-02-19 15:20:44] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 33, 132, 15, 83, 18>>, timestamp: ~N[2018-02-19 15:04:33]}}, {:temp_basal, %{ rate: 0.95, rate_type: :absolute, raw: <<51, 38, 33, 132, 15, 83, 18, 0>>, timestamp: ~N[2018-02-19 15:04:33] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 11, 181, 14, 83, 18>>, timestamp: ~N[2018-02-19 14:53:11]}}, {:temp_basal, %{ rate: 0.85, rate_type: :absolute, raw: <<51, 34, 11, 181, 14, 83, 18, 0>>, timestamp: ~N[2018-02-19 14:53:11] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 16, 172, 14, 83, 18>>, timestamp: ~N[2018-02-19 14:44:16]}}, {:temp_basal, %{ rate: 2.2, rate_type: :absolute, raw: <<51, 88, 16, 172, 14, 83, 18, 0>>, timestamp: ~N[2018-02-19 14:44:16] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 34, 170, 14, 83, 18>>, timestamp: ~N[2018-02-19 14:42:34]}}, {:temp_basal, %{ rate: 0.85, rate_type: :absolute, raw: <<51, 34, 34, 170, 14, 83, 18, 0>>, timestamp: ~N[2018-02-19 14:42:34] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 31, 154, 14, 83, 18>>, timestamp: ~N[2018-02-19 14:26:31]}}, {:temp_basal, %{ rate: 0.85, rate_type: :absolute, raw: <<51, 34, 31, 154, 14, 83, 18, 0>>, timestamp: ~N[2018-02-19 14:26:31] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 19, 145, 14, 83, 18>>, timestamp: ~N[2018-02-19 14:17:19]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 19, 145, 14, 83, 18, 0>>, timestamp: ~N[2018-02-19 14:17:19] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 22, 133, 14, 83, 18>>, timestamp: ~N[2018-02-19 14:05:22]}}, {:temp_basal, %{ rate: 0.85, rate_type: :absolute, raw: <<51, 34, 22, 133, 14, 83, 18, 0>>, timestamp: ~N[2018-02-19 14:05:22] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 33, 176, 13, 83, 18>>, timestamp: ~N[2018-02-19 13:48:33]}}, {:temp_basal, %{ rate: 0.85, rate_type: :absolute, raw: <<51, 34, 33, 176, 13, 83, 18, 0>>, timestamp: ~N[2018-02-19 13:48:33] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 42, 172, 13, 83, 18>>, timestamp: ~N[2018-02-19 13:44:42]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 42, 172, 13, 83, 18, 0>>, timestamp: ~N[2018-02-19 13:44:42] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 2, 158, 13, 83, 18>>, timestamp: ~N[2018-02-19 13:30:02]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 2, 158, 13, 83, 18, 0>>, timestamp: ~N[2018-02-19 13:30:02] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 4, 145, 13, 83, 18>>, timestamp: ~N[2018-02-19 13:17:04]}}, {:temp_basal, %{ rate: 0.85, rate_type: :absolute, raw: <<51, 34, 4, 145, 13, 83, 18, 0>>, timestamp: ~N[2018-02-19 13:17:04] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 12, 187, 12, 83, 18>>, timestamp: ~N[2018-02-19 12:59:12]}}, {:temp_basal, %{ rate: 0.85, rate_type: :absolute, raw: <<51, 34, 12, 187, 12, 83, 18, 0>>, timestamp: ~N[2018-02-19 12:59:12] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 41, 170, 12, 83, 18>>, timestamp: ~N[2018-02-19 12:42:41]}}, {:temp_basal, %{ rate: 0.85, rate_type: :absolute, raw: <<51, 34, 41, 170, 12, 83, 18, 0>>, timestamp: ~N[2018-02-19 12:42:41] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 34, 168, 12, 83, 18>>, timestamp: ~N[2018-02-19 12:40:34]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 34, 168, 12, 83, 18, 0>>, timestamp: ~N[2018-02-19 12:40:34] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 56, 165, 12, 83, 18>>, timestamp: ~N[2018-02-19 12:37:56]}}, {:temp_basal, %{ rate: 1.65, rate_type: :absolute, raw: <<51, 66, 56, 165, 12, 83, 18, 0>>, timestamp: ~N[2018-02-19 12:37:56] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 18, 161, 12, 83, 18>>, timestamp: ~N[2018-02-19 12:33:18]}}, {:temp_basal, %{ rate: 0.85, rate_type: :absolute, raw: <<51, 34, 18, 161, 12, 83, 18, 0>>, timestamp: ~N[2018-02-19 12:33:18] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 7, 142, 12, 83, 18>>, timestamp: ~N[2018-02-19 12:14:07]}}, {:temp_basal, %{ rate: 0.85, rate_type: :absolute, raw: <<51, 34, 7, 142, 12, 83, 18, 0>>, timestamp: ~N[2018-02-19 12:14:07] }}, {:bolus_normal, %{ amount: 10.0, duration: 0, programmed: 10.0, raw: <<1, 100, 100, 0, 28, 134, 76, 19, 18>>, timestamp: ~N[2018-02-19 12:06:28], type: :normal }}, {:bolus_wizard_estimate, %{ bg: 0, bg_target_high: 110, bg_target_low: 90, bolus_estimate: 10.0, carb_ratio: 5, carbohydrates: 50, correction_estimate: 0.0, food_estimate: 10.0, insulin_sensitivity: 25, raw: <<91, 0, 28, 134, 12, 19, 18, 50, 80, 5, 25, 90, 0, 100, 0, 0, 0, 0, 100, 110>>, timestamp: ~N[2018-02-19 12:06:28], unabsorbed_insulin_total: 0.0 }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 19, 128, 12, 83, 18>>, timestamp: ~N[2018-02-19 12:00:19]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 19, 128, 12, 83, 18, 0>>, timestamp: ~N[2018-02-19 12:00:19] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 48, 174, 11, 83, 18>>, timestamp: ~N[2018-02-19 11:46:48]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 48, 174, 11, 83, 18, 0>>, timestamp: ~N[2018-02-19 11:46:48] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 36, 169, 11, 83, 18>>, timestamp: ~N[2018-02-19 11:41:36]}}, {:temp_basal, %{ rate: 0.85, rate_type: :absolute, raw: <<51, 34, 36, 169, 11, 83, 18, 0>>, timestamp: ~N[2018-02-19 11:41:36] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 40, 152, 11, 83, 18>>, timestamp: ~N[2018-02-19 11:24:40]}}, {:temp_basal, %{ rate: 0.85, rate_type: :absolute, raw: <<51, 34, 40, 152, 11, 83, 18, 0>>, timestamp: ~N[2018-02-19 11:24:40] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 39, 136, 11, 83, 18>>, timestamp: ~N[2018-02-19 11:08:39]}}, {:temp_basal, %{ rate: 0.85, rate_type: :absolute, raw: <<51, 34, 39, 136, 11, 83, 18, 0>>, timestamp: ~N[2018-02-19 11:08:39] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 57, 185, 10, 83, 18>>, timestamp: ~N[2018-02-19 10:57:57]}}, {:temp_basal, %{ rate: 0.9, rate_type: :absolute, raw: <<51, 36, 57, 185, 10, 83, 18, 0>>, timestamp: ~N[2018-02-19 10:57:57] }}, {:bolus_normal, %{ amount: 16.0, duration: 0, programmed: 16.0, raw: <<1, 160, 160, 0, 45, 173, 74, 19, 18>>, timestamp: ~N[2018-02-19 10:45:45], type: :normal }}, {:bolus_wizard_estimate, %{ bg: 0, bg_target_high: 110, bg_target_low: 90, bolus_estimate: 16.0, carb_ratio: 5, carbohydrates: 80, correction_estimate: 0.0, food_estimate: 16.0, insulin_sensitivity: 25, raw: <<91, 0, 45, 173, 10, 19, 18, 80, 80, 5, 25, 90, 0, 160, 0, 0, 0, 0, 160, 110>>, timestamp: ~N[2018-02-19 10:45:45], unabsorbed_insulin_total: 0.0 }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 44, 172, 10, 83, 18>>, timestamp: ~N[2018-02-19 10:44:44]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 44, 172, 10, 83, 18, 0>>, timestamp: ~N[2018-02-19 10:44:44] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 22, 161, 10, 83, 18>>, timestamp: ~N[2018-02-19 10:33:22]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 22, 161, 10, 83, 18, 0>>, timestamp: ~N[2018-02-19 10:33:22] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 23, 149, 10, 83, 18>>, timestamp: ~N[2018-02-19 10:21:23]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 23, 149, 10, 83, 18, 0>>, timestamp: ~N[2018-02-19 10:21:23] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 6, 130, 10, 83, 18>>, timestamp: ~N[2018-02-19 10:02:06]}}, {:temp_basal, %{ rate: 0.95, rate_type: :absolute, raw: <<51, 38, 6, 130, 10, 83, 18, 0>>, timestamp: ~N[2018-02-19 10:02:06] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 0, 176, 9, 83, 18>>, timestamp: ~N[2018-02-19 09:48:00]}}, {:temp_basal, %{ rate: 1.25, rate_type: :absolute, raw: <<51, 50, 0, 176, 9, 83, 18, 0>>, timestamp: ~N[2018-02-19 09:48:00] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 20, 174, 9, 83, 18>>, timestamp: ~N[2018-02-19 09:46:20]}}, {:temp_basal, %{ rate: 3.45, rate_type: :absolute, raw: <<51, 138, 20, 174, 9, 83, 18, 0>>, timestamp: ~N[2018-02-19 09:46:20] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 11, 162, 9, 83, 18>>, timestamp: ~N[2018-02-19 09:34:11]}}, {:temp_basal, %{ rate: 3.0, rate_type: :absolute, raw: <<51, 120, 11, 162, 9, 83, 18, 0>>, timestamp: ~N[2018-02-19 09:34:11] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 3, 145, 9, 83, 18>>, timestamp: ~N[2018-02-19 09:17:03]}}, {:temp_basal, %{ rate: 2.8, rate_type: :absolute, raw: <<51, 112, 3, 145, 9, 83, 18, 0>>, timestamp: ~N[2018-02-19 09:17:03] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 15, 132, 9, 83, 18>>, timestamp: ~N[2018-02-19 09:04:15]}}, {:temp_basal, %{ rate: 2.5, rate_type: :absolute, raw: <<51, 100, 15, 132, 9, 83, 18, 0>>, timestamp: ~N[2018-02-19 09:04:15] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 2, 183, 8, 83, 18>>, timestamp: ~N[2018-02-19 08:55:02]}}, {:temp_basal, %{ rate: 1.25, rate_type: :absolute, raw: <<51, 50, 2, 183, 8, 83, 18, 0>>, timestamp: ~N[2018-02-19 08:55:02] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 38, 161, 8, 83, 18>>, timestamp: ~N[2018-02-19 08:33:38]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 38, 161, 8, 83, 18, 0>>, timestamp: ~N[2018-02-19 08:33:38] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 44, 156, 8, 83, 18>>, timestamp: ~N[2018-02-19 08:28:44]}}, {:temp_basal, %{ rate: 1.25, rate_type: :absolute, raw: <<51, 50, 44, 156, 8, 83, 18, 0>>, timestamp: ~N[2018-02-19 08:28:44] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 28, 134, 8, 83, 18>>, timestamp: ~N[2018-02-19 08:06:28]}}, {:temp_basal, %{ rate: 1.25, rate_type: :absolute, raw: <<51, 50, 28, 134, 8, 83, 18, 0>>, timestamp: ~N[2018-02-19 08:06:28] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 31, 181, 7, 83, 18>>, timestamp: ~N[2018-02-19 07:53:31]}}, {:temp_basal, %{ rate: 2.1, rate_type: :absolute, raw: <<51, 84, 31, 181, 7, 83, 18, 0>>, timestamp: ~N[2018-02-19 07:53:31] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 31, 170, 7, 83, 18>>, timestamp: ~N[2018-02-19 07:42:31]}}, {:temp_basal, %{ rate: 1.95, rate_type: :absolute, raw: <<51, 78, 31, 170, 7, 83, 18, 0>>, timestamp: ~N[2018-02-19 07:42:31] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 20, 152, 7, 83, 18>>, timestamp: ~N[2018-02-19 07:24:20]}}, {:temp_basal, %{ rate: 1.05, rate_type: :absolute, raw: <<51, 42, 20, 152, 7, 83, 18, 0>>, timestamp: ~N[2018-02-19 07:24:20] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 26, 149, 7, 83, 18>>, timestamp: ~N[2018-02-19 07:21:26]}}, {:temp_basal, %{ rate: 1.8, rate_type: :absolute, raw: <<51, 72, 26, 149, 7, 83, 18, 0>>, timestamp: ~N[2018-02-19 07:21:26] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 28, 144, 7, 83, 18>>, timestamp: ~N[2018-02-19 07:16:28]}}, {:temp_basal, %{ rate: 1.05, rate_type: :absolute, raw: <<51, 42, 28, 144, 7, 83, 18, 0>>, timestamp: ~N[2018-02-19 07:16:28] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 35, 138, 7, 83, 18>>, timestamp: ~N[2018-02-19 07:10:35]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 35, 138, 7, 83, 18, 0>>, timestamp: ~N[2018-02-19 07:10:35] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 18, 176, 6, 83, 18>>, timestamp: ~N[2018-02-19 06:48:18]}}, {:temp_basal, %{ rate: 1.15, rate_type: :absolute, raw: <<51, 46, 18, 176, 6, 83, 18, 0>>, timestamp: ~N[2018-02-19 06:48:18] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 43, 160, 6, 83, 18>>, timestamp: ~N[2018-02-19 06:32:43]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 43, 160, 6, 83, 18, 0>>, timestamp: ~N[2018-02-19 06:32:43] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 24, 150, 6, 83, 18>>, timestamp: ~N[2018-02-19 06:22:24]}}, {:temp_basal, %{ rate: 1.15, rate_type: :absolute, raw: <<51, 46, 24, 150, 6, 83, 18, 0>>, timestamp: ~N[2018-02-19 06:22:24] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 29, 130, 6, 83, 18>>, timestamp: ~N[2018-02-19 06:02:29]}}, {:temp_basal, %{ rate: 1.15, rate_type: :absolute, raw: <<51, 46, 29, 130, 6, 83, 18, 0>>, timestamp: ~N[2018-02-19 06:02:29] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 23, 181, 5, 83, 18>>, timestamp: ~N[2018-02-19 05:53:23]}}, {:temp_basal, %{ rate: 2.35, rate_type: :absolute, raw: <<51, 94, 23, 181, 5, 83, 18, 0>>, timestamp: ~N[2018-02-19 05:53:23] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 27, 166, 5, 83, 18>>, timestamp: ~N[2018-02-19 05:38:27]}}, {:temp_basal, %{ rate: 1.45, rate_type: :absolute, raw: <<51, 58, 27, 166, 5, 83, 18, 0>>, timestamp: ~N[2018-02-19 05:38:27] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 28, 162, 5, 83, 18>>, timestamp: ~N[2018-02-19 05:34:28]}}, {:temp_basal, %{ rate: 2.25, rate_type: :absolute, raw: <<51, 90, 28, 162, 5, 83, 18, 0>>, timestamp: ~N[2018-02-19 05:34:28] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 21, 160, 5, 83, 18>>, timestamp: ~N[2018-02-19 05:32:21]}}, {:temp_basal, %{ rate: 1.45, rate_type: :absolute, raw: <<51, 58, 21, 160, 5, 83, 18, 0>>, timestamp: ~N[2018-02-19 05:32:21] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 48, 155, 5, 83, 18>>, timestamp: ~N[2018-02-19 05:27:48]}}, {:temp_basal, %{ rate: 2.15, rate_type: :absolute, raw: <<51, 86, 48, 155, 5, 83, 18, 0>>, timestamp: ~N[2018-02-19 05:27:48] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 47, 149, 5, 83, 18>>, timestamp: ~N[2018-02-19 05:21:47]}}, {:temp_basal, %{ rate: 1.4, rate_type: :absolute, raw: <<51, 56, 47, 149, 5, 83, 18, 0>>, timestamp: ~N[2018-02-19 05:21:47] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 15, 133, 5, 83, 18>>, timestamp: ~N[2018-02-19 05:05:15]}}, {:temp_basal, %{ rate: 1.4, rate_type: :absolute, raw: <<51, 56, 15, 133, 5, 83, 18, 0>>, timestamp: ~N[2018-02-19 05:05:15] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 5, 180, 4, 83, 18>>, timestamp: ~N[2018-02-19 04:52:05]}}, {:temp_basal, %{ rate: 1.45, rate_type: :absolute, raw: <<51, 58, 5, 180, 4, 83, 18, 0>>, timestamp: ~N[2018-02-19 04:52:05] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 56, 156, 4, 83, 18>>, timestamp: ~N[2018-02-19 04:28:56]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 56, 156, 4, 83, 18, 0>>, timestamp: ~N[2018-02-19 04:28:56] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 40, 148, 4, 83, 18>>, timestamp: ~N[2018-02-19 04:20:40]}}, {:temp_basal, %{ rate: 1.45, rate_type: :absolute, raw: <<51, 58, 40, 148, 4, 83, 18, 0>>, timestamp: ~N[2018-02-19 04:20:40] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 13, 128, 4, 83, 18>>, timestamp: ~N[2018-02-19 04:00:13]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 13, 128, 4, 83, 18, 0>>, timestamp: ~N[2018-02-19 04:00:13] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 49, 178, 3, 83, 18>>, timestamp: ~N[2018-02-19 03:50:49]}}, {:temp_basal, %{ rate: 1.45, rate_type: :absolute, raw: <<51, 58, 49, 178, 3, 83, 18, 0>>, timestamp: ~N[2018-02-19 03:50:49] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 9, 162, 3, 83, 18>>, timestamp: ~N[2018-02-19 03:34:09]}}, {:temp_basal, %{ rate: 1.45, rate_type: :absolute, raw: <<51, 58, 9, 162, 3, 83, 18, 0>>, timestamp: ~N[2018-02-19 03:34:09] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 14, 143, 3, 84, 18>>, timestamp: ~N[2018-02-19 03:15:14]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 14, 143, 3, 84, 18, 0>>, timestamp: ~N[2018-02-19 03:15:14] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 58, 138, 3, 84, 18>>, timestamp: ~N[2018-02-19 03:10:58]}}, {:temp_basal, %{ rate: 1.25, rate_type: :absolute, raw: <<51, 50, 58, 138, 3, 84, 18, 0>>, timestamp: ~N[2018-02-19 03:10:58] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 46, 132, 3, 84, 18>>, timestamp: ~N[2018-02-19 03:04:46]}}, {:temp_basal, %{ rate: 2.3, rate_type: :absolute, raw: <<51, 92, 46, 132, 3, 84, 18, 0>>, timestamp: ~N[2018-02-19 03:04:46] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 54, 185, 2, 84, 18>>, timestamp: ~N[2018-02-19 02:57:54]}}, {:temp_basal, %{ rate: 1.15, rate_type: :absolute, raw: <<51, 46, 54, 185, 2, 84, 18, 0>>, timestamp: ~N[2018-02-19 02:57:54] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 19, 168, 2, 84, 18>>, timestamp: ~N[2018-02-19 02:40:19]}}, {:temp_basal, %{ rate: 3.25, rate_type: :absolute, raw: <<51, 130, 19, 168, 2, 84, 18, 0>>, timestamp: ~N[2018-02-19 02:40:19] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 32, 166, 2, 84, 18>>, timestamp: ~N[2018-02-19 02:38:32]}}, {:temp_basal, %{ rate: 2.55, rate_type: :absolute, raw: <<51, 102, 32, 166, 2, 84, 18, 0>>, timestamp: ~N[2018-02-19 02:38:32] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 57, 161, 2, 84, 18>>, timestamp: ~N[2018-02-19 02:33:57]}}, {:temp_basal, %{ rate: 1.15, rate_type: :absolute, raw: <<51, 46, 57, 161, 2, 84, 18, 0>>, timestamp: ~N[2018-02-19 02:33:57] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 27, 150, 2, 84, 18>>, timestamp: ~N[2018-02-19 02:22:27]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 27, 150, 2, 84, 18, 0>>, timestamp: ~N[2018-02-19 02:22:27] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 36, 139, 2, 84, 18>>, timestamp: ~N[2018-02-19 02:11:36]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 36, 139, 2, 84, 18, 0>>, timestamp: ~N[2018-02-19 02:11:36] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 57, 128, 2, 84, 18>>, timestamp: ~N[2018-02-19 02:00:57]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 57, 128, 2, 84, 18, 0>>, timestamp: ~N[2018-02-19 02:00:57] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 4, 178, 1, 84, 18>>, timestamp: ~N[2018-02-19 01:50:04]}}, {:temp_basal, %{ rate: 1.1, rate_type: :absolute, raw: <<51, 44, 4, 178, 1, 84, 18, 0>>, timestamp: ~N[2018-02-19 01:50:04] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 7, 158, 1, 84, 18>>, timestamp: ~N[2018-02-19 01:30:07]}}, {:temp_basal, %{ rate: 3.5, rate_type: :absolute, raw: <<51, 140, 7, 158, 1, 84, 18, 0>>, timestamp: ~N[2018-02-19 01:30:07] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 14, 130, 1, 84, 18>>, timestamp: ~N[2018-02-19 01:02:14]}}, {:temp_basal, %{ rate: 3.5, rate_type: :absolute, raw: <<51, 140, 14, 130, 1, 84, 18, 0>>, timestamp: ~N[2018-02-19 01:02:14] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 28, 183, 0, 84, 18>>, timestamp: ~N[2018-02-19 00:55:28]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 28, 183, 0, 84, 18, 0>>, timestamp: ~N[2018-02-19 00:55:28] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 28, 172, 0, 84, 18>>, timestamp: ~N[2018-02-19 00:44:28]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 28, 172, 0, 84, 18, 0>>, timestamp: ~N[2018-02-19 00:44:28] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 55, 159, 0, 84, 18>>, timestamp: ~N[2018-02-19 00:31:55]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 55, 159, 0, 84, 18, 0>>, timestamp: ~N[2018-02-19 00:31:55] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 45, 147, 0, 84, 18>>, timestamp: ~N[2018-02-19 00:19:45]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 45, 147, 0, 84, 18, 0>>, timestamp: ~N[2018-02-19 00:19:45] }}, {:temp_basal_duration, %{duration: 30, raw: <<22, 1, 29, 136, 0, 84, 18>>, timestamp: ~N[2018-02-19 00:08:29]}}, {:temp_basal, %{ rate: 0.0, rate_type: :absolute, raw: <<51, 0, 29, 136, 0, 84, 18, 0>>, timestamp: ~N[2018-02-19 00:08:29] }}, {:daily_total_522, %{ raw: <<109, 51, 18, 5, 21, 24, 24, 24, 1, 0, 0, 11, 26, 4, 154, 41, 6, 128, 59, 0, 200, 6, 128, 59, 5, 224, 90, 0, 160, 10, 0, 0, 0, 4, 3, 1, 0, 0, 12, 0, 232, 0, 0, 0>>, timestamp: ~N[2018-02-19 00:00:00] }}, {:result_daily_total, %{ raw: <<7, 0, 0, 11, 26, 51, 18>>, strokes: 2842, timestamp: ~N[2018-02-19 00:00:00], units: 71.05 }} ] end defp sgv_entries do [ {:sensor_glucose_value, %{sgv: 87, timestamp: ~N[2018-02-19 23:55:39.000]}}, {:sensor_glucose_value, %{sgv: 97, timestamp: ~N[2018-02-19 23:50:39.000]}}, {:sensor_glucose_value, %{sgv: 104, timestamp: ~N[2018-02-19 23:45:39.000]}}, {:sensor_glucose_value, %{sgv: 118, timestamp: ~N[2018-02-19 23:40:39.000]}}, {:sensor_glucose_value, %{sgv: 127, timestamp: ~N[2018-02-19 23:35:39.000]}}, {:sensor_glucose_value, %{sgv: 137, timestamp: ~N[2018-02-19 23:30:39.000]}}, {:sensor_glucose_value, %{sgv: 145, timestamp: ~N[2018-02-19 23:25:39.000]}}, {:sensor_glucose_value, %{sgv: 158, timestamp: ~N[2018-02-19 23:20:39.000]}}, {:sensor_glucose_value, %{sgv: 166, timestamp: ~N[2018-02-19 23:15:39.000]}}, {:sensor_glucose_value, %{sgv: 176, timestamp: ~N[2018-02-19 23:10:39.000]}}, {:sensor_glucose_value, %{sgv: 183, timestamp: ~N[2018-02-19 23:05:39.000]}}, {:sensor_glucose_value, %{sgv: 187, timestamp: ~N[2018-02-19 23:00:39.000]}}, {:sensor_glucose_value, %{sgv: 195, timestamp: ~N[2018-02-19 22:55:39.000]}}, {:sensor_glucose_value, %{sgv: 203, timestamp: ~N[2018-02-19 22:50:39.000]}}, {:sensor_glucose_value, %{sgv: 210, timestamp: ~N[2018-02-19 22:45:39.000]}}, {:sensor_glucose_value, %{sgv: 219, timestamp: ~N[2018-02-19 22:40:39.000]}}, {:sensor_glucose_value, %{sgv: 228, timestamp: ~N[2018-02-19 22:35:39.000]}}, {:sensor_glucose_value, %{sgv: 240, timestamp: ~N[2018-02-19 22:30:39.000]}}, {:sensor_glucose_value, %{sgv: 247, timestamp: ~N[2018-02-19 22:25:39.000]}}, {:sensor_glucose_value, %{sgv: 256, timestamp: ~N[2018-02-19 22:20:39.000]}}, {:sensor_glucose_value, %{sgv: 267, timestamp: ~N[2018-02-19 22:15:39.000]}}, {:sensor_glucose_value, %{sgv: 279, timestamp: ~N[2018-02-19 22:10:39.000]}}, {:sensor_glucose_value, %{sgv: 289, timestamp: ~N[2018-02-19 22:05:39.000]}}, {:sensor_glucose_value, %{sgv: 300, timestamp: ~N[2018-02-19 22:00:39.000]}}, {:sensor_glucose_value, %{sgv: 308, timestamp: ~N[2018-02-19 21:55:39.000]}}, {:sensor_glucose_value, %{sgv: 310, timestamp: ~N[2018-02-19 21:50:39.000]}}, {:sensor_glucose_value, %{sgv: 308, timestamp: ~N[2018-02-19 21:45:39.000]}}, {:sensor_glucose_value, %{sgv: 297, timestamp: ~N[2018-02-19 21:40:39.000]}}, {:sensor_glucose_value, %{sgv: 285, timestamp: ~N[2018-02-19 21:35:39.000]}}, {:sensor_glucose_value, %{sgv: 272, timestamp: ~N[2018-02-19 21:30:39.000]}}, {:sensor_glucose_value, %{sgv: 263, timestamp: ~N[2018-02-19 21:25:44.000]}}, {:sensor_glucose_value, %{sgv: 226, timestamp: ~N[2018-02-19 21:20:39.000]}}, {:sensor_glucose_value, %{sgv: 216, timestamp: ~N[2018-02-19 21:15:39.000]}}, {:sensor_glucose_value, %{sgv: 212, timestamp: ~N[2018-02-19 21:10:39.000]}}, {:sensor_glucose_value, %{sgv: 208, timestamp: ~N[2018-02-19 21:05:39.000]}}, {:sensor_glucose_value, %{sgv: 199, timestamp: ~N[2018-02-19 21:00:39.000]}}, {:sensor_glucose_value, %{sgv: 191, timestamp: ~N[2018-02-19 20:55:39.000]}}, {:sensor_glucose_value, %{sgv: 187, timestamp: ~N[2018-02-19 20:50:39.000]}}, {:sensor_glucose_value, %{sgv: 182, timestamp: ~N[2018-02-19 20:45:39.000]}}, {:sensor_glucose_value, %{sgv: 170, timestamp: ~N[2018-02-19 20:40:39.000]}}, {:sensor_glucose_value, %{sgv: 169, timestamp: ~N[2018-02-19 20:35:39.000]}}, {:sensor_glucose_value, %{sgv: 165, timestamp: ~N[2018-02-19 20:30:38.000]}}, {:sensor_glucose_value, %{sgv: 154, timestamp: ~N[2018-02-19 20:25:39.000]}}, {:sensor_glucose_value, %{sgv: 144, timestamp: ~N[2018-02-19 20:20:39.000]}}, {:sensor_glucose_value, %{sgv: 138, timestamp: ~N[2018-02-19 20:15:39.000]}}, {:sensor_glucose_value, %{sgv: 138, timestamp: ~N[2018-02-19 20:10:40.000]}}, {:sensor_glucose_value, %{sgv: 139, timestamp: ~N[2018-02-19 20:05:40.000]}}, {:sensor_glucose_value, %{sgv: 139, timestamp: ~N[2018-02-19 20:00:39.000]}}, {:sensor_glucose_value, %{sgv: 141, timestamp: ~N[2018-02-19 19:55:40.000]}}, {:sensor_glucose_value, %{sgv: 141, timestamp: ~N[2018-02-19 19:50:40.000]}}, {:sensor_glucose_value, %{sgv: 141, timestamp: ~N[2018-02-19 19:45:39.000]}}, {:sensor_glucose_value, %{sgv: 139, timestamp: ~N[2018-02-19 19:40:40.000]}}, {:sensor_glucose_value, %{sgv: 137, timestamp: ~N[2018-02-19 19:30:40.000]}}, {:sensor_glucose_value, %{sgv: 141, timestamp: ~N[2018-02-19 19:20:39.000]}}, {:sensor_glucose_value, %{sgv: 141, timestamp: ~N[2018-02-19 19:15:40.000]}}, {:sensor_glucose_value, %{sgv: 141, timestamp: ~N[2018-02-19 19:10:39.000]}}, {:sensor_glucose_value, %{sgv: 141, timestamp: ~N[2018-02-19 19:05:40.000]}}, {:sensor_glucose_value, %{sgv: 138, timestamp: ~N[2018-02-19 19:00:40.000]}}, {:sensor_glucose_value, %{sgv: 135, timestamp: ~N[2018-02-19 18:50:39.000]}}, {:sensor_glucose_value, %{sgv: 137, timestamp: ~N[2018-02-19 18:45:40.000]}}, {:sensor_glucose_value, %{sgv: 140, timestamp: ~N[2018-02-19 18:40:40.000]}}, {:sensor_glucose_value, %{sgv: 144, timestamp: ~N[2018-02-19 18:35:40.000]}}, {:sensor_glucose_value, %{sgv: 151, timestamp: ~N[2018-02-19 18:30:39.000]}}, {:sensor_glucose_value, %{sgv: 161, timestamp: ~N[2018-02-19 18:25:40.000]}}, {:sensor_glucose_value, %{sgv: 173, timestamp: ~N[2018-02-19 18:20:40.000]}}, {:sensor_glucose_value, %{sgv: 166, timestamp: ~N[2018-02-19 18:15:40.000]}}, {:sensor_glucose_value, %{sgv: 156, timestamp: ~N[2018-02-19 18:10:40.000]}}, {:sensor_glucose_value, %{sgv: 157, timestamp: ~N[2018-02-19 18:05:40.000]}}, {:sensor_glucose_value, %{sgv: 155, timestamp: ~N[2018-02-19 18:00:40.000]}}, {:sensor_glucose_value, %{sgv: 154, timestamp: ~N[2018-02-19 17:55:39.000]}}, {:sensor_glucose_value, %{sgv: 156, timestamp: ~N[2018-02-19 17:50:39.000]}}, {:sensor_glucose_value, %{sgv: 153, timestamp: ~N[2018-02-19 17:45:40.000]}}, {:sensor_glucose_value, %{sgv: 151, timestamp: ~N[2018-02-19 17:40:39.000]}}, {:sensor_glucose_value, %{sgv: 150, timestamp: ~N[2018-02-19 17:35:40.000]}}, {:sensor_glucose_value, %{sgv: 148, timestamp: ~N[2018-02-19 17:30:40.000]}}, {:sensor_glucose_value, %{sgv: 148, timestamp: ~N[2018-02-19 17:25:40.000]}}, {:sensor_glucose_value, %{sgv: 143, timestamp: ~N[2018-02-19 17:20:40.000]}}, {:sensor_glucose_value, %{sgv: 146, timestamp: ~N[2018-02-19 17:15:39.000]}}, {:sensor_glucose_value, %{sgv: 149, timestamp: ~N[2018-02-19 17:10:39.000]}}, {:sensor_glucose_value, %{sgv: 149, timestamp: ~N[2018-02-19 17:05:40.000]}}, {:sensor_glucose_value, %{sgv: 149, timestamp: ~N[2018-02-19 17:00:39.000]}}, {:sensor_glucose_value, %{sgv: 150, timestamp: ~N[2018-02-19 16:55:40.000]}}, {:sensor_glucose_value, %{sgv: 151, timestamp: ~N[2018-02-19 16:50:40.000]}}, {:sensor_glucose_value, %{sgv: 149, timestamp: ~N[2018-02-19 16:45:39.000]}}, {:sensor_glucose_value, %{sgv: 149, timestamp: ~N[2018-02-19 16:40:40.000]}}, {:sensor_glucose_value, %{sgv: 150, timestamp: ~N[2018-02-19 16:35:40.000]}}, {:sensor_glucose_value, %{sgv: 151, timestamp: ~N[2018-02-19 16:30:39.000]}}, {:sensor_glucose_value, %{sgv: 149, timestamp: ~N[2018-02-19 16:25:40.000]}}, {:sensor_glucose_value, %{sgv: 145, timestamp: ~N[2018-02-19 16:20:40.000]}}, {:sensor_glucose_value, %{sgv: 145, timestamp: ~N[2018-02-19 16:15:40.000]}}, {:sensor_glucose_value, %{sgv: 146, timestamp: ~N[2018-02-19 16:10:40.000]}}, {:sensor_glucose_value, %{sgv: 144, timestamp: ~N[2018-02-19 16:05:40.000]}}, {:sensor_glucose_value, %{sgv: 143, timestamp: ~N[2018-02-19 16:00:39.000]}}, {:sensor_glucose_value, %{sgv: 145, timestamp: ~N[2018-02-19 15:55:39.000]}}, {:sensor_glucose_value, %{sgv: 145, timestamp: ~N[2018-02-19 15:50:40.000]}}, {:sensor_glucose_value, %{sgv: 146, timestamp: ~N[2018-02-19 15:45:39.000]}}, {:sensor_glucose_value, %{sgv: 142, timestamp: ~N[2018-02-19 15:40:40.000]}}, {:sensor_glucose_value, %{sgv: 132, timestamp: ~N[2018-02-19 15:35:40.000]}}, {:sensor_glucose_value, %{sgv: 131, timestamp: ~N[2018-02-19 15:30:40.000]}}, {:sensor_glucose_value, %{sgv: 126, timestamp: ~N[2018-02-19 15:25:41.000]}}, {:sensor_glucose_value, %{sgv: 120, timestamp: ~N[2018-02-19 15:20:40.000]}}, {:sensor_glucose_value, %{sgv: 114, timestamp: ~N[2018-02-19 15:15:40.000]}}, {:sensor_glucose_value, %{sgv: 108, timestamp: ~N[2018-02-19 15:10:40.000]}}, {:sensor_glucose_value, %{sgv: 100, timestamp: ~N[2018-02-19 15:05:40.000]}}, {:sensor_glucose_value, %{sgv: 95, timestamp: ~N[2018-02-19 15:00:41.000]}}, {:sensor_glucose_value, %{sgv: 96, timestamp: ~N[2018-02-19 14:55:41.000]}}, {:sensor_glucose_value, %{sgv: 98, timestamp: ~N[2018-02-19 14:50:40.000]}}, {:sensor_glucose_value, %{sgv: 96, timestamp: ~N[2018-02-19 14:45:41.000]}}, {:sensor_glucose_value, %{sgv: 87, timestamp: ~N[2018-02-19 14:40:40.000]}}, {:sensor_glucose_value, %{sgv: 78, timestamp: ~N[2018-02-19 14:35:40.000]}}, {:sensor_glucose_value, %{sgv: 73, timestamp: ~N[2018-02-19 14:30:40.000]}}, {:sensor_glucose_value, %{sgv: 72, timestamp: ~N[2018-02-19 14:25:41.000]}}, {:sensor_glucose_value, %{sgv: 69, timestamp: ~N[2018-02-19 14:20:40.000]}}, {:sensor_glucose_value, %{sgv: 64, timestamp: ~N[2018-02-19 14:15:40.000]}}, {:sensor_glucose_value, %{sgv: 62, timestamp: ~N[2018-02-19 14:10:41.000]}}, {:sensor_glucose_value, %{sgv: 62, timestamp: ~N[2018-02-19 14:05:40.000]}}, {:sensor_glucose_value, %{sgv: 64, timestamp: ~N[2018-02-19 14:00:40.000]}}, {:sensor_glucose_value, %{sgv: 62, timestamp: ~N[2018-02-19 13:55:40.000]}}, {:sensor_glucose_value, %{sgv: 61, timestamp: ~N[2018-02-19 13:50:41.000]}}, {:sensor_glucose_value, %{sgv: 60, timestamp: ~N[2018-02-19 13:45:40.000]}}, {:sensor_glucose_value, %{sgv: 59, timestamp: ~N[2018-02-19 13:40:41.000]}}, {:sensor_glucose_value, %{sgv: 60, timestamp: ~N[2018-02-19 13:35:40.000]}}, {:sensor_glucose_value, %{sgv: 63, timestamp: ~N[2018-02-19 13:30:40.000]}}, {:sensor_glucose_value, %{sgv: 67, timestamp: ~N[2018-02-19 13:25:40.000]}}, {:sensor_glucose_value, %{sgv: 67, timestamp: ~N[2018-02-19 13:20:40.000]}}, {:sensor_glucose_value, %{sgv: 70, timestamp: ~N[2018-02-19 13:15:40.000]}}, {:sensor_glucose_value, %{sgv: 74, timestamp: ~N[2018-02-19 13:10:41.000]}}, {:sensor_glucose_value, %{sgv: 80, timestamp: ~N[2018-02-19 13:05:41.000]}}, {:sensor_glucose_value, %{sgv: 87, timestamp: ~N[2018-02-19 13:00:40.000]}}, {:sensor_glucose_value, %{sgv: 93, timestamp: ~N[2018-02-19 12:55:41.000]}}, {:sensor_glucose_value, %{sgv: 95, timestamp: ~N[2018-02-19 12:50:41.000]}}, {:sensor_glucose_value, %{sgv: 96, timestamp: ~N[2018-02-19 12:45:41.000]}}, {:sensor_glucose_value, %{sgv: 97, timestamp: ~N[2018-02-19 12:40:40.000]}}, {:sensor_glucose_value, %{sgv: 97, timestamp: ~N[2018-02-19 12:35:40.000]}}, {:sensor_glucose_value, %{sgv: 101, timestamp: ~N[2018-02-19 12:30:41.000]}}, {:sensor_glucose_value, %{sgv: 99, timestamp: ~N[2018-02-19 12:25:41.000]}}, {:sensor_glucose_value, %{sgv: 101, timestamp: ~N[2018-02-19 12:20:41.000]}}, {:sensor_glucose_value, %{sgv: 103, timestamp: ~N[2018-02-19 12:15:40.000]}}, {:sensor_glucose_value, %{sgv: 100, timestamp: ~N[2018-02-19 12:10:40.000]}}, {:sensor_glucose_value, %{sgv: 98, timestamp: ~N[2018-02-19 12:05:40.000]}}, {:sensor_glucose_value, %{sgv: 100, timestamp: ~N[2018-02-19 12:00:40.000]}}, {:sensor_glucose_value, %{sgv: 104, timestamp: ~N[2018-02-19 11:55:41.000]}}, {:sensor_glucose_value, %{sgv: 111, timestamp: ~N[2018-02-19 11:50:40.000]}}, {:sensor_glucose_value, %{sgv: 117, timestamp: ~N[2018-02-19 11:45:41.000]}}, {:sensor_glucose_value, %{sgv: 123, timestamp: ~N[2018-02-19 11:40:41.000]}}, {:sensor_glucose_value, %{sgv: 126, timestamp: ~N[2018-02-19 11:35:40.000]}}, {:sensor_glucose_value, %{sgv: 128, timestamp: ~N[2018-02-19 11:30:41.000]}}, {:sensor_glucose_value, %{sgv: 129, timestamp: ~N[2018-02-19 11:25:40.000]}}, {:sensor_glucose_value, %{sgv: 124, timestamp: ~N[2018-02-19 11:20:40.000]}}, {:sensor_glucose_value, %{sgv: 116, timestamp: ~N[2018-02-19 11:15:40.000]}}, {:sensor_glucose_value, %{sgv: 108, timestamp: ~N[2018-02-19 11:10:40.000]}}, {:sensor_glucose_value, %{sgv: 106, timestamp: ~N[2018-02-19 11:05:41.000]}}, {:sensor_glucose_value, %{sgv: 105, timestamp: ~N[2018-02-19 11:00:41.000]}}, {:sensor_glucose_value, %{sgv: 104, timestamp: ~N[2018-02-19 10:55:42.000]}}, {:sensor_glucose_value, %{sgv: 102, timestamp: ~N[2018-02-19 10:50:41.000]}}, {:sensor_glucose_value, %{sgv: 98, timestamp: ~N[2018-02-19 10:45:42.000]}}, {:sensor_glucose_value, %{sgv: 100, timestamp: ~N[2018-02-19 10:40:42.000]}}, {:sensor_glucose_value, %{sgv: 104, timestamp: ~N[2018-02-19 10:35:41.000]}}, {:sensor_glucose_value, %{sgv: 107, timestamp: ~N[2018-02-19 10:30:41.000]}}, {:sensor_glucose_value, %{sgv: 109, timestamp: ~N[2018-02-19 10:25:41.000]}}, {:sensor_glucose_value, %{sgv: 111, timestamp: ~N[2018-02-19 10:20:41.000]}}, {:sensor_glucose_value, %{sgv: 114, timestamp: ~N[2018-02-19 10:15:41.000]}}, {:sensor_glucose_value, %{sgv: 117, timestamp: ~N[2018-02-19 10:10:41.000]}}, {:sensor_glucose_value, %{sgv: 118, timestamp: ~N[2018-02-19 10:05:41.000]}}, {:sensor_glucose_value, %{sgv: 119, timestamp: ~N[2018-02-19 10:00:41.000]}}, {:sensor_glucose_value, %{sgv: 120, timestamp: ~N[2018-02-19 09:55:41.000]}}, {:sensor_glucose_value, %{sgv: 120, timestamp: ~N[2018-02-19 09:50:42.000]}}, {:sensor_glucose_value, %{sgv: 119, timestamp: ~N[2018-02-19 09:45:41.000]}}, {:sensor_glucose_value, %{sgv: 122, timestamp: ~N[2018-02-19 09:40:41.000]}}, {:sensor_glucose_value, %{sgv: 119, timestamp: ~N[2018-02-19 09:35:41.000]}}, {:sensor_glucose_value, %{sgv: 114, timestamp: ~N[2018-02-19 09:30:41.000]}}, {:sensor_glucose_value, %{sgv: 112, timestamp: ~N[2018-02-19 09:25:41.000]}}, {:sensor_glucose_value, %{sgv: 111, timestamp: ~N[2018-02-19 09:20:41.000]}}, {:sensor_glucose_value, %{sgv: 107, timestamp: ~N[2018-02-19 09:15:42.000]}}, {:sensor_glucose_value, %{sgv: 106, timestamp: ~N[2018-02-19 09:10:41.000]}}, {:sensor_glucose_value, %{sgv: 104, timestamp: ~N[2018-02-19 09:05:42.000]}}, {:sensor_glucose_value, %{sgv: 103, timestamp: ~N[2018-02-19 09:00:41.000]}}, {:sensor_glucose_value, %{sgv: 100, timestamp: ~N[2018-02-19 08:55:42.000]}}, {:sensor_glucose_value, %{sgv: 97, timestamp: ~N[2018-02-19 08:50:41.000]}}, {:sensor_glucose_value, %{sgv: 97, timestamp: ~N[2018-02-19 08:45:41.000]}}, {:sensor_glucose_value, %{sgv: 97, timestamp: ~N[2018-02-19 08:40:42.000]}}, {:sensor_glucose_value, %{sgv: 97, timestamp: ~N[2018-02-19 08:35:41.000]}}, {:sensor_glucose_value, %{sgv: 100, timestamp: ~N[2018-02-19 08:30:41.000]}}, {:sensor_glucose_value, %{sgv: 104, timestamp: ~N[2018-02-19 08:25:41.000]}}, {:sensor_glucose_value, %{sgv: 106, timestamp: ~N[2018-02-19 08:20:41.000]}}, {:sensor_glucose_value, %{sgv: 107, timestamp: ~N[2018-02-19 08:15:42.000]}}, {:sensor_glucose_value, %{sgv: 107, timestamp: ~N[2018-02-19 08:10:41.000]}}, {:sensor_glucose_value, %{sgv: 107, timestamp: ~N[2018-02-19 08:05:41.000]}}, {:sensor_glucose_value, %{sgv: 107, timestamp: ~N[2018-02-19 08:00:41.000]}}, {:sensor_glucose_value, %{sgv: 107, timestamp: ~N[2018-02-19 07:55:41.000]}}, {:sensor_glucose_value, %{sgv: 106, timestamp: ~N[2018-02-19 07:50:41.000]}}, {:sensor_glucose_value, %{sgv: 104, timestamp: ~N[2018-02-19 07:45:41.000]}}, {:sensor_glucose_value, %{sgv: 102, timestamp: ~N[2018-02-19 07:40:41.000]}}, {:sensor_glucose_value, %{sgv: 99, timestamp: ~N[2018-02-19 07:35:42.000]}}, {:sensor_glucose_value, %{sgv: 99, timestamp: ~N[2018-02-19 07:30:41.000]}}, {:sensor_glucose_value, %{sgv: 98, timestamp: ~N[2018-02-19 07:25:41.000]}}, {:sensor_glucose_value, %{sgv: 99, timestamp: ~N[2018-02-19 07:20:41.000]}}, {:sensor_glucose_value, %{sgv: 101, timestamp: ~N[2018-02-19 07:15:41.000]}}, {:sensor_glucose_value, %{sgv: 97, timestamp: ~N[2018-02-19 07:10:41.000]}}, {:sensor_glucose_value, %{sgv: 94, timestamp: ~N[2018-02-19 07:05:41.000]}}, {:sensor_glucose_value, %{sgv: 95, timestamp: ~N[2018-02-19 07:00:42.000]}}, {:sensor_glucose_value, %{sgv: 97, timestamp: ~N[2018-02-19 06:55:41.000]}}, {:sensor_glucose_value, %{sgv: 98, timestamp: ~N[2018-02-19 06:50:41.000]}}, {:sensor_glucose_value, %{sgv: 98, timestamp: ~N[2018-02-19 06:45:41.000]}}, {:sensor_glucose_value, %{sgv: 96, timestamp: ~N[2018-02-19 06:40:41.000]}}, {:sensor_glucose_value, %{sgv: 92, timestamp: ~N[2018-02-19 06:35:41.000]}}, {:sensor_glucose_value, %{sgv: 92, timestamp: ~N[2018-02-19 06:30:41.000]}}, {:sensor_glucose_value, %{sgv: 95, timestamp: ~N[2018-02-19 06:25:41.000]}}, {:sensor_glucose_value, %{sgv: 99, timestamp: ~N[2018-02-19 06:20:41.000]}}, {:sensor_glucose_value, %{sgv: 100, timestamp: ~N[2018-02-19 06:15:42.000]}}, {:sensor_glucose_value, %{sgv: 100, timestamp: ~N[2018-02-19 06:10:42.000]}}, {:sensor_glucose_value, %{sgv: 99, timestamp: ~N[2018-02-19 06:05:42.000]}}, {:sensor_glucose_value, %{sgv: 99, timestamp: ~N[2018-02-19 06:00:42.000]}}, {:sensor_glucose_value, %{sgv: 98, timestamp: ~N[2018-02-19 05:55:42.000]}}, {:sensor_glucose_value, %{sgv: 96, timestamp: ~N[2018-02-19 05:50:42.000]}}, {:sensor_glucose_value, %{sgv: 92, timestamp: ~N[2018-02-19 05:45:42.000]}}, {:sensor_glucose_value, %{sgv: 90, timestamp: ~N[2018-02-19 05:40:41.000]}}, {:sensor_glucose_value, %{sgv: 90, timestamp: ~N[2018-02-19 05:35:42.000]}}, {:sensor_glucose_value, %{sgv: 92, timestamp: ~N[2018-02-19 05:30:42.000]}}, {:sensor_glucose_value, %{sgv: 90, timestamp: ~N[2018-02-19 05:25:42.000]}}, {:sensor_glucose_value, %{sgv: 88, timestamp: ~N[2018-02-19 05:20:42.000]}}, {:sensor_glucose_value, %{sgv: 88, timestamp: ~N[2018-02-19 05:15:42.000]}}, {:sensor_glucose_value, %{sgv: 86, timestamp: ~N[2018-02-19 05:10:42.000]}}, {:sensor_glucose_value, %{sgv: 85, timestamp: ~N[2018-02-19 05:05:42.000]}}, {:sensor_glucose_value, %{sgv: 85, timestamp: ~N[2018-02-19 05:00:42.000]}}, {:sensor_glucose_value, %{sgv: 84, timestamp: ~N[2018-02-19 04:55:42.000]}}, {:sensor_glucose_value, %{sgv: 85, timestamp: ~N[2018-02-19 04:50:42.000]}}, {:sensor_glucose_value, %{sgv: 85, timestamp: ~N[2018-02-19 04:45:42.000]}}, {:sensor_glucose_value, %{sgv: 86, timestamp: ~N[2018-02-19 04:40:42.000]}}, {:sensor_glucose_value, %{sgv: 87, timestamp: ~N[2018-02-19 04:35:42.000]}}, {:sensor_glucose_value, %{sgv: 88, timestamp: ~N[2018-02-19 04:30:42.000]}}, {:sensor_glucose_value, %{sgv: 89, timestamp: ~N[2018-02-19 04:25:42.000]}}, {:sensor_glucose_value, %{sgv: 92, timestamp: ~N[2018-02-19 04:20:42.000]}}, {:sensor_glucose_value, %{sgv: 93, timestamp: ~N[2018-02-19 04:15:42.000]}}, {:sensor_glucose_value, %{sgv: 94, timestamp: ~N[2018-02-19 04:10:42.000]}}, {:sensor_glucose_value, %{sgv: 95, timestamp: ~N[2018-02-19 04:05:42.000]}}, {:sensor_glucose_value, %{sgv: 95, timestamp: ~N[2018-02-19 04:00:42.000]}}, {:sensor_glucose_value, %{sgv: 94, timestamp: ~N[2018-02-19 03:55:42.000]}}, {:sensor_glucose_value, %{sgv: 95, timestamp: ~N[2018-02-19 03:50:42.000]}}, {:sensor_glucose_value, %{sgv: 95, timestamp: ~N[2018-02-19 03:45:42.000]}}, {:sensor_glucose_value, %{sgv: 96, timestamp: ~N[2018-02-19 03:40:41.000]}}, {:sensor_glucose_value, %{sgv: 96, timestamp: ~N[2018-02-19 03:35:42.000]}}, {:sensor_glucose_value, %{sgv: 97, timestamp: ~N[2018-02-19 03:30:42.000]}}, {:sensor_glucose_value, %{sgv: 97, timestamp: ~N[2018-02-19 03:25:42.000]}}, {:sensor_glucose_value, %{sgv: 120, timestamp: ~N[2018-02-19 03:20:38.000]}}, {:sensor_glucose_value, %{sgv: 123, timestamp: ~N[2018-02-19 03:15:38.000]}}, {:sensor_glucose_value, %{sgv: 126, timestamp: ~N[2018-02-19 03:10:38.000]}}, {:sensor_glucose_value, %{sgv: 130, timestamp: ~N[2018-02-19 03:05:38.000]}}, {:sensor_glucose_value, %{sgv: 133, timestamp: ~N[2018-02-19 03:00:39.000]}}, {:sensor_glucose_value, %{sgv: 130, timestamp: ~N[2018-02-19 02:55:38.000]}}, {:sensor_glucose_value, %{sgv: 133, timestamp: ~N[2018-02-19 02:50:38.000]}}, {:sensor_glucose_value, %{sgv: 134, timestamp: ~N[2018-02-19 02:45:38.000]}}, {:sensor_glucose_value, %{sgv: 134, timestamp: ~N[2018-02-19 02:40:38.000]}}, {:sensor_glucose_value, %{sgv: 131, timestamp: ~N[2018-02-19 02:35:38.000]}}, {:sensor_glucose_value, %{sgv: 127, timestamp: ~N[2018-02-19 02:30:38.000]}}, {:sensor_glucose_value, %{sgv: 123, timestamp: ~N[2018-02-19 02:25:38.000]}}, {:sensor_glucose_value, %{sgv: 120, timestamp: ~N[2018-02-19 02:20:38.000]}}, {:sensor_glucose_value, %{sgv: 120, timestamp: ~N[2018-02-19 02:15:38.000]}}, {:sensor_glucose_value, %{sgv: 120, timestamp: ~N[2018-02-19 02:10:38.000]}}, {:sensor_glucose_value, %{sgv: 124, timestamp: ~N[2018-02-19 02:05:38.000]}}, {:sensor_glucose_value, %{sgv: 127, timestamp: ~N[2018-02-19 02:00:38.000]}}, {:sensor_glucose_value, %{sgv: 130, timestamp: ~N[2018-02-19 01:55:38.000]}}, {:sensor_glucose_value, %{sgv: 133, timestamp: ~N[2018-02-19 01:50:39.000]}}, {:sensor_glucose_value, %{sgv: 133, timestamp: ~N[2018-02-19 01:45:39.000]}}, {:sensor_glucose_value, %{sgv: 135, timestamp: ~N[2018-02-19 01:40:39.000]}}, {:sensor_glucose_value, %{sgv: 134, timestamp: ~N[2018-02-19 01:35:38.000]}}, {:sensor_glucose_value, %{sgv: 132, timestamp: ~N[2018-02-19 01:30:38.000]}}, {:sensor_glucose_value, %{sgv: 127, timestamp: ~N[2018-02-19 01:25:39.000]}}, {:sensor_glucose_value, %{sgv: 118, timestamp: ~N[2018-02-19 01:20:38.000]}}, {:sensor_glucose_value, %{sgv: 113, timestamp: ~N[2018-02-19 01:15:38.000]}}, {:sensor_glucose_value, %{sgv: 111, timestamp: ~N[2018-02-19 01:10:39.000]}}, {:sensor_glucose_value, %{sgv: 104, timestamp: ~N[2018-02-19 01:05:38.000]}}, {:sensor_glucose_value, %{sgv: 91, timestamp: ~N[2018-02-19 01:00:38.000]}}, {:sensor_glucose_value, %{sgv: 73, timestamp: ~N[2018-02-19 00:55:39.000]}}, {:sensor_glucose_value, %{sgv: 56, timestamp: ~N[2018-02-19 00:50:39.000]}}, {:sensor_glucose_value, %{sgv: 45, timestamp: ~N[2018-02-19 00:45:39.000]}}, {:sensor_glucose_value, %{sgv: 47, timestamp: ~N[2018-02-19 00:40:39.000]}}, {:sensor_glucose_value, %{sgv: 49, timestamp: ~N[2018-02-19 00:35:39.000]}}, {:sensor_glucose_value, %{sgv: 51, timestamp: ~N[2018-02-19 00:30:39.000]}}, {:sensor_glucose_value, %{sgv: 54, timestamp: ~N[2018-02-19 00:25:39.000]}}, {:sensor_glucose_value, %{sgv: 57, timestamp: ~N[2018-02-19 00:20:39.000]}}, {:sensor_glucose_value, %{sgv: 60, timestamp: ~N[2018-02-19 00:15:39.000]}}, {:sensor_glucose_value, %{sgv: 64, timestamp: ~N[2018-02-19 00:10:39.000]}}, {:sensor_glucose_value, %{sgv: 69, timestamp: ~N[2018-02-19 00:05:39.000]}}, {:sensor_glucose_value, %{sgv: 78, timestamp: ~N[2018-02-19 00:00:39.000]}} ] end end
lib/pummpcomm/session/pump_fake.ex
0.727201
0.425009
pump_fake.ex
starcoder
defmodule LoggerErrorCounterBackend do @moduledoc """ A `Logger` backend that publishes the number of error messages and the last error message In your config, simply do something like this: ```elixir config :logger_error_counter_backend, path: [:log, :errors] ``` LoggerErrorCounterBackend is configured when specified, and supports the following options: `:point` - the `Nerves.Hub` point to publish the error count. Defaults to: [] `:format` - the format message used to print logs. Defaults to: "$time $metadata[$level] $levelpad$message\n" `:metadata` - the metadata to be printed by $metadata. Defaults to an empty list (no metadata) `:count` - set/reset the count. Defaults to: 0 Configuration may also be conducted using `Logger.configure_backends/2` """ use GenEvent require Logger @point Application.get_env(:logger_error_counter_backend, :point, []) @metadata Application.get_env(:logger_error_counter_backend, :metadata, []) @default_format "$time $metadata[$level] $message\n" @level :error @defaults %{point: @point, format: @default_format, metadata: @metadata, count: 0} @doc false def init({__MODULE__, opts}) do config = configure(opts, @defaults) Logger.debug "#{__MODULE__} Starting at: #{inspect config.point}" Nerves.Hub.put config.point, count: 0, last_message: nil {:ok, config} end def init(__MODULE__), do: init({__MODULE__, []}) def handle_call({:configure, options}, state) do {:ok, :ok, configure(options, state)} end @doc false def handle_event({level, _gl, {Logger, message, timestamp, metadata}}, %{point: point, count: count} = state) do state = if (Logger.compare_levels(level, @level) != :lt and point) do entry = format_event(level, message, timestamp, metadata, state) publish(point, count + 1, entry) %{state | count: count + 1} else state end {:ok, state} end def handle_event(:flush, state) do {:ok, state} end defp configure(opts, defaults) do point = Dict.get(opts, :point, defaults.point) format = case Dict.get(opts, :format, defaults.format) do f when is_list(f) -> f f -> Logger.Formatter.compile f end metadata = Dict.get(opts, :metadata, defaults.metadata) count = Dict.get(opts, :count, defaults.count) %{point: point, format: format, metadata: metadata, count: count} end defp format_event(level, msg, ts, md, %{format: format, metadata: metadata} = _state) do Logger.Formatter.format(format, level, msg, ts, take_metadata(md, metadata)) |> IO.chardata_to_string end defp take_metadata(metadata, keys) do metadatas = Enum.reduce(keys, [], fn key, acc -> case Keyword.fetch(metadata, key) do {:ok, val} -> [{key, val} | acc] :error -> acc end end) Enum.reverse(metadatas) end defp publish(point, count, entry) do Nerves.Hub.put point, count: count, last_message: entry end end
lib/logger_error_counter_backend.ex
0.839092
0.784814
logger_error_counter_backend.ex
starcoder
defmodule Changelog.Episode do use Changelog.Schema, default_sort: :published_at alias Changelog.{ EpisodeHost, EpisodeGuest, EpisodeRequest, EpisodeTopic, EpisodeStat, EpisodeSponsor, Files, Github, NewsItem, Notifier, Podcast, Regexp, Search, Transcripts } alias ChangelogWeb.{EpisodeView, TimeView} defenum(Type, full: 0, bonus: 1, trailer: 2) schema "episodes" do field :slug, :string field :guid, :string field :title, :string field :subtitle, :string field :type, Type field :featured, :boolean, default: false field :highlight, :string field :subhighlight, :string field :summary, :string field :notes, :string field :doc_url, :string field :published, :boolean, default: false field :published_at, :utc_datetime field :recorded_at, :utc_datetime field :recorded_live, :boolean, default: false field :youtube_id, :string field :audio_file, Files.Audio.Type field :audio_bytes, :integer field :audio_duration, :integer field :plusplus_file, Files.PlusPlus.Type field :plusplus_bytes, :integer field :plusplus_duration, :integer field :download_count, :float field :import_count, :float field :reach_count, :integer field :transcript, {:array, :map} # this exists merely to satisfy the compiler # see load_news_item/1 and get_news_item/1 for actual use field :news_item, :map, virtual: true belongs_to :podcast, Podcast belongs_to :episode_request, EpisodeRequest, foreign_key: :request_id has_many :episode_hosts, EpisodeHost, on_delete: :delete_all has_many :hosts, through: [:episode_hosts, :person] has_many :episode_guests, EpisodeGuest, on_delete: :delete_all has_many :guests, through: [:episode_guests, :person] has_many :episode_topics, EpisodeTopic, on_delete: :delete_all has_many :topics, through: [:episode_topics, :topic] has_many :episode_sponsors, EpisodeSponsor, on_delete: :delete_all has_many :sponsors, through: [:episode_sponsors, :sponsor] has_many :episode_stats, EpisodeStat, on_delete: :delete_all timestamps() end def distinct_podcast(query), do: from(q in query, distinct: q.podcast_id) def featured(query \\ __MODULE__), do: from(q in query, where: q.featured == true) def next_after(query \\ __MODULE__, episode), do: from(q in query, where: q.published_at > ^episode.published_at) def previous_to(query \\ __MODULE__, episode), do: from(q in query, where: q.published_at < ^episode.published_at) def published(query \\ __MODULE__), do: published(query, Timex.now()) def published(query, as_of), do: from(q in query, where: q.published, where: q.published_at <= ^Timex.to_datetime(as_of)) def recorded_between(query, start_time, end_time), do: from(q in query, where: q.recorded_at <= ^start_time, where: q.end_time < ^end_time) def recorded_future_to(query, time), do: from(q in query, where: q.recorded_at > ^time) def recorded_live(query \\ __MODULE__), do: from(q in query, where: q.recorded_live == true) def scheduled(query \\ __MODULE__), do: from(q in query, where: q.published, where: q.published_at > ^Timex.now()) def search(query, term), do: from(q in query, where: fragment("search_vector @@ plainto_tsquery('english', ?)", ^term)) def unpublished(query \\ __MODULE__), do: from(q in query, where: not q.published) def top_reach_first(query \\ __MODULE__), do: from(q in query, order_by: [desc: :reach_count]) def with_ids(query \\ __MODULE__, ids), do: from(q in query, where: q.id in ^ids) def with_numbered_slug(query \\ __MODULE__), do: from(q in query, where: fragment("slug ~ E'^\\\\d+$'")) def with_slug(query \\ __MODULE__, slug), do: from(q in query, where: q.slug == ^slug) def with_podcast_slug(query \\ __MODULE__, slug) def with_podcast_slug(query, nil), do: query def with_podcast_slug(query, slug), do: from(q in query, join: p in Podcast, where: q.podcast_id == p.id, where: p.slug == ^slug) def full(query \\ __MODULE__), do: from(q in query, where: q.type == ^:full) def bonus(query \\ __MODULE__), do: from(q in query, where: q.type == ^:bonus) def trailer(query \\ __MODULE__), do: from(q in query, where: q.type == ^:trailer) def exclude_transcript(query \\ __MODULE__) do fields = __MODULE__.__schema__(:fields) |> Enum.reject(&(&1 == :transcript)) from(q in query, select: ^fields) end def has_transcript(%{transcript: nil}), do: false def has_transcript(%{transcript: []}), do: false def has_transcript(_), do: true def is_public(episode, as_of \\ Timex.now()) do is_published(episode) && Timex.before?(episode.published_at, as_of) end def is_published(episode), do: episode.published def is_publishable(episode) do validated = episode |> change(%{}) |> validate_required([:slug, :title, :published_at, :summary, :audio_file]) |> validate_format(:slug, Regexp.slug(), message: Regexp.slug_message()) |> unique_constraint(:slug, name: :episodes_slug_podcast_id_index) |> cast_assoc(:episode_hosts) validated.valid? && !is_published(episode) end def admin_changeset(struct, params \\ %{}) do struct |> cast(params, [ :slug, :title, :subtitle, :published, :featured, :request_id, :highlight, :subhighlight, :summary, :notes, :doc_url, :published_at, :recorded_at, :recorded_live, :youtube_id, :guid, :type ]) |> cast_attachments(params, [:audio_file, :plusplus_file]) |> validate_required([:slug, :title, :published, :featured]) |> validate_format(:slug, Regexp.slug(), message: Regexp.slug_message()) |> validate_published_has_published_at() |> unique_constraint(:slug, name: :episodes_slug_podcast_id_index) |> cast_assoc(:episode_hosts) |> cast_assoc(:episode_guests) |> cast_assoc(:episode_sponsors) |> cast_assoc(:episode_topics) |> derive_audio_bytes_and_duration() |> derive_plusplus_bytes_and_duration() end def get_news_item(episode) do episode |> NewsItem.with_episode() |> Repo.one() end def has_news_item(episode) do episode |> NewsItem.with_episode() |> Repo.exists?() end def load_news_item(episode) do item = episode |> get_news_item() |> NewsItem.load_object(episode) Map.put(episode, :news_item, item) end def object_id(episode), do: "#{episode.podcast_id}:#{episode.id}" def participants(episode) do episode = if Ecto.assoc_loaded?(episode.guests) and Ecto.assoc_loaded?(episode.hosts) do episode else episode |> preload_guests() |> preload_hosts() end episode.guests ++ episode.hosts end def preload_all(episode) do episode |> preload_podcast() |> preload_topics() |> preload_guests() |> preload_hosts() |> preload_sponsors() |> preload_episode_request() end def preload_episode_request(query = %Ecto.Query{}), do: Ecto.Query.preload(query, :episode_request) def preload_episode_request(episode), do: Repo.preload(episode, :episode_request) def preload_hosts(query = %Ecto.Query{}) do query |> Ecto.Query.preload(episode_hosts: ^EpisodeHost.by_position()) |> Ecto.Query.preload(:hosts) end def preload_hosts(episode) do episode |> Repo.preload(episode_hosts: {EpisodeHost.by_position(), :person}) |> Repo.preload(:hosts) end def preload_guests(query = %Ecto.Query{}) do query |> Ecto.Query.preload(episode_guests: ^EpisodeGuest.by_position()) |> Ecto.Query.preload(:guests) end def preload_guests(episode) do episode |> Repo.preload(episode_guests: {EpisodeGuest.by_position(), :person}) |> Repo.preload(:guests) end def preload_podcast(nil), do: nil def preload_podcast(query = %Ecto.Query{}), do: Ecto.Query.preload(query, :podcast) def preload_podcast(episode), do: Repo.preload(episode, :podcast) def preload_sponsors(query = %Ecto.Query{}) do query |> Ecto.Query.preload(episode_sponsors: ^EpisodeSponsor.by_position()) |> Ecto.Query.preload(:sponsors) end def preload_sponsors(episode) do episode |> Repo.preload(episode_sponsors: {EpisodeSponsor.by_position(), :sponsor}) |> Repo.preload(:sponsors) end def preload_topics(query = %Ecto.Query{}) do query |> Ecto.Query.preload(episode_topics: ^EpisodeTopic.by_position()) |> Ecto.Query.preload(:topics) end def preload_topics(episode) do episode |> Repo.preload(episode_topics: {EpisodeTopic.by_position(), :topic}) |> Repo.preload(:topics) end def update_stat_counts(episode) do stats = Repo.all(assoc(episode, :episode_stats)) new_downloads = stats |> Enum.map(& &1.downloads) |> Enum.sum() |> Kernel.+(episode.import_count) |> Kernel./(1) |> Float.round(2) new_reach = stats |> Enum.map(& &1.uniques) |> Enum.sum() episode |> change(%{download_count: new_downloads, reach_count: new_reach}) |> Repo.update!() end def update_notes(episode, text) do episode |> change(notes: text) |> Repo.update!() end def update_transcript(episode, text) do case Transcripts.Parser.parse_text(text, participants(episode)) do {:ok, parsed} -> updated = episode |> change(transcript: parsed) |> Repo.update!() if !has_transcript(episode) && has_transcript(updated) do Task.start_link(fn -> Notifier.notify(updated) end) end Task.start_link(fn -> Search.save_item(updated) end) updated {:error, e} -> source = Github.Source.new("transcripts", episode) Github.Issuer.create(source, e) end end def flatten_for_filtering(query \\ __MODULE__) do query = from episode in query, left_join: podcast in assoc(episode, :podcast), left_join: hosts in assoc(episode, :hosts), left_join: guests in assoc(episode, :guests), left_join: topics in assoc(episode, :topics), preload: [podcast: podcast, hosts: hosts, guests: guests, topics: topics] result = query |> published() |> exclude_transcript() |> Repo.all() |> Enum.map(fn episode -> extract_episode_fields(episode) end) {:ok, result} end def flatten_episode_for_filtering(episode) do episode |> Repo.preload([:podcast, :hosts, :guests, :topics]) |> extract_episode_fields() end defp extract_episode_fields(episode) do %{ id: episode.id, slug: episode.slug, title: episode.title, type: episode.type, published_at: episode.published_at, podcast: episode.podcast.slug, host: Enum.map(episode.hosts, fn host -> host.name end), guest: Enum.map(episode.guests, fn guest -> guest.name end), topic: Enum.map(episode.topics, fn topic -> topic.slug end) } end defp derive_audio_bytes_and_duration(changeset = %{changes: %{audio_file: _}}) do new_file = get_change(changeset, :audio_file) tagged_file = EpisodeView.audio_local_path(%{changeset.data | audio_file: new_file}) case File.stat(tagged_file) do {:ok, stats} -> seconds = extract_duration_seconds(tagged_file) change(changeset, audio_bytes: stats.size, audio_duration: seconds) {:error, _} -> changeset end end defp derive_audio_bytes_and_duration(changeset), do: changeset defp derive_plusplus_bytes_and_duration(changeset = %{changes: %{plusplus_file: _}}) do new_file = get_change(changeset, :plusplus_file) tagged_file = EpisodeView.plusplus_local_path(%{changeset.data | plusplus_file: new_file}) case File.stat(tagged_file) do {:ok, stats} -> seconds = extract_duration_seconds(tagged_file) change(changeset, plusplus_bytes: stats.size, plusplus_duration: seconds) {:error, _} -> changeset end end defp derive_plusplus_bytes_and_duration(changeset), do: changeset defp extract_duration_seconds(path) do try do {info, _exit_code} = System.cmd("ffmpeg", ["-i", path], stderr_to_stdout: true) [_match, duration] = Regex.run(~r/Duration: (.*?),/, info) TimeView.seconds(duration) catch _all -> 0 end end defp validate_published_has_published_at(changeset) do published = get_field(changeset, :published) published_at = get_field(changeset, :published_at) if published && is_nil(published_at) do add_error(changeset, :published_at, "can't be blank when published") else changeset end end end
lib/changelog/schema/episode/episode.ex
0.535584
0.487612
episode.ex
starcoder
defmodule AWS.EMRcontainers do @moduledoc """ Amazon EMR on EKS provides a deployment option for Amazon EMR that allows you to run open-source big data frameworks on Amazon Elastic Kubernetes Service (Amazon EKS). With this deployment option, you can focus on running analytics workloads while Amazon EMR on EKS builds, configures, and manages containers for open-source applications. For more information about Amazon EMR on EKS concepts and tasks, see [What is Amazon EMR on EKS](https://docs.aws.amazon.com/emr/latest/EMR-on-EKS-DevelopmentGuide/emr-eks.html). *Amazon EMR containers* is the API name for Amazon EMR on EKS. The `emr-containers` prefix is used in the following scenarios: * It is the prefix in the CLI commands for Amazon EMR on EKS. For example, `aws emr-containers start-job-run`. * It is the prefix before IAM policy actions for Amazon EMR on EKS. For example, `"Action": [ "emr-containers:StartJobRun"]`. For more information, see [Policy actions for Amazon EMR on EKS](https://docs.aws.amazon.com/emr/latest/EMR-on-EKS-DevelopmentGuide/security_iam_service-with-iam.html#security_iam_service-with-iam-id-based-policies-actions). * It is the prefix used in Amazon EMR on EKS service endpoints. For example, `emr-containers.us-east-2.amazonaws.com`. For more information, see [Amazon EMR on EKS Service Endpoints](https://docs.aws.amazon.com/emr/latest/EMR-on-EKS-DevelopmentGuide/service-quotas.html#service-endpoints). """ alias AWS.Client alias AWS.Request def metadata do %AWS.ServiceMetadata{ abbreviation: nil, api_version: "2020-10-01", content_type: "application/x-amz-json-1.1", credential_scope: nil, endpoint_prefix: "emr-containers", global?: false, protocol: "rest-json", service_id: "EMR containers", signature_version: "v4", signing_name: "emr-containers", target_prefix: nil } end @doc """ Cancels a job run. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS. """ def cancel_job_run(%Client{} = client, id, virtual_cluster_id, input, options \\ []) do url_path = "/virtualclusters/#{URI.encode(virtual_cluster_id)}/jobruns/#{URI.encode(id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, nil ) end @doc """ Creates a managed endpoint. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster. """ def create_managed_endpoint(%Client{} = client, virtual_cluster_id, input, options \\ []) do url_path = "/virtualclusters/#{URI.encode(virtual_cluster_id)}/endpoints" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Creates a virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements. """ def create_virtual_cluster(%Client{} = client, input, options \\ []) do url_path = "/virtualclusters" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Deletes a managed endpoint. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster. """ def delete_managed_endpoint(%Client{} = client, id, virtual_cluster_id, input, options \\ []) do url_path = "/virtualclusters/#{URI.encode(virtual_cluster_id)}/endpoints/#{URI.encode(id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, nil ) end @doc """ Deletes a virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements. """ def delete_virtual_cluster(%Client{} = client, id, input, options \\ []) do url_path = "/virtualclusters/#{URI.encode(id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, nil ) end @doc """ Displays detailed information about a job run. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS. """ def describe_job_run(%Client{} = client, id, virtual_cluster_id, options \\ []) do url_path = "/virtualclusters/#{URI.encode(virtual_cluster_id)}/jobruns/#{URI.encode(id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Displays detailed information about a managed endpoint. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster. """ def describe_managed_endpoint(%Client{} = client, id, virtual_cluster_id, options \\ []) do url_path = "/virtualclusters/#{URI.encode(virtual_cluster_id)}/endpoints/#{URI.encode(id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Displays detailed information about a specified virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements. """ def describe_virtual_cluster(%Client{} = client, id, options \\ []) do url_path = "/virtualclusters/#{URI.encode(id)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Lists job runs based on a set of parameters. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS. """ def list_job_runs( %Client{} = client, virtual_cluster_id, created_after \\ nil, created_before \\ nil, max_results \\ nil, name \\ nil, next_token \\ nil, states \\ nil, options \\ [] ) do url_path = "/virtualclusters/#{URI.encode(virtual_cluster_id)}/jobruns" headers = [] query_params = [] query_params = if !is_nil(states) do [{"states", states} | query_params] else query_params end query_params = if !is_nil(next_token) do [{"nextToken", next_token} | query_params] else query_params end query_params = if !is_nil(name) do [{"name", name} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"maxResults", max_results} | query_params] else query_params end query_params = if !is_nil(created_before) do [{"createdBefore", created_before} | query_params] else query_params end query_params = if !is_nil(created_after) do [{"createdAfter", created_after} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Lists managed endpoints based on a set of parameters. A managed endpoint is a gateway that connects EMR Studio to Amazon EMR on EKS so that EMR Studio can communicate with your virtual cluster. """ def list_managed_endpoints( %Client{} = client, virtual_cluster_id, created_after \\ nil, created_before \\ nil, max_results \\ nil, next_token \\ nil, states \\ nil, types \\ nil, options \\ [] ) do url_path = "/virtualclusters/#{URI.encode(virtual_cluster_id)}/endpoints" headers = [] query_params = [] query_params = if !is_nil(types) do [{"types", types} | query_params] else query_params end query_params = if !is_nil(states) do [{"states", states} | query_params] else query_params end query_params = if !is_nil(next_token) do [{"nextToken", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"maxResults", max_results} | query_params] else query_params end query_params = if !is_nil(created_before) do [{"createdBefore", created_before} | query_params] else query_params end query_params = if !is_nil(created_after) do [{"createdAfter", created_after} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Lists the tags assigned to the resources. """ def list_tags_for_resource(%Client{} = client, resource_arn, options \\ []) do url_path = "/tags/#{URI.encode(resource_arn)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Lists information about the specified virtual cluster. Virtual cluster is a managed entity on Amazon EMR on EKS. You can create, describe, list and delete virtual clusters. They do not consume any additional resource in your system. A single virtual cluster maps to a single Kubernetes namespace. Given this relationship, you can model virtual clusters the same way you model Kubernetes namespaces to meet your requirements. """ def list_virtual_clusters( %Client{} = client, container_provider_id \\ nil, container_provider_type \\ nil, created_after \\ nil, created_before \\ nil, max_results \\ nil, next_token \\ nil, states \\ nil, options \\ [] ) do url_path = "/virtualclusters" headers = [] query_params = [] query_params = if !is_nil(states) do [{"states", states} | query_params] else query_params end query_params = if !is_nil(next_token) do [{"nextToken", next_token} | query_params] else query_params end query_params = if !is_nil(max_results) do [{"maxResults", max_results} | query_params] else query_params end query_params = if !is_nil(created_before) do [{"createdBefore", created_before} | query_params] else query_params end query_params = if !is_nil(created_after) do [{"createdAfter", created_after} | query_params] else query_params end query_params = if !is_nil(container_provider_type) do [{"containerProviderType", container_provider_type} | query_params] else query_params end query_params = if !is_nil(container_provider_id) do [{"containerProviderId", container_provider_id} | query_params] else query_params end Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Starts a job run. A job run is a unit of work, such as a Spark jar, PySpark script, or SparkSQL query, that you submit to Amazon EMR on EKS. """ def start_job_run(%Client{} = client, virtual_cluster_id, input, options \\ []) do url_path = "/virtualclusters/#{URI.encode(virtual_cluster_id)}/jobruns" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Assigns tags to resources. A tag is a label that you assign to an AWS resource. Each tag consists of a key and an optional value, both of which you define. Tags enable you to categorize your AWS resources by attributes such as purpose, owner, or environment. When you have many resources of the same type, you can quickly identify a specific resource based on the tags you've assigned to it. For example, you can define a set of tags for your Amazon EMR on EKS clusters to help you track each cluster's owner and stack level. We recommend that you devise a consistent set of tag keys for each resource type. You can then search and filter the resources based on the tags that you add. """ def tag_resource(%Client{} = client, resource_arn, input, options \\ []) do url_path = "/tags/#{URI.encode(resource_arn)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Removes tags from resources. """ def untag_resource(%Client{} = client, resource_arn, input, options \\ []) do url_path = "/tags/#{URI.encode(resource_arn)}" headers = [] {query_params, input} = [ {"tagKeys", "tagKeys"} ] |> Request.build_params(input) Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, nil ) end end
lib/aws/generated/emrcontainers.ex
0.879619
0.439567
emrcontainers.ex
starcoder
defmodule Mariaex.RowParser do @moduledoc """ Parse a row of the MySQL protocol This parser makes extensive use of binary pattern matching and recursion to take advantage of Erlang's optimizer that will not create sub binaries when called recusively. """ use Bitwise alias Mariaex.Column alias Mariaex.Messages @unsigned_flag 0x20 def decode_init(columns) do fields = for %Column{type: type, flags: flags} <- columns do Messages.__type__(:type, type) |> type_to_atom(flags) end {fields, div(length(fields) + 7 + 2, 8)} end def decode_bin_rows(row, fields, nullint, datetime, json_library) do decode_bin_rows(row, fields, nullint >>> 2, [], datetime, json_library) end ## Helpers defp type_to_atom({:integer, :field_type_tiny}, flags) when (@unsigned_flag &&& flags) == @unsigned_flag do :uint8 end defp type_to_atom({:integer, :field_type_tiny}, _) do :int8 end defp type_to_atom({:integer, :field_type_short}, flags) when (@unsigned_flag &&& flags) == @unsigned_flag do :uint16 end defp type_to_atom({:integer, :field_type_short}, _) do :int16 end defp type_to_atom({:integer, :field_type_int24}, flags) when (@unsigned_flag &&& flags) == @unsigned_flag do :uint32 end defp type_to_atom({:integer, :field_type_int24}, _) do :int32 end defp type_to_atom({:integer, :field_type_long}, flags) when (@unsigned_flag &&& flags) == @unsigned_flag do :uint32 end defp type_to_atom({:integer, :field_type_long}, _) do :int32 end defp type_to_atom({:integer, :field_type_longlong}, flags) when (@unsigned_flag &&& flags) == @unsigned_flag do :uint64 end defp type_to_atom({:integer, :field_type_longlong}, _) do :int64 end defp type_to_atom({:json, :field_type_json}, _) do :json end defp type_to_atom({:string, _mysql_type}, _), do: :string defp type_to_atom({:integer, :field_type_year}, _), do: :uint16 defp type_to_atom({:time, :field_type_time}, _), do: :time defp type_to_atom({:date, :field_type_date}, _), do: :date defp type_to_atom({:timestamp, :field_type_datetime}, _), do: :datetime defp type_to_atom({:timestamp, :field_type_timestamp}, _), do: :timestamp defp type_to_atom({:decimal, :field_type_newdecimal}, _), do: :decimal defp type_to_atom({:float, :field_type_float}, _), do: :float32 defp type_to_atom({:float, :field_type_double}, _), do: :float64 defp type_to_atom({:bit, :field_type_bit}, _), do: :bit defp type_to_atom({:geometry, :field_type_geometry}, _), do: :geometry defp type_to_atom({:null, :field_type_null}, _), do: nil defp decode_bin_rows(<<rest::bits>>, [_ | fields], nullint, acc, datetime, json_library) when (nullint &&& 1) === 1 do decode_bin_rows(rest, fields, nullint >>> 1, [nil | acc], datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:string | fields], null_bitfield, acc, datetime, json_library) do decode_string(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:uint8 | fields], null_bitfield, acc, datetime, json_library) do decode_uint8(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:int8 | fields], null_bitfield, acc, datetime, json_library) do decode_int8(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:uint16 | fields], null_bitfield, acc, datetime, json_library) do decode_uint16(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:int16 | fields], null_bitfield, acc, datetime, json_library) do decode_int16(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:uint32 | fields], null_bitfield, acc, datetime, json_library) do decode_uint32(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:int32 | fields], null_bitfield, acc, datetime, json_library) do decode_int32(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:uint64 | fields], null_bitfield, acc, datetime, json_library) do decode_uint64(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:int64 | fields], null_bitfield, acc, datetime, json_library) do decode_int64(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:time | fields], null_bitfield, acc, datetime, json_library) do decode_time(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:date | fields], null_bitfield, acc, datetime, json_library) do decode_date(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:datetime | fields], null_bitfield, acc, datetime, json_library) do decode_datetime(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:timestamp | fields], null_bitfield, acc, datetime, json_library) do decode_timestamp(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:decimal | fields], null_bitfield, acc, datetime, json_library) do decode_decimal(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:float32 | fields], null_bitfield, acc, datetime, json_library) do decode_float32(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:float64 | fields], null_bitfield, acc, datetime, json_library) do decode_float64(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:bit | fields], null_bitfield, acc, datetime, json_library) do decode_string(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:json | fields], null_bitfield, acc, datetime, json_library) do decode_json(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:geometry | fields], null_bitfield, acc, datetime, json_library) do decode_geometry(rest, fields, null_bitfield >>> 1, acc, datetime, json_library) end defp decode_bin_rows(<<rest::bits>>, [:nil | fields], null_bitfield, acc, datetime, json_library) do decode_bin_rows(rest, fields, null_bitfield >>> 1, [nil | acc], datetime, json_library) end defp decode_bin_rows(<<>>, [], _, acc, _datetime, _json_library) do Enum.reverse(acc) end defp decode_string(<<len::8, string::size(len)-binary, rest::bits>>, fields, nullint, acc, datetime, json_library) when len <= 250 do decode_bin_rows(rest, fields, nullint, [string | acc], datetime, json_library) end defp decode_string(<<252::8, len::16-little, string::size(len)-binary, rest::bits>>, fields, nullint, acc, datetime, json_library) do decode_bin_rows(rest, fields, nullint, [string | acc], datetime, json_library) end defp decode_string(<<253::8, len::24-little, string::size(len)-binary, rest::bits>>, fields, nullint, acc, datetime, json_library) do decode_bin_rows(rest, fields, nullint, [string | acc], datetime, json_library) end defp decode_string(<<254::8, len::64-little, string::size(len)-binary, rest::bits>>, fields, nullint, acc, datetime, json_library) do decode_bin_rows(rest, fields, nullint, [string | acc], datetime, json_library) end defp decode_float32(<<value::size(32)-float-little, rest::bits>>, fields, null_bitfield, acc, datetime, json_library) do decode_bin_rows(rest, fields, null_bitfield, [value | acc], datetime, json_library) end defp decode_float64(<<value::size(64)-float-little, rest::bits>>, fields, null_bitfield, acc, datetime, json_library) do decode_bin_rows(rest, fields, null_bitfield, [value | acc], datetime, json_library) end defp decode_uint8(<<value::size(8)-little-unsigned, rest::bits>>, fields, null_bitfield, acc, datetime, json_library) do decode_bin_rows(rest, fields, null_bitfield , [value | acc], datetime, json_library) end defp decode_int8(<<value::size(8)-little-signed, rest::bits>>, fields, null_bitfield, acc, datetime, json_library) do decode_bin_rows(rest, fields, null_bitfield , [value | acc], datetime, json_library) end defp decode_uint16(<<value::size(16)-little-unsigned, rest::bits>>, fields, null_bitfield, acc, datetime, json_library) do decode_bin_rows(rest, fields, null_bitfield , [value | acc], datetime, json_library) end defp decode_int16(<<value::size(16)-little-signed, rest::bits>>, fields, null_bitfield, acc, datetime, json_library) do decode_bin_rows(rest, fields, null_bitfield , [value | acc], datetime, json_library) end defp decode_uint32(<<value::size(32)-little-unsigned, rest::bits>>, fields, null_bitfield, acc, datetime, json_library) do decode_bin_rows(rest, fields, null_bitfield , [value | acc], datetime, json_library) end defp decode_int32(<<value::size(32)-little-signed, rest::bits>>, fields, null_bitfield, acc, datetime, json_library) do decode_bin_rows(rest, fields, null_bitfield , [value | acc], datetime, json_library) end defp decode_uint64(<<value::size(64)-little-unsigned, rest::bits>>, fields, null_bitfield, acc, datetime, json_library) do decode_bin_rows(rest, fields, null_bitfield , [value | acc], datetime, json_library) end defp decode_int64(<<value::size(64)-little-signed, rest::bits>>, fields, null_bitfield, acc, datetime, json_library) do decode_bin_rows(rest, fields, null_bitfield , [value | acc], datetime, json_library) end defp decode_decimal(<<length, raw_value::size(length)-little-binary, rest::bits>>, fields, null_bitfield, acc, datetime, json_library) do value = Decimal.new(raw_value) decode_bin_rows(rest, fields, null_bitfield, [value | acc], datetime, json_library) end defp decode_time(<< 0::8-little, rest::bits>>, fields, null_bitfield, acc, :structs, json_library) do time = %Time{hour: 0, minute: 0, second: 0} decode_bin_rows(rest, fields, null_bitfield, [time | acc], :structs, json_library) end defp decode_time(<<8::8-little, _::8-little, _::32-little, hour::8-little, min::8-little, sec::8-little, rest::bits>>, fields, null_bitfield, acc, :structs, json_library) do time = %Time{hour: hour, minute: min, second: sec} decode_bin_rows(rest, fields, null_bitfield, [time | acc], :structs, json_library) end defp decode_time(<< fc00:db20:35b:7399::5, _::32-little, _::8-little, hour::8-little, min::8-little, sec::8-little, msec::32-little, rest::bits >>, fields, null_bitfield, acc, :structs, json_library) do time = %Time{hour: hour, minute: min, second: sec, microsecond: {msec, 6}} decode_bin_rows(rest, fields, null_bitfield, [time | acc], :structs, json_library) end defp decode_time(<< 0::8-little, rest::bits>>, fields, null_bitfield, acc, :tuples, json_library) do decode_bin_rows(rest, fields, null_bitfield, [{0, 0, 0, 0} | acc], :tuples, json_library) end defp decode_time(<<8::8-little, _::8-little, _::32-little, hour::8-little, min::8-little, sec::8-little, rest::bits>>, fields, null_bitfield, acc, :tuples, json_library) do decode_bin_rows(rest, fields, null_bitfield, [{hour, min, sec, 0} | acc], :tuples, json_library) end defp decode_time(<< fc00:db20:35b:7399::5, _::32-little, _::8-little, hour::8-little, min::8-little, sec::8-little, msec::32-little, rest::bits >>, fields, null_bitfield, acc, :tuples, json_library) do decode_bin_rows(rest, fields, null_bitfield, [{hour, min, sec, msec} | acc], :tuples, json_library) end defp decode_date(<< 0::8-little, rest::bits >>, fields, null_bitfield, acc, :structs, json_library) do date = %Date{year: 0, month: 1, day: 1} decode_bin_rows(rest, fields, null_bitfield, [date | acc], :structs, json_library) end defp decode_date(<< 4::8-little, year::16-little, month::8-little, day::8-little, rest::bits >>, fields, null_bitfield, acc, :structs, json_library) do date = %Date{year: year, month: month, day: day} decode_bin_rows(rest, fields, null_bitfield, [date | acc], :structs, json_library) end defp decode_date(<< 0::8-little, rest::bits >>, fields, null_bitfield, acc, :tuples, json_library) do decode_bin_rows(rest, fields, null_bitfield, [{0, 0, 0} | acc], :tuples, json_library) end defp decode_date(<< 4::8-little, year::16-little, month::8-little, day::8-little, rest::bits >>, fields, null_bitfield, acc, :tuples, json_library) do decode_bin_rows(rest, fields, null_bitfield, [{year, month, day} | acc], :tuples, json_library) end defp decode_timestamp(<< 0::8-little, rest::bits >>, fields, null_bitfield, acc, :structs, json_library) do datetime = %DateTime{year: 0, month: 1, day: 1, hour: 0, minute: 0, second: 0, std_offset: 0, time_zone: "Etc/UTC", utc_offset: 0, zone_abbr: "UTC"} decode_bin_rows(rest, fields, null_bitfield, [datetime | acc], :structs, json_library) end defp decode_timestamp(<<4::8-little, year::16-little, month::8-little, day::8-little, rest::bits >>, fields, null_bitfield, acc, :structs, json_library) do datetime = %DateTime{year: year, month: month, day: day, hour: 0, minute: 0, second: 0, std_offset: 0, time_zone: "Etc/UTC", utc_offset: 0, zone_abbr: "UTC"} decode_bin_rows(rest, fields, null_bitfield, [datetime | acc], :structs, json_library) end defp decode_timestamp(<< 7::8-little, year::16-little, month::8-little, day::8-little, hour::8-little, min::8-little, sec::8-little, rest::bits >>, fields, null_bitfield, acc, :structs, json_library) do datetime = %DateTime{year: year, month: month, day: day, hour: hour, minute: min, second: sec, std_offset: 0, time_zone: "Etc/UTC", utc_offset: 0, zone_abbr: "UTC"} decode_bin_rows(rest, fields, null_bitfield, [datetime | acc], :structs, json_library) end defp decode_timestamp(<<11::8-little, year::16-little, month::8-little, day::8-little, hour::8-little, min::8-little, sec::8-little, msec::32-little, rest::bits >>, fields, null_bitfield, acc, :structs, json_library) do datetime = %DateTime{year: year, month: month, day: day, hour: hour, minute: min, second: sec, microsecond: {msec, 6}, std_offset: 0, time_zone: "Etc/UTC", utc_offset: 0, zone_abbr: "UTC"} decode_bin_rows(rest, fields, null_bitfield, [datetime | acc], :structs, json_library) end defp decode_timestamp(<< 0::8-little, rest::bits >>, fields, null_bitfield, acc, :tuples, json_library) do decode_bin_rows(rest, fields, null_bitfield, [{{0, 0, 0}, {0, 0, 0, 0}} | acc], :tuples, json_library) end defp decode_timestamp(<<4::8-little, year::16-little, month::8-little, day::8-little, rest::bits >>, fields, null_bitfield, acc, :tuples, json_library) do decode_bin_rows(rest, fields, null_bitfield, [{{year, month, day}, {0, 0, 0, 0}} | acc], :tuples, json_library) end defp decode_timestamp(<< 7::8-little, year::16-little, month::8-little, day::8-little, hour::8-little, min::8-little, sec::8-little, rest::bits >>, fields, null_bitfield, acc, :tuples, json_library) do decode_bin_rows(rest, fields, null_bitfield, [{{year, month, day}, {hour, min, sec, 0}} | acc], :tuples, json_library) end defp decode_timestamp(<<11::8-little, year::16-little, month::8-little, day::8-little, hour::8-little, min::8-little, sec::8-little, msec::32-little, rest::bits >>, fields, null_bitfield, acc, :tuples, json_library) do decode_bin_rows(rest, fields, null_bitfield, [{{year, month, day}, {hour, min, sec, msec}} | acc], :tuples, json_library) end defp decode_datetime(<< 0::8-little, rest::bits >>, fields, null_bitfield, acc, :structs, json_library) do datetime = %NaiveDateTime{year: 0, month: 1, day: 1, hour: 0, minute: 0, second: 0} decode_bin_rows(rest, fields, null_bitfield, [datetime | acc], :structs, json_library) end defp decode_datetime(<<4::8-little, year::16-little, month::8-little, day::8-little, rest::bits >>, fields, null_bitfield, acc, :structs, json_library) do datetime = %NaiveDateTime{year: year, month: month, day: day, hour: 0, minute: 0, second: 0} decode_bin_rows(rest, fields, null_bitfield, [datetime | acc], :structs, json_library) end defp decode_datetime(<< 7::8-little, year::16-little, month::8-little, day::8-little, hour::8-little, min::8-little, sec::8-little, rest::bits >>, fields, null_bitfield, acc, :structs, json_library) do datetime = %NaiveDateTime{year: year, month: month, day: day, hour: hour, minute: min, second: sec} decode_bin_rows(rest, fields, null_bitfield, [datetime | acc], :structs, json_library) end defp decode_datetime(<<11::8-little, year::16-little, month::8-little, day::8-little, hour::8-little, min::8-little, sec::8-little, msec::32-little, rest::bits >>, fields, null_bitfield, acc, :structs, json_library) do datetime = %NaiveDateTime{year: year, month: month, day: day, hour: hour, minute: min, second: sec, microsecond: {msec, 6}} decode_bin_rows(rest, fields, null_bitfield, [datetime | acc], :structs, json_library) end defp decode_datetime(<< 0::8-little, rest::bits >>, fields, null_bitfield, acc, :tuples, json_library) do decode_bin_rows(rest, fields, null_bitfield, [{{0, 0, 0}, {0, 0, 0, 0}} | acc], :tuples, json_library) end defp decode_datetime(<<4::8-little, year::16-little, month::8-little, day::8-little, rest::bits >>, fields, null_bitfield, acc, :tuples, json_library) do decode_bin_rows(rest, fields, null_bitfield, [{{year, month, day}, {0, 0, 0, 0}} | acc], :tuples, json_library) end defp decode_datetime(<< 7::8-little, year::16-little, month::8-little, day::8-little, hour::8-little, min::8-little, sec::8-little, rest::bits >>, fields, null_bitfield, acc, :tuples, json_library) do decode_bin_rows(rest, fields, null_bitfield, [{{year, month, day}, {hour, min, sec, 0}} | acc], :tuples, json_library) end defp decode_datetime(<<11::8-little, year::16-little, month::8-little, day::8-little, hour::8-little, min::8-little, sec::8-little, msec::32-little, rest::bits >>, fields, null_bitfield, acc, :tuples, json_library) do decode_bin_rows(rest, fields, null_bitfield, [{{year, month, day}, {hour, min, sec, msec}} | acc], :tuples, json_library) end defp decode_json(<< len::8, string::size(len)-binary, rest::bits >>, fields, nullint, acc, datetime, json_library) when len <= 250 do json = json_library.decode!(string) decode_bin_rows(rest, fields, nullint, [json | acc], datetime, json_library) end defp decode_json(<< fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, len::16-little, string::size(len)-binary, rest::bits >>, fields, nullint, acc, datetime, json_library) do json = json_library.decode!(string) decode_bin_rows(rest, fields, nullint, [json | acc], datetime, json_library) end defp decode_json(<< fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b, len::24-little, string::size(len)-binary, rest::bits >>, fields, nullint, acc, datetime, json_library) do json = json_library.decode!(string) decode_bin_rows(rest, fields, nullint, [json | acc], datetime, json_library) end defp decode_json(<< fc00:db20:35b:7399::5, len::64-little, string::size(len)-binary, rest::bits >>, fields, nullint, acc, datetime, json_library) do json = json_library.decode!(string) decode_bin_rows(rest, fields, nullint, [json | acc], datetime, json_library) end defp decode_geometry(<<25::8-little, srid::32-little, 1::8-little, 1::32-little, x::little-float-64, y::little-float-64, rest::bits >>, fields, null_bitfield, acc, datetime, json_library) do decode_bin_rows(rest, fields, null_bitfield, [%Mariaex.Geometry.Point{srid: srid, coordinates: {x, y}} | acc], datetime, json_library) end defp decode_geometry(<<_len::8-little, srid::32-little, 1::8-little, 2::32-little, num_points::32-little, points::binary-size(num_points)-unit(128), rest::bits >>, fields, null_bitfield, acc, datetime, json_library) do coordinates = decode_points(points) decode_bin_rows(rest, fields, null_bitfield, [%Mariaex.Geometry.LineString{srid: srid, coordinates: coordinates} | acc], datetime, json_library) end defp decode_geometry(<<_len::8-little, srid::32-little, 1::8-little, 3::32-little, num_rings::32-little, rest::bits >>, fields, null_bitfield, acc, datetime, json_library) do decode_rings(rest, num_rings, {srid, fields, null_bitfield, acc}, datetime, json_library) end ### GEOMETRY HELPERS defp decode_rings(<< rings_and_rows::bits >>, num_rings, state, datetime, json_library) do decode_rings(rings_and_rows, num_rings, state, [], datetime, json_library) end defp decode_rings(<< rest::bits >>, 0, {srid, fields, null_bitfield, acc}, rings, datetime, json_library) do decode_bin_rows(rest, fields, null_bitfield, [%Mariaex.Geometry.Polygon{coordinates: Enum.reverse(rings), srid: srid} | acc], datetime, json_library) end defp decode_rings(<< num_points::32-little, points::binary-size(num_points)-unit(128), rest::bits >>, num_rings, state, rings, datetime, json_library) do points = decode_points(points) decode_rings(rest, num_rings - 1, state, [points | rings], datetime, json_library) end defp decode_points(points_binary, points \\ []) defp decode_points(<< x::little-float-64, y::little-float-64, rest::bits >>, points) do decode_points(rest, [{x, y} | points]) end defp decode_points(<<>>, points), do: Enum.reverse(points) ### TEXT ROW PARSER def decode_text_init(columns) do for %Column{type: type, flags: flags} <- columns do Messages.__type__(:type, type) |> type_to_atom(flags) end end def decode_text_rows(binary, fields, datetime, json_library) do decode_text_part(binary, fields, [], datetime, json_library) end ### IMPLEMENTATION defp decode_text_part(<<len::8, string::size(len)-binary, rest::bits>>, fields, acc, datetime, json_library) when len <= 250 do decode_text_rows(string, rest, fields, acc, datetime, json_library) end defp decode_text_part(<<fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b, len::16-little, string::size(len)-binary, rest::bits>>, fields, acc, datetime, json_library) do decode_text_rows(string, rest, fields, acc, datetime, json_library) end defp decode_text_part(<<2fc00:db20:35b:7399::5, len::24-little, string::size(len)-binary, rest::bits>>, fields, acc, datetime, json_library) do decode_text_rows(string, rest, fields, acc, datetime, json_library) end defp decode_text_part(<<2fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b, len::64-little, string::size(len)-binary, rest::bits>>, fields, acc, datetime, json_library) do decode_text_rows(string, rest, fields, acc, datetime, json_library) end defp decode_text_part(<<>>, [], acc, _datetime, _json_library) do Enum.reverse(acc) end defp decode_text_rows(string, rest, [:string | fields], acc, datetime, json_library) do decode_text_part(rest, fields, [string | acc], datetime, json_library) end defp decode_text_rows(string, rest, [type | fields], acc, datetime, json_library) when type in [:uint8, :int8, :uint16, :int16, :uint32, :int32, :uint64, :int64] do decode_text_part(rest, fields, [:erlang.binary_to_integer(string) | acc], datetime, json_library) end defp decode_text_rows(string, rest, [type | fields], acc, datetime, json_library) when type in [:float32, :float64, :decimal] do decode_text_part(rest, fields, [:erlang.binary_to_float(string) | acc], datetime, json_library) end defp decode_text_rows(string, rest, [:bit | fields], acc, datetime, json_library) do decode_text_part(rest, fields, [string | acc], datetime, json_library) end defp decode_text_rows(string, rest, [:time | fields], acc, datetime, json_library) do decode_text_time(string, rest, fields, acc, datetime, json_library) end defp decode_text_rows(string, rest, [:date | fields], acc, datetime, json_library) do decode_text_date(string, rest, fields, acc, datetime, json_library) end defp decode_text_rows(string, rest, [:datetime | fields], acc, datetime, json_library) do decode_text_datetime(string, rest, fields, acc, datetime, json_library) end defp decode_text_rows(string, rest, [:timestamp | fields], acc, datetime, json_library) do decode_text_timestamp(string, rest, fields, acc, datetime, json_library) end defp decode_text_rows(string, rest, [:json | fields], acc, datetime, json_library) do decode_text_json(string, rest, fields, acc, datetime, json_library) end defmacrop to_int(value) do quote do: :erlang.binary_to_integer(unquote(value)) end defp decode_text_date(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes>>, rest, fields, acc, :structs, json_library) do date = %Date{year: to_int(year), month: to_int(month), day: to_int(day)} decode_text_part(rest, fields, [date | acc], :structs, json_library) end defp decode_text_date(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes>>, rest, fields, acc, :tuples, json_library) do decode_text_part(rest, fields, [{to_int(year), to_int(month), to_int(day)} | acc], :tuples, json_library) end defp decode_text_time(<<hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes>>, rest, fields, acc, :structs, json_library) do time = %Time{hour: to_int(hour), minute: to_int(min), second: to_int(sec)} decode_text_part(rest, fields, [time | acc], :structs, json_library) end defp decode_text_time(<<hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes>>, rest, fields, acc, :tuples, json_library) do decode_text_part(rest, fields, [{to_int(hour), to_int(min), to_int(sec), 0} | acc], :tuples, json_library) end defp decode_text_timestamp(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes, _::8-little, hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes>>, rest, fields, acc, :structs, json_library) do datetime = %DateTime{year: to_int(year), month: to_int(month), day: to_int(day), hour: to_int(hour), minute: to_int(min), second: to_int(sec), std_offset: 0, time_zone: "Etc/UTC", utc_offset: 0, zone_abbr: "UTC"} decode_text_part(rest, fields, [datetime | acc], :structs, json_library) end defp decode_text_timestamp(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes, _::8-little, hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes>>, rest, fields, acc, :tuples, json_library) do decode_text_part(rest, fields, [{{to_int(year), to_int(month), to_int(day)}, {to_int(hour), to_int(min), to_int(sec), 0}} | acc], :tuples, json_library) end defp decode_text_datetime(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes, _::8-little, hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes>>, rest, fields, acc, :structs, json_library) do datetime = %NaiveDateTime{year: to_int(year), month: to_int(month), day: to_int(day), hour: to_int(hour), minute: to_int(min), second: to_int(sec)} decode_text_part(rest, fields, [datetime | acc], :structs, json_library) end defp decode_text_datetime(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes, _::8-little, hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes>>, rest, fields, acc, :tuples, json_library) do decode_text_part(rest, fields, [{{to_int(year), to_int(month), to_int(day)}, {to_int(hour), to_int(min), to_int(sec), 0}} | acc], :tuples, json_library) end defp decode_text_json(string, rest, fields, acc, datetime, json_library) do json = json_library.decode!(string) decode_text_part(rest, fields, [json | acc], datetime, json_library) end end
lib/mariaex/row_parser.ex
0.583915
0.474996
row_parser.ex
starcoder
defmodule Rolodex.Schema do @moduledoc """ Exposes functions and macros for defining reusable parameter schemas. It includes two macros. Used together, you can setup a reusable schema: - `schema/3` - for declaring a schema - `field/3` - for declaring schema fields It also exposes the following functions: - `is_schema_module?/1` - determines if the provided item is a module that has defined a reuseable schema - `to_map/1` - serializes a schema module into a map for use by a `Rolodex.Processor` behaviour - `get_refs/1` - traverses a schema and searches for any nested schemas within """ alias Rolodex.{DSL, Field} defmacro __using__(_opts) do quote do use Rolodex.DSL import Rolodex.Schema end end @doc """ Opens up the schema definition for the current module. Will name the schema and generate metadata for the schema based on subsequent calls to `field/3` **Accepts** - `name` - the schema name - `opts` - a keyword list of options (currently, only looks for a `desc` key) - `block` - the inner schema definition with one or more calls to `field/3` ## Example defmodule MySchema do use Rolodex.Schema schema "MySchema", desc: "Example schema" do # Atomic field with no description field :id, :uuid # Atomic field with a description field :name, :string, desc: "The object's name" # A field that refers to another, nested object field :other, OtherSchema # A field that is an array of items of one-or-more types field :multi, :list, of: [:string, OtherSchema] # A field that is one of the possible provided types field :any, :one_of, of: [:string, OtherSchema] # Treats OtherSchema as a partial to be merged into this schema partial OtherSchema end end """ defmacro schema(name, opts \\ [], do: block) do schema_body_ast = DSL.set_schema(:__schema__, do: block) quote do unquote(schema_body_ast) def __schema__(:name), do: unquote(name) def __schema__(:desc), do: unquote(Keyword.get(opts, :desc, nil)) end end @doc """ Adds a new field to the schema. See `Rolodex.Field` for more information about valid field metadata. Accepts - `identifier` - field name - `type` - either an atom or another Rolodex.Schema module - `opts` - a keyword list of options, looks for `desc` and `of` (for array types) ## Example defmodule MySchema do use Rolodex.Schema schema "MySchema", desc: "Example schema" do # Atomic field with no description field :id, :uuid # Atomic field with a description field :name, :string, desc: "The object's name" # A field that refers to another, nested object field :other, OtherSchema # A field that is an array of items of one-or-more types field :multi, :list, of: [:string, OtherSchema] # You can use a shorthand to define a list field, the below is identical # to the above field :multi, [:string, OtherSchema] # A field that is one of the possible provided types field :any, :one_of, of: [:string, OtherSchema] end end """ defmacro field(identifier, type, opts \\ []) do DSL.set_field(:fields, identifier, type, opts) end @doc """ Adds a new partial to the schema. A partial is another schema that will be serialized and merged into the top-level properties map for the current schema. Partials are useful for shared parameters used across multiple schemas. Bare keyword lists and maps that are parseable by `Rolodex.Field` are also supported. ## Example defmodule AgeSchema do use Rolodex.Schema schema "AgeSchema" do field :age, :integer field :date_of_birth, :datetime field :city_of_birth, :string end end defmodule MySchema do use Rolodex.Schema schema "MySchema" do field :id, :uuid field :name, :string # A partial via another schema partial AgeSchema # A partial via a bare keyword list partial [ city: :string, state: :string, country: :string ] end end # MySchema will be serialized by `to_map/1` as: %{ type: :object, desc: nil, properties: %{ id: %{type: :uuid}, name: %{type: :string}, # From the AgeSchema partial age: %{type: :integer}, date_of_birth: %{type: :datetime} city_of_birth: %{type: :string}, # From the keyword list partial city: %{type: :string}, state: %{type: :string}, country: %{type: :string} } } """ defmacro partial(mod), do: DSL.set_partial(mod) @doc """ Determines if an arbitrary item is a module that has defined a reusable schema via `Rolodex.Schema` macros ## Example iex> defmodule SimpleSchema do ...> use Rolodex.Schema ...> schema "SimpleSchema", desc: "Demo schema" do ...> field :id, :uuid ...> end ...> end iex> iex> # Validating a schema module iex> Rolodex.Schema.is_schema_module?(SimpleSchema) true iex> # Validating some other module iex> Rolodex.Schema.is_schema_module?(OtherModule) false """ @spec is_schema_module?(any()) :: boolean() def is_schema_module?(mod), do: DSL.is_module_of_type?(mod, :__schema__) @doc """ Serializes the `Rolodex.Schema` metadata into a formatted map. ## Example iex> defmodule OtherSchema do ...> use Rolodex.Schema ...> ...> schema "OtherSchema" do ...> field :id, :uuid ...> end ...> end iex> iex> defmodule MySchema do ...> use Rolodex.Schema ...> ...> schema "MySchema", desc: "An example" do ...> # Atomic field with no description ...> field :id, :uuid ...> ...> # Atomic field with a description ...> field :name, :string, desc: "The schema's name" ...> ...> # A field that refers to another, nested object ...> field :other, OtherSchema ...> ...> # A field that is an array of items of one-or-more types ...> field :multi, :list, of: [:string, OtherSchema] ...> ...> # A field that is one of the possible provided types ...> field :any, :one_of, of: [:string, OtherSchema] ...> end ...> end iex> iex> Rolodex.Schema.to_map(MySchema) %{ type: :object, desc: "An example", properties: %{ id: %{type: :uuid}, name: %{desc: "The schema's name", type: :string}, other: %{type: :ref, ref: Rolodex.SchemaTest.OtherSchema}, multi: %{ type: :list, of: [ %{type: :string}, %{type: :ref, ref: Rolodex.SchemaTest.OtherSchema} ] }, any: %{ type: :one_of, of: [ %{type: :string}, %{type: :ref, ref: Rolodex.SchemaTest.OtherSchema} ] } } } """ @spec to_map(module()) :: map() def to_map(mod) do mod.__schema__({nil, :schema}) |> Map.put(:desc, mod.__schema__(:desc)) end @doc """ Traverses a serialized Schema and collects any nested references to other Schemas within. See `Rolodex.Field.get_refs/1` for more info. """ @spec get_refs(module()) :: [module()] def get_refs(mod) do mod |> to_map() |> Field.get_refs() end end
lib/rolodex/schema.ex
0.886917
0.66266
schema.ex
starcoder
defmodule Cldr.Interval do @moduledoc """ Interval formats allow for software to format intervals like "Jan 10-12, 2008" as a shorter and more natural format than "Jan 10, 2008 - Jan 12, 2008". They are designed to take a start and end date, time or datetime plus a formatting pattern and use that information to produce a localized format. The interval functions in the library will determine the calendar field with the greatest difference between the two datetimes before using the format pattern. For example, the greatest difference in "Jan 10-12, 2008" is the day field, while the greatest difference in "Jan 10 - Feb 12, 2008" is the month field. This is used to pick the exact pattern to be used. ### Interval Format Styles CLDR provides a set of format types that map to a concrete format string. To simplify the developer experience, `ex_cldr_dates_times` groups these formats into `styles` and `format types`. Format styles group different CLDR formats into similar types. These format styles can be seen by examing the output below: ```elixir iex> Cldr.Date.Interval.styles %{ date: %{long: :y_mmm_ed, medium: :y_mm_md, short: :y_md}, month: %{long: :mmm, medium: :mmm, short: :m}, month_and_day: %{long: :mmm_ed, medium: :mm_md, short: :md}, year_and_month: %{long: :y_mmmm, medium: :y_mmm, short: :y_m} } iex> Cldr.Time.Interval.styles %{ flex: %{long: :bhm, medium: :bhm, short: :bh}, time: %{long: :hm, medium: :hm, short: :h}, zone: %{long: :hmv, medium: :hmv, short: :hv} } ``` Here the format style is the key if the map: `:date`, `:month`, `:month_and_day` and `year_and_month`. These are then mapped to interval formats. ### Interval formats In a manner similar to formatting individual dates, times and datetimes, format types are introduced to simplify common usage. For all intervals the following format types are; * `:short` * `:medium` (the default) * `:long` In each case, the mapping is from a style to a format type and then ot resolves to a native CLDR format map. These maps can be examined as follows where `"en"` is any configured locale name and `:gregorian` is the underlying CLDR calendar type. In common use the `:gregorian` calendar is the standard. However other calendar types are also supported. For example: ```elixir iex> Cldr.known_calendars [:buddhist, :chinese, :coptic, :dangi, :ethiopic, :ethiopic_amete_alem, :gregorian, :hebrew, :indian, :islamic, :islamic_civil, :islamic_rgsa, :islamic_tbla, :islamic_umalqura, :japanese, :persian, :roc] ``` To examine the available interval formats, `Cldr.DateTime.Format.interval_formats/2` can be used although its use is primarily internal to the implementation of `to_string/3` and would not normally be called directly. ```elixir Cldr.DateTime.Format.interval_formats "en", :gregorian => {:ok, %{ ... h: %{h: ["HH – ", "HH"]}, hm: %{h: ["HH:mm – ", "HH:mm"], m: ["HH:mm – ", "HH:mm"]}, hmv: %{h: ["HH:mm – ", "HH:mm v"], m: ["HH:mm – ", "HH:mm v"]}, hv: %{a: ["h a – ", "h a v"], h: ["h – ", "h a v"]}, m: %{m: ["M – ", "M"]}, m_ed: %{d: ["E, M/d – ", "E, M/d"], m: ["E, M/d – ", "E, M/d"]}, md: %{d: ["M/d – ", "M/d"], m: ["M/d – ", "M/d"]}, mm_md: %{d: ["MMM d – ", "d"], m: ["MMM d – ", "MMM d"]}, mmm: %{m: ["MMM – ", "MMM"]}, mmm_ed: %{d: ["E, MMM d – ", "E, MMM d"], m: ["E, MMM d – ", "E, MMM d"]}, y: %{y: ["y – ", "y"]}, y_m: %{m: ["M/y – ", "M/y"], y: ["M/y – ", "M/y"]}, y_m_ed: %{ d: ["E, M/d/y – ", "E, M/d/y"], m: ["E, M/d/y – ", "E, M/d/y"], y: ["E, M/d/y – ", "E, M/d/y"] }, y_md: %{ d: ["M/d/y – ", "M/d/y"], m: ["M/d/y – ", "M/d/y"], y: ["M/d/y – ", "M/d/y"] }, y_mm_md: %{ d: ["MMM d – ", "d, y"], m: ["MMM d – ", "MMM d, y"], y: ["MMM d, y – ", "MMM d, y"] }, ... } } ``` At this point we can see that the path to resolving a format is: * Apply the format style. For dates, this is `:date` * Apply the format type. For dates, the default is `:medium` This will then return a map such as: ```elixir %{ d: ["MMM d – ", "d, y"], m: ["MMM d – ", "MMM d, y"], y: ["MMM d, y – ", "MMM d, y"] } ``` ### The field with the greatest difference There remains one more choice to make - and that choice is made based upon the highest order date field that is different between the `from` and `to` dates. With two dates `2020-02-02` and `2021-01-01` the highest order difference is `:year`. With `2020-02-02` and `2020-01-01` it is `:month`. ### Formatting the interval Using this `greatest difference` information we can now resolve the final format. With the `:year` field being the greatest difference then the format is `y: ["MMM d, y – ", "MMM d, y"]`. Finally, formatting can proceed for the `from` date being formatted with `"MMM d, y – "` and the `to` date being formatted with `"MMM d, y"` and the two results then being concatenated to form the final string. ### Other ways to specify an interval format So far we have considered formats that a resolved from standard styles and format types. This is the typical usage and they are specified as paramters to the `to_string/3` function. For example: ```elixir iex> Cldr.Date.Interval.to_string ~D[2020-01-01], ~D[2020-01-12], MyApp.Cldr {:ok, "Jan 1 – 12, 2020"} iex> Cldr.Date.Interval.to_string ~D[2020-01-01], ~D[2020-01-12], MyApp.Cldr, format: :long {:ok, "Wed, Jan 1 – Sun, Jan 12, 2020"} iex> Cldr.Date.Interval.to_string ~D[2020-01-01], ~D[2020-01-12], MyApp.Cldr, ...> style: :month_and_day {:ok, "Jan 1 – 12"} ``` ### Direct use of CLDR format types It is also possible to directly specify the CLDR format type. For example: ```elixir iex> Cldr.Date.Interval.to_string ~D[2020-01-01], ~D[2020-01-12], MyApp.Cldr, format: :gy_mm_md {:ok, "Jan 1 – 12, 2020 AD"} ``` ### Using format strings In the unusual situation where one of the standard format styles and types does not meet requirements, a format string can also be specified. For example: ```elixir iex> Cldr.Date.Interval.to_string ~D[2020-01-01], ~D[2020-01-12], MyApp.Cldr, ...> format: "E, M/d/y – E, M/d/y" {:ok, "Wed, 1/1/2020 – Sun, 1/12/2020"} ``` In this case, the steps to formatting are: 1. Split the format string at the point at which the first repeating formating code is detected. In the pattern above it is where the second `E` is detected. The result in this case will be `["E, M/d/y – ", "E, M/d/y"]` For the purposes of splitting, duplicate are ignored. Therefore "EEE, M/d/y – E, M/d/y" will split into `["EEE, M/d/y – ", "E, M/d/y"]`. 2. Each part of the pattern is parsed 3. The two dates, times or datetimes are formatted This is a more expensive operation than using the predefined styles and format types since the underlying formats for these types are precompiled into an efficient runtime format. ### Configuring precompiled interval formats If there is a requirement for repeated use of format strings then they can be configured in the backend module so that they are precompiled and therefore not suffer a runtime performance penaly. In a backend module, configure the required formats as a list under the `:precompile_interval_formats` key: ```elixir defmodule MyApp.Cldr do use Cldr, locales: ["en", "fr"], default_locale: "en", precompile_interval_formats: ["E, MMM d/y – d/y"] end ``` """ @typedoc "A Date.Range or CalendarInterval range" if Cldr.Code.ensure_compiled?(CalendarInterval) do @type range :: Date.Range.t() | CalendarInterval.t() else @type range :: Date.Range.t() end @typedoc "Any date, time or datetime" @type datetime :: Calendar.date() | Calendar.datetime() | Calendar.naive_datetime() | Calendar.time() import Cldr.Calendar, only: [ date: 0, datetime: 0, time: 0 ] import Kernel, except: [ to_string: 1 ] # Single argument version. # Derive backend and locale @doc false def to_string(%Date.Range{} = range) do {locale, backend} = Cldr.locale_and_backend_from(nil, nil) to_string(range, backend, locale: locale) end if Cldr.Code.ensure_compiled?(CalendarInterval) do def to_string(%CalendarInterval{} = interval) do {locale, backend} = Cldr.locale_and_backend_from(nil, nil) to_string(interval, backend, locale: locale) end end @doc false def to_string(unquote(date()) = from, unquote(date()) = to) do {locale, backend} = Cldr.locale_and_backend_from(nil, nil) to_string(from, to, backend, locale: locale) end def to_string(unquote(time()) = from, unquote(time()) = to) do {locale, backend} = Cldr.locale_and_backend_from(nil, nil) to_string(from, to, backend, locale: locale) end # Dual argument version with backend def to_string(%Date.Range{} = range, backend) when is_atom(backend) do {locale, backend} = Cldr.locale_and_backend_from(nil, backend) to_string(range, backend, locale: locale) end if Cldr.Code.ensure_compiled?(CalendarInterval) do def to_string(%CalendarInterval{} = interval, backend) when is_atom(backend) do {locale, backend} = Cldr.locale_and_backend_from(nil, backend) to_string(interval, backend, locale: locale) end end @doc false def to_string(unquote(date()) = from, unquote(date()) = to, backend) when is_atom(backend) do {locale, backend} = Cldr.locale_and_backend_from(nil, backend) to_string(from, to, backend, locale: locale) end def to_string(unquote(time()) = from, unquote(time()) = to, backend) when is_atom(backend) do {locale, backend} = Cldr.locale_and_backend_from(nil, backend) to_string(from, to, backend, locale: locale) end # Dual argument version with options def to_string(%Date.Range{} = range, options) when is_list(options) do {locale, backend} = Cldr.locale_and_backend_from(options) to_string(range, backend, locale: Keyword.put_new(options, :locale, locale)) end if Cldr.Code.ensure_compiled?(CalendarInterval) do def to_string(%CalendarInterval{} = interval, options) when is_list(options) do {locale, backend} = Cldr.locale_and_backend_from(options) to_string(interval, backend, Keyword.put_new(options, :locale, locale)) end end def to_string(unquote(date()) = from, unquote(date()) = to, options) when is_list(options) do {locale, backend} = Cldr.locale_and_backend_from(options) options = Keyword.put_new(options, :locale, locale) to_string(from, to, backend, options) end def to_string(unquote(time()) = from, unquote(time()) = to, options) when is_list(options) do {locale, backend} = Cldr.locale_and_backend_from(options) options = Keyword.put_new(options, :locale, locale) to_string(from, to, backend, options) end @doc """ Returns a `Date.Range` or `CalendarInterval` as a localised string. ## Arguments * `range` is either a `Date.Range.t` returned from `Date.range/2` or a `CalendarInterval.t`. * `backend` is any module that includes `use Cldr` and is therefore a `Cldr` backend module * `options` is a keyword list of options. The default is `[]`. ## Options * `:format` is one of `:short`, `:medium` or `:long` or a specific format type or a string representing of an interval format. The default is `:medium`. * `:style` supports dfferent formatting styles. The valid styles depends on whether formatting is for a date, time or datetime. Since the functions in this module will make a determination as to which formatter to be used based upon the data passed to them it is recommended the style option be ommitted. If styling is important then call `to_string/3` directly on `Cldr.Date.Interval`, `Cldr.Time.Interval` or `Cldr.DateTime.Interval`. * For a date the alternatives are `:date`, `:month_and_day`, `:month` and `:year_and_month`. The default is `:date`. * For a time the alternatives are `:time`, `:zone` and `:flex`. The default is `:time` * For a datetime there are no style options, the default for each of the date and time part is used * `locale` is any valid locale name returned by `Cldr.known_locale_names/0` or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0` * `number_system:` a number system into which the formatted date digits should be transliterated ## Returns * `{:ok, string}` or * `{:error, {exception, reason}}` ## Notes * `to_string/3` will decide which formatter to call based upon the aguments provided to it. * A `Date.Range.t` will call `Cldr.Date.Interval.to_string/3` * A `CalendarInterval` will call `Cldr.Date.Interval.to_string/3` if its `:precision` is `:year`, `:month` or `:day`. Othersie it will call `Cldr.Time.Interval.to_string/3` * If `from` and `to` both conform to the `Calendar.datetime()` type then `Cldr.DateTime.Interval.to_string/3` is called * Otherwise if `from` and `to` conform to the `Calendar.date()` type then `Cldr.Date.Interval.to_string/3` is called * Otherwise if `from` and `to` conform to the `Calendar.time()` type then `Cldr.Time.Interval.to_string/3` is called * `CalendarInterval` support requires adding the dependency [calendar_interval](https://hex.pm/packages/calendar_interval) to the `deps` configuration in `mix.exs`. * For more information on interval format string see `Cldr.Interval`. * The available predefined formats that can be applied are the keys of the map returned by `Cldr.DateTime.Format.interval_formats("en", :gregorian)` where `"en"` can be replaced by any configuration locale name and `:gregorian` is the underlying `CLDR` calendar type. * In the case where `from` and `to` are equal, a single date, time or datetime is formatted instead of an interval ## Examples iex> Cldr.Interval.to_string Date.range(~D[2020-01-01], ~D[2020-01-12]), MyApp.Cldr, ...> format: :long {:ok, "Wed, Jan 1 – Sun, Jan 12, 2020"} iex> use CalendarInterval iex> Cldr.Interval.to_string ~I"2020-01-01/12", MyApp.Cldr, ...> format: :long {:ok, "Wed, Jan 1 – Sun, Jan 12, 2020"} """ @spec to_string(range, Cldr.backend(), Keyword.t) :: {:ok, String.t} | {:error, {module, String.t}} def to_string(%Date.Range{first: first, last: last}, backend, options) do Cldr.Date.Interval.to_string(first, last, backend, options) end if Cldr.Code.ensure_compiled?(CalendarInterval) do def to_string(%CalendarInterval{first: from, last: to, precision: precision}, backend, options) when precision in [:year, :month, :day] do Cldr.Date.Interval.to_string(from, to, backend, options) end def to_string(%CalendarInterval{first: from, last: to, precision: precision}, backend, options) when precision in [:hour, :minute] do from = %{from | second: 0, microsecond: {0, 6}} to = %{to | second: 0, microsecond: {0, 6}} Cldr.DateTime.Interval.to_string(from, to, backend, options) end def to_string(%CalendarInterval{first: from, last: to, precision: precision}, backend, options) when precision in [:second, :microsecond] do from = %{from | microsecond: {0, 6}} to = %{to | microsecond: {0, 6}} Cldr.DateTime.Interval.to_string(from, to, backend, options) end end @doc false def to_string(from, to, backend, options \\ []) @doc """ Returns a string representing the formatted interval formed by two dates. ## Arguments * `from` is any map that conforms to the any one of the `Calendar` types. * `to` is any map that conforms to the any one of the `Calendar` types. `to` must occur on or after `from`. * `backend` is any module that includes `use Cldr` and is therefore a `Cldr` backend module * `options` is a keyword list of options. The default is `[]`. ## Options * `:format` is one of `:short`, `:medium` or `:long` or a specific format type or a string representing of an interval format. The default is `:medium`. * `:style` supports dfferent formatting styles. The valid styles depends on whether formatting is for a date, time or datetime. Since the functions in this module will make a determination as to which formatter to be used based upon the data passed to them it is recommended the style option be ommitted. If styling is important then call `to_string/3` directly on `Cldr.Date.Interval`, `Cldr.Time.Interval` or `Cldr.DateTime.Interval`. * For a date the alternatives are `:date`, `:month_and_day`, `:month` and `:year_and_month`. The default is `:date`. * For a time the alternatives are `:time`, `:zone` and `:flex`. The default is `:time` * For a datetime there are no style options, the default for each of the date and time part is used * `locale` is any valid locale name returned by `Cldr.known_locale_names/0` or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0` * `number_system:` a number system into which the formatted date digits should be transliterated ## Returns * `{:ok, string}` or * `{:error, {exception, reason}}` ## Notes * `to_string/3` will decide which formatter to call based upon the aguments provided to it. * A `Date.Range.t` will call `Cldr.Date.Interval.to_string/3` * A `CalendarInterval` will call `Cldr.Date.Interval.to_string/3` if its `:precision` is `:year`, `:month` or `:day`. Othersie it will call `Cldr.Time.Interval.to_string/3` * If `from` and `to` both conform to the `Calendar.datetime()` type then `Cldr.DateTime.Interval.to_string/3` is called * Otherwise if `from` and `to` conform to the `Calendar.date()` type then `Cldr.Date.Interval.to_string/3` is called * Otherwise if `from` and `to` conform to the `Calendar.time()` type then `Cldr.Time.Interval.to_string/3` is called * `CalendarInterval` support requires adding the dependency [calendar_interval](https://hex.pm/packages/calendar_interval) to the `deps` configuration in `mix.exs`. * For more information on interval format string see `Cldr.Interval`. * The available predefined formats that can be applied are the keys of the map returned by `Cldr.DateTime.Format.interval_formats("en", :gregorian)` where `"en"` can be replaced by any configuration locale name and `:gregorian` is the underlying `CLDR` calendar type. * In the case where `from` and `to` are equal, a single date, time or datetime is formatted instead of an interval ## Examples iex> Cldr.Interval.to_string ~D[2020-01-01], ~D[2020-12-31], MyApp.Cldr {:ok, "Jan 1 – Dec 31, 2020"} iex> Cldr.Interval.to_string ~D[2020-01-01], ~D[2020-01-12], MyApp.Cldr {:ok, "Jan 1 – 12, 2020"} iex> Cldr.Interval.to_string ~D[2020-01-01], ~D[2020-01-12], MyApp.Cldr, ...> format: :long {:ok, "Wed, Jan 1 – Sun, Jan 12, 2020"} iex> Cldr.Interval.to_string ~D[2020-01-01], ~D[2020-12-01], MyApp.Cldr, ...> format: :long, style: :year_and_month {:ok, "January – December 2020"} iex> Cldr.Interval.to_string ~U[2020-01-01 00:00:00.0Z], ~U[2020-12-01 10:05:00.0Z], MyApp.Cldr, ...> format: :long {:ok, "January 1, 2020 at 12:00:00 AM UTC – December 1, 2020 at 10:05:00 AM UTC"} iex> Cldr.Interval.to_string ~U[2020-01-01 00:00:00.0Z], ~U[2020-01-01 10:05:00.0Z], MyApp.Cldr, ...> format: :long {:ok, "January 1, 2020 at 12:00:00 AM UTC – 10:05:00 AM UTC"} """ @spec to_string(datetime, datetime, Cldr.backend(), Keyword.t) :: {:ok, String.t} | {:error, {module, String.t}} def to_string(unquote(datetime()) = from, unquote(datetime()) = to, backend, options) do Cldr.DateTime.Interval.to_string(from, to, backend, options) end def to_string(unquote(date()) = from, unquote(date()) = to, backend, options) do Cldr.Date.Interval.to_string(from, to, backend, options) end def to_string(unquote(time()) = from, unquote(time()) = to, backend, options) do Cldr.Time.Interval.to_string(from, to, backend, options) end @doc false def to_string!(%Date.Range{} = range, backend) when is_atom(backend) do {locale, backend} = Cldr.locale_and_backend_from(nil, backend) to_string!(range, backend, locale: locale) end @doc false def to_string!(%Date.Range{} = range, options) when is_list(options) do {locale, backend} = Cldr.locale_and_backend_from(options) options = Keyword.put_new(options, :locale, locale) to_string!(range, backend, options) end if Cldr.Code.ensure_compiled?(CalendarInterval) do @doc false def to_string!(%CalendarInterval{} = range, backend) when is_atom(backend) do {locale, backend} = Cldr.locale_and_backend_from(nil, backend) to_string!(range, backend, locale: locale) end @doc false def to_string!(%CalendarInterval{} = range, options) when is_list(options) do {locale, backend} = Cldr.locale_and_backend_from(options) options = Keyword.put_new(options, :locale, locale) to_string!(range, backend, options) end end @doc """ Returns a `Date.Range` or `CalendarInterval` as a localised string or raises an exception. ## Arguments * `range` is either a `Date.Range.t` returned from `Date.range/2` or a `CalendarInterval.t`. * `backend` is any module that includes `use Cldr` and is therefore a `Cldr` backend module. * `options` is a keyword list of options. The default is `[]`. ## Options * `:format` is one of `:short`, `:medium` or `:long` or a specific format type or a string representing of an interval format. The default is `:medium`. * `:style` supports dfferent formatting styles. The valid styles depends on whether formatting is for a date, time or datetime. Since the functions in this module will make a determination as to which formatter to be used based upon the data passed to them it is recommended the style option be ommitted. If styling is important then call `to_string/3` directly on `Cldr.Date.Interval`, `Cldr.Time.Interval` or `Cldr.DateTime.Interval`. * For a date the alternatives are `:date`, `:month_and_day`, `:month` and `:year_and_month`. The default is `:date`. * For a time the alternatives are `:time`, `:zone` and `:flex`. The default is `:time`. * For a datetime there are no style options, the default for each of the date and time part is used. * `locale` is any valid locale name returned by `Cldr.known_locale_names/0` or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0`. * `number_system:` a number system into which the formatted date digits should be transliterated. ## Returns * `string` or * raises an exception ## Notes * `to_string/3` will decide which formatter to call based upon the aguments provided to it. * A `Date.Range.t` will call `Cldr.Date.Interval.to_string/3` * A `CalendarInterval` will call `Cldr.Date.Interval.to_string/3` if its `:precision` is `:year`, `:month` or `:day`. Othersie it will call `Cldr.Time.Interval.to_string/3` * If `from` and `to` both conform to the `Calendar.datetime()` type then `Cldr.DateTime.Interval.to_string/3` is called * Otherwise if `from` and `to` conform to the `Calendar.date()` type then `Cldr.Date.Interval.to_string/3` is called * Otherwise if `from` and `to` conform to the `Calendar.time()` type then `Cldr.Time.Interval.to_string/3` is called * `CalendarInterval` support requires adding the dependency [calendar_interval](https://hex.pm/packages/calendar_interval) to the `deps` configuration in `mix.exs`. * For more information on interval format string see `Cldr.Interval`. * The available predefined formats that can be applied are the keys of the map returned by `Cldr.DateTime.Format.interval_formats("en", :gregorian)` where `"en"` can be replaced by any configuration locale name and `:gregorian` is the underlying `CLDR` calendar type. * In the case where `from` and `to` are equal, a single date, time or datetime is formatted instead of an interval ## Examples iex> use CalendarInterval iex> Cldr.Interval.to_string! ~I"2020-01-01/12", MyApp.Cldr, ...> format: :long "Wed, Jan 1 – Sun, Jan 12, 2020" iex> Cldr.Interval.to_string! Date.range(~D[2020-01-01], ~D[2020-01-12]), MyApp.Cldr, ...> format: :long "Wed, Jan 1 – Sun, Jan 12, 2020" """ @spec to_string!(range, Cldr.backend(), Keyword.t()) :: String.t() | no_return() def to_string!(%Date.Range{} = range, backend, options) do case to_string(range, backend, options) do {:ok, string} -> string {:error, {exception, reason}} -> raise exception, reason end end if Cldr.Code.ensure_compiled?(CalendarInterval) do def to_string!(%CalendarInterval{} = range, backend, options) do case to_string(range, backend, options) do {:ok, string} -> string {:error, {exception, reason}} -> raise exception, reason end end end @doc """ Returns a string representing the formatted interval formed by two dates or raises an exception. ## Arguments * `from` is any map that conforms to the any one of the `Calendar` types. * `to` is any map that conforms to the any one of the `Calendar` types. `to` must occur on or after `from`. * `backend` is any module that includes `use Cldr` and is therefore a `Cldr` backend module * `options` is a keyword list of options. The default is `[]`. ## Options * `:format` is one of `:short`, `:medium` or `:long` or a specific format type or a string representing of an interval format. The default is `:medium`. * `:style` supports dfferent formatting styles. The valid styles depends on whether formatting is for a date, time or datetime. Since the functions in this module will make a determination as to which formatter to be used based upon the data passed to them it is recommended the style option be ommitted. If styling is important then call `to_string/3` directly on `Cldr.Date.Interval`, `Cldr.Time.Interval` or `Cldr.DateTime.Interval`. * For a date the alternatives are `:date`, `:month_and_day`, `:month` and `:year_and_month`. The default is `:date`. * For a time the alternatives are `:time`, `:zone` and `:flex`. The default is `:time` * For a datetime there are no style options, the default for each of the date and time part is used * `locale` is any valid locale name returned by `Cldr.known_locale_names/0` or a `Cldr.LanguageTag` struct. The default is `Cldr.get_locale/0` * `number_system:` a number system into which the formatted date digits should be transliterated ## Returns * `{:ok, string}` or * `{:error, {exception, reason}}` ## Notes * `to_string/3` will decide which formatter to call based upon the aguments provided to it. * A `Date.Range.t` will call `Cldr.Date.Interval.to_string/3` * A `CalendarInterval` will call `Cldr.Date.Interval.to_string/3` if its `:precision` is `:year`, `:month` or `:day`. Othersie it will call `Cldr.Time.Interval.to_string/3` * If `from` and `to` both conform to the `Calendar.datetime()` type then `Cldr.DateTime.Interval.to_string/3` is called * Otherwise if `from` and `to` conform to the `Calendar.date()` type then `Cldr.Date.Interval.to_string/3` is called * Otherwise if `from` and `to` conform to the `Calendar.time()` type then `Cldr.Time.Interval.to_string/3` is called * `CalendarInterval` support requires adding the dependency [calendar_interval](https://hex.pm/packages/calendar_interval) to the `deps` configuration in `mix.exs`. * For more information on interval format string see `Cldr.Interval`. * The available predefined formats that can be applied are the keys of the map returned by `Cldr.DateTime.Format.interval_formats("en", :gregorian)` where `"en"` can be replaced by any configuration locale name and `:gregorian` is the underlying `CLDR` calendar type. * In the case where `from` and `to` are equal, a single date, time or datetime is formatted instead of an interval ## Examples iex> Cldr.Interval.to_string! ~D[2020-01-01], ~D[2020-12-31], MyApp.Cldr "Jan 1 – Dec 31, 2020" iex> Cldr.Interval.to_string! ~D[2020-01-01], ~D[2020-01-12], MyApp.Cldr "Jan 1 – 12, 2020" iex> Cldr.Interval.to_string! ~D[2020-01-01], ~D[2020-01-12], MyApp.Cldr, ...> format: :long "Wed, Jan 1 – Sun, Jan 12, 2020" iex> Cldr.Interval.to_string! ~D[2020-01-01], ~D[2020-12-01], MyApp.Cldr, ...> format: :long, style: :year_and_month "January – December 2020" iex> Cldr.Interval.to_string! ~U[2020-01-01 00:00:00.0Z], ~U[2020-12-01 10:05:00.0Z], MyApp.Cldr, ...> format: :long "January 1, 2020 at 12:00:00 AM UTC – December 1, 2020 at 10:05:00 AM UTC" iex> Cldr.Interval.to_string! ~U[2020-01-01 00:00:00.0Z], ~U[2020-01-01 10:05:00.0Z], MyApp.Cldr, ...> format: :long "January 1, 2020 at 12:00:00 AM UTC – 10:05:00 AM UTC" """ @spec to_string!(datetime, datetime, Cldr.backend(), Keyword.t()) :: String.t() | no_return() def to_string!(from, to, backend, options \\ []) do case to_string(from, to, backend, options) do {:ok, string} -> string {:error, {exception, reason}} -> raise exception, reason end end end
lib/cldr/interval.ex
0.923816
0.929248
interval.ex
starcoder
defmodule Elixoids.Game.Server do @moduledoc """ Game process. One process per running Game. Each object in the game is represented by a Process. The processes update themselves and they report their new state to the Game. Players are identified by a name (AAA..ZZZ) and control a Ship process. """ use GenServer alias Elixoids.Api.SoundEvent alias Elixoids.Asteroid.Server, as: Asteroid alias Elixoids.Bullet.Server, as: Bullet alias Elixoids.Collision.Server, as: CollisionServer alias Elixoids.Game.Snapshot alias Elixoids.News alias Elixoids.Saucer.Supervisor, as: Saucer alias Elixoids.Ship.Server, as: Ship alias Elixoids.Ship.Targets import Elixoids.Const, only: [saucer_interval_ms: 0, saucers: 0] import Logger use Elixoids.Game.Heartbeat def start_link(args = [game_id: game_id, asteroids: _]) do {:ok, _pid} = GenServer.start_link(__MODULE__, args, name: via(game_id)) end defp via(game_id) when is_integer(game_id), do: {:via, Registry, {Registry.Elixoids.Games, {game_id}}} def show(pid) do GenServer.cast(pid, :show) end def state(game_id) do GenServer.call(via(game_id), :state) end def bullet_fired(game_id, shooter_tag, pos, theta) do GenServer.call(via(game_id), {:bullet_fired, shooter_tag, pos, theta}) end def explosion(game_id, pos, radius) do GenServer.cast(via(game_id), {:explosion, pos, radius}) end def update_asteroid(game_id, new_state) do GenServer.cast(via(game_id), {:update_entity, :asteroids, new_state}) end def update_bullet(game_id, new_state) do GenServer.cast(via(game_id), {:update_entity, :bullets, new_state}) end def update_ship(game_id, new_state) do GenServer.cast(via(game_id), {:update_entity, :ships, new_state}) end def spawn_asteroids(game_id, rocks) do GenServer.cast(via(game_id), {:spawn_asteroids, rocks}) end def link(game_id, pid) do GenServer.cast(via(game_id), {:link, pid}) end @spec spawn_player(integer(), String.t()) :: {:ok, pid(), term()} | {:error, {:already_started, pid()}} def spawn_player(game_id, player_tag) do GenServer.call(via(game_id), {:spawn_player, player_tag}) end def state_of_ship(game_id, ship_pid, from) do GenServer.cast(via(game_id), {:state_of_ship, ship_pid, from}) end ## Initial state def generate_asteroids(0, _), do: [] def generate_asteroids(n, game_id) do Enum.map(1..n, fn _ -> {:ok, _pid} = Asteroid.start_link(game_id) end) end ## Server Callbacks @impl true def init(game_id: game_id, asteroids: asteroid_count) do game_state = initial_game_state(asteroid_count, game_id) Process.flag(:trap_exit, true) start_heartbeat() maybe_spawn_saucer() {:ok, game_state} end defp initial_game_state(asteroid_count, game_id) do generate_asteroids(asteroid_count, game_id) %{ :game_id => game_id, :state => %{:asteroids => %{}, :bullets => %{}, :ships => %{}}, :min_asteroid_count => asteroid_count, :saucers => saucers() } end @doc """ Echo the state of the game to the console. {:ok, game} = Elixoids.Game.Server.start_link Elixoids.Game.Server.show(game) """ @impl true def handle_cast(:show, game) do game |> Kernel.inspect(pretty: true) |> IO.puts() {:noreply, game} end def handle_cast({:update_entity, entity, state = %{pid: pid}}, game) do {_, new_game} = get_and_update_in(game, [:state, entity, pid], fn old -> {old, state} end) {:noreply, new_game} end def handle_cast({:spawn_asteroids, rocks}, game = %{game_id: game_id}) do Enum.each(rocks, fn rock -> new_asteroid_in_game(rock, game_id) end) {:noreply, game} end def handle_cast({:link, pid}, game) do Process.link(pid) {:noreply, game} end def handle_cast({:explosion, %{x: x, y: y}, radius}, game) do pan = Elixoids.Space.frac_x(x) News.publish_audio(game.game_id, SoundEvent.explosion(pan, radius)) News.publish_explosion(game.game_id, [x, y]) {:noreply, game} end def handle_cast({:state_of_ship, ship_pid, from}, game) do case game.state.ships[ship_pid] do nil -> {:noreply, game} ship -> GenServer.reply(from, fetch_ship_state(ship, game)) {:noreply, game} end end @doc """ Update the game state and check for collisions. """ @impl Elixoids.Game.Tick def handle_tick(_pid, _delta_t_ms, game = %{game_id: game_id}) do snap = snapshot(game) CollisionServer.collision_tests(game_id, snap) {:ok, game} end def handle_info({:EXIT, pid, :normal}, state) do {:noreply, remove_pid_from_game_state(pid, state, [:ships])} end def handle_info({:EXIT, pid, {:shutdown, :destroyed}}, state) do next_state = remove_pid_from_game_state(pid, state, [:asteroids]) |> check_next_wave() {:noreply, next_state} end def handle_info({:EXIT, pid, {:shutdown, :detonate}}, state) do {:noreply, remove_pid_from_game_state(pid, state, [:bullets])} end def handle_info({:EXIT, pid, :shutdown}, state) do {:noreply, remove_pid_from_game_state(pid, state, [:ships])} end # Saucer exits def handle_info({:EXIT, pid, {:shutdown, :crashed}}, state) do {:noreply, remove_pid_from_game_state(pid, state, [:ships])} end def handle_info(msg = {:EXIT, pid, _}, state) do [:EXIT, msg, state] |> inspect |> warn() {:noreply, remove_pid_from_game_state(pid, state)} end def handle_info(:spawn_saucer, %{:state => %{:ships => ships}} = game) when ships == %{} do Process.send_after(self(), :spawn_saucer, saucer_interval_ms()) {:noreply, game} end def handle_info(:spawn_saucer, %{:saucers => []} = game) do {:noreply, game} end def handle_info(:spawn_saucer, %{:saucers => [saucer | xs]} = game) do Process.send_after(self(), :spawn_saucer, saucer_interval_ms()) {:ok, _pid} = Saucer.start_saucer(game.game_id, saucer) {:noreply, %{game | saucers: xs ++ [saucer]}} end @impl true def handle_call({:bullet_fired, shooter_tag, pos, theta}, _from, game) do {:ok, bullet_pid} = Bullet.start_link(game.game_id, shooter_tag, pos, theta) {:reply, {:ok, bullet_pid}, game} end # Spawn a new ship controlled by player with given tag (unless that ship already exists) def handle_call({:spawn_player, player_tag}, _from, game = %{game_id: game_id}) do case Ship.start_link(game_id, player_tag) do {:ok, ship_pid, ship_id} -> {:reply, {:ok, ship_pid, ship_id}, game} e -> {:reply, e, game} end end # Return the current state of the game to the UI websocket. def handle_call(:state, _from, game) do game_state = %{ :dim => Elixoids.Space.dimensions(), :a => game.state.asteroids |> Map.values(), :s => game.state.ships |> Map.values(), :b => game.state.bullets |> Map.values() } {:reply, game_state, game} end defp fetch_ship_state(shiploc, game) do asteroids = game.state.asteroids |> Map.values() ships = game.state.ships |> Map.values() |> ships_except(shiploc.tag) %Targets{ :theta => shiploc.theta, :ships => ships, :rocks => asteroids, :origin => shiploc.pos } end def ships_except(ships, tag) do ships |> Enum.reject(fn s -> ship_state_has_tag(s, tag) end) end def ship_state_has_tag(%{tag: expected_tag}, expected_tag), do: true def ship_state_has_tag(%{tag: _}, _), do: false # Asteroids def new_asteroid_in_game(a, game_id) do {:ok, _pid} = Asteroid.start_link(game_id, a) end def check_next_wave(game = %{game_id: game_id}) do if few_asteroids?(game) do News.publish_news(game_id, ["ASTEROID", "spotted"]) new_asteroid_in_game(Asteroid.random_asteroid(), game_id) end game end defp few_asteroids?(%{min_asteroid_count: min_asteroid_count, state: %{asteroids: asteroids}}) do length(Map.keys(asteroids)) < min_asteroid_count end # Game state defp remove_pid_from_game_state(pid, game, keys \\ [:asteroids, :bullets, :ships]) do Enum.reduce(keys, game, fn thng, game -> case pop_in(game, [:state, thng, pid]) do {nil, _} -> game {_, new_game} -> new_game end end) end # @spec snapshot(map()) :: Snapshot.t() defp snapshot(game_state) do %Snapshot{ asteroids: Map.values(game_state.state.asteroids), bullets: Map.values(game_state.state.bullets), ships: Map.values(game_state.state.ships) } end defp maybe_spawn_saucer do time = saucer_interval_ms() if time > 0, do: Process.send_after(self(), :spawn_saucer, time) end end
lib/elixoids/game/server.ex
0.711732
0.463444
server.ex
starcoder
defmodule Paidy.Token do @moduledoc """ API for working with Token at Paidy. Through this API you can: * suspend a token * resume a token * delete a token * get a token * get all tokens tokens for credit card allowing you to use instead of a credit card number in various operations. (API ref https://paidy.com/docs/api/jp/index.html#3-) """ @endpoint "tokens" @doc """ Retrieve a token by its id. Returns 404 if not found. ## Example ``` {:ok, token} = Paidy.Token.get "token_id" ``` """ def get(id) do get(id, Paidy.config_or_env_key()) end @doc """ Retrieve a token by its id using given api key. ## Example ``` {:ok, token} = Paidy.Token.get "token_id", key ``` """ def get(id, key) do Paidy.make_request_with_key(:get, "#{@endpoint}/#{id}", key) |> Paidy.Util.handle_paidy_response() end @doc """ Retrieve all tokens.. ## Example ``` {:ok, tokens} = Paidy.Token.all ``` """ def all() do all Paidy.config_or_env_key() end @doc """ Retrieve all tokens using given api key. ## Example ``` {:ok, tokens} = Paidy.Token.all, key ``` """ def all(key) do Paidy.make_request_with_key(:get, "#{@endpoint}/", key, %{}) |> Paidy.Util.handle_paidy_response() end @doc """ Suspend a token. You can set a suspend reason code from the following. - `consumer.requested` - `merchant.requested` - `fraud.suspected` - `general` ## Example ``` params = %{ reason: %{ code: "fraud.suspected", description: "Token suspended because fraud suspected." } } {:ok, token} = Paidy.Token.suspend "token_id", params ``` """ def suspend(id, params) do suspend(id, params, Paidy.config_or_env_key()) end @doc """ Suspend a token by its id using given api key. ## Example ``` params = %{ reason: %{ code: "fraud.suspected", description: "Token suspended because fraud suspected." } } {:ok, token} = Paidy.Token.suspend "token_id", params, key ``` """ def suspend(id, params, key) do Paidy.make_request_with_key(:post, "#{@endpoint}/#{id}/suspend", key, params) |> Paidy.Util.handle_paidy_response() end @doc """ Resume a token. You can set a resume reason code from the following. - `consumer.requested` - `merchant.requested` - `general` ## Example ``` params = %{ reason: %{ code: "merchant.requested", description: "Token is being resumed because the subscription item is back in stock" } } {:ok, token} = Paidy.Token.resume "token_id", params ``` """ def resume(id, params) do resume(id, params, Paidy.config_or_env_key()) end @doc """ Resume a token by its id using given api key. ## Example ``` params = %{ reason: { code: "merchant.requested", description: "Token is being resumed because the subscription item is back in stock" } } {:ok, token} = Paidy.Token.resume "token_id", params, key ``` """ def resume(id, params, key) do Paidy.make_request_with_key(:post, "#{@endpoint}/#{id}/resume", key, params) |> Paidy.Util.handle_paidy_response() end @doc """ Delete a token. You can set a delete reason code from the following. - `consumer.requested` - `subscription.expired` - `merchant.requested` - `fraud.detected` - `general` ## Example ``` params = %{ reason: %{ code: "consumer.requested", description: "Token was deleted because consumer canceled the subscription" } } {:ok, token} = Paidy.Token.delete "token_id", params ``` """ def delete(id, params) do delete(id, params, Paidy.config_or_env_key()) end @doc """ Delete a token by its id using given api key. ## Example ``` params = %{ reason: %{ code: "consumer.requested", description: "Token was deleted because consumer canceled the subscription" } } {:ok, token} = Paidy.Token.delete "token_id", params, key ``` """ def delete(id, params, key) do Paidy.make_request_with_key(:post, "#{@endpoint}/#{id}/delete", key, params) |> Paidy.Util.handle_paidy_response() end end
lib/paidy/token.ex
0.908453
0.866246
token.ex
starcoder
defmodule Statux.Models.TrackingData do @moduledoc """ This Structure holds data that is required to track :count or :duration constraints. It is updated whenever new data comes in and is used to decide wether or not a state can be transitioned into. """ use StructAccess use TypedStruct typedstruct do # To check :count constraints like :min, :max, :is, :not, :gt, :lt. # These constraints expect a number of consecutive message fulfilling # the value requirements. If a message comes in that does not fulfill # the value requirements, the count is reset field :consecutive_message_count, Integer.t(), default: 0 # To check :duration constraints like :min, :max, :is, :not, :gt, :lt. # Is set whenever the first consecutive message is received. # TODO: How to use with n_of_m constraints? field :occurred_at, DateTime.t() # indicates wether an n_of_m constraint is used field :n_of_m_constraint, list(), default: nil # If n_of_m constraint is used, this holds the result of the last # m values. Otherwise, the list remains empty. field :valid_history, list(boolean()), default: [] # If n_of_m is used, this holds the cound of `true` elements in # the :valid_history (so we d oont have to count every time) field :valid_history_true_count, Integer.t(), default: 0 end def from_option(option) do n_of_m_constraint = option[:constraints][:count][:n_of_m] # nil or [n, m] %__MODULE__{n_of_m_constraint: n_of_m_constraint} end def put_valid(%__MODULE__{ n_of_m_constraint: nil, consecutive_message_count: 0, } = tracking_data ) do %{ tracking_data | consecutive_message_count: 1, occurred_at: DateTime.utc_now()} end def put_valid(%__MODULE__{ n_of_m_constraint: nil, consecutive_message_count: n, } = tracking_data ) do %{ tracking_data | consecutive_message_count: n + 1} end def put_valid(%__MODULE__{ n_of_m_constraint: [n, m], valid_history: history, valid_history_true_count: history_count, occurred_at: occurred_at, consecutive_message_count: count, } = tracking_data) do updated_history_true_count = case history |> Enum.at(m - 1) do true -> history_count _ -> history_count + 1 # false or nil end updated_occurred_at = cond do updated_history_true_count < n -> nil updated_history_true_count == n and history_count < n -> DateTime.utc_now() true -> occurred_at end updated_history = [true | Enum.take(history, m - 1)] %{ tracking_data | consecutive_message_count: count + 1, occurred_at: updated_occurred_at, valid_history_true_count: updated_history_true_count, valid_history: updated_history } end def put_invalid(%__MODULE__{n_of_m_constraint: nil} = tracking_data) do %{ tracking_data | consecutive_message_count: 0, occurred_at: nil } end def put_invalid(%__MODULE__{n_of_m_constraint: [n, m], valid_history: history, valid_history_true_count: history_count, occurred_at: occurred_at} = tracking_data) do updated_history_true_count = case history |> Enum.at(m - 1) do true -> history_count - 1 _ -> history_count # false or nil end updated_history = [false | Enum.take(history, m - 1)] updated_occurred_at = cond do updated_history_true_count < n -> nil true -> occurred_at end %{ tracking_data | consecutive_message_count: 0, occurred_at: updated_occurred_at, valid_history_true_count: updated_history_true_count, valid_history: updated_history } end def reset(%__MODULE__{} = tracking_data) do %{ tracking_data | consecutive_message_count: 0, occurred_at: nil, valid_history_true_count: 0, valid_history: [] } end end
lib/Statux/models/tracking_data.ex
0.542621
0.547525
tracking_data.ex
starcoder
defmodule Automaton.Types.TWEANN.Actuator do @moduledoc """ An actuator is a process that accepts signals from the neurons in the output layer, orders them into a vector, and then uses this vector to control some function that acts on the environ or even the NN itself. Actuator's are represented with the tuple: { id, cortex_id, name, vector_len, fanin_ids} • id, a unique id (useful for datastores) • cortex_id, id of the cortex for this sensor • name, name of function the sensor executes to act upon the environment, with the function parameter being the vector it accumulates from the incoming neural signals. • vector_len, vector length of the accumulated actuation vector. • fanin_ids, list of neuron ids to which are connected to the actuator. """ require Logger defstruct id: nil, cx_id: nil, name: nil, vl: nil, fanin_ids: [] @doc ~S""" When `gen/1` is executed it spawns the actuator element and immediately begins to wait for its initial state message. """ def gen(exoself_pid) do spawn(fn -> loop(exoself_pid) end) end def loop(exoself_pid) do receive do {^exoself_pid, {id, cortex_pid, actuator_name, fanin_pids}} -> loop(id, cortex_pid, actuator_name, {fanin_pids, fanin_pids}, []) end end @doc ~S""" The actuator process gathers the control signals from the neurons, appending them to the accumulator. The order in which the signals are accumulated into a vector is in the same order as the neuron ids are stored within NIds. Once all the signals have been gathered, the actuator sends cortex the sync signal, executes its function, and then again begins to wait for the neural signals from the output layer by reseting the fanin_pids from the second copy of the list. """ def loop(id, cortex_pid, actuator_name, {[from_pid | fanin_pids], m_fanin_pids}, acc) do receive do {^from_pid, :forward, input} -> loop( id, cortex_pid, actuator_name, {fanin_pids, m_fanin_pids}, List.flatten([input, acc]) ) {^cortex_pid, :terminate} -> :ok end end def loop(id, cortex_pid, actuator_name, {[], m_fanin_pids}, acc) do apply(__MODULE__, actuator_name, [Enum.reverse(acc)]) send(cortex_pid, {self(), :sync}) loop(id, cortex_pid, actuator_name, {m_fanin_pids, m_fanin_pids}, []) end @doc ~S""" The pts actuation function simply prints to screen the vector passed to it. """ def pts(result) do Logger.debug("actuator:pts(result): #{inspect(result)}") end end
lib/automata/automaton_types/neuroevolution/actuator.ex
0.697815
0.712682
actuator.ex
starcoder
defmodule AWS.Batch do @moduledoc """ Using AWS Batch, you can run batch computing workloads on the AWS Cloud. Batch computing is a common means for developers, scientists, and engineers to access large amounts of compute resources. AWS Batch uses the advantages of this computing workload to remove the undifferentiated heavy lifting of configuring and managing required infrastructure. At the same time, it also adopts a familiar batch computing software approach. Given these advantages, AWS Batch can help you to efficiently provision resources in response to jobs submitted, thus effectively helping you to eliminate capacity constraints, reduce compute costs, and deliver your results more quickly. As a fully managed service, AWS Batch can run batch computing workloads of any scale. AWS Batch automatically provisions compute resources and optimizes workload distribution based on the quantity and scale of your specific workloads. With AWS Batch, there's no need to install or manage batch computing software. This means that you can focus your time and energy on analyzing results and solving your specific problems. """ alias AWS.Client alias AWS.Request def metadata do %AWS.ServiceMetadata{ abbreviation: nil, api_version: "2016-08-10", content_type: "application/x-amz-json-1.1", credential_scope: nil, endpoint_prefix: "batch", global?: false, protocol: "rest-json", service_id: "Batch", signature_version: "v4", signing_name: "batch", target_prefix: nil } end @doc """ Cancels a job in an AWS Batch job queue. Jobs that are in the `SUBMITTED`, `PENDING`, or `RUNNABLE` state are canceled. Jobs that have progressed to `STARTING` or `RUNNING` aren't canceled, but the API operation still succeeds, even if no job is canceled. These jobs must be terminated with the `TerminateJob` operation. """ def cancel_job(%Client{} = client, input, options \\ []) do url_path = "/v1/canceljob" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Creates an AWS Batch compute environment. You can create `MANAGED` or `UNMANAGED` compute environments. `MANAGED` compute environments can use Amazon EC2 or AWS Fargate resources. `UNMANAGED` compute environments can only use EC2 resources. In a managed compute environment, AWS Batch manages the capacity and instance types of the compute resources within the environment. This is based on the compute resource specification that you define or the [launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html) that you specify when you create the compute environment. Either, you can choose to use EC2 On-Demand Instances and EC2 Spot Instances. Or, you can use Fargate and Fargate Spot capacity in your managed compute environment. You can optionally set a maximum price so that Spot Instances only launch when the Spot Instance price is less than a specified percentage of the On-Demand price. Multi-node parallel jobs aren't supported on Spot Instances. In an unmanaged compute environment, you can manage your own EC2 compute resources and have a lot of flexibility with how you configure your compute resources. For example, you can use custom AMIs. However, you must verify that each of your AMIs meet the Amazon ECS container instance AMI specification. For more information, see [container instance AMIs](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/container_instance_AMIs.html) in the *Amazon Elastic Container Service Developer Guide*. After you created your unmanaged compute environment, you can use the `DescribeComputeEnvironments` operation to find the Amazon ECS cluster that's associated with it. Then, launch your container instances into that Amazon ECS cluster. For more information, see [Launching an Amazon ECS container instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_container_instance.html) in the *Amazon Elastic Container Service Developer Guide*. AWS Batch doesn't upgrade the AMIs in a compute environment after the environment is created. For example, it doesn't update the AMIs when a newer version of the Amazon ECS optimized AMI is available. Therefore, you're responsible for managing the guest operating system (including its updates and security patches) and any additional application software or utilities that you install on the compute resources. To use a new AMI for your AWS Batch jobs, complete these steps: Create a new compute environment with the new AMI. Add the compute environment to an existing job queue. Remove the earlier compute environment from your job queue. Delete the earlier compute environment. """ def create_compute_environment(%Client{} = client, input, options \\ []) do url_path = "/v1/createcomputeenvironment" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Creates an AWS Batch job queue. When you create a job queue, you associate one or more compute environments to the queue and assign an order of preference for the compute environments. You also set a priority to the job queue that determines the order that the AWS Batch scheduler places jobs onto its associated compute environments. For example, if a compute environment is associated with more than one job queue, the job queue with a higher priority is given preference for scheduling jobs to that compute environment. """ def create_job_queue(%Client{} = client, input, options \\ []) do url_path = "/v1/createjobqueue" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Deletes an AWS Batch compute environment. Before you can delete a compute environment, you must set its state to `DISABLED` with the `UpdateComputeEnvironment` API operation and disassociate it from any job queues with the `UpdateJobQueue` API operation. Compute environments that use AWS Fargate resources must terminate all active jobs on that compute environment before deleting the compute environment. If this isn't done, the compute environment enters an invalid state. """ def delete_compute_environment(%Client{} = client, input, options \\ []) do url_path = "/v1/deletecomputeenvironment" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Deletes the specified job queue. You must first disable submissions for a queue with the `UpdateJobQueue` operation. All jobs in the queue are eventually terminated when you delete a job queue. The jobs are terminated at a rate of about 16 jobs each second. It's not necessary to disassociate compute environments from a queue before submitting a `DeleteJobQueue` request. """ def delete_job_queue(%Client{} = client, input, options \\ []) do url_path = "/v1/deletejobqueue" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Deregisters an AWS Batch job definition. Job definitions are permanently deleted after 180 days. """ def deregister_job_definition(%Client{} = client, input, options \\ []) do url_path = "/v1/deregisterjobdefinition" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Describes one or more of your compute environments. If you're using an unmanaged compute environment, you can use the `DescribeComputeEnvironment` operation to determine the `ecsClusterArn` that you should launch your Amazon ECS container instances into. """ def describe_compute_environments(%Client{} = client, input, options \\ []) do url_path = "/v1/describecomputeenvironments" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Describes a list of job definitions. You can specify a `status` (such as `ACTIVE`) to only return job definitions that match that status. """ def describe_job_definitions(%Client{} = client, input, options \\ []) do url_path = "/v1/describejobdefinitions" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Describes one or more of your job queues. """ def describe_job_queues(%Client{} = client, input, options \\ []) do url_path = "/v1/describejobqueues" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Describes a list of AWS Batch jobs. """ def describe_jobs(%Client{} = client, input, options \\ []) do url_path = "/v1/describejobs" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Returns a list of AWS Batch jobs. You must specify only one of the following items: * A job queue ID to return a list of jobs in that job queue * A multi-node parallel job ID to return a list of nodes for that job * An array job ID to return a list of the children for that job You can filter the results by job status with the `jobStatus` parameter. If you don't specify a status, only `RUNNING` jobs are returned. """ def list_jobs(%Client{} = client, input, options \\ []) do url_path = "/v1/listjobs" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Lists the tags for an AWS Batch resource. AWS Batch resources that support tags are compute environments, jobs, job definitions, and job queues. ARNs for child jobs of array and multi-node parallel (MNP) jobs are not supported. """ def list_tags_for_resource(%Client{} = client, resource_arn, options \\ []) do url_path = "/v1/tags/#{URI.encode(resource_arn)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :get, url_path, query_params, headers, nil, options, nil ) end @doc """ Registers an AWS Batch job definition. """ def register_job_definition(%Client{} = client, input, options \\ []) do url_path = "/v1/registerjobdefinition" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Submits an AWS Batch job from a job definition. Parameters that are specified during `SubmitJob` override parameters defined in the job definition. vCPU and memory requirements that are specified in the `ResourceRequirements` objects in the job definition are the exception. They can't be overridden this way using the `memory` and `vcpus` parameters. Rather, you must specify updates to job definition parameters in a `ResourceRequirements` object that's included in the `containerOverrides` parameter. Jobs that run on Fargate resources can't be guaranteed to run for more than 14 days. This is because, after 14 days, Fargate resources might become unavailable and job might be terminated. """ def submit_job(%Client{} = client, input, options \\ []) do url_path = "/v1/submitjob" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Associates the specified tags to a resource with the specified `resourceArn`. If existing tags on a resource aren't specified in the request parameters, they aren't changed. When a resource is deleted, the tags associated with that resource are deleted as well. AWS Batch resources that support tags are compute environments, jobs, job definitions, and job queues. ARNs for child jobs of array and multi-node parallel (MNP) jobs are not supported. """ def tag_resource(%Client{} = client, resource_arn, input, options \\ []) do url_path = "/v1/tags/#{URI.encode(resource_arn)}" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Terminates a job in a job queue. Jobs that are in the `STARTING` or `RUNNING` state are terminated, which causes them to transition to `FAILED`. Jobs that have not progressed to the `STARTING` state are cancelled. """ def terminate_job(%Client{} = client, input, options \\ []) do url_path = "/v1/terminatejob" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Deletes specified tags from an AWS Batch resource. """ def untag_resource(%Client{} = client, resource_arn, input, options \\ []) do url_path = "/v1/tags/#{URI.encode(resource_arn)}" headers = [] {query_params, input} = [ {"tagKeys", "tagKeys"} ] |> Request.build_params(input) Request.request_rest( client, metadata(), :delete, url_path, query_params, headers, input, options, nil ) end @doc """ Updates an AWS Batch compute environment. """ def update_compute_environment(%Client{} = client, input, options \\ []) do url_path = "/v1/updatecomputeenvironment" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end @doc """ Updates a job queue. """ def update_job_queue(%Client{} = client, input, options \\ []) do url_path = "/v1/updatejobqueue" headers = [] query_params = [] Request.request_rest( client, metadata(), :post, url_path, query_params, headers, input, options, nil ) end end
lib/aws/generated/batch.ex
0.917034
0.543772
batch.ex
starcoder
defmodule ListToCsv.Key do @moduledoc """ `ListToCsv.Key` contains types and utilities for keys. """ @type t() :: String.t() | atom() | integer() | function() @type many() :: list(t()) | t() | {function(), many()} @doc """ build prefix keys with trailing `:N` ## Examples iex> build_prefix(:name) [:name, :N] iex> build_prefix([:item, :name]) [:item, :name, :N] """ @spec build_prefix(many()) :: many() def build_prefix(keys), do: List.wrap(keys) ++ [:N] @doc """ Returns a list of `keys` duplicated `n` times. And replace first `:N` with current 1 base index. ## Examples iex> duplicate([[:name, :N]], 2) [[:name, 1], [:name, 2]] iex> duplicate([[:name, :N, :item, :N]], 2) [[:name, 1, :item, :N], [:name, 2, :item, :N]] iex> duplicate([{&(&1 + &2), [[:item, :N, :quantity], :capacity]}], 2) [{&(&1 + &2), [[:item, 1, :quantity], :capacity]}, {&(&1 + &2), [[:item, 2, :quantity], :capacity]}] """ @spec duplicate(list(many()), integer()) :: list(many()) def duplicate(keys, n) do Enum.flat_map(1..n, fn i -> Enum.map(keys, &replace_first(&1, :N, i)) end) end @doc """ Returns `true` if `keys` starts with the given `prefix` list; otherwise returns `false`. Note that `:N` can match with `integer`. ## Examples iex> starts_with?(:name, [:item, :N]) false iex> starts_with?([:item, :N, :name], [:item, :N]) true iex> starts_with?([:name], [:item, :N]) false iex> starts_with?([:item, 1, :name, :N, :first], [:item, :N, :name, :N]) true iex> starts_with?([:packages, :N, :name], [:item, :N]) false iex> starts_with?({&(&1 + &2), [[:item, :N, :quantity], :capacity]}, [:item, :N]) true """ @spec starts_with?(many(), list(t())) :: boolean def starts_with?({fun, keys}, prefix) when is_function(fun) and is_list(keys) do Enum.any?(keys, &starts_with?(&1, prefix)) end def starts_with?(keys, _prefix) when not is_list(keys), do: false def starts_with?(keys, prefix) when length(keys) < length(prefix), do: false def starts_with?(keys, prefix) do Enum.zip(prefix, keys) |> Enum.all?(fn {a, a} -> true {:N, n} when is_integer(n) -> true {_, _} -> false end) end @doc """ Returns a new list created by replacing occurrences of `from` in `subject` with `to`. Only the first occurrence is replaced. ## Examples iex> replace_first(:item, :N, 1) :item iex> replace_first([:item], :N, 1) [:item] iex> replace_first([:item, :N, :name], :N, 1) [:item, 1, :name] iex> replace_first([:item, :N, :name, :N], :N, 2) [:item, 2, :name, :N] iex> replace_first({&(&1 + &2), [[:item, :N, :quantity], :capacity]}, :N, 3) {&(&1 + &2), [[:item, 3, :quantity], :capacity]} """ @spec replace_first(list(t()), t(), t()) :: list(t()) def replace_first([] = _subject, _from, _to), do: [] def replace_first([from | tail], from, to), do: [to | tail] def replace_first([head | tail], from, to), do: [head | replace_first(tail, from, to)] def replace_first({fun, subjects}, from, to) when is_function(fun) do {fun, Enum.map(subjects, &replace_first(&1, from, to))} end def replace_first(subject, _from, _to), do: subject end
lib/list_to_csv/key.ex
0.905134
0.662965
key.ex
starcoder
defmodule Membrane.RTP.OutboundPacketTracker do @moduledoc """ Tracks statistics of outbound packets. Besides tracking statistics, tracker can also serialize packet's header and payload stored inside an incoming buffer into a proper RTP packet. When encountering header extensions, it remaps its identifiers from locally used extension names to integer values expected by the receiver. """ use Membrane.Filter alias Membrane.{Buffer, RTP, Payload, Time} alias Membrane.RTP.Session.SenderReport def_input_pad :input, caps: :any, demand_mode: :auto def_output_pad :output, caps: :any, demand_mode: :auto def_input_pad :rtcp_input, availability: :on_request, caps: :any, demand_mode: :auto def_output_pad :rtcp_output, availability: :on_request, caps: :any, demand_mode: :auto def_options ssrc: [spec: RTP.ssrc_t()], payload_type: [spec: RTP.payload_type_t()], clock_rate: [spec: RTP.clock_rate_t()], extension_mapping: [spec: RTP.SessionBin.rtp_extension_mapping_t()], alignment: [ default: 1, spec: pos_integer(), description: """ Number of bytes that each packet should be aligned to. Alignment is achieved by adding RTP padding. """ ] defmodule State do @moduledoc false use Bunch.Access alias Membrane.RTP @type t :: %__MODULE__{ ssrc: RTP.ssrc_t(), payload_type: RTP.payload_type_t(), extension_mapping: RTP.SessionBin.rtp_extension_mapping_t(), alignment: pos_integer(), any_buffer_sent?: boolean(), rtcp_output_pad: Membrane.Pad.ref_t() | nil, stats_acc: %{} } defstruct ssrc: 0, payload_type: 0, extension_mapping: %{}, alignment: 1, any_buffer_sent?: false, rtcp_output_pad: nil, stats_acc: %{ clock_rate: 0, timestamp: 0, rtp_timestamp: 0, sender_packet_count: 0, sender_octet_count: 0 } end @impl true def handle_init(options) do state = %State{} |> put_in([:stats_acc, :clock_rate], options.clock_rate) |> Map.merge(options |> Map.from_struct() |> Map.drop([:clock_rate])) {:ok, state} end @impl true def handle_pad_added(Pad.ref(:rtcp_input, _id), _ctx, state) do {:ok, state} end @impl true def handle_pad_added(Pad.ref(:rtcp_output, _id) = pad, _ctx, %{rtcp_output_pad: nil} = state) do {:ok, %{state | rtcp_output_pad: pad}} end @impl true def handle_pad_added(Pad.ref(:rtcp_output, _id), _ctx, _state) do raise "rtcp_output pad can get linked just once" end @impl true def handle_process(:input, %Buffer{} = buffer, _ctx, state) do state = update_stats(buffer, state) {rtp_metadata, metadata} = Map.pop(buffer.metadata, :rtp, %{}) supported_extensions = Map.keys(state.extension_mapping) extensions = rtp_metadata.extensions |> Enum.filter(fn extension -> extension.identifier in supported_extensions end) |> Enum.map(fn extension -> %{extension | identifier: Map.fetch!(state.extension_mapping, extension.identifier)} end) header = struct(RTP.Header, %{ rtp_metadata | ssrc: state.ssrc, payload_type: state.payload_type, extensions: extensions }) payload = RTP.Packet.serialize(%RTP.Packet{header: header, payload: buffer.payload}, align_to: state.alignment ) buffer = %Buffer{buffer | payload: payload, metadata: metadata} {{:ok, buffer: {:output, buffer}}, %{state | any_buffer_sent?: true}} end @impl true def handle_other(:send_stats, ctx, state) do %{rtcp_output_pad: rtcp_output} = state if rtcp_output && not ctx.pads[rtcp_output].end_of_stream? do stats = get_stats(state) actions = %{state.ssrc => stats} |> SenderReport.generate_report() |> Enum.map(&Membrane.RTCP.Packet.serialize(&1)) |> Enum.map(&{:buffer, {rtcp_output, %Membrane.Buffer{payload: &1}}}) {{:ok, actions}, %{state | any_buffer_sent?: false}} else {:ok, state} end end defp get_stats(%State{any_buffer_sent?: false}), do: :no_stats defp get_stats(%State{stats_acc: stats}), do: stats defp update_stats(%Buffer{payload: payload, metadata: metadata}, state) do %{ sender_octet_count: octet_count, sender_packet_count: packet_count } = state.stats_acc updated_stats = %{ clock_rate: state.stats_acc.clock_rate, sender_octet_count: octet_count + Payload.size(payload), sender_packet_count: packet_count + 1, timestamp: Time.vm_time(), rtp_timestamp: metadata.rtp.timestamp } Map.put(state, :stats_acc, updated_stats) end end
lib/membrane/rtp/outbound_packet_tracker.ex
0.832373
0.482002
outbound_packet_tracker.ex
starcoder
defmodule OMG.Signature do @moduledoc """ Adapted from https://github.com/exthereum/blockchain. Defines helper functions for signing and getting the signature of a transaction, as defined in Appendix F of the Yellow Paper. For any of the following functions, if chain_id is specified, it's assumed that we're post-fork and we should follow the specification EIP-155 from: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md """ @base_recovery_id 27 @base_recovery_id_eip_155 35 @signature_len 32 @type keccak_hash :: binary() @type public_key :: <<_::512>> @type private_key :: <<_::256>> @type hash_v :: integer() @type hash_r :: integer() @type hash_s :: integer() @type signature_len :: unquote(@signature_len) @doc """ Recovers a public key from a signed hash. This implements Eq.(208) of the Yellow Paper, adapted from https://stackoverflow.com/a/20000007 """ @spec recover_public(keccak_hash(), hash_v, hash_r, hash_s, integer() | nil) :: {:ok, public_key} | {:error, String.t()} def recover_public(hash, v, r, s, chain_id \\ nil) do signature = pad(:binary.encode_unsigned(r), @signature_len) <> pad(:binary.encode_unsigned(s), @signature_len) # Fork Ψ EIP-155 recovery_id = if not is_nil(chain_id) and uses_chain_id?(v) do v - chain_id * 2 - @base_recovery_id_eip_155 else v - @base_recovery_id end case :libsecp256k1.ecdsa_recover_compact(hash, signature, :uncompressed, recovery_id) do {:ok, <<_byte::8, public_key::binary()>>} -> {:ok, public_key} {:error, reason} -> {:error, to_string(reason)} end end @spec uses_chain_id?(hash_v) :: boolean() defp uses_chain_id?(v) do v >= @base_recovery_id_eip_155 end @spec pad(binary(), signature_len()) :: binary() defp pad(binary, desired_length) do desired_bits = desired_length * 8 case byte_size(binary) do 0 -> <<0::size(desired_bits)>> x when x <= desired_length -> padding_bits = (desired_length - x) * 8 <<0::size(padding_bits)>> <> binary _ -> raise "Binary too long for padding" end end end
apps/omg/lib/omg/signature.ex
0.882801
0.433322
signature.ex
starcoder
defmodule Panoramix.Error do defexception [:message, :code] @type t :: %__MODULE__{} end defmodule Panoramix do @moduledoc """ Post a query to Druid Broker or request its status. Use Panoramix.Query to build a query. ## Examples Build a query like this: ```elixir use Panoramix q = from "my_datasource", query_type: "timeseries", intervals: ["2019-03-01T00:00:00+00:00/2019-03-04T00:00:00+00:00"], granularity: :day, filter: dimensions.foo == "bar", aggregations: [event_count: count(), unique_id_count: hyperUnique(:user_unique)] ``` And then send it: ```elixir Panoramix.post_query(q, :default) ``` Where `:default` is a configuration profile pointing to your Druid server. The default value for the profile argument is `:default`, so if you only need a single configuration you can omit it: ```elixir Panoramix.post_query(q) ``` Response example: ```elixir {:ok, [ %{ "result" => %{ "event_count" => 7544, "unique_id_count" => 43.18210933535 }, "timestamp" => "2019-03-01T00:00:00.000Z" }, %{ "result" => %{ "event_count" => 1051, "unique_id_count" => 104.02052398847 }, "timestamp" => "2019-03-02T00:00:00.000Z" }, %{ "result" => %{ "event_count" => 4591, "unique_id_count" => 79.19885795313 }, "timestamp" => "2019-03-03T00:00:00.000Z" } ]} ``` To request status from Broker run ```elixir Panoramix.status(:default) ``` """ @moduledoc since: "1.0.0" @spec post_query(%Panoramix.Query{}, atom()) :: {:ok, term()} | {:error, HTTPoison.Error.t() | Jason.DecodeError.t() | Panoramix.Error.t()} def post_query(query, profile \\ :default) do url_path = "/druid/v2" body = Panoramix.Query.to_json query headers = [{"Content-Type", "application/json"}] request_and_decode(profile, :post, url_path, body, headers) end @spec post_query!(%Panoramix.Query{}, atom()) :: term() def post_query!(query, profile \\ :default) do case post_query(query, profile) do {:ok, response} -> response {:error, error} -> raise error end end @spec status(atom) :: {:ok, term()} | {:error, HTTPoison.Error.t() | Jason.DecodeError.t() | Panoramix.Error.t()} def status(profile \\ :default) do url_path = "/status" body = "" headers = [] request_and_decode(profile, :get, url_path, body, headers) end @spec status!(atom) :: term() def status!(profile \\ :default) do case status(profile) do {:ok, response} -> response {:error, error} -> raise error end end defp request_and_decode(profile, method, url_path, body, headers) do broker_profiles = Application.get_env(:panoramix, :broker_profiles) broker_profile = broker_profiles[profile] || raise ArgumentError, "no broker profile with name #{profile}" url = broker_profile[:base_url] <> url_path options = http_options(url, broker_profile) with {:ok, http_response} <- HTTPoison.request(method, url, body, headers, options), {:ok, body} <- maybe_handle_druid_error(http_response), {:ok, decoded} <- Jason.decode body do {:ok, decoded} end end defp http_options(url, broker_profile) do ssl_options(url, broker_profile) ++ auth_options(broker_profile) ++ timeout_options() end defp ssl_options(url, broker_profile) do if url =~ ~r(^https://) do cacertfile = broker_profile[:cacertfile] [ssl: [verify: :verify_peer, cacertfile: cacertfile, depth: 10]] else [] end end defp auth_options(broker_profile) do if broker_profile[:http_username] do auth = {broker_profile[:http_username], broker_profile[:http_password]} [hackney: [basic_auth: auth]] else [] end end defp timeout_options() do # Default to 120 seconds request_timeout = Application.get_env(:panoramix, :request_timeout, 120_000) [recv_timeout: request_timeout] end defp maybe_handle_druid_error( %HTTPoison.Response{status_code: 200, body: body}) do {:ok, body} end defp maybe_handle_druid_error( %HTTPoison.Response{status_code: status_code, body: body}) do message = "Druid error (code #{status_code}): " <> case Jason.decode body do {:ok, %{"error" => _} = decoded} -> # Usually we'll get a JSON object from Druid with "error", # "errorMessage", "errorClass" and "host". Some of them # might be null. Enum.join( for field <- ["error", "errorMessage", "errorClass", "host"], decoded[field] do "#{field}: #{decoded[field]}" end, " ") _ -> "undecodable error: " <> body end {:error, %Panoramix.Error{message: message, code: status_code}} end @doc ~S""" Format a date or a datetime into a format that Druid expects. ## Examples iex> Panoramix.format_time! ~D[2018-07-20] "2018-07-20" iex> Panoramix.format_time!( ...> Timex.to_datetime({{2018,07,20},{1,2,3}})) "2018-07-20T01:02:03+00:00" """ def format_time!(%DateTime{} = datetime) do Timex.format! datetime, "{ISO:Extended}" end def format_time!(%Date{} = date) do Timex.format! date, "{ISOdate}" end defmacro __using__(_params) do quote do import Panoramix.Query, only: [from: 2] end end end
lib/panoramix.ex
0.827793
0.821008
panoramix.ex
starcoder
defmodule Cldr.DateTime.Relative.Backend do @moduledoc false def define_date_time_relative_module(config) do backend = config.backend config = Macro.escape(config) quote location: :keep, bind_quoted: [config: config, backend: backend] do defmodule DateTime.Relative do @second 1 @minute 60 @hour 3600 @day 86400 @week 604_800 @month 2_629_743.83 @year 31_556_926 @unit %{ second: @second, minute: @minute, hour: @hour, day: @day, week: @week, month: @month, year: @year } @other_units [:mon, :tue, :wed, :thu, :fri, :sat, :sun, :quarter] @unit_keys Map.keys(@unit) ++ @other_units @doc false def get_locale(locale \\ unquote(backend).get_locale()) def get_locale(locale_name) when is_binary(locale_name) do with {:ok, locale} <- Cldr.validate_locale(locale_name, unquote(backend)) do get_locale(locale) end end @doc """ Returns a `{:ok, string}` representing a relative time (ago, in) for a given number, Date or Datetime. Returns `{:error, reason}` when errors are detected. * `relative` is a number or Date/Datetime representing the time distance from `now` or from options[:relative_to] * `options` is a `Keyword` list of options which are: ## Options * `:locale` is the locale in which the binary is formatted. The default is `Cldr.get_locale/0` * `:style` is the style of the binary. Style may be `:default`, `:narrow` or `:short` * `:unit` is the time unit for the formatting. The allowable units are `:second`, `:minute`, `:hour`, `:day`, `:week`, `:month`, `:year`, `:mon`, `:tue`, `:wed`, `:thu`, `:fri`, `:sat`, `:sun`, `:quarter` * `:relative_to` is the baseline Date or Datetime from which the difference from `relative` is calculated when `relative` is a Date or a DateTime. The default for a Date is `Date.utc_today`, for a DateTime it is `DateTime.utc_now` ### Notes When `options[:unit]` is not specified, `MyApp.Cldr.DateTime.Relative.to_string/2` attempts to identify the appropriate unit based upon the magnitude of `relative`. For example, given a parameter of less than `60`, then `to_string/2` will assume `:seconds` as the unit. See `unit_from_relative_time/1`. ## Examples iex> #{inspect(__MODULE__)}.to_string(-1) {:ok, "1 second ago"} iex> #{inspect(__MODULE__)}.to_string(1) {:ok, "in 1 second"} iex> #{inspect(__MODULE__)}.to_string(1, unit: :day) {:ok, "tomorrow"} iex> #{inspect(__MODULE__)}.to_string(1, unit: :day, locale: "fr") {:ok, "demain"} iex> #{inspect(__MODULE__)}.to_string(1, unit: :day, style: :narrow) {:ok, "tomorrow"} iex> #{inspect(__MODULE__)}.to_string(1234, unit: :year) {:ok, "in 1,234 years"} iex> #{inspect(__MODULE__)}.to_string(1234, unit: :year, locale: "fr") {:ok, "dans 1 234 ans"} iex> #{inspect(__MODULE__)}.to_string(31) {:ok, "in 31 seconds"} iex> #{inspect(__MODULE__)}.to_string(~D[2017-04-29], relative_to: ~D[2017-04-26]) {:ok, "in 3 days"} iex> #{inspect(__MODULE__)}.to_string(310, style: :short, locale: "fr") {:ok, "dans 5 min"} iex> #{inspect(__MODULE__)}.to_string(310, style: :narrow, locale: "fr") {:ok, "+5 min"} iex> #{inspect(__MODULE__)}.to_string 2, unit: :wed, style: :short, locale: "en" {:ok, "in 2 Wed."} iex> #{inspect(__MODULE__)}.to_string 1, unit: :wed, style: :short {:ok, "next Wed."} iex> #{inspect(__MODULE__)}.to_string -1, unit: :wed, style: :short {:ok, "last Wed."} iex> #{inspect(__MODULE__)}.to_string -1, unit: :wed {:ok, "last Wednesday"} iex> #{inspect(__MODULE__)}.to_string -1, unit: :quarter {:ok, "last quarter"} iex> #{inspect(__MODULE__)}.to_string -1, unit: :mon, locale: "fr" {:ok, "lundi dernier"} iex> #{inspect(__MODULE__)}.to_string(~D[2017-04-29], unit: :ziggeraut) {:error, {Cldr.UnknownTimeUnit, "Unknown time unit :ziggeraut. Valid time units are [:day, :hour, :minute, :month, :second, :week, :year, :mon, :tue, :wed, :thu, :fri, :sat, :sun, :quarter]"}} """ @spec to_string(number | map(), Keyword.t()) :: {:ok, String.t()} | {:error, {module, String.t()}} def to_string(time, options \\ []) do Cldr.DateTime.Relative.to_string(time, unquote(backend), options) end @doc """ Returns a `{:ok, string}` representing a relative time (ago, in) for a given number, Date or Datetime or raises an exception on error. ## Arguments * `relative` is a number or Date/Datetime representing the time distance from `now` or from options[:relative_to]. * `options` is a `Keyword` list of options. ## Options * `:locale` is the locale in which the binary is formatted. The default is `Cldr.get_locale/0` * `:style` is the format of the binary. Style may be `:default`, `:narrow` or `:short`. The default is `:default` * `:unit` is the time unit for the formatting. The allowable units are `:second`, `:minute`, `:hour`, `:day`, `:week`, `:month`, `:year`, `:mon`, `:tue`, `:wed`, `:thu`, `:fri`, `:sat`, `:sun`, `:quarter` * `:relative_to` is the baseline Date or Datetime from which the difference from `relative` is calculated when `relative` is a Date or a DateTime. The default for a Date is `Date.utc_today`, for a DateTime it is `DateTime.utc_now` See `to_string/2` """ @spec to_string!(number | map(), Keyword.t()) :: String.t() def to_string!(time, options \\ []) do Cldr.DateTime.Relative.to_string!(time, unquote(backend), options) end for locale_name <- Cldr.Locale.Loader.known_locale_names(config) do locale_data = locale_name |> Cldr.Locale.Loader.get_locale(config) |> Map.get(:date_fields) |> Map.take(@unit_keys) def get_locale(%LanguageTag{cldr_locale_name: unquote(locale_name)}), do: unquote(Macro.escape(locale_data)) end end end end end
lib/cldr/backend/relative.ex
0.930213
0.595081
relative.ex
starcoder
defmodule GoogleSheets.Loader.Docs do @moduledoc """ Implements GoogleSheets.Loader behavior by fetching a Spreadsheet through Google spreadsheet API. The only configuration value required is :url, which should point to the Atom feed of the spreadsheet. See [README](extra-readme.html) how to publish a spreadsheet and find the URL. The loader first requests the Atom feed and parses URLs pointing to CSV data for each individual worksheet and the last_udpdated time stamp for spreadsheet. If the last_updated field is equal to the one passes as previous_version, the loader stops and returns :unchanged If not, it will filter the found CSV URLs and leave only those that exist in the sheets argument. If the sheets argument is nil, it will load all worksheets. After requesting all URLs and parsing the responses, the loader checks that each individual spreadsheet given as sheets parameter exist and returns an SpreadSheetData.t structure. If there are any errors during HTTP requests and/or parsing, it will most likely raise an exception. If you use this loader in code which is not crash resistant, do handle the exceptions. """ import SweetXml require Logger @behaviour GoogleSheets.Loader @connect_timeout 2_000 @receive_timeout 120_000 @doc """ Load spreadsheet from Google sheets using the URL specified in config[:url] key. """ def load(previous_version, _id, config) when is_list(config) do try do url = Keyword.fetch!(config, :url) ignored_sheets = Keyword.get(config, :ignored_sheets, []) sheets = config |> Keyword.get(:sheets, []) |> Enum.reject(fn sheet -> sheet in ignored_sheets end) load_spreadsheet(previous_version, url, sheets) catch result -> result end end # Fetch Atom feed describing feed and request individual sheets if not modified. defp load_spreadsheet(previous_version, url, sheets) do {:ok, %HTTPoison.Response{status_code: 200} = response} = HTTPoison.get(url, [], timeout: @connect_timeout, recv_timeout: @receive_timeout) updated = response.body |> xpath(~x"//feed/updated/text()") |> List.to_string() |> String.trim() version = :crypto.hash(:sha, url <> Enum.join(sheets) <> updated) |> Base.encode16(case: :lower) if previous_version != nil and version == previous_version do throw({:ok, :unchanged}) end worksheets = response.body |> xpath( ~x"//feed/entry"l, title: ~x"./title/text()", url: ~x"./link[@type='text/csv']/@href" ) |> convert_entries([]) |> filter_entries(sheets, []) |> load_worksheets([]) if not Enum.all?(sheets, fn sheetname -> Enum.any?(worksheets, fn ws -> sheetname == ws.name end) end) do loaded = worksheets |> Enum.map(fn ws -> ws.name end) |> Enum.join(",") throw( {:error, "All requested sheets not loaded, expected: #{Enum.join(sheets, ",")} loaded: #{loaded}"} ) end {:ok, version, worksheets} end # Converts xpath entries to {title, url} with data converted to strings defp convert_entries([], acc), do: acc defp convert_entries([entry | rest], acc) do title = List.to_string(entry[:title]) url = List.to_string(entry[:url]) convert_entries(rest, [{title, url} | acc]) end # Filter out entries not specified in sheets list, if empty sheets list, accept all defp filter_entries(entries, [], _acc), do: entries defp filter_entries([], _sheets, acc), do: acc defp filter_entries([{title, url} | rest], sheets, acc) do if title in sheets do filter_entries(rest, sheets, [{title, url} | acc]) else filter_entries(rest, sheets, acc) end end # Request worksheets and create WorkSheet.t entries defp load_worksheets([], worksheets), do: worksheets defp load_worksheets([{title, url} | rest], worksheets) do {:ok, %HTTPoison.Response{status_code: 200} = response} = HTTPoison.get( url, [], timeout: @connect_timeout, recv_timeout: @receive_timeout, follow_redirect: false ) load_worksheets(rest, [%GoogleSheets.WorkSheet{name: title, csv: response.body} | worksheets]) end end
lib/google_sheets/loader/docs.ex
0.721547
0.577257
docs.ex
starcoder
defmodule Schedules.HoursOfOperation do @moduledoc false alias Schedules.Departures @type departure :: Departures.t() | :no_service @type t :: %__MODULE__{ week: {departure, departure}, saturday: {departure, departure}, sunday: {departure, departure} } defstruct week: {:no_service, :no_service}, saturday: {:no_service, :no_service}, sunday: {:no_service, :no_service} @doc """ Fetches the hours of operation for a given route. The hours of operation are broken into three date ranges: * week * saturday * sunday It's possible for one or more of the ranges to be :no_service, if the route does not run on that day. """ @spec hours_of_operation(Routes.Route.id_t() | [Routes.Route.id_t()]) :: t | {:error, any} def hours_of_operation(route_id_or_ids, date \\ Util.service_date()) do route_id_or_ids |> List.wrap() |> api_params(date) |> Task.async_stream(&V3Api.Schedules.all/1, on_timeout: :kill_task) # 3 dates * 2 directions == 6 responses per route |> Enum.chunk_every(6) |> Enum.map(&parse_responses/1) |> join_hours end @doc """ For a list of route IDs and a date, returns the API queries we'll need to run. For a given route, there are 6 queries: * weekday, direction 0 * saturday, direction 0, * sunday, direction 0, * weekday, direction 1 * saturday, direction 1 * sunday, direction 1 """ @spec api_params([Routes.Route.id_t()], Date.t()) :: Keyword.t() def api_params(route_ids, today) do for route_id <- route_ids, direction_id <- [0, 1], date <- week_dates(today) do [ route: route_id, date: date, direction_id: direction_id, stop_sequence: "first,last", "fields[schedule]": "departure_time,arrival_time" ] end end @doc """ Returns the next Monday, Saturday, and Sunday, relative to a given date. Returns as a list rather than a tuple for easier iteration. """ @spec week_dates(Date.t()) :: [Date.t()] def week_dates(today) do dow = Date.day_of_week(today) [ # Monday Date.add(today, 8 - dow), # Saturday, not going back in time Date.add(today, Integer.mod(6 - dow, 7)), # Sunday Date.add(today, 7 - dow) ] end @doc """ Parses a block of API responses into an %HoursOfOperation struct, or returns an error. It expects 6 responses, in the same order specified in `api_params/2`. """ @spec parse_responses([{:ok, api_response} | {:exit, any}]) :: t | {:error, any} when api_response: JsonApi.t() | {:error, any} def parse_responses([ {:ok, week_response_0}, {:ok, saturday_response_0}, {:ok, sunday_response_0}, {:ok, week_response_1}, {:ok, saturday_response_1}, {:ok, sunday_response_1} ]) do with {:ok, week_0} <- departure(week_response_0), {:ok, week_1} <- departure(week_response_1), {:ok, saturday_0} <- departure(saturday_response_0), {:ok, saturday_1} <- departure(saturday_response_1), {:ok, sunday_0} <- departure(sunday_response_0), {:ok, sunday_1} <- departure(sunday_response_1) do %__MODULE__{ week: {week_0, week_1}, saturday: {saturday_0, saturday_1}, sunday: {sunday_0, sunday_1} } else _ -> parse_responses([]) end end def parse_responses(errors) when is_list(errors) do {:error, :timeout} end @doc """ Merges a list of %HoursOfOperation{} structs, taking the earlier/latest times for each. Used to combine %HoursOfOperation structs for different routes into a single struct representing all the routes together. """ @spec join_hours([t]) :: t def join_hours([single]) do single end def join_hours(multiple) do Enum.reduce(multiple, %__MODULE__{}, &merge/2) end defimpl Enumerable do def count(_hours) do {:error, __MODULE__} end def member?(_hours, _other) do {:error, __MODULE__} end def reduce(hours, acc, fun) do [ week: hours.week, saturday: hours.saturday, sunday: hours.sunday ] |> Enum.reject(&(elem(&1, 1) == {:no_service, :no_service})) |> Enumerable.reduce(acc, fun) end def slice(_hours) do {:error, __MODULE__} end end defp merge(%__MODULE__{} = first, %__MODULE__{} = second) do %__MODULE__{ week: merge_directions(first.week, second.week), saturday: merge_directions(first.saturday, second.saturday), sunday: merge_directions(first.sunday, second.sunday) } end defp merge_directions({first_0, first_1}, {second_0, second_1}) do { merge_departure(first_0, second_0), merge_departure(first_1, second_1) } end defp merge_departure(:no_service, second) do second end defp merge_departure(first, :no_service) do first end defp merge_departure(%Departures{} = first, %Departures{} = second) do %Departures{ first_departure: Enum.min_by( [first.first_departure, second.first_departure], &DateTime.to_unix(&1, :nanosecond) ), last_departure: Enum.max_by( [first.last_departure, second.last_departure], &DateTime.to_unix(&1, :nanosecond) ) } end defp time(%{"departure_time" => nil, "arrival_time" => time}), do: time defp time(%{"departure_time" => time}), do: time defp departure(%JsonApi{data: data}) do {:ok, departure(data)} end defp departure({:error, [%JsonApi.Error{code: "no_service"}]}) do {:ok, :no_service} end defp departure({:error, _} = error) do error end defp departure([]) do :no_service end defp departure(data) do {min, max} = data |> Stream.map(&Timex.parse!(time(&1.attributes), "{ISO:Extended}")) |> Enum.min_max_by(&DateTime.to_unix(&1, :nanosecond)) %Departures{ first_departure: min, last_departure: max } end end
apps/schedules/lib/hours_of_operation.ex
0.841207
0.518729
hours_of_operation.ex
starcoder
defmodule ChallengeGov.Messages.MessageContext do @moduledoc """ MessageContext schema ----------------------------- - Types of Message Contexts - ----------------------------- Gives a description of each context type and the relevant params, permissions, and reply functionality If a param is not listed assume nil Broadcast Contexts ------------------ Thread Type: B-1 Description: Single admin created thread that broadcasts messages to all users. Audience: all Who can create: - Admin Who can see: - Admin: All - Challenge Manager: All - Solver: All What happens on reply: - Admin: Sends another broadcast message in same thread - Challenge Manager: Can't reply - Solver: Can't reply Thread Type: B-2 Description: Admin created thread that broadcasts messages to all challenge managers Audience: challenge_managers Who can create: - Admin Who can see: - Admin: All - Challenge Manager: All What happens on reply: - Admin: Sends another broadcast message in same thread - Challenge Manager: Creates a new message context of type I-1 Thread Type: B-3 Description: Admin or challenge manager created thread that broadcasts messages to all users related to challenge Context: challenge Context ID: challenge_id Audience: all Who can create: - Admin - Challenge Manager Who can see: - Admin: All - Challenge Manager: An manager of the challenge referenced - Solver: Has a submission on the challenge referenced What happens on reply: - Admin: Sends another broadcast message in same thread - Challenge Manager: Sends another broadcast message in same thread - Solver: Creates a new message context of type I-2 Group Contexts -------------- Thread Type: G-1 Description: Single admin created thread for group discussion with all admins Audience: admins Who can create: - Admin Who can see: - Admin: All What happens on reply: - Admin: Sends another message in same thread Thread Type: G-2 Description: Admin or challenge manager created group thread around a challenge Context: challenge Context ID: challenge_id Audience: challenge_managers Who can create: - Admin - Challenge Manager Who can see: - Admin: All - Challenge Manager: Related to the challenge referenced by context_id What happens on reply: - Admin: Sends another message in same thread - Challenge Manager: Sends another message in same thread Isolated Contexts ----------------- Thread Type: I-1 Description: Thread spawned from a challenge manager responding to thread type B-2 Parent ID: ID of the broadcast message context this context spawned from Context: challenge_manager Context ID: ID of the challenge manager being messaged Audience: all Who can create: - Challenge Manager: By replying to a thread type B-2 Who can see: - Admin: All - Challenge Manager: Referenced by context_id What happens on reply: - Admin: Sends another message in same thread - Challenge Manager: Sends another message in same thread Thread Type: I-2 Description: Thread spawned from a solver responding to thread type B-3 Parent ID: ID of the broadcast message context this context spawned from Context: solver Context ID: ID of the solver that responded Audience: all Who can create: - Solver: By replying to a thread type B-3 Who can see: - Admin: All - Challenge Manager: Related to the parent context challenge, - Solver: Referenced by context_id What happens on reply: - Admin: Sends another message in same thread - Challenge Manager: Sends another message in same thread - Solver: Sends another message in same thread Thread Type: I-3 Description: Thread spawned from an admin or challenge manager directly messaging a submission Context: submission Context ID: ID of the submission being messaged Audience: all Who can create: - Admin: Messaging a solver/submission or group of them making individual contexts for each - Challenge Manager: Messaging a solver/submission or group of them making individual contexts for each Who can see: - Admin: All - Challenge Manager: Related to the parent context challenge, - Solver: Related to submission being referenced by context_id What happens on reply: - Admin: Sends another message in same thread - Challenge Manager: Sends another message in same thread - Solver: Sends another message in same thread """ use Ecto.Schema import Ecto.Changeset alias ChallengeGov.Messages.Message alias ChallengeGov.Messages.MessageContext alias ChallengeGov.Messages.MessageContextStatus @valid_contexts [ "challenge", "challenge_manager", "submission", "solver" ] @valid_audiences [ "all", "admins", "challenge_managers" ] @type t :: %__MODULE__{} schema "message_contexts" do belongs_to(:parent, MessageContext) has_many(:contexts, MessageContext, foreign_key: :parent_id) has_many(:messages, Message) has_many(:statuses, MessageContextStatus) belongs_to(:last_message, Message, on_replace: :nilify) field(:context, :string) field(:context_id, :integer) field(:audience, :string) timestamps(type: :utc_datetime_usec) end def changeset(struct, params \\ %{}) do struct |> cast(params, [ :context, :context_id, :audience, :parent_id ]) |> foreign_key_constraint(:parent_id) |> validate_inclusion(:context, [nil | @valid_contexts]) |> validate_inclusion(:audience, @valid_audiences) end end
lib/challenge_gov/messages/message_context.ex
0.806738
0.513059
message_context.ex
starcoder
defmodule AMQP.Connection do @moduledoc """ Functions to operate on Connections. """ import AMQP.Core alias AMQP.Connection defstruct [:pid] @type t :: %Connection{pid: pid} @doc """ Opens an new Connection to an AMQP broker. The connections created by this module are supervised under amqp_client's supervision tree. Please note that connections do not get restarted automatically by the supervision tree in case of a failure. If you need robust connections and channels, use monitors on the returned connection PID. The connection parameters can be passed as a keyword list or as a AMQP URI. When using a keyword list, the following options can be used: # Options * `:username` - The name of a user registered with the broker (defaults to \"guest\"); * `:password` - The password of user (defaults to \"<PASSWORD>\"); * `:virtual_host` - The name of a virtual host in the broker (defaults to \"/\"); * `:host` - The hostname of the broker (defaults to \"localhost\"); * `:port` - The port the broker is listening on (defaults to `5672`); * `:channel_max` - The channel_max handshake parameter (defaults to `0`); * `:frame_max` - The frame_max handshake parameter (defaults to `0`); * `:heartbeat` - The hearbeat interval in seconds (defaults to `10`); * `:connection_timeout` - The connection timeout in milliseconds (defaults to `60000`); * `:ssl_options` - Enable SSL by setting the location to cert files (defaults to `none`); * `:client_properties` - A list of extra client properties to be sent to the server, defaults to `[]`; * `:socket_options` - Extra socket options. These are appended to the default options. \ See http://www.erlang.org/doc/man/inet.html#setopts-2 and http://www.erlang.org/doc/man/gen_tcp.html#connect-4 \ for descriptions of the available options. ## Enabling SSL To enable SSL, supply the following in the `ssl_options` field: * `cacertfile` - Specifies the certificates of the root Certificate Authorities that we wish to implicitly trust; * `certfile` - The client's own certificate in PEM format; * `keyfile` - The client's private key in PEM format; ### Example ``` AMQP.Connection.open port: 5671, ssl_options: [cacertfile: '/path/to/testca/cacert.pem', certfile: '/path/to/client/cert.pem', keyfile: '/path/to/client/key.pem', # only necessary with intermediate CAs # depth: 2, verify: :verify_peer, fail_if_no_peer_cert: true] ``` ## Examples iex> AMQP.Connection.open host: \"localhost\", port: 5672, virtual_host: \"/\", username: \"guest\", password: \"<PASSWORD>\" {:ok, %AMQP.Connection{}} iex> AMQP.Connection.open \"amqp://guest:guest@localhost\" {:ok, %AMQP.Connection{}} """ @spec open(keyword|String.t) :: {:ok, t} | {:error, atom} | {:error, any} def open(options \\ []) def open(options) when is_list(options) do options = options |> normalize_ssl_options amqp_params = amqp_params_network(username: Keyword.get(options, :username, "guest"), password: Keyword.get(options, :password, "<PASSWORD>"), virtual_host: Keyword.get(options, :virtual_host, "/"), host: Keyword.get(options, :host, 'localhost') |> to_charlist, port: Keyword.get(options, :port, :undefined), channel_max: Keyword.get(options, :channel_max, 0), frame_max: Keyword.get(options, :frame_max, 0), heartbeat: Keyword.get(options, :heartbeat, 10), connection_timeout: Keyword.get(options, :connection_timeout, 60000), ssl_options: Keyword.get(options, :ssl_options, :none), client_properties: Keyword.get(options, :client_properties, []), socket_options: Keyword.get(options, :socket_options, []), auth_mechanisms: Keyword.get(options, :auth_mechanisms, [&:amqp_auth_mechanisms.plain/3, &:amqp_auth_mechanisms.amqplain/3])) do_open(amqp_params) end def open(uri) when is_binary(uri) do case uri |> to_charlist |> :amqp_uri.parse do {:ok, amqp_params} -> do_open(amqp_params) error -> error end end @doc """ Closes an open Connection. """ @spec close(t) :: :ok | {:error, any} def close(conn) do case :amqp_connection.close(conn.pid) do :ok -> :ok error -> {:error, error} end end defp do_open(amqp_params) do case :amqp_connection.start(amqp_params) do {:ok, pid} -> {:ok, %Connection{pid: pid}} error -> error end end defp normalize_ssl_options(options) when is_list(options) do for {k, v} <- options do if k in [:cacertfile, :cacertfile, :cacertfile] do {k, to_charlist(v)} else {k, v} end end end defp normalize_ssl_options(options), do: options end
lib/amqp/connection.ex
0.829112
0.772015
connection.ex
starcoder
defmodule Grizzly.ZWave.Commands.PriorityRouteReport do @moduledoc """ This command is used to advertise the current network route in use for an actual destination NodeID. Params: * `:node_id` - the NodeID destination for which the current network route is requested (required) * `:type` - the route type (required) * `:repeaters` - node ids of repeaters for the route (required) * `:speed` - speed used for the route (required) """ @behaviour Grizzly.ZWave.Command alias Grizzly.ZWave.{Command, DecodeError} alias Grizzly.ZWave.CommandClasses.NetworkManagementInstallationMaintenance @type param :: {:node_id, byte} | {:type, NetworkManagementInstallationMaintenance.route_type()} | {:repeaters, [byte]} | {:speed, NetworkManagementInstallationMaintenance.speed()} @impl true @spec new([param()]) :: {:ok, Command.t()} def new(params) do command = %Command{ name: :priority_route_report, command_byte: 0x03, command_class: NetworkManagementInstallationMaintenance, params: params, impl: __MODULE__ } {:ok, command} end @impl true @spec encode_params(Command.t()) :: binary() def encode_params(command) do node_id = Command.param!(command, :node_id) type_byte = Command.param!(command, :type) |> NetworkManagementInstallationMaintenance.route_type_to_byte() repeater_bytes = Command.param!(command, :repeaters) |> NetworkManagementInstallationMaintenance.repeaters_to_bytes() speed_byte = Command.param!(command, :speed) |> NetworkManagementInstallationMaintenance.speed_to_byte() <<node_id, type_byte>> <> repeater_bytes <> <<speed_byte>> end @impl true @spec decode_params(binary()) :: {:ok, [param()]} | {:error, DecodeError.t()} def decode_params(<<node_id, type_byte, repeater_bytes::binary-size(4), speed_byte>>) do with {:ok, type} <- NetworkManagementInstallationMaintenance.route_type_from_byte(type_byte), {:ok, speed} <- NetworkManagementInstallationMaintenance.speed_from_byte(speed_byte) do {:ok, [ node_id: node_id, type: type, speed: speed, repeaters: NetworkManagementInstallationMaintenance.repeaters_from_bytes(repeater_bytes) ]} else {:error, %DecodeError{} = decode_error} -> {:error, %DecodeError{decode_error | command: :priority_route_report}} end end end
lib/grizzly/zwave/commands/priority_route_report.ex
0.846609
0.409634
priority_route_report.ex
starcoder
defmodule Verk.Job do @moduledoc """ The Job struct. Set `config :verk, max_retry_count: value` on your config file to set the default max amount of retries on all your `Verk.Job` when none is informed. Defaults at `25`. """ @keys [ error_message: nil, failed_at: nil, retry_count: 0, queue: nil, class: nil, args: [], jid: nil, finished_at: nil, enqueued_at: nil, retried_at: nil, created_at: nil, error_backtrace: nil, max_retry_count: nil ] @string_keys @keys |> Keyword.keys() |> Enum.map(&Atom.to_string/1) @type t :: %__MODULE__{ error_message: String.t(), failed_at: DateTime.t(), retry_count: non_neg_integer, queue: String.t(), class: String.t() | atom, jid: String.t(), finished_at: DateTime.t(), retried_at: DateTime.t(), error_backtrace: String.t() } defstruct [:original_json | @keys] @doc """ Encode the struct to a JSON string, raising if there is an error """ @spec encode!(t) :: binary def encode!(job = %__MODULE__{}) do job |> Map.from_struct() |> Map.take(Keyword.keys(@keys)) # We wrap the args so there is no issue with cJson on Redis side # It's just an opaque string as far as Redis is concerned |> Map.update!(:args, &Jason.encode!(&1)) |> Jason.encode!() end @doc """ Decode the JSON payload storing the original json as part of the struct. """ @spec decode(binary) :: {:ok, %__MODULE__{}} | {:error, Jason.DecodeError.t()} def decode(payload) do with {:ok, map} <- Jason.decode(payload), {:ok, args} <- unwrap_args(map["args"]) do fields = map |> Map.take(@string_keys) |> Map.update!("args", fn _ -> args end) |> Map.new(fn {k, v} -> {String.to_existing_atom(k), v} end) job = %__MODULE__{} |> struct(fields) |> build(payload) {:ok, job} end end @doc """ Decode the JSON payload storing the original json as part of the struct, raising if there is an error """ @spec decode!(binary) :: %__MODULE__{} def decode!(payload) do case decode(payload) do {:ok, job} -> job {:error, error} -> raise error end end def default_max_retry_count do Confex.get_env(:verk, :max_retry_count, 25) end defp unwrap_args(wrapped_args) when is_binary(wrapped_args), do: Jason.decode(wrapped_args, keys: Application.get_env(:verk, :args_keys, :strings)) defp unwrap_args(args), do: {:ok, args} defp build(job = %{args: %{}}, payload) do build(%{job | args: []}, payload) end defp build(job, payload) do %Verk.Job{job | original_json: payload} end end
lib/verk/job.ex
0.81549
0.403655
job.ex
starcoder
defmodule TypeCheck.Builtin.FixedList do @moduledoc """ Checks whether the value is a list with the expected elements On failure returns a problem tuple with: - `:not_a_list` if the value is not a list - `:different_length` if the value is a list but not of equal size. - `:element_error` if one of the elements does not match. The extra information contains in this case `:problem` and `:index` to indicate what and where the problem occured. """ defstruct [:element_types] use TypeCheck @type! t :: %__MODULE__{element_types: list(TypeCheck.Type.t())} @type! problem_tuple :: {t(), :not_a_list, %{}, any()} | {t(), :different_length, %{expected_length: non_neg_integer()}, list()} | {t(), :element_error, %{problem: lazy(TypeCheck.TypeError.Formatter.problem_tuple()), index: non_neg_integer()}, list()} defimpl TypeCheck.Protocols.ToCheck do def to_check(s, param) do expected_length = length(s.element_types) element_checks_ast = build_element_checks_ast(s.element_types, param, s) quote generated: :true, location: :keep do case unquote(param) do x when not is_list(x) -> {:error, {unquote(Macro.escape(s)), :not_a_list, %{}, x}} x when length(x) != unquote(expected_length) -> {:error, {unquote(Macro.escape(s)), :different_length, %{expected_length: unquote(expected_length)}, x}} _ -> unquote(element_checks_ast) end end end def build_element_checks_ast(element_types, param, s) do element_checks = element_types |> Enum.with_index() |> Enum.flat_map(fn {element_type, index} -> impl = TypeCheck.Protocols.ToCheck.to_check( element_type, quote generated: true, location: :keep do hd(var!(rest, unquote(__MODULE__))) end ) quote generated: true, location: :keep do [ {{:ok, element_bindings, altered_element}, index, var!(rest, unquote(__MODULE__))} <- {unquote(impl), unquote(index), tl(var!(rest, unquote(__MODULE__)))}, bindings = element_bindings ++ bindings, altered_param = [altered_element | altered_param] ] end end) quote generated: true, location: :keep do bindings = [] altered_param = [] with var!(rest, unquote(__MODULE__)) = unquote(param), unquote_splicing(element_checks), altered_param = :lists.reverse(altered_param) do {:ok, bindings, altered_param} else {{:error, error}, index, _rest} -> {:error, {unquote(Macro.escape(s)), :element_error, %{problem: error, index: index}, unquote(param)}} end end end end defimpl TypeCheck.Protocols.Inspect do def inspect(s, opts) do s.element_types |> Elixir.Inspect.inspect(%Inspect.Opts{ opts | inspect_fun: &TypeCheck.Protocols.Inspect.inspect/2 }) |> Inspect.Algebra.color(:builtin_type, opts) end end if Code.ensure_loaded?(StreamData) do defimpl TypeCheck.Protocols.ToStreamData do def to_gen(s) do s.element_types |> Enum.map(&TypeCheck.Protocols.ToStreamData.to_gen/1) |> StreamData.fixed_list() end end end end
lib/type_check/builtin/fixed_list.ex
0.860472
0.667586
fixed_list.ex
starcoder
defmodule Bandit.PhoenixAdapter do @moduledoc """ A Bandit adapter for Phoenix. Note that this adapter does not currently support WebSocket connections; it is only suitable for use with HTTP(S)-only Phoenix instances. To use this adapter, your project will need to include Bandit as a dependency; see https://hex.pm/bandit for details on the currently supported version of Bandit to include. Once Bandit is included as a dependency of your Phoenix project, add the following to your endpoint configuration in `config/config.exs`: ``` config :your_app, YourAppWeb.Endpoint, adapter: Bandit.PhoenixAdapter ``` ## Endpoint configuration This adapter uses the following endpoint configuration: * `:http`: the configuration for the HTTP server. Accepts the following options: * `port`: The port to run on. Defaults to 4000 * `ip`: The address to bind to. Can be specified as `{127, 0, 0, 1}`, or using `{:local, path}` to bind to a Unix domain socket. Defaults to {127, 0, 0, 1}. * `transport_options`: Any valid value from `ThousandIsland.Transports.TCP` Defaults to `false`, which will cause Bandit to not start an HTTP server. * `:https`: the configuration for the HTTPS server. Accepts the following options: * `port`: The port to run on. Defaults to 4040 * `ip`: The address to bind to. Can be specified as `{127, 0, 0, 1}`, or using `{:local, path}` to bind to a Unix domain socket. Defaults to {127, 0, 0, 1}. * `transport_options`: Any valid value from `ThousandIsland.Transports.SSL` Defaults to `false`, which will cause Bandit to not start an HTTPS server. """ require Logger @doc false def child_specs(endpoint, config) do for {scheme, port} <- [http: 4000, https: 4040], opts = config[scheme] do port = :proplists.get_value(:port, opts, port) unless port do Logger.error(":port for #{scheme} config is nil, cannot start server") raise "aborting due to nil port" end ip = :proplists.get_value(:ip, opts, {127, 0, 0, 1}) transport_options = :proplists.get_value(:transport_options, opts, []) opts = [port: port_to_integer(port), transport_options: [ip: ip] ++ transport_options] [plug: endpoint, scheme: scheme, options: opts] |> Bandit.child_spec() |> Supervisor.child_spec(id: {endpoint, scheme}) end end defp port_to_integer(port) when is_binary(port), do: String.to_integer(port) defp port_to_integer(port) when is_integer(port), do: port end
lib/bandit/phoenix_adapter.ex
0.853226
0.836955
phoenix_adapter.ex
starcoder
defmodule ExHal.Assertions do @moduledoc """ Convenience functions for asserting things about HAL documents ```elixir iex> import ExUnit.Assertions nil iex> import ExHal.Assertions nil iex> assert_property ~s({"name": "foo"}), "name" true iex> assert_property ~s({"name": "foo"}), "address" ** (ExUnit.AssertionError) address is absent iex> assert_property ~s({"name": "foo"}), "name", eq "foo" true iex> assert_property ~s({"name": "foo"}), "name", matches ~r/fo/ true iex> assert_property ~s({"name": "foo"}), "name", eq "bar" ** (ExUnit.AssertionError) expected property `name` to eq("bar") iex> assert_link_target ~s({"_links": { "profile": {"href": "http://example.com" }}}), ...> "profile" true iex> assert_link_target ~s({"_links": { "profile": {"href": "http://example.com" }}}), ...> "item" ** (ExUnit.AssertionError) link `item` is absent iex> assert_link_target ~s({"_links": { "profile": {"href": "http://example.com" }}}), ...> "profile", eq "http://example.com" true iex> assert_link_target ~s({"_links": { "profile": {"href": "http://example.com" }}}), ...> "profile", matches ~r/example.com/ true iex> assert_link_target ~s({"_links": { "profile": {"href": "http://example.com" }}}), ...> "profile", eq "http://bad.com" ** (ExUnit.AssertionError) expected (at least one) `item` link to eq("http://bad.com") but found only http://example.com iex> assert collection("{}") |> Enum.empty? true iex> assert 1 == collection("{}") |> Enum.count ** (ExUnit.AssertionError) Assertion with == failed ``` """ import ExUnit.Assertions alias ExHal.{Document, Link, Collection} @doc """ Returns a stream representation of the document. """ def collection(doc) when is_binary(doc) do Document.parse!(doc) |> collection end def collection(doc) do Collection.to_stream(doc) end @doc """ Returns a function that checks if the actual value is equal to the expected. """ def eq(expected) do fn actual -> actual == expected end end @doc """ Returns a function that checks if the actual value matches the expected pattern. """ def matches(expected) do fn actual -> actual =~ expected end end @doc """ Asserts that a property exists and, optionally, that its value checks out. """ defmacro assert_property(doc, rel) do quote do p_assert_property(unquote(doc), unquote(rel), fn _ -> true end, nil) end end defmacro assert_property(doc, rel, check_fn) do check_desc = Macro.to_string(check_fn) quote do p_assert_property(unquote(doc), unquote(rel), unquote(check_fn), unquote(check_desc)) end end @doc """ Asserts that the specifed link exists and that its target checks out. """ defmacro assert_link_target(doc, rel) do quote do p_assert_link_target(unquote(doc), unquote(rel), fn _ -> true end, nil) end end defmacro assert_link_target(doc, rel, check_fn) do check_desc = Macro.to_string(check_fn) quote do p_assert_link_target(unquote(doc), unquote(rel), unquote(check_fn), unquote(check_desc)) end end # internal functions @spec p_assert_property(String.t | Document.t, String.t, (any() -> boolean()), String.t) :: any() def p_assert_property(doc, prop_name, check_fn, check_desc) when is_binary(doc) do p_assert_property(Document.parse!(doc), prop_name, check_fn, check_desc) end def p_assert_property(doc, prop_name, check_fn, check_desc) do prop_val = Document.get_property_lazy(doc, prop_name, fn -> flunk("#{prop_name} is absent") end) assert check_fn.(prop_val), "expected property #{prop_name} to #{check_desc}" end def p_assert_link_target(doc, rel, check_fn, check_desc) when is_binary(doc) do p_assert_link_target(Document.parse!(doc), rel, check_fn, check_desc) end def p_assert_link_target(doc, rel, check_fn, check_desc) do link_targets = doc |> Document.get_links_lazy(rel, fn -> flunk("#{rel} link is absent") end) |> Enum.map(&Link.target_url(&1)) |> Enum.map(&elem(&1, 1)) assert link_targets |> Enum.any?(&check_fn.(&1)), "expected (at least one) `#{rel}` link to #{check_desc} but found only #{link_targets}`" end end
lib/exhal/assertions.ex
0.887793
0.806777
assertions.ex
starcoder
defmodule Utility.Test.MockCache do @moduledoc """ This cache is designed to be isolated by process and only visible to that process, ideally for ExUnit tests since each test is a spawned process. However, this can only be done: 1) if the test process directly calls start_mock/1 AND does not call the cache through a spawned process 2) if the test spawns a process, then the call stack can receive and pass the cache's pid through so it can be used in the mock. Supported options: stubs: [on_get_hit: 1, return: some_value, on_set_hit: 2, return: some_other_value] This option will act like a stub and return a value you want at a certain hit count. For example, if you want to return "foo" when the cache.get is hit on the 2nd time, then you would provide [stubs: [on_get_hit: 2, return: "foo"]] as options, or tag the test with: @tag cache: [stubs: [on_get_hit: 2, return: "foo"]] Usage in a test: use Utility.DataCase, async: true | false # when async = true, the mock_pid is passed into the test context test "my indirect test", %{mock_pid: mock_pid} do {:ok, result} = MyModule.something_that_spawns_processes(options: [cache_pid: mock_pid]) # assumes that options is passed all the way to the cache interface assert result.stuff end test "my direct test" do {:ok, result} = MyModule.something_that_calls_the_cache_directly() assert result.stuff end """ alias Utility.Test.KVStore @behaviour Utility.Cache @global_kv_name Utility.Test.KVStore def start_mock(opts \\ []) do {async?, opts} = Keyword.pop(opts, :async, false) name = if async? do {:ok, kv_pid} = KVStore.start_link(%{opts: opts}) Process.put(:mock_cache_pid, kv_pid) kv_pid else @global_kv_name end {:ok, name} end @impl Utility.Cache def multi(commands, opts) do result = Enum.map(commands, fn [cmd | args] -> elem(apply(__MODULE__, cmd, args ++ [opts]), 1) end) {:ok, result} end @impl Utility.Cache def hash_get(key, field, opts) do {:ok, GenServer.call(mock_cache_pid(opts), {:hash_get, key, field})} end @impl Utility.Cache def hash_set(key, field, value, opts) do {:ok, GenServer.call(mock_cache_pid(opts), {:hash_set, key, field, value})} end @impl Utility.Cache def keys(term, opts) do {:ok, GenServer.call(mock_cache_pid(opts), {:keys, term})} end @impl Utility.Cache def expire(term, ttl, opts) do {:ok, GenServer.call(mock_cache_pid(opts), {:expire, term, ttl})} end @impl Utility.Cache def flush(opts) do {:ok, GenServer.call(mock_cache_pid(opts), :flush)} end @impl Utility.Cache def bust(key, opts) do {:ok, GenServer.call(mock_cache_pid(opts), {:bust, key})} end def state!(opts \\ []) do GenServer.call(mock_cache_pid(opts), :state) end def mock_cache_pid(opts) do Process.get(:mock_cache_pid) || Keyword.get(opts, :mock_cache_pid, @global_kv_name) end end
test/support/mock_cache.ex
0.77518
0.516474
mock_cache.ex
starcoder
defmodule AWS.Health do @moduledoc """ AWS Health The AWS Health API provides programmatic access to the AWS Health information that is presented in the [AWS Personal Health Dashboard](https://phd.aws.amazon.com/phd/home#/). You can get information about events that affect your AWS resources: <ul> <li> `DescribeEvents`: Summary information about events. </li> <li> `DescribeEventDetails`: Detailed information about one or more events. </li> <li> `DescribeAffectedEntities`: Information about AWS resources that are affected by one or more events. </li> </ul> In addition, these operations provide information about event types and summary counts of events or affected entities: <ul> <li> `DescribeEventTypes`: Information about the kinds of events that AWS Health tracks. </li> <li> `DescribeEventAggregates`: A count of the number of events that meet specified criteria. </li> <li> `DescribeEntityAggregates`: A count of the number of affected entities that meet specified criteria. </li> </ul> The Health API requires a Business or Enterprise support plan from [AWS Support](http://aws.amazon.com/premiumsupport/). Calling the Health API from an account that does not have a Business or Enterprise support plan causes a `SubscriptionRequiredException`. For authentication of requests, AWS Health uses the [Signature Version 4 Signing Process](http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). See the [AWS Health User Guide](http://docs.aws.amazon.com/health/latest/ug/what-is-aws-health.html) for information about how to use the API. **Service Endpoint** The HTTP endpoint for the AWS Health API is: <ul> <li> https://health.us-east-1.amazonaws.com </li> </ul> """ @doc """ Returns a list of entities that have been affected by the specified events, based on the specified filter criteria. Entities can refer to individual customer resources, groups of customer resources, or any other construct, depending on the AWS service. Events that have impact beyond that of the affected entities, or where the extent of impact is unknown, include at least one entity indicating this. At least one event ARN is required. Results are sorted by the `lastUpdatedTime` of the entity, starting with the most recent. """ def describe_affected_entities(client, input, options \\ []) do request(client, "DescribeAffectedEntities", input, options) end @doc """ Returns the number of entities that are affected by each of the specified events. If no events are specified, the counts of all affected entities are returned. """ def describe_entity_aggregates(client, input, options \\ []) do request(client, "DescribeEntityAggregates", input, options) end @doc """ Returns the number of events of each event type (issue, scheduled change, and account notification). If no filter is specified, the counts of all events in each category are returned. """ def describe_event_aggregates(client, input, options \\ []) do request(client, "DescribeEventAggregates", input, options) end @doc """ Returns detailed information about one or more specified events. Information includes standard event data (region, service, etc., as returned by `DescribeEvents`), a detailed event description, and possible additional metadata that depends upon the nature of the event. Affected entities are not included; to retrieve those, use the `DescribeAffectedEntities` operation. If a specified event cannot be retrieved, an error message is returned for that event. """ def describe_event_details(client, input, options \\ []) do request(client, "DescribeEventDetails", input, options) end @doc """ Returns the event types that meet the specified filter criteria. If no filter criteria are specified, all event types are returned, in no particular order. """ def describe_event_types(client, input, options \\ []) do request(client, "DescribeEventTypes", input, options) end @doc """ Returns information about events that meet the specified filter criteria. Events are returned in a summary form and do not include the detailed description, any additional metadata that depends on the event type, or any affected resources. To retrieve that information, use the `DescribeEventDetails` and `DescribeAffectedEntities` operations. If no filter criteria are specified, all events are returned. Results are sorted by `lastModifiedTime`, starting with the most recent. """ def describe_events(client, input, options \\ []) do request(client, "DescribeEvents", input, options) end @spec request(map(), binary(), map(), list()) :: {:ok, Poison.Parser.t | nil, Poison.Response.t} | {:error, Poison.Parser.t} | {:error, HTTPoison.Error.t} defp request(client, action, input, options) do client = %{client | service: "health"} host = get_host("health", client) url = get_url(host, client) headers = [{"Host", host}, {"Content-Type", "application/x-amz-json-1.1"}, {"X-Amz-Target", "AWSHealth_20160804.#{action}"}] payload = Poison.Encoder.encode(input, []) headers = AWS.Request.sign_v4(client, "POST", url, headers, payload) case HTTPoison.post(url, payload, headers, options) do {:ok, response=%HTTPoison.Response{status_code: 200, body: ""}} -> {:ok, nil, response} {:ok, response=%HTTPoison.Response{status_code: 200, body: body}} -> {:ok, Poison.Parser.parse!(body), response} {:ok, _response=%HTTPoison.Response{body: body}} -> error = Poison.Parser.parse!(body) exception = error["__type"] message = error["message"] {:error, {exception, message}} {:error, %HTTPoison.Error{reason: reason}} -> {:error, %HTTPoison.Error{reason: reason}} end end defp get_host(endpoint_prefix, client) do if client.region == "local" do "localhost" else "#{endpoint_prefix}.#{client.region}.#{client.endpoint}" end end defp get_url(host, %{:proto => proto, :port => port}) do "#{proto}://#{host}:#{port}/" end end
lib/aws/health.ex
0.871235
0.64542
health.ex
starcoder
defmodule OLED.Display do @moduledoc """ Defines a display module When used, the displaly expects an `:app` as option. The `:app` should be the app that has the configuration. Example: defmodule MyApp.MyDisplay do use OLED.Display, app: :my_app end Could be configured with: config :my_app, MyApp.MyDisplay, width: 128, height: 64, driver: :ssd1306, type: :spi, device: "spidev0.0", rst_pin: 25, dc_pin: 24 ## Configuration: * `:driver` - For now only `:ssd1306` is available * `:type` - Type of connection: (i.e.: `:spi`, `:i2c`) * `:width` - Display width * `:height` - Display height * `:rst_pin` - GPIO for RESET pin * `:dc_pin` - GPIO for DC pin """ alias OLED.Display.Server defmacro __using__(opts) do quote bind_quoted: [opts: opts, moduledoc: @moduledoc] do @moduledoc moduledoc |> String.replace(~r/MyApp\.MyDisplay/, Enum.join(Module.split(__MODULE__), ".")) |> String.replace(~r/:my_app/, Atom.to_string(Keyword.fetch!(opts, :app))) @app Keyword.fetch!(opts, :app) @me __MODULE__ @behaviour OLED.Display def module_config(), do: Application.get_env(@app, @me, []) def start_link(config \\ []) do module_config() |> Keyword.merge(config) |> Server.start_link(name: @me) end spec = [ id: opts[:id] || @me, start: Macro.escape(opts[:start]) || quote(do: {@me, :start_link, [opts]}), restart: opts[:restart] || :permanent, type: :worker ] @doc false @spec child_spec(Keyword.t()) :: Supervisor.child_spec() def child_spec(opts) do %{unquote_splicing(spec)} end defoverridable child_spec: 1 def display(), do: Server.display(@me) def display_frame(data, opts \\ []), do: Server.display_frame(@me, data, opts) def display_raw_frame(data, opts \\ []), do: Server.display_raw_frame(@me, data, opts) def clear(), do: Server.clear(@me) def clear(pixel_state), do: Server.clear(@me, pixel_state) def put_buffer(data), do: Server.put_buffer(@me, data) def get_buffer(), do: Server.get_buffer(@me) def put_pixel(x, y, opts \\ []), do: Server.put_pixel(@me, x, y, opts) def line(x1, y1, x2, y2, opts \\ []), do: Server.line(@me, x1, y1, x2, y2, opts) def line_h(x, y, width, opts \\ []), do: Server.line_h(@me, x, y, width, opts) def line_v(x, y, height, opts \\ []), do: Server.line_v(@me, x, y, height, opts) def rect(x, y, width, height, opts \\ []), do: Server.rect(@me, x, y, width, height, opts) def circle(x0, y0, r, opts \\ []), do: Server.circle(@me, x0, y0, r, opts) def fill_rect(x, y, width, height, opts \\ []), do: Server.fill_rect(@me, x, y, width, height, opts) def get_dimensions(), do: Server.get_dimensions(@me) end end @doc """ Transfer the display buffer to the screen. You MUST call display() after drawing commands to make them visible on screen. """ @callback display() :: :ok @doc """ Transfer a data frame to the screen. The data frame format is equal to the display buffer that gets altered via the drawing commands. Calling this function transfers the data frame directly to the screen and does not alter the display buffer. """ @callback display_frame(data :: binary(), opts :: Server.display_frame_opts()) :: :ok @doc """ Transfer a raw data frame to the screen. A raw data frame is in a different format than the display buffer. To transform a display buffer to a raw data frame, `OLED.Display.Impl.SSD1306.translate_buffer/3` can be used. """ @callback display_raw_frame(data :: binary(), opts :: Server.display_frame_opts()) :: :ok @doc """ Clear the buffer. """ @callback clear() :: :ok @doc """ Clear the buffer putting all the pixels on certain state. """ @callback clear(pixel_state :: Server.pixel_state()) :: :ok @doc """ Override the current buffer which is the internal data structure that is sent to the screen with `c:display/0`. A possible use-case is to draw some content, get the buffer via `c:get_buffer/0` and set it again at a later time to save calls to the draw functions. """ @callback put_buffer(data :: binary()) :: :ok | {:error, term()} @doc """ Get the current buffer which is the internal data structure that is changed by the draw methods and sent to the screen with `c:display/0`. """ @callback get_buffer() :: {:ok, binary()} @doc """ Put a pixel on the buffer. The pixel can be on or off and be drawed in xor mode (if the pixel is already on is turned off). """ @callback put_pixel( x :: integer(), y :: integer(), opts :: Server.pixel_opts() ) :: :ok @doc """ Draw a line. """ @callback line( x1 :: integer(), y1 :: integer(), x2 :: integer(), y2 :: integer(), opts :: Server.pixel_opts() ) :: :ok @doc """ Draw an horizontal line (speed optimized). """ @callback line_h( x :: integer(), y :: integer(), width :: integer(), opts :: Server.pixel_opts() ) :: :ok @doc """ Draw a vertical line (speed optimized). """ @callback line_v( x :: integer(), y :: integer(), height :: integer(), opts :: Server.pixel_opts() ) :: :ok @doc """ Draw a rect """ @callback rect( x :: integer(), y :: integer(), width :: integer(), height :: integer(), opts :: Server.pixel_opts() ) :: :ok @doc """ Draw a circle Origin `(x0, y0)` with radius `r`. """ @callback circle( x0 :: integer(), y0 :: integer(), r :: integer(), opts :: Server.pixel_opts() ) :: :ok @doc """ Draw a filled rect """ @callback fill_rect( x :: integer(), y :: integer(), width :: integer(), height :: integer(), opts :: Server.pixel_opts() ) :: :ok @doc """ Get display dimensions """ @callback get_dimensions() :: { :ok, width :: integer(), height :: integer() } | {:error, term()} end
lib/oled/display.ex
0.923489
0.473292
display.ex
starcoder
defmodule Lemma.En.Nouns do @moduledoc false @nouns_set """ 'hood .22 0 1 1-dodecanol 1-hitter 10 100 1000 10000 100000 1000000 1000000000 1000000000000 11 11-plus 12 120 13 14 144 15 1530s 16 17 1728 1750s 1760s 1770s 1780s 1790s 18 1820s 1830s 1840s 1850s 1860s 1870s 1880s 1890s 19 1900s 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2 2-hitter 20 20/20 21 22 23 24 24/7 25 26 27 28 29 3 3-d 3-hitter 30 3d 3tc 4 4-hitter 40 401-k 4to 4wd 5 5-hitter 5-hydroxytryptamine 50 500 6 60 7 70 78 8 80 8vo 9 9-11 9/11 90 a a'man a-bomb a-horizon a-line a-list a-team a.e. aa aaa aachen aalborg aalii aalst aalto aar aardvark aardwolf aare aarhus aaron aarp aas aave ab aba abaca abacus abadan abalone abamp abampere abandon abandonment abarticulation abasement abashment abasia abatement abatis abator abattis abattoir abaya abb abbacy abbe abbess abbey abbot abbreviation abbreviator abc abc's abcoulomb abcs abdias abdication abdicator abdomen abdominal abdominocentesis abdominoplasty abdominousness abducens abducent abduction abductor abecedarian abecedarius abel abelard abele abelia abelmoschus abelmosk abenaki aberdare aberdeen aberrance aberrancy aberrant aberration abetalipoproteinemia abetment abettal abetter abettor abeyance abfarad abhenry abhorrence abhorrer abidance abidjan abience abies abila abilene ability abiogenesis abiogenist abiotrophy abjection abjuration abjurer abkhas abkhasian abkhaz abkhazia abkhazian ablactation ablation ablative ablaut able-bodiedism able-bodism ableism ablepharia ablism abls ablution abm abnaki abnegation abnegator abnormalcy abnormality abo abocclusion abode abohm abolishment abolition abolitionism abolitionist abomasum abomination abominator abor aboriginal aborigine abort aborticide abortifacient abortion abortionist abortus aboulia about-face above abracadabra abrachia abradant abrader abraham abramis abrasion abrasive abrasiveness abreaction abridgement abridger abridgment abrocoma abrocome abrogation abrogator abronia abruption abruptness abruzzi abs abscess abscissa abscission absconder abscondment abseil abseiler absence absentee absenteeism absentmindedness absinth absinthe absolute absoluteness absolution absolutism absolutist absolver absorbance absorbate absorbency absorbent absorber absorptance absorption absorptivity abstainer abstemiousness abstention abstinence abstinent abstract abstractedness abstracter abstraction abstractionism abstractionist abstractness abstractor abstruseness abstrusity absurd absurdity absurdness abudefduf abuja abukir abulia abundance abuse abuser abutilon abutment abutter abvolt abwatt abydos abyla abysm abyss abyssinia abyssinian ac acacia academe academia academic academician academicianship academicism academism academy acadia acadian acalypha acantha acanthaceae acanthion acanthisitta acanthisittidae acanthocephala acanthocephalan acanthocereus acanthocybium acanthocyte acanthocytosis acantholysis acanthoma acanthophis acanthopterygian acanthopterygii acanthoscelides acanthosis acanthuridae acanthurus acanthus acapnia acapulco acaracide acardia acariasis acaricide acarid acaridae acaridiasis acarina acarine acariosis acarophobia acarus acaryote acatalectic acataphasia acathexia acathexis acc accelerando acceleration accelerator accelerometer accent accenting accentor accentuation acceptability acceptableness acceptance acceptation acceptor access accessary accessibility accession accessory accho acciaccatura accidence accident accidental accipiter accipitridae accipitriformes acclaim acclamation acclimation acclimatisation acclimatization acclivity accolade accommodation accommodator accompaniment accompanist accompanyist accomplice accomplishment accord accordance accordion accordionist accouchement accoucheur accoucheuse account accountability accountancy accountant accountantship accounting accouterment accoutrement accra accreditation accretion accroides accrual accruement acculturation accumulation accumulator accuracy accusal accusation accusative accused accuser ace acebutolol acedia acephalia acephalism acephaly acer aceraceae acerbity acerola acervulus acetabulum acetal acetaldehyde acetaldol acetamide acetaminophen acetanilid acetanilide acetate acetin acetone acetonemia acetonuria acetophenetidin acetphenetidin acetum acetyl acetylation acetylcholine acetylene achaea achaean achaian ache achene acheron acherontia acheson acheta achievability achievement achiever achillea achilles achimenes aching achira achlorhydria achoerodus acholia achomawi achondrite achondroplasia achondroplasty achras achromasia achromaticity achromatin achromatism achromia achromycin achylia acicula acid acidemia acidification acidimetry acidity acidophil acidophile acidophilus acidosis acidulousness acinonyx acinos acinus acipenser acipenseridae ack-ack ackee acknowledgement acknowledgment aclant acme acne acnidosporidia acocanthera acokanthera acolyte aconcagua aconite aconitum acoraceae acorea acores acorn acorus acousma acoustic acoustician acousticophobia acoustics acquaintance acquaintanceship acquiescence acquirement acquirer acquiring acquisition acquisitiveness acquittal acquittance acragas acrasiomycetes acre acre-foot acreage acres acridid acrididae acridity acridness acridotheres acrilan acrimony acris acroanaesthesia acroanesthesia acrobat acrobates acrobatics acrocarp acrocarpus acrocephalus acrocephaly acroclinium acrocomia acrocyanosis acrodont acrogen acrolein acromegalia acromegaly acromicria acromikria acromion acromphalus acromyotonia acronym acrophobia acrophony acropolis acropora acrosome acrostic acrostichum acrylamide acrylate acrylic acrylonitrile acrylonitrile-butadiene-styrene act actaea acth actias actifed actin actinaria acting actinia actinian actiniaria actiniarian actinide actinidia actinidiaceae actiniopteris actinism actinium actinoid actinolite actinomeris actinometer actinometry actinomyces actinomycetaceae actinomycetales actinomycete actinomycin actinomycosis actinomyxidia actinomyxidian actinon actinopod actinopoda actinotherapy actinozoa actinozoan action actitis actium activase activating activation activator active activeness activewear activism activist activity actomyosin actor actress acts actualisation actuality actualization actuary actuation actuator acuity acular aculea aculeus acumen acupressure acupuncture acute acuteness acyclovir acyl acylation acylglycerol ad ad-lib ada ada-scid adactylia adactylism adactyly adad adage adagio adalia adam adam-and-eve adamance adamant adams adana adansonia adapa adapid adapin adaptability adaptation adapter adaption adaptor adar add add-in add-on addax addend addendum adder addict addiction addition additive addle-head addlehead address addressee addressograph adducer adducing adduct adduction adductor ade adelaide adelges adelgid adelgidae adelie aden adenanthera adenauer adenine adenitis adenium adenocarcinoma adenohypophysis adenoid adenoidectomy adenoma adenomegaly adenomyosarcoma adenomyosis adenopathy adenosine adenosis adenota adenovirus adept adeptness adequacy adequateness adermin adesite adh adhd adherence adherent adhesion adhesive adhesiveness adhocracy adiantaceae adiantum adience adieu adige adios adiposeness adiposis adiposity adirondacks adit aditi aditya adjacency adjective adjournment adjudication adjudicator adjunct adjunction adjuration adjuster adjustment adjustor adjutant adjuvant adlumia adman admass administration administrator administrivia admirability admirableness admiral admiralty admiration admirer admissibility admission admittance admixture admonisher admonishment admonition adnexa adnoun ado adobe adobo adolescence adolescent adonic adonis adoptee adopter adoption adorability adorableness adoration adorer adornment adoxography adp adps adrenal adrenalectomy adrenalin adrenaline adrenarche adrenergic adrenocorticotrophin adrenocorticotropin adrenosterone adrian adrianople adrianopolis adriatic adroitness adsorbate adsorbent adsorption adulation adulator adult adulterant adulteration adulterator adulterer adulteress adultery adulthood adumbration advance advancement advancer advantage advantageousness advection advent adventism adventist adventitia adventure adventurer adventuress adventurism adventurousness adverb adverbial adversary adversity advert advertence advertency advertisement advertiser advertising advertizement advertizer advertizing advertorial advice advil advisability advisee advisement adviser advisor advisory advocacy advocate advocator advowson adynamia adz adze adzhar adzharia aec aeciospore aecium aedes aegates aegean aegiceras aegilops aegina aegir aegis aegisthus aegospotami aegospotamos aegypiidae aegypius aegyptopithecus aeneas aeneid aengus aeolia aeolian aeolic aeolis aeolus aeon aeonium aepyceros aepyornidae aepyorniformes aepyornis aeration aerator aerial aerialist aerides aerie aerobacter aerobatics aerobe aerobics aerobiosis aerodontalgia aerodrome aerodynamics aeroembolism aerofoil aerogenerator aerogram aerogramme aerolite aerology aeromechanics aeromedicine aeronaut aeronautics aerophagia aerophilately aerophile aerophyte aeroplane aerosol aerospace aertex aery aeschylus aeschynanthus aesculapius aesculus aesir aesop aesthesia aesthesis aesthete aesthetic aesthetician aesthetics aestivation aether aethionema aethusa aetiologist aetiology aetobatus affability affableness affair affaire affairs affect affectation affectedness affection affectionateness affenpinscher afferent affiant affidavit affiliate affiliation affine affinity affirmation affirmative affirmativeness affirmed affirmer affix affixation afflatus affliction affluence affluent afforestation affray affricate affrication affricative affright affront affusion afghan afghani afghanistan afghanistani afibrinogenemia aficionado afisr afl afl-cio aflatoxin aflaxen afp aframomum afrasian africa african african-american africander afrikaans afrikander afrikaner afrl afro afro-american afro-asiatic afro-wig afroasiatic afrocarpus afropavo afspc after-shave afterbirth afterburner aftercare afterdamp afterdeck aftereffect afterglow afterimage afterlife aftermath afternoon afterpains afterpiece afters aftersensation aftershaft aftershock aftertaste afterthought afterworld ag aga agal agalactia agalactosis agalinis agama agamemnon agamete agamid agamidae agammaglobulinemia agamogenesis agapanthus agape agapornis agar agar-agar agaric agaricaceae agaricales agaricus agassiz agastache agate agateware agathis agavaceae agave agdestis agdistis age aged agedness agee ageing ageism agelaius agelessness agency agenda agendum agene agenesia agenesis agent agent-in-place agerasia ageratina ageratum aggeus agglomerate agglomeration agglomerator agglutination agglutinin agglutinogen aggrandisement aggrandizement aggravation aggravator aggregate aggregation aggregator aggression aggressiveness aggressor aggro agha aghan agility agincourt aging agio agiotage agism agitation agitator agitprop agkistrodon aglaia aglaomorpha aglaonema aglet agnail agnate agnatha agnathan agnation agni agnomen agnosia agnostic agnosticism agon agonidae agonist agonus agony agora agoraphobia agouti agra agranulocytosis agranulosis agrapha agraphia agreeability agreeableness agreement agribusiness agricola agriculturalist agriculture agriculturist agrigento agrimonia agrimony agriocharis agrippa agrippina agrobacterium agrobiology agrology agromania agronomist agronomy agropyron agrostemma agrostis agrypnia agua aguacate ague agueweed ahab ahem ahimsa ahpcrc ahriman ahuehuete ahura ahvenanmaa ai aiai aid aide aide-de-camp aide-memoire aides aidoneus aids aigina aiglet aigret aigrette aiguilette aiken aikido ail ailanthus aileron ailey ailment ailurophobia ailuropoda ailuropodidae ailurus aim aimlessness aioli air air-intake air-sleeve airbrake airbrush airburst airbus aircraft aircraftman aircraftsman aircrew aircrewman airdock airdrome airdrop aire airedale airfare airfield airflow airfoil airforce airframe airgun airhead airiness airing airlift airline airliner airlock airmail airmailer airman airmanship airplane airport airpost airs airscrew airship airsickness airspace airspeed airstream airstrip airwave airway airwoman airworthiness aisle aitchbone aix aix-la-chapelle aizoaceae ajaia ajax ajuga ak akaba akan akaryocyte akaryote akee aken akeridae akha akhbari akhenaten akhenaton akinesia akinesis akka akkadian akko akmola akron aku akvavit akwa'ala al al-asifa al-fatah al-hakim al-haytham al-hudaydah al-iraq al-jihad al-ma'unah al-magrib al-muhajiroun al-mukalla al-qa'ida al-qaeda al-qaida al-qur'an al- tawhid al-ummah ala alabama alabaman alabamian alabaster alacrity aladdin alalia alamo alanine alar alaric alarm alarmism alarmist alarum alaska alaskan alastrim alauda alaudidae alb albacore albania albanian albany albatrellus albatross albedo albee albers albert alberta alberti albigenses albigensianism albinism albino albion albite albizia albizzia alborg albuca albuginaceae albuginea albugo albula albulidae album albumen albumin albuminoid albuminuria albuquerque albuterol alca alcaeus alcahest alcaic alcalde alcapton alcaptonuria alcazar alcea alcedinidae alcedo alcelaphus alces alchemist alchemy alcibiades alcidae alcides alcohol alcoholic alcoholism alcott alcove alcyonacea alcyonaria alcyone aldactone aldebaran aldehyde aldehyde-alcohol alder alderfly alderman aldohexose aldol aldomet aldose aldosterone aldosteronism aldrovanda ale alecost alectis alecto alectoria alectoris alectura alehoof alehouse alembic alendronate alep aleph aleph-nought aleph-null aleph-zero alepisaurus aleppo alert alerting alertness aletris aleurites aleurone aleut aleutian aleutians aleve alewife alexander alexanders alexandria alexandrian alexandrine alexandrite alexia alexic aleyrodes aleyrodidae alfalfa alfilaria alfileria alfred alga algae algarobilla algarroba algarrobilla algebra algebraist alger algeria algerian algerie algeripithecus algidity algiers algin algol algolagnia algology algometer algometry algonkian algonkin algonquian algonquin algophilia algophobia algorism algorithm algren alhacen alhambra alhazen ali alias alibi alidad alidade alien alienage alienation alienator alienee alienism alienist alienor alignment alikeness aliment alimentation alimony alinement aliquant aliquot alir alisma alismales alismataceae alismatidae aliterate aliveness aliyah alizarin alizarine alka-seltzer alkahest alkalemia alkali alkalimetry alkalinity alkalinuria alkaliser alkalizer alkaloid alkalosis alkaluria alkane alkanet alkapton alkaptonuria alkene alkeran alky alkyd alkyl alkylbenzene alkylbenzenesulfonate alkyne all-rounder allah allamanda allantois allayer allegation allegement alleghenies allegheny allegiance allegoriser allegorizer allegory allegretto allegro allele allelomorph allemande allen allentown allergen allergist allergology allergy alleviant alleviation alleviator alley alleyway allgood allhallows allhallowtide alliaceae alliance alliaria allice allies alligator alligatorfish alligatoridae allionia allioniaceae allis alliteration alliterator allium allmouth alloantibody allocation allocator allocution allogamy allograft allograph allomerism allometry allomorph allopathy allopatry allophone allopurinol allosaur allosaurus allotment allotrope allotropism allotropy allowance alloy allspice allure allurement allusion allusiveness alluviation alluvion alluvium ally allyl alma-ata almanac almandine almandite almaty almighty almond almoner almoravid alms alms-giving almsgiver almsgiving alnico alnus alocasia aloe aloeaceae aloes aloha aloneness alonso aloofness alopecia alopecurus alopex alopiidae alopius alosa alouatta alp alpaca alpena alpenstock alpha alpha-adrenoceptor alpha-blocker alpha-interferon alpha- lipoprotein alpha-naphthol alpha-tocopheral alphabet alphabetisation alphabetiser alphabetization alphabetizer alphanumerics alphavirus alpinia alpinism alpinist alprazolam alps als alsace alsatia alsatian also-ran alsobia alsophila alstonia alstroemeria alstroemeriaceae alt altace altaic altair altar altarpiece altazimuth alterability alteration altercation altering alternanthera alternate alternation alternative alternator althaea althea altimeter altitude alto altocumulus altogether altoist altoona altostratus altruism altruist alula alum alumbloom alumina aluminate aluminium aluminum alumna alumnus alumroot alundum alupent alveolar alveolitis alveolus alyssum alytes alzheimer's alzheimers am amadavat amaethon amah amalgam amalgamation amalgamator amanita amanuensis amaranth amaranthaceae amaranthus amarelle amaretto amarillo amaryllidaceae amaryllis amastia amaterasu amateur amateurishness amateurism amati amativeness amatungulu amauropelta amaurosis amazement amazon amazona ambage ambages ambassador ambassadorship ambassadress amber amberbell amberboa amberfish ambergris amberjack ambiance ambidexterity ambidextrousness ambience ambiguity ambit ambition ambitiousness ambivalence ambivalency ambiversion amble ambler ambloplites amblygonite amblyopia amblyrhynchus ambo amboyna ambrose ambrosia ambrosiaceae ambulacrum ambulance ambulation ambulatory ambuscade ambush ambusher ambystoma ambystomatidae ambystomid amd ameba amebiasis amebiosis ameer ameiuridae ameiurus amelanchier amelia amelioration ameloblast amelogenesis amen amen-ra amenability amenableness amendment amends amenia amenities amenity amenorrhea amenorrhoea ament amentia amentiferae amercement america american americana americanisation americanism americanization americium amerind amerindian amethopterin amethyst ametria ametropia amex amhara amharic amia amiability amiableness amianthum amicability amicableness amide amidopyrine amigo amiidae amine amino aminoaciduria aminoalkane aminobenzine aminomethane aminopherase aminophylline aminoplast aminopyrine aminotransferase amiodarone amir amish amitosis amitriptyline amity amman ammeter ammine ammo ammobium ammodytes ammodytidae ammonia ammoniac ammonification ammonite ammonium ammoniuria ammonoid ammotragus ammunition amnesia amnesiac amnesic amnesty amnio amniocentesis amnion amnios amniota amniote amobarbital amoeba amoebiasis amoebida amoebina amoebiosis amon amon-ra amontillado amor amora amoralism amoralist amorality amorist amorousness amorpha amorphophallus amortisation amortization amos amount amour amoxicillin amoxil amoy amp amperage ampere ampere-hour ampere-minute ampere-second ampere-turn ampersand amphetamine amphibia amphibian amphibole amphibolips amphibolite amphibology amphiboly amphibrach amphicarpa amphicarpaea amphictyony amphidiploid amphidiploidy amphigory amphimixis amphineura amphioxidae amphioxus amphipod amphipoda amphiprion amphisbaena amphisbaenia amphisbaenidae amphitheater amphitheatre amphiuma amphiumidae amphora amphotericin ampicillin ampleness amplification amplifier amplitude ampoule ampul ampule ampulla amputation amputator amputee amrinone amsinckia amsonia amsterdam amulet amun amundsen amur amusd amusement amygdala amygdalaceae amygdalin amygdaloid amygdalotomy amygdalus amyl amylase amyloid amyloidosis amylolysis amylum amyotonia amyotrophia amyotrophy amytal amyxia an ana anabantidae anabaptism anabaptist anabas anabiosis anabolism anabrus anacanthini anacardiaceae anacardium anachronism anaclisis anacoluthia anacoluthon anaconda anacyclus anadenanthera anadiplosis anaemia anaerobe anaesthesia anaesthetic anaesthetist anagallis anagasta anaglyph anaglyphy anagnost anagoge anagram anagrams anagyris anaheim analbuminemia analecta analects analeptic analgesia analgesic analog analogist analogue analogy analphabet analphabetic analphabetism analysand analyser analysis analyst analyticity analyzer anamnesis anamorphism anamorphosis ananas ananias anapaest anapest anaphalis anaphase anaphor anaphora anaphrodisia anaphylaxis anaplasia anaplasmosis anaplasty anaprox anapsid anapsida anapurna anarchism anarchist anarchy anarhichadidae anarhichas anarthria anas anasa anasarca anasazi anaspid anaspida anastalsis anastatica anastigmat anastomosis anastomus anastrophe anastylosis anathema anathematisation anathematization anatidae anatolia anatolian anatomical anatomist anatomy anatotitan anatoxin anaxagoras anaximander anaximenes ancestor ancestress ancestry anchor anchorage anchorite anchorman anchorperson anchovy anchusa anchylosis ancient ancientness ancients ancistrodon ancohuma ancylidae ancylostomatidae ancylus andalucia andalusia andante andelmin andersen anderson andes andesite andira andiron andorra andorran andradite andreaea andreaeales andrena andrenid andrenidae andrew andrews andricus androecium androgen androgenesis androgeny androglossia androgyne androgyny android andromeda androphobia andropogon androsterone andryala andvari anecdote anecdotist aneides anemia anemography anemometer anemometry anemone anemonella anemopsis anencephalia anencephaly anergy aneroid anesthesia anesthesiologist anesthesiology anesthetic anesthetist anesthyl anestrum anestrus anethum aneuploidy aneurin aneurism aneurysm ang angara angas angel angelfish angelica angelim angelique angelology angelus anger angevin angevine angiitis angina angiocardiogram angiocarp angioedema angiogenesis angiogram angiography angiohemophilia angiologist angiology angioma angiopathy angioplasty angiopteris angiosarcoma angioscope angiosperm angiospermae angiotelectasia angiotensin angiotonin angle angledozer angler anglerfish anglesea anglesey anglewing angleworm anglia anglian anglican anglicanism anglicisation anglicism anglicization angling anglo-american anglo-catholicism anglo-french anglo-indian anglo-norman anglo-saxon anglomania anglophil anglophile anglophilia anglophobe anglophobia angola angolan angolese angora angostura angraecum angrecum angriness angst angstrom anguidae anguilla anguillan anguillidae anguilliformes anguillula anguis anguish angularity angulation angus angwantibo anhedonia anhidrosis anhima anhimidae anhinga anhingidae anhydride anhydrosis ani anigozanthus anil aniline anima animadversion animal animal-worship animalcule animalculum animalia animalisation animalism animality animalization animateness animation animatism animator animatronics anime animism animist animosity animus anion anionic anise aniseed aniseikonia anisette anisogamete anisogamy anisometropia anisoptera anisotremus anisotropy anjou ankara ankle anklebone anklet anklets ankus ankyloglossia ankylosaur ankylosaurus ankylosis anlage anna annaba annalist annals annam annamese annamite annapolis annapurna anne annealing annelid annelida annex annexa annexation annexe anniellidae annihilation annihilator anniversary annon annona annonaceae annotating annotation annotator announcement announcer annoyance annoyer annoying annual annualry annuitant annuity annulet annulment annulus annum annunciation annunciator annwfn annwn ano anoa anobiidae anode anodonta anodyne anoectochilus anoestrum anoestrus anogramma anointer anointing anointment anole anolis anomala anomalist anomalopidae anomalops anomalopteryx anomalousness anomaly anomia anomie anomiidae anomy anonym anonymity anopheles anopheline anopia anoplura anorak anorchia anorchidism anorchism anorectic anorexia anorexic anorgasmia anorthite anorthography anorthopia anosmia anostraca anouilh anova anovulant anovulation anoxemia anoxia anpu ans ansaid anselm anser anseres anseriformes anserinae anshar answer answerability answerableness answerer ant antabuse antacid antagonism antagonist antakiya antakya antalya antananarivo antapex antarctic antarctica antares antbird ante anteater antecedence antecedency antecedent antechamber antediluvian antedon antedonidae antefix antelope antenna antennaria antennariidae antepenult antepenultima antepenultimate anterior anteriority anteroom anthelminthic anthelmintic anthem anthemis anther antheraea anthericum antheridiophore antheridium antheropeas antherozoid anthesis anthidium anthill anthoceropsida anthoceros anthocerotaceae anthocerotales anthologist anthology anthonomus anthony anthophyllite anthophyta anthozoa anthozoan anthracite anthracosis anthrax anthriscus anthropocentricity anthropocentrism anthropogenesis anthropogeny anthropoid anthropoidea anthropolatry anthropologist anthropology anthropometry anthropomorphism anthropophagite anthropophagus anthropophagy anthroposophy anthurium anthus anthyllis anti anti- american anti-catholicism anti-inflammatory anti-intellectual anti-semite anti- semitism antiacid antiaircraft antialiasing antiarrhythmic antibacterial antibaryon antibiosis antibiotic antibody antic anticatalyst anticholinergic anticholinesterase antichrist anticipant anticipation anticipator anticlimax anticoagulant anticoagulation anticonvulsant anticyclone antidepressant antidiabetic antidiarrheal antidiuretic antido antidorcas antidote antielectron antiemetic antiepileptic antiestablishmentarianism antiestablishmentism antifeminism antifeminist antiferromagnetism antiflatulent antifreeze antifungal antigen antigone antigonia antigonus antigram antigua antiguan antihero antihistamine antihypertensive antiknock antilepton antilles antilocapra antilocapridae antilog antilogarithm antilope antimacassar antimalarial antimatter antimeson antimetabolite antimicrobial antimicrobic antimony antimuon antimycin antimycotic antineoplastic antineutrino antineutron antinode antinomasia antinomian antinomianism antinomy antioch antioxidant antiparticle antipasto antipathy antiperspirant antiphon antiphonal antiphonary antiphony antiphrasis antipodal antipode antipodes antipope antiproton antiprotozoal antipruritic antipsychotic antipyresis antipyretic antiquarian antiquark antiquary antique antiquity antiredeposition antirrhinum antisemitism antisepsis antiseptic antiserum antispasmodic antistrophe antisyphilitic antitauon antithesis antitoxin antitrade antitrades antitussive antitype antivenene antivenin antivert antiviral antler antlia antlion antofagasta antoninus antonius antony antonym antonymy antrozous antrum antum antwerp antwerpen anu anubis anunnaki anura anuran anuresis anuria anus anvers anvil anxiety anxiolytic anxiousness anzac anzio aorist aorta aortitis aotus aoudad apache apadana apalachicola apanage apar apartheid apartment apathy apatite apatosaur apatosaurus apatura apc ape ape-man apeldoorn apennines aper apercu aperea aperient aperitif aperture apery apex aphaeresis aphagia aphakia aphakic aphanite aphasia aphasic aphasmidia aphelion apheresis aphesis aphid aphididae aphidoidea aphis aphonia aphorism aphorist aphriza aphrodisia aphrodisiac aphrodite aphrophora aphyllanthaceae aphyllanthes aphyllophorales apia apiaceae apiarist apiary apiculture apiculturist apidae apios apis apishamore apium aplacophora aplacophoran aplasia aplectrum aplite aplodontia aplodontiidae aplomb aplysia aplysiidae apnea apoapsis apocalypse apocope apocrypha apocynaceae apocynum apodeme apodemus apodidae apodiformes apoenzyme apogamy apogee apogon apogonidae apoidea apojove apolemia apollinaire apollo apologetics apologia apologist apologue apology apolune apomict apomixis apomorphine aponeurosis apophasis apophatism apophthegm apophysis apoplexy apoptosis aporocactus aposelene aposiopesis apostasy apostate apostle apostleship apostrophe apothecary apothecium apothegm apotheosis appalachia appalachian appalachians appalling appaloosa appanage apparatchik apparatus apparel apparency apparentness apparition appeal appealingness appearance appearing appeasement appeaser appellant appellation appellative appendage appendectomy appendicectomy appendicitis appendicle appendicularia appendix appenzeller apperception appetence appetency appetiser appetisingness appetite appetizer appetizingness applauder applause apple applecart applejack applemint applesauce applet appleton applewood appliance applicability applicant application applicator applier applique appoggiatura appointee appointment apportioning apportionment appositeness apposition appraisal appraiser appreciation appreciativeness appreciator apprehender apprehension apprehensiveness apprentice apprenticeship apprisal appro approach approachability approaching approbation appropriateness appropriation appropriator approval approver approving approximation appurtenance apr apraxia apresoline apricot april apron apse apsis apsu aptenodytes apterygidae apterygiformes apteryx aptitude aptness apulia apus aqaba aqua aqua-lung aquaculture aqualung aquamarine aquanaut aquaphobia aquaplane aquarium aquarius aquatic aquatics aquatint aquavit aqueduct aquiculture aquifer aquifoliaceae aquila aquilege aquilegia aquinas aquitaine aquitania ar ara arab arab-berbers arabesque arabia arabian arabic arabidopsis arability arabis arabist araceae arachis arachnid arachnida arachnoid arachnophobia arafat aragon aragonite araguaia araguaya arak arales aralia araliaceae aram aramaean aramaic arame aramean aramus aranea araneae araneida araneus aranyaka arapaho arapahoe ararat arariba araroba aras arauca araucaria araucariaceae araujia arava arawak arawakan arawn araxes arb arbalest arbalist arbiter arbitrage arbitrager arbitrageur arbitrament arbitrariness arbitration arbitrator arbitrement arbor arboretum arboriculture arboriculturist arborist arborolatry arborvirus arborvitae arbour arbovirus arbutus arc arc- boutant arca arcade arcadia arcadian arcadic arcado-cyprians arcanum arccos arccosecant arccosine arccotangent arcdegree arcella arcellidae arceuthobium arch archaebacteria archaebacterium archaeobacteria archaeologist archaeology archaeopteryx archaeornis archaeornithes archaeozoic archaicism archaism archaist archangel archbishop archbishopric archdeacon archdeaconry archdiocese archduchess archduchy archduke archean archegonium archenteron archeobacteria archeologist archeology archeopteryx archeozoic archer archerfish archery archespore archesporium archetype archiannelid archiannelida archidiaconate archidiskidon archil archilochus archimandrite archimedes archine archipallium archipelago architect architectonics architecture architeuthis architrave archive archives archivist archness archosargus archosaur archosauria archosaurian archpriest archway arcidae arcminute arcsec arcsecant arcsecond arcsin arcsine arctan arctangent arctic arctictis arctiid arctiidae arctium arctocebus arctocephalus arctonyx arctostaphylos arctotis arcturus arcus arda ardea ardeb ardeidae ardennes ardisia ardor ardour ards arduousness are area areaway areca arecaceae arecidae areflexia arena arenaria arenaria-melanocephala arenaviridae arenavirus arendt arenga areola areopagite areopagus arequipa arere ares arete arethusa argal argali argasid argasidae argemone argent argentina argentine argentinian argentinidae argentinosaur argentite argil argillite arginine argiope argiopidae argive argle-bargle argo argon argonaut argonauta argonautidae argonne argonon argos argosy argot arguer arguing argument argumentation argun argus argusianus argy-bargy argyle argyll argynnis argyranthemum argyreia argyrodite argyrol argyrotaenia argyroxiphium arhant arhat arhus aria ariadne ariana arianism arianist arianrhod arianrod aricara aridity aridness aries arietta ariidae arikara aril arilus ariocarpus ariomma arioso arisaema arisarum arishth arista aristarchus aristocort aristocracy aristocrat aristolochia aristolochiaceae aristolochiales aristopak aristophanes aristotelean aristotelia aristotelian aristotelianism aristotle arithmancy arithmetic arithmetician arity arius arizona arizonan arizonian arjuna ark arkansan arkansas arkansawyer arles arlington arm arm-twisting armada armadillidiidae armadillidium armadillo armageddon armagnac armament armamentarium armature armband armchair armenia armenian armeria armet armful armguard armhole armiger armilla armillaria armillariella armin arming arminian arminianism arminius armistice armlet armoire armor armor-bearer armoracia armorer armory armour armourer armoury armpit armrest arms arms-runner armstrong army armyworm arng arnhem arnica arno arnold arnoseris aroid aroma aromatherapy arouet arousal arouser arp arpeggio arpent arquebus arrack arraignment arrangement arranger arranging arras array arrears arrest arrester arrhenatherum arrhenius arrhythmia arrival arrivederci arriver arriviste arroba arrogance arrogation arrogator arrow arrowhead arrowroot arrowsmith arrowworm arroyo arse arsehole arsenal arsenate arsenic arsenical arsenide arsenopyrite arsine arson arsonist art artamidae artamus artaxerxes artefact artemia artemis artemisia arteria arteriectasia arteriectasis arteriogram arteriography arteriola arteriole arteriolosclerosis arteriosclerosis arteritis artery artfulness arthralgia arthritic arthritis arthrocentesis arthrodesis arthrogram arthrography arthromere arthropathy arthroplasty arthropod arthropoda arthropteris arthroscope arthroscopy arthrospore arthur artichoke article articulateness articulatio articulation articulator artifact artifice artificer artificiality artillery artilleryman artiodactyl artiodactyla artisan artist artiste artistry artlessness artocarpus artois arts artsd artwork aruba arugula arui arulo arum arundinaria arundo aruru arvicola aryan arytaenoid arytenoid as asadha asafetida asafoetida asahikawa asala asama asamiya asana asanga asarabacca asarh asarum asbestos asbestosis ascaphidae ascaphus ascariasis ascaridae ascaridia ascaris ascendance ascendancy ascendant ascendence ascendency ascendent ascender ascending ascension ascent ascesis ascetic asceticism asch aschelminthes ascidiaceae ascidian ascii ascites asclepiad asclepiadaceae asclepias asclepius ascocarp ascolichen ascoma ascomycete ascomycetes ascomycota ascomycotina ascophyllum ascospore ascot ascription ascus asdic asean asepsis asexuality asgard ash ash-bin ash-key ash-pan ashbin ashcake ashcan ashe asheville ashir ashkenazi ashkhabad ashlar ashram ashton ashtoreth ashtray ashur ashurbanipal asia asian asiatic aside asilidae asimina asimov asin asininity asio asker asking asklepios asl asmara asmera asp aspadana aspalathus asparagaceae asparaginase asparagine asparagus aspartame aspect aspen asper aspergill aspergillaceae aspergillales aspergillosis aspergillus asperity aspersion aspersorium asperula asphalt asphodel asphodelaceae asphodeline asphodelus asphyxia asphyxiation asphyxiator aspic aspidelaps aspidiotus aspidistra aspidophoroides aspinwall aspirant aspirate aspiration aspirator aspirer aspirin aspis aspleniaceae asplenium ass ass-kisser assagai assailability assailant assam assamese assassin assassination assassinator assault assaulter assay assay-mark assayer assegai assemblage assembler assembling assembly assemblyman assemblywoman assent assenter assenting asserter assertion assertiveness assessee assessment assessor asset assets asseveration asseverator asshole assibilation assiduity assiduousness assignation assignee assigning assignment assignor assimilation assimilator assist assistance assistant assize assizes associability associableness associate associateship association associationism assonance assortment assouan assuagement assuan assumption assur assurance assurbanipal assuredness assyria assyrian assyriology astacidae astacura astacus astaire astana astarte astasia astatine aster asteraceae astereognosis asteridae asterion asterisk asterism asteroid asteroidea asterope asthenia asthenopia asthenosphere astheny asthma asthmatic astigmatism astigmia astilbe astonishment astor astragal astragalus astrakhan astrantia astraphobia astreus astringence astringency astringent astrobiology astrocyte astrodome astrodynamics astrogator astroglia astrolabe astrolatry astrologer astrologist astrology astroloma astrometry astronaut astronautics astronavigation astronium astronomer astronomy astrophysicist astrophysics astrophyton astropogon astuteness asuncion asur asura asurbanipal asvina asvins aswan asylum asymmetry asymptote asynchronism asynchrony asynclitism asyndeton asynergia asynergy asystole at at-bat atabrine atakapa atakapan atar ataractic atarax ataraxia ataraxis ataturk atavism atavist ataxia ataxy atayalic ate atelectasis ateleiosis ateles atelier ateliosis aten atenolol atf athabascan athabaskan athanasianism athanasius athanor athapascan athapaskan athar atharva- veda atheism atheist athelstan athena athenaeum athene atheneum athenian athens atherinidae atherinopsis atherodyde atherogenesis atheroma atherosclerosis atherurus athetosis athinai athiorhodaceae athlete athleticism athletics athodyd athos athrotaxis athyriaceae athyrium ativan atlanta atlantic atlantides atlantis atlas atm atmometer atmosphere atmospherics atole atoll atom atomisation atomiser atomism atomization atomizer aton atonalism atonality atonement atonia atonicity atony atopognosia atopognosis atopy atorvastatin atp atrazine atresia atreus atrichornis atrichornithidae atriplex atrium atrociousness atrocity atromid-s atropa atrophedema atrophy atropidae atropine atropos atrovent atsugewi attacapa attacapan attache attachment attack attacker attainability attainableness attainder attainment attalea attar attempt attempter attendance attendant attendee attender attending attention attentiveness attenuation attenuator attestant attestation attestator attester attestor attic attica atticus attila attilio attire attitude attlee attorney attorneyship attosecond attracter attraction attractiveness attractor attribute attribution attrition atypicality au auberge aubergine auc auchincloss auckland auction auctioneer aucuba audaciousness audacity audad auden audibility audible audibleness audience audile audio audiocassette audiogram audiology audiometer audiometry audiotape audiovisual audit audition auditor auditorium audubon aug augeas augend auger aught augite augmentation augmentin augur augury august augusta augustine augustinian augustus auk auklet aulacorhyncus aulostomidae aulostomus aum aunt auntie aunty aura aurelius aureolaria aureole aureomycin auricle auricula auriculare auricularia auriculariaceae auriculariales auriga auriparus auriscope aurochs aurora auroscope auschwitz auscultation auspex auspice auspices auspiciousness aussie austen austenite austereness austerity austerlitz austin austral australasia australia australian australopithecine australopithecus austria austria-hungary austrian austro-asiatic austrocedrus austronesia austronesian austrotaxus autacoid autarchy autarky auteur authentication authenticator authenticity author authoress authorisation authoriser authoritarian authoritarianism authorities authority authorization authorizer authorship autism auto auto-changer auto-da-fe auto-mechanic auto- suggestion autoantibody autobahn autobiographer autobiography autobus autocatalysis autochthon autochthony autoclave autocoid autocracy autocrat autocue autodidact autoeroticism autoerotism autofluorescence autofocus autogamy autogenesis autogenics autogeny autogiro autograft autograph autogyro autoimmunity autoinjector autolatry autoloader autolysis automaker automat automatic automation automatism automaton automeris automobile automobilist automysophobia autonomy autophyte autopilot autoplasty autopsy autoradiograph autoradiography autoregulation autosexing autosome autostrada autosuggestion autotelism autotomy autotroph autotype autotypy autumn auvergne auxesis auxiliary auxin av avadavat avahi avail availability availableness avalanche avalokiteshvara avalokitesvara avant-garde avaram avarice avariciousness avaritia avatar avena avenger avens aventail aventurine avenue average averageness averment averrhoa averroes aversion averting aves avesta avestan aviary aviation aviator aviatress aviatrix avicenna avicennia avicenniaceae avidity avidness avifauna avignon avionics avitaminosis avo avocado avocation avocet avogadro avoidance avoirdupois avon avouchment avowal avower avulsion awakening award awarding awareness awayness awe awfulness awkwardness awl awlwort awn awning awol ax axe axerophthol axil axilla axiology axiom axis axle axletree axolemma axolotl axon axone axseed ayah ayapana ayatollah aye-aye ayin ayr ayrshire aythya ayurveda az azactam azadirachta azadirachtin azalea azaleastrum azathioprine azedarach azederach azerbaijan azerbaijani azerbajdzhan azeri azide azimuth azithromycin azoimide azolla azollaceae azores azotaemia azote azotemia azoturia azt aztec aztecan aztreonam azure azurite azymia b b-52 b-girl b-horizon b-meson b.o. b.t.u. b.th.u. ba baa baa-lamb baal baas baba babar babassu babbitt babbitting babble babbler babbling babe babel babesiidae babies'-breath babinski babiroussa babirusa babirussa babka baboo baboon babu babushka baby baby-sitter baby-walker babyhood babylon babylonia babylonian babyminder babyrousa babysitter babysitting babytalk bacca baccalaureate baccarat bacchanal bacchanalia bacchant bacchante baccharis bacchus baccy bach bachelor bachelor-at-arms bachelorette bachelorhood bacillaceae bacillariophyceae bacillus bacitracin back back-blast back-formation back-number backache backband backbeat backbench backbencher backbend backbiter backblast backboard backbone backchat backcloth backdoor backdown backdrop backer backfield backfire backflow backflowing backgammon background backgrounder backgrounding backhand backhander backhoe backing backlash backlighting backlog backpack backpacker backpacking backplate backrest backroom backsaw backscratcher backseat backsheesh backside backslapper backslider backsliding backspace backspacer backspin backstage backstairs backstay backstitch backstop backstroke backstroker backswimmer backsword backtalk backup backwardness backwash backwater backwoods backwoodsman backyard bacon bacteremia bacteria bacteriacide bacteriaemia bactericide bacteriemia bacteriochlorophyll bacteriologist bacteriology bacteriolysis bacteriophage bacteriostasis bacteriostat bacterium bacteroid bacteroidaceae bacteroides bad badaga baddeleyite baddie bade badge badger badgerer badgering badinage badlands badminton badness baeda baedeker baffle baffled bafflement bag bagascosis bagasse bagassosis bagatelle bagdad bagel bagful baggage baggageman bagger bagging baghdad bagman bagnio bagpipe bagpiper baguet baguette bahai bahaism bahamas bahamian bahasa bahrain bahraini bahrein bahreini baht bai baic baikal bail bailee bailey bailiff bailiffship bailiwick bailment bailor bain-marie baiomys bairava bairdiella bairiki bairn baisa baisakh bait baiting baiza baize bakeapple bakehouse bakelite baker bakersfield bakery bakeshop baking baklava baksheesh bakshis bakshish baku bakunin balaclava balaena balaeniceps balaenicipitidae balaenidae balaenoptera balaenopteridae balagan balalaika balance balancer balanchine balancing balanidae balanitis balanoposthitis balanus balarama balas balata balaton balboa balbriggan balcony baldachin balder balderdash baldhead baldness baldpate baldr baldric baldrick baldwin baldy bale baleen balefire balefulness balenciaga balfour bali balibago balinese balistes balistidae balk balkan balkans balker balkiness balkline ball ball-breaker ball- buster ballad ballade balladeer ballast ballcock balldress ballerina ballet balletomane balletomania ballgame ballista ballistics ballistite ballistocardiogram ballistocardiograph ballock balloon balloonfish ballooning balloonist ballot ballota balloting ballottement ballpark ballpen ballplayer ballpoint ballroom balls-up ballup ballyhoo balm balminess balmoral balochi baloney balsa balsam balsaminaceae balsamorhiza balsamroot balthasar balthazar baltic baltic-finnic baltimore balto-slavic balto-slavonic baluchi baluster balusters balustrade balzac bam bamako bambino bamboo bambusa bambuseae ban banality banana band bandage bandaging bandana bandanna bandbox bandeau bandelet bandelette banderilla banderillero bandicoot banding bandit banditry bandleader bandlet bandmaster bandoleer bandolier bandoneon bandsaw bandsman bandstand bandtail bandung bandwagon bandwidth bandyleg bane baneberry banff bang bangalore banger bangiaceae banging bangkok bangla bangladesh bangladeshi bangle bangor bangtail bangui banian banishment banister banjo banjul bank bankbook banker bankhead bankia banking banknote bankroll bankrupt bankruptcy banks banksia banner banneret banning banning-order bannister bannock bannockburn banns banquet banqueting banquette banshee banshie bantam bantamweight banteng banter banting bantu banyan banzai baobab bap baphia baptisia baptism baptist baptistery baptistry baptists bar baraka baranduki barany barb barbacan barbadian barbados barbarea barbarian barbarisation barbarism barbarity barbarization barbarossa barbarousness barbary barbasco barbecue barbecuing barbel barbell barbeque barber barberry barbershop barbet barbette barbican barbital barbitone barbiturate barbu barbuda barbwire barcarole barcarolle barcelona bard bardeen bardolatry bareboat bareboating bareness barf bargain bargainer bargaining barge bargee bargello bargeman bari barilla baring barish barite baritone barium bark bark-louse barkeep barkeeper barker barkley barley barley-sugar barleycorn barm barmaid barman barmbrack barn barnacle barnburner barndoor barnful barnstormer barnum barnyard barograph barometer baron baronage baronduki baroness baronet baronetage baronetcy barong barony baroque baroqueness baroreceptor barosaur barosaurus barouche barque barrack barracking barracouta barracuda barrage barramundi barranquilla barrater barrator barratry barrel barrelfish barrelful barrelhouse barrels barren barrenness barrenwort barrette barretter barricade barrie barrier barring barrio barrister barroom barrow barrow-boy barrow-man barrowful barrymore bars barstow bart bartender barter barterer barth barthelme bartholdi bartholin bartlesville bartlett bartok bartonia bartramia baruch barunduki barycenter barye baryon baryshnikov baryta barytes barytone basalt bascule base baseball baseboard basel baseline basement baseness basenji bash bashfulness basia basic basics basidiocarp basidiolichen basidiomycete basidiomycetes basidiomycota basidiomycotina basidiospore basidium basil basileus basilica basilicata basiliscus basilisk basin basinet basinful basis basket basketball basketeer basketful basketmaker basketry basketweaver basle basophil basophile basophilia basotho basque basra bass bassariscidae bassariscus bassarisk basse-normandie basset basseterre bassia bassine bassinet bassist basso bassoon bassoonist basswood bast bastard bastardisation bastardization bastardy baste baster bastille bastinado basting bastion bastnaesite bastnasite basuco basuto basutoland bat bata bataan batch batfish bath bathe bather bathhouse bathing batholite batholith bathometer bathos bathrobe bathroom bathsheba bathtub bathyergidae bathyergus bathymeter bathymetry bathyscape bathyscaph bathyscaphe bathysphere batidaceae batik batis batiste batman batna batoidei baton batrachia batrachian batrachoididae batrachomyomachia batrachoseps batsman batswana battalion batten batter battercake battering battery battery-acid batting battle battle-ax battle-axe battledore battlefield battlefront battleground battlement battler battleship battlesight battlewagon battue batwing bauble baud baudelaire bauhaus bauhinia baulk baulk-line baulker baum bauxite bavaria bavarian bawbee bawd bawdiness bawdry bawdy bawdyhouse bawler bawling bay baya bayard bayat bayberry baycol bayer bayes baykal bayonet bayonne bayou bayrut bazaar bazar bazooka bb bbl bbs bd bdellium be beach beachball beachcomber beachfront beachhead beachwear beacon bead beading beadle beads beadsman beadwork beagle beagling beak beaker beam beam-ends bean beanbag beanball beaner beanfeast beanie beano beanstalk beantown beany bear bearberry bearcat beard bearer bearing bearnaise bearskin bearwood beast beastliness beat beater beatification beating beatitude beatles beatnik beatniks beatrice beats beau beaugregory beaujolais beaumont beaumontia beaut beauteousness beautician beautification beauty beauvoir beaver beaverbrook bebop bechamel bechuana beck becket beckett beckley becomingness becquerel bed bed- and-breakfast bed-ground bed-wetting beda bedbug bedchamber bedclothes bedcover bedder bedding bede bedesman bedevilment bedfellow bedframe bedground bedlam bedlamite bedouin bedpan bedpost bedrest bedrock bedroll bedroom bedside bedsit bedsitter bedsore bedspread bedspring bedstead bedstraw bedtime beduin bedwetter bee beebalm beebread beech beecher beechnut beechwood beef beefalo beefburger beefcake beefeater beefsteak beefwood beehive beekeeper beekeeping beeline beelzebub beep beeper beer beerbohm beeswax beet beethoven beetle beetleweed beetroot befooling befoulment befuddlement begetter beggar beggar's-ticks beggar-my-neighbor beggar-my-neighbour beggar-ticks beggarman beggarweed beggarwoman beggary begging begin beginner beginning begonia begoniaceae beguilement beguiler beguine begum behalf behavior behaviorism behaviorist behaviour behaviourism behaviourist beheading behemoth behest behind behmen behmenism beholder beholding behrens behring beige beigel beignet beijing being beingness beira beirut bel bel-merodach belamcanda belarus belarusian belau belay belch belching beldam beldame beleaguering belem belemnite belemnitidae belemnoidea belfast belfry belgian belgique belgium belgrade belief believability believer believing belisarius belittling belize bell bell-bottoms belladonna bellarmine bellarmino bellbird bellboy belle bellerophon belles- lettres bellflower bellhop bellicoseness bellicosity belligerence belligerency belligerent belling bellingham bellini bellis bellman belloc bellow bellower bellowing bellows bellpull bellwether bellwort belly bellyache bellyacher bellyband bellybutton bellyful belmont belonging belongings belonidae belorussia belorussian belostomatidae beloved belsen belshazzar belt belting beltway beluga belvedere bema bemidji bemisia bemusement ben benadryl bench benchley benchmark bend bendability bender bending bendopa bends benedick benedict benedictine benediction benefaction benefactor benefactress benefice beneficence beneficiary beneficiation benefit benelux benet benevolence bengal bengali benghazi benignancy benignity benin beninese benison <NAME> bennet bennett bennettitaceae bennettitales bennettitis benni bennie bennington benniseed benny bent bent-grass bentham benthos benton bentonite bentwood benweed benzedrine benzene benzine benzoate benzocaine benzodiazepine benzofuran benzoin benzol benzoquinone benzyl benzylpenicillin beograd beowulf bequest berating berber berberidaceae berberis berbers berceuse bercy bereaved bereavement beret berg bergall bergamot bergen bergenia bergman bergson beria beriberi bering berit berith berk berkeley berkelium berkshire berkshires berlage berlin berliner berlioz berm bermuda bermudan bermudas bermudian bern bernard berne bernhardt bernini bernoulli bernstein beroe berra berretta berry berserk berserker berteroa berth bertholletia bertillon bertolucci berycomorphi beryl beryllium berzelius besieger besieging besom bessel bessemer bessera besseya best bestiality bestiary bestowal bestower bestowment bestseller bet beta beta- adrenoceptor beta-carotene beta-interferon beta-lactamase beta-lipoprotein beta- naphthol betaine betatron betel betelgeuse beth bethe bethel bethlehem bethlehem-judah bethune betise betrayal betrayer betrothal betrothed better betterment bettong bettongia bettor betula betulaceae betweenbrain bevatron bevel beverage beveridge bevin bevy bewilderment bewitchery bewitchment bextra bey bezant bezel bezique bezzant bh bhadon bhadrapada bhaga bhagavad-gita bhagavadgita bhakti bhang bharat bhutan bhutanese bhutani bi bialy bialystoker bias bib bib-and-tucker bible bible-worship bibliographer bibliography bibliolatry bibliomania bibliophile bibliopole bibliopolist bibliothec bibliotheca bibliotics bibliotist bibos bicarbonate bicentenary bicentennial biceps bichloride bichromate bicker bickering bicorn bicorne bicuspid bicycle bicycle-built-for-two bicycler bicycling bicyclist bid bida bidder bidding biddy bidens bidet biennial bier bierce biff bifocals bifurcation bigamist bigamy bigarade bigeye bigfoot biggin bighead bigheartedness bighorn bight bigness bignonia bignoniaceae bignoniad bigos bigot bigotry bigram bigwig bihar bihari bijou bike bikers bikini bilabial bilateralism bilaterality bilberry bilby bile bilestone bilge bilges bilgewater bilharzia bilharziasis bilimbi bilingual bilingualism bilingualist biliousness bilirubin bill billabong billboard billet billfish billfold billhook billiards billing billings billingsgate billion billionaire billionth billow billy billy-ho billyo billyoh billystick bilocation biloxi bilsted biltong bimbo bimester bimetal bimetallism bimetallist bimillenary bimillennium bimli bimonthly bin binary bind binder bindery binding bindweed bine binet binful binge binger binghamton bingle bingo binnacle binoculars binomial binturong bio-assay bioarm bioassay bioattack biocatalyst biochemist biochemistry biochip bioclimatology biodefence biodefense biodiversity bioelectricity bioengineering bioethics biofeedback bioflavinoid biogenesis biogeny biogeography biographer biography biohazard bioko biologism biologist biology bioluminescence biomass biome biomedicine biometrics biometry bionics bionomics biont biophysicist biophysics biopiracy biopsy bioremediation biosafety bioscience bioscope biosphere biostatistics biosynthesis biosystematics biosystematy biota biotech biotechnology bioterrorism biotin biotite biotype bioweapon biped bipedalism biplane biprism biquadrate biquadratic birch birchbark bird bird-on-the-wing bird-scarer birdbath birdbrain birdcage birdcall birder birdfeeder birdhouse birdie birdlime birdnest birdnesting birdseed birdsong birefringence biretta biriani birling birmingham biro birr birretta birth birthday birthing birthmark birthplace birthrate birthright birthroot birthwort biryani bisayan bisayas biscuit biscutella bise bisection bisexual bisexuality bishkek bishop bishopric bishopry biskek bismarck bismark bismuth bison bisque bissau bister bistre bistro bit bitartrate bitch bitchery bitchiness bite biteplate biter bitewing bithynia bitis bitmap bitok bitstock bitt bittacidae bitter bitter-bark bittercress bittern bitterness bitternut bitterroot bitters bittersweet bitterweed bitterwood bitthead bitumastic bitumen biu-mandara bivalve bivalvia bivouac bivouacking biweekly biz bizarreness bize bizet bja bjs bk blabber blabbermouth blaberus black blackamoor blackball blackbeard blackbeetle blackberry blackberry-lily blackbird blackboard blackbody blackbuck blackburn blackcap blackcock blackdamp blackening blackface blackfish blackfly blackfoot blackfriar blackguard blackhead blackheart blacking blackjack blackleg blacklist blackmail blackmailer blackness blackout blackpoll blackpool blacksburg blackseed blackshirt blacksmith blacksnake blacktail blackthorn blacktop blacktopping blackwash blackwater blackwood bladder bladdernose bladderpod bladderwort bladderwrack blade blaeberry blah blahs blain blair blake blame blamelessness blameworthiness blanc blancmange blandfordia blandishment blandness blank blanket blankness blanquillo blantyre blare blarina blaring blarney blasphemer blasphemy blast blastema blaster blastocele blastocladia blastocladiales blastocoel blastocoele blastocyst blastocyte blastocytoma blastoderm blastodiaceae blastodisc blastoff blastogenesis blastoma blastomere blastomyces blastomycete blastomycosis blastopore blastosphere blastula blatancy blather blatherskite blatta blattaria blattella blattidae blattodea blaxploitation blaze blazer blazing blazon blazonry bleach bleacher bleachers bleakness bleat bleb blechnaceae blechnum bleeder bleeding bleep blemish blend blende blender blending blenheim blenniidae blennioid blennioidea blennius blenny blepharism blepharitis blepharospasm blephilia bleriot blessedness blessing blether bletia bletilla bleu blewits blida bligh blighia blight blighter blighty blimp blind blinder blindfold blindness blindworm bling blini blink blinker blinking blinks blintz blintze bliny blip bliss blissfulness blissus blister blistering blitheness blitt blitz blitzkrieg blitzstein blixen blizzard bloat bloater blob bloc blocadren bloch block blockade blockade-runner blockage blockbuster blocker blockhead blockhouse blocking bloemfontein blog blogger blok bloke blolly blond blonde blondness blood blood-twig bloodbath bloodberry bloodguilt bloodhound bloodiness bloodleaf bloodletting bloodline bloodlust bloodmobile bloodroot bloodshed bloodstain bloodstock bloodstone bloodstream bloodsucker bloodthirstiness bloodworm bloodwort bloom bloomer bloomeria bloomers bloomfield blooming bloomington bloomsbury blooper blossom blossoming blot blotch blotter blouse blow blowback blowball blower blowfish blowfly blowgun blowhard blowhole blowing blowjob blowlamp blowout blowpipe blowtorch blowtube blowup blt blu-82 blubber blubberer blucher bludgeon bludgeoner blue blue-belly blue-blindness bluebeard bluebell blueberry bluebill bluebird bluebonnet bluebottle bluecoat bluefin bluefish bluegill bluegrass bluehead blueing bluejacket blueness bluenose bluepoint blueprint blues bluestem bluestocking bluestone bluethroat bluetick bluetongue blueweed bluewing bluff bluffer bluffness bluing blunder blunderbuss blunderer bluntness blur blurb blurriness blush blusher bluster blusterer bm bmdo bmi bmr bmus bns bo's'n bo'sun boa boann boar board boarder boarding boardinghouse boardroom boards boardwalk boarfish boarhound boast boaster boastfulness boasting boat boatbill boatbuilder boater boathouse boating boatload boatman boatmanship boatswain boatyard bob bobber bobbin bobble bobby bobby-socker bobbysock bobbysocks bobbysoxer bobcat bobfloat bobolink bobsled bobsledding bobsleigh bobtail bobwhite boccaccio bocce bocci boccie bocconia boche bock bod boddhisatva bodega bodensee bodhisattva bodice boding bodkin bodo-garo bodoni body body-build bodybuilder bodybuilding bodyguard bodywork boehm boehme boehmenism boehmeria boell boeotia boer boethius boeuf boffin bog bogart bogbean bogey bogeyman bogie bogmat bogota bogy bohemia bohemian bohemianism bohme bohr bohrium boidae boil boiler boilerplate boilersuit boiling boise boisterousness bokkos bokmaal bokmal bola bolanci bolbitis bold boldface boldness bole bolero boletaceae bolete boletellus boletus boleyn bolide bolingbroke bolivar bolivia bolivian boliviano boll bollard bollock bollworm bollywood bolo bologna bologram bolograph bolometer boloney bolshevik bolshevism bolshevist bolshie bolshy bolster bolt bolt-hole bolti boltonia boltzmann bolus bolzano bomarea bomb bombacaceae bombard bombardier bombardment bombardon bombast bombax bombay bombazine bomber bombie bombilation bombina bombination bombing bomblet bombproof bombshell bombsight bombus bombycid bombycidae bombycilla bombycillidae bombyliidae bombyx bonaire bonanza bonaparte bonasa bonavist bonbon bonce bond bondage bondholder bonding bondmaid bondman bondsman bondswoman bonduc bondwoman bone bonefish bonehead bonelet bonemeal boner bones boneset bonesetter boneshaker bonete bonfire bong bongo bonheur bonhoeffer bonhomie boniface boniness bonito bonn bonnet bonnethead bonney bonobo bonsai bontemps bonus bonxie bonyness boo boo- boo boob booboisie booby boodle booger boogeyman boogie boogie-woogie book bookbinder bookbindery bookbinding bookcase bookclub bookdealer bookend booker bookfair bookie booking bookishness bookkeeper bookkeeping booklet booklouse booklover bookmaker bookman bookmark bookmarker bookmobile bookplate bookseller bookshelf bookshop bookstall bookstore bookworm boole boom boomer boomerang boon boondocks boondoggle boone boor boorishness boost booster boot bootblack bootboys bootee bootes booth boothose bootie bootjack bootlace bootleg bootlegger bootlegging bootlicker bootmaker bootstrap booty booyong booze booze- up boozer boozing bop bopeep borage boraginaceae borago borassus borate borax bordeaux bordelaise bordello border borderer borderland borderline bore bore- hole boreas borecole boredom borer borges borgia boring boringness born bornean borneo bornite borodin borodino boron borosilicate borough borrelia borrower borrowing borsch borscht borsh borshch borsht borstal bortsch borzoi bos bos'n bosc bosch bose boselaphus bosh bosie bosk bosnia bosnia-herzegovina bosom boson bosporus boss bossism boston bostonian bosun boswell boswellia bot bota botanical botanist botany botaurus botch botcher botfly bother botheration bothidae bothrops botox botrychium botswana botticelli bottle bottle-grass bottle-tree bottlebrush bottlecap bottleful bottleneck bottlenose bottler bottom bottom-dweller bottom-feeder bottomland bottomlessness botulin botulinum botulinus botulism botulismotoxin bouchee boucle boudoir bouffant bouffe bougainvillaea bougainville bougainvillea bough bouillabaisse bouillon boulder boule boulevard boulevardier boulez boulle bounce bouncer bounciness bouncing bound boundary boundedness bounder boundlessness bounds bounteousness bountifulness bounty bouquet bourbon bourdon bourgeois bourgeoisie bourgogne bourguignon bourn bourne bourse bourtree boustrophedon bout bouteloua boutique boutonniere bouvines bouyei bovid bovidae bovinae bovine bovini bovril bow bow- tie bow-wow bowditch bowdler bowdlerisation bowdleriser bowdlerism bowdlerization bowdlerizer bowel bowels bower bowerbird bowery bowfin bowhead bowie bowiea bowing bowknot bowl bowlder bowleg bowler bowlful bowline bowling bowls bowman bowsprit bowstring bowtie box boxberry boxcar boxcars boxer boxers boxershorts boxfish boxful boxing boxthorn boxwood boy boycott boyfriend boyhood boyishness boykinia boyle boyne boys-and-girls boysenberry bozeman bozo bph bpi bpm bps br bra brace bracelet bracer bracero braces brachiation brachinus brachiopod brachiopoda brachium brachycephalic brachycephalism brachycephaly brachychiton brachycome brachydactylia brachydactyly brachystegia brachyura brachyuran bracing bracken bracket brackishness bract bracteole bractlet brad bradawl bradbury bradford bradley bradstreet brady bradycardia bradypodidae bradypus brae brag braga brage bragg braggadocio braggart bragger bragging bragi brahe brahma brahman brahmana brahmanism brahmaputra brahmi brahmin brahminism brahms brahui braid braiding brail braille brain brain-fag brain-stem brain- teaser brain-worker braincase brainchild brainiac brainpan brainpower brainstem brainstorm brainstorming brainwashing brainwave brainworker braising brake brakeman brakes brama bramante bramble brambling bramidae bran branch branchia branching branchiobdella branchiobdellidae branchiopod branchiopoda branchiopodan branchiostegidae branchiostomidae branchiura branchlet brancusi brand brand-newness brandenburg branding brandish brandt brandy brandyball brandysnap brant branta braque brasenia brashness brasier brasil brasilia brasov brass brassard brassavola brasserie brassia brassica brassicaceae brassie brassiere brat bratislava brattice brattleboro bratwurst braun braunschweig bravado brave braveness bravery bravo bravura brawl brawler brawn brawniness bray brazenness brazier brazil brazilian brazilwood brazos brazzaville breach bread bread-bin bread-stick breadbasket breadboard breadbox breadcrumb breadfruit breadline breadroot breadstick breadstuff breadth breadwinner break break-axe break-in breakability breakable breakableness breakage breakaway breakax breakaxe breakdown breaker breakers breakfast breaking breakout breakstone breakthrough breakup breakwater bream breast breastbone breastpin breastplate breaststroke breaststroker breastwork breath breathalyser breathalyzer breather breathing breathlessness breccia brecht breech breechblock breechcloth breechclout breeches breechloader breed breeder breeding breeze breeziness bregma breiz bremen bremerhaven bren brent brescia breslau brest bretagne brethren breton breuer breughel breve brevet breviary brevibloc brevicipitidae brevity brevoortia brew brewage brewer brewery brewing brewpub brezhnev briar briard briarroot briarwood bribe briber bribery bric-a-brac brick brickbat brickellia brickfield brickkiln bricklayer bricklaying brickwork brickyard bricole bridal bridal-wreath bride bride-gift bride-to-be bridecake bridegroom bridesmaid bridge bridged-t bridgehead bridgeport bridges bridget bridgetown bridgework bridle bridoon brie brief briefcase briefing briefness briefs brier brier-wood brierpatch brierwood brig brigade brigadier brigand brigandine brigantine brightness brighton brigid brigit brihaspati brill brilliance brilliancy brilliantine brim brimstone brindisi brine bringing brininess brinjal brink brinkmanship brinton briny brio brioche briony brioschi briquet briquette bris brisance brisbane brisket briskness brisling briss bristle bristlegrass bristletail bristliness bristol brit britain britches brith briticism british britisher britishism briton brits britt brittanic brittany britten brittle brittle-star brittlebush brittleness brno broach broad broad- bean broad-mindedness broadax broadaxe broadbill broadcast broadcaster broadcasting broadcloth broadening broadloom broadness broadsheet broadside broadsword broadtail broadway brobdingnag broca brocade brocadopa broccoli brochette brochure brocket brockhouse brodiaea brogan broglie brogue broil broiler broiling brokenheartedness broker broker-dealer brokerage brolly bromberg brome bromegrass bromelia bromeliaceae bromeosin bromide bromine bromo- seltzer bromoform bromus bronc bronchiole bronchiolitis bronchitis broncho bronchodilator bronchopneumonia bronchoscope bronchospasm bronchus bronco broncobuster bronte brontosaur brontosaurus bronx bronze brooch brood brooder brooding broodmare broody brook brooke brooklet brooklime brooklyn brooks brookweed broom broom-weed broomcorn broomstick broomweed brosmius broth brothel brother brother-in-law brotherhood brotula brotulidae brougham brouhaha broussonetia brow browallia brown browne brownie browning brownness brownout brownshirt brownstone brownsville browntail browse browser browsing bruce brucella brucellosis bruch bruchidae bruchus brucine bruckenthalia bruckner bruegel brueghel bruges brugmansia bruin bruise bruiser brule brumaire brummagem brummell brummie brummy brunanburh brunch brunei bruneian brunelleschi brunet brunette brunfelsia brunhild brunn brunnhilde bruno brunswick brunt brusa brush brush-off brushing brushup brushwood brushwork brusqueness brussels brutalisation brutality brutalization brute brutus bruxelles bruxism brya bryaceae bryales bryan bryanthus brynhild bryony bryophyta bryophyte bryopsida bryozoa bryozoan brythonic bryum bs bsarch bse btu bubalus bubble bubblejet bubbler bubbliness bubbly buber bubo bubulcus buccaneer buccaneering buccinidae bucconidae buccula bucephala buceros bucerotidae buchanan bucharest bucharesti buchenwald buchloe buchner buck buck-and-wing buckaroo buckbean buckboard buckeroo bucket bucketful buckeye buckle buckler buckleya buckminsterfullerene buckram bucksaw buckshot buckskin buckskins buckthorn bucktooth buckwheat buckyball bucolic bucuresti bud budapest buddha buddhism buddhist budding buddleia buddy budge budgereegah budgerigar budgerygah budget budgie budorcas buff buffalo buffalofish buffer bufferin buffet buffeting bufflehead buffoon buffoonery bufo bufonidae bug bug-hunter bugaboo buganda bugbane bugbear bugger buggery bugginess buggy bugle bugler bugleweed bugloss bugologist bugology buhl build builder building buildup bujumbura bukharin bulawayo bulb bulbil bulblet bulbul bulgaria bulgarian bulge bulghur bulginess bulgur bulimarexia bulimia bulimic bulk bulkhead bulkiness bull bull's-eye bull-snake bulla bullace bullbat bullbrier bulldog bulldozer bullet bullethead bulletin bullfight bullfighter bullfighting bullfinch bullfrog bullhead bullheadedness bullhorn bullion bullnose bullock bullpen bullring bullrush bullshit bullshot bullterrier bully bullyboy bullying bulnesia bulrush bultmann bulwark bulwer-lytton bum bumblebee bumbler bumboat bumelia bumf bummer bump bumper bumph bumpiness bumpkin bumptiousness bun bun-fight buna bunce bunch bunchberry bunche bunchgrass bunco buncombe bundesbank bundle bundling bunfight bung bungalow bungarus bungee bunghole bungle bungler bunion bunji-bunji bunk bunker bunkmate bunko bunkum bunny buns bunsen bunt buntal bunter bunting bunuel bunyan bunyaviridae bunyavirus buoy buoyancy buphthalmum bur bura burbage burbank burberry burbot burden burdensomeness burdock bureau bureaucracy bureaucrat bureaucratism buret burette burg burger burgess burgh burgher burglar burglary burgomaster burgoo burgoyne burgrass burgrave burgundy burhinidae burhinus burial burin burk burka burke burl burlap burlesque burlington burma burmannia burmanniaceae burmeisteria burmese burmese-yi burn burnability burner burnett burnham burning burnish burnoose burnous burnouse burns burnside burnup burp burping burqa burr burrawong burrfish burrito burro burroughs burrow bursa bursar bursary bursera burseraceae bursitis burst burster burt burthen burton burundi burundian burunduki burying bus busbar busboy busby bush bushbaby bushbuck bushel bushido bushing bushman bushnell bushtit bushwhacker business businessman businessmen businesspeople businessperson businesswoman busker buskin busload busman buspar buspirone buss bust bust-up bustard buster bustier bustle busybody busyness busywork butacaine butadiene butane butanol butanone butat butazolidin butch butcher butcherbird butchering butchery butea butene buteo buteonine butler butt butt-weld butt-welding butte butter butter-and-eggs butter-flower butter-print butterball butterbean butterbur buttercrunch buttercup butterfat butterfield butterfingers butterfish butterflower butterfly butterflyfish buttermilk butternut butterscotch butterweed butterwort buttery buttinsky buttock buttocks button button-quail buttonhole buttonhook buttonwood buttress buttressing butty butut butyl butylene butyrin buxaceae buxomness buxus buy buyback buyer buyi buying buyout buzz buzzard buzzer buzzword bvd bvd's bw bwr by-and-by by-blow by-catch by-election by-line by-product byblos bycatch bydgoszcz bye bye-bye bye-election byelarus byelorussia byelorussian bygone bylaw byname bypass bypath byplay byproduct byrd byre byrnie byroad byron byssus bystander byte byway byword byzant byzantine byzantinism byzantium c c-clamp c-horizon c-note c-ration c-section c.p.u. c2h6 ca caaba cab cabal cabala cabalism cabalist cabana cabaret cabasset cabassous cabbage cabbageworm cabbala cabbalah cabby cabdriver cabell caber cabernet cabg cabin cabinet cabinetmaker cabinetmaking cabinetry cabinetwork cable cablegram cabman cabochon cabomba cabombaceae caboodle caboose cabot cabotage cabriolet cabstand cacajao cacalia cacao cacatua cachalot cache cachet cachexia cachexy cachi cachinnation cachou cacicus cacique cackle cackler cacodaemon cacodemon cacodyl cacoethes cacogenesis cacogenics cacography cacomistle cacomixle cacophony cactaceae cactus cad cadaster cadastre cadaver cadaverine caddice-fly caddie caddis-fly caddisworm caddo caddoan caddy cadence cadency cadenza cadet cadetship cadger cadiz cadmium cadmus cadra cadre caduceus caeciliadae caecilian caeciliidae caecum caelum caenogenesis caenolestes caenolestidae caesalpinia caesalpiniaceae caesalpinioideae caesar caesarea caesarean caesarian caesarism caesaropapism caesium caesura cafe cafeteria caff caffein caffeine caffeinism caffer caffre caftan cage cager cagliostro cagney cagoule cahita cahoot caiman caimitillo caimito cain cainogenesis cairene cairina cairn cairngorm cairo caisson caitiff caitra cajanus cajolery cajun cakchiquel cake cakehole cakewalk cakile calaba calabash calabazilla calabria calabura caladenia caladium calais calamagrostis calamari calamary calamine calamint calamintha calamity calamus calan calandrinia calanthe calapooya calapuya calash calc-tufa calcaneus calcedony calceolaria calceus calciferol calcification calcimine calcination calcite calcitonin calcium calcium-cyanamide calculation calculator calculus calcutta calder caldera calderon caldron caldwell calean caleche caledonia calefaction calendar calender calendula calf calfskin calgary cali caliber calibration calibre caliche calico caliculus calidris calif calif. california californian californium caligula caliper caliph caliphate calisaya calisthenics calk calkin call call-back call-board call-in call-out calla callas callathump callback caller caller-out caller-up calliandra callicebus calligrapher calligraphist calligraphy callimorpha callinectes calling callionymidae calliope calliophis calliopsis calliper calliphora calliphoridae callirhoe callisaurus callistephus callisthenics callisto callithricidae callithrix callithump callitrichaceae callitriche callitris callophis callorhinus callosectomy callosity callosotomy callousness callowness calluna callus calm calming calmness calocarpum calocedrus calochortus calomel caloocan caloosahatchee calophyllum calopogon calorie calorimeter calorimetry calosoma calostomataceae calpac calpack calpe calque caltha caltrop calumet calumniation calumny calvados calvaria calvary calvatia calvin calving calvinism calvinist calvino calx calycanthaceae calycanthus calycle calycophyllum calyculus calymmatobacterium calypso calypter calyptra calystegia calyx cam camachile camail camaraderie camarilla camas camash camass camassia cambarus camber cambium cambodia cambodian cambria cambrian cambric cambridge camcorder camden camel camelhair camelia camelidae camelina camellia camelopard camelot camelpox camelus camembert cameo camera cameraman cameroon cameroonian cameroun camion camise camisole camlan camlet camo camomile camorra camosh camouflage camp campaign campaigner campaigning campana campania campanile campanula campanulaceae campanulales campbell campeachy campeche campephilus camper campfire campground camphor camphorweed camping campion campmate campong camponotus campsite campstool camptosorus campus campyloneurum campylorhynchus camshaft camus camwood can canaan canaanite canaanitic canachites canada canadian canafistola canafistula canal canaliculus canalisation canalization cananga canangium canape canara canard canarese canaries canary canasta canavalia canavanine canberra cancan cancel cancellation cancer cancerweed cancridae cancroid cancun candela candelabra candelabrum candelilla candida candidacy candidate candidature candidiasis candidness candle candleberry candlelight candlemaker candlemas candlenut candlepin candlepins candlepower candlesnuffer candlestick candlewick candlewood candor candour candy candyfloss candymaker candytuft candyweed cane canebrake canecutter canella canella-alba canellaceae canetti canfield canful cangue canicula canicule canid canidae canine caning canis canistel canister canker cankerweed cankerworm canna cannabidaceae cannabin cannabis cannaceae cannae cannelloni cannery cannes cannibal cannibalism cannikin cannister cannon cannonade cannonball cannoneer cannula cannulation cannulisation cannulization canoe canoeist canola canon canonisation canonist canonization canopus canopy cant cantabrigian cantala cantaloup cantaloupe cantata canteen canter canterbury cantharellus canthus canticle canticles cantilever cantillation cantle canto canton cantonese cantonment cantor canuck canulation canulisation canulization canute canvas canvasback canvass canvasser canvassing canyon canyonside caoutchouc cap capability capableness capaciousness capacitance capacitor capacity caparison cape capek capelan capelin capella caper capercaillie capercailzie capet capetian capeweed capful capibara capillarity capillary capital capitalisation capitalism capitalist capitalization capitate capitation capitol capitonidae capitulation capitulum capiz caplin capo capon capone caporetto capote capoten cappadocia capparidaceae capparis cappelletti cappuccino capra caprella capreolus capri capriccio caprice capriciousness capricorn capricornis capricornus caprifig caprifoliaceae caprimulgid caprimulgidae caprimulgiformes caprimulgus capriole caproidae capromyidae capros capsaicin capsella capsicum capsid capsidae capsizing capstan capstone capsule captain captaincy captainship caption captivation captive captivity captopril captor capture capturer capuchin capulin caput capybara car car-ferry car-mechanic carabao carabidae carabineer carabiner carabinier caracal caracara caracas carack caracolito caracul carafate carafe caragana carageen carambola caramel carancha caranda caranday carangid carangidae caranx carapace carapidae carassius carat caravaggio caravan caravanning caravansary caravanserai caraway carbamate carbamide carbide carbine carbineer carbohydrate carboloy carbomycin carbon carbonado carbonara carbonate carbonation carbondale carboniferous carbonisation carbonization carbonyl carborundum carboxyl carboy carbuncle carburetor carburettor carcajou carcase carcass carcharhinidae carcharhinus carcharias carchariidae carcharodon carcinogen carcinoid carcinoma carcinosarcoma card card-house cardamine cardamom cardamon cardamum cardboard cardcase cardcastle cardholder cardhouse cardia cardiff cardigan cardiidae cardinal cardinalate cardinalfish cardinality cardinalship cardiogram cardiograph cardiography cardioid cardiologist cardiology cardiomegaly cardiomyopathy cardiopathy cardiospasm cardiospermum carditis cardium cardizem cardoon cardroom cards cardsharp cardsharper carducci carduelinae carduelis cardura carduus care careen career careerism careerist carefreeness carefulness caregiver carelessness carelian caress caressing caret caretaker caretta carew carex carfare carful cargo carhop cariama cariamidae carib caribbean caribe caribees caribou carica caricaceae caricature caricaturist caries carillon carillonneur carina carinate caring carioca carissa carjacking carlina carload carlos carlovingian carlsbad carlyle carmaker carmelite carmichael carminative carmine carnage carnality carnallite carnation carnauba carnegie carnegiea carnelian carnival carnivora carnivore carnosaur carnosaura carnot carnotite carob caroche carol caroler carolina carolinas caroling carolingian carolinian caroller carolus carom carotene carotenemia carotenoid carothers carotin carousal carouse carousel carouser carp carpal carpathians carpel carpentaria carpenter carpenteria carpentry carper carpet carpetbag carpetbagger carpeting carpetweed carphophis carpinaceae carping carpinus carpobrotus carpocapsa carpodacus carpophore carport carpospore carpus carrack carrageen carrageenan carrageenin carragheen carrefour carrel carrell carrere carriage carriageway carrier carrion carrizo carroll carrot carrottop carrousel carry carry-forward carry-over carryall carrycot carson cart cartage cartagena carte cartel carter cartesian carthage carthaginian carthamus carthorse carthusian cartier cartilage cartilaginification carting cartload cartographer cartography carton cartonful cartoon cartoonist cartouch cartouche cartridge cartroad cartwheel cartwright carum caruncle caruncula caruso carvedilol carver carving carya caryatid caryocar caryocaraceae caryophyllaceae caryophyllales caryophyllidae caryopsis caryota casaba casablanca casals casanova casava casbah cascabel cascade cascades cascara cascarilla case casebook caseful casein casement casern casework caseworker caseworm cash cashbox cashcard cashew cashier cashmere casing casino casino-hotel cask casket caskful casmerodius caspar caspase casper caspian casque casquet casquetel cassandra cassareep cassava casserole cassette cassia cassie cassino cassiope cassiopeia cassirer cassiri cassite cassiterite cassius cassock cassowary cast castanea castanets castanopsis castanospermum castaway caste caster castigation castile castilian castilla castilleia castilleja castillian casting castle castling castor castoridae castoroides castrate castration castrato castries castro castroism casualness casualty casuaridae casuariiformes casuarina casuarinaceae casuarinales casuarius casuist casuistry cat cat's-claw cat's-ear cat's-paw cat's-tail cat-o'-nine-tails catabiosis catabolism catacala catachresis cataclysm catacomb catafalque cataflam catalan catalase catalectic catalepsy cataleptic catalexis catalog cataloger catalogue cataloguer catalonia catalpa catalufa catalysis catalyst catamaran catamenia catamite catamount catamountain catananche cataphasia cataphatism cataphoresis cataphract cataphyll cataplasia cataplasm catapres catapult cataract catarrh catarrhine catasetum catastrophe catatonia catawba catbird catboat catbrier catcall catch catchall catcher catchfly catching catchment catchphrase catchweed catchword catclaw catechesis catechin catechism catechist catecholamine catechu catechumen categorem categoreme categorisation categorization category catena catenary caterer catering caterpillar caterwaul catfish catgut catha catharacta catharanthus cathari catharism cathars catharsis cathartes cathartic cathartid cathartidae cathay cathaya cathedra cathedral cather catherine catheter catheterisation catheterization cathexis cathode catholic catholicism catholicity catholicon catholicos cathouse cation catkin catling catmint catnap catnip catoptrics catoptrophorus catostomid catostomidae catostomus catskills catsup cattail cattalo cattell cattie cattiness cattle cattleman cattleship cattleya catty catullus catwalk caucasia caucasian caucasus caucus cauda caudata caudate caudex caul cauldron cauliflower caulk caulking caulophyllum causa causalgia causality causation cause causerie causeway causing caustic cauterant cauterisation cauterization cautery caution cautious cautiousness cavalcade cavalier cavalla cavalry cavalryman cave caveat cavell caveman cavendish cavern cavetto cavia caviar caviare caviidae cavil caviler caviller cavity cavum cavy caw caxton cay cayenne cayman cayuga cayuse cazique cbc cbr cc ccrc cd cd-r cd- rom cd-wo cd4 cd8 cdc cdna ce cease cease-fire ceaselessness cebidae cebu cebuan cebuano cebuella cebus cecidomyidae cecity cecropia cecropiaceae cecum cedar cedarbird cedarwood cedi cedilla ceding cedrela cedrus cefadroxil cefobid cefoperazone cefotaxime ceftazidime ceftin ceftriaxone cefuroxime ceiba ceibo ceilidh ceiling celandine celastraceae celastrus celebes celebrant celebrater celebration celebrator celebrex celebrity celecoxib celeriac celerity celery celesta celestite celibacy celibate celiocentesis celioma celioscopy cell cellar cellarage cellaret cellblock cellini cellist cello cellophane cellphone cellularity cellulite cellulitis celluloid cellulose cellulosic celom celoma celosia celsius celt celtic celtis celtuce cembalo cement cementite cementum cemetery cenchrus cenobite cenogenesis cenotaph cenozoic censer censor censoring censorship censure census cent cental centare centas centaur centaurea centaurium centaurus centaury centavo centenarian centenary centennial center centerboard centerfield centerfielder centerfold centering centerline centerpiece centesimo centesis centile centiliter centilitre centime centimeter centimetre centimo centipede centner central centralisation centralism centrality centralization centranthus centrarchid centrarchidae centre centreboard centrefold centrepiece centrex centrifugation centrifuge centriole centriscidae centrism centrist centrocercus centroid centrolobium centromere centropomidae centropomus centropristis centropus centrosema centrosome centrospermae centrum centunculus centurion century ceo cephalalgia cephalanthera cephalaspid cephalaspida cephalexin cephalhematoma cephalitis cephalobidae cephalochordata cephalochordate cephaloglycin cephalohematoma cephalometry cephalopod cephalopoda cephalopterus cephaloridine cephalosporin cephalotaceae cephalotaxaceae cephalotaxus cephalothin cephalotus cepheus cepphus cer cerambycidae ceramic ceramicist ceramics ceramist cerapteryx ceras cerastes cerastium cerate ceratin ceratitis ceratodontidae ceratodus ceratonia ceratopetalum ceratophyllaceae ceratophyllum ceratopogon ceratopogonidae ceratopsia ceratopsian ceratopsidae ceratopteris ceratosaur ceratosaurus ceratostomataceae ceratostomella ceratotherium ceratozamia cerberus cercaria cercidiphyllaceae cercidiphyllum cercidium cercis cercocebus cercopidae cercopithecidae cercopithecus cercospora cercosporella cere cereal cerebellum cerebration cerebromeningitis cerebrum cerecloth cerement ceremonial ceremoniousness ceremony ceres ceresin cereus ceriman cerise cerium cerivastatin cero ceroxylon cert certainty certhia certhiidae certificate certification certiorari certitude cerulean cerumen ceruse cerussite cervantes cervicitis cervid cervidae cervix cervus ceryle cesarean cesarian cesium cessation cession cesspit cesspool cestida cestidae cestoda cestode cestrum cestum cetacea cetacean cetchup ceterach cetonia cetoniidae cetorhinidae cetorhinus cetraria cetrimide cetus cewa ceylon ceylonite cezanne cf cfc cfo cftr cgs ch'i ch'in ch'ing cha-cha cha-cha-cha chabad chabad-lubavitch chabasite chabazite chablis chachalaca chachka chacma chad chadar chaddar chadian chadic chadlock chador chaenactis chaenomeles chaenopsis chaeronea chaeta chaetodipterus chaetodon chaetodontidae chaetognath chaetognatha chafe chafeweed chaff chaffinch chaffweed chafing chaga chagall chagatai chagga chagrin chahta chain chain- smoker chains chainsaw chair chairlift chairman chairmanship chairperson chairwoman chaise chait chaja chalaza chalazion chalcanthite chalcedon chalcedony chalcid chalcidae chalcidfly chalcididae chalcis chalcocite chalcopyrite chalcostigma chaldaea chaldaean chaldea chaldean chaldee chaldron chalet chalice chalk chalkboard chalkpit chalkstone challah challenge challenger challis chalons chalons-sur-marne chalybite chamaea chamaecrista chamaecyparis chamaecytisus chamaedaphne chamaeleo chamaeleon chamaeleonidae chamaeleontidae chamaemelum chamber chamberlain chambermaid chamberpot chambers chambray chameleon chamfer chamfron chammy chamois chamomile chamosite champ champagne champagne-ardenne champaign champerty champion championship champlain champollion chanal chanar chance chance-medley chancel chancellery chancellor chancellorship chancellorsville chancery chancre chancroid chandelier chandelle chandi chandler chandlery chanfron chang changan change change-of-pace change-up changeability changeableness changefulness changelessness changeling changeover changer changjiang changtzu channel channelisation channelization channels channidae channukah channukkah chanoyu chant chantarelle chanter chanterelle chantey chanting chantry chanty chanukah chanukkah chaos chap chaparral chapati chapatti chapeau chapel chapelgoer chaperon chaperone chapiter chaplain chaplaincy chaplainship chaplet chaplin chapman chapter chapterhouse chapultepec char chara charabanc characeae characid characidae characin characinidae character characterisation characteristic characterization charade charades charadrii charadriidae charadriiformes charadrius charales charcoal charcot charcuterie chard chardonnay charge chargeman charger chari chari-nile charina chariness chariot charioteer charisma charitableness charity charivari charlatan charlatanism charlemagne charleroi charles charleston charlestown charley-horse charlock charlotte charlottetown charm charmer charnel charolais charon charophyceae charr charronia chart charter charterhouse chartism chartist chartres chartreuse charwoman charybdis chase chased chaser chasid chasidim chasidism chasm chasse chassid chassidim chassidism chassis chasteness chastening chastisement chastity chasuble chat chateau chateau-thierry chateaubriand chatelaine chateura chatroom chattahoochee chattanooga chattel chatter chatterbox chatterer chattering chaucer chauffeur chauffeuse chaulmoogra chaulmugra chauna chauvinism chauvinist chavez chaw chawbacon cheap-jack cheapjack cheapness cheapskate cheat cheater cheatgrass cheating chebab chechen chechenia chechnya check check-in checkbook checker checkerberry checkerbloom checkerboard checkers checklist checkmate checkout checkpoint checkrein checkroom checksum checkup cheddar cheek cheekbone cheekiness cheekpiece cheep cheer cheerer cheerfulness cheering cheerio cheerleader cheerlessness cheese cheeseboard cheeseburger cheesecake cheesecloth cheeseflower cheesemonger cheetah cheever cheewink chef chef-d'oeuvre cheilanthes cheilitis cheiloschisis cheilosis cheiranthus chekhov chekov chela chelate chelation chelicera chelicerata chelidonium chelifer cheloid chelone chelonethida chelonia chelonian chelonidae cheloniidae chelyabinsk chelydra chelydridae chemakuan chemakum chemical chemiluminescence chemise chemisorption chemist chemist's chemistry chemnitz chemoimmunology chemoreceptor chemosis chemosorption chemosurgery chemosynthesis chemotaxis chemotherapy chemulpo chen chenfish chenille chennai chenopodiaceae chenopodiales chenopodium cheops cheque chequebook chequer cherbourg cheremis cheremiss cherepovets cherimolla cherimoya chermidae chernobyl cherokee cheroot cherry cherrystone chert cherub cherubini chervil chess chessboard chessman chest chester chesterfield chesterton chestnut chetah chetrum cheval-de-frise chevalier chevaux-de-frise cheviot cheviots chevre chevron chevrotain chew chewa chewer chewing chewink cheyenne chi chianti chiaroscuro chiasm chiasma chiasmus chic chicago chicane chicanery chicano chicha chichewa chichi chichipe chick chickadee chickamauga chickasaw chicken chickenfeed chickenpox chickenshit chickeree chickpea chickweed chicle chicness chico chicory chicot chiding chief chieftain chieftaincy chieftainship chiffon chiffonier chigetai chigger chiggerflower chignon chigoe chihuahua chilblain chilblains child childbearing childbed childbirth childcare childhood childishness childlessness chile chilean chili chiliad chiliasm chiliast chill chiller chilli chilliness chilling chilly chiloe chilomastix chilomeniscus chilomycterus chilopoda chilopsis chiluba chimaera chimaeridae chimakum chimaphila chimariko chimborazo chime chimera chimney chimneypiece chimneypot chimneystack chimneysweep chimneysweeper chimonanthus chimp chimpanzee chimwini chin chin-up chin-wag chin-wagging china chinaberry chinaman chinaware chincapin chinch chincherinchee chinchilla chinchillidae chinchillon chinchona chine chinese chingpo chink chinkapin chino chinoiserie chinook chinookan chinquapin chintz chiococca chionanthus chios chip chipboard chipewyan chipmunk chipolata chipotle chippendale chippewa chippewaian chippewyan chipping chips chiralgia chirico chirocephalus chirography chirology chiromancer chiromancy chiron chironomidae chironomus chiropodist chiropody chiropractic chiropractor chiroptera chiropteran chirp chirpiness chirrup chisel chiseler chiseller chishona chisinau chislev chit chit-chat chitchat chitin chitlings chitlins chiton chittagong chittamwood chitterlings chittimwood chivalry chivaree chive chives chiwere chlamydera chlamydia chlamydiaceae chlamydomonadaceae chlamydomonas chlamydosaurus chlamydospore chlamyphore chlamyphorus chlamys chloasma chlor-trimeton chlorambucil chloramine chloramine-t chloramphenicol chloranthaceae chloranthus chlorate chlordiazepoxide chlorella chlorenchyma chlorhexidine chloride chlorination chlorine chlorinity chloris chlorite chloroacetophenone chlorobenzene chlorobenzylidenemalononitrile chlorococcales chlorococcum chlorofluorocarbon chloroform chlorofucin chloromycetin chlorophis chlorophoneus chlorophthalmidae chlorophyceae chlorophyl chlorophyll chlorophyta chlorophyte chloropicrin chloroplast chloroprene chloroquine chlorosis chlorothiazide chloroxylon chlorpromazine chlorpyrifos chlortetracycline chlorthalidone chlorura choanocyte choc choc-ice chock chocolate choctaw choeronycteris choice choiceness choir choirboy choirmaster choke chokecherry chokedamp chokehold chokepoint choker chokey choking choky cholangiography cholangitis cholecalciferol cholecystectomy cholecystitis cholecystokinin cholelithiasis cholelithotomy choler cholera cholestasis cholesterin cholesterol choline cholinesterase cholla choloepus chomp chomping chomsky chon chondrichthian chondrichthyes chondrin chondriosome chondrite chondrodystrophy chondroma chondrosarcoma chondrule chondrus chongqing choo-choo chooser chop chophouse chopin chopine chopper choppiness chopsteak chopstick choragus choral chorale chord chordamesoderm chordata chordate chordeiles chorditis chordomesoderm chordophone chordospartium chore chorea choreographer choreography chorine chorioallantois choriomeningitis chorion chorioretinitis choriotis chorister chorizagrotis chorizema chorizo choroid chortle chorus chosen chou chough chow chowchow chowder chrestomathy chrism chrisom christ christ's-thorn christchurch christella christendom christening christian christiania christianisation christianity christianization christie christmas christmasberry christmastide christmastime christology christopher chroma chromaesthesia chromate chromaticity chromatid chromatin chromatism chromatogram chromatography chrome chromesthesia chromite chromium chromoblastomycosis chromogen chromolithography chromophore chromoplast chromosome chromosphere chronicle chronicler chronograph chronology chronometer chronoperates chronoscope chrysalis chrysanthemum chrysaora chrysarobin chrysemys chrysobalanus chrysoberyl chrysochloridae chrysochloris chrysolepis chrysolite chrysolophus chrysomelid chrysomelidae chrysophrys chrysophyceae chrysophyllum chrysophyta chrysopid chrysopidae chrysoprase chrysopsis chrysosplenium chrysothamnus chrysotherapy chrysotile chuang-tzu chub chubbiness chuck chuck- will's-widow chucker-out chuckhole chuckle chuckwalla chuddar chufa chug chukaku-ha chukchi chukka chukker chum chumminess chump chunga chungking chunk chunking chunnel church church-state churchgoer churchill churchman churchwarden churchyard churidars churl churn chute chute-the-chute chutney chutzpa chutzpah chutzpanik chuvash chyle chyloderma chylomicron chyme chymosin chytridiaceae chytridiales chytridiomycetes ci cia cialis ciao ciardi cibotium cicada cicadellidae cicadidae cicala cicatrice cicatrix cicer cicero cicerone cichlid cichlidae cichorium cicindelidae ciconia ciconiidae ciconiiformes cicuta cid cider ciderpress cigar cigaret cigarette cigarfish cigarillo cilantro ciliata ciliate cilioflagellata ciliophora ciliophoran cilium cim cimabue cimarron cimetidine cimex cimicidae cimicifuga cinch cinchona cinchonine cincinnati cincinnatus cinclidae cinclus cincture cinder cinderella cine-camera cine-film cinema cinematographer cinematography cineraria cinerarium cingulum cinnabar cinnamene cinnamomum cinnamon cinque cinquefoil cio cipher cipro ciprofloxacin cira circaea circaetus circassian circe circinus circle circlet circuit circuitry circular circularisation circularity circularization circulation circumcision circumduction circumference circumflex circumlocution circumnavigation circumscription circumspection circumstance circumstances circumvention circumvolution circus cirio cirque cirrhosis cirrhus cirriped cirripede cirripedia cirrocumulus cirrostratus cirrus cirsium cis cisc cisco cistaceae cistercian cistern cisterna cistothorus cistron cistus citadel citation cite citellus citharichthys cither cithern citizen citizenry citizenship citlaltepetl citole citrange citrate citrin citrine citron citroncirus citronwood citrulline citrullus citrus cittern city city-state cityscape cive civet civics civies civilian civilisation civility civilization civvies cjd cl clabber clack cladding clade cladistics cladode cladogram cladonia cladoniaceae cladophyll cladorhyncus cladrastis claforan claim claimant clairvoyance clairvoyant clam clamatores clambake clamber clamminess clammyweed clamor clamoring clamour clamouring clamp clampdown clams clamshell clan clang clanger clangor clangoring clangour clangula clank clannishness clansman clanswoman clap clapboard clapper clapperboard clappers clapping claptrap claque clarence claret clarification clarinet clarinetist clarinettist clarion clarity clark clarksburg claro clary clash clasp class classic classical classicalism classicism classicist classics classification classified classifier classmate classroom classwork clast clathraceae clathrus clatter claudication claudius clause clausewitz claustrophobe claustrophobia claustrum clavariaceae claviceps clavichord clavicipitaceae clavicle clavier clavus claw clawback clawfoot clawhammer claxon clay claymore claystone claytonia clayware clean cleaner cleaners cleaning cleanliness cleanness cleanser cleansing cleanthes cleanup clear clearance clearcutness clearing clearness clearstory clearway clearweed cleat cleats cleavage cleaver cleavers clef cleft cleg clegg cleistes cleistocarp cleistogamy cleistothecium clematis clemenceau clemency clemens clementine clench cleome cleopatra clepsydra clerestory clergy clergyman cleric clericalism clericalist clerid cleridae clerihew clerisy clerk clerking clerkship clethra clethraceae clethrionomys cleveland cleverness clevis clew clews cli clianthus cliche clichy clichy-la-garenne click click-clack clickety- clack clickety-click client clientage clientele cliff cliff-brake cliffhanger cliftonia climacteric climate climatologist climatology climax climb climb-down climber climbing clime clinch clincher cline cling clingfilm clingfish clingstone clinic clinician clinid clinidae clink clinker clinocephalism clinocephaly clinodactyly clinometer clinopodium clinoril clinton clintonia clio clioquinol clip clip-clop clip-on clipboard clipper clippety-clop clipping clique cliquishness clit clitocybe clitoria clitoridectomy clitoris clive clivers cloaca cloak cloakmaker cloakroom clobber cloche clock clock-watching clocking clockmaker clocks clocksmith clockwork clod clodhopper clofibrate clog cloisonne cloister clomid clomiphene clomipramine clon clone clonidine cloning clonus clop clopping clorox close closedown closeness closeout closer closet closeup closing clostridia clostridium closure clot clotbur cloth clothes clothesbrush clotheshorse clothesline clothespin clothespress clothier clothing clotho clotting cloture cloud cloud-cuckoo-land cloudberry cloudburst cloudiness clouding cloudlessness clout clove clover clover-root cloverleaf cloveroot clovis clowder clown clowning clozapine clozaril club club-head club-moss clubbing clubfoot clubhead clubhouse clubroom cluck clucking clue clumber clump clumping clumsiness clunch clunk clunking clupea clupeid clupeidae clusia clusiaceae cluster clustering clutch clutches clutter clyde clydesdale clypeus clyster clytemnestra cm cmb cmbr cmv cnemidophorus cnicus cnidaria cnidarian cnidoscolus cnidosporidia cnossos cnossus cnpz cns cnut co co-beneficiary co- defendant co-discoverer co-ed co-occurrence co-op co-optation co-option co- ordinate co-pilot co-respondent co-star co-worker co2 coach coach-and-four coachbuilder coaching coachman coachwhip coaction coadjutor coagulant coagulase coagulation coagulator coagulum coahuila coal coalbin coalescence coalescency coalface coalfield coalhole coalition coalman coalpit coaming coarctation coarseness coast coaster coastguard coastguardsman coastland coastline coat coatdress coatee coati coati-mondi coati-mundi coating coatrack coatroom coattail coauthor coax coaxer coaxing cob cobalamin cobalt cobaltite cobber cobble cobbler cobblers cobblestone cobbling cobia cobitidae cobnut cobol cobra cobweb coca cocain cocaine cocarboxylase cocci coccidae coccidia coccidioidomycosis coccidiomycosis coccidiosis coccidium coccinellidae coccobacillus coccoidea coccothraustes cocculus coccus coccyx coccyzus cochimi cochin cochineal cochise cochlea cochlearia cochlearius cochran cock cock-a -doodle-doo cock-a-leekie cockade cockaigne cockateel cockatiel cockatoo cockatrice cockchafer cockcroft cockcrow cocker cockerel cockfight cockfighting cockhorse cockiness cockle cockle-bur cockle-burr cocklebur cockleburr cockleshell cockloft cockney cockpit cockroach cockscomb cocksfoot cockspur cocksucker cocksureness cocktail cockup cocky-leeky coco cocoa cocoanut cocobolo coconspirator coconut cocoon cocooning cocopa cocopah cocos cocoswood cocotte cocoyam cocozelle cocteau cocus cocuswood cocytus cod coda codariocalyx coddler code codefendant codeine coder codetalker codex codfish codger codiaeum codicil codification coding codling codlins-and-cream codon codpiece codswallop cody coeducation coefficient coelacanth coelenterata coelenterate coelenteron coeloglossum coelogyne coelom coelophysis coelostat coenobite coenzyme coercion coereba coerebidae coeval coevals coexistence coextension cofactor coffea coffee coffeeberry coffeecake coffeehouse coffeepot coffer cofferdam coffin cofounder cog cogency cogitation cognac cognate cognation cognisance cognition cognizance cognomen cognoscente cogwheel cohabitation cohan coherence coherency cohesion cohesiveness cohn coho cohoe cohort cohosh cohune coif coiffeur coiffeuse coiffure coign coigne coigue coil coin coinage coincidence coiner coinsurance coir coition coitus coke col cola colander colaptes colbert colchicaceae colchicine colchicum colchis cold coldcream coldheartedness coldness cole coleonyx coleoptera coleridge coleslaw colette coleus colewort colic colicroot colima colinus coliphage coliseum colitis collaboration collaborationism collaborationist collaborator collage collagen collagenase collapse collar collarbone collard collards collateral collation colleague collect collectable collectible collecting collection collective collectivisation collectivism collectivist collectivization collector colleen college collegian collembola collembolan collet collider collie collier colliery colligation collimation collimator collins collinsia collinsonia collision collocalia collocation collodion colloid colloquialism colloquium colloquy collotype collusion collyrium collywobbles colobus colocasia cologne colombia colombian colombo colon colonel colonial colonialism colonialist colonic colonisation coloniser colonist colonization colonizer colonnade colonoscope colonoscopy colony colophon colophony color coloradan coloradillo colorado coloration coloratura colorcast colored colorimeter colorimetry coloring colorist colorlessness colors colossae colosseum colossian colossians colossus colostomy colostrum colour colouration colourcast colouring colourlessness colours colpitis colpocele colpocystitis colpocystocele colpoxerosis colt coltan colter coltsfoot coluber colubrid colubridae colubrina colugo columba columbarium columbary columbia columbidae columbiformes columbine columbite columbite-tantalite columbium columbo columbus columella column columnea columniation columnist colutea colymbiformes colza coma comanche comandra comatoseness comatula comatulid comatulidae comb comb-out comb-plate combat combatant combativeness comber combination combine combing combining combo combretaceae combretum combustibility combustible combustibleness combustion come come-on comeback comedian comedienne comedo comedown comedy comeliness comenius comer comestible comet comeupance comeuppance comfit comfort comfortableness comforter comforts comfrey comic comicality coming comint comity comma command commandant commander commandership commandery commandment commando commelina commelinaceae commelinales commelinidae commemoration commemorative commencement commendation commensal commensalism commensurateness comment commentary commentator commerce commercial commercialisation commercialism commercialization commie commination commiphora commiseration commissar commissariat commissary commission commissionaire commissioner commissioning commissure commitment committal committedness committee committeeman committeewoman commixture commode commodiousness commodity commodore common commonage commonality commonalty commoner commonness commonplace commonplaceness commons commonweal commonwealth commotion communalism commune communicant communicating communication communications communicativeness communicator communion communique communisation communism communist community communization commutability commutation commutator commute commuter commuting comoros comp compact compaction compactness companion companionability companionableness companionship companionway company comparability comparative compare comparing comparison compartment compartmentalisation compartmentalization compass compassion compassionateness compatibility compatriot compeer compendium compensation compere competence competency competition competitiveness competitor compilation compiler compiling complacence complacency complainant complainer complaint complaisance complement complementarity complementary complementation completeness completion complex complexifier complexion complexity complexness compliance compliancy complicatedness complication complicity compliment compliments complin compline component comportment composer composing compositae composite compositeness composition compositor compost composure compote compound compounding comprehensibility comprehension comprehensive comprehensiveness compress compressibility compressing compression compressor compromise compromiser compsognathus compton comptonia comptroller comptrollership compulsion compulsive compulsiveness compulsivity compunction computation computer computerization computing comrade comradeliness comradery comradeship comstock comstockery comte comtism con conacaste conakry concatenation concaveness concavity concealing concealment conceding conceit conceitedness conceivability conceivableness conceiver concentrate concentration concentricity concepcion concept conception conceptualisation conceptualism conceptuality conceptualization conceptus concern concert concert-goer concertina concerto concession concessionaire concessioner conch concha conchfish conchologist conchology concierge conciliation conciliator conciseness concision conclave conclusion conclusiveness concoction concomitance concomitant concord concordance concordat concourse concrete concreteness concretion concretism concubinage concubine concupiscence concurrence concurrency concussion condemnation condensate condensation condenser condensing condescendingness condescension condiment condition conditionality conditioner conditioning conditions condo condolence condom condominium condonation condor condorcet conduct conductance conducting conduction conductivity conductor conductress conduit condyle condylion condylura cone coneflower conenose conepatus conessi conestoga coney confab confabulation confect confection confectionary confectioner confectionery confederacy confederate confederation conferee conference conferment conferral conferrer conferva confession confessional confessor confetti confidant confidante confidence confidentiality configuration configurationism confinement confines confirmation confiscation confit confiture conflagration conflict confluence confluent conflux conformance conformation conformism conformist conformity confrere confrontation confucian confucianism confucianist confucius confusedness confusion confutation confuter conga conge congealment congee congelation congenator congener congeneric congeniality congenialness conger congeries congestion congius conglobation conglomerate conglomeration conglutination congo congolese congou congratulation congratulations congregant congregating congregation congregationalism congregationalist congress congressman congresswoman congreve congridae congruence congruity congruousness conic conidiophore conidiospore conidium conifer coniferales coniferophyta coniferophytina coniferopsida conilurus conima coniogramme conium conjecture conjugate conjugation conjunction conjunctiva conjunctive conjunctivitis conjuncture conjuration conjurer conjuring conjuror conjury conk conker connaraceae connarus connectedness connecter connecticut connecticuter connection connective connectivity connector connexion conniption connivance connochaetes connoisseur connoisseurship connolly connors connotation conocarpus conoclinium conodont conodonta conodontophorida conoid conopodium conospermum conoy conquering conqueror conquest conquistador conrad conradina consanguinity conscience conscientiousness consciousness conscript conscription consecration consensus consent consequence conservancy conservation conservationist conservatism conservative conservativism conservativist conservatoire conservator conservatory conserve conserves considerateness consideration consignee consigner consignment consignor consistence consistency consistory consolation console consolida consolidation consomme consonance consonant consort consortium conspecific conspectus conspicuousness conspiracy conspirator constable constabulary constance constancy constant constantan constantina constantine constantinople constatation constellation consternation constipation constituency constituent constitution constitutional constitutionalism constitutionalist constraint constriction constrictor construal construct construction constructiveness constructivism constructivist constructor consubstantiation consuetude consuetudinal consuetudinary consul consulate consulship consultancy consultant consultation consumer consumerism consummation consumption consumptive contact contadino contagion container containerful containership containment contaminant contamination contemplation contemplative contemplativeness contemporaneity contemporaneousness contemporaries contemporary contempt contemptibility contemptuousness contender content contentedness contention contentiousness contentment contents contest contestant contestation contestee contester context contextualism contiguity contiguousness continence continency continent contingence contingency contingent continuance continuant continuation continuative continuity continuo continuousness continuum conto contopus contortion contortionist contour contra contraband contrabandist contrabass contrabassoon contraception contraceptive contract contractility contracting contraction contractor contracture contradance contradiction contradictoriness contradictory contradistinction contrafagotto contrail contraindication contralto contraption contrapuntist contrarian contrariety contrariness contrary contras contrast contravention contredanse contretemps contribution contributor contriteness contrition contrivance contriver control controller controllership controversialist controversy contumacy contumely contusion conundrum conurbation conuropsis convalescence convalescent convallaria convallariaceae convection convector convener convenience conveniences convening convent conventicle convention conventionalisation conventionalism conventionality conventionalization conventioneer convergence convergency converging conversance conversancy conversation conversationalist conversationist converse conversion converso convert converter convertibility convertible convertor convexity convexness conveyance conveyancer conveyancing conveyer conveying conveyor convict convictfish conviction convincingness conviviality convocation convolution convolvulaceae convolvulus convoy convulsion cony conyza coo cook cookbook cooke cooker cookery cookfire cookhouse cookie cooking cookout cookstove cookware cooky cool coolant cooler coolidge coolie cooling coolness coolwart cooly coon coondog coonhound coonskin coontie coop cooper cooperation cooperative cooperativeness cooperator cooperstown coordinate coordination coordinator coosa coot cooter cootie cop copaiba copal copaline copalite copartner copartnership cope copeck copehan copenhagen copepod copepoda copernicia copernicus copestone copier copilot coping copiousness copland copley copolymer copout copper copperhead copperplate coppersmith copperware coppice coppola copra coprinaceae coprinus coprolalia coprolite coprolith coprophagia coprophagy copse copt coptic coptis copula copulation copulative copy copybook copycat copyhold copyholder copying copyist copyreader copyright copywriter coquetry coquette coquille cora coracan coracias coraciidae coraciiformes coracle coragyps corakan coral coral- wood coralbells coralberry corallorhiza coralroot coralwood coralwort corbel corbett corbie-step corbiestep corbina corchorus cord cordage cordaitaceae cordaitales cordaites cordarone corday cordgrass cordia cordial cordiality cordierite cordite corditis cordoba cordon cordova cordovan cords corduroy corduroys cordwood cordylidae cordyline cordylus core coreference coregonidae coregonus coreid coreidae coreligionist corelli coreopsis corer corespondent corgard corgi coriander coriandrum coricidin corinth corinthian corium corixa corixidae cork corkage corkboard corker corkscrew corkwood corm cormorant corn cornaceae cornbread corncob corncrake corncrib cornea corneille cornel cornelian cornell corner cornerback cornerstone cornet cornetfish cornetist corneum cornfield cornflour cornflower cornhusk cornhusker cornhusking cornice cornish cornishman cornishwoman cornmeal cornpone cornsilk cornsmut cornstalk cornstarch cornu cornucopia cornus cornwall cornwallis corokia corolla corollary corona coronach coronal coronary coronation coroner coronet coronilla coronion coropuna corot corozo corp corporal corporality corporation corporatism corporatist corporeality corposant corps corpse corpulence corpulency corpus corpuscle corral corrasion correction corrections correctitude corrective correctness correggio corregidor correlate correlation correlative correlativity correspondence correspondent corrida corridor corrie corrigenda corrigendum corroboration corrodentia corroding corrosion corrosive corrugation corruptibility corruption corruptness corsage corsair corse corselet corset corsica corslet cortaderia cortef cortege cortes cortex cortez corticium corticoid corticosteroid corticosterone corticotrophin corticotropin cortina cortinariaceae cortinarius cortisol cortisone cortland corundom corundum coruscation corvee corvette corvidae corvus coryanthes corydalidae corydalis corydalus corylaceae corylopsis corylus corymb corynebacteriaceae corynebacterium corypha coryphaenidae coryphantha corythosaur corythosaurus coryza cos coscoroba cosec cosecant cosh cosignatory cosigner cosine cosiness cosmea cosmetic cosmetician cosmetologist cosmetology cosmid cosmocampus cosmogeny cosmogony cosmographer cosmographist cosmography cosmolatry cosmologist cosmology cosmonaut cosmopolitan cosmopolite cosmos cosmotron coss cossack cost costa costalgia costanoan costermonger costia costiasis costing costliness costmary costochondritis costs costume costumer costumier costusroot cosy cot cotacachi cotan cotangent cote cotenant coterie cothromboplastin cotilion cotillion cotinga cotingidae cotinus cotoneaster cotonou cotopaxi cotswold cotswolds cottage cottager cottar cotter cottidae cottier cotton cottonmouth cottonseed cottontail cottonweed cottonwick cottonwood cottus cotula coturnix cotyledon coucal couch couchette coue cougar cough coughing coulisse coulomb coulter coumadin coumarone coumarouna council councillor councillorship councilman councilorship councilwoman counsel counseling counselling counsellor counsellorship counselor counselor-at-law counselorship count countdown countenance counter counter-revolutionist counter-sabotage counteraction counterargument counterattack counterattraction counterbalance counterblast counterblow counterbombardment counterbore countercharge countercheck counterclaim countercoup counterculture countercurrent counterdemonstration counterdemonstrator counterespionage counterexample counterfactuality counterfeit counterfeiter counterfire counterfoil counterglow counterinsurgency counterintelligence counterirritant counterman countermand countermarch countermeasure countermine countermove counteroffensive counteroffer counterpane counterpart counterperson counterplan counterplay counterplea counterplot counterpoint counterpoise counterpoison counterproposal counterpunch counterreformation counterrevolution counterrevolutionary counterrevolutionist countershot countersign countersignature countersink counterspy counterstain countersubversion countersuit countertenor counterterrorism counterterrorist countertop countertransference counterweight counterwoman countess counting countinghouse countlessness country country-dance countryfolk countryman countryseat countryside countrywoman counts/minute county coup coupe couperin couple coupler couplet coupling coupon courage courageousness courante courbaril courbet courgette courier courlan course courser coursework coursing court court-martial courtelle courtesan courtesy courthouse courtier courting courtliness courtroom courtship courtyard couscous cousin cousin-german cousteau couture couturier couvade couverture covalence covalency covariance covariation cove coven covenant coventry cover cover-up coverage coverall covering coverlet covert covertness covetousness covey coville cow cowage coward cowardice cowardliness cowbarn cowbell cowberry cowbird cowboy cowcatcher cowfish cowgirl cowhand cowherb cowherd cowhide cowhouse cowl cowlick cowling cowman cowpea cowpens cowper cowpie cowpoke cowpox cowpuncher cowrie cowry cows cowshed cowskin cowslip cowtown cox cox-1 cox-2 coxa coxcomb coxsackievirus coxswain coydog coyness coyol coyote coypu cozenage coziness cozy cpa cpi cpr cps cpu cr crab crabapple crabbedness crabbiness crabgrass crabmeat crabs cracidae crack crack-up crackdown cracker crackerberry crackerjack cracking crackle crackleware crackling cracklings crackpot cracksman cracow cracticidae cracticus cradle cradlesong craft crafter craftiness craftsman craftsmanship crag cragsman craigie crake crambe crammer cramp crampbark crampfish crampon crampoon cran cranberry crane cranesbill crangon crangonidae craniata craniate craniologist craniology craniometer craniometry craniotomy cranium crank crankcase crankiness crankshaft cranny crap crap-shooter crapaud crape crapette crapper crappie craps crapshoot crapshooter crapulence crash crasher craspedia crassitude crassness crassostrea crassula crassulaceae crataegus crate crateful crater crateva craton cravat craven cravenness craving craw crawdad crawdaddy crawfish crawford crawl crawler crawling crawlspace crax crayfish crayon craze craziness crazy crazyweed creak creaking cream creamcups creamer creamery creaminess crease creashak creatin creatine creation creationism creativeness creativity creator creature creche crecy cred credence credendum credential credentials credenza credibility credibleness credit creditor credits creditworthiness credo credulity credulousness cree creed creek creel creep creeper creepiness creeping creeps creepy-crawlies creepy-crawly creese cremains cremation crematorium crematory cremona crenation crenature crenel crenelation crenellation crenelle creole creole-fish creon creosol creosote crepe crepis crepitation crepuscle crepuscule crescendo crescent crescentia cresol cress crest cretaceous cretan crete cretin cretinism cretonne crevasse crevice crew crewelwork crewet crewman crex crib cribbage cricetidae cricetus crichton crick cricket cricketer crier crime crimea criminal criminalisation criminalism criminality criminalization criminalness criminologist criminology crimp crimper crimson cringle crinion crinkle crinkle- root crinkleroot crinoid crinoidea crinoline criollo cripple crisis crisp crispin crispiness crispness crisscross cristal cristobalite criterion crith critic criticality criticalness criticism critique critter crius crixivan cro cro-magnon croak croaker croaking croat croatia croatian crocethia crochet crocheting crock crockery crocket crockett crocodile crocodilia crocodilian crocodilus crocodylia crocodylidae crocodylus crocolite crocus crocuta croesus croft crofter crohn croissant cromlech cromorne cromwell cronartium crone cronus crony cronyism cronyn crook crookback crookedness crookes crookneck crooner crooning crop crop-dusting cropper croquet croquette crore crosby crosier cross cross-classification cross-division cross-dresser cross-examination cross- examiner cross-eye cross-fertilisation cross-fertilization cross-index cross- link cross-linkage cross-pollination cross-purpose cross-question cross- questioner cross-reference cross-stitch crossbar crossbeam crossbench crossbencher crossbill crossbones crossbow crossbreed crossbreeding crosscheck crosscurrent crosscut crosse crossfire crosshairs crosshatch crosshead crossheading crossing crossjack crossness crossopterygian crossopterygii crossover crosspatch crosspiece crossroad crossroads crosstalk crosstie crosswalk crossway crosswind crossword crotal crotalaria crotalidae crotalus crotaphion crotaphytus crotch crotchet crotchetiness croton crotonbug crotophaga crottal crottle crouch croup croupe croupier crouse crouton crow crow-bait crowbait crowbar crowberry crowd crowding crowfoot crowing crown crown-beard crown-of-the-field crownbeard crownwork crozier crp crt cruciality crucible crucifer cruciferae crucifix crucifixion crud crude crudeness crudites crudity cruelness cruelty cruet cruet-stand cruise cruiser cruiserweight cruller crumb crumbliness crumhorn crumpet crunch crupper crus crusade crusader cruse crush crusher crushing crust crustacea crustacean crutch crux cry cryaesthesia crybaby cryesthesia crying cryoanaesthesia cryoanesthesia cryobiology cryocautery cryogen cryogenics cryogeny cryolite cryometer cryonics cryopathy cryophobia cryoscope cryostat cryosurgery crypt cryptacanthodes cryptanalysis cryptanalyst cryptanalytics cryptobiosis cryptobranchidae cryptobranchus cryptocercidae cryptocercus cryptococcosis cryptocoryne cryptogam cryptogamia cryptogram cryptogramma cryptogrammataceae cryptograph cryptographer cryptography cryptologist cryptology cryptomeria cryptomonad cryptophyceae cryptophyta cryptophyte cryptoprocta cryptorchidism cryptorchidy cryptorchism cryptotermes cryptotis crystal crystallisation crystallite crystallization crystallizing crystallographer crystallography cs cse csis cst ct ctc ctene ctenidium ctenizidae ctenocephalides ctenocephalus ctenophora ctenophore cu cub cuba cuban cubby cubbyhole cube cubeb cubicity cubicle cubism cubist cubit cubitiere cubitus cuboid cuckold cuckoldom cuckoldry cuckoo cuckoo-bumblebee cuckooflower cuckoopint cuculidae cuculiformes cuculus cucumber cucumis cucurbit cucurbita cucurbitaceae cud cudbear cuddle cuddling cuddy cudgel cudweed cue cuff cufflink cuirass cuirassier cuisine cuisse cuke cul culbertson culcita culdoscope culdoscopy culebra culex culiacan culicidae cull cullender cullis culm culmination culotte culpability culpableness culprit cult cultism cultist cultivar cultivation cultivator culturati culture cultus culverin culvert cum cumana cumarone cumberland cumbersomeness cumbria cumfrey cumin cuminum cummerbund cummings cumquat cumulation cumulonimbus cumulus cunaxa cunctation cunctator cuneiform cuneus cuniculus cunner cunnilinctus cunnilingus cunning cunningham cunoniaceae cunt cuon cup cupbearer cupboard cupcake cupel cupflower cupful cupid cupidity cupola cuppa cupper cupping cupressaceae cupressus cuprimine cuprite cupronickel cupule cuquenan cur curability curableness curacao curacoa curacy curandera curandero curare curassow curate curative curator curatorship curb curbing curbside curbstone curculionidae curcuma curd curdling cure cure-all curet curettage curette curettement curfew curia curie curietherapy curing curio curiosa curiosity curiousness curitiba curium curl curler curlew curlicue curliness curling curly-heads curmudgeon currajong currant currawong currency current currentness curriculum currier curry currycomb curse cursive cursor cursorius curtailment curtain curtilage curtis curtisia curtiss curtness curtsey curtsy curvaceousness curvature curve curvet cusco cuscus cuscuta cush-cush cushat cushaw cushing cushion cushioning cushitic cusk cusk-eel cusp cuspid cuspidation cuspidor cuss cussedness custard custer custodian custodianship custody custom custom-built custom-made customer customhouse customs customshouse cut cut-and-thrust cut-in cut-up cutaway cutback cutch cuteness cuterebra cuterebridae cuticle cuticula cutin cutis cutlas cutlass cutlassfish cutler cutlery cutlet cutoff cutout cutpurse cutter cutthroat cutting cuttle cuttlefish cutwork cutworm cuvier cuzco cv cva cwm cwt cyamopsis cyamus cyan cyanamid cyanamide cyanide cyanite cyanobacteria cyanocitta cyanocobalamin cyanogen cyanohydrin cyanophyceae cyanophyta cyanosis cyanuramide cyathea cyatheaceae cybele cyber-terrorism cyber-terrorist cyberart cybercafe cybercrime cyberculture cybernation cybernaut cybernetics cyberphobia cyberpunk cybersex cyberspace cyberwar cyborg cycad cycadaceae cycadales cycadofilicales cycadophyta cycadophytina cycadopsida cycas cyclades cyclamen cycle cycles/second cyclicity cycling cycliophora cyclist cyclobenzaprine cyclohexanol cycloid cycloloma cyclone cyclooxygenase cyclooxygenase-1 cyclooxygenase-2 cyclopaedia cyclopedia cyclopes cyclophorus cyclopia cyclopropane cyclops cyclopteridae cyclopterus cyclorama cycloserine cyclosis cyclosorus cyclosporeae cyclostomata cyclostome cyclostyle cyclothymia cyclotron cycnoches cyder cydippea cydippida cydippidea cydonia cygnet cygnus cylinder cylindricality cylindricalness cylix cyma cymatiidae cymatium cymbal cymbalist cymbid cymbidium cyme cymene cymling cymograph cymric cymru cymry cymule cynancum cynara cynewulf cynic cynicism cynipidae cynips cynocephalidae cynocephalus cynodon cynodont cynodontia cynoglossidae cynoglossum cynomys cynophobia cynopterus cynoscephalae cynoscion cynosure cynthia cynwulf cyon cyperaceae cyperus cypher cyphomandra cypraea cypraeidae cypre cypress cyprian cyprinid cyprinidae cypriniformes cyprinodont cyprinodontidae cyprinus cypriot cypriote cypripedia cypripedium cyproheptadine cyprus cyril cyrilla cyrilliaceae cyrillic cyrtomium cyrus cyst cysteine cystine cystitis cystocele cystolith cystoparalysis cystophora cystoplegia cystopteris cytherea cytidine cytisus cytoarchitectonics cytoarchitecture cytochrome cytogenesis cytogeneticist cytogenetics cytogeny cytokine cytokinesis cytokinin cytol cytologist cytology cytolysin cytolysis cytomegalovirus cytomembrane cytopenia cytophotometer cytophotometry cytoplasm cytoplast cytosine cytoskeleton cytosmear cytosol cytostome cytotoxicity cytotoxin czar czarina czaritza czech czechoslovak czechoslovakia czechoslovakian czerny czestochowa d d-day d-layer d.a. d.c. d.p.r.k. da da'wah dab daba dabbler dabchick daboecia dacca dace dacelo dacha dachau dachshund dachsie dacite dacninae dacoit dacoity dacron dacrycarpus dacrydium dacrymyces dacrymycetaceae dacryocyst dacryocystitis dacryon dactyl dactylis dactyloctenium dactylomegaly dactylopiidae dactylopius dactylopteridae dactylopterus dactylorhiza dactyloscopidae dad dada dadaism daddy dado dae-han- min-gook daedal daedalus daemon daffo daffodil dafla daftness dag dagame dagan dagda dagestani dagga dagger daggerboard dago dagon daguerre daguerreotype dah dahl dahlia dahna dahomey daikon dail daily daimler daimon daintiness dainty daiquiri dairen dairy dairying dairymaid dairyman dais daishiki daisy daisy-bush daisybush dak dakar dakoit dakoity dakota dal dalasi dalbergia dale dalea dalesman daleth dali dalian dallas dalliance dallier dallisgrass dalmane dalmatia dalmatian dalo dalton daltonism dam dama damage damages damaliscus damar damascene damascus damask dame damgalnunna daminozide damkina dammar damn damnation damned damocles damoiselle damon damosel damourite damozel damp dampener dampening damper dampness damsel damselfish damselfly damson dana danaea danaid danaidae danau danaus dance dancer dancing dancing-master dandelion dander dandruff dandy dandyism dane danewort dangaleat danger dangerousness dangla dangle-berry dangleberry dangling daniel danish dankness danmark dano-norwegian danseur danseuse dante danton danu danube danzig daoism daphne daphnia dapperness dapple dapple-gray dapple-grey dappled-gray dappled- grey dapsang dapsone daraf dard dardan dardanelles dardanian dardanus dardic dare daredevil daredevilry daredeviltry darfur dari daricon daring darjeeling dark darkening darkey darkie darkness darkroom darky darling darlingtonia darmera darmstadtium darn darnel darner darning darpa darrow darsana dart dartboard darter dartmouth darts darvon darwin darwinian darwinism das dash dash-pot dashboard dasheen dashiki dasht-e-kavir dasht-e-lut dassie dastard dastardliness dasyatidae dasyatis dasymeter dasypodidae dasyprocta dasyproctidae dasypus dasyure dasyurid dasyuridae dasyurus dat data database date dateline dating dative datril datum datura daub daubentonia daubentoniidae dauber daubing daucus daugavpils daughter daughter-in-law daumier dauntlessness dauphin davallia davalliaceae davenport david daviesia davis davit davy davys daw dawah dawdler dawdling dawes dawn dawning dawson day dayan daybed daybook dayboy daybreak daycare daydream daydreamer daydreaming dayflower dayfly daygirl daylight daylily daypro days dayspring daystar daytime dayton daze dazzle db dba dbms dc dccp dci dd ddc ddi dds ddt de de-escalation de-iodinase de-iodination de-nazification de-stalinisation de-stalinization dea deacon deaconess deactivation dead dead-man's-fingers dead-men's-fingers deadbeat deadbolt deadening deadeye deadhead deadlight deadline deadliness deadlock deadness deadwood deaf deaf-aid deaf-mute deaf-muteness deaf-mutism deafness deal dealer dealership dealfish dealignment dealing dealings deamination deaminization dean deanery deanship dear dearest dearie dearness dearth deary death death-roll deathbed deathblow deathrate deathtrap deathwatch deb debacle debarkation debarment debasement debaser debate debater debauch debauchee debaucher debauchery debenture debilitation debility debit debitor debridement debriefing debris debs debt debtor debugger debunking debussy debut debutante dec decade decadence decadency decadent decadron decaf decagon decagram decahedron decal decalcification decalcomania decalescence decaliter decalitre decalogue decameter decametre decampment decantation decanter decapitation decapod decapoda decapterus decarboxylase decarboxylation decasyllable decathlon decatur decay decease deceased decedent deceit deceitfulness deceiver deceleration december decency decennary decennium decentalisation decentralisation decentralization deception deceptiveness decibel deciding decidua decigram decile deciliter decilitre decimal decimalisation decimalization decimation decimeter decimetre decipherer decipherment decision decisiveness decius deck deck-house decker deckhand deckle declamation declaration declarative declarer declassification declension declination decline declinometer declivity declomycin deco decoagulant decoction decoder decoding decolletage decolonisation decolonization decomposition decompressing decompression decongestant deconstruction deconstructionism deconstructivism decontamination decor decoration decorativeness decorator decorousness decortication decorum decoupage decoy decrease decree decrement decrepitation decrepitude decrescendo decriminalisation decriminalization decryption decubitus decumaria decumary decussation ded dedication dedifferentiation deductible deduction deed deedbox deeds deep deep-freeze deepening deepfreeze deepness deer deer's-ear deer's-ears deerberry deere deerhound deerskin deerstalker deerstalking defacement defalcation defalcator defamation defamer default defaulter defeat defeated defeatism defeatist defecation defecator defect defection defectiveness defector defence defencelessness defendant defender defenestration defense defenselessness defensibility defensive defensiveness deference deferment deferral defervescence defiance defibrillation defibrillator deficiency deficit defilade defile defilement defiler defining definiteness definition deflagration deflation deflator deflection deflector deflexion defloration defoe defoliant defoliation defoliator deforestation deformation deformity defrauder defrayal defrayment defroster deftness defunctness defusing degas degaussing degeneracy degenerate degeneration deglutition degradation degrader degree degustation dehiscence dehumanisation dehumanization dehydration dehydroretinol deicer deictic deification deimos deinocheirus deinonychus deipnosophist deism deist deity deixis dejectedness dejection dejeuner dekagram dekaliter dekalitre dekameter dekametre dekker dekko delacroix delairea delavirdine delaware delawarean delawarian delay delayer delbruck delectability delectation delegacy delegate delegating delegation deletion delf delft delhi deli deliberateness deliberation delibes delicacy delicatessen delichon delicious deliciousness delight delilah delimitation delineation delinquency delinquent deliquium delirium delius deliverable deliverance deliverer delivery deliveryman dell delonix delorme delphi delphinapterus delphinidae delphinium delphinus delta deltasone deltoid deluge delusion demagnetisation demagnetization demagog demagogue demagoguery demagogy demand demander demantoid demarcation demarche dematiaceae demavend demeanor demeanour dementedness dementia demerara demerit demerol demesne demeter demetrius demi-glaze demiglace demigod demijohn demille demimondaine demimonde demineralisation demineralization demise demisemiquaver demister demitasse demiurge demo demobilisation demobilization democracy democrat democratisation democratization democritus demodulation demodulator demogorgon demographer demographic demographist demography demoiselle demolishing demolition demon demonetisation demonetization demoniac demonisation demonism demonization demonolatry demonstrability demonstration demonstrative demonstrativeness demonstrator demoralisation demoralization demosthenes demotic demotion dempsey demulcent demulen demur demureness demurrage demurral demurrer demyelination demythologisation demythologization den denali denationalisation denationalization denaturant denazification dendranthema dendraspis dendrite dendroaspis dendrobium dendrocalamus dendrocolaptes dendrocolaptidae dendroctonus dendroica dendrolagus dendromecon deneb denebola dengue denial denier denigration denim denisonia denizen denmark dennstaedtia dennstaedtiaceae denomination denominationalism denominator denotation denotatum denouement denouncement denseness densification densimeter densitometer densitometry density dent dental dentaria denticle dentifrice dentin dentine dentist dentistry dentition denture denturist denudation denunciation denver deodar deodorant deodourant deossification deoxyadenosine deoxycytidine deoxyephedrine deoxyguanosine deoxyribose deoxythymidine depardieu deparia departed departer department departure dependability dependableness dependance dependant dependence dependency dependent depersonalisation depersonalization depicting depiction depigmentation depilation depilator depilatory depletion deployment depokene depolarisation depolarization deponent depopulation deportation deportee deportment deposer deposit depositary deposition depositor depository depot depravation depravity deprecation depreciation depreciator depredation depressant depression depressive depressor deprivation depth deputation deputy deracination derailment derain derangement derby deregulating deregulation derelict dereliction derision derivation derivative deriving derma dermabrasion dermacentor dermaptera dermatitis dermatobia dermatoglyphic dermatoglyphics dermatologist dermatology dermatome dermatomycosis dermatomyositis dermatophytosis dermatosclerosis dermatosis dermestidae dermis dermochelyidae dermochelys dermoptera derogation derrick derrida derriere derring-do derringer derris derv dervish des desalination desalinisation desalinization descant descartes descendant descendants descendent descender descensus descent description descriptivism descriptor descurainia desecration desegregation desensitisation desensitization desert deserter desertification desertion deserts deservingness deshabille desiccant desiccation desideratum design designation designatum designer designing desipramine desirability desirableness desire desk deskman desktop desmanthus desmid desmidiaceae desmidium desmodium desmodontidae desmodus desmograthus desolation desorption despair despatch desperado desperate desperation despicability despicableness despisal despising despite despoilation despoiler despoilment despoina despoliation despondence despondency despot despotism desquamation dessert dessertspoon dessertspoonful dessiatine destabilisation destabilization destalinisation destalinization destination destiny destitution destroyer destructibility destruction destructiveness desuetude desynchronisation desynchronization desynchronizing desyrel detachment detail detailing details detainee detainment detecting detection detective detector detent detente detention detergence detergency detergent deterioration determent determinant determinateness determination determinative determiner determinism determinist deterrence deterrent detestation dethronement detonation detonator detour detox detoxification detraction detractor detribalisation detribalization detriment detrition detritus detroit detumescence deuce deuce-ace deuteranopia deuterium deuteromycetes deuteromycota deuteromycotina deuteron deuteronomy deutschland deutschmark deutzia devaluation devanagari devastation developer developing development devi deviance deviant deviate deviation deviationism deviationist device devices devil devil-worship devilfish devilment devilry deviltry devilwood deviousness devisal devise devisee deviser devising devisor devitalisation devitalization devoir devolution devolvement devon devonian devonshire devotedness devotee devotion devotional devourer devoutness devries dew dewar dewberry dewdrop dewey dewlap dexamethasone dexedrine dexone dexterity dextrality dextrin dextrocardia dextroglucose dextrorotation dextrose dflp dg dhahran dhak dhaka dhal dharma dhaulagiri dhava dhawa dhegiha dhodhekanisos dhole dhoti dhow dhu'l-hijja dhu'l-hijjah dhu'l-qa'dah di-iodotyrosine dia diabeta diabetes diabetic diabolatry diabolism diabolist diacalpa diacetylmorphine diachrony diacritic diadem diadophis diaeresis diaghilev diaglyph diagnosing diagnosis diagnostician diagnostics diagonal diagonalisation diagonalization diagram diagramming diakinesis dial dialect dialectic dialectician dialectics dialectology dialeurodes dialog dialogue dialysis dialyzer diam diamagnet diamagnetism diamante diameter diamine diamond diamondback diana dianthus diapason diapedesis diapensia diapensiaceae diapensiales diaper diapheromera diaphone diaphoresis diaphoretic diaphragm diaphysis diapir diapsid diapsida diarchy diarist diarrhea diarrhoea diarthrosis diary dias diaspididae diaspora diastasis diastema diastole diastrophism diathermy diathesis diatom diatomite diatomophyceae diatribe diaz diazepam diazonium diazoxide dibber dibble dibbuk dibrach dibranch dibranchia dibranchiata dibranchiate dibs dibucaine dicamptodon dicamptodontid dicamptodontidae dice dicentra dicer diceros dichloride dichlorodiphenyltrichloroethane dichloromethane dichondra dichotomisation dichotomization dichotomy dichroism dichromacy dichromasy dichromat dichromate dichromatism dichromatopsia dichromia dick dickens dickey dickey-bird dickey- seat dickeybird dickhead dickie dickie-seat dickinson dicksonia dicksoniaceae dicky dicky-bird dicky-seat dickybird dicloxacillin dicot dicotyledon dicotyledonae dicotyledones dicoumarol dicranaceae dicranales dicranopteris dicranum dicrostonyx dictamnus dictaphone dictate dictation dictator dictatorship diction dictionary dictostylium dictum dictyophera dictyoptera dictyosome dicumarol dicynodont dicynodontia didacticism didactics didanosine diddley diddly diddly-shit diddly-squat diddlyshit diddlysquat didelphidae didelphis dideoxycytosine dideoxyinosine diderot didion dido didrikson die die- sinker dieback dieffenbachia diegueno diehard dielectric dielectrolysis diemaker diencephalon dieresis diervilla diesel diesel-electric diesel-hydraulic diesinker diesis diestock diestrum diestrus diet dietary dieter dietetics diethylmalonylurea diethylstilbesterol diethylstilbestrol diethylstilboestrol dietician dieting dietitian dietrich difference differentia differential differentiation differentiator difficultness difficulty diffidence difflugia diffraction diffuseness diffuser diffusion diffusor diflunisal dig digenesis digest digester digestibility digestibleness digestion digestive digger digging diggings digit digitalin digitalis digitalisation digitalization digitaria digitigrade digitisation digitiser digitization digitizer digitoxin dignitary dignity digoxin digram digraph digression digs dihybrid dihydrostreptomycin dihydroxyphenylalanine dijon dik-dik dika dike dilantin dilapidation dilatation dilater dilation dilator dilatoriness dilaudid dildo dilemma dilettante diligence dill dillenia dilleniaceae dilleniidae dilly-dallier dillydallier diltiazem diluent dilutant dilution dimaggio dimash dime dimenhydrinate dimension dimensionality dimer dimetane dimetapp dimethylglyoxime dimetrodon diminuendo diminution diminutive diminutiveness dimity dimmer dimness dimocarpus dimorphism dimorphotheca dimout dimple dimwit din dinar dindymene diner dinero dinesen dinette ding ding-dong dingbat dinge dinghy dinginess dingle dingo dining dining-hall dining-room dink dinka dinkey dinky dinner dinnertime dinnerware dinoceras dinocerata dinocerate dinoflagellata dinoflagellate dinornis dinornithidae dinornithiformes dinosaur dint diocesan diocese diocletian diode diodon diodontidae diogenes diol diomedeidae dionaea dionysia dionysius dionysus dioon diophantus diopter dioptre dior diorama diorite dioscorea dioscoreaceae diospyros diovan dioxide dioxin dip diphenhydramine diphenylhydantoin diphtheria diphthong diphylla dipladenia diplegia diplococcus diplodocus diploid diploidy diploma diplomacy diplomat diplomate diplomatist diplopia diplopoda diplopterygium diplotaxis diplotene dipnoi dipodidae dipodomys dipogon dipole dipper dippers dipsacaceae dipsacus dipsomania dipsomaniac dipsosaurus dipstick diptera dipteran dipterocarp dipterocarpaceae dipteron dipteronia dipteryx diptych dipus dipylon dirac dirca direction directionality directive directiveness directivity directness director directorate directorship directory dirge dirham dirigible dirk dirndl dirt dirtiness dirtying dis disa disability disabled disablement disaccharidase disaccharide disadvantage disaffection disaffirmation disagreeableness disagreement disambiguation disambiguator disappearance disappearing disappointment disapprobation disapproval disarmament disarmer disarming disarrangement disarray disassembly disassociation disaster disavowal disbandment disbarment disbelief disbeliever disbursal disbursement disburser disc discant discard disceptation discernability discernment discharge discina disciple discipleship disciplinarian discipline disclaimer disclosure disco discocephali discoglossidae discography discoloration discolouration discombobulation discomfited discomfiture discomfort discomposure discomycete discomycetes disconcertion disconcertment disconnect disconnectedness disconnection disconsolateness discontent discontentedness discontentment discontinuance discontinuation discontinuity discord discordance discotheque discount discounter discouragement discourse discourtesy discoverer discovery discredit discreetness discrepancy discreteness discretion discrimination discriminator discursiveness discus discussant discussion disdain disdainfulness disease disembarkation disembarkment disembarrassment disembowelment disenchantment disenfranchisement disengagement disentanglement disentangler disequilibrium disestablishment disesteem disfavor disfavour disfiguration disfigurement disfluency disforestation disfranchisement disfunction disgorgement disgrace disgracefulness disgruntlement disguise disgust disgustingness dish dishabille disharmony dishcloth disheartenment dishful dishonesty dishonor dishonorableness dishonour dishonourableness dishpan dishrag dishtowel dishware dishwasher dishwashing dishwater disillusion disillusionment disincentive disinclination disinfectant disinfection disinfestation disinflation disinformation disingenuousness disinheritance disintegration disinterest disinterestedness disinterment disinvestment disjointedness disjunction disjuncture disk diskette dislike dislocation dislodgement dislodgment disloyalty dismantlement dismantling dismay dismemberment dismissal dismission dismount disney disneyland disobedience disorder disorderliness disorganisation disorganization disorientation disowning disownment disparagement disparager disparateness disparity dispassion dispassionateness dispatch dispatcher dispensability dispensableness dispensary dispensation dispenser dispersal dispersion dispiritedness displacement display displeasure disposable disposal disposition dispossession dispraise disproof disproportion disprover disputant disputation dispute disqualification disquiet disquietude disquisition disraeli disregard disrepair disreputability disreputableness disrepute disrespect disruption dissatisfaction dissection dissembler dissembling dissemination disseminator dissension dissent dissenter dissertation disservice dissidence dissident dissilience dissimilarity dissimilation dissimilitude dissimulation dissimulator dissipation dissociation dissolubility dissoluteness dissolution dissolve dissolvent dissolver dissolving dissonance dissuasion dissyllable dissymmetry distaff distance distaste distastefulness distemper distension distention distich distillate distillation distiller distillery distillment distinction distinctiveness distinctness distomatosis distortion distortionist distraction distraint distress distressfulness distressingness distributary distributer distribution distributor district distrust distrustfulness disturbance disturber disulfiram disunion disunity disuse disyllable dit dita ditch ditchmoss dither dithering dithyramb dittany ditto ditty diuresis diuretic diuril diva divagation divan divarication dive dive-bombing diver divergence divergency diverseness diversification diversion diversionist diversity diverticulitis diverticulosis diverticulum divertimento divestiture divi-divi divide dividend divider divination divine diviner diving divinity divisibility division divisor divorce divorcee divorcement divot divulgement divulgence divvy diwan dix dixie dixiecrats dixieland dizziness dj djakarta djanet djibouti djiboutian djinn djinni djinny dkg dkl dkm dl dle dm dmd dmus dmz dna dneprodzerzhinsk dnieper dnipropetrovsk do do-gooder do-nothing do-si-do dobbin doberman dobra dobrich dobson dobsonfly doc docent docetism docility dock dock-walloper dockage docker docket dockhand docking dockside dockworker dockyard doctor doctor-fish doctorate doctorfish doctorow doctorspeak doctrinaire doctrine docudrama document documentary documentation dod dodder dodderer doddle dodecagon dodecahedron dodecanese dodge dodgem dodger dodging dodgson dodo dodoma dodonaea doe doei doer doeskin dog dog-ear dog-iron dogbane dogcart doge dogfight dogfighter dogfish doggedness doggerel doggie doggy doghouse dogie dogleg dogma dogmatism dogmatist dogsbody dogshit dogsled dogtooth dogtrot dogwatch dogwood dogy doh doha doi doily doings doj dojc dol dolby doldrums dole dolefulness dolichocephalic dolichocephalism dolichocephaly dolichonyx dolichos dolichotis doliolidae doliolum doll dollar dollarfish dollhouse dollop dolly dolman dolmas dolmen dolobid dolomite dolor dolour dolphin dolphinfish dolt domain domatium dombeya dome domestic domestication domesticity domicile domiciliation dominance dominant domination dominatrix domine dominee domineeringness domingo dominic dominica dominican dominick dominicus dominie dominion dominique domino dominoes dominos dominus domitian don don't-know dona donar donatello donation donatism donatist donatus donbas donbass donee donetsk donetske dong dongle donizetti donjon donkey donkeywork donkin donna donne donor donut doo-wop doob doodad doodia doodle doodlebug doodly-squat doofus doohickey doojigger doolittle doom doomed doomsday door doorbell doorcase doorframe doorhandle doorjamb doorkeeper doorknob doorknocker doorlock doorman doormat doornail doorplate doorpost doorsill doorstep doorstop doorstopper doorway dooryard dopa dopamine dopastat dope doppelganger doppelzentner doppler dorado dorbeetle dorian doric doriden doris dork dorking dorm dormancy dormer dormition dormitory dormouse doronicum dorotheanthus dorsiflexion dorsum dortmund dory dorylinae doryopteris dos dosage dose dosemeter dosimeter dosimetry dossal dossel dosser dosshouse dossier dostoevski dostoevsky dostoyevsky dot dot-com dotage dotard dotrel dotterel dottle douala double double-bogey double-crosser double-crossing double-dealer double-dealing double-decker double-magnum double-prop double-spacing double-u doubleheader doubler doubles doublespeak doublet doublethink doubleton doubletree doubling doubloon doubt doubter doubtfulness douche dough doughboy doughnut douglas douglass doula doura dourah douroucouli dousing dove dovecote dovekie dover dovetail dovishness dovyalis dowager dowdiness dowding dowdy dowel doweling dower dowery dowitcher dowland down down-and-out down-bow downbeat downcast downdraft downer downfall downgrade downheartedness downhill downiness downing downpour downrightness downshift downside downsizing downslope downspin downstage downstroke downswing downtick downtime downtown downturn dowry dowse dowser dowsing doxazosin doxepin doxology doxorubicin doxy doxycycline doyen doyenne doyley doyly doze dozen dozens dozer dp dph dphil dprk dr. drab draba drabness dracaena dracaenaceae dracenaceae drachm drachma draco dracocephalum dracontium dracula dracunculiasis dracunculidae dracunculus draft draftee drafter drafting draftsman draftsmanship draftsperson drag dragee dragger dragnet dragoman dragon dragonet dragonfly dragonhead dragoon dragunov drain drainage drainboard drainpipe drainplug drake dram drama dramamine dramatics dramatisation dramatist dramatization dramaturgy drambuie drape draper drapery draught draughts draughtsman dravidian dravidic draw drawback drawbar drawbridge drawee drawer drawers drawing drawknife drawl drawler drawnwork drawshave drawstring dray drayhorse dread dreadfulness dreadlock dreadnaught dreadnought dream dreamer dreaminess dreaming dreamland dreamworld dreariness dreck dredge dredger dreg dregs dreiser dreissena drenching drepanididae drepanis dresden dress dressage dresser dressing dressmaker dressmaking drew drey dreyfus drib dribble dribbler dribbling driblet drier drift driftage drifter driftfish drifting driftwood drill drilling drimys drink drinkable drinker drinking drip drippage drippiness dripping drippings dripstone drive drive-in drivel driveller driver driveshaft driveway driving drixoral drizzle drms drogheda drogue drollery dromaeosaur dromaeosauridae dromaius drome dromedary dronabinol drone droning drool drooler droop drop drop-leaf drop-off drop-seed dropkick dropkicker droplet dropline dropout dropper droppings dropseed dropsy drosera droseraceae droshky drosky drosophila drosophilidae drosophyllum dross drought drouth drove drover drowse drowsiness drubbing drudge drudgery drug drugget drugging druggist drugstore druid druidism drum drumbeat drumbeater drumfire drumfish drumhead drumlin drummer drumming drumstick drunk drunk-and-disorderly drunkard drunkenness drupe drupelet druse drusen druthers druze dry dry-gulching dryad dryadella dryas dryden drydock dryer drygoods drymarchon drymoglossum drynaria dryness dryopithecine dryopithecus dryopteridaceae dryopteris drypis drywall ds dscdna dsl dtic dts duad dualism dualist duality dub dubai dubbin dubbing dubiety dubiousness dublin dubliner dubnium dubonnet dubrovnik dubuque dubya dubyuh ducat duce duchamp duchess duchy duck duckbill duckboard ducking duckling duckpin duckpins duckweed ducky duct ductileness ductility ductule ductulus dud dude dudeen dudgeon duds due duel dueler duelist dueller duellist duenna duet duette duff duffel duffer duffle dufy dug dugong dugongidae dugout dukas duke dukedom dulciana dulcimer dulcinea dullard dulles dullness dulse duluth duma dumas dumbass dumbbell dumbness dumbwaiter dumdum dumetella dummy dump dumpcart dumper dumpiness dumping dumpling dumplings dumps dumpsite dumpster dumuzi dun duncan dunce dunderhead dune dung dungaree dungeon dunghill dunk dunkard dunker dunkerque dunkers dunkirk dunlin dunnock duo duodecimal duodenum duologue duomo dupe dupery duplex duplicability duplicate duplication duplicator duplicidentata duplicity dura durability durables durabolin duralumin duramen durance durango durant durante duration durative durazzo durban durbar durer duress durga durham durian durio durion durkheim durmast durra durrell durres durum dusanbe duse dushanbe dusicyon dusk duskiness dusseldorf dust dustbin dustcart dustcloth duster dustiness dustman dustmop dustpan dustpanful dustrag dustup dutch dutchman dutchman's-pipe dutifulness duty duvalier duvet dvd dvorak dwarf dwarfishness dwarfism dweeb dweller dwelling dwindling dy dyad dyarchy dyaus dyaus-pitar dybbuk dye dye-works dyeing dyer dyer's-broom dyestuff dyeweed dyewood dying dyirbal dyke dylan dynamic dynamics dynamism dynamite dynamiter dynamitist dynamo dynamometer dynapen dynast dynasty dyne dysaphia dysarthria dyscalculia dyschezia dyscrasia dysdercus dysentery dysfunction dysgenesis dysgenics dysgraphia dyskinesia dyslectic dyslexia dyslogia dysmenorrhea dysomia dysosmia dyspepsia dyspeptic dysphagia dysphasia dysphemism dysphonia dysphoria dysplasia dyspnea dyspnoea dysprosium dyssynergia dysthymia dystopia dystrophy dysuria dytiscidae dyushambe dziggetai e e-bomb e-commerce e-mail e-mycin e.s.p. ea eacles eadwig eager eagerness eagle eaglet eagre eames ear ear-shell earache eardrop eardrum earflap earful earhart earl earlap earldom earliness earlobe earmark earmuff earner earnest earnestness earnings earphone earpiece earplug earreach earring earshot earth earth-ball earth-closet earth- god earth-goddess earth-tongue earthball earthenware earthing earthling earthman earthnut earthquake earthstar earthtongue earthwork earthworm earwax earwig eas ease easel easement easiness easing east east-sider easter easterly easterner eastertide eastman eastward easygoingness eatable eatage eater eatery eating eats eaves eavesdropper eb ebb ebbing ebbtide ebenaceae ebenales ebionite ebit ebitda eblis ebn ebola ebonics ebonite ebony ebro ebs ebullience ebullition eburnation eburophyton ebv ec ecarte ecballium ecc eccentric eccentricity ecchymosis eccles ecclesiastes ecclesiastic ecclesiasticism ecclesiasticus ecclesiology eccm eccyesis ecdysiast ecdysis ecesis ecf ecg echelon echeneididae echeneis echidna echidnophaga echinacea echinocactus echinocereus echinochloa echinococcosis echinococcus echinoderm echinodermata echinoidea echinops echinus echium echo echocardiogram echocardiograph echocardiography echoencephalogram echoencephalograph echoencephalography echogram echography echolalia echolocation echovirus eck eckhart eclair eclampsia eclat eclectic eclecticism eclecticist eclipse eclipsis ecliptic eclogue ecm eco-warfare ecobabble ecologist ecology econometrician econometrics econometrist economics economiser economist economizer economy ecosoc ecosystem ecoterrorism ecotourism ecphonesis ecrevisse ecru ecstasy ect ectasia ectasis ectoblast ectoderm ectomorph ectomorphy ectoparasite ectopia ectopistes ectoplasm ectoproct ectoprocta ectotherm ectozoan ectozoon ectrodactyly ecuador ecuadoran ecuadorian ecumenicalism ecumenicism ecumenism eczema ed edacity edam edaphosauridae edaphosaurus edd edda eddington eddo eddy edecrin edelweiss edema eden edentata edentate ederle edgar edge edger edginess edging edibility edible edibleness edict edification edifice edinburgh edirne edison editing edition editor editorial editorialist editorship edmonton edmontonia edmontosaurus edo edp edronax eds edta educatee education educationalist educationist educator edutainment edward edwardian edwards edwin edwy ee eec eeg eel eelam eelblenny eelgrass eelpout eelworm eeriness effacement effect effecter effectiveness effectivity effector effects effectuality effectualness effectuation effeminacy effeminateness effendi efferent effervescence efficaciousness efficacy efficiency effigy effleurage efflorescence effluence effluent effluvium efflux effort effortfulness effortlessness effrontery effulgence effusion effusiveness eft egalitarian egalitarianism egalite egality egbert egeria egg egg-and-anchor egg-and-dart egg-and-tongue eggar eggbeater eggcup egger eggfruit egghead eggnog eggplant eggs eggshake eggshell eggwhisk egis eglantine eglevsky ego egocentric egocentrism egoism egoist egomania egomaniac egotism egotist egress egression egret egretta egtk egypt egyptian egyptologist egyptology ehadhamen ehf ehrenberg ehrlich eib eibit eichhornia eichmann eider eiderdown eidos eiffel eigen eigenvalue eight eight-spot eighteen eighteenth eighter eighth eighties eightieth eightpence eightsome eightvo eighty eijkman eimeria eimeriidae eindhoven einstein einsteinium einthoven eira eire eisegesis eisenhower eisenstaedt eisenstein eisteddfod ejaculate ejaculation ejaculator ejection ejector ekg ekman el el-aksur ela elaborateness elaboration elaeagnaceae elaeagnus elaeis elaeocarpaceae elaeocarpus elagatis elam elamite elamitic elan eland elanoides elanus elaphe elaphure elaphurus elapid elapidae elasmobranch elasmobranchii elastance elastase elastic elasticity elastin elastomer elastoplast elastosis elater elaterid elateridae elation elavil elbe elbow elbowing eld elder elderberry elderly eldership eldest eldorado elecampane elect election electioneering elective elector electorate electra electric electrician electricity electrification electrocardiogram electrocardiograph electrocardiography electrocautery electrochemistry electrocution electrocutioner electrode electrodeposition electrodynamometer electroencephalogram electroencephalograph electrograph electrologist electrolysis electrolyte electrolytic electromagnet electromagnetics electromagnetism electrometer electromyogram electromyograph electromyography electron electronegativity electronics electrophoresis electrophoridae electrophorus electroplate electroplater electroretinogram electroscope electroshock electrosleep electrostatics electrosurgery electrotherapist electrotherapy electrum elegance elegist elegy element elements elemi eleocharis eleotridae elephant elephant's-foot elephant-tusk elephantiasis elephantidae elephantopus elephas elettaria eleusine eleutherodactylus elevated elevation elevator eleven eleven-plus eleventh elf elgar elia elicitation eligibility elijah elimination eliminator elint elinvar eliomys eliot elisa elisabethville elision elite elitism elitist elixir elixophyllin elizabeth elizabethan elk elk- wood elkhound elkwood ell ellas elli ellington ellipse ellipsis ellipsoid ellipticity ellison ellsworth ellul elm elmont elmwood eln elocution elocutionist elodea elongation elopement elopidae elops eloquence elsass elsholtzia elspar eluate elucidation eluding elul elusion elusiveness elution elver elves elvis elymus elysium elytron em emaciation email emanation emancipation emancipationist emancipator emasculation embalmer embalmment embankment embargo embarkation embarkment embarrassment embassador embassy embayment embellishment ember emberiza emberizidae embezzlement embezzler embiodea embioptera embiotocidae embitterment emblem embodiment embolectomy embolism embolus embonpoint embossment embothrium embouchure embrace embracement embracing embrasure embrocation embroiderer embroideress embroidery embroilment embryo embryologist embryology emcee emda emeer emendation emerald emergence emergency emeritus emersion emerson emery emeside emesis emetic emetrol emf emg emigrant emigration emigre emigree emile emilia emilia-romagna eminence emir emirate emissary emission emitter emmanthe emmenagogue emmental emmentaler emmenthal emmenthaler emmer emmet emmetropia emmy emollient emolument emoticon emotion emotionalism emotionality emotionlessness empathy empedocles empennage emperor empetraceae empetrum emphasis emphasizing emphysema empire empiricism empiricist empirin emplacement employ employable employee employer employment emporium empowerment empress emptiness emptor empty emptying empyema empyrean emu emulation emulator emulsifier emulsion emydidae en en-lil enactment enalapril enallage enamel enamelware enamine enamoredness enanthem enanthema enantiomer enantiomorph enantiomorphism enarthrosis enate enation enbrel encainide encampment encapsulation encasement encaustic encelia enceliopsis encephalartos encephalitis encephalocele encephalogram encephalography encephalomeningitis encephalomyelitis encephalon encephalopathy enchanter enchantment enchantress enchilada enchiridion enchondroma encirclement enclave enclosing enclosure encoding encolure encomium encompassment encopresis encore encounter encouragement encroacher encroachment encrustation encryption enculturation encumbrance encyclia encyclical encyclopaedia encyclopaedism encyclopaedist encyclopedia encyclopedism encyclopedist end end-all end-plate endaemonism endameba endamoeba endamoebidae endangerment endarterectomy endarteritis endearment endeavor endeavour endecott endemic endemism endgame endicott ending endive endlessness endoblast endocarditis endocardium endocarp endocervicitis endocranium endocrine endocrinologist endocrinology endoderm endodontia endodontics endodontist endogamy endogen endogeny endolymph endometriosis endometritis endometrium endomorph endomorphy endomycetales endoneurium endonuclease endoparasite endoplasm endoprocta endorphin endorsement endorser endoscope endoscopy endoskeleton endosperm endospore endosteum endothelium endotoxin endowment endozoan endplate endpoint endurance enduringness ene enema enemy energid energiser energizer energizing energy enervation enesco enets enfeeblement enfeoffment enfilade enflurane enfolding enforcement enforcer enfranchisement engagement engelmannia engels engine engineer engineering enginery england english english-gothic english-weed englishman englishwoman engorgement engram engraulidae engraulis engraver engraving engrossment enhancement enhancer enhydra enid enigma eniwetok enjambement enjambment enjoining enjoinment enjoyableness enjoyer enjoyment enkaid enkephalin enki enkidu enl enlargement enlarger enlightened enlightenment enlil enlistee enlisting enlistment enlivener enmity ennead ennoblement ennui enol enologist enology enophile enormity enormousness enosis enough enovid enquirer enquiry enragement enrichment enrollee enrollment enrolment ensemble ensete ensign ensilage ensis enslavement entablature entail entailment entandrophragma entanglement entasis entebbe entelea entelechy entellus entente enterics entering enteritis enterobacteria enterobacteriaceae enterobiasis enterobius enteroceptor enterokinase enterolith enterolithiasis enterolobium enteron enteropathy enteroptosis enterostenosis enterostomy enterotomy enterotoxemia enterotoxin enterovirus enterprise enterpriser enterprisingness entertainer entertainment enthalpy enthrallment enthronement enthronisation enthronization enthusiasm enthusiast enticement entire entireness entirety entitlement entity entlebucher entoblast entoderm entoloma entolomataceae entombment entomion entomologist entomology entomophobia entomophthora entomophthoraceae entomophthorales entomostraca entoparasite entoproct entoprocta entourage entozoan entozoon entr'acte entrails entrance entrancement entranceway entrant entrapment entreaty entrecote entree entremets entrenchment entrepot entrepreneur entresol entric entropy entry entryway entsi entsy enucleation enuki enumeration enumerator enunciation enuresis envelope envelopment enviousness environment environmentalism environmentalist environs envisioning envoi envoy envy enzyme enzymologist enzymology eocene eohippus eolian eolic eolith eolithic eon eoraptor eos eosin eosinopenia eosinophil eosinophile eosinophilia epa epacridaceae epacris epanalepsis epanaphora epanodos epanorthosis eparch eparchy epaulet epaulette epauliere epee ependyma epenthesis epergne epha ephah ephedra ephedraceae ephedrine ephemera ephemeral ephemerality ephemeralness ephemerid ephemerida ephemeridae ephemeris ephemeron ephemeroptera ephemeropteran ephesian ephesians ephestia ephesus ephippidae ephippiorhynchus epi epic epicalyx epicanthus epicardia epicardium epicarp epicene epicenter epicentre epicondyle epicondylitis epicranium epictetus epicure epicurean epicureanism epicurism epicurus epicycle epicycloid epidemic epidemiologist epidemiology epidendron epidendrum epidermis epidiascope epididymis epididymitis epidural epigaea epigastrium epigenesis epiglottis epiglottitis epigon epigone epigram epigraph epigraphy epikeratophakia epilachna epilation epilator epilepsy epileptic epilobium epilog epilogue epimedium epimetheus epinephelus epinephrin epinephrine epipactis epipaleolithic epiphany epiphenomenon epiphora epiphyllum epiphysis epiphyte epiplexis epipremnum epirus episcia episcleritis episcopacy episcopalian episcopalianism episcopate episiotomy episode episome epispadias episperm epistasis epistaxis episteme epistemologist epistemology epistle epistrophe epitaph epitaxy epithalamium epithelioma epithelium epithet epitome epitope epizoan epizoon epoch epona eponym eponymy epos epoxy eprom epsilon epstein eptatretus eptesicus eq equal equalisation equaliser equalitarian equalitarianism equality equalization equalizer equanil equanimity equatability equating equation equator equatorial equerry equestrian equetus equid equidae equidistribution equilateral equilibration equilibrium equine equinoctial equinox equipage equipment equipoise equipping equisetaceae equisetales equisetatae equisetum equitation equity equivalence equivalent equivocalness equivocation equivocator equus er era eradication eradicator eragrostis eranthis eraser erasmus erastianism erasure erato eratosthenes erbium ercilla erebus erecting erection erectness eremite eremitism eresh-kigal ereshkigal ereshkigel erethism erethizon erethizontidae eretmochelys erewhon erg ergocalciferol ergodicity ergometer ergonomics ergonovine ergosterol ergot ergotamine ergotism ergotropism erianthus erica ericaceae ericales eridanus erie erigeron erignathus erin erinaceidae erinaceus eringo erinyes eriobotrya eriocaulaceae eriocaulon eriodictyon eriogonum eriophorum eriophyllum eriosoma eris eristic erithacus eritrea eritrean erivan erlang erlenmeyer ermine ern erne ernst eroding erodium erolia eros erosion erotic erotica eroticism erotism errancy errand erratum erroneousness error ersatz erse ert eruca eructation eruditeness erudition eruption erving erwinia eryngium eryngo erysimum erysipelas erysiphaceae erysiphales erysiphe erythema erythrina erythrite erythroblast erythroblastosis erythrocebus erythrocin erythrocyte erythrocytolysin erythroderma erythrolysin erythromycin erythronium erythropoiesis erythropoietin erythroxylaceae erythroxylon erythroxylum es esaki esau escadrille escalade escalader escalation escalator escallop escapade escape escapee escapement escapism escapist escapologist escapology escargot escarole escarp escarpment eschalot eschar eschatologist eschatology eschaton escheat escherichia eschrichtiidae eschrichtius eschscholtzia escolar escort escritoire escrow escudo escutcheon ese esfahan esidrix eskalith esker eskimo eskimo-aleut esm esmolol esocidae esop esophagitis esophagoscope esophagus esoterica esotropia esox esp espadrille espagnole espalier espana esparcet esperantido esperanto espial espionage esplanade espoo espousal espresso esprit esq esquimau esquire esr essay essayer essayist esselen essen essence essene essential essentiality essentialness essex essonite est establishment establishmentarianism establishmentism estaminet estate estazolam esteem ester esther esthesia esthesis esthete esthetic esthetician esthetics esthonia esthonian estimate estimation estimator estivation estonia estonian estoppel estradiol estragon estrangement estrilda estriol estrogen estrone estronol estrus estuary esurience eta etagere etamin etamine etanercept etcetera etcher etching etd eternity etf ethanal ethanamide ethane ethanediol ethanoate ethanol ethchlorvynol ethelbert ethelred ethene ether ethernet ethic ethician ethicism ethicist ethics ethiopia ethiopian ethmoid ethnarch ethnic ethnicity ethnocentrism ethnographer ethnography ethnologist ethnology ethnos ethocaine ethologist ethology ethos ethosuximide ethoxyethane ethrane ethril ethyl ethylene ethyne etiolation etiologist etiology etiquette etna etodolac etonian etropus etruria etruscan etude etui etymologist etymologizing etymology etymon eu euarctos euascomycetes eubacteria eubacteriales eubacterium eubryales eubstance eucalypt eucalyptus eucarya eucaryote eucharist euchre eucinostomus euclid eudaemon eudaemonia eudaimonia eudemon eudemonism euderma eudiometer eudyptes eugene eugenia eugenics euglena euglenaceae euglenid euglenoid euglenophyceae euglenophyta euglenophyte eukaryote euler eulogist eulogium eulogy eumeces eumenes eumenides eumetopias eumops eumycetes eumycota eunectes eunuch eunuchoidism euonymus eupatorium euphagus euphausiacea euphemism euphonium euphony euphorbia euphorbiaceae euphorbium euphoria euphoriant euphory euphractus euphrates euphrosyne euphuism euplectella eupnea eupnoea euproctis eurafrican eurasia eurasian eureka eurhythmics eurhythmy euripides euro eurobabble eurocentrism eurocurrency eurodollar euronithopod euronithopoda europa europan europe european europeanisation europeanization europium europol eurotiales eurotium euryale euryalida eurydice eurylaimi eurylaimidae eurypterid eurypterida eurythmics eurythmy eusebius eusporangium eustachio eustoma eutamias eutectic euterpe euthanasia euthenics eutheria eutherian euthynnus eutrophication ev evacuation evacuee evaluation evaluator evanescence evangel evangelicalism evangelism evangelist evans evansville evaporation evaporite evaporometer evasion evasiveness eve even evenfall evening evening-snow eveningwear evenk evenki evenness evensong event eventide eventration eventuality everest everglades evergreen everlasting everlastingness evernia evers eversion evert everting everydayness everyman eviction evidence evil evildoer evildoing evilness evisceration evocation evolution evolutionism evolutionist ew ewe ewenki ewer ex ex-boyfriend ex-gambler ex-husband ex-mayor ex-president ex-serviceman ex-spouse ex-wife exabit exabyte exacerbation exacta exaction exactitude exactness exacum exaeretodon exaggeration exaltation exam examen examination examinee examiner example exanthem exanthema exarch exarchate exasperation exbibit exbibyte excalibur excavation excavator exceedance excellence excellency excelsior exception excerpt excerption excess excessiveness exchange exchangeability exchanger exchequer excise exciseman excision excitability excitableness excitant excitation excitement exclaiming exclamation exclusion exclusive exclusiveness excogitation excogitator excommunication excoriation excrement excrescence excreta excreting excretion excruciation exculpation excursion excursionist excursus excuse excuser exec execration executability executant executing execution executioner executive executor executrix exegesis exegete exemplar exemplification exemption exenteration exercise exerciser exercising exercycle exertion exfoliation exhalation exhaust exhaustion exhibit exhibition exhibitioner exhibitionism exhibitionist exhibitor exhilaration exhortation exhumation exigency exiguity exile existence existentialism existentialist exit exmoor exobiology exocarp exocet exocoetidae exocrine exocycloida exode exoderm exodontia exodontics exodontist exodus exogamy exogen exomphalos exon exoneration exonuclease exophthalmos exopterygota exorbitance exorciser exorcism exorcist exordium exoskeleton exosphere exostosis exotherm exoticism exoticness exotism exotoxin exotropia expanse expansion expansionism expansiveness expansivity expat expatiation expatriate expatriation expectancy expectation expectedness expectorant expectoration expectorator expedience expediency expedient expedition expeditiousness expelling expender expending expenditure expense expensiveness experience experiment experimentalism experimentation experimenter expert expertise expertness expiation expiration expiry explanandum explanans explanation expletive explicandum explication explicitness exploit exploitation exploiter exploration explorer explosion explosive expo exponent exponential exponentiation export exportation exporter exporting expose exposition expositor expostulation exposure expounder expounding express expressage expression expressionism expressionist expressiveness expressway expropriation expulsion expunction expunging expurgation expurgator exquisiteness extemporisation extemporization extension extensiveness extensor extent extenuation exterior exteriorisation exteriorization extermination exterminator extern external externalisation externality externalization exteroception exteroceptor extinction extinguisher extinguishing extirpation extoller extolment extortion extortioner extortionist extra extract extraction extractor extradition extrados extraneousness extraordinariness extrapolation extrasystole extraterrestrial extravagance extravagancy extravaganza extravasation extraversion extravert extreme extremeness extremism extremist extremity extremum extrication extropy extroversion extrovert extrusion exuberance exudate exudation exultation exurbia exuviae eyas eyck eye eye- beaming eye-catcher eye-drop eye-lotion eyeball eyebath eyebrow eyecup eyedness eyedrop eyeful eyeglass eyeglasses eyehole eyeish eyelash eyelessness eyelet eyelid eyeliner eyepatch eyepiece eyes eyeshade eyeshadow eyeshot eyesight eyesore eyespot eyestrain eyetooth eyewash eyewitness eyra eyre eyrie eyrir eyry eysenck ezechiel ezed ezekias ezekiel ezo ezo-yama-hagi ezra f f.i.s.c. fa faa fabaceae faberge fabian fabiana fabianism fable fabric fabrication fabricator fabulist facade face face-off facelift faceplate facer facet facetiousness facia facial facilitation facilitator facility facing facsimile fact faction factoid factor factorial factoring factorisation factorization factory factotum factuality factualness facula faculty fad faddist fade fadeout fading fado fae faecalith faeces faerie faeroes faeroese faery fafnir fag fagaceae fagales faggot faggoting fagin fagopyrum fagot fagoting fagus fahd fahrenheit faience fail-safe failing faille failure faineance faint faintheartedness faintness fair fair-maids-of-france fair-mindedness fairbanks fairground fairlead fairness fairway fairy fairy-slipper fairyland fairytale faisal faisalabad faith faithful faithfulness faithlessness fake fakeer faker fakery fakir falafel falanga falange falangist falcatifolium falchion falco falcon falcon-gentil falcon- gentle falconer falconidae falconiformes falconry falderol falkner fall fall- board falla fallaciousness fallacy fallal fallback fallboard faller fallibility falloff fallopio fallopius fallot fallout fallow falls falsehood falseness falsetto falsie falsification falsifier falsifying falsity falstaff falter faltering fame familiar familiarisation familiarity familiarization family famine famishment famotidine famulus fan fan-jet fanaloka fanatic fanaticism fanatism fancier fancy fancywork fandango fandom fanfare fang fanion fanjet fanlight fanny fantail fantan fantasia fantasist fantasm fantast fantasy fantods fanweed fanwort fao faq faqir faquir far farad faraday farandole farawayness farc farce fardel fare fare-stage fare-thee-well farewell farfalle fargo farina farkleberry farm farm-place farmer farmerette farmhand farmhouse farming farmington farmland farmplace farmstead farmyard farness faro faroes faroese farrago farragut farrell farrier farrow farrowing farsi farsightedness fart farthing farthingale farting fartlek fas fasces fascia fascicle fasciculation fascicule fasciculus fascination fasciola fascioliasis fasciolidae fasciolopsiasis fasciolopsis fasciolosis fascism fascist fascista fashion fashioning fashionmonger fast fastball fastener fastening fastidiousness fasting fastnacht fastness fat fatah fatah-rc fatalism fatalist fatality fatback fate fathead father father-figure father-god father-in-law fatherhood fatherland fatherliness fathom fathometer fatigability fatigue fatigues fatiha fatihah fatima fatimah fatism fatness fatso fattiness fattism fatty fatuity fatuousness fatwa fatwah faubourg fauces faucet fauld faulkner fault faultfinder faultfinding faultiness faulting faultlessness faun fauna fauntleroy faunus faust faustus fauteuil fauve fauvism fauvist favism favor favorableness favorite favoritism favour favourableness favourite favouritism favus fawkes fawn fawner fax fay fayetteville fbi fcc fcs fda fdic fdr fe fealty fear fearfulness fearlessness feasibility feasibleness feast feasting feat feather feather-foil featherbed featherbedding featheredge featherfoil featheriness feathering feathertop featherweight feature feb febricity febrifuge febrility february fecalith feces fechner fecklessness fecula feculence fecundation fecundity fed fedayeen fedelline federal federalisation federalism federalist federalization federation federita fedora fee feeblemindedness feebleness feed feedback feedbag feeder feeding feedlot feedstock feel feeler feeling feelings feifer feigning feijoa feint feist felafel feldene feldspar felicia felicitation felicitousness felicity felid felidae feline felis fell fella fellah fellata fellatio fellation feller fellini felloe fellow fellowship felly felo-de-se felon felony felspar felt felucca felwort fema female femaleness feminine feminineness femininity feminisation feminism feminist feminization femoris femtochemistry femtometer femtometre femtosecond femtovolt femur fen fence fence-sitter fencer fencesitter fencing fender fender-bender fenestella fenestra fenestration fengtien fenland fennel fennic fenoprofen fenrir fentanyl fenugreek fenusa feoff feosol fer-de- lance ferber ferdinand fergon fergusonite feria fermat fermata ferment fermentation fermenting fermentologist fermi fermion fermium fern ferocactus ferociousness ferocity ferrara ferret ferricyanide ferrimagnetism ferrite ferritin ferrocerium ferroconcrete ferrocyanide ferromagnetism ferrule ferry ferryboat ferrying ferryman fertilisation fertiliser fertility fertilization fertilizer ferule fervency fervidness fervor fervour fes fescue fess fesse fester festering festination festival festivity festoon festoonery festschrift festuca fet fetch fete feterita fetich fetichism feticide fetidness fetish fetishism fetishist fetlock fetology fetometry fetoprotein fetor fetoscope fetoscopy fetter fetterbush fettle fettuccine fettuccini fetus feud feudalism feudatory fever feverfew feverishness feverroot few fewness feynman fez fha fhlmc fiance fiancee fiasco fiat fib fibber fibbing fiber fiberboard fiberglass fiberoptics fiberscope fibre fibreboard fibreglass fibreoptics fibril fibrillation fibrin fibrinase fibrinogen fibrinolysin fibrinolysis fibrinopeptide fibroadenoma fibroblast fibrocartilage fibroid fibroma fibromyositis fibrosis fibrositis fibrosity fibrousness fibula fica fice fichu fickleness fiction fictionalisation fictionalization ficus fiddle fiddle-faddle fiddlehead fiddleneck fiddler fiddlestick fidelity fidget fidgetiness fiduciary fiedler fief fiefdom field fielder fieldfare fieldhand fielding fieldmouse fields fieldsman fieldstone fieldwork fieldworker fiend fierceness fieriness fiesta fife fifo fifteen fifteenth fifth fifties fiftieth fifty fig fig-bird figeater fight fighter fighting figment figuration figure figurehead figurer figurine figuring figwort fiji fijian fijis filaggrin filago filagree filament filaree filaria filariasis filariidae filature filbert file filefish filename filer filet filiation filibuster filibusterer filicales filicide filicinae filicopsida filigree filing filipino fill fill-in fillagree fille filler fillet filling fillip fillmore filly film filmdom filming filmmaker filoviridae filovirus fils filter filth filthiness filtrate filtration filum fimbria fin finagler final finale finalisation finalist finality finalization finance finances financier financing finback fincen finch find finder finding findings fine fineness finery finesse finger finger-flower finger-painting finger- pointing finger-roll finger-root fingerboard fingerbreadth fingerflower fingering fingerling fingermark fingernail fingerpaint fingerpointing fingerpost fingerprint fingerprinting fingerroot fingerspelling fingerstall fingertip finial finis finish finisher finishing finiteness finitude fink finland finn finnan finnbogadottir finnic finnish finno-ugrian finno-ugric finocchio fiord fipple fir fire fire-bush fire-eater fire-on-the-mountain fire-raising fire- swallower fire-wheel fire-worship firearm fireball firebase firebird fireboat firebomb firebox firebrand firebrat firebreak firebrick firebug fireclay firecracker firedamp firedog firedrake firefighter firefly fireguard firehouse firelight firelighter firelock fireman firenze fireplace fireplug firepower fireroom fireside firestone firestorm firethorn firetrap firewall firewater fireweed firewood firework firing firkin firm firmament firmiana firmness firmware first first-nighter first-rater firstborn firth fisa fisc fischer fish fish-fly fish-worship fishbone fishbowl fisher fisherman fishery fishgig fishhook fishing fishmonger fishnet fishpaste fishplate fishpond fishwife fishworm fission fissiparity fissiped fissipedia fissure fissurella fissurellidae fist fistfight fistful fisticuffs fistmele fistula fistularia fistulariidae fistulina fistulinaceae fit fitch fitfulness fitment fitness fitter fitting fittingness fitzgerald five five-finger five-hitter five-spot fivepence fiver fives fivesome fix fixation fixative fixedness fixer fixer-upper fixing fixings fixity fixture fizgig fizz fizzle fjord fl flab flabbiness flaccidity flack flacourtia flacourtiaceae flag flag-waver flagellant flagellata flagellate flagellation flagellum flageolet flagfish flagging flagon flagpole flagroot flagship flagstaff flagstone flagyl flail flair flak flake flakiness flambeau flamboyance flamboyant flame flame-flower flame-out flamefish flameflower flamen flamenco flamethrower flaming flamingo flaminius flammability flammulina flan flanders flange flank flanker flannel flannel-cake flannelbush flannelette flap flapcake flapjack flapper flapping flaps flare flare-up flash flash-forward flashback flashboard flashboarding flashbulb flashcard flasher flashflood flashgun flashiness flashing flashlight flashover flashpoint flask flaskful flat flatbed flatboat flatbread flatbrod flatcar flatfish flatfoot flathead flatiron flatlet flatmate flatness flats flatterer flattery flattop flatulence flatulency flatus flatware flatwork flatworm flaubert flaunt flautist flavin flaviviridae flavivirus flavone flavonoid flavor flavorer flavoring flavorlessness flavorsomeness flavour flavourer flavouring flavourlessness flavoursomeness flaw flawlessness flax flaxedil flaxseed flea fleabag fleabane fleapit fleawort flecainide fleck flection fledgeling fledgling fleece fleer fleet fleetingness fleetness fleming flemish flesh fleshiness fletc fletcher fleur-de-lis fleur-de-lys flex flexeril flexibility flexibleness flexion flexor flexure flibbertigibbet flick flick-knife flicker flickertail flier flies flight flightiness flimflam flimsiness flimsy flinch flinders flindersia flindosa flindosy fling flint flinthead flintlock flintstone flip flip-flop flippancy flipper flirt flirtation flirting flit flitch flnc float floatation floater floating floating-moss floatplane floc flocculation floccule flock flodden floe flogger flogging flood floodgate floodhead flooding floodlight floodplain floor floorboard flooring floorshow floorwalker floozie floozy flop flophouse floppy flora floreal florence florentine florescence floret florey floriculture florida floridian floridity floridness florilegium florin florio florist flory floss flotation flotilla flotsam flounce flounder flour flourish flouter flow flowage flowchart flower flower-of-an-hour flowerbed floweret flowering flowerpot flowers-of-an-hour flowing floxuridine flu flub fluctuation flue fluegelhorn fluency fluff fluffiness flugelhorn fluid fluidity fluidness fluidounce fluidram fluke flume flummery flunitrazepan flunk flunkey flunky fluor fluorapatite fluorescein fluoresceine fluorescence fluorescent fluoridation fluoride fluoridisation fluoridization fluorine fluorite fluoroboride fluorocarbon fluorochrome fluoroform fluoroscope fluoroscopy fluorosis fluorouracil fluorspar fluosilicate fluoxetine fluphenazine flurazepam flurbiprofen flurry flush fluster flute fluting flutist flutter fluttering fluvastatin flux fluxion fluxmeter fly fly-by fly-by-night fly-fishing flybridge flycatcher flyer flying flyleaf flyover flypaper flypast flyspeck flyswat flyswatter flytrap flyway flyweight flywheel fm fmri fnma fo fo'c'sle foal foam foamflower foaminess fob focalisation focalization focus focusing focussing fodder foe foehn foeman foeniculum foetology foetometry foetoprotein foetor foetoscope foetoscopy foetus fog fogbank fogey fogginess foghorn foglamp fogsignal fogy fohn foible foil foiling folacin folate fold folder folderal folderol folding foldout foliage foliation folie folio folium folk folklore folks folksong folktale follicle folliculitis follies follow-on follow-through follow-up follower followers following followup folly fomentation fomenter fomes fomite fomor fomorian fonda fondant fondler fondling fondness fondu fondue font fontanel fontanelle fontanne fontenoy fonteyn food foodie foodstuff fool foolery foolhardiness foolishness foolscap foot foot-lambert foot-pound foot-poundal foot-ton footage football footballer footbath footboard footbridge footcandle footedness footer footfall footfault footgear foothill foothold footing footlights footlocker footman footmark footnote footpad footpath footplate footprint footrace footrest footslogger footstall footstep footsteps-of-spring footstool footwall footwear footwork fop foppishness forage forager foraging foram foramen foraminifer foraminifera foray forbear forbearance forbiddance forbidding force force-out forcefulness forcemeat forceps ford fordhooks fording fore fore-and-after fore- topmast fore-topsail fore-wing forearm forebear foreboding forebrain forecast forecaster forecasting forecastle foreclosure forecourt foredeck foredge forefather forefinger forefoot forefront foreground foregrounding forehand forehead foreigner foreignness foreknowledge forelady foreland foreleg forelimb forelock foreman foremanship foremast foremilk foremother forename forenoon forensics foreordination forepart forepaw foreperson foreplay forequarter forerunner foresail foreshadowing foreshank foreshock foreshore foresight foresightedness foresightfulness foreskin forest forestage forestalling forestay forester forestiera forestry foretaste foretelling forethought foretoken foretop forewarning forewing forewoman foreword forfeit forfeiture forficula forficulidae forge forger forgery forget-me-not forgetfulness forging forgiveness forgiver forgivingness forgoing forint fork forking forklift forlornness form formal formaldehyde formalin formalisation formalism formalities formality formalization formalness formalwear format formation formative formatting former formica formicariidae formicarius formicary formication formicidae formidability formol formosa formosan formula formulary formulation fornax fornication fornicator fornicatress fornix forsaking forseti forswearing forsythia fort fort-lamy fortaz forte forte-piano forth forthcomingness forthrightness forties fortieth fortification fortissimo fortitude fortnight fortran fortress fortuitousness fortuity fortuna fortune fortunella fortuneteller fortunetelling forty forty-five forty-niner forum forward forwarding forwardness foryml fosamax fosbury fossa fosse fossil fossilisation fossilist fossilization fossilology foster foster-brother foster- child foster-daughter foster-father foster-mother foster-nurse foster-parent foster-sister foster-son fosterage fostering fosterling fothergilla fots foucault foul foul-up foulard foulmart foulness foumart found foundation founder foundering founding foundling foundress foundry fount fountain fountainhead fouquieria fouquieriaceae four four-flusher four-hitter four-in-hand four-poster four-pounder four-spot four-wheeler fourier fourpence fourscore foursome foursquare fourteen fourteenth fourth fovea fowl fowler fox fox-trot foxberry foxglove foxhole foxhound foxhunt foxiness foxtail foxtrot foyer fpd fps fr fracas fractal fraction fractionation fractiousness fracture fradicin fragaria fragility fragment fragmentation fragonard fragrance fragrancy frail frailness frailty fraise frambesia framboesia framboise frame frame-up framer framework framing franc franc-tireur france franche-comte franchise franciscan francisella francium franck franco franco-american francoa francophil francophile francophobe frangibility frangibleness frangipane frangipani frangipanni frank frankenstein frankfort frankfurt frankfurter frankincense franklin frankliniella frankness frappe frasera frat fratercula fraternisation fraternity fraternization fratricide frau fraud fraudulence fraulein fraxinella fraxinus fray frazer frazzle freak freakishness freckle frederick fredericksburg fredericton free free-for-all free-lance free-liver free-reed freebee freebie freebooter freedman freedom freedwoman freehold freeholder freeing freelance freelancer freeloader freemail freeman freemason freemasonry freesia freestone freestyle freetail freethinker freethinking freetown freeware freeway freewheel freewheeler freewoman freeze freeze-drying freezer freezing fregata fregatidae freight freightage freighter fremont fremontia fremontodendron french frenchman frenchwoman frenzy freon frequence frequency frequentative frequenter fresco freshener fresher freshet freshman freshness freshwater fresnel fresno fret fretfulness fretsaw fretwork freud freudian frey freya freyja freyr frg fri friability friar friar's-cowl friary fricandeau fricassee fricative frick friction friday fridge friedan friedcake friedman friend friendlessness friendliness friendly friendship frier fries friesian friesland frieze frigate frigg frigga fright frightening frightfulness frigidity frigidness frijol frijole frijolillo frijolito frill frimaire fringe fringepod fringilla fringillidae frippery frisbee frisch frisia frisian frisk friskiness frisking frisson fritillaria fritillary frittata fritter friuli friulian frivolity frivolousness frizz frobisher frock froebel froelichia frog frog's-bit frogbit frogfish froghopper frogman frogmouth frolic frolicsomeness frond front front- runner front-stall frontage frontal frontbencher frontier frontiersman frontierswoman frontispiece frontlet frontstall frost frost-weed frostbite frostiness frosting frostweed frostwort froth frothiness frottage frotteur frown frs fructidor fructification fructose fructosuria frugality frugalness fruit fruitage fruitcake fruiterer fruitfulness fruition fruitlessness fruitlet fruitwood frumenty frump frunze frustration frustum fry frye fryer frying frypan fsb fsh ft ft-l ftc fthm fto ftp fucaceae fucales fuchs fuchsia fuck fucker fuckhead fucking fuckup fucoid fucus fuddle fuddy-duddy fudge fuego fuel fueling fuentes fug fugaciousness fugacity fugard fugitive fugleman fugo fugu fugue fuji fuji-san fujinoyama fujiyama fukien fukkianese fukuoka ful fula fulah fulani fulbe fulbright fulcrum fulfillment fulfilment fulgoridae fulica full full-of- the-moon fullback fuller fullerene fullness fulmar fulmarus fulminate fulmination fulsomeness fulton fulvicin fumaria fumariaceae fumble fumbler fume fumeroot fumes fumewort fumigant fumigation fumigator fumitory fun funafuti funambulism funambulist function functionalism functionalist functionality functionary functioning fund fundament fundamental fundamentalism fundamentalist fundamentals funding fundraiser funds fundulus fundus funeral funeral-residence funfair fungi fungia fungibility fungible fungicide fungus funicle funicular funiculitis funiculus funk funka funkaceae funnel funnies funniness funny funrun fuqra fur fur-piece furan furane furbelow furcation furcula furfural furfuraldehyde furfuran furiousness furlong furlough furnace furnariidae furnarius furnishing furniture furnivall furor furore furosemide furrier furring furrow furtherance furtiveness furuncle furunculosis fury furze fusain fusanus fuschia fuscoboletinus fuse fusee fuselage fusil fusilier fusillade fusion fuss fuss-budget fussiness fusspot fustian futility futon future futurism futurist futuristics futurity futurology fuze fuzee fuzz fuzziness fws g g-force g-jo g-man g-string ga gaap gab gaba gabapentin gabardine gabble gabbro gaberdine gabfest gable gabon gabonese gabor gaboriau gaborone gabriel gabun gad gadaba gadabout gaddafi gaddi gadfly gadget gadgeteer gadgetry gadidae gadiformes gadoid gadolinite gadolinium gadsden gadus gaea gael gaelic gaff gaffe gaffer gaffsail gafsa gag gagarin gage gaggle gagman gagster gagwriter gaia gaiety gaillardia gain gainer gainesville gainfulness gainsborough gaiseric gait gaiter gaius gal gala galactagogue galactocele galactose galactosemia galactosis galago galahad galan galangal galantine galapagos galatea galatia galatian galatians galax galaxy galbanum galbraith galbulidae galbulus gale galea galega galen galena galeocerdo galeopsis galeorhinus galeras galere galicia galician galilaean galilean galilee galileo galingale galium gall gall-berry gallamine gallant gallantry gallaudet gallberry gallbladder galleon galleria gallery galley gallfly gallia galliano gallicanism gallicism galliformes gallimaufry gallina gallinacean gallinago gallinula gallinule gallirallus gallium gallon gallop gallous galloway gallows gallows-tree gallstone gallup gallus galois galoot galosh galsworthy galton galvani galvanisation galvaniser galvanism galvanization galvanizer galvanometer galveston galway gam gamba gambelia gambia gambian gambist gambit gamble gambler gambling gamboge gambol gambrel gambusia game gamebag gameboard gamecock gamekeeper gamelan gameness games-master games- mistress gamesmanship gametangium gamete gametocyte gametoecium gametogenesis gametophore gametophyte gamin gamine gaminess gaming gamma gamma-interferon gammon gammopathy gamow gamp gamut ganapati gand gander gandhi ganef ganesa ganesh ganesha gang gangboard gangdom ganger ganges gangland gangliocyte ganglion gangplank gangrene gangsaw gangsta gangster gangway ganja gannet ganof ganoid ganoidei ganoin ganoine gansu gantanol gantlet gantrisin gantry ganymede gao gaol gaolbird gaolbreak gaoler gap gape gar garage garambulla garamycin garand garb garbage garbageman garbanzo garbo garboard garboil garbology garcinia garden gardener gardenia gardening gardiner gardner garfield garfish garganey gargantua garget gargle gargoyle gargoylism gari garibaldi garishness garland garlic garment garment-worker garmentmaker garner garnet garnier garnierite garnish garnishee garnishment garonne garotte garpike garret garrick garrison garrote garroter garrotte garrotter garrulinae garrulity garrulousness garrulus garter garuda gary gas gasbag gascogne gasconade gascony gaseousness gasfield gash gasherbrum gasification gaskell gasket gaskin gaslight gasman gasmask gasohol gasolene gasoline gasometer gasp gaspar gassing gasteromycete gasteromycetes gasterophilidae gasterophilus gasteropoda gasterosteidae gasterosteus gastralgia gastrectomy gastrin gastritis gastroboletus gastrocnemius gastrocybe gastroenteritis gastroenterologist gastroenterology gastroenterostomy gastrogavage gastrolobium gastromy gastromycete gastromycetes gastronome gastronomy gastrophryne gastropod gastropoda gastroscope gastroscopy gastrostomy gastrula gastrulation gasworks gat gate gateau gatecrasher gatefold gatehouse gatekeeper gatepost gates gateway gather gatherer gathering gathic gatling gator gatt gaucheness gaucherie gaucho gaud gaudery gaudi gaudiness gaudy gauffer gauge gauguin gaul gaultheria gauntlet gauntness gauntry gaur gauri gauss gaussmeter gautama gauze gavage gavel gavia gavial gavialidae gavialis gavidae gaviiformes gavotte gawain gawk gawker gawkiness gay gay- feather gay-lussac gayal gayfeather gaylussacia gayness gaywings gaza gazania gaze gazebo gazella gazelle gazette gazetteer gazillion gazpacho gb gbit gbu-28 gc gca gcse gd gdansk gdp ge gean gear gearbox gearing gearset gearshift gearstick geartrain geastraceae geastrum geb gecko gee gee-gee geebung geek geezer geezerhood gegenschein geglossaceae gehenna gehrig geiger geisel geisha gekkonidae gel gelatin gelatine gelatinousness gelding gelechia gelechiid gelechiidae gelidity gelignite gell-mann gelly gelsemium gelt gem gemara gemfibrozil geminate gemination gemini gemma gemmation gemmule gemonil gempylid gempylidae gempylus gemsbok gemsbuck gemstone gen gendarme gendarmerie gendarmery gender gene gene-splicing genealogist genealogy general generalcy generalisation generalissimo generalist generality generalization generalship generation generator generic generosity generousness genesis genet geneticism geneticist genetics genetta geneva genevan geneve genf geniality genie genip genipa genipap genista genitalia genitals genitive genitor genius genlisea genoa genocide genoese genoise genome genomics genotype genova genre gens genseric gent gentamicin genteelness gentian gentiana gentianaceae gentianales gentianella gentianopsis gentile gentility gentlefolk gentleman gentleman's-cane gentleman-at-arms gentleness gentlewoman gentrification gentry genu genuflection genuflexion genuineness genus genus-fenusa genus-megapodius genus-milvus genyonemus geochelone geochemistry geococcyx geode geodesic geodesy geoduck geoffroea geoglossaceae geoglossum geographer geographics geography geologist geology geomancer geomancy geometer geometrician geometrid geometridae geometry geomorphology geomyidae geomys geophagia geophagy geophilidae geophilomorpha geophilus geophysicist geophysics geophyte geopolitics geordie george georgetown georgette georgia georgian geosphere geostrategy geothlypis geotropism geraint geraniaceae geraniales geranium gerardia gerbera gerbert gerbil gerbille gerbillinae gerbillus gerea gerenuk gerfalcon geriatrician geriatrics germ german germander germaneness germanic germanism germanist germanite germanium germany germicide germinal germination geronimo gerontocracy gerontologist gerontology gerreidae gerres gerrhonotus gerridae gerrididae gerris gerrymander gershwin gerund geryon gesell gesner gesneria gesneriaceae gesneriad gesso gestalt gestapo gestation gesticulation gesture get get-go get-up-and-go geta getaway getting gettysburg getup geum gewgaw geyser ghana ghanian gharry ghastliness ghat ghatti ghb ghee gheg ghent gherkin ghetto ghillie ghost ghostfish ghostliness ghostwriter ghoul ghq ghrelin ghrf ghz gi gia giacometti giant giantess giantism giardia giardiasis gib gibber gibberellin gibberish gibbet gibbon gibbosity gibbousness gibbs gibbsite gibe gibibit gibibyte gibit giblet giblets gibraltar gibraltarian gibran gibson gidar giddiness gide gidgee gielgud gift gig gigabit gigabyte gigacycle gigahertz gigantism gigartinaceae giggle giggler gigo gigolo gigot gigue gikuyu gila gilbert gild gilder gildhall gilding gilgamesh gilgamish gill gill-over-the-ground gillespie gillette gillie gillyflower gilman gilmer gilt gimbal gimcrack gimcrackery gimel gimlet gimmick gimmickry gimp gimpiness gin ginep ginger gingerbread gingerol gingerroot gingersnap gingham gingiva gingivitis gingko ginglymostoma ginglymus ginkgo ginkgoaceae ginkgoales ginkgophytina ginkgopsida ginmill ginsberg ginseng ginzo giotto gipsy gipsywort giraffa giraffe giraffidae girandola girandole girard girasol giraudoux girder girdle giriama girl girlfriend girlhood girlishness giro gironde girondin girondism girondist girru girth gish gismo gist git gita gitana gitano gittern give give-and-go give-and-take giveaway given givenness giver giving giza gizeh gizmo gizzard gjellerup glabella glaciation glacier glad gladdon glade gladfulness gladiator gladiola gladiolus gladness gladsomeness gladstone glamor glamorisation glamorization glamour glamourisation glamourization glance gland glanders glans glare glareola glareole glareolidae glaser glasgow glasnost glass glass-cutter glassblower glasses glassful glasshouse glassmaker glassware glasswork glassworker glassworks glasswort glaswegian glaucium glaucoma glaucomys glauconite glaux glaze glazer glazier gleam gleaming gleaner gleba glebe glechoma gleditsia glee gleefulness gleet gleichenia gleicheniaceae glen glendower glengarry glenn glia glibness glide glider gliding glimmer glimmering glimpse glinka glint glioblastoma glioma glipizide gliricidia gliridae glis glissade glissando glisten glister glitch glitter glitz gloam gloaming gloat gloating glob globalisation globalization globe globefish globeflower globetrotter globicephala globigerina globigerinidae globin globosity globularness globule globulin glochid glochidium glockenspiel glogg glomerule glomerulonephritis glomerulus gloom gloominess glop glorification gloriole gloriosa glory gloss glossa glossalgia glossarist glossary glossina glossiness glossinidae glossitis glossodia glossodynia glossolalia glossopsitta glossoptosis glossy glottis glottochronology gloucester gloucestershire glove glow glower glowing glowworm gloxinia glucagon glucinium gluck glucocorticoid glucophage glucosamine glucose glucoside glucosuria glucotrol glue glueyness gluiness glume glumness gluon glut glutamate glutamine glute glutelin gluten glutethimide gluteus glutinosity glutinousness glutton gluttony glyburide glyceraldehyde glyceria glyceride glycerin glycerine glycerite glycerogel glycerogelatin glycerol glycerole glyceryl glycine glycogen glycogenesis glycol glycolysis glycoprotein glycoside glycosuria glycyrrhiza glyoxaline glyph glyptics glyptography gm gmt gnaphalium gnarl gnat gnatcatcher gnathion gnathostomata gnathostome gnawer gneiss gnetaceae gnetales gnetophyta gnetophytina gnetopsida gnetum gnocchi gnome gnomon gnosis gnostic gnosticism gnp gnu go go-ahead go-around go-between go-cart go-getter go-kart go-slow goa goad goading goal goal-kick goalie goalkeeper goalmouth goalpost goaltender goat goatee goatfish goatherd goatsbeard goatsfoot goatskin goatsucker gob gobbet gobble gobbledygook gobbler gobi gobiesocidae gobiesox gobiidae gobio goblet goblin gobs goby god godard godchild goddard goddaughter goddess godel godfather godhead godiva godlessness godliness godmother godown godparent godsend godson godspeed godunov godwit goebbels goer goering goeteborg goethals goethe goethite gofer goffer goggle-eye goggles gogh gogol goidelic going going-over goiter goitre goitrogen golan golconda gold gold-beater gold-worker goldbeater goldberg goldbrick goldbricking goldcrest goldcup goldenbush goldeneye goldenrod goldenseal goldfield goldfields goldfinch goldfish goldilocks golding goldman goldmark goldmine goldoni goldsboro goldsmith goldstone goldthread goldworker goldwyn golem golf golf-club golfcart golfer golfing golgi golgotha goliard goliath golliwog golliwogg golosh goma gombrowicz gomel gomorrah gomorrha gompers gomphothere gomphotheriidae gomphotherium gomphrena gomuti gonad gonadotrophin gonadotropin goncourt gond gondi gondola gondolier gondoliere gondwanaland goner gong gongora gongorism gongorist gonif goniff goniometer gonion goniopteris gonioscopy gonne gonococcus gonorhynchidae gonorhynchus gonorrhea gonorrhoea goo goober good good-by good-bye good-for-naught good-for- nothing good-humoredness good-humouredness good-king-henry good-naturedness good-neighborliness good-neighbourliness good-temperedness goodall goodby goodbye goodenia goodeniaceae goodman goodness goodwill goody goody-goody goodyear goodyera goof goof-off goofball goofy google googly googol googolplex gook goon gooney goonie goony goop goosander goose goose-tansy gooseberry goosebump goosefish gooseflesh goosefoot gooseneck gop gopher gopherus gopherwood goral gorbachev gordimer gordius gore gorgas gorge gorger gorgerin gorget gorgon gorgonacea gorgoniacea gorgonian gorgonocephalus gorgonzola gorilla goring gorki gorkiy gorky gorse gosainthan gosan-chiku goshawk gosling gosmore gospel gospeler gospeller gospels gossamer gossip gossiper gossiping gossipmonger gossipmongering gossypium goteborg goth gothenburg gothic gothite gotterdammerung gouache gouda goudy gouge gouger goujon goulash gould gounod gourd gourde gourmand gourmandism gourmandizer gourmet gout governance governed governess governing government government-in-exile governor governorship gown goy goya gp gpa gpo gps grab grabber grace gracefulness gracelessness gracie gracilariid gracilariidae gracility gracillariidae graciousness grackle gracula grad gradation grade grader gradient grading gradual graduality gradualness graduate graduation graecophile graf graffiti graffito graft grafting graham grahame grail grain grainfield grainger graininess graining gram grama gramicidin graminaceae graminales gramineae gramma grammar grammarian grammatolatry grammatophyllum gramme gramophone gramps grampus gran granada granadilla granadillo granary grand grandad grandaunt grandchild granddad granddaddy granddaughter grandee grandeur grandfather grandiloquence grandiosity grandma grandmaster grandmother grandnephew grandness grandniece grandpa grandparent grandson grandstand grandstander granduncle grange granger granicus granite graniteware grannie granny granola grant grant-in-aid grantee granter granth grantor granularity granulation granule granulocyte granulocytopenia granuloma granville-barker grape grapefruit grapeshot grapevine graph grapheme graphic graphics graphite graphologist graphology graphospasm grapnel grapo grappa grappelli grapple grappler grappling graptophyllum grasp grasping grass grass-of-parnassus grassfinch grassfire grasshopper grassland grate gratefulness grater graticule gratification grating gratitude gratuity grave gravedigger gravel gravelweed graveness graver graverobber graves gravestone graveyard gravida gravidation gravidity gravidness gravimeter gravimetry gravitas gravitation graviton gravity gravity-assist gravure gravy gray grayback graybeard grayhen graylag grayness graz graze grazier grazing grease grease-gun greaseball greasepaint greaser greasewood greasiness great great-aunt great- nephew great-niece great-uncle greatcoat greatness greave greaves grebe grecian greco greece greed greediness greegree greek greeley green green-blindness greenback greenbelt greenberg greenbottle greenbrier greene greenery greeneye greenfly greengage greengrocer greengrocery greenhood greenhorn greenhouse greening greenishness greenland greenling greenmail greenmarket greenness greenockite greenpeace greenroom greens greensand greensboro greenshank greensickness greenskeeper greensward greenville greenway greenweed greenwich greenwing greenwood greeter greeting gregarine gregarinida gregariousness gregory greisen gremlin grenada grenade grenadian grenadier grenadine grenoble gres-gris gresham gretzky grevillea grewia grey greyback greybeard greyhen greyhound greylag greyness gri-gri grias grid griddle griddlecake gridiron gridlock grief grieg grievance griever griffin griffith griffon grifter grigri grill grille grilling grillroom grillwork grimace grime griminess grimm grimness grimoire grin grind grindelia grinder grinding grindle grindstone gringo grinner grinning griot grip gripe gripes griping grippe gripsack gris grisaille griselinia griseofulvin grison grissino grist gristle gristmill grit gritrock grits gritstone grivet grizzle grizzly groan groaner groat groats grocer grocery groenendael groenlandia grog grogginess grogram groin grommet gromwell gromyko gronland groom groom-to-be grooming groomsman groove groover grooving grope gropius grosbeak groschen grosgrain gross grossbeak grossness grossulariaceae grosz grot grotesque grotesqueness grotesquerie grotesquery grotius grotto grouch groucho ground ground-berry ground-shaker groundball groundberry groundbreaker groundbreaking groundcover grounder groundfish groundhog grounding groundkeeper groundlessness groundling groundmass groundnut grounds groundsel groundsheet groundskeeper groundsman groundspeed groundwork group grouper groupie grouping groupthink groupware grouse grouse-berry grouseberry grout grove groveler groveller groves grower growing growl growler growling grownup growth groyne grozny groznyy grub grubbiness grubby grubstake grudge gruel gruesomeness gruffness grugru gruidae gruiformes grumble grumbler grumbling grume grummet grump grumpiness grundyism grunge grunt grunter grus gruyere gryllidae gryphon gsa gspc gsr gu guacamole guacharo guadalajara guadalcanal guadeloupe guaiac guaiacum guaira guallatiri guam guama guan guanabana guanabenz guanaco guangdong guangzhou guanine guano guanosine guantanamo guar guarani guarantee guarantor guaranty guard guardhouse guardian guardianship guardrail guardroom guardsman guarneri guarnerius guarnieri guatemala guatemalan guava guayaquil guayule gubbins guck gudgeon guenevere guenon guerdon guereza gueridon guerilla guernsey guerrilla guess guesser guessing guesstimate guesswork guest guesthouse guestimate guestroom guestworker guevara guevina guff guffaw guggenheim gui guiana guib guidance guide guidebook guideline guidepost guideword guild guilder guildhall guile guillemot guilloche guillotine guilt guiltiness guiltlessness guimpe guine-bissau guinea guinea-bissau guinean guinevere guinness guise guitar guitarfish guitarist gujarat gujarati gujerat gujerati gula gulag gulch gulden gulf gulfweed gull gullet gullibility gulliver gully gulo gulp gulper gulping gulu gulyas gum gum-lac gumbo gumbo-limbo gumboil gumdrop gumma gumminess gumming gummite gummosis gumption gumshield gumshoe gumweed gumwood gun gun-sight gunboat guncotton gunfight gunfire gunflint gunite gunk gunlock gunman gunmetal gunnel gunner gunnery gunny gunnysack gunplay gunpoint gunpowder gunrunner gunrunning gunshot gunsight gunslinger gunsmith gunstock gunwale guomindang guppy gur gurgle gurkha gurnard gurney guru gush gusher gusset gust gustation gustavus gusto gut gutenberg guthrie gutierrezia gutlessness guts gutsiness gutta-percha gutter guttersnipe guttiferae guttiferales guttural guvnor guy guyana guyanese guyot guzzler guzzling gwydion gwyn gwynn gy gym gymkhana gymnadenia gymnadeniopsis gymnasium gymnast gymnastics gymnelis gymnocalycium gymnocarpium gymnocladus gymnogyps gymnomycota gymnophiona gymnopilus gymnorhina gymnosophist gymnosophy gymnosperm gymnospermae gymnospermophyta gymnosporangium gymnura gymslip gynaecologist gynaecology gynaeolatry gynandromorph gynarchy gynecocracy gynecologist gynecology gynecomastia gyneolatry gynne gynobase gynoecium gynogenesis gynophobia gynophore gynostegium gynura gyp gypaetus gyps gypsophila gypsum gypsy gypsyweed gypsywort gyration gyre gyrfalcon gyrinidae gyro gyrocompass gyromitra gyroplane gyroscope gyrostabiliser gyrostabilizer gyrus gywn h h-bomb h.p. h2o ha ha'p'orth ha'penny ha-ha haart haastia habacuc habakkuk habanera habenaria haber haberdasher haberdashery habergeon habiliment habit habitability habitableness habitant habitat habitation habituation habitude habitue habitus habsburg hacek hachiman hachure hacienda hack hack-driver hackamore hackberry hackbut hackee hackelia hacker hackle hackles hackmatack hackney hacksaw hackwork haddock hadean hades hadith hadj hadji hadrian hadron hadrosaur hadrosauridae hadrosaurus haecceity haeckel haem haemagglutination haemangioma haemanthus haematemesis haematinic haematite haematobia haematocele haematochezia haematocoele haematocolpometra haematocolpos haematocrit haematocytopenia haematocyturia haematogenesis haematohiston haematoidin haematologist haematology haematolysis haematoma haematopodidae haematopoiesis haematopus haematoxylon haematoxylum haematuria haemitin haemodialysis haemodoraceae haemodorum haemogenesis haemoglobin haemoglobinemia haemoglobinopathy haemoglobinuria haemolysin haemolysis haemophile haemophilia haemophiliac haemopis haemopoiesis haemoproteid haemoproteidae haemoprotein haemoproteus haemoptysis haemorrhage haemorrhoid haemorrhoidectomy haemosiderin haemosiderosis haemosporidia haemosporidian haemostasia haemostasis haemostat haemothorax haemulidae haemulon hafnium haft haftarah haftorah hag hagada haganah hagberry hagbut hagerstown hagfish haggada haggadah haggai haggard haggis haggle haggler haggling hagiographa hagiographer hagiographist hagiography hagiolatry hagiologist hagiology hahn hahnium haick haida haifa haik haiku hail hailstone hailstorm haiphong hair hair's-breadth hair-raiser hairball hairbrush haircare haircloth haircut hairdo hairdresser hairdressing hairgrip hairiness hairlessness hairline hairnet hairpiece hairpin hairsbreadth hairsplitter hairsplitting hairspring hairstreak hairstyle hairstylist hairtail hairweaving haiti haitian haj haji hajj hajji hake hakea hakeem hakenkreuz hakham hakim hakka halab halacha halaka halakah halal halberd halberdier halchidhoma halcion halcyon haldane haldea haldol hale haleness halenia haler halesia halevy haley half half-and-half half-breed half-brother half-caste half- century half-cock half-holiday half-hour half-intensity half-length half-life half-light half-mast half-moon half-pay half-pint half-relief half-sister half- slip half-staff half-term half-truth half-wit halfback halfbeak halfpenny halfpennyworth halftime halftone haliaeetus halibut halicarnassus halicoeres halictidae halide halifax halimodendron haliotidae haliotis halite halitosis halitus hall hallah halle halle-an-der-saale hallel hallelujah halley halliard hallmark halloo hallowe'en halloween hallowmas hallowmass hallstand hallucination hallucinogen hallucinosis hallux hallway halm halma halo haloalkane halobacter halobacteria halobacterium halocarbon halocarpus haloform halogen halogeton halon haloperidol halophil halophile halophyte haloragaceae haloragidaceae halothane hals halt halter haltere halyard ham hamadryad hamamelidaceae hamamelidae hamamelidanthum hamamelidoxylon hamamelis hamamelites haman hamartia hamartoma hamas hamate hamburg hamburger hame hamelia hamelin hameln hamilton haminoea hamitic hamito-semitic hamlet hammarskjold hammer hammerhead hammering hammerlock hammerstein hammertoe hammett hamming hammock hammurabi hammurapi hamper hampshire hampton hamster hamstring hamsun han han- gook hancock hand hand-me-down handbag handball handbarrow handbasin handbasket handbell handbill handbook handbow handbreadth handcar handcart handclap handclasp handcraft handcuff handedness handel handful handgrip handgun handhold handicap handicapped handicapper handicraft handiness handiwork handkerchief handle handle-bars handlebar handler handline handling handlock handloom handmaid handmaiden handoff handout handover handrail handrest hands handsaw handsbreadth handset handshake handshaking handsomeness handspike handspring handstamp handstand handwear handwheel handwork handwriting handy handyman hang hang-up hangar hangbird hangchow hanger hanger-on hanging hangman hangnail hangout hangover hangzhou hani hank hankering hankey hankie hanks hanky hannibal hannover hannukah hanoi hanover hanoverian hansard hansom hanukah hanukkah hanuman hao haoma hap haphazardness haphtarah haphtorah haploid haploidy haplopappus haplosporidia haplosporidian haplotype happening happenstance happiness hapsburg haptoglobin hara-kiri harakiri harangue haranguer harare harasser harassment harbinger harbor harborage harbour harbourage hard-on hardback hardbake hardball hardboard hardcover hardenbergia hardening hardheads hardheartedness hardihood hardiness harding hardinggrass hardliner hardness hardpan hardship hardtack hardtop hardware hardwareman hardwood hardy hare harebell haredi hareem harefoot harelip harem hargeisa hargreaves haricot harijan harikari harkat-ul-jihad-e-islami harkat-ul-mujahidin harlem harlequin harlequin-snake harlequinade harlot harlotry harlow harm harmattan harmfulness harmonic harmonica harmonics harmoniousness harmonisation harmoniser harmonium harmonization harmonizer harmony harmsworth harness harp harper harpia harpist harpo harpoon harpooneer harpooner harpsichord harpsichordist harpulla harpullia harpy harquebus harridan harrier harriman harris harrisburg harrisia harrison harrod harrow harshness hart hart's-tongue harte hartebeest hartford hartley harum-scarum harvard harvest harvest-lice harvester harvestfish harvesting harvestman harvey has-been haschisch hasdrubal hasek hash hasheesh hashish hashmark hasid hasidim hasidism haslet hasp hassam hassel hassid hassidim hassidism hassium hassle hassock haste hastinapura hastiness hastings hat hatband hatbox hatch hatchback hatchel hatchery hatchet hatching hatchling hatchway hate hatefulness hatemonger hater hatful hathaway hatiora hatmaker hatpin hatrack hatred hatter hattiesburg hauberk haughtiness haul haulage hauler haulier hauling haulm haunch haunt hausa hausen hausmannite haussa haustorium hautbois hautboy haute-normandie hauteur havana havasupai have have-not havel havelock haven haversack havoc haw haw-haw hawai'i hawaii hawaiian hawala hawfinch hawk hawk's-beard hawk's-beards hawkbill hawkbit hawker hawking hawkins hawkishness hawkmoth hawksbill hawkshaw hawkweed hawkyns haworth hawse hawsehole hawsepipe hawser hawthorn hawthorne hay hay-scented hayastan haycock haydn hayek hayes hayfield hayfork haying hayloft haymaker haymaking haymow hayrack hayrick hayrig hays hayseed haystack hayti haywire haywood hazan hazard hazardia hazardousness haze hazel hazelnut hazelwood haziness hazlitt hazmat hb hcfc hcg hdl hdtv he he-goat he-huckleberry he-man head head-shrinker headache headband headboard headcheese headcount headcounter headdress header headfast headfish headful headgear headhunter heading headlamp headland headlight headline headliner headlinese headlock headman headmaster headmastership headmistress headmistressship headphone headpiece headpin headquarters headrace headrest headroom heads-up headsail headscarf headset headshake headshaking headship headshot headsman headspace headspring headstall headstand headstock headstone headstream headwaiter headwater headway headwind headword healer healing health healthcare healthfulness healthiness heap heaps hearer hearing hearsay hearse hearst heart heart-leaf heart-to-heart heartache heartbeat heartbreak heartbreaker heartburn heartburning hearth hearthrug hearthstone heartiness heartland heartleaf heartlessness heartrot hearts heartsease heartseed heartsickness heartstrings heartthrob heartwood heat heater heath heathen heathenism heather heathfowl heathland heating heatstroke heaume heave heaven heavens heaver heaves heaviness heaving heaviside heavy heavyheartedness heavyweight hebbel hebdomad hebe hebei hebephrenia hebetude hebraism hebraist hebrew hebrews hebrides hecate hecatomb hecht heckelphone heckle heckler heckling hectare hectogram hectograph hectoliter hectolitre hectometer hectometre hector hedeoma hedera hedge hedgefund hedgehog hedger hedgerow hedging hediondilla hedjaz hedonism hedonist hedysarum hee-haw heebie-jeebies heed heedfulness heedlessness heel heelbone hefa heft heftiness hegari hegel hegelian hegemon hegemony hegira heidegger heifer height heights heilong heimdal heimdall heimdallr heinlein heinousness heinz heir heir-at-law heiress heirloom heisenberg heist hejaz hejira hel hela helen helena helenium heleodytes heliamphora helianthemum helianthus helichrysum helicidae helicon helicopter helicteres heliobacter heliogram heliograph heliogravure heliolatry heliometer heliopause heliophila heliopsis helios heliosphere heliotherapy heliothis heliotrope heliotropism heliotype heliozoa heliozoan heliport helipterum helium helix hell hell-kite hell-rooster hellbender hellcat hellebore helleborine helleborus hellene hellenic hellenism heller helleri hellespont hellfire hellgrammiate hellhole hellhound hellion hellman hello helm helmet helmetflower helmholtz helminth helminthiasis helminthic helminthostachys helmsman heloderma helodermatidae heloise helot helotiaceae helotiales helotium help helpdesk helper helpfulness helping helplessness helpmate helpmeet helsingfors helsinki helve helvella helvellaceae helvetica helwingia helxine hem hemachatus hemagglutination hemangioma hematemesis hematin hematinic hematite hematocele hematochezia hematochrome hematocoele hematocolpometra hematocolpos hematocrit hematocyst hematocytopenia hematocyturia hematogenesis hematohiston hematoidin hematologist hematology hematolysis hematoma hematopoiesis hematuria heme hemeralopia hemerobiid hemerobiidae hemerocallidaceae hemerocallis hemiacetal hemianopia hemianopsia hemiascomycetes hemicrania hemicycle hemidemisemiquaver hemiepiphyte hemigalus hemigrammus hemimetabola hemimetabolism hemimetaboly hemimetamorphosis hemimorphite hemin heming hemingway hemiparasite hemiplegia hemiplegic hemipode hemiprocnidae hemiptera hemipteran hemipteron hemipteronatus hemiramphidae hemisphere hemitripterus hemline hemlock hemming-stitch hemminge hemochromatosis hemodialysis hemodialyzer hemodynamics hemofil hemogenesis hemoglobin hemoglobinemia hemoglobinopathy hemoglobinuria hemolysin hemolysis hemophile hemophilia hemophiliac hemopoiesis hemoprotein hemoptysis hemorrhage hemorrhoid hemorrhoidectomy hemosiderin hemosiderosis hemostasia hemostasis hemostat hemothorax hemp hemstitch hemstitching hen hen-of-the-woods henbane henbit henchman hencoop hendiadys hendrix henhouse henna henroost henry henson hepadnavirus heparin hepatic hepatica hepaticae hepaticopsida hepatitis hepatocarcinoma hepatoflavin hepatoma hepatomegaly hepatotoxin hepburn hephaestus hephaistos heptad heptagon heptane hepworth hera heracles heracleum heraclitus herakles herald heraldry herat herb herbage herbal herbalist herbarium herbart herbert herbicide herbivore herculaneum hercules hercules'-club hercules'-clubs hercules-club herculius herd herder herdsman here hereafter hereditament hereditarianism heredity hereford hereness herero heresy heretic heritage heritiera heritor herm herman hermann hermannia hermaphrodism hermaphrodite hermaphroditism hermaphroditus hermeneutics hermes hermissenda hermit hermitage hermosillo hernaria hernia herniation hero herod herodotus heroic heroics heroin heroine heroism heron heronry herpangia herpes herpestes herpetologist herpetology herr herrenvolk herrerasaur herrerasaurus herrick herring herringbone herschel hershey hertfordshire hertha hertz herzberg heshvan hesiod hesitance hesitancy hesitater hesitation hesitator hesperides hesperiphona hesperis hesperus hess hesse hessian hessonite hestia heteranthera heterobasidiomycetes heterocephalus heterocycle heterocyclic heterodon heterodoxy heterogeneity heterogeneousness heterogenesis heterograft heterokontae heterokontophyta heterology heteromeles heterometabolism heterometaboly heteromyidae heteronym heteroploid heteroploidy heteroptera heteroscelus heterosexism heterosexual heterosexualism heterosexuality heterosis heterosomata heterospory heterostracan heterostraci heterotaxy heterotheca heterotrichales heterotroph heterozygosity heterozygote heth heuchera heulandite heuristic hevea hevesy hewer hex hexachlorophene hexad hexadrol hexagon hexagram hexagrammidae hexagrammos hexahedron hexalectris hexameter hexamita hexanchidae hexanchus hexane hexapod hexapoda hexenbesen hexestrol hexose heyday heyerdahl heyrovsky heyse heyward hezbollah hezekiah hf hfc hg hhs hi hi-fi hiatus hiawatha hibachi hibbertia hibbing hibernation hibernia hibiscus hiccough hiccup hick hickey hickock hickory hidatsa hiddenite hiddenness hide hide-and-seek hideaway hideousness hideout hiding hidrosis hieracium hierarch hierarchy hieratic hierocracy hieroglyph hieroglyphic hierolatry hieronymus higginson high high-five high-handedness high-low high-low-jack high-mindedness high- muck-a-muck high-rise high-spiritedness high-up highball highbinder highboard highboy highbrow highchair higher-up highflier highflyer highjack highjacker highjacking highland highlander highlands highlife highlight highlighter highlighting highness highroad highschool highwater highway highwayman higi hijab hijack hijacker hijacking hijaz hijinks hike hiker hiking hilarity hilbert hildebrand hill hillary hillbilly hillel hilliness hillock hillside hilltop hilo hilt hilum hilus himalaya himalayas himalayish himantoglossum himantopus himmler hin hinault hinayana hinayanism hinayanist hind hindbrain hindemith hindenburg hinderance hindfoot hindgut hindi hindlimb hindoo hindooism hindoostani hindostani hindquarter hindquarters hindrance hindshank hindsight hindu hinduism hindustan hindustani hinge hinny hint hinterland hip hip-hop hipbone hipflask hipline hipparchus hippeastrum hippie hippies hippo hippobosca hippoboscid hippoboscidae hippocampus hippocastanaceae hippocrates hippocrepis hippodamia hippodrome hippoglossoides hippoglossus hippopotamidae hippopotamus hipposideridae hipposideros hippotragus hippy hipster hipsters hipsurus hire hire-purchase hireling hirer hirohito hiroshima hirschfeld hirschsprung hirsuteness hirsutism hirudinea hirudinean hirudinidae hirudo hirundinidae hirundo hispanic hispaniola hiss hisser hissing histaminase histamine histidine histiocyte histiocytosis histocompatibility histogram histoincompatibility histologist histology histone historian historicalness historicism historiographer historiography history histrion histrionics hit hitch hitchcock hitchhiker hitchings hitchiti hitchrack hitler hitman hitter hitting hittite hiv hive hives hizballah hizbollah hizbullah hl hm hmo hmong hn hnd ho hoactzin hoagie hoagland hoagy hoar hoard hoarder hoarding hoarfrost hoariness hoarseness hoatzin hoax hoaxer hob hobart hobbes hobbit hobble hobbledehoy hobbler hobbs hobby hobbyhorse hobbyism hobbyist hobgoblin hobnail hobo hock hock-joint hockey hocus-pocus hod hodeida hoder hodgepodge hodgkin hodman hodometer hodoscope hodr hodur hoe hoecake hoenir hoffa hoffman hoffmann hoffmannsthal hog hogan hogarth hogback hogchoker hogfish hogg hogget hoggishness hogmanay hogshead hogwash hogweed hohenlinden hohenzollern hoheria hohhot hoist hoister hoka hokan hokkaido hokkianese hokum hokusai holarrhena holbein holbrookia holcus hold hold-down holdall holder holdfast holding holdout holdover holdup hole hole-in- the-wall holibut holiday holidaymaker holiness holism holla holland hollandaise hollander hollands holler hollering hollerith hollo holloa hollow hollow-back holloware hollowness hollowware holly hollygrape hollyhock hollywood holmes holmium holocaust holocene holocentridae holocentrus holocephalan holocephali holocephalian holofernes hologram holograph holography holometabola holometabolism holometaboly holonym holonymy holophyte holothuria holothurian holothuridae holothuroidea holotype holstein holstein-friesian holster holy holystone homage homaridae homarus hombre homburg home home-builder home-farm homebody homebound homeboy homebrew homebuilder homecoming homefolk homegirl homel homeland homeless homelessness homeliness homemaker homemaking homeobox homeopath homeopathy homeostasis homeotherm homeowner homepage homer homeroom homesickness homespun homestead homesteader homestretch hometown homework homicide homiletics homily hominid hominidae hominoid hominoidea hominy hommos homo homobasidiomycetes homoeopath homoeopathy homoeroticism homogenate homogeneity homogeneousness homogenisation homogenization homogeny homograft homograph homogyne homoiotherm homology homomorphism homomorphy homona homonym homonymy homophile homophobe homophobia homophone homophony homoptera homopteran homosexual homosexualism homosexuality homospory homotherm homozygosity homozygote homunculus homyel honcho hondo honduran honduras hone honegger honestness honesty honey honey-flower honeybee honeybells honeycomb honeycreeper honeydew honeyflower honeymoon honeymooner honeypot honeysucker honeysuckle honiara honk honker honkey honkie honky honky-tonk honkytonk honolulu honor honorableness honorarium honoree honorific honoring honour honourableness honours honshu hoo-ha hoo-hah hooch hood hoodlum hoodmold hoodmould hoodoo hoodooism hooey hoof hoof-mark hoofer hoofing hoofprint hook hookah hooke hooker hooking hooknose hooks hookup hookworm hooky hooligan hooliganism hoop hoopla hoopoe hoopoo hoops hoopskirt hooray hoosegow hoosgow hoosier hoot hootch hooter hoover hop hop-picker hop-step-and-jump hope hopeful hopefulness hopeh hopei hopelessness hoper hopi hopkins hopkinson hopper hops hopsack hopsacking hopscotch horace horde hordeolum hordeum horehound horizon horizontal horizontality hormone horn hornbeam hornbill hornblende hornbook horne horneophyton hornet horney hornfels horniness hornist hornpipe hornpout hornstone hornwort horologe horologer horologist horology horoscope horoscopy horowitz horridness horripilation horror horse horse-brier horse-cart horse-head horse-pistol horse-trail horseback horsebean horsebox horsecar horsecloth horsefish horseflesh horsefly horsehair horsehead horsehide horselaugh horseleech horseman horsemanship horsemeat horsemint horseplay horsepond horsepower horsepower-hour horseradish horseshit horseshoe horseshoer horseshoes horseshow horsetail horseweed horsewhip horsewhipping horsewoman horst horta hortensia horticulture horticulturist horus hosanna hose hosea hosepipe hosier hosiery hospice hospitableness hospital hospitalisation hospitality hospitalization host hosta hostaceae hostage hostel hosteller hostelry hostess hostile hostilities hostility hostler hot-rod hotbed hotbox hotcake hotchpotch hotdog hotei hotei-chiku hotel hotel-casino hotelier hotelkeeper hotelman hotfoot hoth hothead hothouse hothr hotness hotplate hotpot hotshot hotspot hotspur hottentot hottonia houdah houdini houghton houhere hoummos hound hound's-tongue hour hourglass houri hours housatonic house house-builder house- raising houseboat housebreaker housebreaking housebuilder housecleaning housecoat housecraft housedog housefather housefly houseful houseguest household householder househusband housekeeper housekeeping houselights housemaid houseman housemaster housemate housemother housepaint houseplant houseroom housetop housewarming housewife housewifery housework housewrecker housing housman houston houttuynia houyhnhnm houyhnhnms hovea hovel hovercraft how-d'ye-do how- do-you-do howard howdah howdy howe howells howitzer howl howler howling hoy hoya hoyden hoydenism hoyle hp hq hr hrolf hrt hrvatska hryvnia hs hs1 hs2 hsian hsv-1 hsv-2 hsv-i hsv-ii htlv-1 html http hua huainaputina hualapai hualpai huamachil huambo huarache huaraches huascaran hub hub-and-spoke hubbard hubble hubble-bubble hubbly-bubbly hubbub hubby hubcap hubel hubris huck huckaback huckleberry huckster hud huddle huddler hudood hudson hudsonia hudud hue huff huffiness huffing huffishness hug hug-me-tight hugger hugger-mugger hugging huggins hughes hugo hugueninia huguenot huisache huitre huji hula hula-hoop hula-hula hulk hull hullabaloo hullo hulsea hum hum-vee human humaneness humanisation humanism humanist humanitarian humanitarianism humanities humanity humanization humankind humanness humanoid humans humate humber humblebee humbleness humboldt humbug humdinger humdrum hume humectant humerus humidity humidness humification humiliation humility humin hummer humming hummingbird hummock hummus humor humoring humorist humorousness humour humourist humous hump humpback humperdinck humulin humulus humus humvee hun hunan hunch hunchback hundred hundred-percenter hundredth hundredweight hungarian hungary hunger hungriness hunk hunkpapa hunnemannia hunt hunter hunter-gatherer hunting huntington huntress huntsman huntsville hupa hurdle hurdler hurdles hurdling hurdy-gurdy hurl hurler hurling hurok huron hurrah hurricane hurriedness hurry hurrying hurt hurting hus husain husayn husband husbandman husbandry hush hushing hushpuppy husk huskiness husking husky huss hussar hussein husserl hussite hussy hustings hustle hustler huston hut hutch hutchins hutchinson hutment hutton hutu hutzpah huxley huygens hyacinth hyacinthaceae hyacinthoides hyades hyaena hyaenidae hyalin hyaline hyalinisation hyalinization hyaloid hyalophora hyaloplasm hyalosperma hyalospongiae hyaluronidase hyazyme hybanthus hybrid hybridisation hybridization hybridizing hybridoma hydantoin hydathode hydatid hydatidosis hyderabad hydnaceae hydnocarpus hydnoraceae hydnum hydra hydralazine hydramnios hydrangea hydrangeaceae hydrant hydrargyrum hydrarthrosis hydrastis hydrate hydration hydraulics hydrazine hydrazoite hydremia hydride hydrilla hydrobates hydrobatidae hydrocarbon hydrocele hydrocephalus hydrocephaly hydrocharidaceae hydrocharis hydrocharitaceae hydrochloride hydrochlorofluorocarbon hydrochlorothiazide hydrochoeridae hydrochoerus hydrocolloid hydrocortisone hydrocortone hydrocracking hydrodamalis hydrodiuril hydrodynamics hydroelectricity hydroflumethiazide hydrofluorocarbon hydrofoil hydrogel hydrogen hydrogenation hydrography hydroid hydrokinetics hydrolith hydrologist hydrology hydrolysate hydrolysis hydromancer hydromancy hydromantes hydromel hydrometer hydrometry hydromorphone hydromyinae hydromys hydronephrosis hydropathy hydrophidae hydrophobia hydrophobicity hydrophyllaceae hydrophyllum hydrophyte hydroplane hydroponics hydrops hydrosphere hydrostatics hydrotherapy hydrothorax hydroxide hydroxybenzene hydroxychloroquine hydroxyl hydroxymethyl hydroxyproline hydroxytetracycline hydroxyzine hydrozoa hydrozoan hydrus hyemoschus hyena hygeia hygiene hygienics hygienist hygrocybe hygrodeik hygrometer hygrophoraceae hygrophorus hygrophyte hygroscope hygroton hygrotrama hyla hylactophryne hylidae hylobates hylobatidae hylocereus hylocichla hylophylax hymen hymenaea hymenanthera hymeneal hymeneals hymenium hymenogastrales hymenomycetes hymenophyllaceae hymenophyllum hymenopter hymenoptera hymenopteran hymenopteron hymie hymn hymnal hymnary hymnbook hymnody hynerpeton hyoid hyoscine hyoscyamine hyoscyamus hypallage hypanthium hypatia hype hypentelium hyperacidity hyperactivity hyperacusia hyperacusis hyperadrenalism hyperadrenocorticism hyperaemia hyperaldosteronism hyperalimentation hyperbaton hyperbetalipoproteinemia hyperbilirubinemia hyperbola hyperbole hyperboloid hyperborean hypercalcaemia hypercalcemia hypercalcinuria hypercalciuria hypercapnia hypercarbia hypercatalectic hypercellularity hypercholesteremia hypercholesterolemia hypercoaster hyperdactyly hyperemesis hyperemia hyperextension hyperglycaemia hyperglycemia hyperhidrosis hypericaceae hypericales hypericism hypericum hyperidrosis hyperion hyperkalemia hyperlink hyperlipaemia hyperlipemia hyperlipidaemia hyperlipidemia hyperlipoidaemia hyperlipoidemia hyperlipoproteinemia hypermarket hypermastigina hypermastigote hypermedia hypermenorrhea hypermetropia hypermetropy hypermotility hypernatremia hypernym hypernymy hyperoartia hyperodontidae hyperoglyphe hyperon hyperoodon hyperope hyperopia hyperotreta hyperparathyroidism hyperpiesia hyperpiesis hyperpigmentation hyperpituitarism hyperplasia hyperpnea hyperpyrexia hypersecretion hypersensitivity hypersomnia hypersplenism hyperstat hypertensin hypertension hypertensive hypertext hyperthermia hyperthermy hyperthyroidism hypertonia hypertonicity hypertonus hypertrophy hypervelocity hyperventilation hypervitaminosis hypervolaemia hypervolemia hypesthesia hypha hyphantria hyphema hyphen hyphenation hypnagogue hypnoanalysis hypnogenesis hypnopedia hypnophobia hypnos hypnosis hypnotherapy hypnotic hypnotiser hypnotism hypnotist hypnotizer hypo hypoadrenalism hypoadrenocorticism hypobasidium hypobetalipoproteinemia hypoblast hypocalcaemia hypocalcemia hypocapnia hypocellularity hypochaeris hypochlorite hypochoeris hypochondria hypochondriac hypochondriasis hypochondrium hypocorism hypocreaceae hypocreales hypocrisy hypocrite hypocycloid hypoderma hypodermatidae hypodermic hypodermis hypoesthesia hypogammaglobulinemia hypoglossal hypoglycaemia hypoglycemia hypogonadism hypokalemia hypolipoproteinemia hyponatremia hyponym hyponymy hypopachus hypoparathyroidism hypophysectomy hypophysis hypopigmentation hypopitys hypoplasia hypopnea hypoproteinemia hyposmia hypospadias hypostasis hypostatisation hypostatization hypotension hypotensive hypotenuse hypothalamus hypothermia hypothesis hypothetical hypothrombinemia hypothyroidism hypotonia hypotonicity hypotonus hypovitaminosis hypovolaemia hypovolemia hypoxia hypoxidaceae hypoxis hypozeugma hypozeuxis hypsiglena hypsiprymnodon hypsography hypsometer hypsometry hyracoidea hyracotherium hyrax hyson hyssop hyssopus hysterectomy hysteresis hysteria hysteric hysterics hysterocatalepsy hysterosalpingogram hysteroscopy hysterotomy hystricidae hystricomorpha hytrin hz i i-beam i.d. i.e.d. i.q. i.w.w. ia iaa iaea iago iamb iambic iambus ianfu iapetus ibadan ibda-c iberia iberian iberis ibero-mesornis ibert ibex ibis ibn-roshd ibn-sina ibrahim ibrd ibsen ibuprofen ic icaco icao icarus icbm icc ice ice-skater ice-wagon iceberg iceboat icebox icebreaker icecap icecream icefall icehouse iceland icelander icelandic iceman icepick icetray ichneumon ichneumonidae ichor ichthyolatry ichthyologist ichthyology ichthyosaur ichthyosauria ichthyosauridae ichthyosaurus ichthyosis ichyostega icicle iciness icing icon iconoclasm iconoclast iconography iconolatry iconology iconoscope icosahedron icsh ictalurus icteria icteridae icterus ictiobus ictodosaur ictodosauria ictonyx ictus icu id ida idaho idahoan iddm idea ideal idealisation idealism idealist ideality idealization idealogue ideation identicalness identification identifier identikit identity ideogram ideograph ideography ideologist ideologue ideology ides idesia idf idiocy idiolatry idiolect idiom idiopathy idiosyncrasy idiot iditarod idle idleness idler idling ido idocrase idol idolater idolatress idolatry idolisation idoliser idolization idolizer idp idun idyl idyll ie ied ifc ig iga igbo igd ige igg igigi iglesias igloo iglu igm ignatius igniter ignition ignitor ignobility ignobleness ignominiousness ignominy ignoramus ignorance ignorantness iguana iguania iguanid iguanidae iguanodon iguanodontidae iguassu iguazu ii iii iis ijssel ijsselmeer ijtihad ike ikhanaton ikon il ilama ilang-ilang ile-de-france ile-st-louis ileitis ileostomy ileum ileus ilex iliad iliamna ilion ilium ilk ill ill-being ill-breeding ill-treatment ill-usage illampu illation illecebrum illegality illegibility illegitimacy illegitimate illiberality illicitness illicium illimani illinois illinoisan illiteracy illiterate illness illogic illogicality illogicalness illuminance illuminant illumination illusion illusionist illustration illustrator illustriousness illyria illyrian ilmen ilmenite ilo ilosone image imagery imaginary imagination imaginativeness imaging imagism imago imam imaret imaum imavate imbalance imbauba imbecile imbecility imbiber imbibing imbibition imbrication imbroglio imf imidazole imide iminazole imipramine imitation imitator immaculateness immanence immanency immateriality immatureness immaturity immediacy immediateness immenseness immensity immersion immigrant immigration imminence imminency imminentness immobilisation immobility immobilization immobilizing immoderateness immoderation immodesty immolation immorality immortal immortality immortelle immotility immovability immovable immovableness immune immunisation immunity immunization immunoassay immunochemistry immunocompetence immunodeficiency immunoelectrophoresis immunofluorescence immunogen immunogenicity immunoglobulin immunohistochemistry immunologist immunology immunopathology immunosuppressant immunosuppression immunosuppressive immunosuppressor immunotherapy immurement immutability immutableness imo imp impact impaction impairer impairment impala impalement impalpability impartation impartiality imparting impasse impassiveness impassivity impasto impatience impeachability impeachment impeccability impecuniousness impedance impediment impedimenta impeller impendence impendency impenetrability impenetrableness impenitence impenitency imperative imperativeness imperceptibility imperfect imperfectibility imperfection imperfective imperfectness imperial imperialism imperialist imperiousness imperishability imperishableness imperishingness imperium impermanence impermanency impermeability impermeableness impermissibility impersonation impersonator impertinence imperturbability imperturbableness imperviousness impetigo impetuosity impetuousness impetus impiety impingement impinging impiousness impishness implant implantation implausibility implausibleness implement implementation implication implicitness implosion impoliteness imponderable import importance importation importee importer importing importunity imposition impossibility impossible impossibleness impost imposter impostor imposture impotence impotency impounding impoundment impoverishment impracticability impracticableness impracticality imprecation impreciseness imprecision impregnability impregnation impresario impress impression impressionism impressionist impressiveness impressment imprimatur imprint imprinting imprisonment improbability improbableness impromptu improperness impropriety improvement improver improvidence improvisation imprudence impudence impuissance impulse impulsion impulsiveness impunity impureness impurity imputation imu imuran in in-basket in-fighting in-joke in-law in-migration in- tray inability inaccessibility inaccuracy inachis inaction inactivation inactiveness inactivity inadequacy inadequateness inadmissibility inadvertence inadvertency inadvisability inamorata inamorato inanimateness inanition inanity inanna inapplicability inappositeness inappropriateness inaptitude inaptness inattention inattentiveness inaudibility inaudibleness inaugural inauguration inauspiciousness inbreeding inc inca incalescence incan incandescence incantation incapability incapableness incapacity incarceration incarnation incasement incaution incautiousness incendiarism incendiary incense incentive inception incertitude incessancy incessantness incest inch incheon inchoative inchon inchworm incidence incident incidental incienso incineration incinerator incipience incipiency incision incisiveness incisor incisura incisure incitation incitement inciter incivility inclemency inclementness inclination incline inclining inclinometer inclosure inclusion incognizance incoherence incoherency income incoming incommodiousness incommutability incompatibility incompetence incompetency incompetent incompleteness incomprehensibility incomprehension incompressibility inconceivability inconceivableness inconclusiveness inconel incongruity incongruousness inconsequence inconsiderateness inconsideration inconsistency inconspicuousness inconstancy incontinence incontinency incontrovertibility incontrovertibleness inconvenience inconvertibility incoordination incorporation incorporeality incorrectness incorruptibility incorruption incorruptness increase incredibility incredibleness incredulity increment incrimination incrustation incubation incubator incubus inculcation inculpability inculpableness inculpation incumbency incumbent incumbrance incurability incurable incurableness incurrence incurring incursion incurvation incurvature incus indaba indapamide indebtedness indecency indecision indecisiveness indecorousness indecorum indefatigability indefatigableness indefiniteness indefinity indelicacy indemnification indemnity indene indent indentation indention indenture independence independency independent inderal indestructibility indeterminacy indeterminateness indetermination index indexation indexer indexing india indiaman indian indiana indianan indianapolis indic indicant indication indicative indicator indicatoridae indictability indiction indictment indie indifference indigen indigence indigene indigenousness indigestibility indigestibleness indigestion indigirka indignation indignity indigo indigofera indigotin indinavir indirection indirectness indiscipline indiscreetness indiscretion indispensability indispensableness indisposition indisputability indistinctness indistinguishability indium individual individualisation individualism individualist individuality individualization individuation indo-aryan indo- european indo-hittite indo-iranian indochina indocin indoctrination indolence indomethacin indomitability indonesia indonesian indorsement indorser indra indri indriidae indris indubitability inducement inducer inducing inductance inductee induction inductor indulgence indulging indument indumentum induration indus indusium industrialisation industrialism industrialist industrialization industriousness industry indweller inebriant inebriate inebriation inebriety ineffectiveness ineffectuality ineffectualness inefficaciousness inefficacy inefficiency inelasticity inelegance ineligibility ineluctability ineptitude ineptness inequality inequity inerrancy inertia inertness inessential inessentiality inevitability inevitable inevitableness inexactitude inexactness inexorability inexorableness inexpedience inexpediency inexpensiveness inexperience inexplicitness infallibility infamy infancy infant infant's-breath infanticide infantilism infantry infantryman infarct infarction infatuation infeasibility infection infelicity inference inferior inferiority infernal inferno infertility infestation infidel infidelity infield infielder infiltration infiltrator infinite infiniteness infinitesimal infinitive infinitude infinity infirmary infirmity infix inflaming inflammability inflammation inflater inflation inflator inflection inflexibility inflexibleness inflexion infliction infliximab inflorescence inflow influence influenza influx info infolding infomercial informality informant informatics information informer informercial informing infotainment infraction infrared infrastructure infrequency infrigidation infringement infructescence infundibulum infuriation infusion infusoria infusorian inga ingathering inge ingeniousness ingenue ingenuity ingenuousness inger ingerman ingesta ingestion inglenook ingot ingraining ingrate ingratiation ingratitude ingredient ingres ingress ingrian ingroup ingrowth inguen inh inhabitancy inhabitant inhabitation inhalant inhalation inhalator inhaler inharmoniousness inherence inherency inheritance inheritor inheritress inheritrix inhibition inhibitor inhomogeneity inhospitableness inhospitality inhumaneness inhumanity inhumation inion iniquity initial initialisation initialization initiate initiation initiative initiator injectant injection injector injudiciousness injun injunction injuriousness injury injustice ink inka inkberry inkblot inkiness inkle inkling inkpad inkpot inkstand inkwell inla inlay inlet inmarriage inmate inn innards innateness innersole innervation inning innings innkeeper innocence innocency innocense innocent innovation innovativeness innovator innsbruck innuendo innumerableness inocor inoculant inoculating inoculation inoculator inoculum inopportuneness inordinateness inosculation inosine inositol inpatient inpour inpouring input inquest inquietude inquirer inquiring inquiry inquisition inquisitiveness inquisitor inr inroad inrush ins insalubriousness insalubrity insaneness insanity inscription inscrutability insect insecta insecticide insectifuge insectivora insectivore insecureness insecurity insemination insensibility insensitiveness insensitivity insentience insert insertion insessores inset inside insider insidiousness insight insightfulness insignia insignificance insincerity insinuation insipidity insipidness insistence insistency insisting insobriety insolation insole insolence insolubility insolvency insolvent insomnia insomniac insouciance inspection inspector inspectorate inspectorship inspiration inspirer inspissation instability installation installing installment instalment instance instancy instant instantaneousness instantiation instar instauration instep instigant instigation instigator instillation instillator instilling instillment instilment instinct institute institution instroke instruction instructions instructor instructorship instructress instrument instrumentalism instrumentalist instrumentality instrumentation insubordination insubstantiality insufficiency insufflation insulant insularism insularity insulation insulator insulin insult insurability insurance insured insurer insurgence insurgency insurgent insurrection insurrectionism insurrectionist intactness intaglio intake intangibility intangible intangibleness integer integral integrality integrating integration integrator integrity integument intellect intellection intellectual intellectualisation intellectualization intelligence intelligentsia intelligibility intelnet intemperance intemperateness intensification intensifier intension intensity intensive intensiveness intent intention intentionality intentness interaction interahamwe interbrain interbreeding intercalation intercept interception interceptor intercession intercessor interchange interchangeability interchangeableness intercom intercommunication intercommunion interconnectedness interconnection intercostal intercourse interdependence interdependency interdict interdiction interest interestedness interestingness interface interference interferometer interferon interim interior interjection interlaken interlanguage interlayer interleaf interleukin interlingua interlock interlocking interlocutor interloper interlude intermarriage intermediary intermediate intermediation intermediator interment intermezzo intermission intermittence intermittency intermixture intern internalisation internality internalization international internationale internationalisation internationalism internationalist internationality internationalization interne internee internet internist internment internode internship internuncio interoception interoceptor interoperability interpellation interpenetration interphone interplay interpol interpolation interposition interpretation interpreter interpreting interreflection interregnum interrelatedness interrelation interrelationship interrogation interrogative interrogator interrogatory interrupt interrupter interruption intersection intersex interspersal interspersion interstate interstice intertrigo interval intervenor intervention interview interviewee interviewer intestacy intestine inti intifada intifadah intima intimacy intimate intimation intimidation intolerance intonation intoxicant intoxication intractability intractableness intrados intranet intransigence intransigency intransitive intransitiveness intransitivity intravasation intrenchment intrepidity intricacy intrigue intriguer intro introduction introit introitus introject introjection intromission intron intropin introspection introspectiveness introversion introvert intruder intrusion intrusiveness intubation intuition intuitionism intumescence intumescency intussusception inuit inula inulin inunction inundation inutility invader invagination invalid invalidation invalidator invalidism invalidity invalidness invaluableness invar invariability invariable invariableness invariance invariant invasion invective invention inventiveness inventor inventory inventorying inverse inversion invertase invertebrate inverter investigating investigation investigator investing investiture investment investor invidia invigilation invigilator invigoration invigorator invincibility invirase invisibility invisibleness invitation invite invitee invocation invoice involucre involuntariness involution involvement invulnerability inwardness io iodide iodin iodination iodine iodine-125 iodine-131 iodochlorhydroxyquin iodocompound iodoform iodoprotein iodopsin iodothyronine iodotyrosine iol ion ionesco ionia ionian ionic ionisation ionization ionophoresis ionosphere iontophoresis iontotherapy iop iota iou iowa iowan ioway ip ipecac iphigenia ipidae ipo ipod ipomoea iproclozide ipsedixitism ipsus ipv iq ir ira irak iraki iran irani iranian iraq iraqi irascibility ire ireland irelander irena irenaeus irenidae iresine iridaceae iridectomy iridescence iridium iridocyclitis iridokeratitis iridoncus iridoprocne iridosmine iridotomy iris irish irishman irishwoman iritis iron iron-gray iron- grey iron-tree ironclad ironing ironist ironman ironmonger ironmongery irons ironside ironsides ironware ironweed ironwood ironwork ironworker ironworks irony iroquoian iroquois irradiation irrational irrationality irrawaddy irreality irredenta irredentism irredentist irregular irregularity irrelevance irrelevancy irreligion irreligionist irreligiousness irreplaceableness irrepressibility irreproducibility irresistibility irresistibleness irresoluteness irresolution irresponsibility irresponsibleness irreverence irreversibility irridenta irridentism irridentist irrigation irritability irritant irritation irruption irs irtish irtysh irula irving irvingia isaac isabella isaiah isarithm isatis ischaemia ischemia ischia ischigualastia ischium isere iseult isfahan isherwood ishmael ishtar isi isinglass isis iskcon islam islamabad islamism islamist islamophobia island island-dweller islander islay isle islet ism ismaili ismailian ismailism isn isoagglutination isoagglutinin isoagglutinogen isoantibody isobar isobutylene isocarboxazid isochrone isoclinal isocrates isocyanate isoetaceae isoetales isoetes isoflurane isogamete isogamy isogon isogone isogram isohel isolation isolationism isolationist isolde isoleucine isomer isomerase isomerisation isomerism isomerization isometric isometrics isometropia isometry isomorphism isomorphy isoniazid isopleth isopod isopoda isopropanol isoproterenol isoptera isoptin isopyrum isordil isosorbide isospondyli isostasy isotherm isothiocyanate isotope isotropy israel israeli israelite israelites issachar issuance issue issuer issuing issus istanbul isthmus istiophoridae istiophorus isuprel isuridae isurus it italia italian italic italy itch itchiness itching item itemisation itemization iteration iterative ithaca ithaki ithunn itinerant itinerary itineration itraconazole iud iv iva ivanov ives ivory ivorybill ivp ivry ivy iw iwo iww ix ixia ixobrychus ixodes ixodid ixodidae iyar iyyar izanagi izanami izar izmir izzard j jab jabalpur jabber jabberer jabbering jabberwocky jabbing jabiru jaboncillo jabot jaboticaba jacamar jacaranda jacinth jack jack-a-lantern jack-by-the-hedge jack- in-the-box jack-in-the-pulpit jack-o'-lantern jack-o-lantern jack-tar jackal jackanapes jackass jackboot jackdaw jacket jackfruit jackhammer jackknife jackknife-fish jacklight jackpot jackrabbit jacks jackscrew jacksmelt jacksnipe jackson jacksonia jacksonian jacksonville jackstones jackstraw jackstraws jacob jacobean jacobi jacobin jacobinism jacobite jacobs jaconet jacquard jacquinia jactation jactitation jaculus jade jadeite jadestone jaeger jafar jaffa jaffar jag jagannath jagannatha jagatai jagganath jaggary jaggedness jagger jaggery jagghery jaghatai jagua jaguar jaguarondi jaguarundi jahvey jahweh jail jailbird jailbreak jailer jailhouse jailor jainism jainist jaish-e-muhammad jaish-i-mohammed jak jakarta j<NAME> jalalabad jalapeno jalopy jalousie jam jamaica jamaican jamb jambalaya jambeau jamberry jambon jamboree jambos jambosa james jamesonia jamestown jamison jamjar jammer jammies jamming jampan jampot jan jangle janissary janitor jansen jansenism jansenist january janus jap japan japanese jape japery japheth japonica jar jarful jargon jargoon jarrell jasmine jasminum jason jasper jaspers jassid jassidae jat jati jatropha jaundice jaunt jauntiness java javan javanese javanthropus javelin javelina jaw jawan jawbone jawbreaker jawfish jay jaybird jayshullah jaywalker jazz jazzman jdam jealousy jean jed'dah jeddah jeep jeer jeerer jeering jeffers jefferson jeffersonian jehad jehovah jejuneness jejunitis jejunity jejunoileitis jejunostomy jejunum jell-o jellaba jello jelly jellyfish jellyleaf jellyroll jem jemmy jena jenner jennet jenny jensen jeopardy jerboa jeremiad jeremiah jerevan jerez jericho jerk jerk-off jerker jerkin jerkiness jerking jerky jeroboam jerome jerry jerry-builder jerry-building jersey jerusalem jespersen jessamine jest jester jesuit jesuitism jesuitry jesus jet jeth jetliner jetsam jetty jevons jew jew's-ear jew's-ears jew-baiter jew-bush jewbush jewel jeweler jeweller jewellery jewelry jewels-of-opar jewelweed jewess jewfish jewison jewry jezebel jfk jhvh ji jiao jib jibboom jibe jidda jiddah jiffy jig jigaboo jigger jiggermast jiggery-pokery jiggle jigsaw jihad jihadist jillion jilt jimdandy jimenez jimhickey jimmies jimmy jimsonweed jinghpaw jinghpo jingle jingo jingoism jingoist jinja jinks jinnah jinnee jinni jinrikisha jinx jiqui jird jirga jirrbal jitney jitter jitterbug jitteriness jitters jiujitsu jive jnd jnr joachim job jobber jobbery jobcentre jobholder jocasta jock jockey jockstrap jocoseness jocosity jocote jocularity jocundity jodhpur jodhpurs joel joewood joffre joffrey jog jogger jogging joggle johannesburg john johnny johnny-jump-up johnnycake johns johnson johnston join joiner joinery joining joint jointer jointure jointworm joist joke joker jokester joliet joliot joliot-curie jolliet jollification jolliness jollity jolly jolson jolt jonah jonathan jones jonesboro jong jongleur jonquil jonson jook joplin joppa jordan jordanella jordanian jorum joseph josephus joshua joss jostle jostling josue jot jotter jotting jotun jotunn joule jounce journal journalese journalism journalist journey journeyer journeying journeyman joust jove joviality jowett jowl joy joyce joyfulness joylessness joyousness joyride joystick jr jra juarez jubbulpore jubilance jubilancy jubilation jubilee juda judaea judah judaica judaism judas jude judea judeo-spanish judge judgement judges judgeship judging judgment judicatory judicature judiciary judiciousness judith judo jug jugale jugful juggernaut juggle juggler jugglery juggling juglandaceae juglandales juglans jugoslav jugoslavian jugoslavija jugular juice juicer juiciness jujitsu juju jujube jujutsu juke jukebox julep julian julienne july jumbal jumble jumbojet jument jump jump-start jumper jumpiness jumping jumpstart jumpsuit juncaceae juncaginaceae junco junction juncture juncus jund-ul-islam june juneau juneberry jung jungermanniaceae jungermanniales jungian jungle junior juniper juniperus junk junker junkers junket junketing junkie junky junkyard juno junta junto jupati jupaty jupiter jurassic jurisdiction jurisprudence jurist juror jury juryman jurywoman jussieu justice justiciar justiciary justification justifier justinian justness jut jute jutish jutland jutting juvenal juvenescence juvenile juvenility juxtaposition jv jyaistha jylland jynx k k-lor k-lyte k-meson k.e. k2 ka kaaba kabala kabbala kabbalah kabbalism kabbalist kabob kabolin kabul kach kachaturian kachin kachina kachinic kadai kadikoy kaffir kaffiyeh kafir kafiri kafka kafocin kaftan kahikatea kahlua kahn kahoolawe kail kainite kainogenesis kaiser kakatoe kakemono kaki kala-azar kalahari kalamazoo kalansuwa kalantas kalapooia kalapooian kalapuya kalapuyan kalashnikov kale kaleidoscope kalemia kali kalian kalif kalimantan kalinin kaliph kaliuresis kalka kalki kalmia kalotermes kalotermitidae kalpac kaluga kalumpang kaluresis kam-sui kam-tai kama kamarupan kamasutra kamba kameez kamet kami kamia kamikaze kampala kampong kampuchea kampuchean kanaf kanamycin kananga kanara kanarese kanawha kanchanjanga kanchenjunga kanchil kandahar kandinski kandinsky kandy kangaroo kangaroo's-foot kannada kansa kansan kansas kansu kant kantrex kanzu kaochlor kaoliang kaolin kaoline kaolinite kaon kaopectate kapeika kaph kapok kappa kappa-meson kapsiki kapuka karabiner karachi karaites karakalpak karakoram karakul karaoke karat karate karbala karelia karelian karen karenic karl-marx- stadt karlfeldt karloff karma karnataka karok karpov karsavina kartik kartikeya karttika karttikeya karyokinesis karyolymph karyolysis karyon karyoplasm karyotype kasai kasbah kasha kashag kashmir kashmiri kasparov kassite kastler kat katabolism katamorphism katar katari katharevusa katharobe katharometer katharsis kathmandu katmandu katowice katsina katsuwonidae katsuwonus kattegatt katydid katzenjammer kauai kaufman kaunas kaunda kauri kaury kava kavakava kavrin kawaka kayak kayo kazak kazakh kazakhstan kazakhstani kazakstan kazan kazoo kb kbit kbo kc kea kean keaton keats keb kebab keble kechua kechuan kedgeree keel keelboat keelson keen keenness keep keeper keeping keepsake keeshond keflex keflin keftab keg kegful keister kekchi kekule keller kellogg kelly keloid kelp kelpie kelpwort kelpy kelt kelter kelvin kemadrin ken kenaf kenalog kendal kendall kendrew kennan kennedia kennedy kennedya kennel kennelly kennewick kenning keno kenogenesis kent kentan kentish kentuckian kentucky kenya kenyan kenyapithecus kenyata keokuk kepi kepler kera keratalgia keratectasia keratin keratinisation keratinization keratitis keratoacanthoma keratocele keratoconjunctivitis keratoconus keratoderma keratodermia keratohyalin keratoiritis keratomalacia keratomycosis keratonosis keratonosus keratoplasty keratoscleritis keratoscope keratoscopy keratosis keratotomy kerb kerbala kerbela kerbstone kerchief kerensky kerfuffle kerion kern kernel kernicterus kernite kerosene kerosine kerouac kerugma kerygma kesey kestrel ketalar ketamine ketch ketchup keteleeria ketembilla ketoacidosis ketoaciduria ketohexose ketone ketonemia ketonuria ketoprofen ketorolac ketose ketosis ketosteroid kettering kettle kettledrum kettleful ketubim keurboom key keyboard keyboardist keycard keyhole keynes keynesian keynesianism keynote keypad keystone keystroke kg kgb khabarovsk khachaturian khadafy khaddar khadi khaki khakis khalif khalifah khalka khalkha khalsa khama khamsin khamti khan khanate khanty kharkiv kharkov khartoum khat khaya khedive khepera khesari khi khimar khios khirghiz khmer khoikhoi khoikhoin khoisan khomeini khoum khowar khrushchev khuen khufu khukuri khz ki kiaat kiang kib kibble kibbutz kibbutznik kibe kibibit kibibyte kibit kibitzer kichaga kichai kick kickapoo kickback kicker kicking kickoff kickshaw kicksorter kickstand kid kidd kiddy kidnaper kidnapper kidnapping kidney kidskin kierkegaard kieselguhr kieserite kieslowski kiev kigali kiggelaria kike kikladhes kildeer kilderkin kiley kilimanjaro kiliwa kiliwi kill killdeer killer killifish killing killjoy kiln kilo kilobit kilobyte kilocalorie kilocycle kilogram kilogram-meter kilohertz kiloliter kilolitre kilometer kilometre kiloton kilovolt kilovolt-ampere kilowatt kilroy kilt kilter kimberley kimberlite kimono kin kina kinaesthesia kinaesthesis kinanesthesia kinase kinchinjunga kind kind-heartedness kindergarten kindergartener kindergartner kindheartedness kindliness kindling kindness kindred kine kinematics kinescope kinesiology kinesis kinesthesia kinesthesis kinesthetics kinetics kinetochore kinetoscope kinetosis kinfolk king kingbird kingbolt kingcup kingdom kingfish kingfisher kinglet kingmaker kingpin kingship kingsnake kingston kingstown kingwood kinin kink kinkajou kino kinosternidae kinosternon kinsey kinsfolk kinshasa kinship kinsman kinsperson kinswoman kinyarwanda kiosk kiowa kip kipling kipper kirchhoff kirchner kirghiz kirghizia kirghizstan kirgiz kirgizia kirgizstan kiribati kirk kirkia kirkuk kirpan kirsch kirtle kishar kishinev kishke kislev kismat kismet kiss kiss-me-over-the-garden-gate kisser kissimmee kissing kissinger kisumu kiswahili kit kitakyushu kitambilla kitbag kitchen kitchener kitchenette kitchenware kite kitembilla kith kitsch kittee kitten kitten-tails kittiwake kittul kitty kitty-cat kitul kivu kiwi kkk klaipeda klamath klan klansman klaproth klavern klavier klaxon klebsiella klee kleenex klein kleist kleptomania kleptomaniac klick klimt kline klinefelter klondike klopstock klorvess klotho kludge klutz kluxer klystron klyuchevskaya km km/h knack knacker knackwurst knapsack knapweed knave knavery knawe knawel knee knee- hi knee-high kneecap kneel kneeler kneeling kneepan knell knesset knesseth knickerbockers knickers knickknack knickknackery knife knife-edge knife-handle knight knight-errant knighthood knightia knightliness kniphofia knish knit knitter knitting knitwear knitwork knob knobble knobkerrie knobkerry knock knock-knee knockabout knockdown knocker knocking knockoff knockout knockwurst knoll knossos knot knotgrass knothole knottiness knout know know-all know-how know-it-all knower knowing knowingness knowledge knowledgeability knowledgeableness knox knoxville knuckle knuckleball knucklebones knucklehead knuckler knuckles knucks knut ko koala koan koasati kob kobe kobenhavn kobo kobus koch kochia kodiak koellia koestler kogia kohl kohleria kohlrabi koine koinonia kok-saghyz kok-sagyz kokka kola kolam kolami kolkata kolkhoz kolkhoznik kolkwitzia koln kolonia komi komondor konakri kongfuze kongo konini konoe konoye konqueror koodoo kook kookaburra koopmans kopeck kopek kopiyka kopje koppie kor koran korbut korchnoi korda kordofan kordofanian kore korea korean korinthos koruna korzybski kos kosciusko kosciuszko kosher kosovo kosteletzya kota kotar kotex koto kotoko kotow koudou koumiss koussevitzky kovna kovno koweit kowhai kowtow kp kph kr kraal krafft-ebing kraft krait krakatao krakatau krakatoa krakau krakow krasner kraurosis kraut krauthead krebs kreisler kremlin krigia krill kris krishna krishnaism kriti kroeber krona krone kronecker kroon kropotkin kroto krubi kruger krummhorn krupp krypterophaneron krypton ks kshatriya kt ku-chiku kuangchou kubrick kuchean kudos kudu kudzu kuenlun kuhn kui kuiper kukenaam kuki kuki-chin kulanapan kulun kumasi kumis kummel kumquat kunlun kunzite kuomintang kura kurakkan kurchee kurchi kurd kurdish kurdistan kuri-chiku kurosawa kuroshio kurrajong kurrat kursk kurta kuru kurus kurux kusan kutch kutuzov kuvasz kuvi kuwait kuwaiti kuznets kv kvass kvetch kw kw-hr kwa kwacha kwai kwajalein kwakiutl kwan-yin kwangchow kwangju kwangtung kwannon kwanza kwanzaa kwashiorkor kwazulu-natal kweek kwela kwell ky kyanite kyat kyd kylie kylix kymograph kyo-chiku kyoto kyphosidae kyphosis kyphosus kyrgyzstan kyushu kyyiv l l'aquila l'enfant l-dopa l-p l-plate la laager lab laban labanotation labdanum label labetalol labial labiatae labiodental labium lablab lablink labor laboratory laborer laboriousness labour labourer labourite labrador labridae labrocyte labrouste laburnum labyrinth labyrinthitis labyrinthodont labyrinthodonta labyrinthodontia lac laccopetalum lace lacebark lacepod lacer laceration lacerta lacertid lacertidae lacertilia lacewing lacewood lacework lachaise lachesis lachnolaimus lachrymation lachrymator lacing lack lackey laconia laconian laconicism laconism lacquer lacquerware lacrimation lacrimator lacrosse lactaid lactalbumin lactarius lactase lactate lactation lacteal lactifuge lactobacillaceae lactobacillus lactobacteriaceae lactoflavin lactogen lactophrys lactose lactosuria lactuca lacuna lad ladanum ladder ladder- back laddie ladies'-eardrop ladies'-eardrops ladin lading ladino ladle ladoga lady lady's-eardrop lady's-eardrops lady's-finger lady-in-waiting lady-of-the- night lady-slipper ladybeetle ladybird ladybug ladyfinger ladyfish ladylikeness ladylove ladyship laelia laertes laetrile laevulose lafayette laffer laffite lafitte lag lagan lagarostrobus lagenaria lagend lagenophera lager lagerphone lagerstroemia laggard lagger lagging lagidium lagniappe lagodon lagomorph lagomorpha lagoon lagophthalmos lagopus lagorchestes lagos lagostomus lagothrix laguna laguncularia lagune lah lahar lahore lahu lair laird laity laius lake lakefront lakeland lakeshore lakeside lakh lakota lakshmi lallans lallation lally lam lama lamaism lamaist lamarck lamarckian lamarckism lamasery lamb lamb's-quarter lamb's-quarters lamb-chop lambchop lambda lambdacism lambency lambert lambertia lambis lambkill lambkin lambrequin lambskin lame lamedh lamella lamellibranch lamellibranchia lamellicornia lameness lament lamentation lamentations lamenter lamia lamiaceae lamina laminaria laminariaceae laminariales laminate lamination laminator laminectomy laminitis lamisil lamium lamivudine lammas lammastide lammergeier lammergeyer lamna lamnidae lamp lampblack lamphouse lamplight lamplighter lampoon lampooner lamppost lamprey lampridae lampris lampropeltis lampshade lampshell lampyridae lan lanai lancashire lancaster lancastrian lance lancelet lancelot lancer lancers lancet lancetfish lancewood lanchou lanchow land landau lander landfall landfill landgrave landholder landholding landing landlady landler landline landlord landlubber landman landmark landmass landowner landowska landrover landscape landscaper landscaping landscapist landside landslide landslip landsmaal landsmal landsman landsteiner lane laney langbeinite lange langlaufer langley langmuir langobard langouste langoustine langsat langset langside langsyne langtry language languedoc-roussillon languisher languor langur laniard laniidae lanius lankiness lanolin lanoxin lansa lansat lanseh lanset lansing lansoprazole lantana lantern lantern-fly lanternfish lanthanide lanthanoid lanthanon lanthanotidae lanthanotus lanthanum lanugo lanyard lanzhou lao lao-tse lao-tzu lao-zi laocoon laos laotian lap laparocele laparoscope laparoscopy laparotomy lapboard lapdog lapel lapful lapidarist lapidary lapidation lapidator lapidist lapin laplace lapland laportea lapp lappet lappic lapping lappish lappland lapplander lappula lapse lapsing laptop laputa lapwing laramie larboard larcener larcenist larcenous larceny larch lard larder lardizabala lardizabalaceae lardner laredo large largemouth largeness largess largesse larghetto largo lari lariat laricariidae larid laridae larium larix lark larkspur larodopa larotid larousse larrea larus larva larvacea larvacean larvacide larvicide laryngectomy laryngismus laryngitis laryngopharyngitis laryngopharynx laryngoscope laryngospasm laryngostenosis laryngotracheobronchitis larynx lasagna lasagne lasalle lascar lascaux lasciviousness lasek laser lash lash-up lasher lashing lashings lashkar-e-jhangvi lashkar-e-omar lashkar-e-taiba lashkar-e-tayyiba lashkar-e-toiba lasik lasiocampa lasiocampid lasiocampidae lasiurus lasix lass lassa lassie lassitude lasso last lastex lasthenia lastingness lastreopsis lat latakia latanier latch latchet latchkey latchstring latecomer lateen lateen-rig latency lateness lateral lateralisation laterality lateralization lateran laterite lates latest latex lath lathe lathee lather lathi lathyrus laticifer latimeria latimeridae latin latinae latinesce latinism latinist latino latitude latitudinarian latium latke latona latria latrine latrobe latrodectus lats latte latten latter lattice latticework latvia latvian laudability laudableness laudanum laudator lauder laudo laugh laugher laughingstock laughter laughton lauhala launce launch launcher launching launchpad launderette laundering laundress laundromat laundry laundryman laundrywoman lauraceae laurasia laureate laurel laurel-tree laurels laurelwood laurens laurentius laurus lausanne lav lava lavabo lavage lavalava lavalier lavaliere lavalliere lavandula lavatera lavation lavatory lavender laver lavishness lavoisier law law-breaking law- makers lawbreaker lawcourt lawfulness lawgiver lawlessness lawmaker lawmaking lawman lawn lawrence lawrencium laws lawsuit lawton lawyer lawyerbush laxation laxative laxity laxness lay lay-by lay-up layabout layby layer layette layia laying layman layoff layout layover layperson layup lazar lazaret lazarette lazaretto lazarus laziness lazio lazuli lazuline lazybones lb lbf. lbj lcd lcm ld. ldl le lea leach leaching leacock lead lead-in leadbelly leader leaders leadership leading leadplant leadwort leaf leaf-book leaf-cutter leaf-miner leaf-roller leafage leafhopper leafing leaflet leafstalk league leak leakage leaker leakey leakiness lean lean-to leander leaner leaning leanness leap leaper leapfrog leaping lear learnedness learner learning leary lease lease-lend leasehold leaseholder leash least leather leatherback leatherette leatherfish leatherjack leatherjacket leatherleaf leatherneck leatherwood leatherwork leave leave-taking leaven leavening leaver leaving lebanese lebanon lebensraum lebistes lecanopteris lecanora lecanoraceae leccinum lech lechanorales lechatelierite lecher lecherousness lechery lechwe lecithin lectern lectin lector lecture lecturer lectureship lecturing lecythidaceae led leda ledbetter lede lederhosen ledge ledgeman ledger ledum lee leech leechee leeds leek leer lees leeuwenhoek leeward leeway leflunomide left left-handedness left-hander left-winger leftfield lefthander leftism leftist leftover leftovers lefty leg leg-pull leg-pulling legacy legalese legalisation legalism legality legalization legate legatee legateship legation legend leger legerdemain legerity legging leghorn legibility leging legion legionary legionella legionnaire legislating legislation legislator legislatorship legislature legitimacy legitimation lego legs legume leguminosae lehar lei leibnitz leibniz leicester leicestershire leiden leigh leiomyoma leiomyosarcoma leiopelma leiopelmatidae leiophyllum leipoa leipzig leishmania leishmaniasis leishmaniosis leister leisure leisureliness leitmotif leitmotiv leitneria leitneriaceae lek lekvar lem lemaireocereus lemaitre lemanderin lemma lemming lemmon lemmus lemna lemnaceae lemniscus lemnos lemon lemon-wood lemonade lemongrass lemonwood lempira lemur lemuridae lemuroidea lena lenard lend-lease lender lending lendl length lengthening lengthiness lenience leniency lenin leningrad leninism lenitive lenity lennoaceae lennon lens lense lensman lent lententide lentia lentibulariaceae lenticel lentigo lentil lentinus lentisk leo leon leonard leonardo leonberg leoncita leone leonidas leonotis leontief leontocebus leontodon leontopodium leonurus leopard leopard's-bane leopardbane leopardess leopoldville leotard leotards lepadidae lepanto lepas lepechinia leper lepidium lepidobotryaceae lepidobotrys lepidochelys lepidocrocite lepidocybium lepidodendraceae lepidodendrales lepidolite lepidomelane lepidophobia lepidoptera lepidopteran lepidopterist lepidopterologist lepidopterology lepidopteron lepidoptery lepidosauria lepidothamnus lepiota lepiotaceae lepisma lepismatidae lepisosteidae lepisosteus lepomis leporid leporidae leporide leppy leprechaun leprosy leptarrhena leptinotarsa leptocephalus leptodactylid leptodactylidae leptodactylus leptoglossus leptomeninges leptomeningitis lepton leptopteris leptoptilus leptospira leptospirosis leptosporangium leptotene leptotyphlopidae leptotyphlops lepus ler leresis lermontov lerner lerot lesbian lesbianism lesbos lescol lesion lesotho lespedeza lesquerella lessee lessening lesseps lessing lesson lessor lesvos let letch letdown lethality lethargy lethe leto letter lettercard letterer letterhead lettering letterman letterpress letters letting lettish lettuce letup leu leucadendron leucaemia leucaena leucanthemum leucine leuciscus leucocyte leucocytosis leucocytozoan leucocytozoon leucogenes leucoma leucopenia leucorrhea leucothoe leucotomy leuctra leukaemia leukemia leukeran leukocyte leukocytosis leukoderma leukoencephalitis leukoma leukopenia leukorrhea leukotomy leuwenhoek lev levallorphan levant levanter levantine levator levee level leveler leveling leveller lever leverage leveraging leveret levi levi's levi-strauss leviathan levirate levis levisticum levitation levite leviticus levitra levity levodopa levorotation levulose levy lewdness lewis lewisia lewiston lexeme lexicalisation lexicalization lexicographer lexicography lexicologist lexicology lexicon lexicostatistics lexington lexis ley leycesteria leyden leymus leyte lf lgb lgv lh lhasa lhotse li liabilities liability liaison liakoura liana liao liar liatris libation libber libby libel libeler liberal liberalisation liberalism liberalist liberality liberalization liberalness liberation liberator liberia liberian libertarian libertarianism libertine liberty libido libocedrus libra librarian librarianship library libration librettist libretto libreville libritabs librium libya libyan licence license licensee licenser licentiate licentiousness lichanura lichee lichen lichenales lichenes lichgate lichi lichtenstein licitness lick licking licorice lid lidar lido lidocaine lie lie- abed lie-in liebfraumilch liechtenstein liechtensteiner lied liederkranz liege liegeman lien liepaja lietuva lieu lieutenancy lieutenant life life-of-man life- style life-time lifeblood lifeboat lifeguard lifelessness lifeline lifer lifesaver lifesaving lifespan lifestyle lifetime lifework lifo lift lifter liftman liftoff ligament ligan ligand ligation ligature liger light light- mindedness light-o'-love light-of-love light-year lightbulb lightening lighter lighterage lighterman lightheadedness lightheartedness lighthouse lighting lightlessness lightness lightning lights-out lightship lightsomeness lightweight lightwood ligne lignin lignite lignosae lignum ligularia ligule liguria ligustrum like likelihood likeliness likeness likening liking likuta lilac lilangeni liliaceae liliales liliidae liliopsid liliopsida lilith lilium liliuokalani lille lillie lilliput lilliputian lilo lilongwe lilt lily lilyturf lima limacidae liman limanda limax limb limber limbers limbo limburger limbus lime limeade limeira limekiln limelight limen limenitis limerick limestone limewater limey limicolae limit limitation limited limiter limiting limitlessness limner limning limnobium limnocryptes limnodromus limnologist limnology limnos limo limonene limonite limonium limosa limousin limousine limp limpa limper limpet limpidity limping limpkin limpness limpopo limulidae limulus lin linac linaceae linage linalool linanthus linaria linchpin lincocin lincoln lincolnshire lincomycin lind lindane lindbergh linden lindera lindesnes lindheimera lindsay lindy line line-shooter line-shooting lineage lineament linearity lineation linebacker linecut lineman linemen linen linendraper liner linesman lineup ling ling-pao lingam lingberry lingcod lingenberry lingerer lingerie lingering lingo lingonberry lingua lingual lingualumina linguica linguine linguini linguist linguistics liniment linin lining link linkage linkboy linkman links linksman linkup linnaea linnaeus linnet lino linocut linoleum linotype linseed linsey-woolsey linstock lint lintel lintwhite linum linuron linux linz liomys lion lion's-ear lion-hunter lioness lionet lionfish liopelma liopelmidae liothyronine lip lip-gloss lipaemia liparidae liparididae liparis lipase lipchitz lipectomy lipemia lipfern lipid lipidaemia lipide lipidemia lipidosis lipitor lipizzan lipmann lipo-hepin lipo-lutin lipochondrodystrophy lipogram lipoid lipoidaemia lipoidemia lipoma lipomatosis lipoprotein liposarcoma liposcelis liposome liposuction lipotyphla lippi lippizan lippizaner lippmann lipreading lipscomb lipstick liquaemin liquefaction liqueur liquid liquidambar liquidation liquidator liquidiser liquidity liquidizer liquidness liquor liquorice lir lira liriodendron liriope lisboa lisbon lisinopril lisle lisp lisper lissomeness list listener listening lister listera listeria listeriosis listing listlessness liston lisu liszt lit litany litas litchee litchi liter literacy literal literalism literalness literate literati literature lithane litheness lithiasis lithium lithocarpus lithodidae lithoglyptics lithograph lithographer lithography lithology lithomancer lithomancy lithonate lithophragma lithophyte lithops lithospermum lithosphere lithotomy lithuania lithuanian lithuresis litigant litigation litigator litigiousness litmus litocranius litoral litotes litre litter litter-basket litter-bearer litterateur litterbin litterbug litterer little littleneck littleness littoral littorina littorinidae littre liturgics liturgiology liturgist liturgy live-and-die live-bearer live-forever livedo livelihood liveliness livelong liveness liver liverleaf livermore liverpool liverpudlian liverwort liverwurst livery liveryman livestock lividity lividness living living-room livingston livingstone livistona livonia livonian livy liza lizard lizard's-tail lizardfish ljubljana llama llano llb lld llm lloyd llud llullaillaco llyr lm lo/ovral loach load load-shedding loader loading loads loadstar loadstone loaf loafer loafing loam loan loan-blend loanblend loaner loaning loanword loasa loasaceae loather loathing loathsomeness lob lobachevsky lobata lobby lobbyism lobbyist lobe lobectomy lobefin lobelia lobeliaceae lobipes lobito loblolly lobotes lobotidae lobotomy lobscouse lobscuse lobster lobsterback lobsterman lobularia lobularity lobule lobworm local locale localisation localism locality localization locater locating location locative locator loch lochia lock lock-gate lockage lockbox lockdown locke locker locket locking lockjaw lockkeeper lockman lockmaster locknut lockout lockring locksmith lockstep lockstitch lockup locoism locomotion locomotive locoweed locule loculus locum locus locust locusta locustidae locution lode lodestar lodestone lodge lodgement lodgepole lodger lodging lodgings lodgment lodine lodz loeb loess loestrin loewe loewi lofortyx lofoten loft loftiness log logagraphia logan loganberry logania loganiaceae logarithm logbook loge logger loggerhead loggia logginess logging logic logicality logicalness logician logicism loginess logion logistician logistics logjam logo logogram logograph logomach logomachist logomachy logomania logorrhea logos logotype logrolling logrono logwood lohan loin loincloth loins loir loire loiseleuria loiterer loki loligo lolita lolium lollipop lolly lolo lolo-burmese loloish lomariopsidaceae lomatia lombard lombardia lombardy lome loment lomogramma lomotil lomustine lonas lonchocarpus london londoner loneliness loner lonesomeness long-beard long-legs long- sufferance long-suffering long-windedness longan longanberry longanimity longbeard longboat longbow longbowman longer longevity longfellow longhand longhorn longicorn longing longitude longlegs longness longroot longshoreman longshot longsightedness longueur longways longwool longyi lonicera loniten lontar loo loofa loofah look look-alike look-over lookdown looker looker-on looking lookout lookup loom loon looney loonie loony loop loop-line loop-the- loop looper loophole looping loos looseness loosening loosestrife loot looter looting lope lophiidae lophius lophodytes lopholatilus lophophora lophophorus lophosoria lophosoriaceae lopid lopper lopressor lopsidedness loquaciousness loquacity loquat loranthaceae loranthus lorazepam lorca lorchel lord lordliness lordolatry lordosis lords-and-ladies lordship lore lorelei loren lorentz lorenz lorfan lorgnette lorica loricata loriinae lorikeet lorisidae lorraine lorre lorry lory loser losings loss losses lost lost-and-found lot lota lothario lothringen loti lotion lots lotte lottery lotto lotus lotus-eater lotusland loud-hailer loudmouth loudness loudspeaker lough louis louisiana louisianan louisianian louisville lounge lounger loungewear loup-garou loupe louse lousiness lout louvar louver louvre lovage lovastatin love love-in-a-mist love- in-idleness love-in-winter love-lies-bleeding love-philter love-philtre love- potion love-song love-token lovebird lovelace loveliness lovell lovely lovemaking lover loveseat lovesickness loving-kindness lovingness lovoa low low- down low-spiritedness low-warp-loom lowan lowboy lowbrow lowell lower lower- normandy lowercase lowerclassman lowering lowland lowlander lowlands lowlife lowliness lowness lowry lox loxapine loxia loxitane loxodonta loxodrome loxoma loxomataceae loxostege loyalist loyalty loyang loyola lozal lozenge lozier lp lpn lr lsd ltd. ltm ltte lu luanda luau luba lubavitch lubavitcher lubber lubbock lube lubeck lubitsch lublin lubricant lubrication lubricator lubricity lubumbashi lucania lucanidae lucas luce lucerne lucidity lucidness lucifer luciferin lucilia lucite luck luckiness lucknow lucrativeness lucre lucretius lucubration lucullus luculus lucy luda luddite ludian ludo lues lufengpithecus luff luffa lufkin luftwaffe lug luganda luge luger luggage lugger lugh luging lugosi lugsail lugubriousness lugworm luik luke lukewarmness lull lullaby lulli lully lulu luluabourg lumbago lumber lumbering lumberjack lumberman lumbermill lumberyard lumbus lumen luminal luminance luminary luminescence luminism luminosity luminousness lumma lummox lump lumpectomy lumpenproletariat lumpenus lumper lumpfish lumpsucker luna lunacy lunaria lunatic lunation lunch luncheon luncher lunching lunchroom lunchtime lund lunda lunette lung lung-power lunge lungen lunger lungfish lungi lungyi lunkhead lunt lunula lunule luo luoyang lupin lupine lupinus lupus lurch lurcher lure luridness lurker lusaka lusatian luscinia lusciousness lush lushness lushun lusitania lust luster lusterlessness lusterware lustfulness lustiness lustre lustrelessness lustrum luta lutanist lute lutecium lutefisk lutein lutenist luteotropin lutetium lutfisk luther lutheran lutheranism luthier luting lutist lutjanidae lutjanus lutra lutrinae lutyens lutzen luvaridae luvarus luvian luwian lux luxation luxembourg luxembourg-ville luxembourger luxemburg luxemburger luxor luxuria luxuriance luxuriation luxuriousness luxury luyia luzon lwei lx lxx lxxviii lxxx lyallpur lycaena lycaenid lycaenidae lycaeon lycanthrope lycanthropy lycee lyceum lychee lychgate lychnis lycia lycian lycium lycopene lycoperdaceae lycoperdales lycoperdon lycopersicon lycopersicum lycophyta lycopod lycopodiaceae lycopodiales lycopodiate lycopodineae lycopodium lycopsida lycopus lycosa lycosidae lydia lydian lye lygaeid lygaeidae lyginopteridales lyginopteris lygodium lygus lying lying-in lyly lymantria lymantriid lymantriidae lymph lymphadenitis lymphadenoma lymphadenopathy lymphangiectasia lymphangiectasis lymphangiogram lymphangiography lymphangioma lymphangitis lymphedema lymphoblast lymphocyte lymphocytopenia lymphocytosis lymphogranuloma lymphography lymphokine lymphoma lymphopenia lymphopoiesis lymphuria lynchburg lynching lynchpin lynx lyon lyonia lyonnais lyons lyophilisation lyophilization lypressin lyra lyre lyre-flower lyrebird lyreflower lyric lyricality lyricism lyricist lyrist lyrurus lysander lysenko lysichiton lysichitum lysiloma lysimachia lysimachus lysin lysine lysinemia lysippus lysis lysogenicity lysogenisation lysogenization lysogeny lysol lysosome lysozyme lyssa lyssavirus lythraceae lythrum lytton m m-1 m-theory m.m. m1 m2 m3 ma ma'am maalox maar maarianhamina mac macaca macadam macadamia macamba macao macaque macaroni macaroon macarthur macau macaulay macaw macbeth macdowell mace macebearer macedoine macedon macedonia macedonian macer maceration macgregor macguffin mach machaeranthera machete machiavelli machiavellian machiavellianism machicolation machilid machilidae machination machinator machine machinery machinist machismo machmeter macho macho-man macintosh mack mackem mackenzie mackerel mackinaw mackintosh mackle macleaya macleish macleod maclura macon maconnais macoun macowanites macrame macrencephaly macro macrobiotics macrocephalon macrocephaly macrocheira macroclemys macrocosm macrocyte macrocytosis macrodactylus macrodantin macroeconomics macroeconomist macroevolution macroglia macroglossia macromolecule macron macronectes macrophage macropodidae macropus macrorhamphosidae macrosporangium macrospore macrothelypteris macrotis macrotus macrotyloma macrouridae macrozamia macrozoarces macruridae macula maculation macule macumba macushla madagascan madagascar madake madam madame madcap madder madderwort madeira madeiras mademoiselle madhouse madia madison madman madnep madness madonna madoqua madras madrasa madrasah madreporaria madrepore madrid madrigal madrigalist madrilene madrona madrono madwoman madwort maeandra maelstrom maenad maestro maeterlinck mafa maffia mafia mafioso mag magadhan magazine magdalen magdalena magellan magenta maggot magh magha maghreb magi magic magician magicicada magilp maginot magistracy magistrate magistrature maglev magma magnanimity magnanimousness magnate magnesia magnesite magnesium magnet magnetics magnetisation magnetism magnetite magnetization magneto magnetograph magnetohydrodynamics magnetometer magneton magnetosphere magnetron magnificat magnification magnificence magnifico magnifier magniloquence magnitude magnolia magnoliaceae magnoliidae magnoliophyta magnoliopsid magnoliopsida magnum magpie magritte maguey magus magyar magyarorszag mah-jongg maha mahabharata mahabharatam mahabharatum mahagua mahan maharaja maharajah maharanee maharani maharashtra mahatma mahayana mahayanism mahayanist mahdi mahdism mahdist mahgrib mahican mahimahi mahjong mahler mahlstick mahoe mahogany mahomet mahonia mahound mahout mahratta mahratti mahuang maia maianthemum maid maiden maidenhair maidenhead maidenhood maidenliness maidhood maidism maidservant maidu maiduguri maiger maigre maikoa mail mailbag mailboat mailbox maildrop mailer mailing mailing-card maillol maillot mailman mailsorter maimed maimer maimonides main main-topmast main-topsail maine mainer mainframe mainland mainmast mainsail mainsheet mainspring mainstay mainstream maintainer maintenance maintenon maiolica maisonette maisonnette maitland maitreya maize maja majagua majesty majidae majolica major major-domo major-general majorana majorca majorette majority majors majuscule mak makaira makalu makataimeshekiakiak make make-believe make-do make-peace make-up make-work makedonija makeover maker makeready makeshift makeup makeweight makin making mako makomako malabo malabsorption malacanthidae malacca malachi malachias malachite malacia malaclemys malacologist malacology malaconotinae malacopterygian malacopterygii malacosoma malacostraca malacothamnus maladjustment maladroitness malady malaga malahini malaise malamud malamute malanga malaprop malapropism malar malaria malarkey malarky malathion malawi malawian malaxis malaxis-unifolia malay malaya malayalam malayan malayo- polynesian malaysia malaysian malcolmia malcontent maldivan maldives maldivian maldon male maleate maleberry malebranche malecite malediction malefactor maleficence malemute maleness maleo maleseet malevich malevolence malevolency malfeasance malfeasant malformation malfunction mali malian malice maliciousness malignance malignancy maligner malignity malignment malik malingerer malingering malinois malinowski mall mallard mallarme malleability mallee mallet malleus mallon mallophaga mallotus mallow malmo malmsey malnourishment malnutrition malocclusion malodor malodorousness malodour malone malonylurea malope malopterurus malory malosma malpighi malpighia malpighiaceae malposition malpractice malraux mals malt malta malted maltese maltha malthus malthusian malthusianism malti maltman malto maltose maltreater maltreatment maltster malus malva malvaceae malvales malvasia malvastrum malvaviscus malversation mam mama mamba mambo mamet mamey mamilla mamma mammal mammalia mammalian mammalogist mammalogy mammea mammee mammilla mammillaria mammogram mammography mammon mammoth mammothermography mammut mammuthus mammutidae mammy mamo mamoncillo man man-about-town man-at-arms man-child man-eater man-of-the-earth man-of-war man- on-a-horse manacle manageability manageableness management manager manageress managership managua manakin manama manana manannan manat manatee manawydan manawyddan manchester manchu manchuria mancunian manda mandaean mandaeanism mandala mandalay mandamus mandara mandarin mandatary mandate mandator mandatory mande mandean mandeanism mandela mandelamine mandelbrot mandelshtam mandelstam mandevilla mandible mandibula mandioc mandioca mandola mandolin mandragora mandrake mandrel mandril mandrill mandrillus manduca manduction mane manes manet maneuver maneuverability maneuverer manfulness mangabey manganate manganese manganite mange mangel-wurzel manger mangifera manginess mangle mangler manglietia mango mangold mangold-wurzel mangonel mangosteen mangrove manhattan manhole manhood manhunt mania maniac manic-depressive manichaean manichaeanism manichaeism manichean manichee manicotti manicure manicurist manidae manifest manifestation manifesto manifold manihot manikin manila manilkara manilla manioc manioca manipulability manipulation manipulator manipur maniraptor maniraptora manis manitoba mankato mankind manliness mann manna mannequin manner mannerism manners mannheim mannikin mannitol manoeuvrability manoeuvre manoeuvrer manometer manor manpad manpower manroot mansard mansart manse manservant mansfield mansi mansion manslaughter manslayer manson manta mantegna manteidae mantel mantelet mantell mantelpiece manteodea mantichora manticora manticore mantid mantidae mantiger mantilla mantinea mantineia mantis mantispid mantispidae mantissa mantle mantlepiece mantlet mantophasmatodea mantra mantrap mantua manual manubrium manufactory manufacture manufacturer manufacturing manul manumission manumitter manure manus manuscript manx manzanilla manzanita manzoni mao maoi maoism maoist maori map map-reader mapinguari maple maple-leaf mapmaking mapper mapping mapquest maputo maquiladora maquis maquisard mar mara marabou marabout maraca maracaibo maracay maraco marang maranta marantaceae marasca maraschino marasmius marasmus marat maratha marathi marathon marathoner marattia marattiaceae marattiales maraud marauder maravilla marble marble-wood marbleisation marbleising marbleization marbleizing marbles marblewood marbling marc marceau marcel march marchantia marchantiaceae marchantiales marche marcher marches marching marchioness marchland marchpane marciano marcionism marconi marcuse marduk mare marengo margarin margarine margarita margasivsa margate margay marge margin marginalia marginalisation marginality marginalization marginocephalia marginocephalian margosa margrave marguerite mari maria mariachi marianas maricopa mariehamn marigold marihuana marijuana marimba marina marinade marinara marine marineland mariner marines marini marino marionette mariposa mariposan mariticide maritimes marjoram mark markaz-ud-dawa-wal-irshad marker market marketer marketing marketplace markhoor markhor marking markka markoff markov markova marks marksman marksmanship markup markweed marl marlberry marley marlin marline marlinespike marlingspike marlinspike marlite marlowe marlstone marmalade marmara marmite marmora marmoset marmot marmota maroc marocain maroon marplan marquand marque marquee marquess marqueterie marquetry marquette marquis marquise marrakech marrakesh marrano marri marriage marriageability married marrow marrowbone marrubium marruecos mars marsala marseillaise marseille marseilles marsh marshal marshall marshals marshalship marshland marshmallow marsilea marsileaceae marstan marsupial marsupialia marsupium mart martagon marten martensite martes marti martial martian martin martinet martingale martini martinique martinmas martynia martyniaceae martyr martyrdom marum marumi marupa marut marvel marvel-of-peru marvell marveller marx marxism marxism- leninism marxist mary maryland marylander marzipan masa masai mascara mascarpone mascot masculine masculinisation masculinity masculinization masdevallia masefield maser maseru mash masher mashhad mashi mashie mashriq masjid mask masker masking masochism masochist mason masonite masonry masora masorah masorete masorite masoud masqat masque masquer masquerade masquerader mass massachuset massachusetts massacre massage massager massasauga massasoit massawa masse massenet masses masseter masseur masseuse massicot massicotite massif massine massiveness massorete mast mastaba mastabah mastalgia mastectomy master master-at-arms mastering mastermind masterpiece masters mastership masterstroke masterwort mastery masthead mastic mastication masticophis mastiff mastigomycota mastigomycotina mastigophora mastigophoran mastigophore mastigoproctus mastitis mastocyte mastodon mastodont mastoid mastoidal mastoidale mastoidectomy mastoiditis mastopathy mastopexy mastotermes mastotermitidae masturbation masturbator mat matabele matador matai matakam matamoros match match-up matchboard matchbook matchbox matchbush matcher matchet matchlock matchmaker matchmaking matchstick matchup matchweed matchwood mate matelote mater materfamilias material materialisation materialism materialist materiality materialization materiel maternalism maternity mates math mathematician mathematics mathias maths matinee mating matins matisse matman matoaka matriarch matriarchate matriarchy matric matricaria matricide matriculate matriculation matrikin matrilineage matrimony matrisib matrix matron matronymic matsyendra matt matte matter matterhorn matteuccia matthew matthiola matting mattock mattole mattress maturation maturement matureness maturity matzah matzo matzoh maugham maui maul mauldin mauler maulers maulstick maund maundy maupassant mauriac mauritania mauritanian mauritanie mauritian mauritius maurois mauser mausoleum mauve maven maverick mavik mavin mavis maw mawkishness mawlamyine max maxi maxilla maxillaria maxillary maxim maximation maximian maximisation maximization maximum maxostoma maxwell maxzide may maya mayaca mayacaceae mayakovski mayan mayapple mayas mayday mayeng mayenne mayer mayetiola mayfish mayflower mayfly mayhaw mayhem mayidism mayo mayonnaise mayor mayoralty mayoress maypole maypop mays mayweed mazama mazar-i-sharif mazatlan mazdaism maze mazer mazopathy mazurka mazzard mazzini mb mba mbabane mbd mbeya mbit mbundu mc mcalester mcallen mccarthy mccarthyism mccartney mccauley mccormick mccullers mcg mcgraw mcguffey mcguffin mcia mcintosh mckim mckinley mcluhan mcmaster mcpherson md mdi mdiv mdma me mead meade meadow meadowgrass meadowlark meagerness meagreness meal mealberry mealie mealtime mealworm mealybug mean meander meanie meaning meaningfulness meaninglessness meanness means meantime meanwhile meany mearstone measles measurability measure measurement measurer measuring meat meatball meatloaf meatman meatpacking meatus mebaral mebendazole mebibit mebibyte mecca meccano mechanic mechanics mechanisation mechanism mechanist mechanization mecholyl meclizine meclofenamate meclomen meconium meconopsis mecoptera mecopteran med medal medalist medallion medallist medan medawar meddler meddlesomeness meddling medea medellin medevac medfly medford mediacy median mediant mediastinum mediateness mediation mediator mediatrix medic medicago medicaid medical medicament medicare medication medici medicine medick medico mediety medina medinilla mediocrity meditation meditativeness mediterranean medium medivac medlar medlars medley medline medoc medroxyprogesterone medulla medusa medusan medusoid meed meekness meerestone meerkat meerschaum meet meeter meeting meetinghouse mefloquine mefoxin meg megabat megabit megabucks megabyte megacardia megacephaly megachile megachilidae megachiroptera megacolon megacycle megadeath megaderma megadermatidae megaera megaflop megagametophyte megahertz megahit megakaryocyte megalith megalobatrachus megaloblast megalocardia megalocephaly megalocyte megalohepatia megalomania megalomaniac megalonychidae megalopolis megaloptera megalosaur megalosauridae megalosaurus megaphone megapode megapodiidae megapodius megaptera megasporangium megaspore megasporophyll megathere megatherian megatheriid megatheriidae megatherium megaton megawatt megestrol megillah megilp megohm megrim megrims mei meiosis meir meissner meitner meitnerium mek mekong melaena melagra melamine melampodium melampsora melampsoraceae melancholia melancholiac melancholic melancholy melanchthon melanerpes melanesia melange melanin melanism melanitta melanoblast melanocyte melanoderma melanogrammus melanoma melanoplus melanosis melanotis melanthiaceae melasma melastoma melastomaceae melastomataceae melatonin melba melbourne melchior melchite meld meleagrididae meleagris melee melena meles melia meliaceae melicocca melicoccus melicytus melilot melilotus melinae melioration meliorism meliorist meliphagidae melissa melkite mellaril mellivora mellon mellowing mellowness melocactus melodiousness melodrama melody melogale meloid meloidae melolontha melolonthidae melon melophagus melopsittacus melosa melospiza melphalan melpomene melt meltdown melter melting meltwater melursus melville mem member membership membracidae membrane membranophone meme memel memento memo memoir memorabilia memorability memoranda memorandum memorial memorialisation memorialization memorisation memoriser memorization memorizer memory memphis memsahib men men's menace menadione menage menagerie menander menarche mencken mend mendacity mendel mendeleev mendelevium mendeleyev mendelian mendelianism mendelism mendelsohn mendelssohn mender mendicancy mendicant mendicity mending menelaus menhaden menhir menial meniere meninges meningioma meningism meningitis meningocele meningoencephalitis meninx menippe meniscectomy meniscium meniscus menispermaceae menispermum menninger mennonite mennonitism menominee menomini menopause menopon menorah menorrhagia menorrhea menotti menotyphla mensa mensch menses mensh menshevik menstruation menstruum mensuration mentalism mentality mentation mentha menthol menticirrhus mention mentioner mentor mentum mentzelia menu menuhin menura menurae menuridae menyanthaceae menyanthes menziesia meow mepacrine meperidine mephaquine mephenytoin mephistopheles mephitinae mephitis mephobarbital meprin meprobamate meq meralgia merbromine mercantilism mercaptopurine mercator mercedario mercenaria mercenary mercer merchandise merchandiser merchandising merchant merchant-venturer merchantability merchantman mercifulness mercilessness merckx mercouri mercurialis mercurochrome mercury mercy mere meredith merestone meretriciousness merganser mergenthaler merger merginae merging mergus mericarp merida meridian meringue merino meriones meristem merit meritocracy meritoriousness merl merlangus merle merlin merlon merlot merluccius mermaid merman merodach meromelia meronym meronymy meropidae merops merostomata merovingian merozoite merrimac merrimack merriment merriness merry-go-round merrymaker merrymaking mertensia merthiolate merton meryta mesa mesalliance mesantoin mesasamkranti mescal mescaline mesembryanthemum mesencephalon mesenchyme mesentery mesh meshed meshing meshugaas meshuggeneh meshuggener meshwork mesmer mesmerism mesmerist mesmerizer mesoamerica mesoamerican mesoblast mesocarp mesocolon mesocricetus mesoderm mesohippus mesolithic mesomorph mesomorphy meson mesophyron mesophyte mesopotamia mesosphere mesothelioma mesothelium mesotron mesozoic mespilus mesquit mesquite mess mess-up message messaging messenger messiah messiahship messidor messina messiness messmate messuage mestiza mestizo mestranol mesua metabola metabolism metabolite metacarpal metacarpus metacenter metacentre metacyesis metadata metagenesis metaknowledge metal metalanguage metalepsis metalhead metallic metallurgist metallurgy metalware metalwork metalworker metalworking metalworks metamathematics metamere metamorphism metamorphopsia metamorphosis metaphase metaphor metaphysics metaphysis metaproterenol metarule metasequoia metastability metastasis metatarsal metatarsus metatheria metatherian metathesis metazoa metazoan metchnikoff metchnikov mete metempsychosis metencephalon meteor meteorite meteoroid meteorologist meteorology meteortropism meter meterstick metformin meth methacholine methadon methadone methamphetamine methanal methane methanogen methanol methapyrilene methaqualone metharbital methedrine metheglin methenamine methicillin methionine methocarbamol method methodicalness methodism methodist methodists methodology methotrexate methuselah methyl methylbenzene methyldopa methylene methylenedioxymethamphetamine methylphenidate methyltestosterone metic metical meticorten meticulosity meticulousness metier metis metonym metonymy metopion metoprolol metralgia metrazol metre metrestick metric metrication metrics metrification metritis metro metrology metronidazole metronome metronymic metropolis metropolitan metroptosis metrorrhagia metroxylon metternich mettle mettlesomeness metycaine meuse meuse-argonne mevacor mew mews mexicali mexican mexican-american mexicano mexico mexiletine mexitil meyerbeer meyerhof mezcal mezereon mezereum mezuza mezuzah mezzanine mezzo mezzo-relievo mezzo-rilievo mezzo-soprano mezzotint mf mfa mflop mg mho mhz mi miami miao miaou miaow miasm miasma <NAME> michaelmas michaelmastide <NAME> <NAME> michigan michigander <NAME> micmac miconazole micro-organism microbalance microbar microbat microbe microbiologist microbiology microbrachia microbrewery microcentrum microcephalus microcephaly microchip microchiroptera microcircuit micrococcaceae micrococcus microcode microcomputer microcosm microcyte microcytosis microdesmidae microdipodops microdot microeconomics microeconomist microelectronics microevolution microfarad microfiche microfilm microflora microfossil microgametophyte microgauss microglia microgliacyte microgram microgramma microgramma-piloselloides microhylidae micromeria micrometeor micrometeorite micrometeoroid micrometer micrometry micromicron micromillimeter micromillimetre micromyx micron micronase micronesia micronor micronutrient microorganism micropaleontology micropenis microphage microphallus microphone microphoning microphotometer micropogonias microprocessor micropterus micropyle microradian microscope microscopist microscopium microscopy microsecond microseism microsome microsorium microsporangium microspore microsporidian microsporophyll microsporum microstomus microstrobos microsurgery microtaggant microtome microtubule microtus microvolt microwave microzide micruroides micrurus micturition mid-april mid-august mid-calf mid-december mid-eighties mid-february mid-fifties mid-forties mid-january mid-july mid-june mid-march mid-may mid-nineties mid-november mid-october mid-off mid-on mid-september mid- seventies mid-sixties mid-thirties mid-twenties mid-water midafternoon midair midas midazolam midbrain midday midden middle middlebreaker middlebrow middleman middleton middleweight middling middy mideast midfield midgard midge midget midgrass midi midi-pyrenees midinette midiron midland midline midnight midplane midpoint midrash midrib midriff midsection midshipman midst midstream midsummer midsummer-men midterm midvein midwatch midway midweek midwest midwife midwifery midwinter mien mierkat mifepristone miff might might-have-been mightiness mignonette migraine migrant migration migrator mihrab mikado mikania mike mikir- meithei mikmaq mikvah mil milady milage milan milanese milano milcher mildew mildness mile mileage mileometer milepost miler milestone milfoil milhaud miliaria milieu militainment militance militancy militant militarisation militarism militarist militarization military militia militiaman milium milk milk-vetch milkcap milker milkmaid milkman milkshake milksop milkwagon milkweed milkwort mill mill-girl mill-hand millais millay millboard milldam millenarian millenarianism millenarism millenarist millenary millennium millenniumism millepede miller miller's-thumb millerite millet millettia milliammeter milliampere milliard millibar millicurie millidegree milliequivalent millifarad milligram millihenry millikan milliliter millilitre millime millimeter millimetre millimicron milline milliner millinery milling million millionaire millionairess millionth milliped millipede milliradian millisecond millivolt millivoltmeter milliwatt millpond millrace millrun mills millstone millwheel millwork millwright milne milo milometer milontin milord milquetoast milt miltiades miltomate milton miltonia miltown milvus milwaukee mimamsa mime mimeo mimeograph mimer mimesis mimic mimicker mimicry mimidae mimir mimosa mimosaceae mimosoideae mimus min mina minah minaret mince mincemeat mincer mind mind-set mindanao minden minder mindfulness mindlessness mindoro mindset mine minefield minelayer minelaying miner mineral mineralocorticoid mineralogist mineralogy minerva mineshaft minestrone minesweeper minesweeping mineworker ming minge minginess mingle-mangle mingling mini miniature miniaturisation miniaturist miniaturization minibar minibike minibus minicab minicar minicomputer miniconju minim minimalism minimalist minimisation minimization minimum minimus mining minion minipress miniskirt minister ministrant ministration ministry minisub minisubmarine minium minivan miniver mink minkowski minneapolis minnesota minnesotan minnewit minniebush minnow minoan minocin minocycline minor minority minors minos minotaur minoxidil minsk minster minstrel minstrelsy mint mintage minter mintmark minuartia minuend minuet minuit minus minuscule minute minuteman minuteness minutes minutia minx minyan miocene miosis miotic mips mirabeau mirabilis miracle miracle-worship mirage mirasol mire miri mirid miridae mirish miro mirounga mirror mirth mirthfulness misadventure misalignment misalliance misanthrope misanthropist misanthropy misapplication misapprehension misappropriation misbehavior misbehaviour misbeliever miscalculation miscarriage miscegenation miscellanea miscellany mischance mischief mischief-maker mischief- making mischievousness misconception misconduct misconstrual misconstruction miscount miscreant miscreation miscue misdating misdeal misdeed misdemeanor misdemeanour misdirection miser miserableness miserliness misery misestimation misfeasance misfire misfit misfortune misgiving misgovernment mishap mishegaas mishegoss mishmash mishna mishnah mishpachah mishpocha misinformation misinterpretation misleader mismanagement mismatch misnomer miso misocainea misogamist misogamy misogynism misogynist misogyny misology misoneism misopedia mispickel misplacement misplay misprint mispronunciation misquotation misquote misreading misreckoning misrepresentation misrule miss missal misshapenness missile mission missionary missioner missis mississippi mississippian missive missoula missouri missourian misspelling misstatement misstep missus missy mist mist-flower mistake mistaking mister mistflower mistiming mistiness mistletoe mistral mistranslation mistreatment mistress mistrial mistrust misunderstanding misuse mit mitchell mitchella mitchum mite mitella miter miterwort mitford mithan mithra mithracin mithraicism mithraism mithraist mithramycin mithras mithridates mitigation mitochondrion mitogen mitomycin mitosis mitra mitre mitrewort mitsvah mitt mittelschmerz mitten mitterrand mitzvah miwok mix mix-up mixed-blood mixer mixing mixologist mixology mixture mizen mizenmast mizzen mizzenmast mizzle mko ml mlitt mls mm mmpi mn mnemonic mnemonics mnemonist mnemosyne mniaceae mnium mo moa moan moaner moat mob moban mobcap mobile mobilisation mobility mobilization mobius mobocracy mobster mobula mobulidae mocambique mocassin moccasin mocha mock mock-heroic mock-up mocker mockernut mockery mockingbird mod modal modality mode model modeler modeling modeller modelling modem moderate moderateness moderation moderationism moderationist moderatism moderator moderatorship modern modernisation modernism modernist modernity modernization modernness modestness modesty modicon modicum modification modifier modigliani modillion modiolus modishness modiste mods modulation module modulus moehringia mogadiscio mogadishu moghul mogul mohair mohammad mohammed mohammedan mohammedanism moharram mohave mohawk mohican moho mohorovicic mohria moiety moirae moirai moire moistener moistening moistness moisture mojarra mojave mojo moke moksa mokulu mol mola molality molar molarity molasses mold moldavia moldboard moldiness molding moldova mole molech molecule molehill moleskin molestation molester molidae moliere molindone moline molise moll mollah molle mollie mollienesia mollification molluga mollusc mollusca molluscum mollusk molly mollycoddle mollycoddler mollymawk molnar moloch molokai molossidae molothrus molotov molt molter molting moluccas molucella molva molybdenite molybdenum mom mombasa mombin moment momentousness momentum momism momma mommsen mommy momordica momos momot momotidae momotus momus mon mon-khmer mona monacan monaco monaco-ville monad monal monandry monarch monarchism monarchist monarchy monarda monardella monario monas monastery monastic monasticism monaul monazite monday mondrian monegasque monera moneran moneron moneses monet monetarism monetarist monetisation monetization money money- spinner moneybag moneyer moneygrubber moneylender moneymaker moneymaking moneyman moneywort monger mongo mongol mongolia mongolian mongolianism mongolic mongolism mongoloid mongoose mongrel moniker monilia moniliaceae moniliales moniliasis monism monistat monition monitor monitoring monitrice monk monkey monkey-wrench monkeypod monkfish monkshood monnet mono mono-iodotyrosine monoamine monoblast monocanthidae monocanthus monocarp monochamus monochromacy monochromasy monochromat monochromatism monochrome monochromia monocle monocline monoclonal monocot monocotyledon monocotyledonae monocotyledones monocracy monoculture monocycle monocyte monocytosis monod monodon monodontidae monody monogamist monogamousness monogamy monogenesis monogram monograph monogynist monogyny monohybrid monohydrate monolatry monolingual monolith monologist monologue monomania monomaniac monomer monomorium mononeuropathy monongahela mononucleosis monophony monophthalmos monophysite monophysitism monoplane monoplegia monopolisation monopoliser monopolist monopolization monopolizer monopoly monopsony monorail monorchidism monorchism monosaccharide monosaccharose monosemy monosomy monosyllable monotheism monotheist monothelitism monotone monotony monotremata monotreme monotropa monotropaceae monotype monoxide monroe monrovia mons monsieur monsignor monsoon monster monstera monstrance monstrosity montage montagu montaigne montana montanan monte montenegro monterey monterrey montespan montesquieu montessori monteverdi montevideo montez montezuma montfort montgolfier montgomery month monthly montia montmartre montpelier montrachet montreal montserrat montserratian monument moo moo-cow mooch moocher mood moodiness moody moolah moon moon-curser moon-ray moon-worship moonbeam mooneye moonfish moonflower moonie moonlight moonlighter moonseed moonshell moonshine moonshiner moonstone moonwalk moonwort moor moor- bird moorage moorbird moorcock moore moorfowl moorgame moorhen mooring moorish moorland moorwort moose moose-wood moosewood moot mop mopboard mope moped mopes mopper moppet mopping moquelumnan moquette moraceae moraine moral morale moralisation moralism moralist morality moralization moralizing morals morass moratorium moravia moray morbidity morbidness morbilli morceau morchella morchellaceae mordacity mordant mordva mordvin mordvinian more moreen morel morello mores morgan morganite morgantown morgen morgue morion morley mormon mormonism mormons morn morning moro moroccan morocco moron morone moronity moroseness morosoph morphallaxis morphea morpheme morpheus morphia morphine morphogenesis morphology morphophoneme morphophonemics morphophysiology morrigan morrigu morris morrison morristown morrow mors morse morsel mortal mortality mortar mortarboard mortgage mortgagee mortgager mortgagor mortice mortician mortification mortimer mortise mortmain morton mortuary morula morus mosaic mosaicism mosan mosander moschus moscow moselle moses moshav moslem mosque mosquito mosquitofish moss moss-trooper mossad mossback mossbauer mostaccioli mosul mot motacilla motacillidae mote motel motet moth mothball mother mother- in-law mother-of-pearl mother-of-thousands motherese motherfucker motherhood motherland motherliness motherwell motherwort motif motile motilin motility motion motionlessness motivating motivation motivator motive motivity motley motmot motoneuron motor motorbike motorboat motorbus motorcade motorcar motorcoach motorcycle motorcycling motorcyclist motoring motorisation motorist motorization motorman motormouth motortruck motorway motown motrin mott mottle mottling motto moue moufflon mouflon moujik moukden mould mouldboard moulding moulmein moult moulter moulting mound mound-bird mount mountain mountaineer mountaineering mountainside mountebank mounter mountie mounties mounting mourner mournfulness mourning mouse mousepad mouser mousetrap moussaka mousse moussorgsky moustache moustachio mouth mouthbreeder mouthful mouthpart mouthpiece mouthwash mouton movability movable movableness move movement mover movie moviegoer moviemaking mow mower moxie moynihan mozambican mozambique mozart mozzarella mp mpeg mph mps mr mr. mrd mri mrna mrs mrs. mrta ms ms-dos ms. msasa msb msc msec msg msh mst mt mu mu-meson muadhdhin muazzin mubarak much muchness mucilage mucin muck muckheap muckhill muckle muckraker muckraking mucoid mucopolysaccharide mucopolysaccharidosis mucor mucoraceae mucorales mucosa mucoviscidosis mucuna mucus mud mudcat mudder muddiness muddle mudguard mudhif mudra mudskipper mudslide mudslinger mudspringer muenchen muenster muesli muezzin muff muffin muffle muffler mufti mug mugful muggee mugger mugginess mugging muggins mugil mugilidae mugiloidea mugshot mugwort mugwump muhammad muhammadan muhammadanism muhammedan muharram muharrum muhlenbergia muir muishond mujahadeen mujahadein mujahadin mujahedeen mujahedin mujahid mujahideen mujahidin mujik mujtihad mukalla mukataa mukden mulatto mulberry mulch mulct mule muleteer muliebrity mulishness mull mulla mullah mullein muller mullet mullidae mulligan mulligatawny mullion mulloidichthys mulloway mullus multi- billionaire multicollinearity multiculturalism multifariousness multiflora multimedia multinomial multiple multiplex multiplexer multiplicand multiplication multiplicity multiplier multiprocessing multiprocessor multiprogramming multistage multitude multitudinousness multivalence multivalency multiversity multivitamin mulwi mum mumbai mumble mumble-the-peg mumbler mumblety-peg mumbling mummer mummery mummichog mummification mummy mumps mumpsimus munch munchausen munchener muncher munchhausen muncie munda munda-mon- khmer mundaneness mundanity mung munich municipality munificence muniments munition munj munja munjeet munjuk munro muntiacus muntingia muntjac muon muraenidae mural muralist muramidase murder murderee murderer murderess murderousness murdoch muridae murillo murine muritaniya murk murkiness murmansk murmur murmuration murmurer murmuring muroidea murphy murrain murray murre murrow murrumbidgee mus musa musaceae musales musca muscadel muscadelle muscadet muscadine muscardinus muscari muscat muscatel musci muscicapa muscicapidae muscidae muscivora muscivora-forficata muscle muscle-builder musclebuilder musclebuilding muscleman muscoidea muscovite muscovy muscularity musculature musculus musd muse muser musette museum musgoi musgu mush musher mushiness mushroom musial music musical musicality musicalness musician musicianship musicologist musicology musing musjid musk muskat muskellunge musket musketeer musketry muskhogean muskiness muskmelon muskogean muskogee muskrat muskwood muslim muslimah muslimism muslin musnud musophaga musophagidae musophobia musquash muss mussel musset mussiness mussitation mussolini mussorgsky must mustache mustachio mustagh mustang mustard mustela mustelid mustelidae musteline mustelus muster musth mustiness mutability mutableness mutagen mutagenesis mutamycin mutant mutation mutawa mutawa'een mutchkin mute muteness mutilation mutilator mutillidae mutineer mutinus mutiny mutisia mutism muton mutsuhito mutt mutter mutterer muttering mutton muttonfish muttonhead mutualism mutuality mutualness muumuu muybridge muzhik muzjik muztag muztagh muzzle muzzler mv mvp mwanza mwera mx mya myaceae myacidae myadestes myalgia myanmar myasthenia mycelium mycenae mycenaen mycetophilidae mycobacteria mycobacteriaceae mycobacterium mycologist mycology mycomycin mycophage mycophagist mycophagy mycoplasma mycoplasmataceae mycoplasmatales mycosis mycostatin mycotoxin mycrosporidia mycteria mycteroperca myctophidae mydriasis mydriatic myelatelia myelencephalon myelin myeline myelinisation myelinization myelitis myeloblast myelocyte myelofibrosis myelogram myelography myeloma myelomeningocele myg myiasis mylanta mylar myliobatidae mylitta mylodon mylodontid mylodontidae mym myna mynah myocardiopathy myocarditis myocardium myocastor myoclonus myodynia myofibril myofibrilla myoglobin myoglobinuria myogram myology myoma myometritis myometrium myomorpha myonecrosis myopathy myope myopia myopus myosarcoma myosin myosis myositis myosotis myotic myotis myotomy myotonia myrcia myrciaria myrdal myriad myriagram myriameter myriametre myriapod myriapoda myrica myricaceae myricales myricaria myringa myringectomy myringoplasty myringotomy myriophyllum myristica myristicaceae myrmecia myrmecobius myrmecophaga myrmecophagidae myrmecophile myrmecophyte myrmeleon myrmeleontidae myrmidon myrobalan myroxylon myrrh myrrhis myrsinaceae myrsine myrtaceae myrtales myrtillocactus myrtle myrtus mysidacea mysidae mysis mysoline mysophilia mysophobia mysore mystery mystic mysticeti mysticism mystification mystifier mystique myth mythologisation mythologist mythologization mythology mytilene mytilid mytilidae mytilus myxedema myxine myxinidae myxiniformes myxinikela myxinoidea myxinoidei myxobacter myxobacterales myxobacteria myxobacteriaceae myxobacteriales myxobacterium myxocephalus myxoedema myxoma myxomatosis myxomycete myxomycetes myxomycota myxophyceae myxosporidia myxosporidian myxovirus n n'djamena n.b. na na-dene naan nabalus nablus nabob nabokov naboom nabu nabumetone nac nacelle nacho nacimiento nacre nad nada nadir nadolol nadp naemorhedus nafcil nafcillin nafta nafud nag naga nagami nagano nagari nagasaki nageia nagger nagi nagoya nahuatl nahum naiad naiadaceae naiadales naias naif naiki nail nailbrush nailer nailfile nailhead nailrod nainsook naira nairobi naismith naiveness naivete naivety naja najadaceae najas najd nakedness nakedwood nakuru nalchik nalfon nalline nalorphine naloxone naltrexone namby-pamby name name-dropping nameko namelessness nameplate namer names namesake namibia namibian naming nammad nammu namoi nampa namtar namtaru namur nan nan-chang nan-ning nanaimo nanak nance nancere nanchang nancy nandrolone nandu nanism nanjing nankeen nanking nanna nanning nanny nanny-goat nanocephaly nanogram nanometer nanometre nanomia nanophthalmos nanosecond nanotechnology nanotube nanovolt nansen nantes nanticoke nantua nantucket nanus naomi nap napa napaea napalm nape napery naphazoline naphtha naphthalene naphthol naphthoquinone napier napkin naples napoleon napoli nappy naprapath naprapathy naprosyn naproxen napu naqua nara naranjilla narc narcan narcism narcissism narcissist narcissus narcist narco- state narcolepsy narcoleptic narcosis narcoterrorism narcotic narcotraffic nard nardil nardo nardoo narghile nargileh naris nark narration narrative narrator narrow narrow-body narrow-mindedness narrowboat narrowing narrowness narthecium narthex narwal narwhal narwhale nasa nasal nasalis nasalisation nasality nasalization nascence nascency nasdaq naseby nash nashville nasion nasopharynx nassau nasser nast nastiness nasturtium nasua natal natality natantia natation natator natatorium natchez nates naticidae nation national nationalisation nationalism nationalist nationality nationalization nationhood native nativeness nativism nativist nativity nato natriuresis natrix natrolite natta natterjack nattiness natural naturalisation naturalism naturalist naturalization naturalness nature naturism naturist naturopath naturopathy nauch nauclea naucrates naught naughtiness naumachia naumachy naupathia nauru nauruan nausea nauseant nauseatingness nautch nautilidae nautilus navaho navajo navane navarino nave navel navel-gazing navicular navigability navigation navigator navratilova navvy navy nawab nawcwpns nay naysayer naysaying nazarene nazareth naze nazi nazification naziism nazimova nazism nb nbe nbw nc ncdc nd ndebele ndjamena ne ne'er-do-well neandertal neanderthal neap neapolitan nearness nearside nearsightedness neatness neb nebbech nebbish nebcin nebe nebiim nebn nebo nebraska nebraskan nebuchadnezzar nebuchadrezzar nebula nebule nebuliser nebulizer nec necessary necessitarian necessity neck neckar neckband neckcloth necker neckerchief necking necklace necklet neckline neckpiece necktie neckwear necrobiosis necrology necrolysis necromancer necromancy necromania necrophagia necrophagy necrophilia necrophilism necropolis necropsy necrosis nectar nectarine nectary necturus nederland need needer neediness needle needle-bush needle-wood needlebush needlecraft needlefish needlepoint needlewoman needlewood needlework needleworker needy neel neem neencephalon nefariousness nefazodone nefertiti nefud negaprion negation negative negativeness negativism negativist negativity negatron negev neggram neglect neglecter neglectfulness neglige negligee negligence negotiant negotiation negotiator negotiatress negotiatrix negress negritude negro negroid negus nehemiah nehru neigh neighbor neighborhood neighborliness neighbour neighbourhood neighbourliness nejd nekton nelfinavir nelson nelumbo nelumbonaceae nematocera nematoda nematode nembutal nemea nemertea nemertean nemertina nemertine nemesis nemophila nenets nentsi nentsy neo-darwinism neo-lamarckism neo-latin neobiotic neoceratodus neoclassicism neoclassicist neocolonialism neocon neoconservatism neoconservative neocortex neodymium neoencephalon neoexpressionism neofiber neohygrophorus neolentinus neoliberal neoliberalism neolith neolithic neologism neologist neology neomycin neomys neon neonate neonatology neopallium neophobia neophron neophyte neoplasia neoplasm neoplatonism neoplatonist neopolitan neoprene neoromanticism neosho neosporin neostigmine neoteny neotoma neotony nepa nepal nepalese nepali nepenthaceae nepenthes nepeta nepheline nephelinite nephelite nephelium nephew nephology nephoscope nephralgia nephrectomy nephrite nephritis nephroangiosclerosis nephroblastoma nephrocalcinosis nephrolepis nephrolith nephrolithiasis nephrology nephron nephropathy nephrops nephropsidae nephroptosia nephroptosis nephrosclerosis nephrosis nephrotomy nephrotoxin nephthys nephthytis nepidae nepotism nepotist neptune neptunium nerd nereid nereus nergal nerita neritid neritidae neritina nerium nernst nero nerodia nerthus neruda nerva nerve nervelessness nerveroot nerves nervi nervousness nervure nervus nescience nesokia ness nesselrode nessie nest nester nestle nestling nestor nestorian nestorianism nestorius net netball netherlander netherlands netherworld netkeeper netminder netscape netting nettle network neumann neuralgia neuralgy neurasthenia neurasthenic neurectomy neurilemma neurilemoma neurinoma neuritis neuroanatomy neurobiologist neurobiology neuroblast neuroblastoma neurochemical neurodermatitis neuroepithelioma neuroepithelium neuroethics neurofibroma neurofibromatosis neurogenesis neuroglia neurogliacyte neurohormone neurohypophysis neurolemma neuroleptic neurolinguist neurolinguistics neurologist neurology neurolysin neuroma neuron neurontin neuropathy neurophysiology neuropil neuropile neuroplasty neuropsychiatry neuropsychology neuroptera neuropteran neuropteron neurosarcoma neuroscience neuroscientist neurosis neurospora neurosurgeon neurosurgery neurosyphilis neurotic neuroticism neurotoxin neurotransmitter neurotrichus neurotropism neuter neutering neutral neutralisation neutralism neutralist neutrality neutralization neutrino neutron neutropenia neutrophil neutrophile neva nevada nevadan neve nevelson never-never nevirapine nevis nevus newari newark newbie newborn newburgh newcastle newcastle-upon-tyne newcomb newcomer newel newfoundland newgate newlywed newman newmarket newness newport news newsagent newsboy newsbreak newscast newscaster newsdealer newsflash newsletter newsman newsmonger newspaper newspapering newspaperman newspaperwoman newspeak newsperson newsprint newsreader newsreel newsroom newssheet newsstand newsvendor newswoman newsworthiness newswriter newt newton newtonian nexus ney ng nga nganasan ngb ngf ngo ngu ngultrum nguni ngwee nh ni ni-hard ni-resist niacin niagara niamey nib nibble nibbler nibelung nibelungenlied niblick nicad nicaea nicandra nicaragua nicaraguan nice niceness nicety niche nicholas nichrome nick nickel nickelodeon nicker nicklaus nicknack nickname nicolson nicosia nicotiana nicotine nictation nictitation nicu nidaros nidation niddm nidularia nidulariaceae nidulariales nidus niebuhr niece nielsen nierembergia nietzsche nifedipine niff nigella niger niger-congo niger-kordofanian nigeria nigerian nigerien nigga niggard niggardliness niggardness nigger niggler night night- light night-line night-robe night-sight night-stop nightbird nightcap nightclothes nightclub nightcrawler nightdress nightfall nightgown nighthawk nightie nightingale nightjar nightlife nightmare nightrider nightshade nightshirt nightspot nightstick nighttime nightwalker nightwear nightwork nigra nigroporus nih nihau nihil nihilism nihilist nihility nihon nij nijinsky nijmegen nike nil nile nilgai nilo-saharan nilotic nilsson nim nimbleness nimblewill nimbus nimby nimiety nimitz nimravus nimrod nin-sin nina nincompoop nine nine-spot ninepence ninepin ninepins niner nineteen nineteenth nineties ninetieth ninety nineveh ningal ningirsu ningishzida ninhursag ninib ninigi ninigino-mikoto ninja ninjitsu ninjutsu ninkharsag ninkhursag ninny ninon ninth nintoo nintu ninurta niobe niobite niobium niobrara nip nipa nipper nipple nippon nipponese nipr niqaabi niqab nirvana nisan nisei nissan nist nisus nit nitella niter nitpicker nitramine nitrate nitrazepam nitre nitride nitrification nitril nitrile nitrite nitrobacter nitrobacteria nitrobacteriaceae nitrobacterium nitrobenzene nitrocalcite nitrocellulose nitrochloroform nitrochloromethane nitrocotton nitrofuran nitrofurantoin nitrogen nitrogenase nitroglycerin nitroglycerine nitrosobacteria nitrosomonas nitrospan nitrostat nitty-gritty nitweed nitwit nivose nix nixon nj njord njorth nlp nlrb nm nmr nne nnrti nnw no no-account no-brainer no-goal no-hitter no-see-um no-show no-trump no. noaa noah nob nobel nobelist nobelium nobility noble noble-mindedness nobleman nobleness noblesse noblewoman nobody noc noctambulation noctambulism noctambulist noctiluca noctua noctuid noctuidae nocturia nocturne nod noddle node nodule noel noemi noesis noether nog nogales noggin nogging noguchi noise noiselessness noisemaker noisiness noisomeness noli-me-tangere nolina noma nomad nombril nome nomenclature nomenklatura nomia nominal nominalism nominalist nomination nominative nominator nominee nomogram nomograph non-catholic non- discrimination non-engagement non-involvement non-issue non-jew non- proliferation non-resistant non-ugric nonabsorbency nonacceptance nonaccomplishment nonachievement nonachiever nonage nonagenarian nonaggression nonagon nonalignment nonalinement nonallele nonappearance nonattendance nonattender nonbeing nonbeliever noncandidate nonce nonchalance noncitizen noncom noncombatant noncompliance noncompliant nonconductor nonconformance nonconformism nonconformist nonconformity nondescript nondevelopment nondisjunction nondrinker nondriver none nonentity nonequivalence nones nonessential nonesuch nonevent nonexistence nonfeasance nonfiction nonindulgence noninterference nonintervention nonmember nonmetal nonobservance nonoccurrence nonpareil nonparticipant nonparticipation nonpartisan nonpartisanship nonpartizan nonpayment nonperformance nonperson nonprofit nonproliferation nonreader nonremittal nonresident nonresistance nonsense nonsensicality nonsmoker nonstarter nonsteroid nonsteroidal nonstop nonsuch nontricyclic nonuniformity nonviolence nonworker noodle nook nookie nooky noon noonday noontide noose nootka nopal nopalea nor'-east nor'-nor'-east nor'-nor'-west nor'-west nor-q-d noradrenaline nord-pas-de-calais nordic noreaster noreg norepinephrine norethandrolone norethindrone norethynodrel norflex norfolk norge norgestrel noria norinyl norlestrin norlutin norm norma normal normalcy normalisation normaliser normality normalization normalizer norman norman-french normandie normandy normodyne normothermia norn norris norrish norse norseman north northampton northamptonshire northeast northeaster northeastward norther northerly northern northerner northernness northland northman northrop northumberland northumbria northward northwest northwester northwestward nortriptyline noruz norvasc norvir norway norwegian nose nosebag noseband nosebleed nosecount nosedive nosegay nosepiece nosewheel nosey-parker nosh nosh- up nosher nosiness nosology nostalgia nostoc nostocaceae nostradamus nostril nostrum nosy-parker not-for-profit notability notable notary notation notch note notebook notecase notechis notemigonus notepad notepaper nothing nothingness nothings nothofagus nothosaur nothosauria notice noticeability noticeableness noticer notification notion notochord notomys notonecta notonectidae notophthalmus notoriety notornis notoryctidae notoryctus notostraca notropis notturno nouakchott nougat nought noumenon noun nourishment nous nouveau-riche nov nov-esperanto nov-latin nova novation novel novelette novelisation novelist novelization novella novelty november novena novgorod novial novice noviciate novillada novillero novitiate novobiocin novocain novocaine novosibirsk now nowadays nowhere nowness nowrooz nowruz nox noxiousness noyes nozzle np npa npc nra nrc nrem nrl nrna nro nrti nsa nsaid nsc nsf nsu nsw nswc nt ntis nu nuance nub nubbin nubbiness nubble nubia nubian nucellus nucha nucifraga nuclease nucleole nucleolus nucleon nucleonics nucleoplasm nucleoprotein nucleoside nucleosynthesis nucleotide nucleus nuda nude nudeness nudge nudger nudibranch nudibranchia nudism nudist nudity nudnick nudnik nuffield nugget nuisance nuke null nullah nullification nullifier nullipara nullity numbat number numbering numberplate numbers numbfish numbness numdah numen numenius numeracy numeral numeration numerator numerologist numerology numerosity numerousness numida numidia numidian numididae numidinae numismatics numismatist numismatologist numismatology nummulite nummulitidae numskull nun nunavut nuncio nung nunnery nuphar nuprin nuptials nuptse nuremberg nureyev nurnberg nurse nurse-midwife nurseling nursemaid nurser nursery nurseryman nursing nursling nurturance nurture nusku nut nutation nutcase nutcracker nutgrass nuthatch nuthouse nutlet nutmeg nutmeg-yew nutria nutrient nutriment nutrition nutritionist nutritiousness nutritiveness nutsedge nutshell nutter nuwc nuytsia nv nw nwbn nwbw ny nyala nyamuragira nyamwezi nyasaland nybble nyctaginaceae nyctaginia nyctalopia nyctanassa nyctereutes nycticebus nycticorax nyctimene nyctophobia nycturia nydrazid nyiragongo nylghai nylghau nylon nylons nymph nymphaea nymphaeaceae nymphalid nymphalidae nymphalis nymphet nymphicus nympho nympholepsy nympholept nymphomania nymphomaniac nynorsk nypa nyse nyssa nyssaceae nystagmus nystan nystatin nyx o o'brien o'casey o'connor o'flaherty o'hara o'keeffe o'neill o'toole o.e.d. o.k. oaf oahu oak oakland oakley oakum oar oarfish oarlock oarsman oarsmanship oarswoman oas oasis oast oat oatcake oates oath oatmeal oaxaca ob obadiah obbligato obduracy obeah obeche obechi obedience obeisance obelion obelisk oberson obesity obfuscation obi obiism obit obituary object objectification objection objectionableness objective objectiveness objectivity objector objurgation oblate oblateness oblation obligation obligato obliger obligingness oblique obliqueness obliquity obliteration obliterator oblivion obliviousness oblong oblongness obloquy obnoxiousness oboe oboist obolus obscenity obscurantism obscurantist obscureness obscurity obsequiousness observance observation observatory observer obsession obsessive obsessive-compulsive obsessiveness obsessivity obsidian obsolescence obsoleteness obstacle obstetrician obstetrics obstinacy obstinance obstipation obstreperousness obstructer obstruction obstructionism obstructionist obstructor obstruent obtainment obtention obtrusiveness obturator obtuseness obverse obviation obviousness oca ocarina occam occasion occasions occident occidental occidentalism occiput occitan occlusion occlusive occult occultation occultism occultist occupancy occupant occupation occupier occurrence occurrent ocean oceanaut oceanfront oceania oceanic oceanica oceanid oceanites oceanographer oceanography oceanology oceanus ocellus ocelot ocher ochlocracy ochna ochnaceae ochoa ochotona ochotonidae ochre ochroma ochronosis ochs ocimum ockham ocotillo oct octad octagon octahedron octameter octane octans octant octave octavian octavo octet octette octillion october octoberfest octogenarian octonary octopod octopoda octopodidae octopus octoroon octosyllable octroi ocular oculism oculist oculomotor oculus ocyurus od odalisque oddball oddity oddment oddments oddness odds odds-maker ode oder odesa odessa odets odin odiousness odist odium odo odoacer odobenidae odobenus odocoileus odometer odonata odonate odontalgia odontaspididae odontaspis odontiasis odontoceti odontoglossum odontology odontophorus odor odour odovacar odovakar odynophagia odysseus odyssey oecanthus oecumenism oed oedema oedipus oedogoniaceae oedogoniales oedogonium oenanthe oengus oenologist oenology oenomel oenophile oenothera oersted oesophagitis oesophagoscope oesophagus oesterreich oestradiol oestridae oestriol oestrogen oestrone oestrus oeuvre off-broadway off-day off-licence off-roader off-season off-white offal offbeat offenbach offence offender offense offensive offensiveness offer offerer offering offeror offertory office office-bearer officeholder officer official officialdom officialese officiant officiating officiation officiousness offing offprint offset offshoot offside offspring offstage ofo oftenness ogalala ogcocephalidae ogden ogdoad ogee ogive oglala ogler ogre ogress oh ohio ohioan ohm ohmage ohmmeter oig oil oilbird oilcan oilcloth oiler oilfield oilfish oiliness oilman oilpaper oilrig oilseed oilskin oilstone oilstove oink ointment oireachtas ois ojibwa ojibway ok oka okapi okapia okay okeechobee okeh oken okenfuss okey okinawa oklahoma oklahoman okra oktoberfest ola old old-fashionedness old-man-of-the-woods old-timer oldenburg oldfield oldie oldness oldster oldtimer oldwench oldwife olea oleaceae oleaginousness oleales oleander oleandra oleandraceae olearia oleaster olecranon oled olefin olefine olein oleo oleomargarine oleoresin olfaction olfersia olibanum oligarch oligarchy oligocene oligochaeta oligochaete oligoclase oligodactyly oligodendria oligodendrocyte oligodendroglia oligodontia oligomenorrhea oligoplites oligopoly oligoporus oligosaccharide oligospermia oliguria olimbos olive olive-green olivenite oliver olivier olivine olla ollari olm olmec olmsted ology olympia olympiad olympian olympics olympus omaha oman omani omasum omayyad omb ombu ombudsman omdurman omega omega-3 omega-6 omelet omelette omen omentum omeprazole omerta omicron omission omiya ommastrephes ommatidium ommiad omnibus omnipotence omnipresence omnirange omniscience omnium- gatherum omnivore omomyid omophagia omotic omphalocele omphalos omphaloskepsis omphalotus omphalus omsk on-license onager onagraceae onanism onanist once-over onchocerciasis oncidium oncogene oncologist oncology oncoming oncorhynchus oncovin ondaatje ondatra one one-and-one one-billionth one-dimensionality one- eighth one-fifth one-fourth one-half one-hitter one-hundred-millionth one- hundred-thousandth one-hundredth one-liner one-millionth one-ninth one-off one- quadrillionth one-quarter one-quintillionth one-seventh one-sixteenth one-sixth one-sixtieth one-sixty-fourth one-spot one-step one-ten-thousandth one-tenth one-third one-thirty-second one-thousandth one-trillionth one-twelfth one- upmanship onega oneida oneirism oneiromancer oneiromancy oneness onerousness oni onion onionskin oniscidae oniscus onlooker ono onobrychis onoclea onomancer onomancy onomasticon onomastics onomatomania onomatopoeia onondaga ononis onopordon onopordum onosmodium onrush onsager onset onslaught ontario ontogenesis ontogeny ontology onus onychium onychogalea onycholysis onychomys onychophora onychophoran onychosis onyx onyxis oocyte oodles oogenesis oology oolong oomph oomycetes oophorectomy oophoritis oophorosalpingectomy oort oosphere oospore ootid ooze oozing opacification opacity opah opal opalescence opaqueness opcw opec opel open openbill opener openhandedness opening openness openwork opepe opera operagoer operand operation operationalism operations operative operator operculum operetta operon operoseness opheodrys ophidia ophidian ophidiidae ophidism ophiodon ophiodontidae ophioglossaceae ophioglossales ophioglossum ophiolatry ophiophagus ophisaurus ophiuchus ophiurida ophiuroidea ophryon ophrys ophthalmectomy ophthalmia ophthalmitis ophthalmologist ophthalmology ophthalmoplegia ophthalmoscope ophthalmoscopy opiate opiliones opinion opisthobranchia opisthocomidae opisthocomus opisthognathidae opisthorchiasis opisthotonos opium opopanax oporto opossum oppenheimer opponent opportuneness opportunism opportunist opportunity opposer opposite oppositeness opposition oppression oppressiveness oppressor opprobrium ops opsin opsonin opsonisation opsonization optative optez optic optician optics optimisation optimism optimist optimization optimum option optometrist optometry opulence opuntia opuntiales opus opv or orach orache oracle oradexon oral oran orang orange orangeade orangeman orangeness orangery orangewood orangutan orangutang orasone oration orator oratorio oratory orb orb-weaver orbignya orbison orbit orbitale orbiter orca orchard orchestia orchestiidae orchestra orchestration orchestrator orchid orchidaceae orchidales orchidalgia orchidectomy orchiectomy orchil orchiopexy orchis orchitis orchotomy orcinus orcus orczy ordainer ordeal order order-chenopodiales orderer ordering orderliness orderly ordinal ordinance ordinand ordinariness ordinary ordinate ordination ordnance ordovician ordure ore oread oreamnos orectolobidae orectolobus oregano oregon oregonian oreide oreo oreopteris oreortyx orestes orff organ organ-grinder organdie organdy organelle organic organicism organification organisation organiser organism organist organization organizer organon organophosphate organs organza orgasm orgy oriel orient oriental orientalism orientalist orientation orifice oriflamme origami origanum origen origin original originalism originality origination originator orinasal orinase orinoco oriole oriolidae oriolus orion orison orissa orites oriya orizaba orlando orleanais orleanism orleanist orleans orlon orlop orly ormandy ormazd ormer ormolu ormosia ormuzd ornament ornamental ornamentalism ornamentalist ornamentation ornateness orneriness ornithine ornithischia ornithischian ornithogalum ornithologist ornithology ornithomimid ornithomimida ornithopod ornithopoda ornithopter ornithorhynchidae ornithorhynchus ornithosis orobanchaceae orogeny orography oroide orology orono orontium oropharynx orozco orphan orphanage orphanhood orphenadrine orpheus orphrey orpiment orpin orpine orpington orr orrery orris orrisroot ortalis ortega orthicon orthilia orthochorea orthoclase orthodontia orthodontics orthodontist orthodonture orthodoxy orthoepist orthoepy orthogonality orthography orthomyxovirus orthopaedics orthopaedist orthopedics orthopedist orthophosphate orthopnea orthopristis orthopter orthoptera orthopteran orthopteron orthoptics orthoptist orthoscope orthotomus ortolan ortygan orudis orumiyeh oruvail orwell orycteropodidae orycteropus oryctolagus oryx oryza oryzomys oryzopsis orzo os osage osaka osasco osborne oscan oscar oscheocele oscheocoele oscillation oscillator oscillatoriaceae oscillogram oscillograph oscilloscope oscine oscines oscitance oscitancy osco-umbrian osculation osculator osha osier osiris oslo osmanli osmanthus osmeridae osmerus osmiridium osmitrol osmium osmoreceptor osmosis osmund osmundaceae osprey ossete ossicle ossiculum ossification ossuary ostariophysi osteichthyes osteitis ostensorium ostentation ostentatiousness osteoarthritis osteoblast osteoblastoma osteochondroma osteoclasis osteoclast osteocyte osteodystrophy osteoglossidae osteoglossiformes osteologer osteologist osteology osteolysis osteoma osteomalacia osteomyelitis osteopath osteopathist osteopathy osteopetrosis osteophyte osteoporosis osteosarcoma osteosclerosis osteostracan osteostraci osteotomy ostiarius ostiary ostinato ostiole ostler ostomy ostraciidae ostracism ostracod ostracoda ostracoderm ostracodermi ostrava ostrea ostreidae ostrich ostrogoth ostrya ostryopsis ostwald ostyak ostyak- samoyed oswald otalgia otaria otariidae othello otherness otherworld otherworldliness otho othonna otides otididae otis otitis oto otoe otoganglion otolaryngologist otolaryngology otologist otology otoplasty otorhinolaryngologist otorhinolaryngology otorrhea otosclerosis otoscope ottar ottawa otter otterhound ottoman ottumwa otus ouachita oubliette ouguiya ouija oujda ounce ouranopithecus ouranos ouse ousel ouster ousting out out-and-outer out-basket out-migration out-of-doors out-tray outage outaouais outback outboard outbreak outbuilding outburst outcast outcaste outcome outcrop outcropping outcry outdoors outdoorsman outdoorswoman outercourse outerwear outfall outfield outfielder outfit outfitter outfitting outflow outgo outgoer outgrowth outhouse outing outlander outlandishness outlaw outlawry outlay outlet outlier outline outlook outpatient outport outpost outpouring output outrage outrageousness outreach outrider outrigger outset outside outsider outsize outskirt outskirts outsole outspokenness outstation outstroke outtake outthrust outturn outwardness outwork ouzel ouzo ov oval ovalbumin ovalipes ovariectomy ovaritis ovary ovation oven ovenbird ovenware over over-crowding overabundance overachievement overachiever overacting overactivity overage overall overanxiety overappraisal overbearingness overbid overbite overburden overcall overcapitalisation overcapitalization overcast overcasting overcharge overclothes overcoat overcoating overcomer overcompensation overconfidence overcredulity overcrossing overdraft overdrive overeating overemphasis overestimate overestimation overexertion overexploitation overexposure overfeeding overflight overflow overgarment overgrowth overhang overhaul overhead overheating overindulgence overkill overlap overlapping overlay overlayer overlip overload overlook overlord overlordship overmantel overmuch overmuchness overnighter overpass overpayment overplus overpopulation overpressure overprint overproduction overprotection overrating overreaction overreckoning overrefinement override overrun overseer oversensitiveness overshielding overshoe overshoot oversight oversimplification overskirt overspill overstatement overstrain oversupply overtaking overthrow overtime overtolerance overtone overture overturn overuse overutilisation overutilization overvaluation overview overweight overwork overworking ovibos ovid oviduct oviedo ovimbundu ovipositor oviraptorid ovis ovocon ovoflavin ovoid ovolo ovotestis ovral ovrette ovulation ovule ovulen ovum owen owens owensboro owl owlclaws owlet owlt owner owner-driver owner-occupier ownership ox oxacillin oxalacetate oxalate oxalidaceae oxalis oxaloacetate oxandra oxaprozin oxazepam oxbow oxbridge oxcart oxen oxeye oxford oxheart oxidant oxidase oxidation oxidation-reduction oxide oxidisation oxidiser oxidization oxidizer oxidoreductase oxidoreduction oxime oximeter oxlip oxonian oxtail oxtant oxtongue oxyacetylene oxyacid oxybelis oxybenzene oxycephaly oxydendrum oxygen oxygenase oxygenation oxyhaemoglobin oxyhemoglobin oxylebius oxymoron oxyopia oxyphenbutazone oxyphencyclimine oxytetracycline oxytocic oxytocin oxytone oxytropis oxyura oxyuranus oxyuridae oyabun oyster oyster-fish oystercatcher oysterfish oz. ozaena ozarks ozawa ozena ozocerite ozokerite ozone ozonide ozonium ozonosphere ozothamnus p p.a. p.e. p.o. pa pa'anga paba pabir pablum pabulum pac paca pace pacemaker pacer pacesetter pacha pachinko pachisi pachouli pachuco pachycephala pachycephalosaur pachycephalosaurus pachycheilia pachyderm pachyderma pachyrhizus pachysandra pachytene pacific pacification pacificism pacificist pacifier pacifism pacifist pacing pack package packaging packer packera packet packhorse packing packinghouse packman packrat packsack packsaddle packthread pact pad padauk padda padder padding paddle paddle-box paddle-wheeler paddlefish paddler paddlewheel paddock paddy paddymelon pademelon paderewski padlock padouk padova padre padrone padua paducah paean paederast paederasty paediatrician paediatrics paedophile paedophilia paella paeonia paeoniaceae paeony pagad pagan paganini paganism page pageant pageantry pageboy pagellus pager paget pagination paging pagoda pagophila pagophilus pagrus paguridae pagurus pahautea pahlavi pahlevi pahoehoe paige paigle pail pailful paillasse pain paine painfulness painkiller pains painstakingness paint paintball paintbox paintbrush painter painting pair pairing paisa paisley paiute paiwanic pajama pakchoi pakistan pakistani pal palace paladin palaeencephalon palaemon palaemonidae palaeoanthropology palaeobiology palaeobotany palaeoclimatology palaeodendrology palaeoecology palaeoethnography palaeogeography palaeogeology palaeolithic palaeology palaeontologist palaeontology palaeopathology palaeornithology palaeozoology palaestra palaetiology palaic palankeen palanquin palaquium palas palatability palatableness palatal palate palatinate palatine palatopharyngoplasty palau palaver pale paleacrita paleencephalon paleface paleness paleo-american paleo- amerind paleo-indian paleoanthropology paleobiology paleobotany paleocene paleocerebellum paleoclimatology paleocortex paleodendrology paleoecology paleoencephalon paleoethnography paleogeography paleogeology paleographer paleographist paleography paleolith paleolithic paleology paleomammalogy paleontologist paleontology paleopathology paleornithology paleostriatum paleozoic paleozoology palermo palestine palestinian palestra palestrina paletiology palette palfrey palgrave pali palilalia palimony palimpsest palindrome paling palingenesis palinuridae palinurus palisade paliurus pall pall-mall palladio palladium pallas pallasite pallbearer pallet pallette palliasse palliation palliative pallidity pallidness pallidum pallium pallone pallor palm palmaceae palmae palmales palmature palmer palmetto palmist palmister palmistry palmitin palmyra palometa palomino palooka paloverde palpability palpation palpebra palpebration palpitation palsgrave palsy paltering paltriness pamelor pamlico pampas pamperer pampering pamphlet pamphleteer pan panacea panache panadol panama panamanian panamica panamiga panatela panax pancake pancarditis panchayat panchayet pancreas pancreatectomy pancreatin pancreatitis pancytopenia panda pandanaceae pandanales pandanus pandar pandemic pandemonium pander panderer pandiculation pandion pandionidae pandora pandowdy pane panegyric panegyrist panel paneling panelist panelling panellist panencephalitis panetela panetella panfish pang panga pangaea pangea pangloss pangolin panhandle panhandler panhysterectomy panic panicle panicum panini panipat panjabi panjandrum pannier pannikin panocha panoche panofsky panonychus panoply panopticon panorama panorpidae panpipe pansa pansexual pansinusitis pansy pant pantaloon pantechnicon pantheism pantheist pantheon panther panthera pantie pantile panting panto pantograph pantomime pantomimer pantomimist pantothen pantotheria pantry pantryman pants pantsuit panty pantyhose pantywaist panzer pap papa papacy papaia papain paparazzo papaver papaveraceae papaverales papaverine papaw papaya papeete paper paper-mache paper-pusher paperback paperboard paperboy paperclip paperer paperhanger paperhanging papering paperknife papermaking papers paperweight paperwork paphiopedilum papier-mache papilionaceae papilionoideae papilla papilledema papilloma papillon papio papism papist papoose papooseroot papovavirus pappa pappoose pappus paprika paprilus papua papuan papule papulovesicle papyrus par para parable parabola paraboloid paracelsus paracentesis paracheirodon parachute parachuter parachuting parachutist paraclete paracosm parade parader paradiddle paradigm paradisaeidae paradise paradox paradoxurus paraesthesia paraffin parafovea paragliding paragon paragonite paragraph paragrapher paraguay paraguayan parakeet paralanguage paraldehyde paralegal paraleipsis paralepsis paralichthys paralipomenon paralipsis paralithodes parallax parallel parallelepiped parallelepipedon parallelism parallelogram parallelopiped parallelopipedon paralogism paralysis paralytic paramagnet paramagnetism paramaribo paramecia paramecium paramedic paramedical parameter parametritis paramilitary paramnesia paramountcy paramour paramyxovirus parana parang paranoia paranoiac paranoid paranthias paranthropus paraparesis parapet paraph paraphernalia paraphilia paraphrase paraphrasis paraphrenia paraphysis paraplegia paraplegic parapodium parapraxis paraprofessional parapsychologist parapsychology paraquat paraquet parasail parasailing parascalops parashurama parasitaemia parasitaxus parasite parasitemia parasitism parasol parasympathetic parathelypteris parathion parathormone parathyroid paratrooper paratroops paratyphoid parazoa parazoan parcae parcel parceling parcellation parcelling parcheesi parchesi parchisi parchment pardner pardon pardoner paregmenon paregoric parenchyma parent parentage parenthesis parenthetical parenthood parer paresis paresthesia paretic pareto parfait parget pargeting pargetry pargetting parhelion pariah paridae paries parietales parietaria parimutuel paring paris parish parishioner parisian parisienne parisology parity parjanya parji park parka parker parkeriaceae parkersburg parkia parking parkinson parkinson's parkinsonia parkinsonism parkland parks parkway parlance parlay parley parliament parliamentarian parlor parlormaid parlour parlourmaid parmelia parmeliaceae parmenides parmesan parnahiba parnaiba parnassia parnassus parnell parochetus parochialism parodist parody parole parolee paronomasia paronychia parophrys paroquet parosamia parotitis parousia paroxetime paroxysm paroxytone parquet parqueterie parquetry parr parrakeet parricide parrish parroket parroquet parrot parrotfish parrotia parrotiopsis parry parsec parsee parseeism parser parsi parsiism parsimoniousness parsimony parsley parsnip parson parsonage parsons part part-owner part-singing part-timer partaker parterre parthenium parthenocarpy parthenocissus parthenogenesis parthenogeny parthenon parthenote parthia parthian partial partiality partialness participant participation participial participle particle particular particularisation particularism particularity particularization particulate parting partisan partisanship partita partition partitioning partitionist partitive partizan partner partnership partridge partridgeberry parts partsong parturiency parturition party partygoer parula parulidae parus parvati parvenu parvis parvo parvovirus pas pasadena pasang pascal pasch pascha paseo pasha pashto pashtoon pashtu pashtun pasigraphy pasiphae paspalum pasqueflower pasquinade pass pass- through passado passage passageway passamaquody passbook passe-partout passel passementerie passenger passer passer-by passerby passeres passeridae passeriformes passerina passerine passero passiflora passifloraceae passing passion passionateness passionflower passive passiveness passivism passivity passkey passover passport password past pasta paste paste-up pasteboard pastel paster pastern pasternak pasteur pasteurellosis pasteurisation pasteurization pastiche pastil pastille pastime pastinaca pastis pastness pasto pastor pastoral pastorale pastorate pastorship pastrami pastry pasturage pasture pastureland pasty pat pataca patagonia patas patavium patch patchboard patchcord patchiness patching patchouli patchouly patchwork pate patella patellidae patency patent patentee pater paterfamilias paternalism paternity paternoster paterson path pathan pathfinder pathogen pathogenesis pathologist pathology pathos pathway patience patient patina patio patisserie patka patness patois paton patrai patras patrial patriarch patriarchate patriarchy patrician patricide patrick patrikin patrilineage patrimony patriot patrioteer patriotism patrisib patristics patroclus patrol patroller patrolman patrology patron patronage patroness patronne patronym patronymic patsy patten patter pattern patternmaker patty patty-pan patwin patzer paucity paul pauli pauling paunch paunchiness pauper pauperisation pauperism pauperization pauropoda pause pavage pavan pavane pavarotti pave pavement pavilion paving pavior paviour pavis pavise pavlov pavlova pavo pavonia paw pawer pawl pawn pawnbroker pawnee pawnshop pawpaw pax paxil paxto paxton pay pay-phone pay-station payable payables payback paycheck payday paye payee payena payer paygrade payload paymaster payment paynim payoff payola payroll paysheet payslip pb pbit pbs pc pcp pct pd pda pdflp pdl pe pe- tsai pea pea-chick pea-souper peabody peace peaceableness peacefulness peacekeeper peacekeeping peacemaker peacenik peacetime peach peach-wood peachick peachwood peacoat peacock peacock-throne peafowl peag peahen peak peal pealing pean peanut peanuts pear pearl pearl-fish pearl-weed pearler pearlfish pearlite pearlweed pearlwort pearly pearmain peary peasant peasanthood peasantry peasecod peat peavey peavy peba pebble pebibit pebibyte pecan peccadillo peccary peck pecker peckerwood pecopteris pecos pecs pectin pectinibranchia pectinidae pectoral pectoralis pectus peculation peculator peculiarity pedagog pedagogics pedagogue pedagogy pedal pedaler pedaliaceae pedaller pedant pedantry peddler peddling pederast pederasty pedesis pedestal pedestrian pediamycin pediapred pediatrician pediatrics pediatrist pedicab pedicel pedicle pediculati pediculicide pediculidae pediculosis pediculus pedicure pedigree pedilanthus pediment pediocactus pedioecetes pedionomus pedipalpi pedlar pedodontist pedology pedometer pedophile pedophilia peduncle pedwood pee peeing peek peekaboo peel peeler peeling peen peep peeper peephole peepshow peepul peer peerage peeress peeve peevishness peewee peewit peg pegasus pegboard pegleg pegmatite pehlevi pei peignoir peiping peirce peireskia pekan peke pekinese peking pekingese pekoe pel pelage pelagianism pelagius pelargonium pelecanidae pelecaniformes pelecanoididae pelecanus pelecypod peleus pelew pelf pelham pelican peliosis pelisse pellaea pellagra pellet pellicle pellicularia pellitory pellitory-of-spain pellitory-of-the-wall pellucidity pellucidness pelmet pelobatidae peloponnese peloponnesus pelota pelt peltandra pelter pelting peltiphyllum peludo pelvimeter pelvimetry pelvis pelycosaur pelycosauria pembroke pemican pemmican pempheridae pemphigus pen pen-and-ink pen-friend pen- tail penalisation penalization penalty penance penchant pencil pendant pendent pendragon pendulum peneidae penelope peneplain peneplane penetrability penetralia penetration penetrator peneus pengo penguin penicillamine penicillin penicillinase penicillium peninsula penis penitence penitent penitentiary penknife penlight penman penmanship penn penn'orth pennant pennatula pennatulidae penne penni pennilessness pennines penning pennisetum pennon pennoncel pennoncelle pennsylvania pennsylvanian penny penny-pinching pennycress pennyroyal pennyweight pennywhistle pennyworth penobscot penoche penologist penology penoncel penpusher pensacola pension pensionary pensioner pensiveness penstemon penstock pentacle pentad pentaerythritol pentagon pentagram pentahedron pentail pentameter pentamethylenetetrazol pentangle pentastomid pentastomida pentateuch pentathlete pentathlon pentatone pentazocine pentecost pentecostal pentecostalism pentecostalist penthouse pentimento pentlandite pentobarbital pentode pentose pentothal pentoxide pentoxifylline pentylenetetrazol penuche penuchle penult penultima penultimate penumbra penuriousness penury penutian peon peonage peony people peoples peoria pep pepcid peperomia pepin peplos peplum peplus pepper pepper-and-salt peppercorn pepperidge pepperiness peppermint pepperoni pepperwood pepperwort peppiness pepsi pepsin pepsinogen peptidase peptide peptisation peptization pepto-bismal peptone pepys peradventure perambulation perambulator peramelidae perca percale perceiver percent percentage percentile percept perceptibility perception perceptiveness perceptivity perch percher percheron perchlorate perchloride perchloromethane percidae perciformes percina percipient percoid percoidea percoidean percolate percolation percolator percomorphi percophidae percussion percussionist percussor percy perdicidae perdicinae perdition perdix perdurability peregrination peregrine perejil perennation perennial pereskia perestroika perfect perfecta perfecter perfectibility perfection perfectionism perfectionist perfective perfidiousness perfidy perfluorocarbon perforation performance performer performing perfume perfumer perfumery perfusion pergamum pergola peri periactin perianth periapsis periarteritis pericallis pericarditis pericardium pericarp pericementoclasia periclase pericles peridinian peridiniidae peridinium peridium peridot peridotite perigee perigon perigone perigonium perihelion perijove peril perilla perilousness perilune perilymph perimeter perimysium perinatologist perinatology perineotomy perineum perineurium period periodical periodicity periodontia periodontics periodontist periodontitis periophthalmus periosteum peripatetic peripateticism peripatidae peripatopsidae peripatopsis peripatus peripeteia peripetia peripety peripheral periphery periphrasis periplaneta periploca periscope periselene perishability perishable perishableness perisher perisoreus perisperm perissodactyl perissodactyla peristalsis peristediinae peristedion peristome peristyle perithecium perithelium peritoneum peritonitis peritrate periwig periwinkle perjurer perjury perk perkiness perleche perm permafrost permalloy permanence permanency permanent permanganate permeability permeableness permeation permian permic permissibility permission permissiveness permit permutability permutableness permutation pernambuco perniciousness pernio pernis pernod perodicticus perognathus peromyscus peron peroneus peronospora peronosporaceae peronosporales peroration peroxidase peroxide perpendicular perpendicularity perpetration perpetrator perpetuation perpetuity perphenazine perplexity perquisite perry persea persecution persecutor persephone persepolis perseus perseverance perseveration pershing persia persian persiflage persimmon persistence persistency person persona personableness personage personal personality personalty personation personhood personification personnel persoonia perspective perspex perspicaciousness perspicacity perspicuity perspicuousness perspiration perspirer persuader persuasion persuasiveness pertainym perth pertinacity pertinence pertinency pertness perturbation pertusaria pertusariaceae pertussis peru peruke perusal perusing perutz peruvian pervaporation pervasion pervasiveness perverseness perversion perversity pervert perviousness pes pesach pesah pesantran pesantren peseta pesewa peshawar peshmerga peso pessary pessimism pessimist pest pesterer pesthole pesthouse pesticide pestilence pestis pestle pesto pet pet-food petabit petabyte petal petard petasites petaurista petauristidae petaurus petchary petcock petechia peter peterburg petersburg petfood petiole petiolule petite petiteness petitio petition petitioner petrarca petrarch petrel petrifaction petrification petrissage petrochemical petrocoptis petrogale petroglyph petrograd petrol petrolatum petroleum petrology petromyzon petromyzoniformes petromyzontidae petronius petroselinum petter petteria petticoat pettifogger pettifoggery pettiness petting pettishness petty petulance petunia peul pew pewee pewit pewter peyote peziza pezizaceae pezizales pezophaps pfalz pfannkuchen pfc pfennig pflp pflp-gc ph ph.d. phacelia phacochoerus phacoemulsification phaeochromocytoma phaeophyceae phaeophyta phaethon phaethontidae phaeton phage phagocyte phagocytosis phagun phaius phalacrocoracidae phalacrocorax phalacrosis phalaenopsis phalaenoptilus phalanger phalangeridae phalangida phalangiidae phalangist phalangitis phalangium phalanx phalaris phalarope phalaropidae phalaropus phalguna phallaceae phallales phalloplasty phallus phalsa phanerogam phanerogamae phaneromania phanerozoic phantasm phantasma phantasmagoria phantasy phantom pharaoh pharisee pharma pharmaceutic pharmaceutical pharmaceutics pharmacist pharmacogenetics pharmacokinetics pharmacologist pharmacology pharmacopeia pharmacopoeia pharmacy pharomacrus pharos pharsalus pharyngeal pharyngitis pharynx phascogale phascolarctos phase phase-out phaseolus phasianid phasianidae phasianus phasmatidae phasmatodea phasmid phasmida phasmidae phasmidia phd pheasant pheasant's-eye phegopteris pheidias phellem phellodendron phenacetin phenacomys phenaphen phenazopyridine phencyclidine phenelzine phenergan phenicia pheniramine pheno-safranine phenobarbital phenobarbitone phenol phenolic phenolphthalein phenomenology phenomenon phenoplast phenothiazine phenotype phensuximide phentolamine phenylacetamide phenylalanine phenylamine phenylbutazone phenylephrine phenylethylene phenylketonuria phenylpropanolamine phenyltoloxamine phenytoin pheochromocytoma pheresis pheromone phi phial phidias philadelphaceae philadelphia philadelphus philaenus philanderer philanthropist philanthropy philatelist philately philemon philharmonic philhellene philhellenism philhellenist philia philip philippi philippian philippians philippic philippine philippines philippopolis philistia philistine philistinism phillidae phillipsite phillyrea philodendron philogyny philohela philologist philologue philology philomachus philomath philophylla philosopher philosophiser philosophizer philosophizing philosophy philter philtre phimosis phintias phiz phlebectomy phlebitis phlebodium phlebogram phlebothrombosis phlebotomist phlebotomus phlebotomy phlegm phleum phloem phlogiston phlogopite phlomis phlox phobia phobophobia phobos phoca phocidae phocoena phocomelia phoebe phoebus phoenicia phoenician phoenicophorium phoenicopteridae phoeniculidae phoeniculus phoenicurus phoenix pholadidae pholas pholidae pholidota pholiota pholis pholistoma phon phonation phone phone-in phonebook phoneme phonemics phoner phonetician phonetics phoney phonics phonogram phonograph phonologist phonology phonophobia phony phoradendron phoronid phoronida phoronidea phosgene phosphatase phosphate phosphine phosphocreatine phospholipid phosphoprotein phosphor phosphorescence phosphorus phot photalgia photinia photius photo photo-offset photoblepharon photocathode photocell photochemistry photocoagulation photocoagulator photoconduction photoconductivity photocopier photocopy photoelectricity photoelectron photoemission photoengraving photoflash photoflood photograph photographer photography photogravure photojournalism photojournalist photolithograph photolithography photomechanics photometer photometrician photometrist photometry photomicrograph photomontage photomosaic photon photophobia photopigment photoretinitis photosensitivity photosphere photostat photosynthesis phototherapy phototropism phoxinus phragmacone phragmipedium phragmites phragmocone phrase phraseology phrasing phratry phrenitis phrenologist phrenology phrontistery phrygia phrygian phrynosoma phs phthiriidae phthirius phthirus phthisis phthorimaea phycobilin phycocyanin phycoerythrin phycology phycomycetes phycomycosis phylactery phyle phyllidae phyllitis phyllium phyllo phylloclad phyllocladaceae phylloclade phyllocladus phyllode phyllodoce phylloporus phylloquinone phyllorhynchus phylloscopus phyllostachys phyllostomatidae phyllostomidae phyllostomus phylloxera phylloxeridae phylogenesis phylogeny phylum physa physalia physalis physaria physeter physeteridae physiatrics physic physicalism physicality physicalness physician physicist physics physidae physiognomy physiography physiologist physiology physiotherapist physiotherapy physique physostegia physostigma physostigmine phytelephas phytochemical phytochemist phytochemistry phytohormone phytolacca phytolaccaceae phytologist phytology phytomastigina phytonadione phytophthora phytoplankton phytotherapy phytotoxin pi pi-meson pia piaf piaffe piaget pianism pianissimo pianist piano pianoforte pianola piaster piastre piazza pib pibgorn pibit pibroch pic pica pica-pica picador picaninny picardie picardy picariae picasso piccalilli piccaninny piccolo picea pichi pichiciago pichiciego picidae piciformes pick pick-me-up pick-off pickaninny pickax pickaxe pickelhaube picker pickerel pickerelweed pickeringia picket pickett pickford picking pickings pickle picklepuss picknicker pickpocket pickup picnic picnicker picofarad picoides picometer picometre picornavirus picosecond picot picovolt picrasma picris pictograph pictor pictorial picture picturesqueness picturing picul piculet picumnus picus pid piddle piddock pidgin pidlimdi pie pie-dog piece piecework pied-a-terre piedmont piemonte pieplant pier pierce pierid pieridae pieris pierre pierrot pieta pietism piety piezoelectricity piezometer piffle pig pigboat pigeon pigeonhole pigeonholing pigfish piggery piggishness piggy piggyback pigheadedness piglet pigman pigment pigmentation pigmy pignolia pignut pigpen pigskin pigsticking pigsty pigswill pigtail pigwash pigweed pij pika pike pike-perch pikeblenny pikestaff pilaf pilaff pilaster pilate pilau pilaw pilchard pile pilea piles pileup pileus pilewort pilferage pilferer pilgrim pilgrimage piling pill pillage pillager pillaging pillar pillbox pillion pillock pillory pillow pillowcase pillwort pilocarpine pilosella pilosity pilot pilotage pilotfish pilothouse piloting pilsen pilsener pilsner pilularia pilus pima pimenta pimento pimiento pimlico pimozide pimp pimpernel pimpinella pimple pin pin-up pinaceae pinafore pinata pinatubo pinball pince-nez pincer pinch pinchbeck pinche pinchgut pinckneya pinctada pincus pincushion pindar pindaric pindolol pine pine-weed pinealoma pineapple pinecone pinesap pinetum pineus pineweed pinfish pinfold ping ping-pong pinger pinguecula pinguicula pinguinus pinhead pinhole pinicola pining pinion pinite pink pinkeye pinkie pinkness pinko pinkroot pinky pinna pinnace pinnacle pinnatiped pinner pinning pinniped pinnipedia pinnotheres pinnotheridae pinnule pinny pinochle pinocle pinocytosis pinole pinon pinophytina pinopsida pinot pinpoint pinprick pinscher pinsk pinstripe pint pintado pintail pinter pintle pinto pinus pinwheel pinworm pinyon piolet pion pioneer piousness pip pip-squeak pipa pipage pipal pipe pipeclay pipefish pipefitting pipeful pipeline piper piperaceae piperacillin piperales piperazine piperin piperine piperocaine pipet pipette pipework pipewort pipidae pipile pipilo piping pipistrel pipistrelle pipistrellus pipit pippin pipra pipracil pipridae pipsissewa piptadenia pipturus pipul piquance piquancy piquantness pique piqueria piquet piracy pirana pirandello piranga piranha pirate pirogi pirogue piroplasm piroshki pirouette piroxicam pirozhki pisa pisanosaur pisanosaurus piscary pisces piscidia pisiform pismire pisonia piss piss-up pisser pissing pissis pistachio pistacia piste pistia pistil pistillode pistol pistoleer piston pisum pit pita pitahaya pitanga pitch pitchblende pitcher pitcherful pitchfork pitching pitchman pitchstone pitfall pith pithead pithecanthropus pithecellobium pithecia pithecolobium pithiness pitilessness pitman pitocin piton pitot pitprop pitressin pitsaw pitt pitta pittance pitter- patter pittidae pitting pittsburgh pittsfield pituitary pituophis pity pitymys pityriasis pityrogramma piute pivot pix pixel pixie pixy pizarro pizza pizzaz pizzazz pizzeria pizzicato pj's pkd pku placard placation place place-kicker place-kicking place-worship placebo placeholder placekicker placeman placement placenta placental placentation placer placeseeker placidity placidness placidyl placket placoderm placodermi placuna plage plagianthus plagiarisation plagiariser plagiarism plagiarist plagiarization plagiarizer plagiocephaly plagioclase plague plaice plaid plain plainchant plainclothesman plainness plainsman plainsong plaint plaintiff plaintiveness plait plaiter plan planaria planarian planation planchet planchette planck plane planeness planer planera planet planetarium planetesimal planetoid plangency planimeter plank plank-bed planking plankton planner planning plano planococcus planography plant plantae plantagenet plantaginaceae plantaginales plantago plantain plantation planter planthopper plantigrade planting plantlet plantsman planula plaque plaquenil plash plasm plasma plasmablast plasmacyte plasmacytoma plasmapheresis plasmid plasmin plasminogen plasmodiidae plasmodiophora plasmodiophoraceae plasmodium plassey plaster plasterboard plasterer plastering plasterwork plastic plasticine plasticiser plasticity plasticizer plastid plastination plastique plastron plat plataea platalea plataleidae platan platanaceae platanistidae platanthera platanus plate plateau plateful platelayer platelet plateletpheresis platen plater platform plath platichthys plating platinum platitude platitudinarian plato platonism platonist platoon plattdeutsch platte plattensee platter platy platycephalidae platycerium platyctenea platyctenean platyhelminth platyhelminthes platylobium platymiscium platypoecilus platypus platyrrhine platyrrhini platyrrhinian platysma platystemon plaudit plaudits plausibility plausibleness plautus plavix play play-actor play-box playacting playactor playback playbill playbook playbox playboy playday player playfellow playfulness playgoer playground playhouse playing playlet playlist playmaker playmate playoff playpen playroom playschool playscript playsuit plaything playtime playwright plaza plea pleader pleading pleasance pleasantness pleasantry pleaser pleasing pleasingness pleasure pleat pleating pleb plebe plebeian plebiscite plecoptera plecopteran plecotus plectania plectognath plectognathi plectomycetes plectophera plectorrhiza plectranthus plectron plectrophenax plectrum pledge pledgee pledger pleiades pleione pleiospilos pleistocene plenipotentiary plenitude plenteousness plentifulness plentitude plenty plenum pleochroism pleomorphism pleonasm pleonaste pleopod plesianthropus plesiosaur plesiosauria plesiosaurus plessimeter plessor plethodon plethodont plethodontidae plethora plethysmograph pleura pleuralgia pleurisy pleurobrachia pleurobrachiidae pleurocarp pleurodont pleurodynia pleuronectes pleuronectidae pleuropneumonia pleurosorus pleurothallis pleurotus pleven plevna plexiglas plexiglass pleximeter pleximetry plexor plexus plf pliability pliancy pliantness plica plication plicatoperipatus plier pliers plight plimsoll plinth pliny pliocene plo ploce ploceidae ploceus plod plodder plodding plonk plop plosion plosive plot plotinus plotter plough ploughboy ploughing ploughland ploughman ploughshare ploughwright plovdiv plover plow plowboy plower plowing plowland plowman plowshare plowwright ploy pluck pluckiness plug plug-in plug-ugly plugboard plugger plughole plum plum-yew plumage plumb plumbaginaceae plumbaginales plumbago plumber plumbery plumbing plumbism plumcot plume plumeria plumiera plummet plump plumpness plumule plunder plunderage plunderer plundering plunge plunger plunk plunker pluperfect plural pluralisation pluralism pluralist plurality pluralization plus plush plutarch pluteaceae pluteus pluto plutocracy plutocrat pluton plutonium pluvialis pluvianus pluviometer pluviose ply plyboard plyer plyers plymouth plywood plzen pm pms pneumatics pneumatophore pneumococcus pneumoconiosis pneumocytosis pneumoencephalogram pneumogastric pneumonectomy pneumonia pneumonitis pneumonoconiosis pneumothorax pneumovax po poa poaceae poacher poaching pob pocahontas pocatello pochard pock pocket pocket- handkerchief pocketbook pocketcomb pocketful pocketknife pockmark pod podalgia podalyria podargidae podargus podaxaceae podetium podiatrist podiatry podiceps podicipedidae podicipediformes podicipitiformes podilymbus podium podocarp podocarpaceae podocarpus podophyllum podsol podzol poe poeciliid poeciliidae poecilocapsus poecilogale poem poenology poephila poesy poet poet-singer poetess poetics poetiser poetizer poetry pogey pogge pogonia pogonion pogonip pogonophora pogonophoran pogostemon pogrom pogy poi poignance poignancy poikilotherm poilu poinciana poinsettia point pointedness pointel pointer pointillism pointillist pointlessness pointrel pointsman poise poison poison- berry poisonberry poisoner poisoning poitier poitiers poitou poitou-charentes poivrade poke poker pokeweed pokey poking pokomo poky pol polack poland polanisia polarimeter polaris polarisation polariscope polarity polarization polarography polaroid polder pole poleax poleaxe polecat polemic polemicist polemics polemist polemoniaceae polemoniales polemonium polenta poler polestar polianthes police policeman policewoman policy policyholder polio poliomyelitis polioptila poliosis poliovirus polish polisher polishing polistes politburo politeness politesse politician politico politics polity polk polka poll pollachius pollack pollard pollen pollenation pollex pollination pollinator pollinium pollinosis polliwog pollock polls pollster pollucite pollutant polluter pollution pollux pollyfish pollywog polo polo-neck polonaise polonium polony polska poltergeist poltroon poltroonery polyamide polyandrist polyandry polyangiaceae polyangium polyanthus polyarteritis polyborus polybotria polybotrya polybutene polybutylene polycarp polychaeta polychaete polychete polychrome polycillin polycirrus polycythemia polydactylus polydactyly polydipsia polyelectrolyte polyergus polyester polyethylene polyfoam polygala polygalaceae polygamist polygamy polygene polyglot polygon polygonaceae polygonales polygonatum polygonia polygonum polygraph polygynist polygyny polyhedron polyhidrosis polyhymnia polymastigina polymastigote polymath polymer polymerase polymerisation polymerization polymorph polymorphism polymox polymyositis polymyxin polynemidae polynesia polynesian polyneuritis polynomial polynya polyodon polyodontidae polyoma polyose polyp polypectomy polypedates polypedatidae polypeptide polyphone polyphony polyphosphate polyplacophora polyplacophore polyploid polyploidy polypodiaceae polypodiales polypodium polypody polyporaceae polypore polyporus polyprion polypropene polypropenonitrile polypropylene polyptoton polypus polysaccharide polysemant polysemy polysomy polystichum polystyrene polysyllable polysyndeton polytechnic polytetrafluoroethylene polytheism polytheist polythene polytonalism polytonality polyurethan polyurethane polyuria polyvalence polyvalency polyvinyl-formaldehyde polyzoa polyzoan pom pom-pom pomacanthus pomacentridae pomacentrus pomade pomaderris pomatomidae pomatomus pomatum pome pomegranate pomelo pomeranian pomfret pommel pommy pomo pomolobus pomologist pomology pomoxis pomp pompadour pompano pompeii pompey pompon pomposity pompousness ponca ponce poncho poncirus pond pond-skater ponderer ponderosa ponderosity ponderousness pondweed pone pong pongamia pongee pongid pongidae pongo poniard ponka pons ponselle ponstel pontederia pontederiaceae pontiac pontifex pontiff pontifical pontificate pontoon pontos pontus pony pony-trekking ponycart ponytail pooch pood poodle pooecetes poof pooh-bah pool pooler poolroom poon poop poor poorhouse poorness poorwill poove pop pop-fly pop-up popcorn pope popery popgun popillia popinjay poplar poplin popover popper poppet popping poppy poppycock popsicle populace popularisation populariser popularism popularity popularization popularizer population populism populist populus porbeagle porc porcelain porcellio porcellionidae porch porcupine porcupinefish porcupines pore porgy porifera poriferan pork pork-barreling pork-fish porkchop porker porkfish porkholt porkpie porn porno pornographer pornography poronotus poroporo porosity porousness porphyra porphyria porphyrin porphyrio porphyrula porphyry porpoise porridge porringer port port-au-prince port-of-spain porta portability portable portage portal portcullis porte porte-cochere portent porter porterage porterhouse portfolio porthole portico portiere portion portland portmanteau porto portrait portraitist portraiture portrayal portrayer portraying portsmouth portugal portuguese portulaca portulacaceae portunidae portunus portwatcher porzana pose poseidon poser poseur poseuse posing posit position positioner positioning positive positiveness positivism positivist positivity positron posology posse posseman possession possessive possessiveness possessor posset possibility possible possibleness possum possumwood post post- horse post-impressionist post-it post-maturity post-menopause post-mortem postage postbag postbox postcard postcava postcode postdiluvian postdoc postdoctoral poster posterboard posterior posteriority posterity postern postfix postgraduate posthitis posthole posthouse postiche postilion postillion postimpressionist posting postlude postman postmark postmaster postmistress postmodernism postmortem postponement postponer postposition postscript postulant postulate postulation postulator postum posture posturer posturing posy pot pot-au-feu potable potage potamogale potamogalidae potamogeton potamogetonaceae potamophis potash potassium potation potato potawatomi potbelly potboiler potboy poteen potemkin potence potency potentate potential potentiality potentiation potentilla potentiometer poterium potful pothead pother potherb potholder pothole potholer pothook pothos pothouse pothunter potion potlatch potluck potman potomac potomania potoroinae potoroo potorous potos potpie potpourri potsdam potsherd potshot pottage potter potterer pottery pottle potto potty potyokin pouch poudrin pouf pouffe poulenc poulet poulette poulterer poultice poultry poultryman pounce pound poundage poundal pounder pounding pourboire pousse-cafe poussin pout pouter pouteria poverty pow powder powderer powderiness powderpuff powell power powerboat powerbroker powerfulness powerhouse powerlessness powhatan powwow powys pox poxvirus poyang poyou pozsony ppk pplo ppp pr practicability practicableness practicality practice practician practitioner praenomen praesidium praetor praetorian praetorium praetorship prag pragmatic pragmatics pragmatism pragmatist prague praha praia prairial prairie praise praiseworthiness praisworthiness prajapati prakrit praline pram prance prancer prang prank prankishness prankster praseodymium prat prate prater pratfall pratincole prattle prattler praunus pravachol pravastatin prawn praxis praxiteles praya prayer prayerbook prazosin prc pre-eclampsia pre-empt pre- emption pre-emptor pre-raphaelite pre-socratic preacher preachification preaching preachment preakness preamble prearrangement prebend prebendary precambrian precariousness precaution precava precedence precedency precedent precentor precentorship precept preceptor preceptorship precession prechlorination precinct preciosity preciousness precipice precipitance precipitancy precipitant precipitate precipitateness precipitation precipitator precipitin precipitousness precis preciseness precision preclusion precociousness precocity precognition preconception precondition precordium precursor predation predator predecessor predestinarian predestinarianism predestination predestinationist predetermination predicament predicate predication predicator predictability prediction predictor predilection predisposition prednisolone prednisone predominance predomination preeclampsia preemie preeminence preempt preemption preemptor preexistence prefab prefabrication preface prefect prefecture preference preferment prefiguration prefix prefixation preformation pregnancy pregnanediol prehension prehensor prehistory preindication prejudgement prejudgment prejudice prelacy prelate prelature prelim preliminary prelims prelone prelude prematureness prematurity premeditation premie premier premiere premiership premise premises premiss premium premix premolar premonition prenanthes prentice preoccupancy preoccupation preordination prep preparation preparedness prepayment preponderance preposition prepossession prepotency prepuberty prepuce prerequisite prerogative presage presbyope presbyopia presbyter presbyterian presbyterianism presbytery presbytes preschool preschooler prescience prescott prescript prescription prescriptivism preseason presence present presentation presenter presentiment presentism presentist presentment presentness preservation preservationist preservative preserve preserver preserves presidency president presidentship presidio presidium presley press press-up pressburg pressing pressman pressmark pressor pressure prestidigitation prestidigitator prestige prestigiousness presumption presumptuousness presupposition preteen preteenager pretence pretend pretender pretending pretense pretension pretentiousness preterist preterit preterite preterition pretermission pretext pretor pretoria pretorium pretrial prettiness pretzel preussen prevacid prevalence prevarication prevaricator preventative prevention preventive preview prevision prevue prexy prey priacanthidae priacanthus priam priapism priapus price price-fixing pricelessness pricing prick pricker pricket pricking prickle prickle-weed prickleback prickliness prickling prickteaser pride pride-of-india pridefulness prie-dieu priest priest-doctor priestcraft priestess priesthood priestley prig priggishness prilosec prima primacy primality primaquine primary primate primates primateship primatology primaxin prime primer primidone primigravida priming primipara primitive primitiveness primitivism primness primo primogenitor primogeniture primordium primping primrose primula primulaceae primulales primus prince prince's-feather prince's-plume prince-of-wales'-heath princedom princeling princess princeton princewood principal principality principalship principe principen principle prinia prinival print printer printing printmaker printmaking printout priodontes prion prionace prionotus prior prioress priority priorship priory priscoan prism prismatoid prismoid prison prison-breaking prisonbreak prisoner pristidae pristis pritzelago privacy private privateer privateersman privateness privates privation privatisation privatization privet privilege privine privy prize prizefight prizefighter pro pro-lifer proaccelerin probabilism probability probable probate probation probationer probe probenecid probiotic probity problem proboscidea proboscidean proboscidian proboscis procaine procarbazine procardia procaryote procavia procaviidae procedure proceeding proceedings proceeds procellaria procellariidae procellariiformes process process-server processing procession processional processor prochlorperazine prociphilus proclamation proclivity procnias proconsul proconsulate proconsulship proconvertin procrastination procrastinator procreation procrustes proctalgia proctitis proctocele proctologist proctology proctoplasty proctor proctorship proctoscope proctoscopy procural procurance procurator procurement procurer procuress procyclidine procyon procyonid procyonidae prod prodding prodigal prodigality prodigy prodroma prodrome produce producer product production productiveness productivity proenzyme prof profanation profaneness profanity professing profession professional professionalisation professionalism professionalization professor professorship proffer proficiency profile profiling profit profitability profitableness profiteer profiterole profits profligacy profligate profoundness profundity profuseness profusion progenitor progeny progeria progesterone progestin progestogen prognathism progne prognosis prognostic prognostication prognosticator program programing programma programme programmer programming progress progression progressive progressiveness progressivism progressivity progymnosperm prohibition prohibitionist project projectile projection projectionist projector prokaryote prokayotae prokhorov prokofiev prolactin prolamine prolapse prolapsus prole prolegomenon prolepsis proletarian proletariat proliferation prolificacy proline prolixity prolixness prolog prologue prolongation prolonge prolusion prom promenade promethazine prometheus promethium prominence promiscuity promiscuousness promise promisee promiser promisor promontory promoter promotion prompt promptbook prompter prompting promptitude promptness promulgation promulgator promycelium pronation pronator proneness prong prongbuck pronghorn pronominal pronoun pronouncement pronucleus pronunciamento pronunciation proof proofreader prop propaedeutic propaedeutics propaganda propagandist propagation propagator propanal propanamide propane propanediol propanol propanolol propanone proparoxytone propellant propellent propeller propellor propenal propene propenoate propenonitrile propensity properness property prophase prophecy prophesier prophet prophetess prophets prophylactic prophylaxis prophyll propinquity propionaldehyde propitiation propitiousness propjet propman proponent proportion proportional proportionality proportionateness proposal proposer proposition propositus propoxyphene proprietary proprietor proprietorship proprietress propriety proprioception proprioceptor proprionamide props propulsion propyl propylene propylthiouracil proration prorogation prosaicness prosauropoda proscenium prosciutto proscription prose prosecution prosecutor proselyte proselytism prosencephalon proserpina proserpine prosimian prosimii prosiness prosodion prosody prosom prosopis prosopium prosopopoeia prospect prospector prospectus prosperity prospicience prostaglandin prostate prostatectomy prostatitis prostheon prosthesis prosthetics prosthetist prosthion prosthodontia prosthodontics prosthodontist prostigmin prostitute prostitution prostration protactinium protagonism protagonist protamine protanopia protea proteaceae proteales protease protection protectionism protectionist protectiveness protector protectorate protectorship protege protegee proteidae protein proteinase proteinuria proteles proteolysis proteome proteomics proteosome proterochampsa proterozoic protest protestant protestantism protestation protester proteus prothalamion prothalamium prothorax prothrombin prothrombinase protirelin protist protista protistan protium proto-norse proto-oncogene protoactinium protoanthropology protoarchaeology protoarcheology protoavis protoceratops protocol protoctist protoctista protoheme protohemin protohippus protohistory protology protomammal proton protoplasm protoplast prototheria prototherian prototype protozoa protozoan protozoologist protozoology protozoon protraction protractor protriptyline protropin protrusion protuberance protura proturan proudhon proust provability provenance provencal provence provender provenience proventil provera proverb proverbs providence provider province provincial provincialism provirus provision provisioner provisions proviso provitamin provo provocateur provocation provoker provos provost prow prowess prowl prowler proxemics proxima proximity proxy prozac prude prudence prudery prudishness prumnopitys prune prunella prunellidae pruner pruning pruno prunus prurience pruriency prurigo pruritus prussia prussian pry prying ps psa psalm psalmist psalmody psalms psalter psalterium psaltery psaltriparus psammoma psenes psephologist psephology psephurus psetta psettichthys pseud pseudacris pseudaletia pseudechis pseudemys pseudepigrapha pseudo pseudobombax pseudobulb pseudocarp pseudococcidae pseudococcus pseudocolus pseudocyesis pseudoephedrine pseudohallucination pseudohermaphrodite pseudohermaphroditism pseudolarix pseudomonad pseudomonadales pseudomonas pseudomonodaceae pseudonym pseudophloem pseudopleuronectes pseudopod pseudopodium pseudorubella pseudoryx pseudoscience pseudoscorpion pseudoscorpiones pseudoscorpionida pseudosmallpox pseudotaxus pseudotsuga pseudovariola pseudowintera psf psi psidium psilocin psilocybin psilomelane psilophytaceae psilophytales psilophyte psilophyton psilopsida psilosis psilotaceae psilotales psilotatae psilotum psithyrus psittacidae psittaciformes psittacosaur psittacosaurus psittacosis psittacula psittacus psoas psocid psocidae psocoptera psophia psophiidae psophocarpus psoralea psoriasis pst psyche psychedelia psychiatrist psychiatry psychic psycho psychoanalysis psychoanalyst psychobabble psychodid psychodidae psychodynamics psychogenesis psychokinesis psycholinguist psycholinguistics psychologist psychology psychometrics psychometrika psychometry psychoneurosis psychoneurotic psychonomics psychopath psychopathology psychopathy psychopharmacology psychophysicist psychophysics psychophysiology psychopomp psychopsis psychosexuality psychosis psychosurgery psychotherapeutics psychotherapist psychotherapy psychotic psychotria psychrometer psylla psyllid psyllidae psyllium psyop pt ptah ptarmigan pteretis pteridaceae pteridium pteridologist pteridology pteridophyta pteridophyte pteridosperm pteridospermae pteridospermaphyta pteridospermopsida pteriidae pterion pteris pternohyla pterocarpus pterocarya pterocles pteroclididae pterocnemia pterodactyl pterodactylidae pterodactylus pterois pteropogon pteropsida pteropus pterosaur pterosauria pterospermum pterostylis pterygium ptilocercus ptilocrinus ptilonorhynchidae ptilonorhynchus ptloris pto ptolemy ptomain ptomaine ptosis ptsd ptyalin ptyalism ptyalith ptyas ptychozoon pu pub puberty pubes pubescence pubis public publican publication publiciser publicist publicity publicizer publicizing publisher publishing puccini puccinia pucciniaceae puccoon puce puck pucker puckerbush puckishness pud pudden-head pudding pudding-face pudding-wife puddingwife puddle puddler pudendum pudge pudginess puebla pueblo pueraria puerility puerpera puerperium puff puffball puffbird puffer pufferfish puffery puffin puffiness puffing puffinus pug pug-dog pugilism pugilist pugin puglia pugnacity puissance pujunan puka puke puking puku pul pula pulasan pulassan pulchritude pulex pulicaria pulicidae pulitzer pull pull-in pull-off pull- through pull-up pullback puller pullet pulley pulley-block pulling pullman pullout pullover pullulation pulmonata pulp pulpiness pulpit pulpwood pulque pulsar pulsatilla pulsation pulse pulsing pulverisation pulverization puma pumice pummelo pump pumpernickel pumpkin pumpkinseed pun punch punch-up punchayet punchball punchboard puncher punctilio punctiliousness punctuality punctuation punctum puncture pundit pung pungapung pungency punic punica punicaceae puniness punishment punjab punjabi punk punkah punkey punkie punks punky punnet punning punster punt punter punting pup pupa pupil puppet puppeteer puppetry puppis puppy purace purana purau purcell purchase purchaser purchasing purdah pureblood purebred puree pureness purgation purgative purgatory purge purging purification purifier purim purine purinethol purism purist puritan puritanism purity purkinje purl purlieu purloo purple purpleness purplish-red purport purpose purposefulness purposelessness purpura purr purse purser purslane pursual pursuance pursued pursuer pursuit purulence purulency purus purveyance purveyor purview pus pusan pusey puseyism push push-bike pushan pushball pushcart pushchair pusher pushiness pushing pushkin pushover pushpin pushtun pushup pusillanimity pusillanimousness puss pussley pussly pussy pussy's-paw pussy-paw pussy-paws pussycat pussytoes pustule put put-down put-on put-put putamen putin putoff putout putrajaya putrefaction putrescence putrescine putridity putridness putsch putt puttee putter putterer putting putty puttyroot putz puzzle puzzlement puzzler pva pvc pwr px pya pyaemia pycnanthemum pycnidium pycnodysostosis pycnogonid pycnogonida pycnosis pydna pye-dog pyelitis pyelogram pyelography pyelonephritis pyemia pygmalion pygmy pygopodidae pygopus pygoscelis pyinma pyjama pyknosis pyle pylodictus pylon pylorus pynchon pyocyanase pyocyanin pyongyang pyorrhea pyorrhoea pyracanth pyracantha pyralid pyralidae pyralididae pyralis pyramid pyramiding pyrausta pyre pyrectic pyrene pyrenees pyrenomycetes pyrethrum pyrex pyrexia pyridine pyridium pyridoxal pyridoxamine pyridoxine pyrilamine pyrimidine pyrite pyrites pyrocellulose pyrocephalus pyrochemistry pyroelectricity pyrogallol pyrogen pyrograph pyrographer pyrography pyrola pyrolaceae pyrolatry pyrolusite pyrolysis pyromancer pyromancy pyromania pyromaniac pyrometer pyromorphite pyrope pyrophobia pyrophorus pyrophosphate pyrophyllite pyroscope pyrosis pyrostat pyrotechnic pyrotechnics pyrotechny pyroxene pyroxylin pyroxyline pyrrhic pyrrhocoridae pyrrhotine pyrrhotite pyrrhula pyrrhuloxia pyrrhus pyrrophyta pyrrosia pyrularia pyrus pythagoras pythia pythiaceae pythias pythium pythius python pythoness pythonidae pythoninae pyuria pyx pyxidanthera pyxidium pyxie pyxis q qabala qabalah qabbala qabbalah qaddafi qadhafi qadi qaeda qandahar qat qatar qatari qcd qed qepiq qi qiang qiangic qibla qin qindarka qing qintar qoph quaalude quack quack-quack quackery quackgrass quad quadragesima quadrangle quadrant quadrantanopia quadraphony quadrate quadratic quadratics quadrature quadrennium quadric quadriceps quadrilateral quadrille quadrillion quadrillionth quadripara quadriplegia quadriplegic quadrivium quadroon quadrumvirate quadruped quadruple quadruplet quadruplicate quadrupling quaestor quaff quaffer quag quagga quagmire quahaug quahog quail quaintness quake quaker quakerism quakers qualification qualifier qualifying quality qualm quamash quamassia quandang quandary quandong quango quantic quantifiability quantification quantifier quantisation quantity quantization quantong quantum quaoar quapaw quarantine quark quarrel quarreler quarreller quarrelsomeness quarrier quarry quarrying quarryman quart quartan quarter quarter-century quarter-circle quarter-hour quarter-tone quarter-vine quarterback quarterdeck quarterfinal quartering quarterlight quarterly quartermaster quartern quarters quarterstaff quartervine quartet quartette quartic quartile quarto quartz quartzite quasar quasi-ngo quasiparticle quassia quat quatercentenary quatercentennial quatern quaternary quaternion quaternity quatrain quattrocento quaver quay quayage queasiness quebec quebecois quechua quechuan queen queenfish queens queensland queer queerness quelling quellung quenching quercitron quercus querier quern querulousness query quesadilla quest quester question questioner questioning questionnaire quetzal quetzalcoatl queue quiaquia quibble quibbler quiche quick quick-wittedness quickener quickening quickie quicklime quickness quicksand quickset quicksilver quickstep quicky quid quiddity quidnunc quiescence quiescency quiet quietism quietist quietness quietude quietus quiff quill quillwort quilt quilting quin quinacrine quince quincentenary quincentennial quincy quine quinidex quinidine quinine quinone quinora quinquagesima quinquennium quinsy quint quintal quintessence quintet quintette quintillion quintillionth quintipara quintuple quintuplet quintupling quip quipu quira quire quirk quirkiness quirt quiscalus quisling quislingism quitclaim quito quittance quitter quiver quivering quixotism quiz quizmaster quizzer qum quodlibet quoin quoit quoits quoratean quorum quota quotability quotation quote quoter quotient quran qurush r r-2 r.v. ra rabat rabato rabbet rabbi rabbinate rabbit rabbit- weed rabbiteye rabbitfish rabbitweed rabbitwood rabble rabble-rouser rabelais rabidity rabidness rabies raccoon race raceabout racecard racecourse racehorse raceme racer racerunner racetrack raceway rachel rachet rachis rachischisis rachitis rachmaninoff rachmaninov rachycentridae rachycentron racialism racialist racine raciness racing racism racist rack racker racket racketeer racketeering racketiness racon raconteur racoon racquet racquetball rad radar raddle radhakrishnan radial radian radiance radiancy radiation radiator radical radicalism radicchio radicle radiculitis radiigera radio radio-gramophone radio- opacity radio-phonograph radioactivity radiobiologist radiobiology radiocarbon radiochemist radiochemistry radiochlorine radiocommunication radiogram radiograph radiographer radiography radioimmunoassay radioisotope radiolaria radiolarian radiolocation radiologist radiology radiolysis radiometer radiomicrometer radiopacity radiopharmaceutical radiophone radiophoto radiophotograph radiophotography radioprotection radioscopy radiosensitivity radiotelegraph radiotelegraphy radiotelephone radiotelephony radiotherapist radiotherapy radiothorium radish radium radius radix radome radon radyera raetam raf raffia raffinose raffle raffles rafflesiaceae raft rafter raftman rafts raftsman rag ragamuffin ragbag rage ragee raggedness ragi raglan ragnarok ragout ragpicker ragsorter ragtag ragtime ragusa ragweed ragwort rahu raid raider rail rail-splitter railbird railcar railhead railing raillery railroad railroader railroading rails railway railwayman railyard raiment rain rain-giver rain-in- the-face rain-wash rainbow raincoat raindrop rainfall rainfly rainforest raininess rainmaker rainmaking rainstorm rainwater raise raiser raisin raising raita raiu raj raja rajab rajah rajanya rajidae rajiformes rajpoot rajput rakaposhi rake rake-off rakehell rakishness rale ralegh raleigh rallidae rally rallying ram ram's-head rama ramachandra ramadan ramalina ramanavami ramayana ramble rambler rambotan rambouillet rambutan rameau ramee ramekin ramequin rameses ramesses ramie ramification ramipril ramjet ramman rammer ramona ramontchi ramp rampage rampart ramphastidae ramphomicron rampion ramrod ramses ramsons ramus rana ranales ranatra ranch rancher ranching rancidity rancidness rancor rancour rand randomisation randomization randomness ranee range rangefinder rangeland ranger rangifer rangoon rangpur rani ranid ranidae ranier ranitidine rank ranker rankin rankine ranking rankness ransacking ransom rant ranter ranting ranula ranunculaceae ranunculales ranunculus raoulia rap rapaciousness rapacity rapateaceae rape raper rapeseed raphael raphanus raphe raphia raphicerus raphidae raphidiidae raphus rapid rapidity rapidness rapier rapine rapist rappahannock rappee rappel rappeller rapper rapport rapporteur rapprochement rapscallion raptor raptores rapture raptus rarebit raree-show rarefaction rareness rariora rarity ras rascal rascality rash rasher rashness rasht rask raskolnikov rasmussen rasp raspberry rasping rasputin rassling rasta rastafari rastafarian rastafarianism rastas raster rat rat-a-tat rat-a-tat-tat rat-catcher rat-tat ratability ratables ratafee ratafia ratan rataplan ratatouille ratch ratchet rate rateability rateables ratel ratepayer rates rathole rathskeller ratibida ratification ratifier rating ratio ratiocination ratiocinator ration rational rationale rationalisation rationalism rationalist rationality rationalization rationalness rationing ratitae ratite ratlin ratline ratsbane rattail rattan ratter rattigan ratting rattle rattle-top rattlebox rattler rattlesnake rattling rattrap rattus rau-sed raudixin raunch rauvolfia rauwolfia ravage ravaging rave rave-up ravehook ravel raveling ravelling raven ravenala ravenna ravenousness raver ravigote ravigotte ravine raving ravioli ravisher ravishment raw rawalpindi rawhide rawness ray rayleigh rayon rayons razbliuto razing razmataz razor razor-fish razorback razorbill razorblade razz razzing razzle razzle-dazzle razzmatazz rb rbc rbi rcmp re re-afforestation re- creation re-echo re-establishment re-experiencing re-formation re-introduction re-sentencing re-uptake reabsorption reach reaching reactance reactant reaction reactionary reactionism reactivity reactor read read-out readability reader readership readiness reading readjustment readmission readout ready ready-made ready-mix ready-to-wear readying reaffiliation reaffirmation reagan reagent reagin real realgar realisation realism realist reality realization reallocation reallotment realm realness realpolitik realtor realty ream reamer reaper reappearance reapportionment reappraisal rear rearguard rearing rearmament rearrangement rearward reason reasonableness reasoner reasoning reassembly reassertion reassessment reassignment reassurance reata reaumur reb rebate rebato rebecca rebekah rebel rebellion rebelliousness rebirth rebound reboxetine rebozo rebroadcast rebuff rebuilding rebuke rebuker reburial reburying rebus rebuttal rebutter recalcitrance recalcitrancy recalculation recall recantation recap recapitulation recapture recasting recce recco reccy receding receipt receipts receivables receiver receivership recency recent recentness receptacle reception receptionist receptiveness receptivity receptor recess recession recessional recessive rechauffe recidivism recidivist recife recipe recipient reciprocal reciprocality reciprocation reciprocity recirculation recission recital recitalist recitation recitative reciter recklessness reckoner reckoning reclamation reclassification recliner reclining recluse reclusiveness recoding recognisance recognition recognizance recoil recollection recombinant recombination recommencement recommendation recompense reconciler reconciliation reconditeness reconnaissance reconnoitering reconnoitring reconsideration reconstruction record record-breaker record-holder record-keeper recorder recording recount recounting recourse recoverer recovery recreant recreation recrimination recrudescence recruit recruiter recruiting-sergeant recruitment rectangle rectangularity rectification rectifier rectitude recto rectocele rectoplasty rector rectorate rectorship rectory rectum rectus recuperation recurrence recursion recurvirostra recurvirostridae recusal recusancy recusant recusation recycling red red-berry red-blindness red-header redact redaction redactor redbelly redberry redbird redbone redbreast redbrush redbud redbug redcap redcoat redding reddle rededication redeemer redefinition redemption redeployment redeposition redetermination redevelopment redeye redfish redford redhead redheader redhorse rediffusion rediscovery redisposition redistribution redmaids redneck redness redolence redonda redoubt redox redpoll redraft redress redroot redshank redshift redskin redstart redtail reducer reducing reductant reductase reductio reduction reductionism reductivism redundance redundancy reduplication reduviid reduviidae redwing redwood reed reedbird reedmace reef reefer reek reel reelection reeler reenactment reenactor reenforcement reenlistment reentry reevaluation reeve reexamination ref refabrication refection refectory referee refereeing reference referendum referent referral refill refilling refinement refiner refinery refining refinisher refit reflation reflectance reflection reflectiveness reflectivity reflectometer reflector reflex reflexion reflexive reflexiveness reflexivity reflexology reflux refocusing reforestation reform reformation reformatory reformer reformism reformist refraction refractiveness refractivity refractometer refractoriness refractory refrain refresher refreshment refrigerant refrigeration refrigerator refueling refuge refugee refulgence refulgency refund refurbishment refusal refuse refutal refutation refuter regaining regalecidae regalia regard regatta regency regeneration regent reggae reggane regicide regime regimen regiment regimentals regimentation regina regiomontanus region regionalism register registrant registrar registration registry reglaecus regnellidium regosol regress regression regret regrets regular regularisation regularity regularization regulating regulation regulator regulus regur regurgitation rehabilitation reharmonisation reharmonization rehash rehearing rehearsal rehnquist reich reichstein reid reification reign reimbursement reimposition reims rein reincarnation reincarnationism reindeer reinforcement reinforcer reinstatement reinsurance reinterpretation reintroduction reissue reit reiter reiteration reithrodontomys reject rejection rejoicing rejoinder rejuvenation relafen relapse relapsing relatedness relation relations relationship relative relative-in-law relativism relativity relatum relaxant relaxation relaxer relaxin relay release relegating relegation relentlessness relevance relevancy reliability reliableness reliance relic relict relief reliever relievo religion religionism religionist religiosity religious religiousism religiousness relinquishing relinquishment reliquary relish relishing relistening reliving relocation reluctance reluctivity rem remainder remains remake remaking remand remark remarriage rematch rembrandt remediation remedy remembering remembrance remicade remilegia remilitarisation remilitarization reminder reminiscence remise remission remissness remit remitment remittal remittance remnant remonstrance remonstration remora remorse remote remoteness remotion remount removal remove remover remuda remuneration remunerator remus renaissance renascence render rendering rendezvous rendition renegade renege renewal renin rennet rennin reno renoir renouncement renovation renovator renown rensselaerite rent rent-a-car rent-rebate rent-roll rental rente renter rentier renting renunciation reorder reordering reorganisation reorganization reorientation reoviridae reovirus rep repair repairer repairman reparation repartee repast repatriate repatriation repayment repeal repeat repeater repeating repechage repellant repellent repentance repercussion repertoire repertory repetition repetitiousness repetitiveness rephrasing replaceability replacement replacing replay replenishment repletion replica replication reply report reportage reporter reporting repose repositing reposition repositioning repository repossession repp reprehensibility reprehension representation representative represser repression repressor reprieve reprimand reprint reprinting reprisal reproach reproacher reprobate reprobation reproducer reproducibility reproduction reproof reproval reprover reptantia reptile reptilia reptilian republic republican republicanism republication republishing repudiation repugnance repulse repulsion repulsiveness repurchase reputability reputation repute request requester requiem requiescat requirement requisite requisiteness requisition requital rerebrace reredos rerun res resale rescission rescript rescriptor rescue rescuer research researcher reseau resection reseda resedaceae resemblance resentment reserpine reservation reserve reserves reservist reservoir reset resettlement resh reshipment resht reshuffle reshuffling resid residence residency resident residual residue residuum resignation resilience resiliency resin resinoid resistance resister resistivity resistor resoluteness resolution resolve resolvent resolving resonance resonator resorcinol resorcinolphthalein resorption resort resource resourcefulness respect respectability respecter respectfulness respects respighi respiration respirator respite resplendence resplendency respondent responder response responsibility responsibleness responsiveness rest rest-cure rest-harrow restatement restaurant restauranter restaurateur rester restfulness restharrow restitution restiveness restlessness restoration restorative restorer restoril restrainer restraint restriction restrictiveness restroom result resultant resume resumption resurgence resurrection resurvey resuscitation resuscitator resuspension retail retailer retailing retainer retake retaking retaliation retaliator retama retard retardant retardation retarded retardent retch rete retem retention retentiveness retentivity rethink reticence reticle reticulation reticule reticulitermes reticulocyte reticulum retina retinal retinene retinitis retinoblastoma retinol retinopathy retinue retiree retirement retort retraction retractor retraining retread retreat retreatant retreated retrenchment retrial retribution retrieval retriever retro retrofit retroflection retroflexion retrogression retronym retrophyllum retrorocket retrospect retrospection retrospective retroversion retrovir retrovirus retrovision retsina return reuben reunification reunion reuptake rev revaluation revealing reveille revel revelation reveler reveller revelry revenant revenge revenue revenuer reverberance reverberation revere reverence reverend reverie revers reversal reverse reversibility reversible reversion reversioner reversionist reverting revery revetement revetment review reviewer revilement revisal revise reviser revising revision revisionism revisionist revitalisation revitalization revival revivalism revivalist revivification revocation revoke revolt revolution revolutionary revolutionism revolutionist revolver revue revulsion rewa-rewa reward rewording rewrite rewriter rewriting rex reyes reykjavik reynard reynolds rf rfd rg rh rhabdomancer rhabdomancy rhabdomyoma rhabdomyosarcoma rhabdosarcoma rhabdoviridae rhabdovirus rhadamanthus rhaeto-romance rhaeto-romanic rhagades rhagoletis rhamnaceae rhamnales rhamnus rhaphe rhapis rhapsody rhd rhea rheidae rheiformes rheims rhein rheinland rhenish rhenium rheology rheometer rheostat rhesus rhetoric rhetorician rheum rheumatic rheumatism rheumatologist rheumatology rhexia rhibhus rhincodon rhincodontidae rhine rhineland rhinencephalon rhinestone rhinion rhinitis rhino rhinobatidae rhinoceros rhinocerotidae rhinolaryngologist rhinolaryngology rhinolophidae rhinonicteris rhinopathy rhinophyma rhinoplasty rhinoptera rhinorrhea rhinoscope rhinoscopy rhinosporidiosis rhinostenosis rhinotermitidae rhinotomy rhinotracheitis rhinovirus rhipsalis rhiptoglossa rhizobiaceae rhizobium rhizoctinia rhizoid rhizome rhizomorph rhizophora rhizophoraceae rhizopod rhizopoda rhizopodan rhizopogon rhizopogonaceae rhizopus rhizotomy rho rhodanthe rhodes rhodesia rhodium rhodochrosite rhododendron rhodolite rhodomontade rhodonite rhodophyceae rhodophyta rhodopsin rhodosphaera rhodymenia rhodymeniaceae rhoeadales rhomb rhombencephalon rhombohedron rhomboid rhombus rhonchus rhone rhone-alpes rhubarb rhumb rhumba rhus rhyacotriton rhyme rhymer rhymester rhynchocephalia rhynchoelaps rhyncostylis rhynia rhyniaceae rhyolite rhythm rhythmicity rhytidectomy rhytidoplasty ri rial riata rib ribald ribaldry riband ribavirin ribband ribbing ribbon ribbonfish ribbonwood ribes ribgrass ribhus ribier riboflavin ribonuclease ribonucleinase ribose ribosome ribwort ricardo rice ricebird ricegrass ricer rich <NAME> richea richelieu riches richler richmond richmondena richness richweed ricin ricinus rick rickenbacker ricketiness rickets rickettsia rickettsiaceae rickettsiales rickettsialpox rickettsiosis rickey rickover rickrack ricksha rickshaw rico ricochet ricotta ricrac rictus riddance riddle ride rider ridge ridgel ridgeline ridgeling ridgepole ridgil ridgling ridicule ridiculer ridiculousness riding ridley riel riemann riesling riesman rifadin rifampin riff riffian riffle riffraff rifle riflebird rifleman rifling rift rig rig-veda riga rigamarole rigatoni rigel rigger rigging right right-handedness right-hander right-winger righteousness rightfield rightfulness righthander rightism rightist rightness rigidification rigidifying rigidity rigidness rigil rigmarole rigor rigorousness rigour rigourousness rigout rijstafel rijstaffel rijsttaffel riksmaal riksmal riley rilievo rilke rill rim rima rimactane rimbaud rime rimski-korsakov rimsky- korsakov rimu rind rinderpest ring ring-a-rosy ring-around-a-rosy ring-around- the-rosy ring-binder ringdove ringer ringgit ringhals ringing ringleader ringlet ringling ringmaster rings ringside ringtail ringway ringworm rink rinkhals rinse rinsing rio rioja riot rioter rioting rip rip-off riparia ripcord ripeness ripening riposte ripper ripple ripple-grass rippling ripsaw riptide rira risc rise riser risibility rising risk riskiness risklessness risotto rissa rissole ritalin rite ritonavir rittenhouse ritual ritualism ritualist ritz rival rivalry river rivera riverbank riverbed riverside rivet riveter rivetter riviera rivina rivulet rivulus riyadh riyal riyal-omani rn rna rnase ro roach road roadbed roadblock roadbook roadhog roadhouse roadkill roadman roadrunner roads roadside roadstead roadster roadway roadworthiness roamer roan roanoke roar roarer roaring roast roaster roasting robalo robaxin robber robbery robbins robe robe- de-chambre robert roberts robertson robeson robespierre robin robinia robinson robitussin roble robot robotics robustness roc rocambole roccella roccellaceae roccus rocephin rochambeau rochester rock rock'n'roll rock-and-roll rockabilly rockchuck rockcress rockefeller rocker rockers rockery rocket rocketry rockfish rockfoil rockford rockies rockiness rockingham rockrose rockslide rockweed rockwell rococo rocroi rod rodent rodentia rodeo rodgers rodhos rodin rodolia rodomontade roe roebling roebuck roentgen roentgenium roentgenogram roentgenography roentgenoscope rofecoxib rogaine rogation rogers roget rogue roguery roguishness rohypnol roi roisterer rolaids role roleplaying rolf roll roll-on rollback roller roller-skater rollerblade rollerblader rollerblading rolling rollmops rollo rollover rolodex roly-poly rolypoliness rom roma romaic romaine roman romanal romance romanesque romani romania romanian romanism romanoff romanov romans romansh romantic romanticisation romanticism romanticist romanticization romany romberg rome romeo rommany rommel romneya romp romper romulus ron rondeau rondel rondelet rondo roneo roneograph rontgen rood rood- tree roof roofer roofing rooftop rooftree roofy rooibos rook rookery rookie room roomer roomette roomful roomie roominess roommate rooms roomy roosevelt roost rooster root rootage rooter rooting rootlet roots rootstalk rootstock rope rope-a-dope rope-maker ropebark ropedancer ropemaker roper ropewalk ropewalker ropeway rophy ropiness roping roquefort roquette roridula roridulaceae rorippa rorqual rorschach rosa rosacea rosaceae rosales rosario rosary rose rose-root roseau rosebay rosebud rosebush rosefish rosehip roselle rosellinia rosemaling rosemary roseola rosette rosewood rosicrucian rosicrucianism rosidae rosilla rosin rosiness rosinweed rosita rosmarinus ross rossbach rossetti rossini rostand roster rostock rostov rostrum roswell rot rota rotarian rotary rotation rotavirus rotc rote rotenone rotgut roth rothko rothschild rotifer rotifera rotisserie rotl rotogravure rotor rottenness rottenstone rotter rotterdam rotting rottweiler rotunda rotundity rotundness rouble roue rouge rougeberry rough rough-and-tumble roughage roughcast roughleg roughneck roughness roughrider roulade rouleau roulette roumania round roundabout roundedness roundel roundelay rounder rounders roundhead roundhouse rounding roundness roundsman roundtable roundup roundworm rous rouser rousing rousseau roustabout rout route routemarch router routine roux rover roving row rowan rowanberry rowboat rowdiness rowdy rowdyism rowel rower rowing rowlock royal royalism royalist royalty roystonea rozelle rpa-abb rpm rtlt ru ruanda rub rub-a-dub rubato rubber rubber-necking rubberneck rubbernecker rubbing rubbish rubble rubdown rube rubefacient rubel rubella rubens rubeola rubia rubiaceae rubiales rubicelle rubicon rubidium rubinstein ruble rubor rubric rubus ruby ruck rucksack ruckus ruction rudapithecus rudbeckia rudd rudder rudderfish rudderpost rudderstock ruddiness ruddle ruddles rudeness rudiment rudiments rudra rue ruefulness ruf ruff ruffian ruffianism ruffle rug ruga rugby rugelach ruggedisation ruggedization ruggedness ruggelach rugger rugulah ruhr ruin ruination ruiner ruining rule ruler rulership ruling rum rum-blossom rumania rumanian rumansh rumba rumble rumbling rumen rumex ruminant ruminantia rumination ruminator rummage rummer rummy rumohra rumor rumormonger rumour rumourmonger rump rumpelstiltskin rumpus rumrunner run run-in run-through run- time run-up runabout runaway runch rundle rundown rundstedt rune rung runnel runner runner-up runniness running runoff runt runtiness runup runway runyon rupee rupert rupiah rupicapra rupicola ruptiliocarpon rupture rupturewort ruralism ruralist rurality ruritania ruritanian rus ruscaceae ruscus ruse rush rush-grass rushdie rusher rushing rushlight rushmore rusk ruskin russell russet russia russian russula russulaceae rust rustbelt rustic rustication rusticism rusticity rustiness rusting rustle rustler rustling rut ruta rutabaga rutaceae ruth ruthenium rutherford rutherfordium ruthfulness ruthlessness rutile rutilus rutland rutledge rv rwanda rwandan rya rydberg rye ryegrass rynchopidae rynchops rypticus ryukyuan s s-shape s.t.p. s.u.v. s/n sa saale saame saami saarinen saba sabah sabahan sabal sabaoth sabaton sabayon sabbat sabbatarian sabbath sabbatia sabbatical sabbatum sabellian saber sabertooth sabicu sabin sabine sabinea sable sabot sabotage saboteur sabra sabre sac sacagawea sacajawea saccade saccharase saccharide saccharin saccharinity saccharomyces saccharomycetaceae saccharose saccharum sacco saccule sacculus sacerdotalism saceur sachem sachet sachsen sack sackbut sackcloth sackful sacking saclant sacque sacrament sacramento sacredness sacrifice sacrificer sacrilege sacrilegiousness sacristan sacristy sacrum sadat saddam saddhu saddle saddleback saddlebag saddlebill saddlebow saddlecloth saddler saddlery sadducee sade sadhe sadhu sadism sadist sadleria sadness sadomasochism sadomasochist saek safaqis safar safari safe safe-conduct safe- deposit safebreaker safecracker safeguard safehold safekeeping safeness safety safety-deposit safflower saffranine saffron safranin safranine sag saga sagaciousness sagacity sagamore sage sagebrush sagina saginaw sagitta sagittaria sagittariidae sagittarius sagittate-leaf sago saguaro sahaptin sahaptino sahara saharan sahib sahuaro saida saiga saigon sail sailboat sailcloth sailfish sailing sailing-race sailmaker sailor sailor's-choice sailplane sailplaning saimiri sainfoin saint saint-bernard's-lily saint-john's-bread saint-mihiel saint-saens sainthood saintliness saintpaulia saipan sajama sakartvelo sake sakharov saki sakkara sakti saktism salaah salaam salaat salability salableness salaciousness salacity salad salade saladin salafism salah salai salal salamander salamandra salamandridae salami salary salat sale salem saleratus salerno saleroom sales salesclerk salesgirl saleslady salesman salesmanship salesperson salesroom saleswoman salian salicaceae salicales salicornia salicylate salience saliency salient salientia salientian salim salina saline salinger salinity salinometer salisbury salish salishan saliva salivation salix salk sallet sallow sallowness sally salmacis salmagundi salmi salmo salmon salmonberry salmonella salmonellosis salmonid salmonidae salmwood salol salome salomon salon salonica salonika saloon salp salpa salpichroa salpidae salpiglossis salpinctes salpingectomy salpingitis salpinx salsa salsify salsilla salsola salt saltation saltbox saltbush saltcellar salter saltine saltiness salting saltire saltpan saltpeter saltpetre saltshaker saltwater saltworks saltwort salubriousness salubrity saluki salutation salutatorian salutatory salute saluter salvador salvadora salvadoraceae salvadoran salvadorean salvadorian salvage salvager salvation salve salvelinus salver salvia salvinia salviniaceae salvinorin salvo salvor salwar salyut salzburg sam sama-veda saman samanala samara samarang samarcand samaria samaritan samarium samarkand samarskite samba sambar sambre sambuca sambucus sambur same samekh sameness samhita sami samia samiel samisen samite samizdat samnite samoa samoan samolus samosa samovar samoyed samoyede samoyedic sampan samphire sample sampler sampling samsara samson samuel samurai sana sana'a sanaa sanatarium sanatorium sanchez sanctification sanctimoniousness sanctimony sanction sanctitude sanctity sanctuary sanctum sand sandal sandalwood sandarac sandarach sandbag sandbagger sandbank sandbar sandberry sandblast sandblaster sandbox sandboy sandbur sandburg sander sanderling sandfish sandfly sandglass sandgrouse sandhi sandhopper sandiness sandlot sandman sandpaper sandpile sandpiper sandpit sandril sands sandspur sandstone sandstorm sandwich sandwichman sandwort saneness sanfoin sang sang-froid sangapenum sangaree sangay sanger sango sangoma sangraal sangria sanguification sanguinaria sanguine sanguineness sanguinity sanhedrin sanicle sanicula sanies sanitariness sanitarium sanitation sanitisation sanitization sanity sannup sannyasi sannyasin sansevieria sanskrit santa santalaceae santalales santalum santee santiago santims santolina santos sanvitalia sanyasi saone sap saphar saphead sapidity sapidness sapience sapindaceae sapindales sapindus sapir sapling sapodilla saponaria saponification saponin sapota sapotaceae sapote sapper sapphire sapphirine sapphism sappho sapporo sapraemia sapremia saprobe saprolegnia saprolegniales saprolite sapropel saprophyte sapsago sapsucker sapwood saqqara saqqarah saquinavir saraband saracen sarafem saragossa sarah sarajevo saran sarape sarasota sarasvati saratoga saratov sarawak sarawakian sarazen sarcasm sarcenet sarcobatus sarcocephalus sarcochilus sarcocystidean sarcocystieian sarcocystis sarcodes sarcodina sarcodine sarcodinian sarcoidosis sarcolemma sarcoma sarcomere sarcophaga sarcophagus sarcophilus sarcoplasm sarcoptes sarcoptid sarcoptidae sarcorhamphus sarcoscyphaceae sarcosine sarcosomataceae sarcosome sarcosporidia sarcosporidian sarcostemma sarcostyle sard sarda sardegna sardina sardine sardinia sardinian sardinops sardis sardius sardonyx saree sargasso sargassum sargent sari sarin sarnoff sarong saroyan sarpanitu sarpedon sarracenia sarraceniaceae sarraceniales sars sarsaparilla sarsenet sartor sartorius sartre sas sash sashay sashimi saskatchewan saskatoon sasquatch sass sassaby sassafras sassenach sassing sat satan satang satanism satanist satanophobia satchel satchmo sateen satellite satiation satie satiety satin satinet satinette satinleaf satinpod satinwood satire satirist satisfaction satisfactoriness satisfier satori satrap satsuma saturation saturday satureia satureja saturn saturnalia saturnia saturniid saturniidae saturnism satyagraha satyr satyriasis satyridae sauce sauce-alone sauceboat saucepan saucepot saucer sauciness saudi sauerbraten sauerkraut sauk saul sauna saunter saunterer saurel sauria saurian saurischia saurischian sauromalus sauropod sauropoda sauropodomorpha sauropterygia saurosuchus saururaceae saururus saury sausage saussure saussurea saute sauteing sauterne sauternes savage savageness savagery savanna savannah savant savara savarin save save-all saveloy saver savin saving savings savior saviour savitar savoir-faire savonarola savor savoriness savoring savorlessness savory savour savouring savourlessness savoury savoy savoyard savvy saw sawan sawbill sawbones sawbuck sawdust sawfish sawfly sawhorse sawm sawmill sawpit sawtooth sawwort sawyer sax saxe saxe-coburg-gotha saxe-gothea saxegothea saxhorn saxicola saxifraga saxifragaceae saxifrage saxist saxitoxin saxon saxony saxophone saxophonist say say-so sayanci sayda sayeret sayers saying sayonara sayornis sazerac sb sba sbe sbw sc scab scabbard scabicide scabies scabiosa scabious scablands scad scads scaffold scaffolding scag scalability scalage scalar scalawag scald scale scalenus scaler scaliness scaling scallion scallop scallopine scallopini scallywag scalp scalpel scalper scam scammer scammony scammonyroot scamp scamper scampi scampo scan scandal scandalisation scandalization scandalmonger scandalmongering scandalousness scandentia scandinavia scandinavian scandium scanner scanning scansion scantiness scantling scantness scanty scape scapegoat scapegrace scaphiopus scaphocephaly scaphopod scaphopoda scaphosepalum scapula scapular scapulary scar scarab scarabaean scarabaeid scarabaeidae scarabaeus scaramouch scaramouche scarceness scarcity scardinius scare scarecrow scaremonger scarer scarf scarface scarfpin scaridae scarlatina scarlet scarp scartella scat scathe scatology scatophagy scatter scatterbrain scattergood scattergun scattering scaup scauper scavenger scd sceliphron sceloglaux sceloporus scenario scenarist scene scene-stealer scenery sceneshifter scent scepter sceptic scepticism sceptre scet schadenfreude schaffneria schedule scheduler scheduling scheele scheelite schefflera scheldt schema schematic schematisation schematization scheme schemer schemozzle schenectady scheol scherzo scheuchzeriaceae schiaparelli schiller schilling schinus schipperke schism schist schistorrhachis schistosoma schistosomatidae schistosome schistosomiasis schizachyrium schizaea schizaeaceae schizanthus schizocarp schizogony schizoid schizomycetes schizopetalon schizophragma schizophrenia schizophrenic schizophyceae schizophyta schizopoda schizosaccharomyces schizosaccharomycetaceae schizothymia schleiden schlemiel schlep schlepper schlesien schlesinger schliemann schlimazel schlock schlockmeister schlumbergera schmaltz schmalz schmear schmeer schmegegge schmidt schmo schmoose schmooze schmoozer schmuck schnabel schnapps schnaps schnauzer schnecken schnittlaugh schnitzel schnook schnorchel schnorkel schnorrer schnoz schnozzle schoenberg scholar scholarship scholastic scholasticism scholia scholiast scholium schomburgkia schonbein schonberg school schoolbag schoolbook schoolboy schoolchild schoolcraft schooldays schoolfellow schoolfriend schoolgirl schoolhouse schooling schoolma'am schoolman schoolmarm schoolmaster schoolmate schoolmistress schoolroom schoolteacher schooltime schoolwork schoolyard schooner schopenhauer schorl schottische schrod schrodinger schtick schtickl schtik schtikl schubert schulz schumann schumann-heink schumpeter schutzstaffel schwa schwann schwarzwald schweitzer schweiz sciadopityaceae sciadopitys sciaena sciaenid sciaenidae sciaenops sciara sciarid sciaridae sciatica scid science scientist scientology scilla scimitar scincella scincid scincidae scincus scindapsus scintilla scintillation sciolism sciolist scion scipio scirpus scission scissors scissortail scissure sciuridae sciuromorpha sciurus sclaff sclera scleranthus scleredema sclerite scleritis scleroderma sclerodermataceae sclerodermatales sclerometer scleropages scleroparei scleroprotein sclerosis sclerotinia sclerotiniaceae sclerotium sclerotomy sclk scnt scoff scoffer scoffing scofflaw scoke scold scolder scolding scolion scoliosis scollop scolopacidae scolopax scolopendrium scolymus scolytidae scolytus scomber scomberesocidae scomberesox scomberomorus scombresocidae scombresox scombridae scombroid scombroidea sconce scone scoop scoopful scooter scope scopes scophthalmus scopolamine scopolia scorbutus scorch scorcher score scoreboard scorecard scorekeeper scorer scores scoria scoring scorn scorner scorpaena scorpaenid scorpaenidae scorpaenoid scorpaenoidea scorper scorpio scorpion scorpionfish scorpionida scorpionweed scorpius scorsese scorzonera scot scotch scotchman scotchwoman scoter scotland scotoma scots scotsman scotswoman scott scottie scottish scoundrel scour scourer scourge scourger scouring scours scouse scouser scout scouter scouting scoutmaster scow scowl scpo scrabble scrag scramble scrambler scranton scrap scrapbook scrape scraper scrapheap scrapie scraping scrapper scrappiness scrapple scraps scratch scratcher scratchiness scratching scratchpad scrawl scrawler scrawniness scream screamer screaming scree screech screecher screeching screed screen screener screening screenland screenplay screenwriter screw screwball screwballer screwbean screwdriver screwing screwtop screwup scriabin scribble scribbler scribe scriber scrim scrimmage scrimshanker scrimshaw scrip scripps script scriptorium scripture scriptwriter scrivener scrod scrofula scroll scrooge scrophularia scrophulariaceae scrophulariales scrotum scrounger scrub scrub-bird scrubber scrubbiness scrubbing scrubbird scrubland scrubs scruff scrum scrummage scrumpy scrunch scruple scruples scrupulousness scrutineer scrutiniser scrutinizer scrutiny scsi scuba scud scudding scuff scuffer scuffle scull sculler scullery sculling scullion sculpin sculptor sculptress sculpture sculpturer scum scumble scunner scup scupper scuppernong scurf scurrility scurry scurvy scut scutcheon scute scutellaria scutigera scutigerella scutigeridae scuttle scuttlebutt scyliorhinidae scylla scyphozoa scyphozoan scyphus scythe scythia scythian sd se sea sea-coast sea-duty sea-ear sea-poose sea-purse sea-puss sea-rocket seabag seabed seabird seaboard seaborg seaborgium seacoast seafarer seafaring seafood seafowl seafront seagrass seagull seahorse seal sealant sealer sealing sealskin sealyham seam seaman seamanship seamount seamster seamstress seanad seance seaplane seaport seaquake search searcher searchlight searobin seascape seashell seashore seasickness seaside seasnail season seasonableness seasonal seasoner seasoning seat seatbelt seating seats seattle seawall seaward seawater seaway seaweed seaworthiness seb sebastiana sebastodes sebastopol sebe seborrhea sebs sebum sec secale secant secateurs secernment secession secessionism secessionist sechuana seckel seclusion secobarbital seconal second second-in-command second- rater second-stringer secondary seconder secondment secondo secotiaceae secotiales secpar secrecy secret secretaire secretariat secretariate secretary secretaryship secretase secreter secretin secretion secretiveness secretor sect sectarian sectarianism sectarist sectary section sectional sectionalisation sectionalism sectionalization sector sectral secular secularisation secularism secularist secularization secundigravida secureness securer security sedalia sedan sedateness sedation sedative sedative-hypnotic seder sedge sediment sedimentation sedition sedna seducer seduction seductress sedulity sedulousness sedum see seed seedbed seedcake seedcase seeder seediness seedling seedman seedpod seedsman seedtime seeger seeing seek seeker seeking seeland seemliness seepage seer seersucker seesaw segal segment segmentation segno segovia segregate segregation segregationism segregationist segregator segue segway seiche seidel seigneur seigneury seignior seigniorage seigniory seine seism seismogram seismograph seismography seismologist seismology seismosaur seismosaurus seiurus seizer seizing seizure sekhet selachian selachii selaginella selaginellaceae selaginellales selar selcraig selection selectivity selectman selector selectwoman selenarctos selene selenicereus selenipedium selenium selenolatry selenology seles seleucus self self-abasement self- abnegation self-absorption self-abuse self-accusation self-aggrandisement self- aggrandizement self-analysis self-annihilation self-assertion self-assertiveness self-assurance self-awareness self-centeredness self-command self-complacency self-concern self-condemnation self-confidence self-consciousness self- contemplation self-contradiction self-control self-criticism self-cultivation self-deceit self-deception self-defence self-defense self-denial self- depreciation self-destruction self-determination self-digestion self-direction self-discipline self-discovery self-disgust self-distrust self-doubt self-drive self-education self-effacement self-esteem self-examination self-expression self-feeder self-fertilisation self-fertilization self-flagellation self- fulfillment self-government self-gratification self-hatred self-heal self-help self-hypnosis self-importance self-improvement self-incrimination self- inductance self-induction self-indulgence self-insurance self-interest self- justification self-knowledge self-loader self-love self-mortification self- organisation self-organization self-pity self-pollination self-portrait self- possession self-praise self-preservation self-pride self-protection self- punishment self-realisation self-realization self-reformation self-regard self- reliance self-renewal self-renunciation self-reproach self-reproof self-respect self-restraint self-rule self-sacrifice self-satisfaction self-seeker self- seeking self-service self-starter self-stimulation self-sufficiency self- suggestion self-torment self-torture self-will self-worship self-worth selfishness selflessness selfsameness seljuk selkirk selkup sell seller sellers selling selloff sellotape sellout selma selsyn seltzer selva selvage selvedge selznick semanticist semantics semaphore semarang semasiology semblance semen semester semi semi-abstraction semi-climber semiautomatic semibreve semicentenary semicentennial semicircle semicolon semicoma semiconductor semiconsciousness semidarkness semidesert semidiameter semiepiphyte semifinal semifinalist semifluidity semigloss semimonthly seminar seminarian seminarist seminary seminole seminoma semiology semiotician semiotics semiparasite semipro semiprofessional semiquaver semite semitic semitone semitrailer semitrance semitransparency semitropics semivowel semiweekly semolina sempatch sempiternity sempstress sen senate senator senatorship send-off sendee sender sending sendup sene seneca senecio senefelder senega senegal senegalese senescence seneschal senhor senility senior seniority seniti senna sennacherib sennenhunde sennett sennit senor senora senorita sens sensation sensationalism sensationalist sense senselessness sensibility sensibleness sensing sensitisation sensitiser sensitising sensitive sensitiveness sensitivity sensitization sensitizer sensitizing sensitometer sensor sensorium sensualism sensualist sensuality sensualness sensuousness sent sente sentence sentience sentiency sentiment sentimentalisation sentimentalism sentimentalist sentimentality sentimentalization sentinel sentry seoul sep sepal separability separate separateness separation separationism separationist separatism separatist separator separatrix sephardi sepia sepiidae sepiolite seppuku sepsis sept septation septectomy september septenary septet septette septicaemia septicemia septillion septobasidiaceae septobasidium septuagenarian septuagesima septuagint septum sepulcher sepulchre sepulture sequel sequela sequella sequenator sequence sequencer sequestration sequin sequoia sequoiadendron sequoya sequoyah seraglio serail serape seraph serax serb serbia serbian serbo-croat serbo-croatian serdica serenade serendipity sereness serengeti serenity serenoa serer serf serfdom serfhood serge sergeant sergeant-at-law serger serial serialisation serialism serialization sericocarpus sericterium serictery sericulture sericulturist seriema series serif serigraph serigraphy serin serine serinus seriocomedy seriola serious-mindedness seriousness seriph seriphidium seriphus serjeant serjeant-at-arms serjeant-at-law serkin sermon sermoniser sermonizer serologist serology serosa serotine serotonin serow serpasil serpens serpent serpent-worship serpentes serra serranid serranidae serranus serrasalmus serratia serration serratula serratus sertraline sertularia sertularian serum serval servant serve server service serviceability serviceableness serviceberry serviceman services servicing serviette servility serving servitor servitude servo servomechanism servosystem serzone sesame sesamoid sesamum sesbania seseli sesotho sesquicentennial sesquipedalia sesquipedalian sesquipedality sess session sessions sestet set set-back set-to seta setaria setback seth setline setoff seton setophaga setscrew setswana sett settee setter setterwort setting settle settlement settler settling settlings settlor setubal setup seurat sevastopol seven seven-spot seven-up sevener sevens sevensome seventeen seventeenth seventh seventies seventieth seventy seventy-eight severalty severance severeness severing severity severn sevilla seville sewage seward sewellel sewer sewerage sewing sex sexagenarian sexcapade sexiness sexism sexist sexlessness sexploitation sexpot sext sextant sextet sextette sextillion sexton sextuplet sexuality seychelles seychellois seyhan seymour sezession sfax sforzando sg sgml sgraffito sha'ban shaaban shabbiness shabu shabuoth shack shackle shad shad-flower shadberry shadblow shadbush shaddock shade shades shadflower shadfly shadiness shading shadow shadowboxing shadower shadowgraph shadowiness shadowing shaft shag shagbark shagginess shaggymane shah shahadah shahaptian shaheed shahn shaitan shake shake-up shakedown shakeout shaker shakers shakespeare shakespearean shakespearian shakeup shakiness shaking shako shakspere shakti shaktism shaktist shale shall-flower shallon shallot shallow shallowness shallu shalwar sham shaman shamanism shamash shamble shambles shambling shame shamefacedness shamefulness shamelessness shamisen shammer shammy shampoo shamrock shamus shan shandy shandygaff shang shanghai shanghaier shangri-la shank shankar shannon shanny shantung shanty shantytown shape shape- up shapelessness shapeliness shaper shaping shapley shard share share-out sharecropper shareholder shareholding shareowner sharer shareware shari sharia shariah sharing shark sharkskin sharksucker sharp sharp-sightedness sharpener sharper sharpie sharpness sharpshooter sharpy shasta shastan shattering shave shaver shavian shaving shavous shavuot shavuoth shaw shawl shawm shawn shawnee shawny shawwal shay shaytan she-devil she-goat she-oak sheaf shear shearer shearing shears shearwater sheatfish sheath sheathing shebang shebat shebeen shed shedder shedding sheen sheeny sheep sheep-tick sheepcote sheepdog sheepfold sheepherder sheepishness sheepman sheeprun sheepshank sheepshead sheepshearing sheepskin sheepwalk sheesha sheet sheeting sheetrock sheffield shegetz sheik sheika sheikdom sheikh sheikha sheikhdom shekel shekels sheldrake shelduck shelf shelfful shell shell-flower shellac shellbark sheller shelley shellfire shellfish shellflower shelling shelter shelterbelt shelver shem shema shemozzle shen-pao shenanigan shenyang shepard shepherd shepherdess sheraton sherbert sherbet sherd sheridan sheriff sherlock sherman sherpa sherrington sherry sherwood shetland shevat shevchenko shf shi'ite shia shiah shiatsu shibah shibboleth shield shielder shielding shift shifter shiftiness shifting shiftlessness shigella shigellosis shih-tzu shiism shiitake shiite shikoku shiksa shikse shill shillalah shillelagh shilling shillyshally shiloh shim shimmer shimmy shin shina shinbone shindig shindy shine shiner shingle shingler shingles shingling shingon shininess shining shinleaf shinney shinny shinpad shinplaster shinto shintoism shintoist ship ship-breaker shipbuilder shipbuilding shipload shipmate shipment shipowner shipper shipping shipside shipway shipworm shipwreck shipwright shipyard shiraz shire shirer shirker shirking shirring shirt shirtdress shirtfront shirting shirtlifter shirtmaker shirtsleeve shirtsleeves shirttail shirtwaist shirtwaister shisha shit shite shithead shitlist shittah shitter shittim shittimwood shitting shitwork shiv shiva shivah shivaism shivaist shivaree shiver shivering shlemiel shlep shlepper shlimazel shlock shlockmeister shmaltz shmear shmegegge shmo shmooze shmuck shnook shnorrer shoal shoat shock shocker shockley shoddiness shoddy shoe shoe- shop shoebill shoebird shoeblack shoebox shoeful shoehorn shoelace shoemaker shoemaking shoes shoeshine shoestring shoetree shofar shogi shogun shogunate shoji shona shoo-in shoofly shook shoot shoot-'em-up shoot-down shooter shooting shootout shop shopaholic shopfront shophar shopkeeper shoplifter shoplifting shopper shopping shopwalker shopwindow shore shorea shorebird shoreline shoring short short-grass short-stop shortage shortbread shortcake shortcoming shortcut shortener shortening shortfall shortgrass shorthand shorthorn shortia shortlist shortness shorts shortsightedness shortstop shoshone shoshonean shoshoni shoshonian shostakovich shot shote shotgun shoulder shout shouter shouting shove shove-ha'penny shove-halfpenny shovel shovelboard shoveler shovelful shovelhead shoveller shover show show-off show-stopper showboat showcase showdown shower showerhead showgirl showiness showing showjumping showman showmanship showpiece showplace showroom showstopper showtime shrapnel shred shredder shreveport shrew shrewdness shrewishness shrewmouse shriek shrieking shrift shrike shrilling shrillness shrimp shrimp-fish shrimper shrimpfish shrine shrink shrink-wrap shrinkage shrinking shroud shrovetide shrub shrubbery shrublet shrug shtick shtickl shtik shtikl shtup shua shuck shucks shudder shudra shuffle shuffleboard shuffler shuffling shufti shumac shunning shunt shunter shut-in shutdown shute shuteye shutout shutter shutterbug shutting shuttle shuttlecock shwa shy shylock shyness shyster si sial sialadenitis sialia sialidae sialis sialolith siam siamang siamese sian sib sibelius siberia siberian sibilant sibilation sibine sibling sibyl siccative sichuan sicilia sicilian sicily sick sickbag sickbay sickbed sickeningness sickle sicklepod sickness sickroom sida sidalcea siddhartha siddons side side-glance side-look side-wheeler side-whiskers sidebar sideboard sideburn sidecar sidekick sidelight sideline siderite sideritis sideroblast siderocyte sideropenia siderophilin siderosis sidesaddle sideshow sideslip sidesman sidesplitter sidestep sidestroke sideswipe sidetrack sidewalk sidewall sidewinder siding sidney sidon sids siege siegfried siemens sienna sierra siesta sieve sif sifter sifting sigeh sigh sight sightedness sighting sightlessness sightreader sights sightseeing sightseer sigint sigma sigmodon sigmoidectomy sigmoidoscope sigmoidoscopy sign signage signal signal-to-noise signal/noise signaler signaling signalisation signalization signaller signalman signatory signature signboard signer signet significance signification signified signifier signing signior signor signora signore signorina signory signpost sigurd sigyn sihasapa sika sikh sikhism sikkim sikorsky silage sild sildenafil silence silencer silene silents silenus silesia silex silhouette silica silicate silicide silicle silicon silicone silicosis siliqua silique silk silkgrass silkiness silks silkscreen silkweed silkwood silkworm sill sillabub sillaginidae sillago silliness sills silly silo siloxane silphium silt siltstone silurian silurid siluridae siluriformes silurus silva silvan silvanus silver silver-bush silver-lace silver-tip silver-worker silverback silverberry silverbush silverfish silverpoint silverrod silverside silversides silversmith silverspot silverstein silversword silvertip silvervine silverware silverweed silverwork silverworker silvex silvia silviculture silybum sima simal simarouba simaroubaceae simazine simenon simeon simian similarity simile similitude simmer simmering simmpleness simnel simoleons simon simoniz simony simoom simoon simper simperer simple simpleness simpleton simplicity simplification simplism simpson simulacrum simulation simulator simulcast simuliidae simulium simultaneity simultaneousness simvastatin sin sinai sinanthropus sinapis sinapism sinatra sinbad sincerity sinciput sinclair sind sindhi sine sinecure sinequan sinew sinfulness sing-kwa singalong singan singapore singaporean singe singer singhalese singing single single-foot single-leaf single-mindedness single- spacing singleness singles singlestick singlet singleton singsong singular singularity singultus sinhala sinhalese sinistrality sinitic sink sinker sinkhole sinkiang sinking sinlessness sinner sinning sinningia sino-tibetan sinologist sinology sinoper sinopia sinopis sinornis sinuosity sinuousness sinus sinusitis sinusoid sion siouan sioux sip sipah-e-sahaba siphon siphonaptera siphonophora siphonophore sipper sipuncula sipunculid siqueiros sir sirach siracusa siraj-ud-daula sirc sirdar sire siren sirenia sirenian sirenidae siriasis siris sirius sirloin sirocco sirrah sirup sis sisal sise sisham siskin sison sissiness sissoo sissu sissy sister sister-in-law sisterhood sistership sistrurus sisyphus sisyridae sisyrinchium sit-down sit-in sit-up sita sitar sitcom site sitka sitophylus sitotroga sitsang sitta sitter sittidae sitting situation sitwell sium siva sivaism sivan sivapithecus siwan six six-footer six- gun six-pack six-shooter six-spot sixer sixpack sixpence sixsome sixteen sixteenth sixth sixth-former sixties sixtieth sixty sixty-fourth sixty-nine size sizeableness sizing sizzle sjaelland sk-ampicillin skag skagerak skagerrak skagit skagway skanda skank skate skateboard skateboarder skateboarding skater skating skaw skeat skedaddle skeet skeg skein skeleton skep skepful skeptic skepticism sketch sketchbook sketcher sketchiness skewer skewness ski ski-plane skiagram skiagraph skiagraphy skibob skid skidder skidpan skier skiff skiffle skiing skill skillet skilletfish skillfulness skilly skim skimmer skimming skin skin-dive skin-diver skincare skinflint skinful skinhead skinheads skink skinner skinnerian skinniness skinny skinny-dip skinny-dipper skip skipjack skipper skirl skirmish skirmisher skirret skirt skit skittishness skittle skittles skivvies skivvy skopje skoplje skua skuld skulduggery skulker skulking skull skullcap skullduggery skunk skunk-weed skunkbush skunkweed sky sky-blue skybox skycap skydiver skydiving skyhook skylab skylark skylight skyline skyrocket skysail skyscraper skywalk skyway skywriting sl slab slack slackening slacker slacking slackness slacks slag slagheap slain slalom slam slammer slander slanderer slang slanginess slanguage slant slant-eye slap slapper slapshot slapstick slash slasher slask slat slate slater slating slattern slatternliness slaughter slaughterer slaughterhouse slav slave slave-maker slaveholder slaveholding slaver slavery slavey slavic slavonic slaw slayer slaying sle sleaze sleaziness sled sledder sledding sledge sledgehammer sleekness sleep sleep-learning sleeper sleepiness sleeping sleeplessness sleepover sleepwalker sleepwalking sleepwear sleepyhead sleet sleeve sleigh sleight slenderness sleuth sleuthhound sleuthing slew slews slezsko slice slicer slicing slick slicker slickness slide slider slideway slight slightness slime sliminess slimness sling slingback slinger slinging slingshot slip slip-on slip-up slipcover slipknot slipover slippage slipper slipperiness slipperwort slipstick slipstream slipway slit sliver slivovitz slo-bid sloanea slob slobber slobberer sloe slogan sloganeer sloganeering slogger sloop slop slop-seller slope sloppiness slops slopseller slopshop slot sloth slothfulness slouch sloucher slough sloughing slovak slovakia sloven slovene slovenia slovenian slovenija slovenliness slow- wittedness slowcoach slowdown slowing slowness slowpoke slowworm sls slub sludge slug slugabed slugfest sluggard slugger sluggishness sluice sluicegate sluiceway slum slumber slumberer slumgullion slump slur slurry slush slut sluttishness slyboots slyness sm smack smacker smacking small small-arm smalley smallholder smallholding smallmouth smallness smallpox smaltite smarm smarminess smart smarta smarting smartness smash smash-up smasher smashing smattering smear smegma smell smelling smelt smelter smeltery smetana smew smidge smidgen smidgeon smidgin smilacaceae smilax smile smiledon smiler smiley smiling smilo smirch smirk smirker smitane smith smithereens smithy smock smocking smog smogginess smoke smokehouse smoker smokescreen smokestack smoking smolder smolensk smollett smooch smooching smooth smoothbark smoothbore smoother smoothhound smoothie smoothness smoothy smorgasbord smother smotherer smoulder smsgt smudge smuggler smuggling smugness smut smuts smuttiness smyrna smyrnium sn snack snacker snaffle snafu snag snail snail-flower snailfish snailflower snake snake-fish snake-head snakeberry snakebird snakebite snakeblenny snakefish snakefly snakehead snakeroot snakeweed snakewood snap snapdragon snapline snapper snappishness snapshot snare snarer snarl snarl-up snatch snatcher snead sneak sneaker sneakiness sneer sneerer sneeze sneezer sneezeweed sneezewort sneezing snellen snick snicker snickersnee sniff sniffer sniffle sniffler snifter snigger snip snipe snipefish sniper snippet snipping snips snit snitch snitcher snivel sniveler sniveling sniveller sno-cat snob snobbery snobbishness snobbism snoek snogging snood snook snooker snoop snooper snoopiness snoopy snoot snootiness snooze snore snorer snoring snorkel snorkeling snort snorter snorting snot snout snow snow-blindness snow-in-summer snow-on-the-mountain snowball snowbank snowbell snowberry snowbird snowblindness snowboard snowboarder snowboarding snowcap snowdrift snowdrop snowfall snowfield snowflake snowman snowmobile snowplough snowplow snowshoe snowstorm snowsuit snp snub snuff snuff-color snuff-colour snuffbox snuffer snuffers snuffle snuffler snug snuggery snuggle snuggling snugness so so-and-so soak soakage soaker soaking soap soap-rock soap-weed soapberry soapbox soapfish soapiness soaprock soapstone soapsuds soapweed soapwort soar soaring soave sob sobbing soberness sobersides sobralia sobriety sobriquet socage soccer sociability sociable sociableness social socialisation socialiser socialising socialism socialist socialite sociality socialization socializer socializing society socinian socinus sociobiologist sociobiology sociolinguist sociolinguistics sociologist sociology sociometry sociopath sock socket sockeye socle socrates sod soda sodalist sodalite sodality sodbuster soddy sodium sodoku sodom sodomist sodomite sodomy sofa soffit sofia soft-cover soft-shoe softback softball softener softening softheartedness softie softness software softwood softy sogginess soh soho soil soiling soilure soiree soissons soixante-neuf soja sojourn sojourner sokoro sol solace solacement solan solanaceae solandra solanopteris solanum solarisation solarium solarization solder solderer soldering soldier soldier-fish soldierfish soldiering soldiership soldiery sole solea solecism soledad soleidae soleirolia solemness solemnisation solemnity solemnization solenichthyes solenidae solenogaster solenogastres solenoid solenopsis solenostemon solent soleus solfa solfege solfeggio solferino solicitation solicitor solicitorship solicitousness solicitude solid solidago solidarity solidification solidifying solidity solidness solidus soliloquy solingen solipsism solitaire solitariness solitary soliton solitude solitudinarian solleret solmisation solmization solo soloist solomon solomon's-seal solomons solon solresol solstice solubility solubleness solute solution solvability solvate solvation solvay solvency solvent solver solving solzhenitsyn som soma somaesthesia somaesthesis somali somalia somalian soman somataesthesis somateria somatesthesia somatosense somatotrophin somatotropin somatotype somberness sombreness sombrero somebody someone somersault somersaulting somerset somesthesia somesthesis somewhere somite somme sommelier somnambulation somnambulism somnambulist somniloquism somniloquist somniloquy somnolence somrai son son-in-law sonant sonar sonata sonatina sonchus sondheim sone song songbird songbook songfulness songhai songster songstress songwriter sonnet sonneteer sonny sonogram sonograph sonography sonometer sonora sonority sonorousness sontag soochong sooner soot sooth soothsayer soothsaying sootiness sop soph sophism sophist sophisticate sophistication sophistry sophocles sophomore sophonias sophora sopor soporific soprano sops sorb sorbate sorbent sorbet sorbian sorbonne sorbus sorcerer sorceress sorcery sordidness sordino sore sorehead soreness sorensen sorex sorgho sorghum sorgo soricidae sorority sorption sorrel sorriness sorrow sorrower sorrowfulness sort sorter sortie sorting sortition sorus sos sot soteriology sothis sotho sottishness sou sou'-east sou'-sou'-east sou'-sou'-west sou'-west sou'easter sou'wester souari soubise soubrette soubriquet souchong soudan souffle soufflot souk soul soul- searching soulfulness sound soundboard soundbox sounder sounding soundlessness soundman soundness soundtrack soup soup-fin soup-strainer soupcon soupfin soupiness soupspoon sour sourball source sourdine sourdough souring sourness sourpuss soursop sourwood sousa sousaphone souse sousing souslik sousse soutache soutane south southeast southeaster southeastward souther southerly southerner southernism southernness southernwood southey southland southpaw southward southwest southwester southwestern southwestward soutine souvenir souvlaki souvlakia sovereign sovereignty soviet sovietism soviets sow sowbane sowbelly sowbread sower soweto soy soya soybean soymilk spa space space-time spacecraft spacefaring spaceflight spaceman spaceship spacesuit spacewalker spacing spaciousness spackle spade spadefish spadefoot spadeful spadework spadix spaghetti spaghettini spain spalacidae spalax spall spallanzani spallation spam spammer span spandau spandex spandrel spandril spangle spaniard spaniel spanish spank spanker spanking spanner spar sparaxis spare spareness sparer sparerib spareribs sparganiaceae sparganium sparge sparid sparidae spark sparker sparkle sparkleberry sparkler sparkling sparling sparmannia sparring sparrow sparseness sparsity sparta spartan spartina spartium spasm spasmolysis spasmolytic spassky spastic spasticity spat spatangoida spatchcock spate spathe spathiphyllum spatiality spatter spatterdock spattering spatula spavin spawl spawn spawner spaying speakeasy speaker speakerphone speakership speaking spear spear-point spearfish spearhead spearmint spearpoint spec special specialisation specialiser specialism specialist speciality specialization specializer specialness specialty speciation specie species specific specification specificity specifier specimen speciousness speck speckle specs spectacle spectacles spectacular spectator specter spectinomycin spectre spectrogram spectrograph spectrometer spectrometry spectrophotometer spectroscope spectroscopy spectrum speculation speculativeness speculator speculum speech speechifier speechlessness speechmaker speechmaking speechwriter speed speed-reading speedboat speeder speediness speeding speedometer speedskater speedup speedway speedwell speer speke spelaeologist spelaeology speleologist speleology spell spell-checker spellbinder spelldown speller spelling spelt spelter spelunker spencer spend-all spender spending spendthrift spengler spenser spergula spergularia sperm spermaceti spermatid spermatocele spermatocide spermatocyte spermatogenesis spermatophyta spermatophyte spermatozoan spermatozoid spermatozoon spermicide spermophile spermophilus sperry spewer spf sphacele sphacelotheca sphacelus sphaeralcea sphaeriaceae sphaeriales sphaerobolaceae sphaerocarpaceae sphaerocarpales sphaerocarpos sphaerocarpus sphagnales sphagnum sphalerite sphecidae sphecius sphecoid sphecoidea sphecotheres sphenion spheniscidae sphenisciformes spheniscus sphenodon sphenoid sphenopsida sphere sphericalness sphericity spherocyte spheroid spherometer spherule sphincter sphingid sphingidae sphinx sphygmomanometer sphyraena sphyraenidae sphyrapicus sphyrna sphyrnidae spic spica spiccato spice spiceberry spicebush spicemill spicery spiciness spick spicule spiculum spider spiderflower spiderwort spiegel spiegeleisen spiel spielberg spiff spigot spik spike spikelet spikemoss spikenard spile spill spillage spillane spiller spillikin spillikins spillover spillway spilogale spin spin-off spinach spinacia spinal spindle spindleberry spindlelegs spindleshanks spindrift spine spinel spinelessness spinet spininess spinmeister spinnability spinnaker spinnbarkeit spinner spinney spinning spinoza spinster spinsterhood spinus spiracle spiraea spiral spirant spiranthes spire spirea spirilla spirillaceae spirillum spirit spiritedness spiritism spiritlessness spirits spiritual spiritualisation spiritualism spiritualist spirituality spiritualization spiritualty spirochaeta spirochaetaceae spirochaetales spirochaete spirochete spirodela spirogram spirograph spirogyra spirometer spirometry spironolactone spirt spirula spirulidae spit spitball spite spitefulness spitfire spitsbergen spitter spitting spittle spittlebug spittoon spitz spitzbergen spiv spizella splash splash-guard splashboard splashdown splasher splashiness splashing splat splatter splattering splay splayfoot spleen spleenwort splendor splendour splenectomy splenitis splenius splenomegaly splice splicer splicing spliff spline splint splinter splintering splinters split split-pea splitsaw splitsville splitter splitworm splodge splotch splurge splutter spock spode spodoptera spodumene spoil spoilable spoilage spoilation spoiler spoiling spoilsport spokane spoke spokeshave spokesman spokesperson spokeswoman spoliation spondee spondias spondylarthritis spondylitis spondylolisthesis sponge spongefly sponger spongillafly sponginess spongioblast spongioblastoma sponsor sponsorship spontaneity spontaneousness spoof spook spool spoon spoonbill spoondrift spoonerism spoonfeeding spoonflower spoonful spoor sporangiophore sporangium sporanox spore spork sporobolus sporocarp sporophore sporophyl sporophyll sporophyte sporotrichosis sporozoa sporozoan sporozoite sporran sport sportfishing sportiveness sportscast sportscaster sportsman sportsmanship sportswear sportswoman sportswriter sporulation spot spot-weld spot-welder spot-welding spotlessness spotlight spots spotsylvania spotter spotting spouse spout spouter sprachgefuhl sprag spraguea sprain sprat sprawl sprawler sprawling spray sprayer spraying spread spreader spreadhead spreading spreadsheet sprechgesang sprechstimme spree sprig sprigger sprightliness sprigtail spring spring-cleaning springboard springbok springbuck springer springfield springiness springtail springtide springtime sprinkle sprinkler sprinkles sprinkling sprint sprinter sprit sprite sprites spritsail spritz spritzer sprocket sprog sprout sprouting spruce spruceness sprue spud spume spunk spur spurge spuriousness spurner spurring spurt sputnik sputter sputtering sputum spy spyeria spyglass spyhole spying spymaster spyware squab squabble squabbler squad squadron squalidae squalidness squall squalor squalus squama squamata squamule squanderer squandering squandermania square square- bashing square-rigger squareness squaretail squark squash squat squatina squatinidae squatness squatter squattiness squatting squaw squaw-bush squawbush squawk squawker squawroot squeak squeaker squeal squealer squeamishness squeegee squeezability squeeze squeezer squeezing squelch squelcher squib squid squiggle squill squilla squillidae squinch squint squint-eye squinter squire squirearchy squirm squirmer squirrel squirrelfish squirt squirter squish sr sravana srbija ss ssa sse sspe ssri sss ssw st.-bruno's-lily stab stabber stabile stabilisation stabiliser stability stabilization stabilizer stable stableboy stableman stablemate stableness stabling stabroek stachyose stachys stack stacker stacks stacte staddle stadium stael staff staffa staffer stag stage stagecoach stagecraft stagehand stager stagflation stagger staggerbush staggerer staggers staghead staghound staginess staging stagira stagirus stagnancy stagnation staidness stain stainability stainer staining stainless stair stair-carpet stair-rod staircase stairhead stairs stairway stairwell stake stakeholder stakeout stakes stalactite stalagmite stalemate staleness stalin stalinabad stalingrad stalinisation stalinism stalinist stalinization stalino stalk stalker stalking stalking-horse stall stalling stallion stalls stalwart stalwartness stamboul stambul stamen stamina stammel stammer stammerer stamp stampede stamper stance stanchion stand stand-down stand-in standard standard-bearer standardisation standardiser standardization standardizer standby standdown standee stander standing standish standoff standoffishness standpipe standpoint standstill stanford stanhope stanhopea stanislavsky stanley stanleya stannite stanton stanza stapedectomy stapelia stapes staph staphylaceae staphylea staphylinidae staphylococci staphylococcus staple staplegun stapler star star- duckweed star-glory star-of-bethlehem star-thistle starboard starch starches stardom stardust stare starer starets starfish starflower stargazer stargazing starkey starkness starlet starlight starling starr starship start start-off starter starting startle startup starvation starveling starving starwort stash stasis state statecraft statehouse stateliness statement stater stateroom statesman statesmanship stateswoman static statice statics statin station stationariness stationer stationery stationmaster stations statistic statistician statistics stator statuary statue statuette stature status statute staunchness staurikosaur staurikosaurus stavanger stave stay stay-at-home stayer stayman stays staysail std stead steadfastness steadiness steady steak steakhouse steal stealer stealing stealth stealthiness steam steamboat steamer steamfitter steaminess steamroller steamship stearin steatite steatocystoma steatopygia steatornis steatornithidae steatorrhea steed steel steele steelmaker steelman steelworker steelworks steelyard steen steenbok steep steeper steeple steeplechase steeplechaser steeplejack steepness steer steerage steerageway steerer steering steersman steffens steganography steganopus stegocephalia stegosaur stegosaurus steichen stein steinbeck steinberg steinbok steinem steiner steinman steinmetz steinway stela stele stelis stella stellaria steller stellite stem stem-winder stemma stemmatics stemmatology stemmer stench stencil stendhal stengel stenocarpus stenochlaena stenograph stenographer stenography stenopelmatidae stenopelmatus stenopterygius stenosis stenotaphrum stenotomus stenotus stent stentor step step-down step-in step-up stepbrother stepchild stepdaughter stepfather stephanion stephanomeria stephanotis stephead stephen stephenson stepladder stepmother stepparent steppe stepper steprelationship steps stepsister stepson steradian stercobilinogen stercolith stercorariidae stercorarius sterculia sterculiaceae stereo stereophony stereoscope stereoscopy stereospondyli stereotype sterileness sterilisation steriliser sterility sterilization sterilizer sterling stern sterna sterne sterninae sternness sternocleidomastoid sternotherus sternpost sternum sternutation sternutator sternutatory sternwheeler steroid sterol sterope stertor stethoscope stetson steuben stevedore stevens stevenson stevia stew steward stewardess stewardship stewart stewing stewpan sth sthene stheno stibnite stichaeidae sticherus stick stick-in-the-mud stickball sticker stickiness stickleback stickler stickpin sticktight stickup stickweed stictomys stictopelia stieglitz stiff stiffener stiffening stiffness stifle stifler stifling stigma stigmata stigmatic stigmatisation stigmatism stigmatist stigmatization stilbesterol stilbestrol stilboestrol stile stiletto still stillbirth stillness stillroom stilt stiltbird stilton stilwell stimulant stimulation stimulus sting stingaree-bush stinger stinginess stinging stingray stink stinkbird stinker stinkhorn stinkiness stinkpot stinkweed stint stinter stipe stipend stipendiary stippler stipulation stipule stir stirk stirrer stirring stirrup stitch stitcher stitchery stitching stitchwort stizidae stizolobium stizostedion stm stoat stob stochasticity stock stock-in-trade stock-take stock-taker stock-taking stockade stockbroker stockcar stocker stockfish stockholder stockholding stockholdings stockholm stockhorn stockinet stockinette stocking stockist stockjobber stockman stockpile stockpiling stockpot stockroom stocks stocktake stocktaker stocktaking stockton stockyard stodge stodginess stoep stogie stogy stoic stoichiometry stoicism stokehold stokehole stoker stokesia stokowski stole stolidity stolidness stolon stoma stomach stomachache stomacher stomate stomatitis stomatopod stomatopoda stomp stomper stone stone-face stone-root stonechat stonecress stonecrop stonecutter stoneface stonefish stonefly stonehenge stonemason stoner stoneroot stonewaller stonewalling stoneware stonework stonewort stoning stooge stool stoolie stoolpigeon stoop stooper stop stopcock stopes stopgap stoplight stopover stoppage stoppard stopper stopping stopple stops stopwatch storage storax store storefront storehouse storekeeper storeria storeroom storey stork storksbill storm storminess story storybook storyline storyteller stotinka stoup stout stoutheartedness stoutness stove stovepipe stovepiping stover stowage stowaway stowe stowing stp strabismus strabotomy strachey strad stradavarius straddle stradivari stradivarius strafe strafer straggle straggler straight straight-arm straightaway straightedge straightener straightforwardness straightjacket straightness strain strainer straining strait straitjacket straits strake strand strangeness stranger stranglehold strangler strangles strangling strangulation strap strapado straphanger strapless strappado strapper strasberg strasbourg strassburg stratagem strategian strategics strategist strategy stratford-on-avon stratford-upon-avon stratification stratigraphy stratocracy stratosphere stratum stratus strauss stravinsky straw strawberry strawboard strawflower strawman strawworm stray strayer streak streaker stream streambed streamer streaming streamlet streamliner streep street streetcar streetlight streetwalker streisand strekelia strelitzia strelitziaceae strength strengthener strengthening strenuosity strenuousness strep strepera strepsiceros strepsirhini streptobacillus streptocarpus streptococci streptococcus streptodornase streptokinase streptolysin streptomyces streptomycetaceae streptomycin streptopelia streptosolen streptothricin stress stressor stretch stretchability stretcher stretcher-bearer stretchiness stretching streusel strewing stria striation striatum strickland strickle strictness stricture stride stridence stridency strider stridor stridulation strife strigidae strigiformes strike strikebreaker strikebreaking strikeout striker striking strikingness strindberg string stringency stringer strings stringybark strip strip-jack-naked stripe striper stripes striping stripling stripper stripping striptease stripteaser striver striving strix strobe strobile strobilomyces strobilus stroboscope stroheim stroke stroking stroll stroller stroma stromateid stromateidae strombidae strombus strong-armer strongbox stronghold strongman strongroom strongylodon strontianite strontium strop strophanthin strophanthus stropharia strophariaceae strophe structuralism structure strudel struggle struggler strum struma strumpet strut struthio struthiomimus struthionidae struthioniformes strychnine strymon stuart stub stubbiness stubble stubbornness stubbs stucco stud studbook student studentship studhorse studio studiousness study studying stuff stuffer stuffiness stuffing stultification stumble stumblebum stumbler stump stumper stumping stumpknocker stunner stunt stuntedness stunting stupa stupe stupefaction stupid stupidity stupor sturdiness sturgeon sturmabteilung sturnella sturnidae sturnus stutter stutterer stuttgart stuyvesant sty stye style stylemark styler stylet stylisation stylishness stylist stylite stylization stylomecon stylophorum stylopodium stylostixis stylus stymie stymy styphelia stypsis styptic styracaceae styracosaur styracosaurus styrax styrene styrofoam styron styx suasion suaveness suavity sub sub-assembly sub-interval sub-test subaltern subbase subbing subclass subcommittee subcompact subconscious subconsciousness subcontinent subcontract subcontractor subculture subdeacon subdirectory subdivider subdivision subdominant subduction subduedness subduer subeditor subfamily subfigure subgenus subgroup subhead subheading subject subjection subjectiveness subjectivism subjectivist subjectivity subjoining subjugation subjugator subjunction subjunctive subkingdom sublease sublet sublieutenant sublimate sublimation sublimaze sublimity subluxation submarine submariner submaxilla submediant submenu submergence submerging submersible submersion submission submissiveness submitter submucosa subnormal subnormality suborder subordinate subordinateness subordination subornation suborner subpart subphylum subpoena subpopulation subprogram subrogation subroutine subscriber subscript subscription subsection subsequence subsequentness subservience subservientness subset subshrub subsidence subsidiarity subsidiary subsiding subsidisation subsidiser subsidization subsidizer subsidy subsistence subsister subsoil subspace subspecies substance substantiality substantialness substantiation substantive substation substitutability substitute substituting substitution substrate substratum substring substructure subsumption subsystem subterfuge subthalamus subtilin subtitle subtlety subtonic subtopia subtotal subtracter subtraction subtrahend subtreasury subtropics subularia subunit suburb suburbanite suburbia subvention subversion subversive subversiveness subverter subvocaliser subvocalizer subway subwoofer succade succedaneum succeeder success successfulness succession successiveness successor succinctness succinylcholine succor succorer succory succos succotash succoth succour succourer succuba succubus succulence succulency succulent succus succussion suck sucker suckerfish sucking suckling sucralfate sucrase sucre sucrose suction sudafed sudan sudanese sudation sudatorium sudatory sudbury suddenness sudoku sudor sudorific sudra suds sue suede suer suet suez sufferance sufferer suffering sufficiency suffix suffixation suffocation suffragan suffrage suffragette suffragism suffragist suffrutex suffusion sufi sufism sugar sugar-bush sugarberry sugarcane sugariness sugarloaf sugarplum suggester suggestibility suggestion sugi suharto suicide suidae suillus suisse suit suitability suitableness suitcase suite suiting suitor sukarno sukiyaki sukkoth suksdorfia sukur sula sulamyd sulawesi sulcus sulfa sulfacetamide sulfadiazine sulfamethazine sulfamethoxazole sulfamezathine sulfanilamide sulfapyridine sulfate sulfide sulfisoxazole sulfonamide sulfonate sulfonylurea sulfur sulidae sulindac sulk sulkiness sulky sulla sullenness sullivan sully sulpha sulphate sulphide sulphur sultan sultana sultanate sultriness sum sum-up sumac sumach sumatra sumatran sumer sumerian sumerology summarisation summarization summary summation summer summercater summercaters summerhouse summersault summerset summertime summit summoning summons sumner sumo sump sumpsimus sumpter sumptuosity sumptuousness sun sun-ray sun-worship sunbather sunbeam sunbelt sunberry sunblind sunblock sunbonnet sunburn sunburst sunchoke sundacarpus sundae sundanese sunday sunderland sundew sundial sundog sundown sundowner sundress sundries sundrops sunfish sunflower sung sunglass sunglasses sunhat sunlamp sunlight sunna sunnah sunni sunniness sunnite sunporch sunray sunrise sunroof sunroom sunrose sunscreen sunset sunshade sunshine sunshine-roof sunspot sunstone sunstroke sunsuit suntan suntrap sunup suomi sup super superabundance superannuation superbia superbug supercargo supercharger superciliousness supercilium superclass supercomputer superconductivity superego supererogation superfamily superfecta superfecundation superfetation superficiality superficies superfluity superfund supergiant supergrass superhet superhighway superinfection superintendence superintendent superior superiority superlative superload superman supermarket supermarketeer supermarketer supermex supermodel supermolecule supermom supernatant supernatural supernaturalism supernaturalness supernova supernumerary superorder superordinate superordination superoxide superpatriotism superphylum superposition superpower superscript superscription supersedure supersession superslasher superstar superstition superstrate superstratum superstring superstructure supersymmetry supertanker supertax supertitle supertonic supertwister supervention supervising supervision supervisor supination supinator supper suppertime supping supplanter supplanting supplejack supplement supplementation suppleness suppliant supplicant supplication supplier supply supplying support supporter supporting supposal supposition suppository suppressant suppresser suppression suppressor suppuration suprainfection suprarenalectomy supremacism supremacist supremacy suprematism suprematist supremo sur sura surbase surcease surcharge surcoat surd sureness surety surf surface surfacing surfactant surfbird surfboard surfboarder surfboarding surfboat surfeit surfer surffish surfing surfperch surfriding surge surgeon surgeonfish surgery suricata suricate surinam suriname surliness surmisal surmise surmontil surmounter surmullet surname surnia surplice surplus surplusage surprint surprisal surprise surpriser surprisingness surrealism surrealist surrebuttal surrebutter surrejoinder surrender surrenderer surrey surrogate surround surroundings surtax surtitle surtout surveillance survey surveying surveyor survival survivalist survivor surya sus susa susah susanna susceptibility susceptibleness sushi susian susiana suslik suspect suspender suspense suspension suspensor suspensory suspicion suspiciousness suspiration susquehanna sussex sustainability sustainer sustainment sustenance sustentation susurration susurrus sutherland sutler sutra suttee sutura suture suturing suv suva suzerain suzerainty svalbard svedberg svengali sverdrup sverige svizzera svoboda svr sw swab swabbing swad swag swage swagger swaggerer swaggie swagman swahili swain swainsona swale swallow swallowtail swallowwort swami swammerdam swamp swamphen swampland swan swan-flower swan-neck swanflower swank swanneck swansea swanson swap sward swarm swarthiness swash swashbuckler swashbuckling swastika swat swatch swath swathe swathing swatter sway swayer swazi swaziland swbs swbw swearer swearing swearword sweat sweatband sweatbox sweater sweating sweatpants sweats sweatshirt sweatshop sweatsuit swede sweden swedenborg swedish sweep sweep-second sweeper sweeping sweepstakes sweet sweetbread sweetbreads sweetbriar sweetbrier sweetener sweetening sweetheart sweetie sweetleaf sweetmeat sweetness sweetpea sweetsop swell swellhead swelling swertia swerve swerving swietinia swift swiftlet swiftness swig swill swilling swim swimmer swimmeret swimming swimsuit swimwear swinburne swindle swindler swine swineherd swing swinger swinging swingletree swipe swirl swish swiss switch switch-hitter switch-ivy switchblade switchboard switcher switcheroo switching switchman swither switzerland swivel swivet swiz swizzle swob swoon swoop swoosh swop sword sword-cut swordfish swordplay swordsman swordsmanship swordtail swot sybarite sycamore syconium sycophancy sycophant sydenham sydney syllabary syllabication syllabicity syllabification syllable syllabub syllabus syllepsis syllogiser syllogism syllogist syllogizer sylph sylva sylvan sylvanite sylvanus sylviidae sylviinae sylvilagus sylvine sylvite symbiosis symbol symbol-worship symbolatry symbolisation symboliser symbolising symbolism symbolist symbolization symbolizer symbolizing symbology symbololatry symmetricalness symmetry symonds symons sympathectomy sympathiser sympathizer sympathy sympatry symphalangus symphilid symphonist symphony symphoricarpos symphyla symphysion symphysis symphytum symplocaceae symplocarpus symploce symplocus symposiarch symposiast symposium symptom synaeresis synaesthesia synagogue synagrops synanceja synapse synapsid synapsida synapsis synaptomys syncarp syncategorem syncategoreme synchro synchrocyclotron synchroflash synchromesh synchroneity synchronicity synchronisation synchroniser synchronising synchronism synchronization synchronizer synchronizing synchronoscope synchrony synchroscope synchrotron synchytriaceae synchytrium syncopation syncopator syncope syncretism syncytium syndactylism syndactyly syndic syndicalism syndicalist syndicate syndication syndicator syndrome synecdoche synechia synentognathi synercus syneresis synergism synergist synergy synesthesia synezesis synge syngnathidae syngnathus syngonium synizesis synod synodontidae synonym synonymist synonymity synonymousness synonymy synopsis synoptics synovia synovitis synovium synset syntactician syntagm syntagma syntax synthesis synthesiser synthesist synthesizer synthetic synthetism syph syphilis syphilitic syphon syracuse syria syrian syringa syringe syrinx syrrhaptes syrup system systematics systematisation systematiser systematism systematist systematization systematizer systemiser systemizer systole syzygium syzygy szechuan szechwan szell szent-gyorgyi szilard t t'ien-ching t-bar t-bill t-junction t-man t-network t-scope t-shirt t-square t.b. ta ta'ziyeh taal tab tabanidae tabard tabasco tabbouleh tabby tabernacle tabernacles tabernaemontana tabes tabi tabis tablature table tableau tablecloth tablefork tableland tablemate tablespoon tablespoonful tablet tabletop tableware tabloid taboo tabooli tabor tabora taboret tabour tabouret tabriz tabu tabuk tabulation tabulator tabun tacamahac tacca taccaceae tach tacheometer tachinidae tachistoscope tachogram tachograph tachometer tachycardia tachyglossidae tachyglossus tachygraphy tachylite tachymeter tachypleus taciturnity tacitus tack tacker tackiness tacking tackle tackler taco tacoma taconite tact tactfulness tactic tactician tactics tactility tactlessness tad tadalafil tadarida tadjik tadorna tadpole tadzhik tadzhikistan taegu taekwondo tael taenia taeniidae taffeta taffrail taffy taft tag tagalog tagalong tagamet tagasaste tageteste tagger tagliatelle tagore taguan tagus tahini tahiti tahitian tai taichi taichichuan taichung taif tail tail-flower tailback tailboard tailcoat tailfin tailflower tailgate tailgater tailing taillight tailor tailor-made tailorbird tailoring tailpiece tailpipe tailplane tailrace tails tailspin tailstock tailwind tailwort taint taipan taipeh taipei taira taiwan taiwanese taiyuan tajik tajiki tajikistan taka takahe takakkaw take take-in take-up takeaway takedown takelma takeoff takeout takeover taker takilman takin taking takings tala talapoin talaria talbot talc talcum tale taleban talebearer talent talentlessness taleteller taliban talien talinum talipes talipot talisman talk talkativeness talker talkie talking talks tall tall-grass tallahassee tallapoosa tallboy tallchief talleyrand tallgrass tallin tallinn tallis tallith tallness tallow tally tallyman talmud talon talpidae talus talwin tam tam-o'-shanter tam-tam tamale tamandu tamandua tamanoir tamarack tamarao tamarau tamaricaceae tamarillo tamarin tamarind tamarindo tamarindus tamarisk tamarix tambac tambala tambocor tambour tambourine tamburlaine tameness tamer tamerlane tamias tamiasciurus tamil tamm tammany tammerfors tammuz tammy tamoxifen tamp tampa tampax tamper tampere tampering tampico tampion tampon tamponade tamponage tamus tan tanacetum tanach tanager tanakh tanbark tancred tandearil tandem tandoor tandy tanekaha taney tang tanga tanganyika tange tangelo tangency tangent tangerine tangibility tangibleness tangier tangiers tanginess tangle tanglebush tango tangor tangram tangshan tanguy tank tanka tankage tankard tanker tankful tannenberg tanner tannery tannia tannin tanning tannoy tanoan tansy tantaliser tantalite tantalization tantalizer tantalum tantalus tantilla tantra tantrism tantrist tantrum tanzania tanzanian tanzim tao taoiseach taoism taoist taos tap tap-off tapa tape tapeline tapenade taper tapering tapestry tapeworm taphephobia taphouse taping tapioca tapir tapiridae tapirus tapis tapotement tappa tappan tapper tappet tapping taproom taproot taps tapster tar tar-wood tara tarabulus taracahitian taradiddle tarahumara taraktagenos taraktogenos tarantella tarantelle tarantino tarantism tarantula tarawa tarawa-makin taraxacum tarbell tarboosh tardigrada tardigrade tardiness tare target tarheel taricha tariff tarkovsky tarmac tarmacadam tarn tarnish taro tarot tarp tarpan tarpaulin tarpon tarquin tarquinius tarradiddle tarragon tarriance tarrietia tarsal tarsier tarsiidae tarsioidea tarsitis tarsius tarsus tart tartan tartar tartarus tartary tartlet tartness tartrate tartu tartufe tartuffe tarweed tarwood tarzan tashkent tashmit tashmitum tashunca-uitco task taskent taskmaster taskmistress tasman tasmania tasse tassel tasset tasso taste taste-maker taste-tester tastebud tastefulness tastelessness taster tastiness tasting tat tatahumara tatar tatary tate tater tati tatou tatouay tatter tatterdemalion tatting tattle tattler tattletale tattoo tatu tatum tau taunt taunting tauon taupe taurine tauromachy taurotragus taurus tautness tautog tautoga tautogolabrus tautology tavern taw tawdriness tawney tawniness tawse tax tax-exempt tax-increase taxability taxaceae taxales taxation taxer taxi taxicab taxidea taxidermist taxidermy taxidriver taximan taximeter taxis taxistand taxiway taxman taxodiaceae taxodium taxon taxonomer taxonomist taxonomy taxophytina taxopsida taxpayer taxus tay tay-sachs tayalic tayassu tayassuidae taylor tayra tazicef tb tbilisi tbit tc tce tchad tchaikovsky tchotchke tchotchkeleh tcp tcp/ip tdt te tea tea-strainer teaberry teacake teacart teach teach-in teacher teachership teaching teacup teacupful teahouse teak teakettle teakwood teal team teammate teamster teamwork teapot tear tearaway teardrop tearfulness teargas tearing tearjerker tearoom tears teasdale tease teasel teaser teashop teasing teasle teaspoon teaspoonful teat teatime teazel tebaldi tebet tebibit tebibyte tec tech techie technetium technical technicality technician technicolor technique techno technobabble technocracy technocrat technologist technology technophile technophilia technophobe technophobia tecophilaeacea tectaria tectona tectonics tecumseh tecumtha ted teddy tediousness tedium tee teemingness teen teenager teens teeoff teepee teeter teeter-totter teeterboard teetertotter teeth teething teetotaler teetotaling teetotalism teetotalist teetotaller teetotum teff tefillin teflon teg tegu tegucigalpa tegument teheran tehran teiid teiidae teju tekki tektite telamon telanthera telco telecast telecaster telecasting telecom telecommerce telecommunication telecommuting teleconference teleconferencing telefilm telegnosis telegram telegraph telegrapher telegraphese telegraphist telegraphy telekinesis telemann telemark telemarketing telemeter telemetry telencephalon teleologist teleology teleost teleostan teleostei telepathist telepathy telephone telephoner telephonist telephony telephoto telephotograph telephotography teleportation teleprinter teleprocessing teleprompter telerobotics telescope telescopium telescopy teleselling telethermometer teletypewriter televangelism televangelist television teleworking telex telfer telferage telint teliospore tell teller tellima telling telltale tellurian telluride tellurium tellus telly telomerase telomere telopea telophase telosporidia telpher telpherage telsontail telugu temazepam temblor temerity temnospondyli temp temper tempera temperament temperance temperateness temperature tempering tempest tempestuousness templar template temple templet templetonia tempo temporal temporalis temporality temporalty temporariness temporary temporiser temporizer tempra temptation tempter temptingness temptress tempura temuco temujin ten ten-spot ten-strike ten-thousandth tenability tenableness tenaciousness tenacity tenancy tenant tenantry tench tendency tendentiousness tender tenderfoot tendergreen tenderheartedness tenderisation tenderiser tenderization tenderizer tenderloin tenderness tending tendinitis tendon tendonitis tendosynovitis tendrac tendril tenebrionid tenebrionidae tenement tenerife tenesmus tenet tenge tenia tenner tennessean tennessee tenniel tennis tenno tennyson tenon tenonitis tenor tenoretic tenorist tenormin tenoroon tenosynovitis tenpence tenpin tenpins tenpounder tenrec tenrecidae tense tenseness tensimeter tensiometer tension tensity tensor tent tent-fly tentacle tentaculata tenter tenterhook tenth tenthredinidae tenting tentmaker tentorium tenuity tenure tepal tepee tephrosia tepic tepidity tepidness tequila tera terabit terabyte teraflop terahertz teras teratogen teratogenesis teratology teratoma terazosin terbinafine terbium terce tercel tercelet tercentenary tercentennial tercet terebella terebellidae terebinth teredinid teredinidae teredo terence teres teresa tereshkova tergiversation tergiversator teriyaki term termagant termer termes terminal termination terminator terminology terminus termite termitidae terms tern ternary ternion terpene terpsichore terpsichorean terrace terrain terramycin terrapene terrapin terrarium terreplein terribleness terrier terrietia terrine territorial territorialisation territoriality territorialization territory terror terrorisation terrorism terrorist terrorization terry terrycloth terseness tertiary tertigravida tertry tertullian terylene terzetto tesla tessella tessellation tessera tesseract tessin test test-cross testa testacea testacean testament testate testator testatrix testcross testee tester testicle testiere testifier testimonial testimony testiness testing testis testosterone testudinata testudines testudinidae testudo tet tetanilla tetanus tetany tetartanopia tetchiness tete-a-tete teth tether tetherball tethyidae tethys teton tetra tetrabromo- phenolsulfonephthalein tetracaine tetrachlorethylene tetrachloride tetrachloroethylene tetrachloromethane tetraclinis tetracycline tetrad tetrafluoroethylene tetragon tetragonia tetragoniaceae tetragonurus tetragram tetragrammaton tetrahalide tetrahedron tetrahydrocannabinol tetrahymena tetraiodothyronine tetralogy tetrameter tetramethyldiarsine tetraneuris tetranychid tetranychidae tetrao tetraodontidae tetraonidae tetrapod tetrapturus tetrasaccharide tetraskele tetraskelion tetrasporangium tetraspore tetrazzini tetri tetrode tetrodotoxin tetrose tetroxide tetryl tetterwort tettigoniid tettigoniidae teucrium teuton teutonist tevere tevet tewkesbury texan texarkana texas text text-matching textbook textile texture th thackeray thaddaeus thai thailand thalamus thalarctos thalassaemia thalassemia thalassoma thales thalia thaliacea thalictrum thalidomide thalidone thallium thallophyta thallophyte thallus thalmencephalon thalweg thames thammuz thamnophilus thamnophis thanatology thanatophobia thanatopsis thanatos thane thaneship thankfulness thanks thanksgiving tharp thatch thatcher thatcherism thatcherite thaumatolatry thaumaturge thaumaturgist thaumaturgy thaw thawing thb thc thd thea theaceae theanthropism theater theatergoer theatre theatregoer theatrical theatricality theban thebe thebes theca thecodont thecodontia theelin theft theia theism theist thelarche thelephoraceae thelypteridaceae thelypteris theme themis themistocles then thenar theobid theobroma theocracy theodicy theodolite theodosius theogony theologian theologiser theologist theologizer theology theophany theophrastaceae theophrastus theophylline theorem theoretician theorisation theoriser theorist theorization theorizer theory theosophism theosophist theosophy theoterrorism therapeutic therapeutics theraphosidae therapist therapsid therapsida therapy theravada there theremin thereness theresa theridiid theridiidae therm thermal thermalgesia thermel thermidor thermion thermionics thermistor thermoacidophile thermobia thermocautery thermochemistry thermocoagulation thermocouple thermodynamics thermoelectricity thermogram thermograph thermography thermogravimeter thermogravimetry thermohydrometer thermojunction thermometer thermometrograph thermometry thermopile thermoplastic thermopsis thermopylae thermoreceptor thermoregulator thermos thermosphere thermostat thermostatics thermotherapy thermotropism theropod theropoda thesaurus theseus thesis thespesia thespian thespis thessalia thessalian thessalonian thessalonica thessaloniki thessaly theta thetis theurgy thevetia thiabendazole thiamin thiamine thiazide thiazine thibet thick thick- knee thickener thickening thicket thickhead thickness thief thielavia thievery thieving thievishness thigh thigh-slapper thighbone thill thimble thimbleberry thimbleful thimblerig thimbleweed thimerosal thing thing-in-itself thingamabob thingamajig thingmabob thingmajig things thingumabob thingumajig thingummy think thinker thinking thinner thinness thinning thiobacillus thiobacteria thiobacteriaceae thiocyanate thiodiphenylamine thioguanine thiopental thioridazine thiosulfil thiotepa thiothixene thiouracil third third- dimensionality third-rater thirst thirster thirstiness thirteen thirteenth thirties thirtieth thirty thirty-second thirty-something thistle thistledown thlaspi thm tho thole tholepin thomas thomism thomomys thompson thomson thong thor thoracentesis thoracocentesis thoracotomy thorax thorazine thoreau thorite thorium thorium-228 thorn thornbill thorndike thorniness thornton thoroughbred thoroughfare thoroughness thoroughwort thorpe thorshavn thortveitite thoth thou thought thought-image thought-reader thoughtfulness thoughtlessness thousand thousandth thrace thracian thraco-phrygian thraldom thrall thralldom thrash thrasher thrashing thraupidae thread thread-fish threader threadfin threadfish threads threadworm threat three three-bagger three-d three-decker three- dimensionality three-fourths three-hitter three-quarters threepence threescore threesome threnody threonine thresher threshing threshold threskiornis threskiornithidae thrift thriftiness thriftlessness thriftshop thrill thriller thrinax thrip thripid thripidae thrips throat throatwort throb throbbing throe throes thrombasthenia thrombectomy thrombin thrombocyte thrombocytopenia thrombocytosis thromboembolism thrombokinase thrombolysis thrombolytic thrombopenia thrombophlebitis thromboplastin thrombosis thrombus throne throng throstle throttle throttlehold throttler throttling throughput throughway throw throw-in throw-weight throwaway throwback thrower throwster thrum thrush thrust thruster thrusting thruway thryothorus thucydides thud thug thuggee thuggery thuja thujopsis thule thulium thumb thumbhole thumbnail thumbnut thumbprint thumbscrew thumbstall thumbtack thump thumping thunbergia thunder thunderbird thunderbolt thunderclap thundercloud thunderer thunderhead thundershower thunderstorm thunk thunnus thurber thurible thurifer thuringia thursday thus thwack thwart thwarter thwarting thylacine thylacinus thylogale thyme thymelaeaceae thymelaeales thymidine thymine thymol thymosin thymus thyreophora thyreophoran thyrocalcitonin thyroglobulin thyroid thyroidectomy thyroiditis thyromegaly thyronine thyroprotein thyrotoxicosis thyrotrophin thyrotropin thyroxin thyroxine thyrse thyrsopteris thyrsus thysanocarpus thysanopter thysanoptera thysanopteron thysanura thysanuron thz ti tia tiamat tianjin tiara tiarella tib tiber tiberius tibet tibetan tibeto-burman tibia tibialis tibicen tibit tibur tic tic-tac-toe tical tichodroma tichodrome ticino tick tick-tack- toe tick-weed ticker ticket ticket-of-leave ticking tickle tickler tickling tickseed ticktack ticktacktoe ticktacktoo ticktock tickweed ticonderoga tictac tidbit tiddler tiddlywinks tide tideland tidemark tidewater tideway tidiness tidings tidy tidytips tie tie-in tie-up tieback tiebreaker tien-pao tientsin tiepin tiepolo tier tierce tiercel tiff tiffany tiffin tiflis tiger tigers tightening tightfistedness tightness tightrope tights tightwad tiglon tigon tigress tigris tijuana tike tilapia tilde tilden tile tilefish tiler tilia tiliaceae tiling tiliomycetes till tillage tillandsia tiller tilletia tilletiaceae tillich tilling tilt tilter tilth tiltyard timalia timaliidae timbale timber timberland timberline timberman timbre timbrel timbuktu time time-ball time-fuse time-out time-switch timecard timekeeper timekeeping timelessness timeline timeliness timepiece timer times timeserver timetable timework timgad timid timidity timidness timimoun timing timolol timor timorese timorousness timothy timpani timpanist timucu timur tin tin-plating tinamidae tinamiformes tinamou tinbergen tinca tincture tindal tindale tinder tinderbox tine tinea tineid tineidae tineoid tineoidea tineola tinfoil ting tinge tingidae tingle tingling tininess tinker tinkerer tinkle tinner tinning tinnitus tinplate tinsel tinsmith tinsnips tint tintack tinter tinting tintinnabulation tintometer tintoretto tinware tip tip-off tipi tipper tippet tipple tippler tipsiness tipstaff tipster tiptoe tiptop tipu tipuana tipulidae tirade tiramisu tirana tire tiredness tirelessness tiresias tiresomeness tiro tirol tirolean tisane tishri tisiphone tissue tit tit-tat-toe titan titaness titania titanium titanosaur titanosaurian titanosauridae titanosaurus titbit titer titfer tithe tither tithonia titi titian titillation titivation titlark title title-holder titmouse tito titration titrator titre titter titterer tittivation tittle tittle-tattle titty titus tiu tivoli tiyin tizzy tko tl tlc tlingit tm tmv tn tnf tnt to-do toad toad-in-the-hole toadfish toadflax toadshade toadstool toady toast toaster toasting toastmaster toastrack tobacco tobacconist tobago tobagonian tobey tobin tobit toboggan tobogganing tobogganist tobramycin toby tocainide tocantins toccata tocharian tocktact tocology tocopherol tocqueville tocsin tod toda today todd toddler toddy todea todidae todus tody toe toe-in toea toecap toehold toenail toetoe toff toffee toffy tofieldia tofranil tofu toga togaviridae togetherness toggle togo togolese togs toil toiler toilet toiletry toilette toilsomeness toitoi tojo tokamak tokay toke token tokio toklas tokyo tolazamide tolazoline tolbooth tolbukhin tolbutamide tole tolectin toledo tolerance toleration tolinase tolkien toll tollbar tollbooth toller tollgate tollgatherer tollhouse tollkeeper tollman tollon tolmiea tolstoy toltec tolu toluene tolypeutes tom tom-tom tomahawk tomalley tomatillo tomato tomb tombac tombak tombaugh tombigbee tombola tomboy tomboyishness tombstone tomcat tome tomentum tomfool tomfoolery tomistoma tommyrot tomograph tomography tomorrow tompion tomtate tomtit ton tonality tone tone-beginning toner tonga tongan tongs tongue tongue-fish tongue-flower tongue-lashing tonguefish tongueflower tonic tonicity tonight tonnage tonne tonocard tonometer tonometry tons tonsil tonsilla tonsillectomy tonsillitis tonsure tontine tonus tool toolbox toolhouse toolmaker toolshed toon toona tooshie toot tooth toothache toothbrush toothpaste toothpick toothpowder toothsomeness toothwort tootle top top-up topaz topcoat tope topee topeka toper topgallant tophus topi topiary topic topicality topicalization topknot topmast topminnow topognosia topognosis topography topolatry topology toponomy toponym toponymy topos topper topping topsail topside topsoil topspin topsy-turvydom topsy-turvyness topv toque tor toradol torah torch torchbearer torchlight tore toreador torero torino torment tormenter tormentor tornado tornillo torodal toroid toronto torpedinidae torpediniformes torpedo torpidity torpidness torpor torque torquemada torr torrent torreon torreya torricelli torridity torsion torsk torso tort tort-feasor torte tortellini tortfeasor torticollis tortilla tortoise tortoiseshell tortoiseshell-cat tortricid tortricidae tortrix tortuosity tortuousness torture torturer torturing torus tory toscana toscanini tosh tosk toss toss-up tosser tossup tostada tot total totalisator totaliser totalism totalitarian totalitarianism totality totalizator totalizer totara tote totem totemism totemist toter totipotence totipotency totterer toucan toucanet touch touch-me-not touch-typist touchback touchdown toucher touchiness touching touchline touchscreen touchstone touchwood tough toughie toughness toulon toulouse toulouse-lautrec toupe toupee tour touraco tourer tourette tourism tourist touristry tourmaline tournament tournedos tourney tourniquet tours tourtiere tout touter tovarich tovarisch tow towage towboat towel toweling towelling tower towhead towhee towline town townee towner townes townie townsend townsendia townsfolk township townsman townspeople towny towpath towrope toxaemia toxemia toxicant toxicity toxicodendron toxicognath toxicologist toxicology toxin toxoid toxoplasmosis toxostoma toxotes toxotidae toy toying toynbee toyohashi toyon toyonaki toyota toyshop tpn tra-la tra-la-la trabecula trablous trace tracer tracery trachea tracheid tracheitis trachelospermum tracheobronchitis tracheophyta tracheophyte tracheostomy tracheotomy trachinotus trachipteridae trachipterus trachodon trachodont trachoma trachurus tracing track trackball tracker tracking tracklayer tract tractability tractableness tractarian tractarianism traction tractor tracy trad trade trade-in trade-last trade-off tradecraft trademark tradeoff trader tradescant tradescantia tradesman tradespeople trading tradition traditionalism traditionalist traditionality traducement traducer trafalgar traffic trafficator trafficker tragacanth tragedian tragedienne tragedy tragelaphus tragicomedy tragopan tragopogon tragulidae tragulus tragus trail trailblazer trailer trailhead trailing train trainband trainbandsman trainbearer trainee traineeship trainer training trainload trainman trainmaster trait traitor traitorousness traitress trajan trajectory tram tramcar tramline trammel tramontana tramontane tramp tramper trample trampler trampling trampoline tramway trance tranche trandate trandolapril tranquility tranquilizer tranquilliser tranquillity tranquillizer transactinide transaction transactions transactor transalpine transaminase transamination transcaucasia transcendence transcendency transcendentalism transcendentalist transcriber transcript transcriptase transcription transducer transduction transept transexual transfer transferability transferase transferee transference transferer transferor transferral transferrer transferrin transfiguration transformation transformer transfusion transgene transgression transgressor transience transiency transient transistor transit transition transitive transitiveness transitivity transitoriness translation translator transliteration translocation translucence translucency transmigrante transmigration transmission transmittal transmittance transmitter transmitting transmogrification transmutability transmutation transom transparence transparency transparentness transpiration transplant transplantation transplanter transplanting transponder transport transportation transporter transposability transpose transposition transposon transsexual transsexualism transshipment transubstantiation transudate transudation transvaal transvestism transvestite transvestitism transylvania tranylcypromine trap trapa trapaceae trapeze trapezium trapezius trapezohedron trapezoid trapper trapping trappings trappist trapshooter trapshooting trash trashiness trasimeno traubel trauma traumatology traumatophobia trautvetteria travail trave travel traveler traveling traveller travelling travelog travelogue traversal traverse traverser travesty trawl trawler tray trazodone treachery treacle tread tread- softly tread-wheel treadle treadmill treadwheel treason treasonist treasure treasurer treasurership treasury treat treater treatise treatment treaty treble trebuchet trebucket tree tree-frog tree-worship treehopper treelet treenail treetop trefoil treillage trek trekker trellis trema trematoda trematode tremble trembler trembles trembling tremella tremellaceae tremellales tremolite tremolo tremor trenail trench trenchancy trencher trencherman trend trend-setter trent trental trente-et-quarante trento trenton trepan trepang trephination trephine trephritidae trepidation treponema treponemataceae trespass trespasser tress trestle trestlework trevelyan trevino trevithick trews trey trf trh tri-chad tri-iodomethane tri-iodothyronine triacetate triad triaenodon triage triakidae trial trialeurodes triamcinolone triangle triangularity triangulation triangulum triassic triatoma triavil triazine triazolam tribade tribadism tribalisation tribalism tribalization tribe tribesman tribolium tribologist tribology tribonema tribonemaceae tribromoethanol tribromomethane tribulation tribulus tribunal tribune tribuneship tributary tribute tributyrin trice triceps triceratops trichechidae trichechus trichina trichiniasis trichinosis trichion trichiuridae trichloride trichlormethiazide trichloroethane trichloroethylene trichloromethane trichobezoar trichoceros trichodesmium trichodontidae trichoglossus tricholoma tricholomataceae trichomanes trichomonad trichomoniasis trichophaga trichophyton trichoptera trichopteran trichopteron trichostema trichostigma trichosurus trichotillomania trichotomy trichroism trichromacy trichuriasis trichys trick tricker trickery trickiness trickle trickster triclinium tricolor tricolour tricorn tricorne tricot tricycle tricyclic tridacna tridacnidae trident tridymite triennial trier trifle trifler trifling trifluoromethane trifoliata trifolium trifurcation trig triga trigeminal trigeminus trigger triggerfish triggerman triglidae triglinae triglochin triglyceride trigon trigonella trigonometrician trigonometry trigram triiodomethane triiodothyronine trike trilateral trilby trilisa trill trilliaceae trilling trillion trillionth trillium trilobite trilogy trim trimaran trimer trimester trimipramine trimmer trimming trimmings trimness trimorphodon trimox trimurti trine trinectes tringa trinidad trinidadian trinitarian trinitarianism trinitroglycerin trinitrotoluene trinity trinket trinketry trio triode triolein trionychidae trionyx triopidae triops triose triostium trioxide trip trip-up tripalmitin tripe triphammer triphosphopyridine triple triple-decker triple-spacing triplet tripletail tripleurospermum triplicate triplicity tripling triplochiton tripod tripoli tripos tripper triptych triquetral trireme trisaccharide triskaidekaphobia triskele triskelion trismus trisomy tristan tristearin tristram trisyllable tritanopia triteness tritheism tritheist triticum tritium tritoma triton triturus triumph triumvir triumvirate trivet trivia triviality trivium trm trna trochanter troche trochee trochilidae trochlear trochlearis trogium troglodyte troglodytes troglodytidae trogon trogonidae trogoniformes troika trojan troll troller trolley trolleybus trolling trollius trollop trollope trombicula trombiculiasis trombiculid trombiculidae trombidiid trombidiidae trombone trombonist trompillo trondheim troop trooper troops troopship tropaeolaceae tropaeolum trope trophobiosis trophoblast trophotropism trophozoite trophy tropic tropicbird tropics tropidoclonion tropism troponomy troponym troponymy tropopause troposphere trot troth trotline trotsky trotskyism trotskyist trotskyite trotter trou-de-loup troubadour trouble troublemaker troubler troubleshooter troublesomeness trough trouncing troupe trouper trouser trousering trousseau trout trove trowel troy truancy truant truce truck truckage trucker trucking truckle truckler truckling truculence truculency trudge trudger true truelove trueness truffaut truffle truism truman trumbo trumbull trump trumpery trumpet trumpet-wood trumpeter trumpetfish trumpets trumpetwood trumping truncation truncheon truncocolumella trundle trunk trunkfish trunks trunnel truss trust trustbuster trustee trusteeship truster trustfulness trustiness trustingness trustor trustworthiness trusty truth truthfulness try try-on tryout trypetidae trypsin trypsinogen tryptophan tryptophane tryst tsa tsar tsarina tsaritsa tsaritsyn tsatske tsetse tsh tshatshke tshiluba tsimshian tsine tsoris tsouic tss tsuga tsunami tsuris tsushima tswana tt tuareg tuatara tub tub-cart tub-thumper tuba tubbiness tube tubeless tuber tuberaceae tuberales tubercle tubercular tubercularia tuberculariaceae tuberculin tuberculosis tuberose tuberosity tubful tubing tubman tubocurarine tubule tubulidentata tucana tuchman tuck tuckahoe tucker tucker-bag tucket tucson tudor tudung tues tuesday tufa tuff tuffet tuft tug tug-of-war tugboat tugela tugger tughrik tugrik tuileries tuille tuition tularaemia tularemia tulestoma tulip tulipa tulipwood tulle tully tulostoma tulostomaceae tulostomataceae tulostomatales tulsa tulu tum tumble tumble-dryer tumblebug tumbler tumbleweed tumbling tumbrel tumbril tumefaction tumescence tumidity tumidness tummy tumor tumour tums tumult tumultuousness tumulus tun tuna tunaburger tundra tune tune-up tunefulness tuner tung tunga tungstate tungsten tungus tungusic tunguska tunguz tunic tunica tunicata tunicate tuning tunis tunisia tunisian tunker tunnage tunnel tunney tunny tup tupaia tupaiidae tupek tupelo tupi tupi-guarani tupik tupinambis tuppence tupungatito tupungato turaco turacou turakoo turban turbatrix turbellaria turbidity turbidness turbinal turbinate turbine turbofan turbogenerator turbojet turboprop turbot turbulence turbulency turcoman turd turdidae turdinae turdus tureen turf turfan turgenev turgidity turgidness turgor turgot turin turing turk turk's-cap turkestan turkey turki turkic turkish turkistan turkmen turkmenia turkmenistan turko-tatar turkoman turkomen turmeric turmoil turn turn-on turnabout turnaround turnbuckle turncoat turncock turndown turner turnery turnicidae turning turnip turnix turnkey turnoff turnout turnover turnpike turnround turnspit turnstile turnstone turntable turnup turnverein turp turpentine turpin turpitude turps turquoise turreae turret turritis tursiops turtle turtledove turtlehead turtleneck turtler tuscaloosa tuscan tuscany tuscarora tush tushery tusk tuskegee tusker tussah tussaud tusseh tusser tussilago tussle tussock tussore tussur tutankhamen tutee tutelage tutelo tutor tutorial tutorship tutsan tutsi tutti-frutti tutu tuvalu tux tuxedo tv tv-antenna twaddle twaddler twain twang twat twayblade tweak tweed tweediness tweet tweeter tweezer twelfth twelfthtide twelve twelvemonth twenties twentieth twenty twenty-eight twenty-five twenty- four twenty-nine twenty-one twenty-seven twenty-six twenty-three twenty-twenty twenty-two twerp twice-pinnate twiddle twiddler twig twilight twill twin twin- prop twin-propeller-plane twinberry twine twiner twinflower twinge twinjet twinkie twinkle twinkler twinkling twins twirl twirler twirp twist twister twisting twistwood twit twitch twitching twitter twitterer two two-bagger two- baser two-by-four two-dimensionality two-hitter two-piece two-seater two-step two-thirds two-timer twofer twopence twosome tx tyche tycoon tying tyiyn tyke tylenchidae tylenchus tylenol tyler tympan tympani tympanist tympanites tympanitis tympanoplasty tympanuchus tympanum tyndale tyndall tyne type typeface typescript typesetter typewriter typewriting typha typhaceae typhlopidae typhoeus typhoid typhon typhoon typhus typicality typification typing typist typo typographer typography typology tyr tyramine tyranni tyrannicide tyrannid tyrannidae tyrannosaur tyrannosaurus tyrannus tyranny tyrant tyre tyro tyrocidin tyrocidine tyrol tyrolean tyrosine tyrosinemia tyrothricin tyrr tyson tyto tytonidae tzar tzara tzarina tzetze u u-boat u-drive u-turn u.k. u.s. u.s.a. u308 uakari ubermensch ubiety ubiquinone ubiquitousness ubiquity ubykh uca uda udder udmurt udometer ufa ufo uganda ugandan ugaritic ugli ugliness ugrian ugric uhf uhland uighur uigur uintathere uintatheriidae uintatherium uk ukase uke ukraine ukrainian ukranian ukrayina ukulele ulaanbaatar ulalgia ulama ulanova ulatrophia ulcer ulceration ulema ulemorrhagia ulex ulfila ulfilas ulitis ull ullage ullr ulmaceae ulmus ulna ulster ulteriority ultima ultimacy ultimate ultimateness ultimatum ultracef ultracentrifugation ultracentrifuge ultraconservative ultramarine ultramicroscope ultramontane ultramontanism ultranationalism ultrasonography ultrasound ultrasuede ultraviolet ululation ulva ulvaceae ulvales ulvophyceae ulysses uma umayyad umbel umbellales umbellifer umbelliferae umbellularia umber umbilical umbilicus umbo umbra umbrage umbrella umbrellawort umbria umbrian umbrina umbundu umlaut umma ummah ump umpirage umpire un unabridged unacceptability unacceptableness unadaptability unaffectedness unai unalterability unambiguity unanimity unappetisingness unappetizingness unapproachability unassertiveness unassumingness unattainableness unattractiveness unau unavailability unavoidability unawareness unbalance unbecomingness unbelief unbeliever unboundedness unbreakableness unceremoniousness uncertainness uncertainty unchangeability unchangeableness unchangingness uncheerfulness uncial uncle uncleanliness uncleanness unclearness uncloudedness uncomfortableness uncommonness uncommunicativeness unconcern unconfessed uncongeniality unconnectedness unconscientiousness unconscious unconsciousness unconstraint unconventionality uncouthness uncovering uncreativeness unction unctuousness uncus undecagon undependability undependableness underachievement underachiever underbelly underbodice underbody underboss underbrush undercarriage undercharge underclass underclassman underclothes underclothing undercoat undercurrent undercut underdevelopment underdog underdrawers underestimate underestimation underevaluation underexposure underfelt underframe underfur undergarment undergrad undergraduate underground undergrowth underlay underlayment underline underling underlip undernourishment underpants underpart underpass underpayment underperformer underproduction underrating underreckoning underscore underseal undersecretary underseller undershirt undershrub underside underskirt undersoil understandability understanding understatement understructure understudy undersurface undertaker undertaking undertide undertone undertow undervaluation underwear underwing underwood underworld underwriter undesirability undesirable undies undine undiscipline undoer undoing undress undset undulation undutifulness unease uneasiness unemotionality unemployed unemployment unenlightenment unequivocalness unesco unevenness unexchangeability unexpectedness unfairness unfaithfulness unfamiliarity unfastener unfastening unfavorableness unfavourableness unfeasibility unfeelingness unfitness unfolding unfortunate unfriendliness ungainliness ungodliness ungracefulness ungraciousness ungratefulness unguent unguiculata unguiculate unguis ungulata ungulate unhappiness unhealthfulness unhealthiness unhelpfulness unholiness unhurriedness uniat uniate unicef unicorn unicycle unicyclist unification uniform uniformity uniformness unilateralism unilateralist unimportance uninitiate uninsurability unintelligibility uninterestingness unio union unionidae unionisation unionism unionist unionization uniqueness unison unit unitard unitarian unitarianism uniting unitisation unitization unity univalve universal universalism universality universe university unix unjustness unkemptness unkindness unknowing unknowingness unknown unlawfulness unlikelihood unlikeliness unlikeness unloading unmalleability unmanageableness unmanliness unmasking unmentionable unmercifulness unmindfulness unnaturalness unneighborliness unnilquadium unnoticeableness unobtrusiveness unoriginality unorthodoxy unpalatability unpalatableness unperceptiveness unpermissiveness unperson unpersuasiveness unpleasantness unpleasingness unpointedness unpopularity unpredictability unpretentiousness unproductiveness unprofitability unprofitableness unpropitiousness unprotectedness unq unquestionability unquestionableness unraveler unraveller unrealism unreality unreason unregularity unrelatedness unreliability unreliableness unrespectability unresponsiveness unrest unrestraint unrighteousness unruliness unsanctification unsanitariness unsatisfactoriness unsavoriness unscrupulousness unseasonableness unseemliness unseen unselfconsciousness unselfishness unsightliness unsimilarity unskillfulness unsnarling unsociability unsociableness unsolvability unsoundness unstableness unsteadiness unsuitability unsuitableness unsusceptibility untangling untermeyer unthoughtfulness untidiness untier untimeliness untouchable untrustiness untrustworthiness untruth untruthfulness untying untypicality ununbium ununhexium ununpentium ununquadium ununtrium unusefulness unusualness unvariedness unveiling unwariness unwellness unwholesomeness unwieldiness unwillingness unwiseness unworthiness unyieldingness up-bow up-tick up-to-dateness upanishad upbeat upbraider upbraiding upbringing upcast update updating updike updraft upending upgrade upheaval uphill upholder upholsterer upholstery upjohn upkeep upland uplift uplifting uplink upper upper-normandy uppercase uppercut uppishness uppityness uppp uppsala upright uprightness uprising uproar uprooter upsala upset upsetter upshot upside upsilon upstage upstager upstairs upstart upstroke upsurge uptake upthrow upthrust uptick uptime uptown upturn upupa upupidae ur uracil uraemia ural-altaic uralic urals uranalysis urania uraninite uranium uranologist uranology uranoplasty uranoscopidae uranus uranyl urarthritis urate uratemia uraturia urbana urbanisation urbanity urbanization urceole urchin urd urdu urea urease uredinales uremia ureter ureteritis ureterocele ureterostenosis urethane urethra urethritis urethrocele urex urey urga urge urgency urginea urging uria uriah urial uricaciduria urinal urinalysis urination urinator urine url urmia urn urobilin urobilinogen urocele urochesia urochezia urochord urochorda urochordata urochordate urocyon urocystis urodele urodella urodynia urokinase urolith urologist urology uropathy urophycis uropsilus uropygi uropygium urosaurus ursidae ursinia ursus urth urtica urticaceae urticales urticaria urtication urubupunga uruguay uruguayan urus us usa usability usableness usacil usaf usage usance usbeg usbek uscb usda use useableness used-car usefulness uselessness user ushas usher usherette using uskub usmc usn usnea usneaceae usps ussher ussr usss ustilaginaceae ustilaginales ustilaginoidea ustilago ustinov usualness usufruct usufructuary usuli usumbura usurer usurpation usurper usury ut ut1 uta utah utahan utahraptor utc ute utensil uterus utica utilisation utiliser utilitarian utilitarianism utility utilization utilizer utmost utn utnapishtim uto-aztecan utopia utopian utopianism utrecht utricle utricularia utriculus utrillo utterance utterer uttermost utterness utu utug uub uuh uup uuq uut uv uvea uveitis uvula uvularia uvulariaceae uvulitis uvulopalatopharyngoplasty ux. uxor uxoricide uxoriousness uygur uzbak uzbeg uzbek uzbekistan uzi v v-1 v-day v.p. va vac vacancy vacation vacationer vacationing vacationist vaccaria vaccina vaccinating vaccination vaccinator vaccine vaccinee vaccinia vaccinium vaccinum vacillation vacillator vacuity vacuolation vacuole vacuolisation vacuolization vacuousness vacuum vaduz vagabond vagabondage vagary vagina vaginismus vaginitis vaginocele vagrancy vagrant vagueness vagus vainglory vaisakha vaishnava vaishnavism vaisnavism vaisya vajra valance valdecoxib valdez valdosta vale valediction valedictorian valedictory valence valencia valenciennes valency valentine valerian valeriana valerianaceae valerianella valet valetta valetudinarian valetudinarianism valgus valhalla vali valiance valiancy validation validity validness valine valise valium valkyrie vallecula valletta valley vallisneria valmy valois valor valorousness valour valparaiso valsartan valse valuable valuableness valuation valuator value value-system valuelessness valuer values valve valvelet valvotomy valvula valvule valvulitis valvulotomy vambrace vamp vamper vampire vampirism van vanadate vanadinite vanadium vanbrugh vancocin vancomycin vancouver vanda vandal vandalism vanderbilt vandyke vane vanellus vanern vanessa vanguard vangueria vanilla vanillin vanir vanisher vanishing vanity vanquisher vantage vanuatu vanzetti vapidity vapidness vapor vaporing vaporisation vaporiser vaporization vaporizer vaporousness vapors vapour vapourousness vapours vaquero vaquita var var. vara varan varanidae varanus vardenafil varese vargas variability variable variableness variance variant variate variation varicella varicocele varicosis varicosity variedness variegation varietal variety variola variolation variolization variometer variorum varix varlet varment varmint varna varnish varnisher varro varsity varuna varus vas vasarely vasari vascularisation vascularity vascularization vasculitis vase vase-fine vasectomy vaseline vasoconstriction vasoconstrictive vasoconstrictor vasodilation vasodilative vasodilator vasomax vasopressin vasopressor vasosection vasotec vasotomy vasovasostomy vasovesiculitis vassal vassalage vastness vat vatican vaticination vaticinator vaudeville vaudevillian vaudois vaughan vault vaulter vaulting vaunt vaunter vaux vayu vcr vd vdu veadar veal veau veblen vector veda vedalia vedanga vedanta vedism vedist veering veery veg vega vegan vegetable vegetarian vegetarianism vegetation veggie vehemence vehicle veil veiling vein vela velar velazquez velban velcro veld veldt velleity vellication vellum velocipede velociraptor velocity velodrome velour velours veloute velum velveeta velvet velvet-leaf velveteen velvetleaf velvetweed vena venality venation vendee vendemiaire vender vendetta vending vendition vendor vendue veneer veneering venerability venerableness veneration venerator veneridae venesection venetia venetian veneto venezia venezia-euganea venezuela venezuelan vengeance vengefulness venice venipuncture venire venison venn venogram venography venom vent vent-hole ventail venter venthole ventilation ventilator venting ventner ventolin ventose ventricle ventriculus ventriloquism ventriloquist ventriloquy venture venturer venturesomeness venturi venue venula venule venus venushair veps vepse vepsian veracity veracruz veranda verandah verapamil veratrum verb verbalisation verbaliser verbalism verbalization verbalizer verbascum verbena verbenaceae verbesina verbiage verbolatry verboseness verbosity verdancy verdandi verdi verdicchio verdict verdigris verdin verdolagas verdun verdure verge verger vergil verification verifier verisimilitude verity verlaine vermeer vermicelli vermicide vermiculation vermiculite vermifuge vermilion vermin vermis vermont vermonter vermouth vernacular vernation verne verner vernier vernix vernonia verona veronal veronese veronica verpa verrazano verrazzano verruca versace versailles versant versatility verse versed versicle versification versifier version verso verst vertebra vertebrata vertebrate vertex verthandi vertical verticality verticalness verticil verticilliosis verticillium vertigo vertu vervain verve vervet verwoerd very-light vesalius vesey vesica vesicant vesicaria vesication vesicatory vesicle vesicopapule vesiculation vesiculitis vesiculovirus vespa vespasian vesper vespers vespertilio vespertilionid vespertilionidae vespid vespidae vespucci vespula vessel vest vesta vestal vestibule vestige vestiture vestment vestris vestry vestryman vestrywoman vesture vesuvian vesuvianite vesuvius vet vetch vetchling vetchworm veteran veterinarian veterinary vetluga veto vexation vexer vfw vhf vi viability viaduct viagra vial viand viands viatication viaticus vibe vibes vibist viborg vibraharp vibramycin vibrancy vibraphone vibraphonist vibration vibrato vibrator vibrio vibrion vibrissa viburnum vicar vicar-general vicarage vicariate vicarship vice vice-presidency vice-regent vicegerent vicereine viceroy viceroyalty viceroyship vichy vichyssoise vicia vicinity viciousness vicissitude vicksburg victim victimisation victimiser victimization victimizer victor victoria victorian victoriana victory victrola victual victualer victualler victuals vicugna vicuna vidal vidalia vidar video videocassette videodisc videodisk videotape vidua vienna vienne vientiane vieques vietnam vietnamese view viewer viewers viewfinder viewgraph viewing viewpoint vigee-lebrun vigil vigilance vigilante vigilantism vigna vignette vigor vigorish vigour vii viii viking vila vileness vilification vilifier villa villa-lobos village villager villahermosa villain villainage villainess villainousness villainy villard villein villeinage villoma villon villus vilna vilnius vilno vim viminaria vinaigrette vinblastine vinca vincetoxicum vincristine vindication vindicator vindictiveness vine vinegar vinegariness vinegarishness vinegarroon vinegarweed vinery vineyard vingt-et-un viniculture vinifera vinification vino vinogradoff vinson vintage vintager vintner vinyl vinylbenzene vinylite viocin viol viola violaceae violation violator violence violet violin violinist violist violoncellist violoncello viomycin viosterol vioxx vip viper vipera viperidae viracept viraemia virago viramune virazole virchow viremia vireo vireonidae virga virgil virgilia virgin virginal virginia virginian virginity virgo virgule viricide viridity virilisation virilism virility virilization virino virion viroid virologist virology virtu virtue virtuosity virtuoso virtuousness virucide virulence virulency virus virusoid vis-a-vis visa visage visayan viscaceae viscacha viscera viscidity viscidness viscometer viscometry visconti viscose viscosimeter viscosimetry viscosity viscount viscountcy viscountess viscounty viscousness viscum viscus vise vishnu vishnuism visibility visibleness visigoth vision visionary visit visitant visitation visiting visitor visken visor vista vistaril vistula visualisation visualiser visualization visualizer vitaceae vitalisation vitaliser vitalism vitalist vitality vitalization vitalizer vitalness vitals vitamin vitellus vithar vitharr vitiation viticulture viticulturist vitidaceae vitiligo vitis vitrectomy vitrification vitrine vitriol vittaria vittariaceae vituperation vitus viva vivacity vivaldi vivarium viverra viverricula viverridae viverrinae viverrine vividness vivification vivisection vivisectionist vixen viyella vizcaino vizier viziership vizor vizsla vladivostok vlaminck vldl vlf vocable vocabulary vocal vocalisation vocaliser vocalism vocalist vocalization vocalizer vocalizing vocation vocative vociferation vociferator vodka vodoun vogue vogul voice voicelessness voicemail voiceprint voicer voicing void voidance voider voiding voile vol-au-vent volaille volans volapuk volary volatile volatility volcanism volcano volcanology vole volga volgaic volgograd volition volkhov volley volleyball volt volt-ampere volta voltage voltaic voltaire voltaren volte-face voltmeter volubility volume volumeter voluminosity voluminousness volund voluntary volunteer voluptuary voluptuousness volute volution volva volvaria volvariaceae volvariella volvocaceae volvocales volvox volvulus vombatidae vomer vomit vomiter vomiting vomitive vomitory vomitus vonnegut voodoo voodooism voraciousness voracity vortex vorticella votary vote voter voting votyak vouchee voucher vouge voussoir vouvray vow vowel vower vox voyage voyager voyeur voyeurism voznesenski vroom vt vuillard vulcan vulcanisation vulcaniser vulcanite vulcanization vulcanizer vulcanology vulgarian vulgarisation vulgariser vulgarism vulgarity vulgarization vulgarizer vulgate vulnerability vulpecula vulpes vultur vulture vulva vulvectomy vulvitis vulvovaginitis w w.c. w.m.d. wa wabash wac wacko waco wad wadding waddle waddler wade wader waders wadi wading wads wafer waffle waffler waft wafture wag wage wager wagerer wages waggery waggishness waggle waggon waggoner waggonwright wagner wagnerian wagon wagon-lit wagoner wagonwright wagram wagtail wahabi wahabism wahhabi wahhabism wahoo wahunsonacock wahvey waif waikiki wail wailer wailing wain wainscot wainscoting wainscotting wainwright waist waistband waistcloth waistcoat waistline wait waite waiter waiting waitress waiver wajda wakashan wake wake-robin wakeboard wakefulness wakening waker waking walapai walbiri waldenses waldheim waldmeister wale wales walesa walhalla walk walk-in walk-on walk-through walk-up walkabout walkaway walker walkie-talkie walking walkingstick walkman walkout walkover walkway walky-talky wall wall-paperer wallaby wallace wallah wallboard wallenstein waller wallet walleye wallflower walloon walloons wallop walloper walloping wallow wallpaper wallpaperer wally walnut walpole walrus walter walton waltz waltzer wampanoag wampee wampum wampumpeag wan wanamaker wand wandala wanderer wandering wanderlust wandflower wane wangle wangler wangling waning wank wanker wannabe wannabee wanness want wanter wanton wantonness wapiti war waratah warble warbler warburg ward ward- heeler warden wardenship warder wardership wardress wardrobe wardroom ware warehouse warehouseman warehouser warehousing warfare warfarin warhead warhol warhorse wariness warji warlock warlord warlpiri warm-up warmer warmheartedness warming warmness warmonger warmongering warmth warner warning warp warpath warping warplane warragal warrant warrantee warranter warrantor warranty warren warrener warrigal warrior warsaw warship warszawa wart warthog wartime wartweed wartwort warwick wasabi wash wash-and-wear washables washbasin washboard washbowl washcloth washday washer washerman washerwoman washhouse washing washing-up washington washingtonian washout washrag washroom washstand washtub washup washwoman wasp wassail wassailer wassermann wastage waste waste-yard wastebasket wastebin wastefulness wasteland waster wastewater wasteweir wasteyard wasting wastrel watch watchband watchdog watcher watchfulness watching watchmaker watchman watchstrap watchtower watchword water water-color water- colour water-mint water-rate water-shield water-skiing water-target waterbird waterbuck waterbury watercannon watercolor watercolorist watercolour watercolourist watercourse watercraft watercress waterdog watered-silk waterer waterfall waterfinder waterford waterfowl waterfront watergate wateriness watering waterleaf waterlessness waterline waterloo waterman watermark watermeal watermelon waterpower waterproof waterproofing waters waterscape watershed waterside waterskin waterspout watertown waterway waterweed waterwheel waterworks wats watson watt watt-hour wattage watteau wattle wattmeter watts watusi watutsi waugh wausau wave wave-off waveband waveform wavefront waveguide wavelength wavelet wavell waver waverer wavering waviness waving waw wax wax- chandler waxberry waxflower waxiness waxing waxmallow waxwing waxwork waxycap way waybill wayfarer wayfaring wayland wayne ways wayside wb wbc wbn wbs weakener weakening weakfish weakling weakness weal weald wealth wealthiness weaning weapon weaponry wear wearable wearer weariness wearing weasel weather weatherboard weatherboarding weathercock weatherglass weatherliness weatherman weatherstrip weatherstripping weathervane weave weaver weaverbird weaving web webb webbing webcam weber webfoot webmaster webpage website webster webworm wed wedding wedge wedgie wedgwood wedlock wednesday wee weed weed-whacker weeder weedkiller weeds week weekday weekend weekender weekly weeknight weeness weenie weeper weepiness weeping weevil weewee weft wegener wei weigela weighbridge weigher weighing weight weightiness weighting weightlessness weightlift weightlifter weightlifting weil weill weimar weimaraner weinberg weir weird weirdie weirdness weirdo weirdy weisenheimer weismann weissbier weisshorn weizenbier weizenbock weizmann weka welcher welcome welcomer weld welder welding weldment welfare welkin well well-being well-wisher well-wishing wellbeing wellerism welles wellhead wellington wellness wellpoint wells wellspring welsh welsher welshman welt weltanschauung welter welterweight weltschmerz welty welwitschia welwitschiaceae wembley wen wen-ti wench wencher werewolf werfel wernicke weser wesley wesleyan wesleyanism wesleyism wessex west west-sider wester westerly western westerner westernisation westernization westinghouse westminster weston westward wet wet-nurse wetback wether wetland wetness wetnurse wetter wetting whack whacker whacking whacko whale whaleboat whalebone whaler whalesucker whammy whang wharf wharfage wharton whatchamacallit whatchamacallum whatnot whatsis wheal wheat wheat-grass wheatear wheatfield wheatflake wheatgrass wheatley wheatstone wheatworm wheedler wheedling wheel wheelbarrow wheelbase wheelchair wheeler wheelhouse wheeling wheelwork wheelwright wheeze wheeziness whelk whelp whereabouts wherefore wherewithal wherry whetstone whey whicker whidah whiff whiffer whiffletree whig while whim whimper whimsey whimsicality whimsy whin whinberry whinchat whine whiner whinny whinstone whip whip-round whip-scorpion whip-snake whipcord whiplash whipper whipper-in whippersnapper whippet whipping whippletree whippoorwill whipsaw whipsnake whipstitch whipstitching whiptail whir whirl whirlaway whirler whirligig whirling whirlpool whirlwind whirlybird whirr whirring whisk whisker whiskers whiskey whisky whisper whisperer whispering whist whistle whistle- blower whistleblower whistler whistling whit whit-tuesday white whitebait whitecap whitecup whiteface whitefish whitefly whitehall whitehead whitehorse whitelash whitener whiteness whitening whiteout whitetail whitethorn whitethroat whitewash whitewater whitewood whitey whiting whitlavia whitlow whitlowwort whitman whitmonday whitney whitsun whitsunday whitsuntide whittier whittle whittler whitweek whiz whiz-kid whizbang whizz whizz-kid whizzbang who whodunit whole wholeheartedness wholeness wholesale wholesaler wholesomeness whoop whoopee whooper whoosh whopper whore whoredom whorehouse whoremaster whoremonger whoreson whorl whorlywort whortleberry why whydah wi wicca wiccan wichita wick wickedness wicker wickerwork wicket wicket-keeper wickiup wickliffe wickup wiclif wicopy wide-body wideness widening widgeon widget widow widower widowhood widowman width wieland wiener wienerwurst wiesbaden wiesel wiesenboden wiesenthal wife wiffle wifi wig wigeon wigging wiggle wiggler wiggliness wight wigmaker wigner wigwam wikiup wild wildcat wildcatter wilde wildebeest wilder wilderness wildfire wildflower wildfowl wilding wildlife wildness wile wilfulness wiliness wilkes wilkins wilkinson will will-o'-the-wisp willamette willard willebrand willet willfulness williams williamstown willies willing willingness willis willow willow-pattern willowherb willowware willpower wilmington wilmut wilno wilson wilt wilting wilton wimble wimbledon wimp wimple win wince wincey winceyette winch winchester winckelmann wind windage windaus windbag windbreak windbreaker windburn windcheater winder windfall windflower windhoek windiness winding winding-clothes winding-sheet windjammer windlass windlessness windmill window window-washing windowpane windows windowsill windpipe windscreen windshield windsock windsor windstorm windtalker windup windward wine wine-colored wine-coloured wineberry wineglass winemaker winemaking winepress winery winesap wineskin winfred wing wing-nut wingback winger wingman wings wingspan wingspread wingstem wink winker winking winkle winnebago winner winning winnings winnipeg winnow winnowing wino winslow winsomeness winston-salem winter wintera winteraceae winterberry wintergreen wintertime wintun wipe wipeout wiper wire wire-puller wirehair wireless wireman wirer wiretap wiretapper wirework wireworm wiriness wiring wisconsin wisconsinite wisdom wise wiseacre wisecrack wiseness wisenheimer wisent wish wish-wash wishbone wishfulness wishing wisp wistaria wister wisteria wistfulness wit witch witch-hunt witch-hunter witchcraft witchery witchgrass witching withdrawal withdrawer withdrawnness withe withering withers witherspoon withholder withholding withstander withy witloof witness witnesser wits wittgenstein witticism wittiness wittol witwatersrand wivern wiz wizard wizardry wlan wmd wmo wnw woad woadwaxen wobble wobbler wobbly wodan wodehouse woden woe woefulness wog wok wold wolf wolfbane wolfe wolff wolffia wolffiella wolffish wolfhound wolfman wolfram wolframite wolfsbane wollaston wollastonite wollstonecraft wolof wolverine woman woman-worship womanhood womaniser womanishness womanizer womankind womanlike womanliness womb wombat won wonder wonderberry wonderer wonderfulness wonderland wonderment wonk wont wonton wood wood-creeper wood-fern wood-frog wood-rat woodbine woodborer woodbury woodcarver woodcarving woodchuck woodcock woodcraft woodcreeper woodcut woodcutter woodenness woodenware woodfern woodgrain woodgraining woodhewer woodhull woodiness woodland woodlet woodlouse woodman woodpecker woodpile woodruff woods woodscrew woodshed woodsia woodsiness woodsman woodward woodwardia woodwaxen woodwind woodwork woodworker woodworking woodworm wooer woof woofer wooing wool woolen woolf woolgatherer woolgathering woollcott woollen woolley woolsorter woolworth wop worcester worcestershire word word-painter word-painting word- splitting word-worship wordbook wordfinder wordiness wording wordmonger wordnet wordplay words wordsmith wordsworth work work-board work-clothes work-clothing work-in work-shirt workaholic workaholism workbag workbasket workbench workboard workbook workbox workday worker workfellow workflow workforce workhorse workhouse working workingman workings workload workman workmanship workmate workout workpiece workplace workroom works worksheet workshop workspace workstation worktable workwear workweek world world-beater world-weariness worldliness worldling worm wormcast wormhole wormseed wormwood worrier worriment worry worrying worrywart worse worsening worship worshiper worshipper worst worsted wort worth worthiness worthlessness worthwhileness worthy wotan wouk wound wounded wounding wow wpm wrack wraith wrangle wrangler wrangling wrap wraparound wrapper wrapping wrasse wrath wreath wreck wreckage wrecker wreckfish wrecking wren wren-tit wrench wrester wrestle wrestler wrestling wretch wretchedness wrick wriggle wriggler wright wring wringer wrinkle wrist wristband wristlet wristwatch writ write-down write-in write-off writer writing writings wroclaw wrong wrongdoer wrongdoing wrongfulness wrongness wrymouth wryneck wsw wtc wto wtv wu wuerzburg wuhan wulfenite wulfila wurlitzer wurtzite wurzburg wuss wv www wy wyat wyatt wycherley wyclif wycliffe wye wyeth wykeham wykehamist wyler wylie wynette wynfrith wynnea wyoming wyomingite wyrd wyszynski wytensin wyvern x x-axis x-radiation x-ray x-raying x-scid xanax xanthate xanthelasma xanthemia xanthine xanthium xanthoma xanthomatosis xanthomonad xanthomonas xanthophyceae xanthophyl xanthophyll xanthopsia xanthorrhoeaceae xanthorroea xanthosis xanthosoma xantusiidae xavier xc xe xenarthra xenicidae xenicus xenogenesis xenograft xenolith xenon xenophanes xenophobia xenophon xenopodidae xenopus xenorhyncus xenosauridae xenosaurus xenotime xenotransplant xenotransplantation xeranthemum xerobates xeroderma xerodermia xerography xeroma xerophile xerophthalmia xerophthalmus xerophyllum xerophyte xeroradiography xerostomia xerotes xerox xhosa xi xian xii xiii xinjiang xiphias xiphiidae xiphosura xiv xix xizang xl xmas xt xtc xv xvi xvii xviii xx xxi xxii xxiii xxiv xxix xxv xxvi xxvii xxviii xxx xxy xxy-syndrome xy xylaria xylariaceae xylem xylene xylocaine xylocopa xylol xylomelum xylophone xylophonist xylopia xylose xylosma xyphophorus xyridaceae xyridales xyris xyy y y-axis y2k yacca yacht yachting yachtsman yachtswoman yack yafo yagi yahi yahoo yahve yahveh yahwe yahweh yajur-veda yak yakety-yak yakima yakut yakuza yale yalta yaltopya yalu yam yama yamaltu yamamoto yamani yamoussukro yana yanan yang yangon yangtze yank yankee yankee-doodle yanker yanquapin yaounde yap yard yardage yardarm yardbird yarder yardgrass yardie yardman yardmaster yardstick yarmelke yarmulka yarmulke yarn yarrow yashmac yashmak yastrzemski yataghan yatobyo yautia yavapai yaw yawl yawn yawner yawning yaws yay yazoo yb ybit yea year year-end yearbook yearling yearly yearner yearning years yeast yeats yeddo yedo yekaterinoslav yell yeller yelling yellow yellow-blindness yellowbird yellowcake yellowfin yellowhammer yellowknife yellowlegs yellowness yellowstone yellowtail yellowthroat yellowwood yelp yelping yemen yemeni yen yenisei yenisei-samoyed yeniseian yenisey yenta yeoman yeomanry yerevan yerkes yersin yerupaja yerwa-maiduguri yes yes-man yeshiva yeshivah yesterday yesteryear yeti yevtushenko yew yezo ygdrasil yggdrasil yhvh yhwh yi yib yibit yid yiddish yield yielder yielding yin yip yips yisrael ylang-ylang ylem ymir yo-yo yob yobbo yobibit yobibyte yobo yodel yodeling yodeller yodh yoga yogacara yoghourt yoghurt yogi yogurt yoke yokel yokohama yokuts yolk yore york yorkshire yorktown yoruba yosemite yottabit yottabyte you-drive young youngness youngster youngstown younker youth youth-on- age youthfulness yowl ypres yquem yr ytterbite ytterbium yttrium yuan yucatan yucatec yucateco yucca yue yugoslav yugoslavia yugoslavian yukawa yukon yule yuletide yuma yuman yunnan yuppie yurak-samoyed yurt z z-axis zaar zabaglione zabrze zacharias zag zaglossus zagreb zaharias zaire zairean zairese zakat zalcitabine zalophus zama zaman zamang zambezi zambia zambian zamboni zamia zamiaceae zangwill zannichellia zannichelliaceae zantac zantedeschia zanthoxylum zanuck zany zanzibar zap zapata zapodidae zapotec zapotecan zapper zapus zaragoza zarathustra zarf zaria zarontin zarpanit zarqa zayin zb zbit zdv zea zeal zealand zealander zealot zealotry zeaxanthin zebibit zebibyte zebra zebrawood zebu zechariah zed zee zeeman zeidae zeitgeist zen zenaidura zend zend-avesta zenith zeno zeolite zeomorphi zep zephaniah zephyr zeppelin zeppo zero zest zestfulness zestril zeta zetland zettabit zettabyte zeugma zeus zhou zhuang zhukov zib zibit zidovudine ziegfeld ziegler zig zigadene zigadenus ziggurat zigzag zikkurat zikurat zilch zill zillion zimbabwe zimbabwean zimbalist zimmer zinacef zinc zinfandel zing zinger zingiber zingiberaceae zinjanthropus zinkenite zinnemann zinnia zinnwaldite zinsser zinzendorf zion zionism zionist zip ziphiidae zipper zippo zirbanit zircon zirconia zirconium zit zither zithern zithromax ziti zizania ziziphus zizz zloty zn zoanthropy zoarces zoarcidae zocor zodiac zoisia zola zoloft zomba zombi zombie zona zone zoning zonotrichia zonula zonule zoo zooerastia zooerasty zooflagellate zooid zoolatry zoologist zoology zoom zoomastigina zoomastigote zoomorphism zoonosis zoophilia zoophilism zoophobia zoophyte zooplankton zoopsia zoospore zootoxin zori zoril zoroaster zoroastrian zoroastrianism zoster zostera zosteraceae zovirax zoysia zr zsigmondy zu zubird zucchini zukerman zulu zuni zurich zurvan zurvanism zweig zwieback zwingli zworykin zydeco zygnema zygnemales zygnemataceae zygnematales zygocactus zygoma zygomatic zygomycetes zygomycota zygomycotina zygophyllaceae zygophyllum zygoptera zygospore zygote zygotene zyloprim zymase zymogen zymology zymolysis zymosis zymurgy zyrian """ |> String.split(~r/\s+/) |> MapSet.new(&String.trim/1) def all do @nouns_set end end
lib/en/nouns.ex
0.541166
0.572663
nouns.ex
starcoder
defmodule IO.ANSI.Sequence do @moduledoc false defmacro defsequence(name, code \\ "", terminator \\ "m") do quote bind_quoted: [name: name, code: code, terminator: terminator] do def unquote(name)() do "\e[#{unquote(code)}#{unquote(terminator)}" end defp escape_sequence(unquote(Atom.to_char_list(name))) do unquote(name)() end defp format_sequence(unquote(name)) do unquote(name)() end end end end defmodule IO.ANSI do @moduledoc """ Functionality to render ANSI escape sequences (http://en.wikipedia.org/wiki/ANSI_escape_code) — characters embedded in text used to control formatting, color, and other output options on video text terminals. """ import IO.ANSI.Sequence @typep ansicode :: atom() @typep ansilist :: maybe_improper_list(char() | ansicode() | binary() | ansilist(), binary() | ansicode() | []) @type ansidata :: ansilist() | ansicode() | binary() @doc false def terminal?(device \\ :erlang.group_leader) do !match?({:win32, _}, :os.type()) and match?({:ok, _}, :io.columns(device)) end @doc """ Checks if ANSI coloring is supported and enabled on this machine. By default, ANSI is only enabled on UNIX machines. Enabling or disabling ANSI escapes can be done by configuring the `:ansi_enabled` value in the `:elixir` application. """ @spec enabled? :: boolean def enabled? do case Application.fetch_env(:elixir, :ansi_enabled) do {:ok, boolean} when is_boolean(boolean) -> boolean :error -> !match?({:win32, _}, :os.type()) end end @doc "Resets all attributes" defsequence :reset, 0 @doc "Bright (increased intensity) or Bold" defsequence :bright, 1 @doc "Faint (decreased intensity), not widely supported" defsequence :faint, 2 @doc "Italic: on. Not widely supported. Sometimes treated as inverse." defsequence :italic, 3 @doc "Underline: Single" defsequence :underline, 4 @doc "Blink: Slow. Less than 150 per minute" defsequence :blink_slow, 5 @doc "Blink: Rapid. MS-DOS ANSI.SYS; 150 per minute or more; not widely supported" defsequence :blink_rapid, 6 @doc "Image: Negative. Swap foreground and background" defsequence :inverse, 7 @doc "Image: Negative. Swap foreground and background" defsequence :reverse, 7 @doc "Conceal. Not widely supported" defsequence :conceal, 8 @doc "Crossed-out. Characters legible, but marked for deletion. Not widely supported." defsequence :crossed_out, 9 @doc "Sets primary (default) font" defsequence :primary_font, 10 for font_n <- [1, 2, 3, 4, 5, 6, 7, 8, 9] do @doc "Sets alternative font #{font_n}" defsequence :"font_#{font_n}", font_n + 10 end @doc "Normal color or intensity" defsequence :normal, 22 @doc "Not italic" defsequence :not_italic, 23 @doc "Underline: None" defsequence :no_underline, 24 @doc "Blink: off" defsequence :blink_off, 25 colors = [:black, :red, :green, :yellow, :blue, :magenta, :cyan, :white] colors = Enum.zip(0..(length(colors)-1), colors) for {code, color} <- colors do @doc "Sets foreground color to #{color}" defsequence color, code + 30 @doc "Sets background color to #{color}" defsequence :"#{color}_background", code + 40 end @doc "Default text color" defsequence :default_color, 39 @doc "Default background color" defsequence :default_background, 49 @doc "Framed" defsequence :framed, 51 @doc "Encircled" defsequence :encircled, 52 @doc "Overlined" defsequence :overlined, 53 @doc "Not framed or encircled" defsequence :not_framed_encircled, 54 @doc "Not overlined" defsequence :not_overlined, 55 @doc "Send cursor home" defsequence :home, "", "H" @doc "Clear screen" defsequence :clear, "2", "J" defp escape_sequence(other) do raise ArgumentError, "invalid ANSI sequence specification: #{other}" end defp format_sequence(other) do raise ArgumentError, "invalid ANSI sequence specification: #{other}" end @doc ~S""" Formats a chardata-like argument by converting named ANSI sequences into actual ANSI codes. The named sequences are represented by atoms. It will also append an `IO.ANSI.reset` to the chardata when a conversion is performed. If you don't want this behaviour, use `format_fragment/2`. An optional boolean parameter can be passed to enable or disable emitting actual ANSI codes. When `false`, no ANSI codes will emitted. By default checks if ANSI is enabled using the `enabled?/0` function. ## Examples iex> IO.ANSI.format(["Hello, ", :red, :bright, "world!"], true) [[[[[[], "Hello, "] | "\e[31m"] | "\e[1m"], "world!"] | "\e[0m"] """ def format(chardata, emit \\ enabled?) when is_boolean(emit) do do_format(chardata, [], [], emit, :maybe) end @doc ~S""" Formats a chardata-like argument by converting named ANSI sequences into actual ANSI codes. The named sequences are represented by atoms. An optional boolean parameter can be passed to enable or disable emitting actual ANSI codes. When `false`, no ANSI codes will emitted. By default checks if ANSI is enabled using the `enabled?/0` function. ## Examples iex> IO.ANSI.format_fragment([:bright, 'Word'], true) [[[[[[] | "\e[1m"], 87], 111], 114], 100] """ def format_fragment(chardata, emit \\ enabled?) when is_boolean(emit) do do_format(chardata, [], [], emit, false) end defp do_format([term | rest], rem, acc, emit, append_reset) do do_format(term, [rest | rem], acc, emit, append_reset) end defp do_format(term, rem, acc, true, append_reset) when is_atom(term) do do_format([], rem, [acc | format_sequence(term)], true, !!append_reset) end defp do_format(term, rem, acc, false, append_reset) when is_atom(term) do do_format([], rem, acc, false, append_reset) end defp do_format(term, rem, acc, emit, append_reset) when not is_list(term) do do_format([], rem, [acc | [term]], emit, append_reset) end defp do_format([], [next | rest], acc, emit, append_reset) do do_format(next, rest, acc, emit, append_reset) end defp do_format([], [], acc, true, true) do [acc | IO.ANSI.reset] end defp do_format([], [], acc, _emit, _append_reset) do acc end @doc false def escape(string, emit \\ terminal?) when is_binary(string) and is_boolean(emit) do {rendered, emitted} = do_escape(string, emit, false, nil, []) if emitted do rendered <> reset else rendered end end @doc false def escape_fragment(string, emit \\ terminal?) when is_binary(string) and is_boolean(emit) do {escaped, _emitted} = do_escape(string, emit, false, nil, []) escaped end defp do_escape(<<?}, t :: binary>>, emit, emitted, buffer, acc) when is_list(buffer) do sequences = buffer |> Enum.reverse() |> :string.tokens(',') |> Enum.map(&(&1 |> :string.strip |> escape_sequence)) |> Enum.reverse() if emit and sequences != [] do do_escape(t, emit, true, nil, sequences ++ acc) else do_escape(t, emit, emitted, nil, acc) end end defp do_escape(<<h, t :: binary>>, emit, emitted, buffer, acc) when is_list(buffer) do do_escape(t, emit, emitted, [h|buffer], acc) end defp do_escape(<<>>, _emit, _emitted, buffer, _acc) when is_list(buffer) do buffer = IO.iodata_to_binary Enum.reverse(buffer) raise ArgumentError, "missing } for escape fragment #{buffer}" end defp do_escape(<<?%, ?{, t :: binary>>, emit, emitted, nil, acc) do do_escape(t, emit, emitted, [], acc) end defp do_escape(<<h, t :: binary>>, emit, emitted, nil, acc) do do_escape(t, emit, emitted, nil, [h|acc]) end defp do_escape(<<>>, _emit, emitted, nil, acc) do {IO.iodata_to_binary(Enum.reverse(acc)), emitted} end end
lib/elixir/lib/io/ansi.ex
0.833731
0.492005
ansi.ex
starcoder
defmodule Quark.Compose do @moduledoc ~S""" Function composition is taking two functions, and joining them together to create a new function. For example: ## Examples iex> sum_plus_one = compose([&(&1 + 1), &Enum.sum/1]) ...> sum_plus_one.([1,2,3]) 7 In this case, we have joined `Enum.sum` with a function that adds one, to create a new function that takes a list, sums it, and adds one. Note that composition normally applies _from right to left_, though `Quark` provides the opposite in the form of `*_forward` functions. """ import Quark.SKI use Quark.Partial use Quark.Curry @doc ~S""" Function composition ## Examples iex> sum_plus_one = compose(&(&1 + 1), &Enum.sum/1) ...> [1, 2, 3] |> sum_plus_one.() 7 """ @spec compose(fun, fun) :: any def compose(g, f) do fn x -> x |> curry(f).() |> curry(g).() end end @doc ~S""" Function composition, from the tail of the list to the head ## Examples iex> sum_plus_one = compose([&(&1 + 1), &Enum.sum/1]) ...> [1,2,3] |> sum_plus_one.() 7 """ @spec compose([fun]) :: fun defpartial compose(func_list), do: func_list |> List.foldr(&id/1, &compose/2) @doc ~S""" Infix compositon operator ## Examples iex> sum_plus_one = fn x -> x + 1 end <|> &Enum.sum/1 ...> sum_plus_one.([1,2,3]) 7 iex> add_one = &(&1 + 1) ...> piped = [1, 2, 3] |> Enum.sum() |> add_one.() ...> composed = [1, 2, 3] |> ((add_one <|> &Enum.sum/1)).() ...> piped == composed true """ @spec fun <|> fun :: fun def g <|> f, do: compose(g, f) @doc ~S""" Function composition, from the back of the list to the front ## Examples iex> sum_plus_one = compose_forward(&Enum.sum/1, &(&1 + 1)) ...> [1, 2, 3] |> sum_plus_one.() 7 """ @spec compose_forward(fun, fun) :: fun defpartial compose_forward(f, g) do fn x -> x |> curry(f).() |> curry(g).() end end @doc ~S""" Infix "forward" compositon operator ## Examples iex> sum_plus_one = (&Enum.sum/1) <~> fn x -> x + 1 end ...> sum_plus_one.([1, 2, 3]) 7 iex> x200 = (&(&1 * 2)) <~> (&(&1 * 10)) <~> (&(&1 * 10)) ...> x200.(5) 1000 iex> add_one = &(&1 + 1) ...> piped = [1, 2, 3] |> Enum.sum() |> add_one.() ...> composed = [1, 2, 3] |> ((&Enum.sum/1) <~> add_one).() ...> piped == composed true """ @spec fun <~> fun :: fun def f <~> g, do: compose_forward(f, g) @doc ~S""" Compose functions, from the head of the list of functions. The is the reverse order versus what one would normally expect (left-to-right rather than right-to-left). ## Examples iex> sum_plus_one = compose_list_forward([&Enum.sum/1, &(&1 + 1)]) ...> sum_plus_one.([1, 2, 3]) 7 """ @spec compose_list_forward([fun]) :: fun defpartial compose_list_forward(func_list) do List.foldl(func_list, &id/1, &compose/2) end @doc ~S""" Compose functions, from the head of the list of functions. The is the reverse order versus what one would normally expect (left-to-right rather than right-to-left). ## Examples iex> sum_plus_one = compose_list([&(&1 + 1), &Enum.sum/1]) ...> sum_plus_one.([1, 2, 3]) 7 """ @spec compose_list([fun]) :: fun defpartial compose_list(func_list) do List.foldr(func_list, &id/1, &compose/2) end end
lib/quark/compose.ex
0.845879
0.673423
compose.ex
starcoder
defmodule Scenic.Primitive.Script do @moduledoc """ A reference to a draw script. The `Script` primitive is used to refer to a script that you created and loaded into the ViewPort separately from the graph. This script also has full access to the `Scenic.Script` API. For example, the check mark shape in the `Checkbox` control is a draw script that is reference by the checkbox control's graph. A graph can reference the same script multiple times, which is very efficient as the script is only sent to the drivers once. If the graph is modified later, then any scripts it references will not need to be resent to the drivers. This is an isolation of concerns. The same is true in reverse. If you rebuild a script and send it to the `ViewPort`, the script will be sent to the drivers, but any graphs that reference it do not need to be. ## `Script` vs. `Path` Both the `Path` and the `Script` primitives use the `Scenic.Script` to create scripts are sent to the drivers for drawing. The difference is that a Path is far more limited in what it can do, and is inserted inline with the compiled graph that created it. The script primitive, on the other hand, has full access to the API set of `Scenic.Script` and accesses scripts by reference. The inline vs. reference difference is important. A simple path will be consume fewer resources. BUT it will cause the entire graph to be recompile and resent to the drivers if you change it. A script primitive references a script that you create separately from the the graph. This means that any changes to the graph (such as an animation) will NOT need to recompile or resend the script. ## Usage You should add/modify primitives via the helper functions in [`Scenic.Primitives`](Scenic.Primitives.html#script/3) This example is based on the check mark script from the Checkbox control. ```elixir alias Scenic.Script # build the checkmark script my_script = Script.start() |> Script.push_state() |> Script.join(:round) |> Script.stroke_width(3) |> Script.stroke_color(:light_blue) |> Script.begin_path() |> Script.move_to(0, 8) |> Script.line_to(5, 13) |> Script.line_to(12, 1) |> Script.stroke_path() |> Script.pop_state() |> Script.finish() # push the script to the ViewPort scene = push_script(scene, my_script, "My Script") # refer to the script in a graph, and position it graph |> script("My Script", translate: {3, 2}) ``` """ use Scenic.Primitive alias Scenic.Script alias Scenic.Primitive alias Scenic.Primitive.Style @type styles_t :: [:hidden | :scissor] @styles [:hidden, :scissor] @impl Primitive @spec validate(script_id :: Scenic.Script.id()) :: {:ok, script_id :: Scenic.Script.id()} | {:error, String.t()} def validate(id) when is_bitstring(id) do {:ok, id} end def validate(data) do { :error, """ #{IO.ANSI.red()}Invalid Script ID Received: #{inspect(data)} #{IO.ANSI.yellow()} The specification for a Script primitive is teh ID of a script that is pushed in to a viewport at some other time. This ID can be a pid, an atom, a string or a reference. You can refer to a script before it is pushed, but it will not draw until it is pushed to the viewport.#{IO.ANSI.default_color()} """ } end # -------------------------------------------------------- # filter and gather styles @doc """ Returns a list of styles recognized by this primitive. """ @impl Primitive @spec valid_styles() :: styles_t() def valid_styles(), do: @styles # -------------------------------------------------------- # compiling a script is a special case and is handled in Scenic.Graph.Compiler @doc false @impl Primitive @spec compile(primitive :: Primitive.t(), styles :: Style.t()) :: Script.t() def compile(%Primitive{module: __MODULE__}, _styles) do raise "compiling a Script is a special case and is handled in Scenic.Graph.Compiler" end end
lib/scenic/primitive/script.ex
0.891946
0.826991
script.ex
starcoder
defmodule OMG.ChildChain.BlockQueue.GasAnalyzer do @moduledoc """ Takes the transaction hash and puts it in the FIFO queue for each transaction hash we're trying to get the gas we've used to submit the block and send it of as a telemetry event to datadog """ require Logger @retries 3 defstruct txhash_queue: :queue.new(), rpc: Ethereumex.HttpClient def enqueue(server \\ __MODULE__, txhash) do GenServer.cast(server, {:enqueue, txhash}) end def child_spec(args) do %{ id: __MODULE__, start: {__MODULE__, :start_link, [args]}, type: :worker } end def start_link(args) do GenServer.start_link(__MODULE__, args, name: Keyword.get(args, :name, __MODULE__)) end def init(_args) do _ = :timer.send_after(3000, self(), :get_gas_used) {:ok, %__MODULE__{}} end def handle_cast({:enqueue, txhash}, state) do try_index = 0 {:noreply, %{state | txhash_queue: :queue.in({txhash, try_index}, state.txhash_queue)}} end @doc """ We receive transaction hashes from BlockQueue. These hashes do not mean that transaction was already accepted. The consequence is that theres a possibility the transaction will never get accepted and that we need to define a constant `try_index`. `try_index` constant is the threshold limit that defines the amount of retries we're willing to fetch gas. After it's reached the tx hash will be thrown away. """ def handle_info(:get_gas_used, state) do txhash_queue = case :queue.is_empty(state.txhash_queue) do true -> state.txhash_queue false -> {{:value, {txhash, try_index}}, txhash_queue} = :queue.out(state.txhash_queue) txhash_hex = to_hex(txhash) gas_used = get_gas_used(txhash_hex, state.rpc) case {gas_used, try_index} do {nil, @retries} -> # reached the threshold, we're omitting this txhash _ = Logger.warn( "Could not get gas used for txhash #{txhash_hex} after #{@retries} retries. Removing from queue." ) txhash_queue {nil, _} -> # we couldn't get gas but we didn't reach the threshold yet :queue.in_r({txhash, try_index + 1}, txhash_queue) {gas, _} -> # Anyway a gas station we passed # We got gas and went on to get grub _ = :telemetry.execute([:gas, __MODULE__], %{gas: gas}, %{}) txhash_queue end end _ = :timer.send_after(3000, self(), :get_gas_used) {:noreply, %{state | txhash_queue: txhash_queue}} end defp get_gas_used(txhash, rpc) do result = {rpc.eth_get_transaction_receipt(txhash), rpc.eth_get_transaction_by_hash(txhash)} case result do {{:ok, %{"gasUsed" => gas_used}}, {:ok, %{"gasPrice" => gas_price}}} -> gas_price_value = parse_gas(gas_price) gas_used_value = parse_gas(gas_used) gas_used = gas_price_value * gas_used_value _ = Logger.info("Block submitted with receipt hash #{txhash} and gas used #{gas_used} wei") gas_used {eth_get_transaction_receipt, eth_get_transaction_by_hash} -> _ = Logger.warn( "Could not get gas used for txhash #{txhash}. Eth_get_transaction_receipt result #{ inspect(eth_get_transaction_receipt) }. Eth_get_transaction_by_hash result #{inspect(eth_get_transaction_by_hash)}." ) nil end end defp to_hex(raw) when is_binary(raw), do: "0x" <> Base.encode16(raw, case: :lower) defp parse_gas(data) do {value, ""} = data |> String.replace_prefix("0x", "") |> Integer.parse(16) value end end
apps/omg_child_chain/lib/omg_child_chain/block_queue/gas_analyzer.ex
0.727395
0.412619
gas_analyzer.ex
starcoder
defmodule StringFormatterIolist do @moduledoc """ A module used to evaluate {placeholders} in strings given a list of params """ import StringFormatterUtils, only: [normalize_params: 1, eval_holder: 2] @status_normal :normal @status_reading_placeholder :reading_placeholder @doc """ Format a string with placeholders. Missing placeholders will be printed back in the formatted text """ def format(string, params, opts \\ []) when is_binary(string) do normalized_params = normalize_params(params) do_format(string, normalized_params, [], @status_normal, nil) |> flush(opts) end defp do_format("", _, formatted, _, nil), do: formatted defp do_format("", _, formatted, _, remaining), do: [formatted, "{", remaining] defp do_format("{{" <> rest, params, formatted, @status_reading_placeholder = status, placeholder) do do_format(rest, params, formatted, status, [placeholder, "{"]) end defp do_format("{{" <> rest, params, formatted, status, placeholder) do do_format(rest, params, [formatted, "{"], status, placeholder) end defp do_format("}}" <> rest, params, formatted, @status_reading_placeholder = status, placeholder) do do_format(rest, params, formatted, status, [placeholder, "}"]) end defp do_format("}}" <> rest, params, formatted, status, placeholder) do do_format(rest, params, [formatted, "}"], status, placeholder) end defp do_format("{" <> rest, params, formatted, @status_normal, _) do do_format(rest, params, formatted, @status_reading_placeholder, []) end defp do_format("}" <> rest, params, formatted, @status_reading_placeholder, placeholder) do evaled = placeholder |> IO.iodata_to_binary() |> eval_holder(params) do_format(rest, params, [formatted, evaled], @status_normal, nil) end defp do_format(<<x :: binary-size(1), rest :: binary>>, params, formatted, @status_reading_placeholder, placeholder) do do_format(rest, params, formatted, @status_reading_placeholder, [placeholder, x]) end defp do_format(<<x :: binary-size(1), rest :: binary>>, params, formatted, status, placeholder) do do_format(rest, params, [formatted, x], status, placeholder) end defp flush(io_data, opts) do case opts[:io_lists] do true -> io_data _ -> IO.iodata_to_binary(io_data) end end end
pattern_matching_and_state_machines/lib/string_formatter_iolist.ex
0.682679
0.437583
string_formatter_iolist.ex
starcoder
defmodule CanvasAPI.Canvas.Formatter do @moduledoc """ Converts a canvas to a given format. """ alias CanvasAPI.{Block, Canvas} @spec to_markdown(Canvas.t | Block.t) :: String.t def to_markdown(block_parent) do block_parent.blocks |> Enum.reduce("", &block_to_markdown/2) |> String.trim_trailing end @spec block_to_markdown(Block.t, String.t) :: String.t defp block_to_markdown(block = %Block{type: "title"}, _md) do "# #{block.content}\n\n" end defp block_to_markdown(block = %Block{type: "paragraph"}, md) do "#{md}#{block.content}\n\n" end defp block_to_markdown(%Block{type: "horizontal-rule"}, md) do "#{md}---\n\n" end defp block_to_markdown(block = %Block{type: "heading"}, md) do "#{md}#{leading_hashes(block)} #{block.content}\n\n" end defp block_to_markdown(block = %Block{type: "url"}, md) do "#{md}<#{URI.encode(block.meta["url"])}>\n\n" end defp block_to_markdown(block = %Block{type: "image"}, md) do "#{md}![](#{URI.encode(block.meta["url"])})\n\n" end defp block_to_markdown(block = %Block{type: "code"}, md) do "#{md}```#{block.meta["language"]}\n#{block.content}\n```\n\n" end defp block_to_markdown(block = %Block{type: "list"}, md) do "#{md}#{to_markdown(block)}\n\n" end defp block_to_markdown(block = %Block{type: "unordered-list-item"}, md) do "#{md}#{leading_spaces(block)}- #{block.content}\n" end defp block_to_markdown(block = %Block{type: "checklist-item"}, md) do check = if block.meta["checked"], do: "x", else: " " "#{md}#{leading_spaces(block)}- [#{check}] #{block.content}\n" end defp block_to_markdown(_, md), do: md @spec leading_hashes(Block.t) :: String.t defp leading_hashes(%Block{meta: %{"level" => level}}) do String.duplicate("#", level) end @spec leading_spaces(Block.t) :: String.t defp leading_spaces(%Block{meta: %{"level" => level}}) do String.duplicate(" ", level - 1) end defp leading_spaces(_), do: "" end
web/models/canvas/formatter.ex
0.810779
0.75358
formatter.ex
starcoder
use Croma alias Croma.Result, as: R defmodule Antikythera.VersionStr do @moduledoc """ Format of versions of antikythera instances and gears. The format rule is a stricter variant of [semantic versioning](https://semver.org/); pre-release part and build metadata part are filled with information from the current git commit (committer date and commit hash, respectively). This way we always make a new version for each new git commit, which enables both antikythera instances and gears to be deployed on a per-commit basis. The actual version strings are created by `Antikythera.MixCommon.version_with_last_commit_info/1` defined in `mix_common.exs` file. Note that the current format prohibits multi-digits numbers as major/minor/patch version; this is just to simplify deployment and not an intrinsic limitation. """ use Croma.SubtypeOfString, pattern: ~R/\A\d\.\d\.\d-\d{14}\+[0-9a-f]{40}\z/ end defmodule Antikythera.Domain do @moduledoc """ Domain name format, originally defined in [RFC1034](https://tools.ietf.org/html/rfc1034#section-3.5). - It accepts 1 to 63 letters label in top-level domains as per original syntax definition. - It accepts all-numeric top-level domains as opposed to the restriction in [RFC3696](https://tools.ietf.org/html/rfc3696#section-2). - If it is the sole part of domain name, (e.g. http://2130706433) client applications will most likely parse them as 32-bit integer representation of IPv4 address. """ @pattern_body "((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)*(?!-)[A-Za-z0-9-]{1,63}(?<!-)" def pattern_body(), do: @pattern_body use Croma.SubtypeOfString, pattern: ~r/\A#{@pattern_body}\z/ end defmodule Antikythera.DomainList do use Croma.SubtypeOfList, elem_module: Antikythera.Domain, max_length: 10 end defmodule Antikythera.PathSegment do @moduledoc """ A type module to represent URI-encoded segment of URL path. See [RFC3986](https://tools.ietf.org/html/rfc3986#section-3.3) for the specifications of URI path. Note that this module accepts empty strings. """ @charclass "[0-9A-Za-z\-._~%!$&'()*+,;=:@]" def charclass(), do: @charclass use Croma.SubtypeOfString, pattern: ~r|\A#{@charclass}*\z| end defmodule Antikythera.PathInfo do use Croma.SubtypeOfList, elem_module: Croma.String # percent-decoded, any string is allowed in each segment end defmodule Antikythera.UnencodedPath do @segment_charclass "[^/?#]" def segment_charclass(), do: @segment_charclass use Croma.SubtypeOfString, pattern: ~r"\A/(#{@segment_charclass}+/)*(#{@segment_charclass}+)?\z" end defmodule Antikythera.EncodedPath do alias Antikythera.PathSegment, as: Segment use Croma.SubtypeOfString, pattern: ~r"\A/(#{Segment.charclass()}+/)*(#{Segment.charclass()}+)?\z" end defmodule Antikythera.Url do @moduledoc """ URL format, originally defined in [RFC1738](https://tools.ietf.org/html/rfc1738), and updated in [RFC3986](https://tools.ietf.org/html/rfc3986) as a subset of URI. - Only accepts `http` or `https` as scheme. - IPv4 addresses in URLs must be 4-part-dotted-decimal formats. - e.g. 192.168.0.1 - See [here](https://tools.ietf.org/html/rfc3986#section-3.2.2) - IPv6 addresses are not supported currently. """ alias Antikythera.Domain alias Antikythera.IpAddress.V4, as: IpV4 @type t :: String.t captured_ip_pattern = "(?<ip_str>(\\d{1,3}\\.){3}\\d{1,3})" host_pattern = "(#{captured_ip_pattern}|#{Domain.pattern_body()})" path_pattern = "((/[^/\\s?#]+)*/?)?" @pattern ~r"\Ahttps?://([^\s:]+(:[^\s:]+)?@)?#{host_pattern}(:\d{1,5})?#{path_pattern}(\?([^\s#]*))?(#[^\s]*)?\z" def pattern(), do: @pattern defun valid?(v :: term) :: boolean do s when is_binary(s) -> case Regex.named_captures(@pattern, s) do %{"ip_str" => "" } -> true %{"ip_str" => ip_str} -> IpV4.parse(ip_str) |> R.ok?() nil -> false end _ -> false end end defmodule Antikythera.Email do @moduledoc """ Email address format, defined in [RFC5321](https://tools.ietf.org/html/rfc5321), and [RFC5322](https://tools.ietf.org/html/rfc5322). There are some differences from original RFCs for simplicity: - Leading, trailing and/or consecutive '.'s in local parts are allowed. - Double-quoted local parts are not allowed. - '[]'-enclosed IP address literals in domain parts are not allowed. - Total length of domain parts are not limited to 255. """ use Croma.SubtypeOfString, pattern: ~r"\A[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]{1,64}@#{Antikythera.Domain.pattern_body()}\z" end defmodule Antikythera.NodeId do @pattern_string "[0-9A-Za-z.-]+" def pattern_string(), do: @pattern_string use Croma.SubtypeOfString, pattern: ~r/\A#{@pattern_string}\z/ end defmodule Antikythera.ContextId do @system_context "antikythera_system" def system_context(), do: @system_context use Croma.SubtypeOfString, pattern: ~r/\A(\d{8}-\d{6}\.\d{3}_#{Antikythera.NodeId.pattern_string()}_\d+\.\d+\.\d+|#{@system_context})\z/ end defmodule Antikythera.ImfFixdate do @moduledoc """ An IMF-fixdate format of date/time. Used in HTTP headers. Only 'GMT' is allowed as timezone string. """ days_of_week = "(Mon|Tue|Wed|Thu|Fri|Sat|Sun)" months_of_year = "(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)" use Croma.SubtypeOfString, pattern: ~r/\A#{days_of_week}, \d\d #{months_of_year} \d\d\d\d \d\d:\d\d:\d\d GMT\z/ end defmodule Antikythera.GearName do @moduledoc """ Type module to represent gear names as atoms. """ alias Antikythera.GearNameStr @type t :: atom defun valid?(v :: term) :: boolean do a when is_atom(a) -> GearNameStr.valid?(Atom.to_string(a)) _ -> false end end defmodule Antikythera.GearNameStr do use Croma.SubtypeOfString, pattern: ~R/\A[a-z][0-9a-z_]{2,31}\z/ end defmodule Antikythera.TenantId do @notenant "notenant" defun notenant() :: String.t, do: @notenant use Croma.SubtypeOfString, pattern: ~r/\A(?!^#{@notenant}$)[0-9A-Za-z_]{3,32}\z/ end
lib/type/string.ex
0.596316
0.48871
string.ex
starcoder
defmodule Collision.Polygon.Vertex do @moduledoc """ A vertex is a point in the Cartesian space where a polygon's edges meet. """ defstruct x: 0, y: 0 alias Collision.Polygon.Vertex @typedoc """ Vertices in two dimensional space are defined by `x` and `y` coordinates. """ @type t :: Vertex.t @doc """ Convert a tuple to a Vertex. Returns: %Vertex{} ## Example iex> Vertex.from_tuple({2, 5}) %Vertex{x: 2, y: 5} """ @spec from_tuple({number, number}) :: Vertex.t def from_tuple({x, y}) do %Vertex{x: x, y: y} end @doc """ Convert a vertex to a tuple. Returns: {} ## Example iex> Vertex.to_tuple(%Vertex{x: 2, y: 5}) {2, 5} """ @spec to_tuple(Vertex.t) :: {number, number} def to_tuple(%Vertex{x: x, y: y}) do {x, y} end @doc """ Determinant of the triangle formed by three vertices. If > 0, counter-clockwise = 0, colinear < 0, clockwise """ @spec determinant(Vertex.t, Vertex.t, Vertex.t) :: number defp determinant(%Vertex{} = v1, %Vertex{} = v2, %Vertex{} = v3) do (v2.x - v1.x) * (v3.y - v1.y) - (v2.y - v1.y) * (v3.x - v1.x) end defp counter_clockwise(v1, v2, v3) do determinant(v1, v2, v3) > 0 end @doc """ Calculate the convex hull of a list of vertices. In the case of a convex polygon, it returns the polygon's vertices. For a concave polygon, it returns a subset of the vertices that form a convex polygon. ## Examples iex> convex_polygon = [ ...> %Vertex{x: 2, y: 2}, %Vertex{x: -2, y: 2}, ...> %Vertex{x: -2, y: -2}, %Vertex{x: 2, y: -2} ...> ] ...> Vertex.graham_scan(convex_polygon) [%Vertex{x: -2, y: -2}, %Vertex{x: 2, y: -2}, %Vertex{x: 2, y: 2}, %Vertex{x: -2, y: 2}] iex> concave_polygon = [ ...> %Vertex{x: 2, y: 2}, %Vertex{x: 0, y: 0}, %Vertex{x: -2, y: 2}, ...> %Vertex{x: -2, y: -2}, %Vertex{x: 2, y: -2} ...> ] ...> Vertex.graham_scan(concave_polygon) [%Vertex{x: -2, y: -2}, %Vertex{x: 2, y: -2}, %Vertex{x: 2, y: 2}, %Vertex{x: -2, y: 2}] """ # Adapted from: # https://gotorecursive.wordpress.com/2014/05/28/grahams-scan-from-imperative-to-functional/ @spec graham_scan([Vertex.t]) :: Vertex.t def graham_scan(vertices) do min_point = Enum.min_by(vertices, fn vertex -> [vertex.y, vertex.x] end) distance_to_min = vertices |> Enum.sort_by(fn vertex -> :math.atan2(vertex.y - min_point.y, vertex.x - min_point.x) end) add_to_hull = fn point, hull -> [point | filter_right_turns(point, hull)] end convex_hull = distance_to_min |> List.foldl([], add_to_hull) |> Enum.reverse convex_hull end # During the scan, filter out the most recently added # point if it makes a reflex angle with the new point. defp filter_right_turns(new_point, hull) do hull |> List.foldr([], fn (current_point, current_hull) -> case current_hull do [previous | _] -> if counter_clockwise(previous, current_point, new_point) do [current_point | current_hull] else current_hull end _ -> [current_point | current_hull] end end) end @doc """ Rounds the x and y components of a vertex. Returns: Vertex.t ## Examples iex> Vertex.round_vertex(%Vertex{x: 1.9999999, y: 1.9999999}) %Vertex{x: 2.0, y: 2.0} """ @spec round_vertex(Vertex.t) :: Vertex.t def round_vertex(%Vertex{x: x, y: y}) when (is_float(x) and is_float(y)) do %Vertex{x: Float.round(x, 5), y: Float.round(y, 5)} end def round_vertex(%Vertex{x: x, y: y}) when (is_integer(x) and is_integer(y)) do %Vertex{x: x, y: y} end @doc """ Rounds a list of vertices. Returns: [Vertex.t] ## Examples iex> Vertex.round_vertices([ ...> %Vertex{x: 1.9999999, y: 1.99999999}, %Vertex{x: 2.11111111, y: 2.11111111} ...> ]) [%Vertex{x: 2.0, y: 2.0}, %Vertex{x: 2.11111, y: 2.11111}] """ @spec round_vertices([Vertex.t]) :: [Vertex.t] def round_vertices(vertices) do vertices |> Enum.map(&round_vertex/1) end defimpl String.Chars, for: Vertex do @spec to_string(Vertex.t) :: String.t def to_string(%Vertex{} = v) do "{#{v.x}, #{v.y}}" end end end
lib/collision/polygon/vertex.ex
0.930205
0.940188
vertex.ex
starcoder
defmodule AMQPX.Receiver do use Supervisor @moduledoc """ Provides message handling with transparent connection recovery. Starts a supervisor with a connection watchdog and a handler process. In case of connection loss the process group will be shutdown and restarted until it can reconnect. The message handler is responsible for setting up all its AMQP entities. `AMQPX.Receiver.Standard` should be used for simple cases as it provides some sane default behaviours and takes care of some common pitfalls. If you're implementing your own receiver, read the documentation of `AMQPX.Receiver.Standard` to be aware of them. """ @type option :: {:connection, name :: atom()} | {:worker, module() | (args :: Keyword.t()) | {module(), args :: Keyword.t()}} | {:reconnect, seconds :: integer()} | {:max_restarts, integer()} | {:max_seconds, integer()} def child_spec(args) do %{ id: Keyword.get(args, :id, __MODULE__), start: {__MODULE__, :start_link, [args]}, type: :supervisor } end @doc """ Starts the process group. ## Options * `:connection` – the connection name as registered with `AMQPX.ConnectionPool` * `:worker` – the handler module; see below * `:reconnect` – the interval between recovery attempts in case of connection loss `max_restarts` and `max_seconds` are used to set the supervisor's crash tolerance if both are set. Otherwise it is inferred from `:reconnect` to be able to keep retrying undefinitely until the broker comes back up. ## Worker settings If the worker module is not set, `AMQPX.Receiver.Standard` is used. Custom worker modules must export `start_link/1`, which will receive `args`. The `:connection` option will be added to `args` automatically. """ @spec start_link([option]) :: {:ok, pid()} def start_link(args), do: Supervisor.start_link(__MODULE__, args) @impl Supervisor def init(args) do worker_args = Keyword.get(args, :worker, []) case Keyword.get(args, :supervisor_name) do nil -> :ok name -> Process.register(self(), name) end children = [ {AMQPX.Watchdog, args}, worker_spec(args, worker_args) ] interval = Keyword.get(args, :reconnect, 1) {max_restarts, max_seconds} = case {args[:max_restarts], args[:max_seconds]} do spec = {max_restarts, max_seconds} when max_restarts != nil and max_seconds != nil -> spec _ -> {2, interval} end Supervisor.init( children, strategy: :one_for_all, max_restarts: max_restarts, max_seconds: max_seconds ) end defp worker_spec(args, module) when is_atom(module) do {module, [connection: args[:connection]]} end defp worker_spec(args, {module, worker_args}) when is_atom(module) do {module, Keyword.put(worker_args, :connection, args[:connection])} end defp worker_spec(args, worker_args) when is_list(worker_args) do {AMQPX.Receiver.Standard, Keyword.put(worker_args, :connection, args[:connection])} end end
lib/amqpx/receiver.ex
0.819929
0.485173
receiver.ex
starcoder
defmodule Bitcoin.Protocol.Types.NetworkAddress do use Bitcoin.Common @moduledoc """ Network address type from the Bitconi protocol ( https://en.bitcoin.it/wiki/Protocol_documentation#Network_address ) It appears in two variations. When exchanging info about peers (Addr message) it includes the time field. But when it appears in the Version message, the time field is ommitted. That's why we have parese and parse_version functions. """ defstruct time: 0, # (uint32) the Time (version >= 31402). Not present in version message. services: <<0, 0, 0, 0, 0, 0, 0, 0>>, # (uint64_t) bitfield of features to be enabled for this connection. See Version Message. address: {0, 0, 0, 0}, # decoded address tuple, 4 elemnt for IPv4, 8 element for IPv6 (see :inet) port: @default_listen_port # (uint16_t) port number, network byte order @type t :: %__MODULE__{ time: non_neg_integer, services: binary, address: tuple, port: non_neg_integer } @spec parse(binary) :: t def parse(payload) do {data, <<>>} = payload |> parse_stream data end @spec parse_stream(binary) :: {t, binary} def parse_stream(payload) do << time :: unsigned-native-integer-size(32), services :: bitstring-size(64), address :: bytes-size(16), port :: unsigned-big-integer-size(16), payload :: binary >> = payload { %__MODULE__{ time: time, services: services, address: address |> addr_to_inet, port: port }, payload } end @spec parse_version(binary) :: t def parse_version(payload) do {data, <<>>} = payload |> parse_version_stream data end @spec parse_version_stream(binary) :: {t, binary} def parse_version_stream(payload) do << services :: bitstring-size(64), address :: bytes-size(16), port :: unsigned-big-integer-size(16), payload :: binary >> = payload { %__MODULE__{ services: services, address: address |> addr_to_inet, port: port }, payload } end # Binary representation as it is used in the Addr message @spec serialize(t) :: binary def serialize(%__MODULE__{} = s) do << s.time :: unsigned-native-integer-size(32), s.services :: bitstring-size(64), (s.address |> inet_to_addr) :: bytes-size(16), s.port :: unsigned-big-integer-size(16) >> end # Binary representation as it is used in the Version message @spec serialize_version(t) :: binary def serialize_version(%__MODULE__{} = s) do << s.services :: bitstring-size(64), (s.address |> inet_to_addr) :: bytes-size(16), s.port :: unsigned-big-integer-size(16) >> end # Convert address bytes to erlang :inet ip adress, IPv4 def addr_to_inet(<<0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, b1, b2, b3, b4>>), do: {b1, b2, b3, b4} def addr_to_inet(<<0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, b1, b2, b3, b4>>), do: {b1, b2, b3, b4} def addr_to_inet(<< _ipv6 :: binary-size(16) >>), do: {0,0,0,0} #TODO IPv6 # Convert erlang inet ip adress to address byptes IPv4 (TODO IPv6) def inet_to_addr({b1, b2, b3, b4}), do: <<0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, b1, b2, b3, b4>> end
lib/bitcoin/protocol/types/network_address.ex
0.798501
0.507324
network_address.ex
starcoder
defmodule ExIntegrate.Core.Pipeline do @moduledoc """ A collection of Steps to be run sequentially. """ alias ExIntegrate.Core.Step @behaviour Access @enforce_keys [:name, :steps] defstruct @enforce_keys ++ [failed?: false] @type key :: String.t() @type t :: %__MODULE__{ failed?: boolean, name: key, steps: ZipZip.t(Step.t()) } @spec new(fields :: Access.t()) :: t def new(fields) do fields = put_in(fields[:steps], ZipZip.zip(fields[:steps])) struct!(__MODULE__, fields) end @spec steps(t) :: [Step.t()] def steps(%__MODULE__{} = pipeline), do: ZipZip.to_list(pipeline.steps) @spec pop_step(t()) :: {Step.t(), t()} def pop_step(%__MODULE__{} = pipeline) do Map.get_and_update(pipeline, :steps, fn steps -> {{:value, value}, _} = :queue.out(steps) {value, steps} end) end @spec advance(t) :: t def advance(%__MODULE__{} = pipeline), do: %{pipeline | steps: ZipZip.right(pipeline.steps)} @spec current_step(t) :: Step.t() | nil def current_step(%__MODULE__{} = pipeline), do: ZipZip.node(pipeline.steps) @spec get_step_by_name(t, String.t()) :: Step.t() def get_step_by_name(%__MODULE__{} = pipeline, step_name) do pipeline |> steps() |> Enum.find(&(&1.name == step_name)) end @spec replace_current_step(t, Step.t()) :: t def replace_current_step(%__MODULE__{} = pipeline, %Step{} = step) do put_step(pipeline, current_step(pipeline), step) end def replace_step_and_advance(%__MODULE__{} = pipeline, %Step{} = step) do pipeline |> replace_current_step(step) |> advance() end @spec put_step(t, Step.t(), Step.t()) :: t def put_step( %__MODULE__{} = pipeline, %Step{name: name} = _old_step, %Step{name: name} = new_step ) do pipeline |> Map.update(:steps, pipeline.steps, fn steps -> index = pipeline |> steps() |> Enum.find_index(&(&1.name == name)) ZipZip.replace_at(steps, index, new_step) end) |> Map.put(:failed?, pipeline.failed? || Step.failed?(new_step)) end def put_step(%__MODULE__{}, %Step{} = old_step, %Step{} = new_step) do raise ArgumentError, """ cannot alter step names after creation! Old step: #{inspect(old_step)}, Attempted new step: #{inspect(new_step)} """ end @spec failed?(t) :: boolean def failed?(%__MODULE__{} = pipeline), do: pipeline.failed? @spec complete?(t) :: boolean def complete?(%__MODULE__{} = pipeline), do: failed?(pipeline) or ZipZip.end?(pipeline.steps) @impl Access @spec fetch(t, String.t()) :: {:ok, Step.t()} def fetch(%__MODULE__{} = pipeline, step_name) do {:ok, get_step_by_name(pipeline, step_name)} end @impl Access @spec get_and_update(t, String.t(), function) :: {Step.t(), t} | no_return def get_and_update(%__MODULE__{} = pipeline, step_name, fun) when is_function(fun, 1) do current = get_step_by_name(pipeline, step_name) case fun.(current) do {get, update} -> {get, put_step(pipeline, current, update)} :pop -> raise "cannot pop steps!" other -> raise "the given function must return a two-element tuple or :pop; got: #{inspect(other)}" end end @impl Access @spec pop(term, term) :: no_return def pop(_pipeline, _step), do: raise("cannot pop steps!") end
lib/ex_integrate/core/pipeline.ex
0.845049
0.633269
pipeline.ex
starcoder
defmodule Membrane.Filter do @moduledoc """ Module defining behaviour for filters - elements processing data. Behaviours for filters are specified, besides this place, in modules `Membrane.Element.Base`, `Membrane.Element.WithOutputPads`, and `Membrane.Element.WithInputPads`. Filters can have both input and output pads. Job of a usual filter is to receive some data on a input pad, process the data and send it through the output pad. If these pads work in pull mode, which is the most common case, then filter is also responsible for receiving demands on the output pad and requesting them on the input pad (for more details, see `c:Membrane.Element.WithOutputPads.handle_demand/5` callback). Filters, like all elements, can of course have multiple pads if needed to provide more complex solutions. """ alias Membrane.{Buffer, Element, Pad} alias Membrane.Element.CallbackContext @doc """ Callback that is to process buffers. By default calls `c:handle_process/4` for each buffer. For pads in pull mode it is called when buffers have been demanded (by returning `:demand` action from any callback). For pads in push mode it is invoked when buffers arrive. """ @callback handle_process_list( pad :: Pad.ref_t(), buffers :: list(Buffer.t()), context :: CallbackContext.Process.t(), state :: Element.state_t() ) :: Membrane.Element.Base.callback_return_t() @doc """ Callback that is to process buffers. In contrast to `c:handle_process_list/4`, it is passed only a single buffer. Called by default implementation of `c:handle_process_list/4`. """ @callback handle_process( pad :: Pad.ref_t(), buffer :: Buffer.t(), context :: CallbackContext.Process.t(), state :: Element.state_t() ) :: Membrane.Element.Base.callback_return_t() @doc """ Brings all the stuff necessary to implement a filter element. Options: - `:bring_pad?` - if true (default) requires and aliases `Membrane.Pad` """ defmacro __using__(options) do quote location: :keep do use Membrane.Element.Base, unquote(options) use Membrane.Element.WithOutputPads use Membrane.Element.WithInputPads @behaviour unquote(__MODULE__) @impl true def membrane_element_type, do: :filter @impl true def handle_caps(_pad, caps, _context, state), do: {{:ok, forward: caps}, state} @impl true def handle_event(_pad, event, _context, state), do: {{:ok, forward: event}, state} @impl true def handle_process(_pad, _buffer, _context, state), do: {{:error, :handle_process_not_implemented}, state} @impl true def handle_process_list(pad, buffers, _context, state) do args_list = buffers |> Enum.map(&[pad, &1]) {{:ok, split: {:handle_process, args_list}}, state} end @impl true def handle_end_of_stream(pad, _context, state), do: {{:ok, forward: :end_of_stream}, state} defoverridable handle_caps: 4, handle_event: 4, handle_process_list: 4, handle_process: 4, handle_end_of_stream: 3 end end end
lib/membrane/filter.ex
0.877483
0.512693
filter.ex
starcoder
defmodule Chex.Piece do @moduledoc false alias Chex.{Board, Game} @callback possible_moves(Chex.game(), Chex.square(), Chex.color()) :: [Chex.square()] @callback attacking_squares(Chex.game(), Chex.square(), Chex.color()) :: [Chex.square()] @spec possible_moves(Chex.game(), Chex.square()) :: [Chex.square()] | [] def possible_moves(game, square) do {name, color, _id} = game.board[square] to_module(name).possible_moves(game, square, color) |> Enum.reject(&Board.occupied_by_color?(game, color, &1)) |> Enum.reject(fn sq -> {:ok, {_piece, _capture, psudo_game}} = Board.move(game, square, sq) Game.in_check?(psudo_game, color) end) end @spec attacking_squares(Chex.game(), Chex.square()) :: [Chex.square()] def attacking_squares(game, square) do case game.board[square] do {name, color, _id} -> to_module(name).attacking_squares(game, square, color) _ -> [] end end @spec from_string(String.t()) :: Chex.piece() def from_string(str) do {piece_from_string(str), color_from_string(str)} end @doc """ Removes the trailing starting square from a three element tuple. Returns a piece(). This is useful as the piece data stored in the game.board contains the piece's starting square as a means of identification. ## Examples iex> Chex.Piece.trim({:pawn, :white, {:e, 2}}) {:pawn, :white} """ @spec trim({Chex.name(), Chex.color(), Chex.square()}) :: Chex.piece() def trim({name, color, _start}), do: {name, color} @spec piece_from_string(String.t()) :: atom defp piece_from_string(str) when byte_size(str) == 1 do %{ "k" => :king, "q" => :queen, "b" => :bishop, "n" => :knight, "r" => :rook, "p" => :pawn } |> Map.get(String.downcase(str, :ascii)) end @spec color_from_string(String.t()) :: atom defp color_from_string(str) when byte_size(str) == 1 do str_up = str |> String.upcase(:ascii) if str == str_up, do: :white, else: :black end def to_string({name, color, _id}), do: __MODULE__.to_string({name, color}) def to_string({name, color}) do %{ king: "k", queen: "q", bishop: "b", knight: "n", rook: "r", pawn: "p" }[name] |> case_for_color(color) end @spec to_module(name :: Chex.name()) :: module() def to_module(name) do name = name |> Kernel.to_string() |> String.capitalize() Module.concat([Chex.Piece, name]) end @spec case_for_color(String.t(), atom) :: String.t() def case_for_color(char, :white), do: String.upcase(char) def case_for_color(char, _black), do: char end
lib/chex/piece.ex
0.852076
0.572962
piece.ex
starcoder
defmodule Farmbot.Firmware.Gcode.Param do @moduledoc "Firmware paramaters." @doc "Turn a number into a param, or a param into a number." @spec parse_param(integer | t) :: t | integer def parse_param(0), do: :param_version def parse_param(1), do: :param_test def parse_param(2), do: :param_config_ok def parse_param(3), do: :param_use_eeprom def parse_param(4), do: :param_e_stop_on_mov_err def parse_param(5), do: :param_mov_nr_retry def parse_param(11), do: :movement_timeout_x def parse_param(12), do: :movement_timeout_y def parse_param(13), do: :movement_timeout_z def parse_param(15), do: :movement_keep_active_x def parse_param(16), do: :movement_keep_active_y def parse_param(17), do: :movement_keep_active_z def parse_param(18), do: :movement_home_at_boot_x def parse_param(19), do: :movement_home_at_boot_y def parse_param(20), do: :movement_home_at_boot_z def parse_param(21), do: :movement_invert_endpoints_x def parse_param(22), do: :movement_invert_endpoints_y def parse_param(23), do: :movement_invert_endpoints_z def parse_param(25), do: :movement_enable_endpoints_x def parse_param(26), do: :movement_enable_endpoints_y def parse_param(27), do: :movement_enable_endpoints_z def parse_param(31), do: :movement_invert_motor_x def parse_param(32), do: :movement_invert_motor_y def parse_param(33), do: :movement_invert_motor_z def parse_param(36), do: :movement_secondary_motor_x def parse_param(37), do: :movement_secondary_motor_invert_x def parse_param(41), do: :movement_steps_acc_dec_x def parse_param(42), do: :movement_steps_acc_dec_y def parse_param(43), do: :movement_steps_acc_dec_z def parse_param(45), do: :movement_stop_at_home_x def parse_param(46), do: :movement_stop_at_home_y def parse_param(47), do: :movement_stop_at_home_z def parse_param(51), do: :movement_home_up_x def parse_param(52), do: :movement_home_up_y def parse_param(53), do: :movement_home_up_z def parse_param(55), do: :movement_step_per_mm_x def parse_param(56), do: :movement_step_per_mm_y def parse_param(57), do: :movement_step_per_mm_z def parse_param(61), do: :movement_min_spd_x def parse_param(62), do: :movement_min_spd_y def parse_param(63), do: :movement_min_spd_z def parse_param(65), do: :movement_home_spd_x def parse_param(66), do: :movement_home_spd_y def parse_param(67), do: :movement_home_spd_z def parse_param(71), do: :movement_max_spd_x def parse_param(72), do: :movement_max_spd_y def parse_param(73), do: :movement_max_spd_z def parse_param(101), do: :encoder_enabled_x def parse_param(102), do: :encoder_enabled_y def parse_param(103), do: :encoder_enabled_z def parse_param(105), do: :encoder_type_x def parse_param(106), do: :encoder_type_y def parse_param(107), do: :encoder_type_z def parse_param(111), do: :encoder_missed_steps_max_x def parse_param(112), do: :encoder_missed_steps_max_y def parse_param(113), do: :encoder_missed_steps_max_z def parse_param(115), do: :encoder_scaling_x def parse_param(116), do: :encoder_scaling_y def parse_param(117), do: :encoder_scaling_z def parse_param(121), do: :encoder_missed_steps_decay_x def parse_param(122), do: :encoder_missed_steps_decay_y def parse_param(123), do: :encoder_missed_steps_decay_z def parse_param(125), do: :encoder_use_for_pos_x def parse_param(126), do: :encoder_use_for_pos_y def parse_param(127), do: :encoder_use_for_pos_z def parse_param(131), do: :encoder_invert_x def parse_param(132), do: :encoder_invert_y def parse_param(133), do: :encoder_invert_z def parse_param(141), do: :movement_axis_nr_steps_x def parse_param(142), do: :movement_axis_nr_steps_y def parse_param(143), do: :movement_axis_nr_steps_z def parse_param(145), do: :movement_stop_at_max_x def parse_param(146), do: :movement_stop_at_max_y def parse_param(147), do: :movement_stop_at_max_z def parse_param(201), do: :pin_guard_1_pin_nr def parse_param(202), do: :pin_guard_1_time_out def parse_param(203), do: :pin_guard_1_active_state def parse_param(205), do: :pin_guard_2_pin_nr def parse_param(206), do: :pin_guard_2_time_out def parse_param(207), do: :pin_guard_2_active_state def parse_param(211), do: :pin_guard_3_pin_nr def parse_param(212), do: :pin_guard_3_time_out def parse_param(213), do: :pin_guard_3_active_state def parse_param(215), do: :pin_guard_4_pin_nr def parse_param(216), do: :pin_guard_4_time_out def parse_param(217), do: :pin_guard_4_active_state def parse_param(221), do: :pin_guard_5_pin_nr def parse_param(222), do: :pin_guard_5_time_out def parse_param(223), do: :pin_guard_5_active_state def parse_param(:param_version), do: 0 def parse_param(:param_test), do: 1 def parse_param(:param_config_ok), do: 2 def parse_param(:param_use_eeprom), do: 3 def parse_param(:param_e_stop_on_mov_err), do: 4 def parse_param(:param_mov_nr_retry), do: 5 def parse_param(:movement_timeout_x), do: 11 def parse_param(:movement_timeout_y), do: 12 def parse_param(:movement_timeout_z), do: 13 def parse_param(:movement_keep_active_x), do: 15 def parse_param(:movement_keep_active_y), do: 16 def parse_param(:movement_keep_active_z), do: 17 def parse_param(:movement_home_at_boot_x), do: 18 def parse_param(:movement_home_at_boot_y), do: 19 def parse_param(:movement_home_at_boot_z), do: 20 def parse_param(:movement_invert_endpoints_x), do: 21 def parse_param(:movement_invert_endpoints_y), do: 22 def parse_param(:movement_invert_endpoints_z), do: 23 def parse_param(:movement_enable_endpoints_x), do: 25 def parse_param(:movement_enable_endpoints_y), do: 26 def parse_param(:movement_enable_endpoints_z), do: 27 def parse_param(:movement_invert_motor_x), do: 31 def parse_param(:movement_invert_motor_y), do: 32 def parse_param(:movement_invert_motor_z), do: 33 def parse_param(:movement_secondary_motor_x), do: 36 def parse_param(:movement_secondary_motor_invert_x), do: 37 def parse_param(:movement_steps_acc_dec_x), do: 41 def parse_param(:movement_steps_acc_dec_y), do: 42 def parse_param(:movement_steps_acc_dec_z), do: 43 def parse_param(:movement_stop_at_home_x), do: 45 def parse_param(:movement_stop_at_home_y), do: 46 def parse_param(:movement_stop_at_home_z), do: 47 def parse_param(:movement_home_up_x), do: 51 def parse_param(:movement_home_up_y), do: 52 def parse_param(:movement_home_up_z), do: 53 def parse_param(:movement_step_per_mm_x), do: 55 def parse_param(:movement_step_per_mm_y), do: 56 def parse_param(:movement_step_per_mm_z), do: 57 def parse_param(:movement_min_spd_x), do: 61 def parse_param(:movement_min_spd_y), do: 62 def parse_param(:movement_min_spd_z), do: 63 def parse_param(:movement_home_spd_x), do: 65 def parse_param(:movement_home_spd_y), do: 66 def parse_param(:movement_home_spd_z), do: 67 def parse_param(:movement_max_spd_x), do: 71 def parse_param(:movement_max_spd_y), do: 72 def parse_param(:movement_max_spd_z), do: 73 def parse_param(:encoder_enabled_x), do: 101 def parse_param(:encoder_enabled_y), do: 102 def parse_param(:encoder_enabled_z), do: 103 def parse_param(:encoder_type_x), do: 105 def parse_param(:encoder_type_y), do: 106 def parse_param(:encoder_type_z), do: 107 def parse_param(:encoder_missed_steps_max_x), do: 111 def parse_param(:encoder_missed_steps_max_y), do: 112 def parse_param(:encoder_missed_steps_max_z), do: 113 def parse_param(:encoder_scaling_x), do: 115 def parse_param(:encoder_scaling_y), do: 116 def parse_param(:encoder_scaling_z), do: 117 def parse_param(:encoder_missed_steps_decay_x), do: 121 def parse_param(:encoder_missed_steps_decay_y), do: 122 def parse_param(:encoder_missed_steps_decay_z), do: 123 def parse_param(:encoder_use_for_pos_x), do: 125 def parse_param(:encoder_use_for_pos_y), do: 126 def parse_param(:encoder_use_for_pos_z), do: 127 def parse_param(:encoder_invert_x), do: 131 def parse_param(:encoder_invert_y), do: 132 def parse_param(:encoder_invert_z), do: 133 def parse_param(:movement_axis_nr_steps_x), do: 141 def parse_param(:movement_axis_nr_steps_y), do: 142 def parse_param(:movement_axis_nr_steps_z), do: 143 def parse_param(:movement_stop_at_max_x), do: 145 def parse_param(:movement_stop_at_max_y), do: 146 def parse_param(:movement_stop_at_max_z), do: 147 def parse_param(:pin_guard_1_pin_nr), do: 201 def parse_param(:pin_guard_1_time_out), do: 202 def parse_param(:pin_guard_1_active_state), do: 203 def parse_param(:pin_guard_2_pin_nr), do: 205 def parse_param(:pin_guard_2_time_out), do: 206 def parse_param(:pin_guard_2_active_state), do: 207 def parse_param(:pin_guard_3_pin_nr), do: 211 def parse_param(:pin_guard_3_time_out), do: 212 def parse_param(:pin_guard_3_active_state), do: 213 def parse_param(:pin_guard_4_pin_nr), do: 215 def parse_param(:pin_guard_4_time_out), do: 216 def parse_param(:pin_guard_4_active_state), do: 217 def parse_param(:pin_guard_5_pin_nr), do: 221 def parse_param(:pin_guard_5_time_out), do: 222 def parse_param(:pin_guard_5_active_state), do: 223 @typedoc "Human readable param name." @type t :: :param_config_ok | :param_use_eeprom | :param_e_stop_on_mov_err | :param_mov_nr_retry | :movement_timeout_x | :movement_timeout_y | :movement_timeout_z | :movement_keep_active_x | :movement_keep_active_y | :movement_keep_active_z | :movement_home_at_boot_x | :movement_home_at_boot_y | :movement_home_at_boot_z | :movement_invert_endpoints_x | :movement_invert_endpoints_y | :movement_invert_endpoints_z | :movement_enable_endpoints_x | :movement_enable_endpoints_y | :movement_enable_endpoints_z | :movement_invert_motor_x | :movement_invert_motor_y | :movement_invert_motor_z | :movement_secondary_motor_x | :movement_secondary_motor_invert_x | :movement_steps_acc_dec_x | :movement_steps_acc_dec_y | :movement_steps_acc_dec_z | :movement_stop_at_home_x | :movement_stop_at_home_y | :movement_stop_at_home_z | :movement_home_up_x | :movement_home_up_y | :movement_home_up_z | :movement_step_per_mm_x | :movement_step_per_mm_y | :movement_step_per_mm_z | :movement_min_spd_x | :movement_min_spd_y | :movement_min_spd_z | :movement_home_spd_x | :movement_home_spd_y | :movement_home_spd_z | :movement_max_spd_x | :movement_max_spd_y | :movement_max_spd_z | :encoder_enabled_x | :encoder_enabled_y | :encoder_enabled_z | :encoder_type_x | :encoder_type_y | :encoder_type_z | :encoder_missed_steps_max_x | :encoder_missed_steps_max_y | :encoder_missed_steps_max_z | :encoder_scaling_x | :encoder_scaling_y | :encoder_scaling_z | :encoder_missed_steps_decay_x | :encoder_missed_steps_decay_y | :encoder_missed_steps_decay_z | :encoder_use_for_pos_x | :encoder_use_for_pos_y | :encoder_use_for_pos_z | :encoder_invert_x | :encoder_invert_y | :encoder_invert_z | :movement_axis_nr_steps_x | :movement_axis_nr_steps_y | :movement_axis_nr_steps_z | :movement_stop_at_max_x | :movement_stop_at_max_y | :movement_stop_at_max_z | :pin_guard_1_pin_nr | :pin_guard_1_time_out | :pin_guard_1_active_state | :pin_guard_2_pin_nr | :pin_guard_2_time_out | :pin_guard_2_active_state | :pin_guard_3_pin_nr | :pin_guard_3_time_out | :pin_guard_3_active_state | :pin_guard_4_pin_nr | :pin_guard_4_time_out | :pin_guard_4_active_state | :pin_guard_5_pin_nr | :pin_guard_5_time_out | :pin_guard_5_active_state end
lib/farmbot/firmware/gcode/param.ex
0.665519
0.678999
param.ex
starcoder
defmodule SmartGlobal.Guard do defguard is_simple(x) when is_atom(x) or is_number(x) or is_binary(x) or is_bitstring(x) defguard is_var(x) when is_tuple(x) and :erlang.size(x) == 2 and elem(x, 0) == :var and is_atom(elem(x, 1)) end defmodule SmartGlobal.Error do defexception [:message] @impl true def exception(value) do msg = "can't encode complex argument #{inspect(value)}" %__MODULE__{message: msg} end end defmodule SmartGlobal do @moduledoc """ SmartGlobal allows you to use a beam module as read-only store. Such module can be generated at the application startup and send to other nodes to load. Doesn't support updates, but the module can be regenerated with different bindings. Supports _ wildcard to return the default value. Example: ``` SmartGlobal.new( XXX, %{fun1: [{[:a, :b, :c], :three_little_piggies}, {[:xx, :yy], [1,2,3,5]}, {[:cc, 123], <<1,2,3,4,5>>}, {[:_], :default}], fun2: %{a: 100, b: 200, _: :yaya}} ) ``` will generate a module which when decompied to Elixir would look like: ``` defmodule XXX do def fun1(:a, :b, :c), do: :three_little_piggies def fun1(:xx, :yy), do: [1,2,3,5] def fun1(:cc, 123), do: <<1,2,3,4,5>> def fun1(_), do: :default def fun2(:a), do: 100 def fun2(:b), do: 200 def fun2(_), do: :yaya end ``` """ import :erl_parse, only: [abstract: 1] import __MODULE__.Guard alias __MODULE__.Error def new(mod_name, mod_mapping) do with {:ok, ^mod_name, mod_binary} <- module(mod_name, mod_mapping) do :code.purge(mod_name) :code.load_binary(mod_name, '#{mod_name}.erl', mod_binary) {:ok, mod_name} end end def module(mod_name, mod_mapping), do: forms(mod_name, mod_mapping) |> :compile.forms([:verbose, :report_errors]) def forms(mod_name, mod_mapping) when not is_nil(mod_name) and is_atom(mod_name) do fun_groups = mod_mapping |> Enum.map(fn {fun, mapping} when is_atom(fun) -> {fun, groups(mapping)} end) |> Enum.into(%{}) [{:attribute, 0, :module, mod_name}, {:attribute, 0, :export, Enum.flat_map(fun_groups, fn {fun, groups} -> for arity <- Map.keys(groups), do: {fun, arity} end)} | Enum.flat_map(fun_groups, fn {fun, groups} -> Enum.map(groups, fn {arity, argsval} -> {:function, 0, fun, arity, Enum.map(argsval, fn {args, val} -> {:clause, 0, Enum.map(args, &abstract_arg/1), [], [ret_expr(val)]} end)} end) end)] end def abstract_arg(:_), do: {:var, 0, :_} def abstract_arg({:var, n}) when is_atom(n), do: {:var, 0, arg_name(n)} def abstract_arg(x), do: abstract(x) def arg_name(x) when is_atom(x), do: :"_#{x}@1" def ret_expr({:"$call", mod, name, args}) when is_atom(name) and is_list(args), do: {:call, 0, {:remote, 0, {:atom, 0, mod}, {:atom, 7, name}}, Enum.map(args, &abstract_arg/1)} def ret_expr(val), do: abstract(val) defp groups(argsvals) when is_list(argsvals), do: Enum.group_by(argsvals, fn {args, _} -> Enum.each(args, &(is_simple(&1) || is_var(&1) || raise Error, value: &1)) Enum.count(args) end) defp groups(argvals) when is_map(argvals) do group1 = argvals |> Map.drop([:_]) |> Enum.reduce([], fn {arg, val}, acc -> &(is_simple(&1) || is_var(&1) || raise Error, value: &1) [{[arg], val} | acc] end) %{1 => Enum.reverse(case Map.get(argvals, :_, nil) do nil -> group1 val -> [{[:_], val} | group1] end)} end end
lib/smart_global.ex
0.627837
0.770162
smart_global.ex
starcoder
defmodule ExHeap do @moduledoc """ ExHeap is a small wrapper for sending tracking and user data to Heap Analytic's Server-Side API. It takes care of forming the requests, headers, etc, but mostly lets you pass through your data untouched. Basic usage: ```elixir iex> ExHeap.track("<EMAIL>", "My Heap Event", %{"extra_id" => 1234}) {:ok, %HTTPoison.Response{...}} iex> ExHeap.add_user_properties("<EMAIL>", %{"company_name" => "MegaCorp"}) {:ok, %HTTPoison.Response{...}} ``` """ @root_url "https://heapanalytics.com/api" @spec track(any, any, any) :: {:error, HTTPoison.Error.t()} | {:ok, %{ :__struct__ => HTTPoison.AsyncResponse | HTTPoison.Response, optional(:body) => any, optional(:headers) => [any], optional(:id) => reference, optional(:request) => HTTPoison.Request.t(), optional(:request_url) => any, optional(:status_code) => integer }} @doc """ Track a user event https://developers.heap.io/reference#track-1 * `identity` - string to identify the user (probably an email) * `event` - event name to pass to Heap * `properties` - arbitrary map of key/value pairs to annotate event ## Examples iex> ExHeap.track("<EMAIL>","My Event") {:ok, %HTTPoison.Response{...}} iex> ExHeap.track("<EMAIL>","My Event", %{"custom_property" => "foo"}) {:ok, %HTTPoison.Response{...}} """ def track(identity, event, properties \\ %{}) do {:ok, datetime} = DateTime.now("Etc/UTC") %{ "app_id" => get_config!(:app_id), "events" => [ %{ "identity" => identity, "timestamp" => datetime |> DateTime.to_iso8601(), "event" => event, "properties" => properties } ] } |> post(track_url()) end @doc """ Assign customer properties to a user https://developers.heap.io/reference#add-user-properties * `identity` - string to identify the user (probably an email) * `properties` - arbitrary map of key/value pairs enrich user data ## Examples iex> ExHeap.add_user_properties("<EMAIL>", %{"key" => "value"}) {:ok, %HTTPoison.Response{...}} """ def add_user_properties(identity, properties \\ %{}) do %{ "app_id" => get_config!(:app_id), "identity" => identity, "properties" => properties } |> post(add_user_properties_url()) end defp track_url(), do: "#{@root_url}/track" defp add_user_properties_url(), do: "#{@root_url}/add_user_properties" defp post(data, url) do headers = %{ "Content-type" => "application/json" } |> Map.to_list() options = Application.get_env(:ex_heap, :httpoison, []) HTTPoison.request(:post, url, Poison.encode!(data), headers, options) end defp get_config(key, default \\ nil) when is_atom(key) do case Application.fetch_env(:ex_heap, key) do {:ok, {:system, env_var}} -> System.get_env(env_var) {:ok, value} -> value :error -> default end end defp get_config!(key) do get_config(key) || raise "ex_unit config #{key} is required" end end
lib/ex_heap.ex
0.872327
0.665721
ex_heap.ex
starcoder
defmodule Xtree do @moduledoc """ Builds an X-Tree Each node has: - `n_id` - (integer() >= 0) The unique ID in the tree """ alias Xtree.Util alias Xtree.Protocol defstruct n_id: 0, type: :element, label: "", value: "", index: 0, idx_label: "", id_attr?: false, nMD: "", tMD: "", iMD: "", # nPtr: nil, # op: :nop, children: [], parent_ids: [], ref: nil @type n_id() :: non_neg_integer() @type node_type() :: :element | :text @type op() :: :nop | :del | :mov | :ins | :upd | :copy @type t() :: %__MODULE__{ n_id: n_id(), type: node_type(), label: String.t(), value: String.t(), index: non_neg_integer(), idx_label: String.t(), id_attr?: boolean(), nMD: String.t(), tMD: String.t(), iMD: String.t(), # nPtr: nil | t(), # op: :nop | op(), children: list(t()), parent_ids: list(n_id()), ref: any() } def build(nil) do build_empty() end def build(node) do {root, _last_n_id} = build_node(node) root end def build_empty() do %__MODULE__{n_id: -1} end defp build_node(node, index \\ 0, n_id \\ 0, parent_ids \\ []) defp build_node(%__MODULE__{} = node, _, _, _) do node end defp build_node(node, index, n_id, parent_ids) do label = Protocol.name(node) value = Protocol.value(node) # uniquely identify each node {iMD, has_id_attr} = case Protocol.id(node) do nil -> {Util.hash(label), false} "" -> {Util.hash(label), false} uid -> {Util.hash(label <> uid), true} end # Node digest (label + value) nMD = Util.hash(label <> value) {children, last_n_id} = node |> Protocol.children() |> build_children(%{}, n_id + 1, [n_id | parent_ids]) # children = Enum.reverse(children) # Tree message digest tMD = Util.hash(nMD <> concat_tMD(children)) {%__MODULE__{ n_id: n_id, type: Protocol.type(node), label: label, index: index, value: value, idx_label: ".#{label}[#{index}]", id_attr?: has_id_attr, # Node message digest nMD: nMD, # ID message digest iMD: iMD, # Tree message digest tMD: tMD, children: children, parent_ids: parent_ids, ref: node }, last_n_id} end # Build children, by assigning indexes based on sibling label defp build_children([], _, last_n_id, _parent_ids) do {[], last_n_id} end defp build_children([node | nodes], idx_map, last_n_id, parent_ids) when is_list(nodes) do {%__MODULE__{label: label} = child, last_n_id} = build_node(node, 0, last_n_id, parent_ids) index = case Map.get(idx_map, label, nil) do nil -> 0 value -> value + 1 end idx_map = Map.put(idx_map, label, index) {children, last_n_id} = build_children(nodes, idx_map, last_n_id, parent_ids) # Update both index and idx_label {[%{child | index: index, idx_label: ".#{label}[#{index}]"} | children], last_n_id} end defp concat_tMD([]) do "" end defp concat_tMD([%__MODULE__{tMD: tMD} | nodes]) do tMD <> concat_tMD(nodes) end end
lib/xtree.ex
0.712532
0.428054
xtree.ex
starcoder
defmodule MT940.StatementLineInformation do @moduledoc ~S""" ## Information to Account Owner Additional information about the transaction detailed in the preceding statement line and which is to be passed on to the account owner. """ defstruct [ :modifier, :content, :code, :transaction_description, :prima_nota, :bank_code, :account_number, :text_key_extension, details: [], account_holder: [], not_implemented_fields: [] ] @type t :: %__MODULE__{} use MT940.Field defp parse_content(result = %__MODULE__{content: content}) do s = ~r/\A(\d{3})((.).*)?\z/s |> Regex.run(content, capture: :all_but_first) result = case s do [code | _] -> %__MODULE__{result | code: code |> String.to_integer} _ -> result end case s do [_, text, separator] -> "#{Regex.escape(separator)}(\\d{2})([^#{Regex.escape(separator)}]*)" |> Regex.compile! |> Regex.scan(text, capture: :all_but_first) |> Enum.map(fn [code, content] -> [code |> String.to_integer, content] end) |> Enum.reduce(result, &assign_sub_fields/2) [_] -> result _ -> %__MODULE__{result | details: [content]} end end defp assign_sub_fields([0, transaction_description], acc = %__MODULE__{}) do %__MODULE__{acc | transaction_description: transaction_description} end defp assign_sub_fields([10, prima_nota], acc = %__MODULE__{}) do %__MODULE__{acc | prima_nota: prima_nota |> String.to_integer} end defp assign_sub_fields([d, detail], acc = %__MODULE__{details: details}) when (d >= 20 and d <= 29) or (d >= 60 and d <= 63) do details = case details do nil -> [detail] _ -> details ++ [detail] end %__MODULE__{acc | details: details} end defp assign_sub_fields([30, bank_code], acc = %__MODULE__{}) do %__MODULE__{acc | bank_code: bank_code} end defp assign_sub_fields([31, account_number], acc = %__MODULE__{}) do %__MODULE__{acc | account_number: account_number} end defp assign_sub_fields([ah, new_account_holder], acc = %__MODULE__{account_holder: account_holder}) when ah >= 32 and ah <= 33 do account_holder = case account_holder do nil -> [new_account_holder] _ -> account_holder ++ [new_account_holder] end %__MODULE__{acc | account_holder: account_holder} end defp assign_sub_fields([34, text_key_extension], acc = %__MODULE__{}) do %__MODULE__{acc | text_key_extension: text_key_extension |> String.to_integer} end defp assign_sub_fields(unknown, acc = %__MODULE__{not_implemented_fields: not_implemented_fields}) do not_implemented_fields = case not_implemented_fields do nil -> [unknown] _ -> not_implemented_fields ++ [unknown] end %__MODULE__{acc | not_implemented_fields: not_implemented_fields} end end
lib/model/statement_line_information.ex
0.670285
0.401365
statement_line_information.ex
starcoder
defmodule Sanity.Pbuf.Tests.EverythingType do @moduledoc false use Protobuf, enum: true, syntax: :proto3 @type t :: integer | :EVERYTHING_TYPE_UNKNOWN | :EVERYTHING_TYPE_SAND | :EVERYTHING_TYPE_SPICE field :EVERYTHING_TYPE_UNKNOWN, 0 field :EVERYTHING_TYPE_SAND, 1 field :EVERYTHING_TYPE_SPICE, 2 end defmodule Sanity.Pbuf.Tests.Everything.Corpus do @moduledoc false use Protobuf, enum: true, syntax: :proto3 @type t :: integer | :UNIVERSAL | :WEB | :IMAGES | :LOCAL | :NEWS | :PRODUCTS | :VIDEO field :UNIVERSAL, 0 field :WEB, 1 field :IMAGES, 2 field :LOCAL, 3 field :NEWS, 4 field :PRODUCTS, 5 field :VIDEO, 6 end defmodule Sanity.Pbuf.Tests.Everything.Map1Entry do @moduledoc false use Protobuf, map: true, syntax: :proto3 @type t :: %__MODULE__{ key: String.t(), value: integer } defstruct [:key, :value] field :key, 1, type: :string field :value, 2, type: :int32 end defmodule Sanity.Pbuf.Tests.Everything.Map2Entry do @moduledoc false use Protobuf, map: true, syntax: :proto3 @type t :: %__MODULE__{ key: integer, value: float | :infinity | :negative_infinity | :nan } defstruct [:key, :value] field :key, 1, type: :int64 field :value, 2, type: :float end defmodule Sanity.Pbuf.Tests.Everything.Map3Entry do @moduledoc false use Protobuf, map: true, syntax: :proto3 @type t :: %__MODULE__{ key: non_neg_integer, value: Sanity.Pbuf.Tests.Child.t() | nil } defstruct [:key, :value] field :key, 1, type: :uint32 field :value, 2, type: Sanity.Pbuf.Tests.Child end defmodule Sanity.Pbuf.Tests.Everything do @moduledoc false use Protobuf, syntax: :proto3 @type t :: %__MODULE__{ choice: {atom, any}, bool: boolean, int32: integer, int64: integer, uint32: non_neg_integer, uint64: non_neg_integer, sint32: integer, sint64: integer, fixed32: non_neg_integer, fixed64: non_neg_integer, sfixed32: integer, sfixed64: integer, float: float | :infinity | :negative_infinity | :nan, double: float | :infinity | :negative_infinity | :nan, string: String.t(), bytes: binary, struct: Sanity.Pbuf.Tests.Child.t() | nil, type: Sanity.Pbuf.Tests.EverythingType.t(), corpus: Sanity.Pbuf.Tests.Everything.Corpus.t(), user: Sanity.Pbuf.Tests.Sub.User.t() | nil, user_status: Sanity.Pbuf.Tests.Sub.UserStatus.t(), bools: [boolean], int32s: [integer], int64s: [integer], uint32s: [non_neg_integer], uint64s: [non_neg_integer], sint32s: [integer], sint64s: [integer], fixed32s: [non_neg_integer], sfixed32s: [integer], fixed64s: [non_neg_integer], sfixed64s: [integer], floats: [float | :infinity | :negative_infinity | :nan], doubles: [float | :infinity | :negative_infinity | :nan], strings: [String.t()], bytess: [binary], structs: [Sanity.Pbuf.Tests.Child.t()], types: [[Sanity.Pbuf.Tests.EverythingType.t()]], corpuss: [[Sanity.Pbuf.Tests.Everything.Corpus.t()]], map1: %{String.t() => integer}, map2: %{integer => float | :infinity | :negative_infinity | :nan}, map3: %{non_neg_integer => Sanity.Pbuf.Tests.Child.t() | nil} } defstruct [ :choice, :bool, :int32, :int64, :uint32, :uint64, :sint32, :sint64, :fixed32, :fixed64, :sfixed32, :sfixed64, :float, :double, :string, :bytes, :struct, :type, :corpus, :user, :user_status, :bools, :int32s, :int64s, :uint32s, :uint64s, :sint32s, :sint64s, :fixed32s, :sfixed32s, :fixed64s, :sfixed64s, :floats, :doubles, :strings, :bytess, :structs, :types, :corpuss, :map1, :map2, :map3 ] oneof :choice, 0 field :bool, 1, type: :bool field :int32, 2, type: :int32 field :int64, 3, type: :int64 field :uint32, 4, type: :uint32 field :uint64, 5, type: :uint64 field :sint32, 6, type: :sint32 field :sint64, 7, type: :sint64 field :fixed32, 8, type: :fixed32 field :fixed64, 9, type: :fixed64 field :sfixed32, 10, type: :sfixed32 field :sfixed64, 11, type: :sfixed64 field :float, 12, type: :float field :double, 13, type: :double field :string, 14, type: :string field :bytes, 15, type: :bytes field :struct, 16, type: Sanity.Pbuf.Tests.Child field :type, 17, type: Sanity.Pbuf.Tests.EverythingType, enum: true field :corpus, 18, type: Sanity.Pbuf.Tests.Everything.Corpus, enum: true field :choice_int32, 19, type: :int32, oneof: 0 field :choice_string, 20, type: :string, oneof: 0 field :user, 21, type: Sanity.Pbuf.Tests.Sub.User field :user_status, 22, type: Sanity.Pbuf.Tests.Sub.UserStatus, enum: true field :bools, 31, repeated: true, type: :bool field :int32s, 32, repeated: true, type: :int32 field :int64s, 33, repeated: true, type: :int64 field :uint32s, 34, repeated: true, type: :uint32 field :uint64s, 35, repeated: true, type: :uint64 field :sint32s, 36, repeated: true, type: :sint32 field :sint64s, 37, repeated: true, type: :sint64 field :fixed32s, 38, repeated: true, type: :fixed32 field :sfixed32s, 39, repeated: true, type: :sfixed32 field :fixed64s, 40, repeated: true, type: :fixed64 field :sfixed64s, 41, repeated: true, type: :sfixed64 field :floats, 42, repeated: true, type: :float field :doubles, 43, repeated: true, type: :double field :strings, 44, repeated: true, type: :string field :bytess, 45, repeated: true, type: :bytes field :structs, 46, repeated: true, type: Sanity.Pbuf.Tests.Child field :types, 47, repeated: true, type: Sanity.Pbuf.Tests.EverythingType, enum: true field :corpuss, 48, repeated: true, type: Sanity.Pbuf.Tests.Everything.Corpus, enum: true field :map1, 61, repeated: true, type: Sanity.Pbuf.Tests.Everything.Map1Entry, map: true field :map2, 62, repeated: true, type: Sanity.Pbuf.Tests.Everything.Map2Entry, map: true field :map3, 63, repeated: true, type: Sanity.Pbuf.Tests.Everything.Map3Entry, map: true end defmodule Sanity.Pbuf.Tests.Child do @moduledoc false use Protobuf, syntax: :proto3 @type t :: %__MODULE__{ id: non_neg_integer, name: String.t(), data1: binary, data2: binary, data3: binary } defstruct [:id, :name, :data1, :data2, :data3] field :id, 1, type: :uint32 field :name, 2, type: :string field :data1, 3, type: :bytes field :data2, 4, type: :bytes field :data3, 5, type: :bytes end
test/schemas/generated/sanity.everything.pb.ex
0.669096
0.608361
sanity.everything.pb.ex
starcoder
defmodule Nebulex.Adapters.Nil do @moduledoc """ The **Nil adapter** is a special cache adapter that disables the cache; it loses all the items saved on it and it returns `nil` for all the read and `true` for all save operations. This adapter is mostly useful for tests. ## Example Suppose you have an application using Ecto for database access and Nebulex for caching. Then, you have defined a cache and a repo within it. Since you are using a database, there might be some cases you may want to disable the cache to avoid issues when running the test, for example, in some test cases, when accessing the database you expect no data at all, but you could retrieve the data from cache anyway because maybe it was cached in a previous test. Therefore, you have to delete all entries from the cache before to run each test to make sure the cache is always empty. This is where the Nil adapter comes in, instead of adding code to flush the cache before each test, you could define a test cache using the Nil adapter for the tests. One one hand, you have defined the cache in your application within `lib/my_app/cache.ex`: defmodule MyApp.Cache do use Nebulex.Cache, otp_app: :my_app, adapter: Nebulex.Adapters.Local end And on the other hand, in the tests you have defined the test cache within `test/support/test_cache.ex`: defmodule MyApp.TestCache do use Nebulex.Cache, otp_app: :my_app, adapter: Nebulex.Adapters.Nil end Now, we have to tell the app what cache to use depending on the environment, for tests we want `MyApp.TestCache`, otherwise it is always `MyApp.Cache`. We can do this very easy by introducing a new config parameter to decide what cache module to use. For tests you can define the config `config/test.exs`: config :my_app, nebulex_cache: MyApp.TestCache, ... The final piece is to read the config parameter and start the cache properly. Within `lib/my_app/application.ex` you could have: def start(_type, _args) do children = [ {Application.get_env(:my_app, :nebulex_cache, MyApp.Cache), []}, ] ... As you can see, by default `MyApp.Cache` is always used, unless the `:nebulex_cache` option points to a different module, which will be when tests are executed (`:test` env). """ # Provide Cache Implementation @behaviour Nebulex.Adapter @behaviour Nebulex.Adapter.Entry @behaviour Nebulex.Adapter.Queryable @behaviour Nebulex.Adapter.Persistence @behaviour Nebulex.Adapter.Stats # Inherit default transaction implementation use Nebulex.Adapter.Transaction ## Nebulex.Adapter @impl true defmacro __before_compile__(_env), do: :ok @impl true def init(_opts) do child_spec = Supervisor.child_spec({Agent, fn -> :ok end}, id: {Agent, 1}) {:ok, child_spec, %{}} end ## Nebulex.Adapter.Entry @impl true def get(_, _, _), do: nil @impl true def get_all(_, _, _), do: %{} @impl true def put(_, _, _, _, _, _), do: true @impl true def put_all(_, _, _, _, _), do: true @impl true def delete(_, _, _), do: :ok @impl true def take(_, _, _), do: nil @impl true def has_key?(_, _), do: false @impl true def ttl(_, _), do: nil @impl true def expire(_, _, _), do: true @impl true def touch(_, _), do: true @impl true def update_counter(_, _, amount, _, default, _), do: default + amount ## Nebulex.Adapter.Queryable @impl true def execute(_, :all, _, _), do: [] def execute(_, _, _, _), do: 0 @impl true def stream(_, _, _), do: Stream.each([], & &1) ## Nebulex.Adapter.Persistence @impl true def dump(_, _, _), do: :ok @impl true def load(_, _, _), do: :ok ## Nebulex.Adapter.Stats @impl true def stats(_), do: %Nebulex.Stats{} end
lib/nebulex/adapters/nil.ex
0.859
0.578895
nil.ex
starcoder
defprotocol Plymio.Vekil.Forom do @moduledoc ~S""" The `Plymio.Vekil.Forom` protocol is implemented by the values returned by the *vekil* accessor functions (e.g. `Plymio.Vekil.proxy_fetch/2`). See `Plymio.Vekil` for a general overview and explanation of the documentation terms. ## Implementation Modules' State See `Plymio.Vekil` for other common fields. All implementations have these fields in their `struct` which can e.g. be pattern matched. | Field | Aliases | Purpose | | :--- | :--- | :--- | | `:produce_default` | *:produce_default* | *holds the produce default value* | | `:realise_default` | *:answer_default* | *holds the realise default value* | ### Module State Field: `:produce_default` This field can hold a default value `produce/2` can use / return as the *product*. For example, some *forom* return a `Keyword` as their *product* and `:produce_default` is an empty list. ### Module State Field: `:realise_default` This field can hold a default value `realise/2` can use / return as the *answer*. It could be, for example, *the unset value* (`Plymio.Fontais.the_unset_value/0`) """ @dialyzer {:nowarn_function, __protocol__: 1} @type error :: Plymio.Vekil.error() @type opts :: Plymio.Vekil.opts() @type proxy :: any @type proxies :: nil | proxy | [proxy] @type forom :: any @type product :: Keyword @type answer :: any @doc ~S""" `update/2` takes a *forom* and optional *opts* and updates the fields in the *forom* with the `{field,value}` tuples in the *opts*, returning `{:ok, forom}`. All implementations should be prepared to be passed values for the *vekil* and / or *proxy* fields. """ @spec update(t, opts) :: {:ok, t} | {:error, error} def update(forom, opts) @doc ~S""" `produce/1` takes a *forom* and "produces" the *forom* to create the *product*, returning `{:ok, {product, forom}}`. The protocol does not define what the *product* will be, but most implemenations return a `Keyword` with zero, one or more `:forom` keys, together with other implementation-specific keys. (The `@spec` for produce uses the type `product` which is defined as a `Keyword` by default.) Producing the *forom* may change it. """ @spec produce(t) :: {:ok, {product, t}} | {:error, error} def produce(forom) @doc ~S""" `produce/2` takes a *forom* and optional *opts*, calls `update/2` with the *vekil* and the *opts*, and then "produces" the *forom* to create the *product*, returning `{:ok, {product, forom}}`. The protocol does not define what the *product* will be, but often will be a `Keyword`. Producing the *forom* may change it. """ @spec produce(t, opts) :: {:ok, {product, t}} | {:error, error} def produce(forom, opts) @doc ~S""" `realise/1` takes a *forom* the realises the *forom* to create the *answer* returning `{:ok, {answer, forom}}`. Usually `realise/1` calls `produce/1` and then transforms the *product* to generate the *answer* returning `{:ok, {answer, forom}}`. """ @spec realise(t) :: {:ok, {answer, t}} | {:error, error} def realise(forom) @doc ~S""" `realise/2` takes a *forom* and optional *opts* the realises the *forom* to create the *answer* returning `{:ok, {answer, forom}}`. Usually `realise/2` calls `produce/2` and reduces the *product* in some way to generate the *answer". """ @spec realise(t, opts) :: {:ok, {answer, t}} | {:error, error} def realise(forom, opts) end
lib/vekil/protocol/forom.ex
0.906963
0.768386
forom.ex
starcoder
defmodule ExRandomString do @moduledoc """ Library for generating random strings. Based on NodeJS library [randomstring](https://www.npmjs.com/package/randomstring). ## Installation The package can be installed by adding `ex_random_string` to your list of dependencies in `mix.exs`: ```elixir def deps do [ {:ex_random_string, "~> 1.0.1"} ] end ``` ## Usage ```elixir ExRandomString.generate() # "XwPp9xazJ0ku5CZnlmgAx2Dld8SHkAeT" ExRandomString.generate(7); # "xqm5wXX" ExRandomString.generate(length: 12, charset: :alphabetic) # "AqoTIzKurxJi" ExRandomString.generate(charset: ~w(a b c)); # "accbaabbbbcccbccccaacacbbcbbcbbc" ``` """ @numeric ~w(1 2 3 4 6 7 8 9 0) @alpha ~w(a b c d e f g h i j k l m n o p q r s t u v w x y z) @hex @numeric ++ ~w(a b c d e f) @alphanumeric @alpha ++ @numeric @default_options [charset: :alphanumeric, length: 32] @doc """ Generates a random string that is 32 characters long and alphanumeric. """ def generate do generate(@default_options[:length]) end @doc """ When provided an integer, it generates a random string with the provided integer as length. String returned will be alphanumeric. When provided a Keyword list, it generates a random string with properties based on the provided options. ## Options Listed below are the supported options. Each of the options are optional. * `length` -- the length of the random string. (default: 32) * `charset` -- define the character set for the string. (default: `:alphanumeric`) * `:alphanumeric` -- [0-9a-zA-Z] * `:alphabetic` -- [a-zA-Z] * `:numeric` -- [0-9] * `:hex` -- [0-9a-f] * any string -- will generate based on the string's set of characters * `case` -- define whether the output should be lowercase / uppercase only. (default: `nil`) * `:lower` -- forces all characters to use lower case * `:upper` -- forces all characters to use upper case * `:mix` -- randomizes the case of each character ## Examples ``` ExRandomString.generate(7) # "xqm5wXX" ExRandomString.generate(length: 12, charset: :alphabetic) # "AqoTIzKurxJi" ExRandomString.generate(charset: "ABC", case: :lower) # "abaccabaacbaabcccabacbacccacbbbb" ``` """ def generate(options) def generate(length) when is_integer(length) do generate(length: length) end def generate(options) do options = with_default_options(options) characters = characters_for_charset(options[:charset]) character_count = Enum.count(characters) Stream.repeatedly(fn -> random_character(characters, character_count) end) |> Stream.map(case_modifier(options)) |> Stream.take(options[:length]) |> Enum.join("") end defp characters_for_charset(charset) do case charset do :alphanumeric -> @alphanumeric :alphabetic -> @alpha :numeric -> @numeric :hex -> @hex characters -> String.graphemes(characters) end end defp random_character(characters, character_count) do random_index = :rand.uniform(character_count) - 1 Enum.at(characters, random_index) end defp case_modifier(options) do case options[:case] do :upper -> &String.upcase/1 :lower -> &String.downcase/1 :mix -> &randomize_case/1 _ -> case_modifier_for_charset(options[:charset]) end end defp case_modifier_for_charset(charset) do identity = &(&1) case charset do :alphanumeric -> &randomize_case/1 :alphabetic -> &randomize_case/1 :numeric -> identity :hex -> identity _ -> identity end end defp randomize_case(character) do case :rand.uniform(2) do 1 -> String.downcase(character) 2 -> String.upcase(character) end end defp with_default_options(options) do Keyword.merge(@default_options, options) end end
lib/ex_random_string.ex
0.858006
0.864368
ex_random_string.ex
starcoder
defmodule Pummpcomm.History.AlarmSensor do @moduledoc """ An alarm raised on the pump on behalf of the CGM. """ use Bitwise alias Pummpcomm.{BloodGlucose, DateDecoder} @behaviour Pummpcomm.History.Decoder # CONSTANTS # TODO change to atom to match Pummpcomm.History.AlarmPump and because dialyzer can check for errors easier with atoms # than String.t @alarm_types %{ 0x65 => "High Glucose", 0x66 => "Low Glucose", 0x68 => "Meter BG Now", 0x69 => "Cal Reminder", 0x6A => "Calibration Error", 0x6B => "Sensor End", 0x70 => "Weak Signal", 0x71 => "Lost Sensor", 0x73 => "Low Glucose Predicted" } # Types @typedoc """ Type of alarm raised for the CGM. * `"High Glucose"` - CGM blood glucose exceeds sensor high glucose limit * `"Low Glucose"` - CGM blood glucose is below sensor low glucose limit * `"Meter BG Now"` - CGM needs a meter blood glucose NOW to contiue reporting CGM blood glucose. * `"Cal Reminder"` - CGM needs a meter blood glucose SOON to continue reporting CGM blood glucose. * `"Calibration Error"` - Meter blood glucose differed too much from expected blood glucose, so CGM value cannot be trusted. * `"Sensor End"` - Sensor has been in for 6 days. Replace with new sensor. * `"Weak Signal"` - Signal to noise ratio is too low when pump is receiving data from CGM. Move Pump closer to CGM. * `"Lost Sensor"` - Signal from CGM went noisier than `"Weak Signal"` and communication was completely lost. Move CGM closer to pump, then go to `Sensor` > `Link to Sensor` > `Find Lost Sensor`. * `"Low Glucose Predicted"` - Due to rate of blood glucose change as measured by CGM, you are likely to hit `"Low Glucose"` soon. Use meter blood glucose to confirm and eat something to correct if meter confirms CGM. """ @type alarm_type :: String.t() # Functions ## Pummpcomm.History.Decoder callbacks @impl Pummpcomm.History.Decoder @spec decode(binary, Pummpcomm.PumpModel.pump_options()) :: %{ alarm_type: alarm_type, amount: BloodGlucose.blood_glucose(), timestamp: NaiveDateTime.t() } | %{ alarm_type: alarm_type, timestamp: NaiveDateTime.t() } def decode(<<0x65, amount::8, timestamp::binary-size(5)>>, _) do decode(0x65, %{amount: amount(amount, timestamp)}, timestamp) end def decode(<<0x66, amount::8, timestamp::binary-size(5)>>, _) do decode(0x66, %{amount: amount(amount, timestamp)}, timestamp) end def decode(<<alarm_type::8, _::8, timestamp::binary-size(5)>>, _) do decode(alarm_type, %{}, timestamp) end ## Private Functions defp amount(amount, timestamp) do <<_::32, high_bit::1, _::7>> = timestamp (high_bit <<< 8) + amount end defp decode(alarm_type, alarm_params, timestamp) do Map.merge( %{ timestamp: DateDecoder.decode_history_timestamp(timestamp), alarm_type: Map.get(@alarm_types, alarm_type, "Unknown") }, alarm_params ) end end
lib/pummpcomm/history/alarm_sensor.ex
0.57093
0.508361
alarm_sensor.ex
starcoder
defmodule Pushest.Socket.Data.Presence do @moduledoc ~S""" Structure representing presence information, connected user IDs and data of them. """ defstruct count: 0, hash: %{}, ids: [], me: %{} @doc ~S""" Merges current Presence struct with new presence data frame. Always keeps :me part from current state. ## Examples iex> Pushest.Socket.Data.Presence.merge(%Pushest.Socket.Data.Presence{count: 1, ids: [1]}, nil) %Pushest.Socket.Data.Presence{count: 1, ids: [1]} iex> Pushest.Socket.Data.Presence.merge( ...> %Pushest.Socket.Data.Presence{me: %{user_id: 1}}, ...> %{"count" => 1, "ids" => [1]} ...> ) %Pushest.Socket.Data.Presence{count: 1, ids: [1], hash: nil, me: %{user_id: 1}} """ @spec merge(%__MODULE__{}, %__MODULE__{} | nil) :: %__MODULE__{} def merge(current, nil), do: current def merge(current, next) do decoded = decode(next) %__MODULE__{ count: decoded.count, hash: decoded.hash, ids: decoded.ids, me: current.me } end @doc ~S""" Adds new user data to a Presence struct and returns new one containg the merge. Used when member_added event is being fired to merge new user to local presence. ## Examples iex> Pushest.Socket.Data.Presence.add_member( ...> %Pushest.Socket.Data.Presence{me: %{user_id: "1"}, count: 1, ids: ["1"], hash: %{"1" => nil}}, ...> %{"user_id" => "2", "user_info" => %{"name" => "<NAME>"}} ...> ) %Pushest.Socket.Data.Presence{ me: %{user_id: "1"}, count: 2, ids: ["2", "1"], hash: %{"1" => nil, "2" => %{"name" => "<NAME>"}} } """ @spec add_member(%__MODULE__{}, map) :: %__MODULE__{} def add_member(%__MODULE__{count: count, hash: hash, ids: ids, me: me}, %{ "user_id" => user_id, "user_info" => user_info }) do %__MODULE__{ count: count + 1, ids: [user_id | ids], hash: Map.merge(hash, %{user_id => user_info}), me: me } end @doc ~S""" Removes user data from a Presence struct and returns new one without given user data. Used when member_removed event is being fired to remove that user from local presence. ## Examples iex> Pushest.Socket.Data.Presence.remove_member( ...> %Pushest.Socket.Data.Presence{me: %{user_id: "1"}, count: 2, ids: ["1", "2"], hash: %{"1" => nil, "2" => nil}}, ...> %{"user_id" => "2"} ...> ) %Pushest.Socket.Data.Presence{ me: %{user_id: "1"}, count: 1, ids: ["1"], hash: %{"1" => nil} } """ @spec remove_member(%__MODULE__{}, map) :: %__MODULE__{} def remove_member(%__MODULE__{count: count, hash: hash, ids: ids, me: me}, %{ "user_id" => user_id }) do %__MODULE__{ count: count - 1, ids: List.delete(ids, user_id), hash: Map.delete(hash, user_id), me: me } end @spec decode(map) :: %__MODULE__{} defp decode(presence) do %__MODULE__{ count: presence["count"], hash: presence["hash"], ids: presence["ids"] } end end
lib/pushest/socket/data/presence.ex
0.771112
0.438004
presence.ex
starcoder
defmodule Bolt.Cogs.Role.Deny do @moduledoc false @behaviour Nosedrum.Command alias Bolt.Converters alias Bolt.Helpers alias Bolt.Humanizer alias Bolt.ModLog alias Bolt.Repo alias Bolt.Schema.SelfAssignableRoles alias Nosedrum.Predicates alias Nostrum.Api @impl true def usage, do: ["role deny <role:role...>"] @impl true def description, do: """ Remove the given role from the self-assignable roles. Self-assignable roles are special roles that can be assigned my members through bot commands. Requires the `MANAGE_ROLES` permission. **Examples**: ```rs // no longer allow self-assginment of the 'Movie Nighter' role role deny movie nighter ``` """ @impl true def predicates, do: [&Predicates.guild_only/1, Predicates.has_permission(:manage_roles)] @impl true def parse_args(args), do: Enum.join(args, " ") @impl true def command(msg, "") do response = "ℹ️ usage: `role deny <role:role...>`" {:ok, _msg} = Api.create_message(msg.channel_id, response) end def command(msg, role_name) do response = case Converters.to_role(msg.guild_id, role_name, true) do {:ok, role} -> existing_row = Repo.get(SelfAssignableRoles, msg.guild_id) cond do existing_row == nil -> "🚫 this guild has no self-assignable roles" role.id not in existing_row.roles -> "🚫 role `#{Helpers.clean_content(role.name)}` is not self-assignable" true -> updated_row = %{ roles: Enum.reject(existing_row.roles, &(&1 == role.id)) } changeset = SelfAssignableRoles.changeset(existing_row, updated_row) {:ok, _updated_row} = Repo.update(changeset) ModLog.emit( msg.guild_id, "CONFIG_UPDATE", "#{Humanizer.human_user(msg.author)} removed" <> " #{Humanizer.human_role(msg.guild_id, role)} from self-assignable roles" ) "👌 role #{Humanizer.human_role(msg.guild_id, role)} is no longer self-assignable" end {:error, reason} -> "🚫 cannot convert `#{Helpers.clean_content(role_name)}` to `role`: #{reason}" end {:ok, _msg} = Api.create_message(msg.channel_id, response) end end
lib/bolt/cogs/role/deny.ex
0.860208
0.497864
deny.ex
starcoder
defmodule Himamo.BaumWelch.StepE do alias Himamo.Logzero import Logzero @moduledoc ~S""" Defines components of the E-step of the Baum-Welch algorithm (Expectation). Calculates required statistics for the given model. """ alias Himamo.{Matrix, Model, ObsSeq} @doc ~S""" Computes alpha variable for Baum-Welch. `α_t(i)` is the probability of being in state `S_i` at time `t` after observing the first `t` symbols. Returns tuple of tuples (size `T×N`) where: * `T` - length of observation sequence * `N` - number of states in the model """ @spec compute_alpha(Model.t, ObsSeq.t) :: Matrix.t def compute_alpha(%Model{a: a, pi: pi, n: num_states}, %ObsSeq{len: seq_len, prob: obs_prob}) do states_range = 0..num_states-1 obs_range = 1..seq_len-1 # initialization first_row = for j <- states_range do lhs = Model.Pi.get(pi, j) rhs = Model.ObsProb.get(obs_prob, {j, 0}) product = ext_log_product(ext_log(lhs), ext_log(rhs)) {{0, j}, product} end |> Enum.into(Matrix.new({seq_len, num_states})) # induction Enum.reduce(obs_range, first_row, fn(t, partial_alpha) -> for j <- states_range do b_j = Model.ObsProb.get(obs_prob, {j, t}) log_alpha = for i <- states_range do ext_log_product( Matrix.get(partial_alpha, {t-1, i}), ext_log(Model.A.get(a, {i, j})) ) end |> sum_log_values product = ext_log_product(log_alpha, ext_log(b_j)) {{t, j}, product} end |> Enum.into(partial_alpha) end) end @doc ~S""" Computes beta variable for Baum-Welch. `ß_t(i)` is the probability of being in state `S_i` at time `t` and observing the partial sequence from `t+1` to the end. Returns tuple of tuples (size `T×N`) where: * `T` - length of observation sequence * `N` - number of states in the model """ @spec compute_beta(Model.t, ObsSeq.t) :: Matrix.t def compute_beta(%Model{a: a, n: num_states}, %ObsSeq{len: seq_len, prob: obs_prob}) do states_range = 0..num_states-1 # initialization last_row = for j <- states_range do {{seq_len-1, j}, 0.0} end |> Enum.into(Matrix.new({seq_len, num_states})) # induction Enum.reduce((seq_len-2)..0, last_row, fn(t, partial_beta) -> for i <- states_range do log_beta = for j <- states_range do transition_prob = Model.A.get(a, {i, j}) emission_prob = Model.ObsProb.get(obs_prob, {j, t+1}) prev_beta = Matrix.get(partial_beta, {t+1, j}) ext_log_product( ext_log(transition_prob), ext_log_product(ext_log(emission_prob), prev_beta) ) end |> sum_log_values {{t, i}, log_beta} end |> Enum.into(partial_beta) end) end @doc ~S""" Computes xi variable for Baum-Welch. `ξ_t(i,j)` is the probability of being in state `S_i` at time `t` and in state `S_j` at time `t+1` given the full observation sequence. Returns tuple of tuples of tuples (size `T×N×N`) where: * `T` - length of observation sequence * `N` - number of states in the model """ @spec compute_xi(Model.t, ObsSeq.t, [alpha: Matrix.t, beta: Matrix.t]) :: Matrix.t def compute_xi( %Model{n: num_states} = model, %ObsSeq{len: seq_len, prob: obs_prob}, alpha: alpha, beta: beta ) do Enum.flat_map((0..seq_len-2), fn(t) -> compute_xi_row(model, alpha, beta, obs_prob, t) end) |> Enum.into(Matrix.new({seq_len-1, num_states, num_states})) end @doc false def compute_xi_row(%Model{a: a, n: num_states}, alpha, beta, obs_prob, t) do states_range = 0..num_states-1 log_xi = for i <- states_range, j <- states_range do curr_alpha = Matrix.get(alpha, {t, i}) curr_a = Model.A.get(a, {i, j}) curr_b_map = Model.ObsProb.get(obs_prob, {j, t+1}) curr_beta = Matrix.get(beta, {t+1, j}) product = ext_log_product( curr_alpha, ext_log_product( ext_log(curr_a), ext_log_product( ext_log(curr_b_map), curr_beta))) {{i, j}, product} end |> Enum.into(Matrix.new({num_states, num_states})) normalizer = Enum.reduce(log_xi.map, Logzero.const, fn {{_i, _j}, element}, sum -> ext_log_sum(sum, element) end) for i <- states_range, j <- states_range do curr_log_xi = Matrix.get(log_xi, {i, j}) product = ext_log_product(curr_log_xi, -normalizer) {{t, i, j}, product} end end @doc ~S""" Computes gamma variable for Baum-Welch. `γ_t(i)` is the probability of being in state `S_i` at time `t` given the full observation sequence. Returns tuple of tuples (size `T×N`) where: * `T` - length of observation sequence * `N` - number of states in the model """ @spec compute_gamma(Model.t, ObsSeq.t, [xi: Matrix.t]) :: Matrix.t def compute_gamma(%Model{n: num_states}, obs_seq, xi: xi) do seq_len = obs_seq.len for t <- 0..seq_len-2, i <- 0..num_states-1 do sum = Enum.map(0..num_states-1, fn(j) -> Matrix.get(xi, {t, i, j}) end) |> sum_log_values {{t, i}, sum} end |> Enum.into(Matrix.new({seq_len-1, num_states})) end @doc ~S""" Computes a Matrix where each element is `alpha_{t, i} * beta_{t, i}`. This is not matrix multiplication. The result of the above expression is used in multiple places, so the values are computed up front. """ @spec compute_alpha_times_beta(Matrix.t, Matrix.t) :: Matrix.t def compute_alpha_times_beta(%Matrix{size: size} = alpha, %Matrix{size: size} = beta) do {seq_len, num_states} = size for t <- 0..seq_len-1, i <- 0..num_states-1 do key = {t, i} curr_log_alpha = Matrix.get(alpha, {t, i}) curr_log_beta = Matrix.get(beta, {t, i}) value = ext_log_product(curr_log_alpha, curr_log_beta) {key, value} end |> Enum.into(Matrix.new({seq_len, num_states})) end end
lib/himamo/baum_welch/step_e.ex
0.852537
0.792544
step_e.ex
starcoder
defmodule Symbelix do alias Symbelix.Expression @moduledoc """ Expression parser and evaluator. """ @spec run(source :: String.t(), library :: Module.t()) :: any() @doc """ Runs a program specified by the source code `source` together with the function library `library`. Returns the result of the program, or an {:error, message} tuple in case of an error. ## Examples: iex> Symbelix.run("(add 1 2)", Mathematician) 3 iex> Symbelix.run("(sub 1 2)", Mathematician) {:error, "Unknown function (atom) 'sub' at line 1 with 2 parameter(s): (1 2)"} iex> Symbelix.run("(sub (add 1 2) 1)", Mathematician) {:error, "Unknown function (atom) 'sub' at line 1 with 2 parameter(s): ((add 1 2) 1)"} iex> Symbelix.run("(first [1 2])", ListProcessor) 1 """ def run(source, library, debug \\ fn x, _ -> x end) do with {:ok, code} <- Expression.parse(source), ^code <- debug.(code, label: "code"), {:ok, ast} <- compile(code, library), ^ast <- debug.(ast, label: "ast") do case ast do {:proc, proc} -> {:proc, proc} |> debug.([]) _ -> {result, _binding} = Code.eval_quoted(ast) result |> debug.([]) end else error -> error |> debug.([]) end end @doc """ Compiles a symbolic expression to Elixir AST. ## Examples: iex> compile([{:atom, 1, 'add'}, {:number, 1, 1}, {:number, 1, 2}], Mathematician) {:ok, {:apply, [context: Symbelix.Library, import: Kernel], [Symbelix.TestHelpers.Libraries.Mathematician, :add, [[1, 2]]]}} iex> compile([{:atom, 1, 'aliens'}, {:atom, 1, 'built'}, {:atom, 1, 'it'}], Mathematician) {:error, "Unknown function (atom) 'aliens' at line 1 with 2 parameter(s): (built it)"} iex> compile([{:atom, 1, '<?php'}], PHP) {:error, "The module PHP doesn't exist"} iex> compile([{:atom, 1, 'public'}], Java) {:error, "The module Symbelix.TestHelpers.Libraries.Java doesn't implement Symbelix.Library behaviour"} iex> compile([{:atom, 1, 'proc'}, {:atom, 1, 'add'}, {:number, 1, 1}, {:number, 1, 2}], Mathematician) {:ok, {:proc, [{:atom, 1, 'add'}, {:number, 1, 1}, {:number, 1, 2}]}} """ def compile([{:atom, _line, 'eval'} | [[{:atom, _, 'proc'} | code]]], library) do {:ok, ast} = compile(code, library) {:ok, ast} end def compile([{:atom, _line, 'eval'} | [params]], library) do {:ok, ast} = compile(params, library) {{:proc, code}, []} = Code.eval_quoted(ast) {{:ok, result}, []} = compile(code, library) |> Code.eval_quoted() {:ok, result} end def compile([{:atom, _, 'proc'} | params], _) do {:ok, {:proc, params}} end def compile([{type, line, name} | params], library) do if Code.ensure_compiled?(library) do values = Enum.map(params, &value_of(&1, library)) try do case library.generate_ast([name] ++ values) do {:ok, ast} -> {:ok, ast} {:error, :no_such_implementation} -> values_description = params |> Enum.map(&show/1) |> Enum.join(" ") {:error, "Unknown function (#{type}) '#{name}' at line #{line} with #{Enum.count(values)} parameter(s): (#{ values_description })"} end rescue UndefinedFunctionError -> {:error, "The module #{inspect(library)} doesn't implement Symbelix.Library behaviour"} end else {:error, "The module #{inspect(library)} doesn't exist"} end end def repl(library \\ Symbelix.Library.Standard) do unless Process.whereis(Symbelix.Library.Memory) do {:ok, memory} = Symbelix.Library.Memory.start_link() Process.register(memory, Symbelix.Library.Memory) end source = IO.gets("> ") case source do :eof -> IO.puts("\nGoodbye") "q\n" -> IO.puts("Goodbye") "r\n" -> IO.inspect(IEx.Helpers.recompile(), label: "recompile") repl(library) source -> try do run(source, library, &IO.inspect/2) rescue exception -> IO.puts("Error: #{inspect(exception)}") IO.inspect(__STACKTRACE__, label: "stacktrace") end repl(library) end end defp show({:number, _, value}), do: "#{value}" defp show({:atom, _, value}), do: "#{value}" defp show({:string, _, value}), do: "#{value}" defp show({:list, value}), do: inspect(value) defp show([x | tail]), do: "(" <> show(x) <> show_tail(tail) defp show_tail([x | tail]), do: " " <> show(x) <> show_tail(tail) defp show_tail([]), do: ")" defp value_of({:number, _, value}, _), do: value defp value_of({:atom, _, value}, _), do: value defp value_of({:string, _, value}, _), do: value defp value_of({:list, value}, binding), do: Enum.map(value, &value_of(&1, binding)) defp value_of([{:atom, _line, 'proc'} | proc], _) do {:proc, Macro.escape(proc)} end defp value_of(expression, library) when is_list(expression) do {:ok, ast} = compile(expression, library) ast end end
lib/symbelix.ex
0.802633
0.570571
symbelix.ex
starcoder