content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def rest(s): """Return all elements in a sequence after the first""" return s[1:]
268d56ff3a24b3a5c9b1e4b1d1ded557afcdce8c
29,266
def add_int(x, y): """Add Integers Add two integer values. Parameters ---------- x : int First value y : int Second value Returns ------- int Result of addition Raises ------ TypeError For invalid input types. """ if not isinstance(x, int) or not isinstance(y, int): raise TypeError('Inputs must be integers.') return x + y
7544a6ddb97567364233bb5ce4d335669644f82e
185,422
def parse_labels_mapping(s): """ Parse the mapping between a label type and it's feature map. For instance: '0;1;2;3' -> [0, 1, 2, 3] '0+2;3' -> [0, None, 0, 1] '3;0+2;1' -> [1, 2, 1, 0] """ if len(s) > 0: split = [[int(y) for y in x.split('+')] for x in s.split(';')] elements = sum(split, []) assert all(x in range(4) for x in elements) assert len(elements) == len(set(elements)) labels_mapping = [] for i in range(4): found = False for j, l in enumerate(split): if i in l: assert not found found = True labels_mapping.append(j) if not found: labels_mapping.append(None) assert len(labels_mapping) == 4 else: labels_mapping = None return labels_mapping
d2f77876f1759e6d4093afc720e7631f1b4d9ff4
6,879
import math import json def process_role_options(options): """ Parse Lemur options and convert them to Vault parameter in json format. :param options: Lemur option dictionary :return: All needed parameters for Vault roles endpoint in json formatted string. """ vault_params = {'allow_subdomains': 'true', 'allow_any_name': 'true'} if 'key_type' in options: vault_params['key_type'] = options['key_type'][:3].lower() vault_params['key_bits'] = options['key_type'][-4:] vault_params['key_usage'] = 'KeyAgreement' if 'extensions' in options and 'key_usage' in options['extensions']: if options['extensions']['key_usage'].digital_signature: vault_params['key_usage'] += ', DigitalSignature' if options['extensions']['key_usage'].key_encipherment: vault_params['key_usage'] += ', KeyEncipherment' ttl = -1 if 'validity_end' in options and 'validity_start' in options: ttl = math.floor(abs(options['validity_end'] - options['validity_start']).total_seconds() / 3600) elif 'validity_years' in options: ttl = options['validity_years'] * 365 * 24 if ttl > 0: vault_params['ttl'] = str(ttl) + 'h' vault_params['max_ttl'] = str(ttl) + 'h' return json.dumps(vault_params)
ddd437b25ed2adc49480ebd2efa20702f8abf042
230,330
def enum(*sequential, **named): """ Enum helper to generate integer values usage: ENUM_TYPE = enum(VALUE, VALUE2, VALUE3) or: EnumType = enum(VALUE="V1", VALUE2=3) The result will be VALUE = 1, VALUE2 = 2, etc. """ enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums)
3f9bc5a9c07c097c5e133d1add7da7091ed8fb89
197,555
def apply_gamma_transform(value): """ Transforms values from linear scale to non-linea by applying gamma transform. :param value: Values to be transformed :return: Transformed values """ if value > 0.0031308: return (pow(1.055 * value, (1 / 2.4))) - 0.055 else: return 12.92 * value
aa1ebd356ce1b05abfa775d17aff379222f47427
155,858
from unittest.mock import call def callWithRaise(command): """ Executes the command like call() does but then raise OSError it it fails. """ status = call(command) if status: raise OSError("Failure on cmd: "+command) return status
43065baa75d5452306b5a7e3ff4a1f54fda2de98
372,719
from typing import Union from typing import List from typing import Tuple import torch def _format_radius( radius: Union[float, List, Tuple, torch.Tensor], pointclouds ) -> torch.Tensor: """ Format the radius as a torch tensor of shape (P_packed,) where P_packed is the total number of points in the batch (i.e. pointclouds.points_packed().shape[0]). This will enable support for a different size radius for each point in the batch. Args: radius: can be a float, List, Tuple or tensor of shape (N, P_padded) where P_padded is the maximum number of points for each pointcloud in the batch. Returns: radius: torch.Tensor of shape (P_packed) """ N, P_padded = pointclouds._N, pointclouds._P points_packed = pointclouds.points_packed() P_packed = points_packed.shape[0] if isinstance(radius, (list, tuple)): radius = torch.tensor(radius).type_as(points_packed) if isinstance(radius, torch.Tensor): if N == 1 and radius.ndim == 1: radius = radius[None, ...] if radius.shape != (N, P_padded): msg = "radius must be of shape (N, P): got %s" raise ValueError(msg % (repr(radius.shape))) else: padded_to_packed_idx = pointclouds.padded_to_packed_idx() radius = radius.view(-1)[padded_to_packed_idx] elif isinstance(radius, float): radius = torch.full((P_packed,), fill_value=radius).type_as(points_packed) else: msg = "radius must be a float, list, tuple or tensor; got %s" raise ValueError(msg % type(radius)) return radius
872eac571be63362a53f04db792cb28e9d2ffeb5
186,755
def create_duplicate_dictionary(duplicate_file): """Creates a lookup dictionary from the WaPo duplicates file Args: duplicate_file (file): WaPo duplicates file Returns: dict: duplicates lookup dictionary """ dup_dict = {} data_dups = open(duplicate_file).readlines() for each in data_dups: idxs = each.strip().split(' ') # source duplicate title if idxs[0] == idxs[1]: dup_dict[idxs[1]] = 2 # the duplicate has the same id as the original else: dup_dict[idxs[1]] = 1 # the duplicate has a different id from the original return dup_dict
9d42b0cca198d92350f9061c6f7a08ff3217e6bc
353,341
def getDiff(child, bar): """Calculates the difference in pieces of a chocolate bar to the requested pieces by a child. Args: child: An integer with pieces requested. bar: An integer with the number of chocolate pieces. Returns: An integer value with the difference of the requested pieces and the given bar size. """ return bar - child
1b1a09a5aa0e9d8ed1c6ec9637dc4da356dad8d9
142,230
def HasProperty(entity, property_name): """Returns whether `entity` has a property by the provided name.""" return property_name in entity._properties # pylint: disable=protected-access
0ce2c7fed31777b5d2e269096fe4d3d6d04169fe
120,994
def get_position(table: tuple[str, str], char: str) -> tuple[int, int]: """ >>> get_position(generate_table('marvin')[0], 'M') (0, 12) """ # `char` is either in the 0th row or the 1st row row = 0 if char in table[0] else 1 col = table[row].index(char) return row, col
00c2a5cd7a46c546ecbc02fada0da084a09ba068
471,130
def disappear_angle_brackets(text: str) -> str: """ Remove all angle brackets, keeping the surrounding text; no spaces are inserted :param text: text with angle bracket :return: text without angle brackets """ text = text.replace("<", "") text = text.replace(">", "") return text
b8e9efe435f3246a5347d9ce4cbca27a2d85de5e
445,299
def val(section, key): """ Return value of section[key] in units specified in configspec Args: section (:class:`qcobj.qconfigobj.QConfigObj`.Section`): instance key (string): valid key for `section` Returns: values in section[key] converted to units defined in configspec """ value = section[key] units = section.main.configUnits(section, key) if isinstance(value, (list, tuple)): try: return [q.to(units).magnitude for q in value] except AttributeError: return [q for q in value] else: try: return value.to(units).magnitude except AttributeError: return value
5b28d7ba9d1abcf42eecaa1af0a3b13f03dd44e6
660,953
def Set(assignments, callback, *args): """Set the stoplight using assignments and a condition callback. Args: assignments: A dict mapping returns of the callback to the stoplight value. callback: The callback to compute the conditional assignment. *args: Input arguments to the callback functions. Example: Set({1: STOPLIGHT_NORMAL, -1: STOPLIGHT_WARNING, 0: STOPLIGHT_UNAVAILABLE}, callback) Returns: Value of the stoplight. Raises: KeyError: Raised if assignment is invalid. """ key = callback(*args) if key not in assignments: raise KeyError("Cannot determine stoplight due to invalid assignment.") return assignments[key]
5727810fc9c84a27d259c014ab116d1691a65df6
415,203
def slug(value): """ Slugify (lower case, replace spaces with dashes) a given value. :param value: value to be slugified :return: slugified value ex: {{ "Abc deF" | slug }} should generate abc-def """ return value.lower().replace(' ', '-')
2dbd51d92a0941c6c9b41fc6f9e56eb19b4b8f46
581,324
def create_contact_person(client, organization_id, contact_id, name, country_code, email=None): """ Creates a contact person object in Billy: https://www.billy.dk/api/#v2contactpersons """ contact = { 'name': name, 'email': email, 'isPrimary': True, 'contactId': contact_id, } response = client.request('POST', '/contactPersons', {'contactPerson': contact}) return response['contactPersons'][0]['id']
e59a663b159c6cbedd83d4719fab2246156ad5ce
179,583
def calculate_cure_rate(confirmed, cure): """ 计算治愈比例 :param confirmed: 确诊人数 :param cure: 治愈人数 :return: 治愈比例 """ cure_rate = cure / confirmed * 100 return cure_rate
d866e21d61dcc8262292daffca7d5dc557ebede6
570,627
import json def json_matches_list(json_object, mylist): """Check if json matches a keyword from a list""" for item in mylist: if item.lower() in json.dumps(json_object).lower(): return True return False
f65dd01f2a929803c4ad454d4804e3d42a80dc3d
152,776
def sort_dict_by_key(dictionary): """ Returns the dictionary sorted as list [(), (),]. """ return sorted(dictionary.items()) if dictionary else None
3c59ed5906cd15ed68b39e3c3cfe8ecfbcaeb7cc
352,473
def is_context_variable(context, variable_name): """ Returns true if the given variable name is in the template context. Usage:: {% is_context_variable "variable_name" as variable_exists %} {% if variable_exists %} ... {% endif %} """ return variable_name in context
012a855b503b01f3098869f1292aa068c730e45c
176,890
def min_rank(series, ascending=True): """ Equivalent to `series.rank(method='min', ascending=ascending)`. Args: series: column to rank. Kwargs: ascending (bool): whether to rank in ascending order (default is `True`). """ ranks = series.rank(method="min", ascending=ascending) return ranks
a772618570517a324a202d4803983240cb54396b
705,443
import socket def ipv4(value): """Return true if IP address v4 is valid, otherwise - false.""" try: socket.inet_pton(socket.AF_INET, value) return True except socket.error: return False
cd1722f7df7abfa3fc7ff2e1038439c5e1a17541
621,355
def forwardsAdditiveError(image, template): """ Compute the forwards additive error """ return (template - image).flatten()
be5db9313fd38aaab27e6d2caf07d84388d17c2a
389,021
def prime_divisors_sieve(lim): """Computes the list of prime divisors for values up to lim included.""" # Pretty similar to totient div = [set() for i in range(lim + 1)] for i in range(2, lim + 1): if not div[i]: for j in range(i, lim + 1, i): div[j].add(i) return div
90bb793a4f709fdda49e896917bc600b955fb7e5
404,910
def get_node_demand(nodes, demand): """Get demand injections Parameters ---------- nodes : pandas DataFrame Node information demand : pandas DataFrame NEM region demand Returns ------- df_node_demand : pandas DataFrame Demand at each at each node """ def node_demand(row): return demand[row['NEM_REGION']] * row['PROP_REG_D'] # Demand at each node df_node_demand = nodes.apply(node_demand, axis=1) df_node_demand['level'] = 'demand' return df_node_demand
1589bd55604fb50545c146dba938aca4ad401283
290,159
def layer_output(model, layer_name=None): """Output tensor of a specific layer in a model. """ conv_index = -1 for i in range(len(model.layers) - 1, -1, -1): layer = model.layers[i] if layer_name in layer.name: conv_index = i break if conv_index < 0: print('Error: could not find the interested layer.') return model.layers[conv_index].output
e3f693d8d5759f1ec1d6aab84e5cc85e9764cebc
632,873
def string_to_bool(_value): """Converts "True" to True None to False. Case-insensitive.""" if _value is not None and _value.lower() == "true": return True else: return False
07a6639d4fb2a90fdb2040a0e6d22438d4532167
125,599
def identity_show(client, resource_group_name, account_name): """ Show the identity for Azure Cognitive Services account. """ sa = client.get(resource_group_name, account_name) return sa.identity if sa.identity else {}
19018c895f3fdf0b2b79788547bf80a400724336
709,835
import time def get_balance_metrics(balance_data, ts=None): """ Return a list of balance metrics. Parsed from the [balance](http://dev.datasift.com/docs/api/1/balance) endpoint. """ ts = ts or time.time() return [ ('datasift.balance.credit', (ts, balance_data['balance']['credit'])) ]
66db8b1c77c89e93ebc0217ce7714c6ea396a6bd
582,556
def v_equil(alpha, cli, cdi): """Calculate the equilibrium glide velocity. Parameters ---------- alpha : float Angle of attack in rad cli : function Returns Cl given angle of attack cdi : function Returns Cd given angle of attack Returns ------- vbar : float Equilibrium glide velocity """ den = cli(alpha)**2 + cdi(alpha)**2 return 1 / den**(.25)
16bd758f7349dd7c79a8441118191155730b1644
63,194
def terminal_errors_except(*args): """ Returns a ``can_retry`` function for :py:func:retry` that only retries if errors the ``Exception`` types specified. :return: a function that accepts a :class:`Failure` and returns ``True`` only if the :class:`Failure` wraps an Exception passed in the args. If no args are passed, no :class:`Exception` is treated as transient. """ def can_retry(f): return f.check(*args) return can_retry
f928574ca644bdf6556751e32e46fc12c55f007c
645,549
def valid_bidi(value): """ Rejects strings which nonsensical Unicode text direction flags. Relying on random Unicode characters means that some combinations don't make sense, from a direction of text point of view. This little helper just rejects those. """ try: value.encode("idna") except UnicodeError: return False else: return True
e58979a1ecd89351a592a89502e848bfbce6ac70
566,286
def is_json_response(response): """Returns ``True`` if response ``Content-Type`` is JSON. :param response: :class:~`requests.Response` object to check :type response: :class:~`requests.Response` :returns: ``True`` if ``response`` is JSON, ``False`` otherwise :rtype bool: """ content_type = response.headers.get('Content-Type', '') return content_type == 'application/json' or content_type.startswith('application/json;')
113bc6e1dcb45d4294287454b2a7519f05bad4cb
607,762
def _normalize(df): """ Normalise the county data i.e. strip spaces and convert to upper case, and finally sort alphabetically. :param df: input data frame with county column :type df: pandas.DataFrame :return: normalised data :rtype: pandas.DataFrame """ df.sort_values(by='county', inplace=True) df['county'] = df['county'].str.upper() df['county'] = df['county'].str.strip() return df
881afe6fcf50108832dd937a1eba5fc78e4097a7
308,017
def configuration_filename(feature_dir, proposed_splits, split, generalized): """Calculates configuration specific filenames. Args: feature_dir (`str`): directory of features wrt to dataset directory. proposed_splits (`bool`): whether using proposed splits. split (`str`): train split. generalized (`bool`): whether GZSL setting. Returns: `str` containing arguments in appropriate form. """ return '{}{}_{}{}.pt'.format( feature_dir, ('_proposed_splits' if proposed_splits else ''), split, '_generalized' if generalized else '', )
a3fc2c23746be7ed17f91820dd30a8156f91940c
706,888
def parse_functions_option(functions_option): """ Return parsed -f command line option or None. """ fvas = None if functions_option: fvas = [int(fva, 0x10) for fva in functions_option.split(",")] return fvas
ea1c3ab5e75bb82c9a3706623289bf9b520e9e09
468,632
def F0F2F4_to_UJ(F0, F2, F4): """ Given :math:`F_0`, :math:`F_2` and :math:`F_4`, return :math:`U` and :math:`J`. Parameters ---------- F0 : float Slater integral :math:`F_0`. F2 : float Slater integral :math:`F_2`. F4 : float Slater integral :math:`F_4`. Returns ------- U : float Coulomb interaction :math:`U`. J : float Hund's coupling :math:`J`. """ U=F0 + 4.0/49.0*(F2+F4) J=3.0/49.0*F2+20/441.0*F4 return U,J
f4f85d9f8d91bd28af14d9f6660f9c9d0f4afda4
391,542
def sqnorm(v): """Compute the square euclidean norm of the vector v.""" res = 0 for elt in v: for coef in elt: res += coef ** 2 return res
1af64ee21d02ae98c62b2a245b8ecb627bb7124b
384,088
import pytz from datetime import datetime def datetime_from_timestamp(ts, tzinfo=pytz.utc): """ Convert an :term:`HMC timestamp number <timestamp>` into a :class:`~py:datetime.datetime` object. The resulting object will be timezone-aware and will be represented in the specified timezone, defaulting to UTC. The HMC timestamp number must be non-negative. This means the special timestamp value -1 cannot be represented as datetime and will cause ``ValueError`` to be raised. The date and time range supported by this function has the following bounds: * The upper bounds is determined by :attr:`py:datetime.datetime.max` and additional limitations, as follows: * 9999-12-31 23:59:59 UTC, for 32-bit and 64-bit CPython on Linux and OS-X. * 3001-01-01 07:59:59 UTC, for 32-bit and 64-bit CPython on Windows, due to a limitation in `gmtime() in Visual C++ <https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/gmtime-gmtime32-gmtime64>`_. * 2038-01-19 03:14:07 UTC, for some 32-bit Python implementations, due to the `Year 2038 problem <https://en.wikipedia.org/wiki/Year_2038_problem>`_. * The lower bounds is the UNIX epoch: 1970-01-01 00:00:00 UTC. Parameters: ts (:term:`timestamp`): Point in time as an HMC timestamp number. Must not be `None`. tzinfo (:class:`py:datetime.tzinfo`): Timezone in which the returned object will be represented. This may be any object derived from :class:`py:datetime.tzinfo`, including but not limited to objects returned by :func:`pytz.timezone`. Note that this parameter does not affect how the HMC timestamp value is interpreted; i.e. the effective point in time represented by the returned object is not affected. What is affected by this parameter is for example the timezone in which the point in time is shown when printing the returned object. Must not be `None`. Returns: :class:`~py:datetime.datetime`: Point in time as a timezone-aware Python datetime object for the specified timezone. Raises: ValueError """ # Note that in Python 2, "None < 0" is allowed and will return True, # therefore we do an extra check for None. if ts is None: raise ValueError("HMC timestamp value must not be None.") if ts < 0: raise ValueError( "Negative HMC timestamp value {} cannot be represented as " "datetime.".format(ts)) epoch_seconds = ts // 1000 delta_microseconds = ts % 1000 * 1000 if tzinfo is None: raise ValueError("Timezone must not be None.") try: dt = datetime.fromtimestamp(epoch_seconds, tzinfo) except (ValueError, OSError) as exc: raise ValueError(str(exc)) dt = dt.replace(microsecond=delta_microseconds) return dt
5d44404bf2a9ed41066fd1dc6c6eb20011bf06a2
325,270
def get_most_and_least_freq_words(frequency_dict_): """ This function returns the most and least frequent words that can be considered noise. :param frequency_dict_: Dictionary that holds the frequency information of words. :type frequency_dict_: dict :return: Words that are frequent in these lexicons. :rtype: set """ size = len(frequency_dict_) frequency_el = int(size / 100) most_freq = frequency_dict_.most_common(frequency_el) least_freq = frequency_dict_.most_common()[:-frequency_el - 1:-1] union_set = set([k[0] for k in most_freq]).union(set(k[0] for k in least_freq)) return union_set
51239fca69ced67d85a0434f9547fd704b473364
159,041
def calc_lix(n_long_words: int, n_words: int, n_sents: int) -> float: """ Вычисление индекса удобочитаемости LIX Описание: Чем выше показатель, тем сложнее текст для чтения Значения индекса лежат в пределах от 0 до 100 и могут интерпретироваться следующим образом: 0-30 - Очень простые тексты, детская литература 30-40 - Простые тексты, художественная литература, газетные статьи 40-50 - Тексты средней сложности, журнальные статьи 50-60 - Сложные тексты, научно-популярные статьи, профессиональная литература, официальные тексты 60-100 - Очень сложные тексты, написанные канцелярским языком, законы Ссылки: https://en.wikipedia.org/wiki/Lix_(readability_test) https://ru.wikipedia.org/wiki/LIX Аргументы: n_long_words (int): Количество длинных слов n_words (int): Количество слов n_sents (int): Количество предложений Вывод: float: Значение индекса """ return (n_words / n_sents) + (100 * n_long_words / n_words)
02557546e5441b129b51bb93cfa43b58c5986227
556,410
def induce_subgraph(G, node_subset): """ Induce a subgraph of G. Parameters ---------- G : networkx.MultiDiGraph input graph node_subset : list-like the subset of nodes to induce a subgraph of G Returns ------- H : networkx.MultiDiGraph the subgraph of G induced by node_subset """ node_subset = set(node_subset) # copy nodes into new graph H = G.__class__() H.add_nodes_from((n, G.nodes[n]) for n in node_subset) # copy edges to new graph, including parallel edges if H.is_multigraph: H.add_edges_from( (n, nbr, key, d) for n, nbrs in G.adj.items() if n in node_subset for nbr, keydict in nbrs.items() if nbr in node_subset for key, d in keydict.items() ) else: H.add_edges_from( (n, nbr, d) for n, nbrs in G.adj.items() if n in node_subset for nbr, d in nbrs.items() if nbr in node_subset ) # update graph attribute dict, and return graph H.graph.update(G.graph) return H
952dea186a93dacdbabda64d64484c6d4aebf889
608,607
def parse_slice(s, size): """ Helper to determine nonnegative integers (start, stop, step) of a slice. :param slice s: A slice. :param int size: The size of the array being indexed into. :returns: A tuple of nonnegative integers ``start, stop, step``. :rtype: tuple """ start = s.start if start is None: start = 0 assert isinstance(start, int) if start >= 0: start = min(size, start) else: start = max(0, size + start) stop = s.stop if stop is None: stop = size assert isinstance(stop, int) if stop >= 0: stop = min(size, stop) else: stop = max(0, size + stop) step = s.step if step is None: step = 1 assert isinstance(step, int) return start, stop, step
a98db53286d8bbc6aee48026fbd572fee9370819
337,709
import torch def get_neighbor_bonds(edge_index, bond_type): """ Takes the edge indices and bond type and returns dictionary mapping atom index to neighbor bond types Note: this only includes atoms with degree > 1 """ start, end = edge_index idxs, vals = torch.unique(start, return_counts=True) vs = torch.split_with_sizes(bond_type, tuple(vals)) return {k.item(): v for k, v in zip(idxs, vs) if len(v) > 1}
96c56c067a3d436b67de093c0407f86900223302
58,383
def create_empty_board(n): """ Creates and returns a grid (list of lists), that has n rows and each row has n columns. All the elements in the grid are set to None. >>> create_empty_board(2) [[None, None], [None, None]] """ grid = [] # Create empty grid for y in range(n): # Create rows one at a time row = [] for x in range(n): # Build up each row by appending to a list row.append(None) grid.append(row) # Append the row (list) onto grid return grid
5cade24a2373bfba879e0a964f897b7c4974823e
463,717
from typing import List from typing import Tuple from typing import Optional def has_winner(field: List[List[int]]) -> Tuple[bool, Optional[Tuple[int, int]], Optional[Tuple[int, int]]]: """ Checks game for winning (or tie) positions :param field: playing field matrix :return: Overall answer & position, from where the winning position starts ((0, 0) when tied) & winning direction ((0, 0) when tied) """ # directions in which to check winning positions dirs = [(0, 1), (1, 0), (1, 1), (1, -1)] for i in range(len(field)): for j in range(len(field[i])): if field[i][j] == 0: continue for dr in dirs: # simply checking an equality of 4 contiguous elements on field try: if field[i][j] == field[i + dr[0]][j + dr[1]] == \ field[i + 2 * dr[0]][j + 2 * dr[1]] == \ field[i + 3 * dr[0]][j + 3 * dr[1]] : return True, (i, j), dr # to skip border cases without making some stupidly clever algorithm except IndexError: continue # checking if any empty cells left after checking winning positions as # last move can cause it as well draw = True for row in field: for el in row: if not el: draw = False if draw: return True, (0, 0), (0, 0) return False, None, None
442935063a143981fb91056a14adda52c016f066
667,584
def remove_smallwords(tokens, smallwords_threshold: int) -> list: """ Function that removes words which length is below a threshold ["hello", "my", "name", "is", "John", "Doe"] --> ["hello","name","John","Doe"] Parameters ---------- text : list list of strings smallwords_threshold: int threshold of small word Returns ------- list """ tokens = [word for word in tokens if len(word) > smallwords_threshold] return tokens
0f824214d621a6c945c6cf30f6c25b5eba3d6a12
79,569
def query_construction(raw_utterance, conv_id, turn_id, query_config, history, title): """ Parameters ---------- raw_utterance - str original conversational query conv_id - conversation id turn_id - int, current turn query_config - QueryConfig, object with configurations to use in query rewriting history - str, what to prfix the qury with title - str, title of the conversation Returns ------- str, utterance rewritten """ if query_config.coreference_json: utterance = query_config.coreference_dic[str(conv_id)][str(turn_id)] else: utterance = raw_utterance if query_config.use_history and turn_id > 1: utterance = history + " " + utterance if query_config.use_title: utterance = title + " " + utterance return utterance
6a3b350b2c0e9bf7f2187cf5818f9c22a3b52d21
353,545
def input_yesno(prompt, default=None): """ ask the user to enter Yes or No prompt: string to be shown as prompt default: True (=Yes), False (=No), or None (can not leave empty) """ while True: value = input(prompt).strip() if not value: if default is None: print('Can not leave empty') continue else: return default value = value.lower() if value in ('y', 'yes'): return True if value in ('n', 'no'): return False print('Enter Yes or No')
7e38febe24d59a215d4c369f53d4ab524799891d
659,468
def create_hf(geom): """Create header and footer for different types of geometries Args: geom (str): geometry type, e.g., polygone """ if geom == "polygone": header = """ { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ """ footer = """ ] } } ] }""" else: raise ValueError(f"{geom} is not implemented.") return header, footer
28276e77ccaa2943dfe4bd2f65a19347f6b1cc1c
683,660
def findSmallest(root): """ Finds the smallest node in the subtree :param root: The root node of the tree or subtree :return: The smallest node in the given subtree """ if root.left is None: return root else: return findSmallest(root.left)
a84552ce444e48c45eec32acb93d791ff8de222c
137,084
def isPrime(n): """ Determines whether a number is prime Arguments: n {integer} -- term Returns: isPrime {boolean} """ assert n > 0, "invalid number" if n == 1: return False for i in range(2, n): if (n % i) == 0: return False return True
189e6282ca78008ff90cbc3d4b0af60bc4f2eba8
316,461
def parse_question_update_sync_agent_data(json): """ Parse the incoming statement for a sync agent event concerning a question update. :param json: A statement concerning a question update. :type json: dict(str, NoneType) :return: A dictionary containing a course id, quiz id and all question information. :rtype: dict(str, str) """ statement = json['statement'] questions_info = statement['context']['extensions']['http://activitystrea.ms/schema/1.0/question'] course_id = statement['context']['contextActivities']['grouping'][1]['id'].split("=")[-1] quiz_id = statement['object']['id'].split("=")[-1] question_update_data = { 'course_id': course_id, 'quiz_id': quiz_id, 'questions': questions_info } return question_update_data
d7c018fd0414181acccdd83fd60f34f1a28f8aec
541,006
def fileExists(file_path): """ Method: A more secure way to know if a file exists or not. Arguments: file_path (str): path to the file to verify. Return: (bool): True if the file exists : False if the file doesn't exists. """ try: with open(file_path): # try to open the file pass except IOError: return False else: return True
36dad3a4fbbbfc079b2e31b131db6b9f9d352440
258,835
def make_html(url, time): """ Return browser readable html that loads url in an iframe and refreshes after time seconds """ html = f""" <!doctype html> <html> <head> <title>Kiosk</title> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> <meta http-equiv="refresh" content={time}> </head> <body style="margin:0px;padding:0px;overflow:hidden"> <iframe src= {url} frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe> </body> </html> """ return html
b87071c19af22c6c81ed100ffec0406d6bca009a
465,474
def uniqueify(items): """Return a list of the unique items in the given iterable. Order is NOT preserved. """ return list(set(items))
b7b85edd311ec261e1db47c17386afaa44a08088
644,278
def trunc(s: str, left=70, right=25, dots=' ... '): """All of string s if it fits; else left and right ends of s with dots in the middle.""" dots = ' ... ' return s if len(s) <= left + right + len(dots) else s[:left] + dots + s[-right:]
08ed3990baa6df66f3508219e96a53612c1cd9f8
71,542
import types def type_legacy_mro(cls): """ drop in replacement of type.mro for loading legacy hickle 4.x files which were created without generalized PyContainer objects available. Consequently some h5py.Datasets and h5py.Group objects expose function objects as their py_obj_type type.mro expects classes only. Parameters ---------- cls (type): the py_obj_type/class of the object to load or dump Returns ------- mro list for cls as returned by type.mro or in case cls is a function or method a single element tuple is returned """ if isinstance( cls, (types.FunctionType,types.BuiltinFunctionType,types.MethodType,types.BuiltinMethodType) ): return (cls,) return type.mro(cls)
9b859cb06eb10394bb2528a0b3c06e89793ecdab
493,399
def fmt_pairs(obj, indent=4, sort_key=None): """Format and sort a list of pairs, usually for printing. If sort_key is provided, the value will be passed as the 'key' keyword argument of the sorted() function when sorting the items. This allows for the input such as [('A', 3), ('B', 5), ('Z', 1)] to be sorted by the ints but formatted like so: l = [('A', 3), ('B', 5), ('Z', 1)] print(fmt_pairs(l, sort_key=lambda x: x[1])) Z 1 A 3 B 5 where the default behavior would be: print(fmt_pairs(l)) A 3 B 5 Z 1 """ lengths = [len(x[0]) for x in obj] if not lengths: return '' longest = max(lengths) obj = sorted(obj, key=sort_key) formatter = '%s{: <%d} {}' % (' ' * indent, longest) string = '\n'.join([formatter.format(k, v) for k, v in obj]) return string
6dc1391d65b10df394e94426fdbde828bf4ae698
86,101
def extract_line_parts(line): """ Builds a dict containing tokenized command portion and comment portion of a config line """ config, hash_char, comment = line.partition('#') return {"command": config.split(), "comment": comment}
5de954601044e0cd48bb00c4ca2c595f5b2f9e6a
505,262
def class_decision(x): """ Returns a vector containing the class with the highest value (probability) Inverse of one_hot function Parameters - x: t.tensor, size=[n, n_classes], where each element represents the probability of the class. Returns t.tensor, size=[n], dtype=long, integer values in range [0, n_classes) """ return x.argmax(axis=1)
7e891131d62f4fb2814870e13014d47c72ba5c1f
198,834
def _joinNamePath(prefix=None, name=None, index=None): """ Utility function for generating nested configuration names """ if not prefix and not name: raise ValueError("Invalid name: cannot be None") elif not name: name = prefix elif prefix and name: name = prefix + "." + name if index is not None: return "%s[%r]" % (name, index) else: return name
fb26dc39ded907cefc1a319d6d0692e67f8c5007
691,404
import hashlib def md5_key(chrom, start, end, ref, alt, assembly): """Generate a md5 key representing uniquely the variant Accepts: chrom(str): chromosome start(int): variant start end(int): variant end ref(str): references bases alt(str): alternative bases assembly(str) genome assembly (GRCh37 or GRCh38) Returns: md5_key(str): md5 unique key """ hash = hashlib.md5() hash.update( (" ".join([chrom, str(start), str(end), str(ref), str(alt), assembly])).encode("utf-8") ) md5_key = hash.hexdigest() return md5_key
64db55c0075d063aeec500f97700ec769840cc4f
8,589
import random def bomber(length, width, bomb, m, n): """ Place bombs randomly (position of first click and its surroundings cannot be bombs) :param length: length of the board :param width: width of the board :param bomb: number of bombs :param m: horizontal position of first click :param n: vertical position of first click :return: list of bomb positions """ forbidden = ((m - 1, n - 1), (m - 1, n), (m - 1, n + 1), (m, n - 1), (m, n), (m, n + 1), (m + 1, n - 1), (m + 1, n), (m + 1, n + 1)) candidates = [(x, y) for x in range(length) for y in range(width) if (x, y) not in forbidden] return random.sample(candidates, bomb)
52591fe68d7d03e29559072148a945700b6aad06
35,743
def multip(*args): """ return the accumulated total of all arguments multiplied together """ accumulated_total = 1 for i in args: accumulated_total *= i return accumulated_total
96983ad6d907afdf1c4641c1f1f08c54bc6fc617
366,332
def predict_ball_path(agent): """Predicts the path of the ball using the rlBot framework Args: agent (BaseAgent): The bot Returns: An array of Vec3 containing the predicted locations of the ball. Each location is seperated in time by 1/60 of a second, or one game tick. """ locations = [] ball_prediction = agent.get_ball_prediction_struct() if ball_prediction is not None: for i in range(0, ball_prediction.num_slices): prediction_slice = ball_prediction.slices[i] locations.append(prediction_slice.physics.location) return locations
327d96ecb4c770ae526862343c111190cae77302
478,308
def pipe_results_table(case_dom): """Print pipe dimensions in a tabular text format Args: case_dom (dict): Pipe flow network data model Returns: (str): Text table of pipe dimensions, routing, and results""" result = ' Pipe From To Diameter Length CHW' \ ' Volumetric Flow Head Loss From Head To Head\n' for currpipe in case_dom['pipe']: ifrom = currpipe['from'] ito = currpipe['to'] result += '{0:3d} {1:3d} {2:3d} {3:12.4E~} {4:12.4E~} ' \ '{5:7.3f} {6:7.3f~} {7:12.4E~} {8:12.4E~} {9:12.4E~}\n' \ .format(currpipe['id'], currpipe['from'], currpipe['to'], currpipe['idiameter'], currpipe['lpipe'], currpipe['chw'], currpipe['vol_flow'], currpipe['head_loss'], case_dom['junc'][ifrom]['head'], case_dom['junc'][ito]['head']) return result
43e8ad3a0f69d96081bcd0e0c0e9cca4313ec125
430,988
def num_transfer(df): """Total number of track transfer.""" return df.extra.Type.isin(['TRANSFER']).sum()
b63861cf2b0299e7d01d946c0d5064ca02cf4792
56,367
import sqlite3 def get_twinkles_visits(opsim_db_file, fieldID=1427): """ Return a sorted list of visits for a given fieldID from an OpSim db file. Parameters ---------- obsim_db_file : str Filename of the OpSim db sqlite file fieldID : int, optional ID number of the field for which to return the visit numbers. The default value is the Twinkles field. Returns ------- list : A list of obsHistIDs (i.e., visit numbers). Since a given visit can belong to more than one proposal, there may be multiple rows in the Summary table with the corresponding obsHistID. This function removes the duplicates. """ connect = sqlite3.connect(opsim_db_file) query = """select distinct obsHistID from Summary where fieldID=%i order by obsHistID asc""" % fieldID obsHistIDs = [x[0] for x in connect.execute(query)] return obsHistIDs
791f779cfba6125eaf7efea1930c6373f71e3efe
659,305
def likert_malign(value): """Tell whether a Likert grade is malign.""" assert value in range(1, 6), value return value > 2
5b3f94536a1e118a4b4852d0bf833ed4ef3bfc6d
149,062
from typing import Optional def percent(flt: Optional[float]) -> str: """ Convert a float into a percentage string. """ if flt is None: return '[in flux]' return '{0:.0f}%'.format(flt * 100)
937a1608be53460369210cdce9150547bcb1fe56
666,522
from typing import List def convert_coordinate(size: tuple, box: List) -> tuple: """Convert coordinate from xywh to x_center, y_center, width, height Arguments: \n `size` (tuple): size of image \n `box` (List): box coordinate \n Returns:\n `tuple`: new yolo coordinate """ dw = 1.0 / size[0] dh = 1.0 / size[1] w = box[2] h = box[3] x = box[0] + box[2] / 2.0 y = box[1] + box[3] / 2.0 x = round(x * dw, 6) w = round(w * dw, 6) y = round(y * dh, 6) h = round(h * dh, 6) return (x, y, w, h)
a5db82b2c0b8af17b8ccd9a288e8d0e44ebef1a3
571,401
def taken(diff): """Convert a time diff to total number of microseconds""" microseconds = diff.seconds * 1_000 + diff.microseconds return abs(diff.days * 24 * 60 * 60 * 1_000 + microseconds)
64e8022bb0a80fcccc1a755fffb79121e61cad17
47,571
def find_relocations_for_section(elf, section_name): """ Given a section, find the relocation section for it in the ELF file. Return a RelocationSection object, or None if none was found. """ rels = elf.get_section_by_name(b'.rel' + section_name) if rels is None: rels = elf.get_section_by_name(b'.rela' + section_name) return rels
594683f10c57119acfd0d81007f85588cfe1c255
523,403
def get_locations(data: dict) -> list: """ Get users' locations from the dictionary. Return list of lists, every one of which contains user's nickname and location. >>> get_locations({'users': [{'screen_name': 'Alina', 'location':\ 'Lviv, Ukraine'}]}) [['Alina', 'Lviv, Ukraine']] """ result = [] users = data['users'] for user in users: name = user['screen_name'] location = user['location'] result.append([name, location]) return result
21c2cbc984e085d8b7b6da418e8184aa2d037cd2
691,612
def symmetric_transmission_constraint_rule(backend_model, loc_tech): """ Constrain e_cap symmetrically for transmission nodes. Transmission techs only. .. container:: scrolling-wrapper .. math:: energy_{cap}(loc1::tech:loc2) = energy_{cap}(loc2::tech:loc1) """ lookup = backend_model.__calliope_model_data["data"]["lookup_remotes"] loc_tech_remote = lookup[loc_tech] return ( backend_model.energy_cap[loc_tech] == backend_model.energy_cap[loc_tech_remote] )
15940abc4ea7a8acc4509e235f94f5167effa87f
260,549
def parse_boss(lines): """Parse boss data from lines to dictionary.""" boss = {} for line in lines: attribute, value = line.split(':') boss[attribute] = int(value) return boss
cc33b2c6d9a00835f7429c532d11090a254842d3
419,895
def valid_year(entry, minimum, maximum): """Validate four digit year entries.""" if len(entry) > 4: return False elif int(entry) >= minimum and int(entry) <= maximum: return True else: return False
12491b406daa3c6d2eceb0929a2a72becca3cb42
667,472
import io import re def pdf_pages(filename): """Return number of pages in PDF.""" try: infile = io.open(filename, "rb") except IOError: return 0 for line in infile: m = re.match(br'\] /Count ([0-9]+)',line) if m: return int(m.group(1)) return 0
a20c5912bb56f0f9b2caad11637bbcfaf4cac4a7
564,090
def check_prec(schedule): """ Checks if a given schedule is acceptable following the order of precedence. Args: schedule (list): a list of jobs (node object) listed according to the schedule. Returns: (boolean): true if schedule follows order of precendence. False otherwise. """ # Check first node. # First node in the schedule must be the start node of the graph if not schedule[0].start: return False # Check intermediate nodes. # Track jobs that have been executed. Dictates the subsequent allowable jobs. executed_list = [schedule[0]] for node in schedule[1:-1]: # If all predecessors (node.nodes_before) have been executed, current job is allowed. if all(before in executed_list for before in node.nodes_before): executed_list.append(node) # Otherwise, job cannot be executed. else: return False # Check end node. # Last node must be the end node of the graph. if not schedule[-1].end: return False # If all above conditions hold true, the schedule follows order of precednece. return True
fe30069d6d907092ee4bcace4ef167acd9d558cd
248,875
def windows_only_packages(pkgs): """Find out which packages are windows only""" res = set() for p in pkgs: for name, info in p.items(): if info.get("OS_type", "").lower() == "windows": res.add(name) return res
d6cd806fc83a0829955f632f14fc7ef95dcc084b
407,993
def _get_used_ports(vms): """ Return a set of ports in use by the ``vms``. :param vms: list of virtual machines :type vms: list(:class:`~.vm.VM`) :return: set of ports :rtype: set(int) """ used_ports = set() for vm in vms: ip, port = vm.get_ssh_info() if port: used_ports.add(port) return used_ports
aaa3e141fb060a78ba86d71d59ed59fb59fd4132
619,779
def build_array(record: dict): """ Build Data Transfer object with whom I'll work /w Python :param record: raw results of InfluxDB :return: a properly formatted object to interact with """ return [ record['_time'], record['asset'], record['_value'], ]
47f901db998024d4024fef84cadab42f1973010d
444,756
from typing import OrderedDict def to_native(key): """ Given a mapping (e.g. dictionary) or a iterable (e.g. list) with 0d NumPy array or Torch tensor values, convert these into native Python data type object (e.g. ints and floats). Args: key: a mapping or an iterable object Returns: Same object as `key` but with 0d NumPy array or Torch tensor value replaced with native scalar value """ if isinstance(key, (dict, OrderedDict)): for k, v in key.items(): if hasattr(v, 'dtype') and len(v) < 2: key[k] = v.item() else: for k, v in enumerate(key): if hasattr(v, 'dtype') and len(v) < 2: key[k] = v.item() return key
6f67ae158b54e2dc459bef67bc3217394ce2ddf8
306,624
def dustmass(f): """ dustFrac * mass """ return f['u_dustFrac'] * f['mass']
d189b9ad10fc0558129c6f85ec2b906797dddd7d
293,880
def valid_options(kwargs, allowed_options): """ Checks that kwargs are valid API options""" diff = set(kwargs) - set(allowed_options) if diff: print("Invalid option(s): ", ', '.join(diff)) return False return True
1d03ebc466ac82fcc691719a066d624a47c220e9
246,957
def concatenate_evidence(df): """ Concatenate the evidence for each claim into one string. Edits df in place. """ df.evidence = df.evidence.transform(lambda x: ' '.join(x)) return df
810df8301ddac0d86531817ca6ec4ff9691797cd
463,713
def sameCategory(Data): """ 判断是否所有数据均属于相同类型。 Args: Data (list): 数据集 Returns: (类型, 是否相同) """ categories = [y[-1] for y in Data] # 数据集中的y向量(所有数据的标签) return categories[0], len(set(categories)) == 1
0c80a1bc78ba43613e2f6a07dc1bdc73d926cf89
224,152
import logging def split_and_put_into_ques(message_batch, que_urls, client, max_batch_size=10): """ Args: message_batch: List of all messages to be put onto the que que_urls: List of que_urls for messages to be put onto max_batch_size: Maximum batch size (default to 10 for sqs) client: boto3 sqs client :return num_messages_success: Number of successful messages """ num_messages_success = 0 num_messages_failed = 0 logger = logging.getLogger('__main__') # Split message batch into equal chunk sizes for each SQS Que chunks = [message_batch[i::len(que_urls)] for i in range(len(que_urls))] messages_per_que = zip(chunks, que_urls) # For each que and chunk, put onto SQS for chunk, que_url in messages_per_que: for k in range(0, len(chunk), max_batch_size): response = client.send_message_batch(QueueUrl=que_url, Entries=chunk[k:k + max_batch_size]) num_messages_success += len(response.get('Successful', [])) num_messages_failed += len(response.get('Failed', [])) logger.info(f"Total Successful Messages: {len(chunk)} successful for {que_url}") logger.info(f"Total Successful messages for all ques: {num_messages_success}") logger.info(f"Total failed messages for all ques: {num_messages_failed}") return num_messages_success
8890a235c6bff4d539dba1295c668c1448a1f102
552,898
def pulses_plugin(pulses_workbench): """Setup the workbench and return the pulses manager plugin. """ return pulses_workbench.get_plugin('exopy.pulses')
480a24ce3c4d8d1f765af8f5921f8315ffd62df3
619,044
def consoO(R,s,tau,w): """Compute the consumption of the old agents Args: R (float): gross return on saving s (float): savings tau (float): percentage of contribution of the wage of the young agent w (float): wage Returns: (float): consumption of the old agents """ return R*s+tau*w
522b6b51b50db29b60a5adc473d6cd9cc04a6a3a
691,791
def last_char(word): """ Return the last letter example: zerrouki; 'i' is the last. @param word: given word @type word: unicode @return: the last letter @rtype: unicode char """ return word[-1:]
a1973e5af77c1369843929585e77813b6e78e9d7
155,259
import zipfile async def extract_zip_archive( input_file_path: str, output_directory_path: str, ) -> dict: """ Extracts a given zip file. Parameters ---------- input_file_path : str Path to the zip file output_directory_path : str Path where all the files should be extracted Returns ------- dict Path to the directory where the archive has been extracted """ with zipfile.ZipFile(input_file_path, "r") as zip: zip.extractall(output_directory_path) return {"output_path": output_directory_path}
1429a265ea4f4e6179855aef616784f62a9a3e7e
548,388
import logging def get_iam_policy(compute_client, image_id, project_id): """ Gets the compute image IAM policy. """ try: policy = compute_client.images().getIamPolicy(project=project_id, resource=image_id).execute() except: logging.error(f"Could not get compute image IAM policy on image {compute_client}.") raise return policy
16e1fc518903a557f64551de303bf8f2942a0176
456,053
from typing import Optional from typing import List import string import random def randomString(length: int, samples: Optional[List[str]] = None) -> str: """A random string is generated. Args: length: the size of string. samples: cumstomized letters for sampling. e.g., ['a', 'b']. """ letters = string.ascii_lowercase if samples: letters = samples return ''.join(random.choice(letters) for i in range(length))
ceaee6d8fe0f12775c2123f98b90aa33558aabe7
498,072
def get_template_user_keys(template): """ Finds the keys in a template that relate to the HumanUser entity. :param template: Template to look for HumanUser related keys. :returns: A list of key names. """ # find all 'user' keys in the template: user_keys = set() if "HumanUser" in template.keys: user_keys.add("HumanUser") for key in template.keys.values(): if key.shotgun_entity_type == "HumanUser": user_keys.add(key.name) return user_keys
cfeca37d39775a63b69f0ee0d582a0f4e03bb44e
69,236
def spreadingRate(Q, beta): """ Calculates the spreading rate on the planet. Inputs: Q - pore space heat flow relative to modern Earth [dimensionless] beta - scaling parameter [dimensionless] Returns: r_sr - the spreading rate relative to the modern Earth [dimensionless] """ r_sr = Q**beta return r_sr
4aab81278a3e5b9f9996c18d94d259cef8fb845b
486,300
def is_singleton(atoms): """ returns whether all the input atoms are the same or not Inputs ------ atoms: List[.logic.Atom] [a_1, a_2, ..., a_n] Returns ------- flag : bool a_1 == a_2 == ... == a_n """ result = True for i in range(len(atoms)-1): result = result and (atoms[i] == atoms[i+1]) return result
50066b657682fd44e373294764ed14645be93b97
224,153
import random def greeting() -> str: """Returns a random greeting message. Returns: str: Random greeting. """ return random.choice( ["Greetings", "Hello", "Welcome", "Bonjour", "Hey there", "What's up", "Yo", "Cheers"] )
6fad78497e4cc0ba41d4417059c20e05e20eab1c
439,538