code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def get_state(self) -> Mapping[str, Any]: """Retrieves replay state as a dictionary (e.g. for serialization).""" return { # Serialize OrderedDict as a simpler, more common data structure. 'storage': list(self._storage.items()), 't': self._t, 'distribution': self._distribution.get...
Retrieves replay state as a dictionary (e.g. for serialization).
get_state
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def set_state(self, state: Mapping[str, Any]) -> None: """Sets replay state from a (potentially de-serialized) dictionary.""" self._storage = collections.OrderedDict(state['storage']) self._t = state['t'] self._distribution.set_state(state['distribution'])
Sets replay state from a (potentially de-serialized) dictionary.
set_state
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def _power(base, exponent) -> np.ndarray: """Same as usual power except `0 ** 0` is zero.""" # By default 0 ** 0 is 1 but we never want indices with priority zero to be # sampled, even if the priority exponent is zero. base = np.asarray(base) return np.where(base == 0.0, 0.0, base**exponent)
Same as usual power except `0 ** 0` is zero.
_power
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def importance_sampling_weights( probabilities: np.ndarray, uniform_probability: float, exponent: float, normalize: bool, ) -> np.ndarray: """Calculates importance sampling weights from given sampling probabilities. Args: probabilities: Array of sampling probabilities for a subset of items. Sin...
Calculates importance sampling weights from given sampling probabilities. Args: probabilities: Array of sampling probabilities for a subset of items. Since this is a subset the probabilites will typically not sum to `1`. uniform_probability: Probability of sampling an item if uniformly sampling. ex...
importance_sampling_weights
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def get(self, indices: Sequence[int]) -> np.ndarray: """Gets values corresponding to given indices.""" indices = np.asarray(indices) if not ((0 <= indices) & (indices < self.size)).all(): raise IndexError('index out of range, expect 0 <= index < %s' % self.size) return self.values[indices]
Gets values corresponding to given indices.
get
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def set(self, indices: Sequence[int], values: Sequence[float]) -> None: """Sets values at the given indices.""" values = np.asarray(values) if not np.isfinite(values).all() or (values < 0.0).any(): raise ValueError('value must be finite and positive.') self.values[indices] = values storage = s...
Sets values at the given indices.
set
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def set_all(self, values: Sequence[float]) -> None: """Sets many values all at once, also setting size of the sum tree.""" values = np.asarray(values) if not np.isfinite(values).all() or (values < 0.0).any(): raise ValueError('Values must be finite positive numbers.') self._initialize(len(values),...
Sets many values all at once, also setting size of the sum tree.
set_all
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def get_state(self) -> Mapping[str, Any]: """Retrieves sum tree state as a dictionary (e.g. for serialization).""" return { 'size': self._size, 'storage': self._storage, 'first_leaf': self._first_leaf, }
Retrieves sum tree state as a dictionary (e.g. for serialization).
get_state
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def set_state(self, state: Mapping[str, Any]) -> None: """Sets sum tree state from a (potentially de-serialized) dictionary.""" self._size = state['size'] self._storage = state['storage'] self._first_leaf = state['first_leaf']
Sets sum tree state from a (potentially de-serialized) dictionary.
set_state
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def _initialize(self, size: int, values: Optional[Sequence[float]]) -> None: """Resizes storage and sets new values if supplied.""" assert size >= 0 assert values is None or len(values) == size if size < self.size: # Keep storage and values, zero out extra values. if values is None: new_...
Resizes storage and sets new values if supplied.
_initialize
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def _set_values(self, values: Sequence[float]) -> None: """Sets values assuming storage has enough capacity and update sums.""" # Note every part of the storage is set here. assert len(values) <= self.capacity storage = self._storage storage[self._first_leaf : self._first_leaf + len(values)] = value...
Sets values assuming storage has enough capacity and update sums.
_set_values
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def _query_single(self, target: float) -> int: """Queries a single target, see query for more detailed documentation.""" if not 0.0 <= target < self.root(): raise ValueError('Require 0 <= target < total sum.') storage = self._storage idx = 1 # Root node. while idx < self._first_leaf: #...
Queries a single target, see query for more detailed documentation.
_query_single
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def ensure_capacity(self, capacity: int) -> None: """Ensures sufficient capacity, a no-op if capacity is already enough.""" if self._max_capacity is not None and capacity > self._max_capacity: raise ValueError( 'capacity %d cannot exceed max_capacity %d' % (capacity, self._max_capacity...
Ensures sufficient capacity, a no-op if capacity is already enough.
ensure_capacity
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def remove_priorities(self, ids: Sequence[int]) -> None: """Remove priorities associated with given IDs.""" indices = [] for i in ids: try: idx = self._id_to_index[i] except IndexError as err: raise IndexError('Cannot remove ID %d, it does not exist.' % i) from err indices....
Remove priorities associated with given IDs.
remove_priorities
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def sample(self, size: int) -> Tuple[np.ndarray, np.ndarray]: """Returns sample of IDs with corresponding probabilities.""" if self.size == 0: raise RuntimeError('No IDs to sample.') uniform_indices = [ self._active_indices[j] for j in self._random_state.randint(self.size, size=size) ...
Returns sample of IDs with corresponding probabilities.
sample
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def get_exponentiated_priorities(self, ids: Sequence[int]) -> Sequence[float]: """Returns priority ** priority_exponent for the given indices.""" indices = np.fromiter( (self._id_to_index[i] for i in ids), dtype=np.int64, count=len(ids) ) return self._sum_tree.get(indices)
Returns priority ** priority_exponent for the given indices.
get_exponentiated_priorities
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def add(self, item: ReplayStructure, priority: float) -> None: """Adds a single item with a given priority to the replay buffer.""" if self.size == self._capacity: oldest_id, _ = self._storage.popitem(last=False) self._distribution.remove_priorities([oldest_id]) item_id = self._t self._dist...
Adds a single item with a given priority to the replay buffer.
add
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def step( self, timestep_t: dm_env.TimeStep, a_t: parts.Action ) -> Iterable[Transition]: """Accumulates timestep and resulting action, maybe yield a transition.""" if timestep_t.first(): self.reset() if self._timestep_tm1 is None: if not timestep_t.first(): raise ValueError('Ex...
Accumulates timestep and resulting action, maybe yield a transition.
step
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def reset(self) -> None: """Resets the accumulator. Following timestep is expected to be `FIRST`.""" self._timestep_tm1 = None self._a_tm1 = None
Resets the accumulator. Following timestep is expected to be `FIRST`.
reset
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def _build_n_step_transition(transitions): """Builds a single n-step transition from n 1-step transitions.""" r_t = 0.0 discount_t = 1.0 for transition in transitions: r_t += discount_t * transition.r_t discount_t *= transition.discount_t # n-step transition, letting s_tm1 = s_tmn, and a_tm1 = a_tmn....
Builds a single n-step transition from n 1-step transitions.
_build_n_step_transition
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def step( self, timestep_t: dm_env.TimeStep, a_t: parts.Action ) -> Iterable[Transition]: """Accumulates timestep and resulting action, yields transitions.""" if timestep_t.first(): self.reset() # There are no transitions on the first timestep. if self._timestep_tm1 is None: assert ...
Accumulates timestep and resulting action, yields transitions.
step
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def reset(self) -> None: """Resets the accumulator. Following timestep is expected to be FIRST.""" self._transitions.clear() self._timestep_tm1 = None self._a_tm1 = None
Resets the accumulator. Following timestep is expected to be FIRST.
reset
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def uncompress_array(compressed: CompressedArray) -> np.ndarray: """Uncompresses a numpy array with snappy given its shape and dtype.""" compressed_array, shape, dtype = compressed byte_string = snappy.uncompress(compressed_array) return np.frombuffer(byte_string, dtype=dtype).reshape(shape)
Uncompresses a numpy array with snappy given its shape and dtype.
uncompress_array
python
google-deepmind/dqn_zoo
dqn_zoo/replay.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay.py
Apache-2.0
def resize(self, size: int) -> None: """Resizes tree, truncating or expanding with zeros as needed.""" # Usually there shouldn't be references to self._values, but to prevent # certain Coverage test errors, we pass refcheck=False. self._values.resize(size, refcheck=False)
Resizes tree, truncating or expanding with zeros as needed.
resize
python
google-deepmind/dqn_zoo
dqn_zoo/replay_test.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay_test.py
Apache-2.0
def _query_single(self, target: float) -> int: """Queries a single target, see `SumTree.query` for more documentation.""" if not 0.0 <= target < self.root(): raise ValueError('Require 0 <= target < total sum.') acc_sum = 0.0 for i in range(self.size): acc_sum += self.values[i] if targe...
Queries a single target, see `SumTree.query` for more documentation.
_query_single
python
google-deepmind/dqn_zoo
dqn_zoo/replay_test.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/replay_test.py
Apache-2.0
def loss_fn(online_params, target_params, transitions, rng_key): """Calculates loss given network parameters and transitions.""" _, online_key, target_key = jax.random.split(rng_key, 3) logits_q_tm1 = network.apply( online_params, online_key, transitions.s_tm1 ).q_logits logits_t...
Calculates loss given network parameters and transitions.
loss_fn
python
google-deepmind/dqn_zoo
dqn_zoo/c51/agent.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/c51/agent.py
Apache-2.0
def update(rng_key, opt_state, online_params, target_params, transitions): """Computes learning update from batch of replay transitions.""" rng_key, update_key = jax.random.split(rng_key) d_loss_d_params = jax.grad(loss_fn)( online_params, target_params, transitions, update_key ) ...
Computes learning update from batch of replay transitions.
update
python
google-deepmind/dqn_zoo
dqn_zoo/c51/agent.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/c51/agent.py
Apache-2.0
def step(self, timestep: dm_env.TimeStep) -> parts.Action: """Selects action given timestep and potentially learns.""" self._frame_t += 1 timestep = self._preprocessor(timestep) if timestep is None: # Repeat action. if self._action is None: raise RuntimeError('Cannot repeat if action ha...
Selects action given timestep and potentially learns.
step
python
google-deepmind/dqn_zoo
dqn_zoo/c51/agent.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/c51/agent.py
Apache-2.0
def _act(self, timestep) -> parts.Action: """Selects action given timestep, according to epsilon-greedy policy.""" s_t = timestep.observation self._rng_key, a_t, v_t = self._select_action( self._rng_key, self._online_params, s_t, self.exploration_epsilon ) a_t, v_t = jax.device_get((a_t, v_t...
Selects action given timestep, according to epsilon-greedy policy.
_act
python
google-deepmind/dqn_zoo
dqn_zoo/c51/agent.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/c51/agent.py
Apache-2.0
def _learn(self) -> None: """Samples a batch of transitions from replay and learns from it.""" logging.log_first_n(logging.INFO, 'Begin learning', 1) transitions = self._replay.sample(self._batch_size) self._rng_key, self._opt_state, self._online_params = self._update( self._rng_key, sel...
Samples a batch of transitions from replay and learns from it.
_learn
python
google-deepmind/dqn_zoo
dqn_zoo/c51/agent.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/c51/agent.py
Apache-2.0
def statistics(self) -> Mapping[str, float]: """Returns current agent statistics as a dictionary.""" # Check for DeviceArrays in values as this can be very slow. assert all( not isinstance(x, jnp.DeviceArray) for x in self._statistics.values() ) return self._statistics
Returns current agent statistics as a dictionary.
statistics
python
google-deepmind/dqn_zoo
dqn_zoo/c51/agent.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/c51/agent.py
Apache-2.0
def main(argv): """Trains Double DQN agent on Atari.""" del argv logging.info( 'Double DQN on Atari on %s.', jax.lib.xla_bridge.get_backend().platform ) random_state = np.random.RandomState(_SEED.value) rng_key = jax.random.PRNGKey( random_state.randint(-sys.maxsize - 1, sys.maxsize + 1, dtype=n...
Trains Double DQN agent on Atari.
main
python
google-deepmind/dqn_zoo
dqn_zoo/double_q/run_atari.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/double_q/run_atari.py
Apache-2.0
def _sample_tau( rng_key: parts.PRNGKey, shape: Tuple[int, ...], ) -> jnp.ndarray: """Samples tau values uniformly between 0 and 1.""" return jax.random.uniform(rng_key, shape=shape)
Samples tau values uniformly between 0 and 1.
_sample_tau
python
google-deepmind/dqn_zoo
dqn_zoo/iqn/agent.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/iqn/agent.py
Apache-2.0
def main(argv): """Trains Prioritized DQN agent on Atari.""" del argv logging.info( 'Prioritized DQN on Atari on %s.', jax.lib.xla_bridge.get_backend().platform, ) random_state = np.random.RandomState(_SEED.value) rng_key = jax.random.PRNGKey( random_state.randint(-sys.maxsize - 1, sys.max...
Trains Prioritized DQN agent on Atari.
main
python
google-deepmind/dqn_zoo
dqn_zoo/prioritized/run_atari.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/prioritized/run_atari.py
Apache-2.0
def main(argv): """Trains QR-DQN agent on Atari.""" del argv logging.info( 'QR-DQN on Atari on %s.', jax.lib.xla_bridge.get_backend().platform ) random_state = np.random.RandomState(_SEED.value) rng_key = jax.random.PRNGKey( random_state.randint(-sys.maxsize - 1, sys.maxsize + 1, dtype=np.int64)...
Trains QR-DQN agent on Atari.
main
python
google-deepmind/dqn_zoo
dqn_zoo/qrdqn/run_atari.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/qrdqn/run_atari.py
Apache-2.0
def select_action(rng_key, network_params, s_t): """Computes greedy (argmax) action wrt Q-values at given state.""" rng_key, apply_key, policy_key = jax.random.split(rng_key, 3) q_t = network.apply(network_params, apply_key, s_t[None, ...]).q_values[0] a_t = rlax.greedy().sample(policy_key, q_t)...
Computes greedy (argmax) action wrt Q-values at given state.
select_action
python
google-deepmind/dqn_zoo
dqn_zoo/rainbow/agent.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/rainbow/agent.py
Apache-2.0
def _act(self, timestep) -> parts.Action: """Selects action given timestep, according to greedy policy.""" s_t = timestep.observation self._rng_key, a_t, v_t = self._select_action( self._rng_key, self._online_params, s_t ) a_t, v_t = jax.device_get((a_t, v_t)) self._statistics['state_val...
Selects action given timestep, according to greedy policy.
_act
python
google-deepmind/dqn_zoo
dqn_zoo/rainbow/agent.py
https://github.com/google-deepmind/dqn_zoo/blob/master/dqn_zoo/rainbow/agent.py
Apache-2.0
def naturalsize(value, binary=False, gnu=False, format="%.1f"): """Format a number of bytes like a human readable filesize (e.g. 10 kB). By default, decimal suffixes (kB, MB) are used. Non-GNU modes are compatible with jinja2's `filesizeformat` filter. Examples: ```pycon >>> naturalsi...
Format a number of bytes like a human readable filesize (e.g. 10 kB). By default, decimal suffixes (kB, MB) are used. Non-GNU modes are compatible with jinja2's `filesizeformat` filter. Examples: ```pycon >>> naturalsize(3000000) '3.0 MB' >>> naturalsize(300, False, True) ...
naturalsize
python
jmoiron/humanize
src/humanize/filesize.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/filesize.py
MIT
def activate(locale, path=None): """Activate internationalisation. Set `locale` as current locale. Search for locale in directory `path`. Args: locale (str): Language name, e.g. `en_GB`. path (str): Path to search for locales. Returns: dict: Translations. Raises: ...
Activate internationalisation. Set `locale` as current locale. Search for locale in directory `path`. Args: locale (str): Language name, e.g. `en_GB`. path (str): Path to search for locales. Returns: dict: Translations. Raises: Exception: If humanize cannot find the l...
activate
python
jmoiron/humanize
src/humanize/i18n.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/i18n.py
MIT
def _pgettext(msgctxt, message): """Fetches a particular translation. It works with `msgctxt` .po modifiers and allows duplicate keys with different translations. Args: msgctxt (str): Context of the translation. message (str): Text to translate. Returns: str: Translated te...
Fetches a particular translation. It works with `msgctxt` .po modifiers and allows duplicate keys with different translations. Args: msgctxt (str): Context of the translation. message (str): Text to translate. Returns: str: Translated text.
_pgettext
python
jmoiron/humanize
src/humanize/i18n.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/i18n.py
MIT
def thousands_separator() -> str: """Return the thousands separator for a locale, default to comma. Returns: str: Thousands separator. """ try: sep = _THOUSANDS_SEPARATOR[_CURRENT.locale] except (AttributeError, KeyError): sep = "," return sep
Return the thousands separator for a locale, default to comma. Returns: str: Thousands separator.
thousands_separator
python
jmoiron/humanize
src/humanize/i18n.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/i18n.py
MIT
def ordinal(value, gender="male"): """Converts an integer to its ordinal as a string. For example, 1 is "1st", 2 is "2nd", 3 is "3rd", etc. Works for any integer or anything `int()` will turn into an integer. Anything other value will have nothing done to it. Examples: ```pycon >>>...
Converts an integer to its ordinal as a string. For example, 1 is "1st", 2 is "2nd", 3 is "3rd", etc. Works for any integer or anything `int()` will turn into an integer. Anything other value will have nothing done to it. Examples: ```pycon >>> ordinal(1) '1st' >>> ordi...
ordinal
python
jmoiron/humanize
src/humanize/number.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/number.py
MIT
def intcomma(value, ndigits=None): """Converts an integer to a string containing commas every three digits. For example, 3000 becomes "3,000" and 45000 becomes "45,000". To maintain some compatibility with Django's `intcomma`, this function also accepts floats. Examples: ```pycon >>> i...
Converts an integer to a string containing commas every three digits. For example, 3000 becomes "3,000" and 45000 becomes "45,000". To maintain some compatibility with Django's `intcomma`, this function also accepts floats. Examples: ```pycon >>> intcomma(100) '100' >>> int...
intcomma
python
jmoiron/humanize
src/humanize/number.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/number.py
MIT
def intword(value, format="%.1f"): """Converts a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1_000_000 becomes "1.0 million", 1200000 becomes "1.2 million" and "1_200_000_000" becomes "1.2 billion". Supports up to decillion (33 digits) and googol...
Converts a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1_000_000 becomes "1.0 million", 1200000 becomes "1.2 million" and "1_200_000_000" becomes "1.2 billion". Supports up to decillion (33 digits) and googol (100 digits). Examples: ```p...
intword
python
jmoiron/humanize
src/humanize/number.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/number.py
MIT
def apnumber(value): """Converts an integer to Associated Press style. Examples: ```pycon >>> apnumber(0) 'zero' >>> apnumber(5) 'five' >>> apnumber(10) '10' >>> apnumber("7") 'seven' >>> apnumber("foo") 'foo' >>> apnumber(None) is None ...
Converts an integer to Associated Press style. Examples: ```pycon >>> apnumber(0) 'zero' >>> apnumber(5) 'five' >>> apnumber(10) '10' >>> apnumber("7") 'seven' >>> apnumber("foo") 'foo' >>> apnumber(None) is None True ``` Args...
apnumber
python
jmoiron/humanize
src/humanize/number.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/number.py
MIT
def fractional(value): """Convert to fractional number. There will be some cases where one might not want to show ugly decimal places for floats and decimals. This function returns a human-readable fractional number in form of fractions and mixed fractions. Pass in a string, or a number or a ...
Convert to fractional number. There will be some cases where one might not want to show ugly decimal places for floats and decimals. This function returns a human-readable fractional number in form of fractions and mixed fractions. Pass in a string, or a number or a float, and this function retur...
fractional
python
jmoiron/humanize
src/humanize/number.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/number.py
MIT
def _abs_timedelta(delta): """Return an "absolute" value for a timedelta, always representing a time distance. Args: delta (datetime.timedelta): Input timedelta. Returns: datetime.timedelta: Absolute timedelta. """ if delta.days < 0: now = _now() return now - (now +...
Return an "absolute" value for a timedelta, always representing a time distance. Args: delta (datetime.timedelta): Input timedelta. Returns: datetime.timedelta: Absolute timedelta.
_abs_timedelta
python
jmoiron/humanize
src/humanize/time.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/time.py
MIT
def _date_and_delta(value, *, now=None): """Turn a value into a date and a timedelta which represents how long ago it was. If that's not possible, return `(None, value)`. """ if not now: now = _now() if isinstance(value, dt.datetime): date = value delta = now - value eli...
Turn a value into a date and a timedelta which represents how long ago it was. If that's not possible, return `(None, value)`.
_date_and_delta
python
jmoiron/humanize
src/humanize/time.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/time.py
MIT
def naturaldelta( value, months=True, minimum_unit="seconds", ) -> str: """Return a natural representation of a timedelta or number of seconds. This is similar to `naturaltime`, but does not add tense to the result. Args: value (datetime.timedelta or int): A timedelta or a number of se...
Return a natural representation of a timedelta or number of seconds. This is similar to `naturaltime`, but does not add tense to the result. Args: value (datetime.timedelta or int): A timedelta or a number of seconds. months (bool): If `True`, then a number of months (based on 30.5 days) will ...
naturaldelta
python
jmoiron/humanize
src/humanize/time.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/time.py
MIT
def naturaltime( value, future=False, months=True, minimum_unit="seconds", when=None, ) -> str: """Return a natural representation of a time in a resolution that makes sense. This is more or less compatible with Django's `naturaltime` filter. Args: value (datetime.datetime, int...
Return a natural representation of a time in a resolution that makes sense. This is more or less compatible with Django's `naturaltime` filter. Args: value (datetime.datetime, int): A `datetime` or a number of seconds. future (bool): Ignored for `datetime`s, where the tense is always figured o...
naturaltime
python
jmoiron/humanize
src/humanize/time.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/time.py
MIT
def naturalday(value, format="%b %d") -> str: """Return a natural day. For date values that are tomorrow, today or yesterday compared to present day return representing string. Otherwise, return a string formatted according to `format`. """ try: value = dt.date(value.year, value.month,...
Return a natural day. For date values that are tomorrow, today or yesterday compared to present day return representing string. Otherwise, return a string formatted according to `format`.
naturalday
python
jmoiron/humanize
src/humanize/time.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/time.py
MIT
def naturaldate(value) -> str: """Like `naturalday`, but append a year for dates more than ~five months away.""" try: value = dt.date(value.year, value.month, value.day) except AttributeError: # Passed value wasn't date-ish return value except (OverflowError, ValueError): ...
Like `naturalday`, but append a year for dates more than ~five months away.
naturaldate
python
jmoiron/humanize
src/humanize/time.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/time.py
MIT
def _quotient_and_remainder(value, divisor, unit, minimum_unit, suppress): """Divide `value` by `divisor` returning the quotient and remainder. If `unit` is `minimum_unit`, makes the quotient a float number and the remainder will be zero. The rational is that if `unit` is the unit of the quotient, we canno...
Divide `value` by `divisor` returning the quotient and remainder. If `unit` is `minimum_unit`, makes the quotient a float number and the remainder will be zero. The rational is that if `unit` is the unit of the quotient, we cannot represent the remainder because it would require a unit smaller than the ...
_quotient_and_remainder
python
jmoiron/humanize
src/humanize/time.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/time.py
MIT
def _carry(value1, value2, ratio, unit, min_unit, suppress): """Return a tuple with two values. If the unit is in `suppress`, multiply `value1` by `ratio` and add it to `value2` (carry to right). The idea is that if we cannot represent `value1` we need to represent it in a lower unit. >>> from hum...
Return a tuple with two values. If the unit is in `suppress`, multiply `value1` by `ratio` and add it to `value2` (carry to right). The idea is that if we cannot represent `value1` we need to represent it in a lower unit. >>> from humanize.time import _carry, Unit >>> _carry(2, 6, 24, Unit.DAYS, U...
_carry
python
jmoiron/humanize
src/humanize/time.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/time.py
MIT
def _suitable_minimum_unit(min_unit, suppress): """Return a minimum unit suitable that is not suppressed. If not suppressed, return the same unit: >>> from humanize.time import _suitable_minimum_unit, Unit >>> _suitable_minimum_unit(Unit.HOURS, []).name 'HOURS' But if suppressed, find a unit ...
Return a minimum unit suitable that is not suppressed. If not suppressed, return the same unit: >>> from humanize.time import _suitable_minimum_unit, Unit >>> _suitable_minimum_unit(Unit.HOURS, []).name 'HOURS' But if suppressed, find a unit greather than the original one that is not suppress...
_suitable_minimum_unit
python
jmoiron/humanize
src/humanize/time.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/time.py
MIT
def _suppress_lower_units(min_unit, suppress): """Extend suppressed units (if any) with all units lower than the minimum unit. >>> from humanize.time import _suppress_lower_units, Unit >>> [x.name for x in sorted(_suppress_lower_units(Unit.SECONDS, [Unit.DAYS]))] ['MICROSECONDS', 'MILLISECONDS', 'DAYS'...
Extend suppressed units (if any) with all units lower than the minimum unit. >>> from humanize.time import _suppress_lower_units, Unit >>> [x.name for x in sorted(_suppress_lower_units(Unit.SECONDS, [Unit.DAYS]))] ['MICROSECONDS', 'MILLISECONDS', 'DAYS']
_suppress_lower_units
python
jmoiron/humanize
src/humanize/time.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/time.py
MIT
def precisedelta(value, minimum_unit="seconds", suppress=(), format="%0.2f") -> str: """Return a precise representation of a timedelta. ```pycon >>> import datetime as dt >>> from humanize.time import precisedelta >>> delta = dt.timedelta(seconds=3633, days=2, microseconds=123000) >>> precised...
Return a precise representation of a timedelta. ```pycon >>> import datetime as dt >>> from humanize.time import precisedelta >>> delta = dt.timedelta(seconds=3633, days=2, microseconds=123000) >>> precisedelta(delta) '2 days, 1 hour and 33.12 seconds' ``` A custom `format` can be sp...
precisedelta
python
jmoiron/humanize
src/humanize/time.py
https://github.com/jmoiron/humanize/blob/master/src/humanize/time.py
MIT
def checkImages(images): """ checkImages(images) Check numpy images and correct intensity range etc. The same for all movie formats. """ # Init results images2 = [] for im in images: if PIL and isinstance(im, PIL.Image.Image): # We assume PIL images are allright ...
checkImages(images) Check numpy images and correct intensity range etc. The same for all movie formats.
checkImages
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def getheaderAnim(self, im): """ getheaderAnim(im) Get animation header. To replace PILs getheader()[0] """ bb = "GIF89a" bb += intToBin(im.size[0]) bb += intToBin(im.size[1]) bb += "\x87\x00\x00" return bb
getheaderAnim(im) Get animation header. To replace PILs getheader()[0]
getheaderAnim
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def getImageDescriptor(self, im, xy=None): """ getImageDescriptor(im, xy=None) Used for the local color table properties per image. Otherwise global color table applies to all frames irrespective of whether additional colors comes in play that require a redefined palette...
getImageDescriptor(im, xy=None) Used for the local color table properties per image. Otherwise global color table applies to all frames irrespective of whether additional colors comes in play that require a redefined palette. Still a maximum of 256 color per frame, obviously. ...
getImageDescriptor
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def getAppExt(self, loops=float('inf')): """ getAppExt(loops=float('inf')) Application extention. This part specifies the amount of loops. If loops is 0 or inf, it goes on infinitely. """ if loops==0 or loops==float('inf'): loops = 2**16-1 ...
getAppExt(loops=float('inf')) Application extention. This part specifies the amount of loops. If loops is 0 or inf, it goes on infinitely.
getAppExt
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def getGraphicsControlExt(self, duration=0.1, dispose=2,transparent_flag=0,transparency_index=0): """ getGraphicsControlExt(duration=0.1, dispose=2) Graphics Control Extension. A sort of header at the start of each image. Specifies duration and transparancy. Dispose ...
getGraphicsControlExt(duration=0.1, dispose=2) Graphics Control Extension. A sort of header at the start of each image. Specifies duration and transparancy. Dispose ------- * 0 - No disposal specified. * 1 - Do not dispose. The graphic is to be lef...
getGraphicsControlExt
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def handleSubRectangles(self, images, subRectangles): """ handleSubRectangles(images) Handle the sub-rectangle stuff. If the rectangles are given by the user, the values are checked. Otherwise the subrectangles are calculated automatically. """ image_i...
handleSubRectangles(images) Handle the sub-rectangle stuff. If the rectangles are given by the user, the values are checked. Otherwise the subrectangles are calculated automatically.
handleSubRectangles
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def getSubRectangles(self, ims): """ getSubRectangles(ims) Calculate the minimal rectangles that need updating each frame. Returns a two-element tuple containing the cropped images and a list of x-y positions. Calculating the subrectangles takes extra time, obvi...
getSubRectangles(ims) Calculate the minimal rectangles that need updating each frame. Returns a two-element tuple containing the cropped images and a list of x-y positions. Calculating the subrectangles takes extra time, obviously. However, if the image sizes w...
getSubRectangles
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def convertImagesToPIL(self, images, dither, nq=0,images_info=None): """ convertImagesToPIL(images, nq=0) Convert images to Paletted PIL images, which can then be written to a single animaged GIF. """ # Convert to PIL images images2 = [] ...
convertImagesToPIL(images, nq=0) Convert images to Paletted PIL images, which can then be written to a single animaged GIF.
convertImagesToPIL
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def writeGifToFile(self, fp, images, durations, loops, xys, disposes): """ writeGifToFile(fp, images, durations, loops, xys, disposes) Given a set of images writes the bytes to the specified stream. """ # Obtain palette for all images and count each occurance ...
writeGifToFile(fp, images, durations, loops, xys, disposes) Given a set of images writes the bytes to the specified stream.
writeGifToFile
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def writeGif(filename, images, duration=0.1, repeat=True, dither=False, nq=0, subRectangles=True, dispose=None): """ writeGif(filename, images, duration=0.1, repeat=True, dither=False, nq=0, subRectangles=True, dispose=None) Write an animated gif from the specified imag...
writeGif(filename, images, duration=0.1, repeat=True, dither=False, nq=0, subRectangles=True, dispose=None) Write an animated gif from the specified images. Parameters ---------- filename : string The name of the file to write the image to. images : list ...
writeGif
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def readGif(filename, asNumpy=True): """ readGif(filename, asNumpy=True) Read images from an animated GIF file. Returns a list of numpy arrays, or, if asNumpy is false, a list if PIL images. """ # Check PIL if PIL is None: raise RuntimeError("Need PIL to read animated gi...
readGif(filename, asNumpy=True) Read images from an animated GIF file. Returns a list of numpy arrays, or, if asNumpy is false, a list if PIL images.
readGif
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def altersingle(self, alpha, i, b, g, r): """Move neuron i towards biased (b,g,r) by factor alpha""" n = self.network[i] # Alter hit neuron n[0] -= (alpha*(n[0] - b)) n[1] -= (alpha*(n[1] - g)) n[2] -= (alpha*(n[2] - r))
Move neuron i towards biased (b,g,r) by factor alpha
altersingle
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def contest(self, b, g, r): """ Search for biased BGR values Finds closest neuron (min dist) and updates self.freq finds best neuron (min dist-self.bias) and returns position for frequently chosen neurons, self.freq[i] is high and self.bias[i] is negative ...
Search for biased BGR values Finds closest neuron (min dist) and updates self.freq finds best neuron (min dist-self.bias) and returns position for frequently chosen neurons, self.freq[i] is high and self.bias[i] is negative self.bias[i] = self.GAMMA*((1/s...
contest
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def paletteImage(self): """ PIL weird interface for making a paletted image: create an image which already has the palette, and use that in Image.quantize. This function returns this palette image. """ if self.pimage is None: palette = [] for i in range(se...
PIL weird interface for making a paletted image: create an image which already has the palette, and use that in Image.quantize. This function returns this palette image.
paletteImage
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def quantize(self, image): """ Use a kdtree to quickly find the closest palette colors for the pixels """ if get_cKDTree(): return self.quantize_with_scipy(image) else: print('Scipy not available, falling back to slower version.') return self.quantize_without_...
Use a kdtree to quickly find the closest palette colors for the pixels
quantize
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def quantize_without_scipy(self, image): """" This function can be used if no scipy is availabe. It's 7 times slower though. """ w,h = image.size px = np.asarray(image).copy() memo = {} for j in range(w): for i in range(h): key = (px[i...
" This function can be used if no scipy is availabe. It's 7 times slower though.
quantize_without_scipy
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def inxsearch(self, r, g, b): """Search for BGR values 0..255 and return colour index""" dists = (self.colormap[:,:3] - np.array([r,g,b])) a= np.argmin((dists*dists).sum(1)) return a
Search for BGR values 0..255 and return colour index
inxsearch
python
JuanPotato/Legofy
legofy/images2gif_py2.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/images2gif_py2.py
MIT
def extend_palette(palette, colors=256, rgb=3): """Extend palette colors to 256 rgb sets.""" missing_colors = colors - len(palette)//rgb if missing_colors > 0: first_color = palette[:rgb] palette += first_color * missing_colors return palette[:colors*rgb]
Extend palette colors to 256 rgb sets.
extend_palette
python
JuanPotato/Legofy
legofy/palettes.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/palettes.py
MIT
def _flatten_palettes(palettes): """Convert palette mappings into color list.""" flattened = {} palettes = _merge_palettes(palettes) for palette in palettes: flat = [i for sub in palettes[palette].values() for i in sub] flattened.update({palette: flat}) return flattened
Convert palette mappings into color list.
_flatten_palettes
python
JuanPotato/Legofy
legofy/palettes.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/palettes.py
MIT
def _merge_palettes(palettes): """Build unified palette using all colors.""" unified = {} for palette in palettes: for item in palettes[palette]: unified.update({item: palettes[palette][item]}) palettes.update({'all': unified}) return palettes
Build unified palette using all colors.
_merge_palettes
python
JuanPotato/Legofy
legofy/palettes.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/palettes.py
MIT
def apply_color_overlay(image, color): '''Small function to apply an effect over an entire image''' overlay_red, overlay_green, overlay_blue = color channels = image.split() r = channels[0].point(lambda color: overlay_effect(color, overlay_red)) g = channels[1].point(lambda color: overlay_effect(co...
Small function to apply an effect over an entire image
apply_color_overlay
python
JuanPotato/Legofy
legofy/__init__.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/__init__.py
MIT
def make_lego_image(thumbnail_image, brick_image): '''Create a lego version of an image from an image''' base_width, base_height = thumbnail_image.size brick_width, brick_height = brick_image.size rgb_image = thumbnail_image.convert('RGB') lego_image = Image.new("RGB", (base_width * brick_width, ...
Create a lego version of an image from an image
make_lego_image
python
JuanPotato/Legofy
legofy/__init__.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/__init__.py
MIT
def get_new_filename(file_path, ext_override=None): '''Returns the save destination file path''' folder, basename = os.path.split(file_path) base, extention = os.path.splitext(basename) if ext_override: extention = ext_override new_filename = os.path.join(folder, "{0}_lego{1}".format(base, e...
Returns the save destination file path
get_new_filename
python
JuanPotato/Legofy
legofy/__init__.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/__init__.py
MIT
def get_new_size(base_image, brick_image, size=None): '''Returns a new size the first image should be so that the second one fits neatly in the longest axis''' new_size = base_image.size if size: scale_x, scale_y = size, size else: scale_x, scale_y = brick_image.size if new_size[0] ...
Returns a new size the first image should be so that the second one fits neatly in the longest axis
get_new_size
python
JuanPotato/Legofy
legofy/__init__.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/__init__.py
MIT
def get_lego_palette(palette_mode): '''Gets the palette for the specified lego palette mode''' legos = palettes.legos() palette = legos[palette_mode] return palettes.extend_palette(palette)
Gets the palette for the specified lego palette mode
get_lego_palette
python
JuanPotato/Legofy
legofy/__init__.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/__init__.py
MIT
def apply_thumbnail_effects(image, palette, dither): '''Apply effects on the reduced image before Legofying''' palette_image = Image.new("P", (1, 1)) palette_image.putpalette(palette) return image.im.convert("P", Image.FLOYDSTEINBERG if dither else Image.NONE, ...
Apply effects on the reduced image before Legofying
apply_thumbnail_effects
python
JuanPotato/Legofy
legofy/__init__.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/__init__.py
MIT
def legofy_gif(base_image, brick_image, output_path, size, palette_mode, dither): '''Alternative function that legofies animated gifs, makes use of images2gif - uses numpy!''' im = base_image # Read original image duration original_duration = im.info['duration'] # Split image into single frames ...
Alternative function that legofies animated gifs, makes use of images2gif - uses numpy!
legofy_gif
python
JuanPotato/Legofy
legofy/__init__.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/__init__.py
MIT
def main(image_path, output_path=None, size=None, palette_mode=None, dither=False): '''Legofy image or gif with brick_path mask''' image_path = os.path.realpath(image_path) if not os.path.isfile(image_path): print('Image file "{0}" was not found.'.format(image_path)) sys.exit(1) ...
Legofy image or gif with brick_path mask
main
python
JuanPotato/Legofy
legofy/__init__.py
https://github.com/JuanPotato/Legofy/blob/master/legofy/__init__.py
MIT
def create_tmpfile(self, suffix): '''Creates a temporary file and stores the path in self.out_path''' handle, self.out_path = tempfile.mkstemp(prefix='lego_', suffix=suffix) os.close(handle) self.assertTrue(os.path.exists(self.out_path)) self.assertTrue(os.path.getsize(self.out_p...
Creates a temporary file and stores the path in self.out_path
create_tmpfile
python
JuanPotato/Legofy
tests/test_legofy.py
https://github.com/JuanPotato/Legofy/blob/master/tests/test_legofy.py
MIT
def test_bricks_parameter(self): '''Can we specify the --brick parameter and is the file size proportional?''' self.create_tmpfile('.png') legofy.main(FLOWER_PATH, output_path=self.out_path, size=5) size5 = os.path.getsize(self.out_path) legofy.main(FLOWER_PATH, output...
Can we specify the --brick parameter and is the file size proportional?
test_bricks_parameter
python
JuanPotato/Legofy
tests/test_legofy.py
https://github.com/JuanPotato/Legofy/blob/master/tests/test_legofy.py
MIT
def test_small_brick(self): '''Test hitting the minimal brick size''' self.create_tmpfile('.png') legofy.main(FLOWER_PATH, output_path=self.out_path, size=1) self.assertTrue(Image.open(self.out_path).size == (30, 30))
Test hitting the minimal brick size
test_small_brick
python
JuanPotato/Legofy
tests/test_legofy.py
https://github.com/JuanPotato/Legofy/blob/master/tests/test_legofy.py
MIT
def test_dither_without_palette(self): '''Dithering without a palette should still work''' self.create_tmpfile('.png') legofy.main(FLOWER_PATH, output_path=self.out_path, dither=True) self.assertTrue(os.path.getsize(self.out_path) > 0)
Dithering without a palette should still work
test_dither_without_palette
python
JuanPotato/Legofy
tests/test_legofy.py
https://github.com/JuanPotato/Legofy/blob/master/tests/test_legofy.py
MIT
def test_get_new_filename(self): '''Test the default output filename generation''' # Is the generated path in the same directory? new_path = legofy.get_new_filename(FLOWER_PATH) self.assertTrue(os.path.dirname(FLOWER_PATH) == os.path.dirname(new_path)) # I...
Test the default output filename generation
test_get_new_filename
python
JuanPotato/Legofy
tests/test_legofy.py
https://github.com/JuanPotato/Legofy/blob/master/tests/test_legofy.py
MIT
def test_lego_palette_length(self): """PIL palette requires 768 ints (256 colors * RGB).""" legos = legofy.palettes.legos() for palette in legos: self.assertTrue(len(legofy.palettes.extend_palette(palette)) == 768)
PIL palette requires 768 ints (256 colors * RGB).
test_lego_palette_length
python
JuanPotato/Legofy
tests/test_legofy.py
https://github.com/JuanPotato/Legofy/blob/master/tests/test_legofy.py
MIT
def __init__(self, md: Markdown): """ Initialize the block parser. Arguments: md: A Markdown instance. Attributes: BlockParser.md (Markdown): A Markdown instance. BlockParser.state (State): Tracks the nesting level of current location in document being parse...
Initialize the block parser. Arguments: md: A Markdown instance. Attributes: BlockParser.md (Markdown): A Markdown instance. BlockParser.state (State): Tracks the nesting level of current location in document being parsed. BlockParser.blockprocessors (u...
__init__
python
Python-Markdown/markdown
markdown/blockparser.py
https://github.com/Python-Markdown/markdown/blob/master/markdown/blockparser.py
BSD-3-Clause
def parseDocument(self, lines: Iterable[str]) -> etree.ElementTree: """ Parse a Markdown document into an `ElementTree`. Given a list of lines, an `ElementTree` object (not just a parent `Element`) is created and the root element is passed to the parser as the parent. The `ElementTree` ...
Parse a Markdown document into an `ElementTree`. Given a list of lines, an `ElementTree` object (not just a parent `Element`) is created and the root element is passed to the parser as the parent. The `ElementTree` object is returned. This should only be called on an entire document, ...
parseDocument
python
Python-Markdown/markdown
markdown/blockparser.py
https://github.com/Python-Markdown/markdown/blob/master/markdown/blockparser.py
BSD-3-Clause
def parseBlocks(self, parent: etree.Element, blocks: list[str]) -> None: """ Process blocks of Markdown text and attach to given `etree` node. Given a list of `blocks`, each `blockprocessor` is stepped through until there are no blocks left. While an extension could potentially call thi...
Process blocks of Markdown text and attach to given `etree` node. Given a list of `blocks`, each `blockprocessor` is stepped through until there are no blocks left. While an extension could potentially call this method directly, it's generally expected to be used internally. T...
parseBlocks
python
Python-Markdown/markdown
markdown/blockparser.py
https://github.com/Python-Markdown/markdown/blob/master/markdown/blockparser.py
BSD-3-Clause
def build_block_parser(md: Markdown, **kwargs: Any) -> BlockParser: """ Build the default block parser used by Markdown. """ parser = BlockParser(md) parser.blockprocessors.register(EmptyBlockProcessor(parser), 'empty', 100) parser.blockprocessors.register(ListIndentProcessor(parser), 'indent', 90) ...
Build the default block parser used by Markdown.
build_block_parser
python
Python-Markdown/markdown
markdown/blockprocessors.py
https://github.com/Python-Markdown/markdown/blob/master/markdown/blockprocessors.py
BSD-3-Clause
def lastChild(self, parent: etree.Element) -> etree.Element | None: """ Return the last child of an `etree` element. """ if len(parent): return parent[-1] else: return None
Return the last child of an `etree` element.
lastChild
python
Python-Markdown/markdown
markdown/blockprocessors.py
https://github.com/Python-Markdown/markdown/blob/master/markdown/blockprocessors.py
BSD-3-Clause
def get_level(self, parent: etree.Element, block: str) -> tuple[int, etree.Element]: """ Get level of indentation based on list level. """ # Get indent level m = self.INDENT_RE.match(block) if m: indent_level = len(m.group(1))/self.tab_length else: indent_...
Get level of indentation based on list level.
get_level
python
Python-Markdown/markdown
markdown/blockprocessors.py
https://github.com/Python-Markdown/markdown/blob/master/markdown/blockprocessors.py
BSD-3-Clause
def __init__(self, **kwargs): """ Creates a new Markdown instance. Keyword Arguments: extensions (list[Extension | str]): A list of extensions. If an item is an instance of a subclass of [`markdown.extensions.Extension`][], the instance will be used ...
Creates a new Markdown instance. Keyword Arguments: extensions (list[Extension | str]): A list of extensions. If an item is an instance of a subclass of [`markdown.extensions.Extension`][], the instance will be used as-is. If an item is of type `str`, it is...
__init__
python
Python-Markdown/markdown
markdown/core.py
https://github.com/Python-Markdown/markdown/blob/master/markdown/core.py
BSD-3-Clause
def build_parser(self) -> Markdown: """ Build the parser from the various parts. Assigns a value to each of the following attributes on the class instance: * **`Markdown.preprocessors`** ([`Registry`][markdown.util.Registry]) -- A collection of [`preprocessors`][markdown.prep...
Build the parser from the various parts. Assigns a value to each of the following attributes on the class instance: * **`Markdown.preprocessors`** ([`Registry`][markdown.util.Registry]) -- A collection of [`preprocessors`][markdown.preprocessors]. * **`Markdown.parser`** ([`...
build_parser
python
Python-Markdown/markdown
markdown/core.py
https://github.com/Python-Markdown/markdown/blob/master/markdown/core.py
BSD-3-Clause
def registerExtensions( self, extensions: Sequence[Extension | str], configs: Mapping[str, dict[str, Any]] ) -> Markdown: """ Load a list of extensions into an instance of the `Markdown` class. Arguments: extensions (list[Extension | str]): A list of exte...
Load a list of extensions into an instance of the `Markdown` class. Arguments: extensions (list[Extension | str]): A list of extensions. If an item is an instance of a subclass of [`markdown.extensions.Extension`][], the instance will be used as-is. If an i...
registerExtensions
python
Python-Markdown/markdown
markdown/core.py
https://github.com/Python-Markdown/markdown/blob/master/markdown/core.py
BSD-3-Clause