content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def remove_flickr8k_splits(flickr30k_splits, flickr8k_splits):
"""Remove Flickr 8k images from Flickr 30k train-dev-test splits."""
flickr8k_all = []
for _, uids in flickr8k_splits.items():
flickr8k_all.extend(list(map(lambda uid: uid.split("_")[0], uids)))
flickr30_removed = {}
for subset,... | 8a42a991904d15433506351f366497d6436d5df8 | 582,458 |
def group_definitions_by_pos(context: dict):
"""
Return a dict mapping from part of speech to a list of all the definitions with that part of speech.
"""
definitions = context["definitions"]
parts_of_speech = set(definition["part_of_speech"] for definition in definitions)
return {pos.lower(): [... | e06eb30ba8defae84bbd71d27bcb7f9ec29f9edd | 582,461 |
def sum_of_multiples(below, multiples):
"""Returns sum of multiples below given maximum."""
sums = set()
for number in multiples:
for i in range(number, below, number):
sums.add(i)
return sum(sums) | 8f9a16c406c9c7fdc352a9b462ca3acfc6b76b1e | 582,464 |
def unparse_host_port(host, port=None):
"""
Undo parse_host_port().
"""
if ":" in host and not host.startswith("["):
host = "[%s]" % host
if port is not None:
return "%s:%s" % (host, port)
else:
return host | a4e0d61a873e67ae8e0986360c74cbc21fae8040 | 582,472 |
def country(country_code):
"""Extract the country from the given variable."""
return country_code[0:country_code.find('-')] | 9782a7b50f05a95969984fe54e59d4d1abbdab34 | 582,479 |
def split(string, separator=None, max_splits=-1):
""":yaql:split
Returns a list of tokens in the string, using separator as the
delimiter.
:signature: string.split(separator => null, maxSplits => -1)
:receiverArg string: value to be splitted
:argType string: string
:arg separator: delimite... | cda01eaf517489543e11924d77166cab63c67d40 | 582,481 |
def month_delta(date, delta):
"""Function: month_delta
Description: Produces a month delta based on date passed to function.
Arguments:
(input) date -> Date time.
(input) delta -> Delta on date time (i.e. -n...0...n).
(output) month = Numeric month of the year.
(outout) ... | 97f3e73e9b5b1679836a8aba8739fc9940a6f3c1 | 582,482 |
def padding_zero(int_to_pad, lim):
"""
Adds a leading, or padding, zero to an integer if needed. Returns the int
as a str
Parameters
------------
int_to_pad : int
The integer to add padding/leading zero to, if needed
lim : int
Used to check to see if the param int needs a p... | d9153cd02d4cf06e4504ca361e3e38078901b194 | 582,484 |
from typing import List
def is_valid_sample(nn_intervals: List[float], outlier_count: int, removing_rule: float = 0.04) -> bool:
"""
Test if the sample meet the condition to be used for analysis
Parameters
----------
nn_intervals : list
list of Normal to Normal Interval
outlier_count :... | a2caffb114715da6f51b760c48282e713abbea67 | 582,490 |
import uuid
def uuidv4(*args):
"""Generates UUID v4"""
return str(uuid.uuid4()) | 8db07339735971633cffb8afa9a80e79ae3d41e4 | 582,495 |
def insertion_sort(arr: list):
"""
Insertion sorting a list. Big-O: n^2 (average/worst) time; 1 on space.
"""
for ndx in range(1, len(arr)):
pos = ndx
val = arr[ndx]
while pos > 0 and arr[pos-1] > val:
arr[pos] = arr[pos-1]
pos = pos-1
arr[pos] = v... | 8a15554499a3eab7f0474355327f8d91403da6c5 | 582,500 |
import time
def build_empty_config(desc_en='', desc_fr=''):
"""
Get a basic empty config. For consistency.
:rtype:
`dict`
"""
return {
'files': [],
'lastUpdatedAt': int(time.time()),
'whatsNew': {
'description_en': desc_en,
'description_fr':... | 11fce3c9a570d2d1c479fa6cac41fc67ff35bd3a | 582,502 |
def reconstruct_token(token):
"""Given a token, reconstruct the original text."""
# TOKEN_TEXT = 0
# TOKEN_VAR = 1
# TOKEN_BLOCK = 2
# TOKEN_COMMENT = 3
formats = ['%s', '{{%s}}', '{%% %s %%}', '{# %s #}']
return formats[token.token_type] % token.contents | 6b43adf442acea0546855fcb3bb1bfa4e6c22aa7 | 582,506 |
def check_if_file_exists_on_disk(filepath):
"""
Checks if the file exists on the disk.
Could use os.path.exists() but some its safer to do that following.
@param filepath: path to the file including the filename
"""
try :
with open(filepath) as f :
return True
except :
... | cb1d519b906c3ec4db9ec13a248ed71394bb7985 | 582,507 |
def runpath(tmp_path):
"""
Return a temporary runpath for testing. The path will not be automatically
removed after the test for easier investigation.
It takes a form like: /tmp/pytest-of-userid/pytest-151/test_sub_pub_unsub0
"""
return str(tmp_path) | df2d0caa4f4e834fb9f0577f143d79aa17649939 | 582,508 |
def first_non_whitespace_char(string):
"""
Simple function that checks to see what the first non whitespace char is
:param string: the string that is going to be checked
:return: returns the first non whitespace char of string
"""
char = None
for i in range(len(string)):
if string[i]... | 25de5e7b2e4f28d51525752f92a5f971145939c0 | 582,510 |
def product_cols(df):
"""Returns the product of the columns of the specified dataframe."""
return df.product(axis=1) | ec0315163ac725f6aa29be155d2aa3900d63a31c | 582,516 |
def identify_exclusive_feature_groups(entries):
"""
Identifies exclusive FASM features and creates groups of them. Returns a
dict indexed by group names containing sets of the features.
"""
groups = {}
# Scan entries, form groups
for entry in entries:
# Get the feature and split i... | 9704418f35befec38c8325eb97637f241f053d8b | 582,518 |
def neighbor_char(c, r):
"""
This function will return all the neighboring alphabet position by taking
the point we needed and then ignoring the point outside the zone.
----------------------------------------------------------------------------
:param c: (int) the columns index position in the grid(list) (c, r)
... | 726acac8cded338b9a8668fbb885206bfc3157f8 | 582,520 |
def is_capital(name):
"""Check if a taxon name is capitalized.
Parameters
----------
name : str
taxon name to check
Returns
-------
bool
whether taxon name is capitalized
Notes
-----
A valid taxon name may start with "[".
"""
try:
return name.ls... | 6a4aad1e3aaa80653b60bbf8d2c1c4d6c7580c73 | 582,522 |
def _get_container_port_mappings(app):
"""
Get the ``portMappings`` field for the app container.
"""
container = app['container']
# Marathon 1.5+: container.portMappings field
port_mappings = container.get('portMappings')
# Older Marathon: container.docker.portMappings field
if port_ma... | ef73aee2a49a7c267c087c3df6002fcbc1329c8e | 582,527 |
import struct
def unpack_double(byte_stream, endian="<"):
"""Return list of doubles, (either endian) from bytestring.
Unpack a bytes object into list of double-precision
floating-point numbers. Each 8 input bytes decodes to a double.
Args:
byte_stream (bytes): length is a multiple of 8
... | 52b557432c33493e8c3ddbadb42afc0eeeb9b9af | 582,528 |
def gains_helper(gains):
"""
This handles three different cases for gains:
1. gains are all 1. In this case, return conversion=1e-6, which applies to all
channels and converts from microvolts to volts.
2. Gains are all equal, but not 1. In this case, multiply this by 1e-6 to apply this
gain to a... | 3e12819f843a298b6481e00256aed73b6a05abc1 | 582,529 |
import click
def pretty(input_, indent=0):
"""
Pretty print dictionary
:param input_: input
:param indent: number of tabs
:return: None
"""
def get_readable_key(key_):
# capitalize and remove _
if '_' in key_:
return key_.upper().replace('_', ' ')
else... | 2c6391b6ed8af9d805f3ed2059af9b0aa1acc0a3 | 582,531 |
import re
def replace_sequence_chars(sequence_name):
"""Replace special characters in the sequence by underscores (as done for corresponding folder names in ADNI).
Args:
sequence_name: sequence to process
Returns: the new string
"""
return re.sub("[ /;*()<>:]", "_", sequence_name) | ef818eca07ba886cbce93cc9b9db67247d0c6704 | 582,533 |
def hit(x_pos, y_pos):
"""(int, int) -> str or None
Returns the dot (if any) that the point (x_pos, y_pos) is within.
Returns None if the point (x_pos, y_pos) does not overlap any dot.
Used when a player clicks the mouse over the board to determine which dot
(if any) was selected.
"""
dot = ... | 88f194ede74e1e081079bdb93e4c40487b1d4737 | 582,538 |
def Sub(a1, a2, ctx=None):
"""Subtract two numbers"""
return a1 - a2 | e563c81eb0f8b01f5f93b49b259954df6efd486f | 582,540 |
import time
def datetime_to_mstimestamp(date):
"""
Active Direcotry has different approach to create timestamp than Unix.
Here's a function to convert the Unix timestamp to the AD one.
>>> datetime_to_mstimestamp(datetime.datetime(2000, 1, 1, 0, 0))
125911548000000000
"""
timestamp = int(... | 006e3a2e54af7f147acf568a10c3ce7b96dbbb66 | 582,542 |
def recursive_merge(s1, s2, overwrite=False):
"""
Recursively merge two dictionaries
>>> recursive_merge({"a": {"b": 1}}, {"a": {"c": 2}})
{'a': {'b': 1, 'c': 2}}
"""
for k, v in s2.items():
if k in s1 and isinstance(v, dict):
if not isinstance(s1[k], dict):
... | b5282deb4eb433ab65dfdfe98e054e6b9bebca7b | 582,545 |
import yaml
def read_config(path):
"""
Return python dict from .yml file.
Args:
path (str): path to the .yml config.
Returns (dict): configuration object.
"""
with open(path, 'r') as ymlfile:
# yaml.load(file, Loader=yaml.FullLoader)
cfg = yaml.load(ymlfile,Loader=yaml.... | cac40b6a81146abcfe9465e9568a24a805c62e0e | 582,547 |
import time
def sleepy_streamer(sleep_time_sec, outval):
"""
:param sleep_time_sec: how long in seconds to sleep
:param outval: forced return value
:return: a function that sleeps for `sleep_time_sec` seconds and returns `outval`
"""
def out(_1, _2):
time.sleep(sleep_time_sec)
... | c9517ff95c2785f14955334d3beee666d63ffe49 | 582,548 |
def build_endpoint_rule_name(endpoint, method):
"""Build policy rule name for endpoint."""
return ('%(endpoint)s:%(method)s' %
{'endpoint': endpoint, 'method': method.lower()}) | 6b564dacdc70804544c3f1ce3f5a1fbe33c390a2 | 582,549 |
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 |
import click
def option_pid_identifier(required: bool = False):
"""Get parameter options for metadata identifier."""
return click.option(
"--pid-identifier",
"--pid-identifier",
"pid_identifier",
required=required,
help="pid identifier as JSON",
) | c21af8908216421557eabcbf2d831445d65e5af0 | 582,557 |
import math
import random
def random_joint_positions(
number_of_fingers,
lower_bounds=[-math.radians(30), -math.radians(60), -math.radians(100)],
upper_bounds=[math.radians(30), math.radians(60), math.radians(2)],
):
"""Sample a random joint configuration for each finger.
Args:
number_of_... | df5282102fa3b233fa27890e161f744a51515a82 | 582,558 |
def get_coeffs(polynomial_regression):
""" Gets the coefficients for a model polynomial out of the Pipeline
object in the form of a list with the coefficients ordered
from x**0 to x**i for a polynomial of i degrees.
"""
params = polynomial_regression.get_params()
poly_reg = params["poly_reg"]
... | 5ae277d605b9d9ef1e164bcebcab9e3ccf8fd433 | 582,561 |
import six
def string_to_bool(possible_bool_string):
"""
ensures a bool
:param possible_bool_string: might be string, unicode or bool
:return: bool
"""
if isinstance(possible_bool_string, bool):
return possible_bool_string
if isinstance(possible_bool_string, (str, six.text_type)):... | ed1e7e08cee799a5e04e06983d943035019d6514 | 582,562 |
def trade_params(classification, trade_flow, year, origin, destination,
product):
"""
Return a dictionary of parameters for requesting trade data and
visualizations.
Args:
classification (str): specifies which product classification to use
(e.g. 'hs92', 'hs96', 'hs0... | 396f83131974e9adca0c9fbf3578db1ae4d7385b | 582,563 |
def solve(s):
"""
s: positive integer, what the sum should add up to
Solves the following optimization problem:
x1 + x2 + x3 + x4 is minimized
subject to the constraint x1*25 + x2*10 + x3*5 + x4 = s
and that x1, x2, x3, x4 are non-negative integers.
Returns a list of the coeffi... | bc51416cdcc8fdf7291fd634aa10974ba1c05a39 | 582,566 |
import time
def parse_time(strTime):
"""Parse a string like this: 2017-05-11T10:02:03.589"""
# Strip fractional seconds.
strTime = strTime.split(".")[0]
return time.mktime(time.strptime(strTime, '%Y-%m-%dT%H:%M:%S')) | 44f1feba1ce27ea3d17d71f124487df27f1b6f1f | 582,569 |
def combine_histories(existing_history: dict, new_history: dict) -> dict:
"""Combines model training history objects, such that the new history from a more recent training session is
appended to the existing history from a previous training session.
Args:
existing_history: Model training history fr... | 679174dbb48b84d68f7b9775d1da5fb5d2632001 | 582,571 |
def science_pixels(data, instrument_name):
"""Given a full frame image, strip off the reference pixels and return
only the science pixels. At the moment, assume 4 rows and columns of
reference pixels
Parameters
----------
data : numpy.ndarray
2D image
instrument_name : str
... | 7712ec53e725af0adb31fde0443ef0341ec72dd5 | 582,572 |
def create_has_sentiments_present_vector(vector1, vector2):
"""
Create a short vector. If the the vectors are not equal
to zero it returns [1,1], if either of the vectors are equal
to zero it will return a zero for that vector. For example, if
vector1 is a zero vector, but vector2 has values, the fu... | 6bfe1f48cdbff1103550cd6203b018385ac157db | 582,577 |
def bbox_from_xywh(xywh):
"""Convert a bounding box from a numeric dict to a numeric list representation."""
return (
xywh['x'],
xywh['y'],
xywh['x'] + xywh['w'],
xywh['y'] + xywh['h']
) | a11d0e9b0915b7513c874056ee28780ddd5553eb | 582,579 |
def maybe_float(string_or_none):
"""
Parse a string into a float, or None.
"""
if string_or_none in {None, ""}:
return None
return float(string_or_none) | d9bafe8c397140fa878baf37ea2ac2e5e2982831 | 582,583 |
import contextlib
import sqlite3
def sqlite3_safe_execute_binary(db_path:str, statement:str, binary_vals:tuple, fetch:bool=False):
"""
execute statement with auto-commit and connection/cursor auto-close
Return:
cursor: sqlite3.conn.cursor
"""
with contextlib.closing(sqlite3.connect(db_pat... | 8807f15e9e7954fc3d0b922e22d585760994540f | 582,584 |
import pathlib
import csv
def csv_reading(file_path: pathlib.Path) -> list:
"""
read csv file.
the fieldnames is omitted, the values in the first row of file f will be used as the fieldnames.
:param file_path: pathlib.Path: csv file path object
:return: list[dict]: dict list of data
"""
wi... | 17f952ab08f02424b5a145332fdef54107a3eb24 | 582,585 |
def head(iterable):
"""
Gets the first element of the iterable.
:param iterable:
A non-empty iterable. If it is empty a StopIteration error will be raised
:type x:
iterable **(A)**
:returns:
A
"""
it = iter(iterable)
return next(it) | a87f77deefd31b4620c13abf136dbb87ba95e619 | 582,587 |
def is_module(node):
"""Returns whether node is a module node."""
return node.__class__.__name__ == 'Module' | d7f26ec6ac97ca72b05dcf1893a08caf0888cc31 | 582,590 |
import json
def _parse_config_json(path):
"""
Parse the config file JSON into a Python dictionary.
:param path: Path to the config file on disk.
:return: Python dictionary parsed from the JSON config file.
"""
with open(path, 'r') as config_file:
return json.loads(config_file.read()) | 3a0b176c1b11ce92154b79106a1d06b1349106f2 | 582,591 |
def parse_values(string, prefix):
"""Parse the value name pairs output by rndc.
Parse the lines output by rndc with a value and name that are separated by
a space character. Spaces are removed from the, it is converted to lower
case, and prefixed with the prefix variable before becoming the key to the
... | 7f179ef02b475954229453878af5b84c02a9fd09 | 582,595 |
import struct
def _read_ulong(f):
"""Read a 32-bit unsigned long."""
return struct.unpack('>I', f.read(4))[0] | 3871185bcd6b53bc2dcfdb302eb9a76f260e9dc4 | 582,601 |
def check(pos: tuple, num_cols: int, num_rows: int):
"""
Check whether current point is in the grid or not
:param pos: current point
:param num_cols: Number of columns of the grid
:param num_rows: Number of rows of the grid
:return: True if the current point is in the grid otherwise False
""... | 73decd1bc4fb37fa4b4731b30dbb1399cf31c384 | 582,602 |
from typing import Counter
def frequency(lst):
"""Return a Counter with the frequency of the elements in <lst>."""
freq = Counter()
for elem in lst:
freq[elem] += 1
return freq | e08a1889a2514f7962f284dbd319f33b179cd51a | 582,612 |
def list_zfill(l, width):
"""
Pad a list with empty strings on the left, to fill the list to the
specified width. No-op when len(l) >= width.
>>> list_zfill(['a', 'b'], 5)
['', '', '', 'a', 'b']
>>> list_zfill(['a', 'b', 'c'], 1)
['a', 'b', 'c']
>>> list_zfill(['a', 'b', 'c'], 3)
[... | 947a2091eb6f22797ba2f0c5f0a62c95b7eb8d19 | 582,617 |
def match(words, times):
"""A dictionary containing all words typed and their times.
Arguments:
words: A list of strings, each string representing a word typed.
times: A list of lists for how long it took for each player to type
each word.
times[i][j] = time it took for ... | e168e3e663dc6130ad4deb4ab767da52569bcf03 | 582,618 |
import socket
def is_ipv4(ip: str) -> bool:
"""
判断ip是否为可连接的ipv4
Determine whether the IP is a connectable IPv4
:param ip: like 8.8.8.8 etc.
:return: bool
"""
try:
socket.inet_pton(socket.AF_INET, ip)
except AttributeError: # no inet_pton here, sorry
try:
s... | fb972e747411c8359a9e387b2b3a1a28f05e645a | 582,621 |
def parse_core_web_vitals(report: dict):
"""Return a dictionary containing the Core Web Vitals from the report.
Args:
report (dict): JSON dictionary containing report data.
Return:
data (dict): Dictionary containing the key data.
"""
final_url = report['lighthouseResult']['finalU... | d077636a20fb448b6427a751b39f799b0e946240 | 582,622 |
def is_locally_represented_number(self, m):
"""
Determines if the rational number m is locally represented by the quadratic form.
INPUT:
`m` -- an integer
OUTPUT:
boolean
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1,1])
sage: Q.is_locally_represented_numb... | db11af2c854e8c9d17144d46b230580e8e72b8fc | 582,624 |
def make_repeater(n: int):
"""Closure that returns n * string"""
def repeater(string: str) -> str:
assert type(string) == str, "Just strings allowed"
return n * string
return repeater | 13b29d4714ed970ceaa32f0e1e4056939fe0b990 | 582,625 |
def inventory_report(products):
"""Loop over products to calculate # of unique product names and mean price, weight, flammability"""
unique_names = []
total_price = 0
total_weight = 0
total_flammability = 0
num_products = len(products)
for i in range(num_products):
if products[i].nam... | a9093a15c35aa65a9c229183f83ffa367a5ab17b | 582,631 |
def invalid_msg(gateway, child, value_type_name):
"""Return a message for an invalid child during schema validation."""
pres = gateway.const.Presentation
set_req = gateway.const.SetReq
return "{} requires value_type {}".format(
pres(child.type).name, set_req[value_type_name].name
) | 215eaaea4be4a1fddfeea1a7e0b91504f3f2fcdd | 582,632 |
from typing import Any
import pickle
def dump_binary(o: Any) -> bytes:
"""
Serializes an object ``o`` to binary format.
Parameters
----------
o
The object to serialize.
Returns
-------
bytes
A sequence of bytes representing the serialized object.
See Also
---... | 4254f483186280984ac7d7dae8aaecff08f8ca9d | 582,633 |
def readfile(filename: str) -> str:
"""Read a whole file into a string and return it."""
with open(filename) as file:
return file.read() | f187fefd32938ab698f20b4473c61f412aac2d54 | 582,634 |
def top_of_stack(l):
"""Returns the element on top of the stack."""
if not l:
return None
return l[-1] | 0b070d7703a2077005d646b92d132d96afaecdf8 | 582,635 |
import math
def lat_lon_2_cart(lat, lon):
"""
Convert lat/lon coordinates to cartesian.
Parameters
----------
lat : array-like
latitude (-90 to 90)
lon : array-like
longitude (-180 to 180)
Returns
-------
cart : tuple
(x, y, z) cartesian coordinates on the... | 64adead28e335c75f0c25b57c8961f142b9fab9f | 582,636 |
def hgt_to_mb(hgt, mslp=1013.25):
"""Convert altitude, in meters, to expected millibars."""
return mslp*(1-hgt/44307.69396)**5.2553026 | 4aa4fd818ee4fbe939fd657e87eebbdd71329287 | 582,645 |
def _get_padding(K, mode):
""" Helper method to compute padding size """
if mode == 'valid':
return 0
elif mode == 'same':
assert K % 2 == 1, 'Invalid kernel size %d for "same" padding' % K
return (K - 1) // 2 | db80b4c4c8953fd3e8d58555f59f0c1440a3d706 | 582,655 |
def get_location_dataframe(matrix_dataframe):
"""
Extracts the X, Y and Z location from the 4x4 matrix dataframe above and places them
in a smaller dataframe with just the locations per timestamp.
:param pd.DataFrame matrix_dataframe:
:return: pd.DataFrame
"""
df_location = matrix_datafram... | fe3d6824dda0496977e3784dfe68f869c13d5c6e | 582,656 |
from datetime import datetime
def get_file_age(file):
"""Returns the age of file.
Args:
file: A PosixPath object representing a file.
Returns: An int represeting the age in days.
"""
return (datetime.today()
- datetime.fromtimestamp(file.stat().st_mtime)).days | 5d62ce19ea5b4fd2d34c4c1ecd0240d85b1af085 | 582,659 |
def iqa_func_wrapper(iqa_compute_function, img1, img2, **kwargs):
"""
:param iqa_compute_function: iqa compute function to be called
:param img1:
:param img2:
:param kwargs: any additional arguments for IQA functions
:return:
"""
# make a copy to avoid any modifications to the original ... | 6d1064ec201e28b1858340f4bde637c0bf933840 | 582,660 |
from typing import Any
from typing import Union
from typing import List
def to_dict(obj: Any) -> dict:
"""Converts class instances to dictionaries.
Handles nested objects as well."""
if not hasattr(obj, "__dict__"):
return obj
result: dict = {}
for key, val in obj.__dict__.items():
... | f47f519e2c91aee9c97a2f8622e2f39cec53e32b | 582,664 |
def find_lcm(num_1, num_2):
"""Find the least common multiple of two numbers.
>>> find_lcm(5,2)
10
>>> find_lcm(12,76)
228
"""
if num_1>=num_2:
max_num=num_1
else:
max_num=num_2
lcm = max_num
while True:
if ((lcm % num_1 == 0) and (lcm % n... | 6d9bfc1f133b744d170febc04680318724d81d6c | 582,666 |
def field_valid(field):
"""
Utility to exclude fields not user added
:param field: arcpy field object
:return: boolean
"""
# exclude object id
if field.type == 'OID':
return False
# exclude global id field
elif field.type == 'GlobalID':
return False
# exclude th... | 7f508f694735f2d1b8902c6a41feb70745a11be0 | 582,667 |
def get_seats(positions, seats):
"""Get seats from positions list and seats list of lists."""
return [seats[adj_row][adj_col] for adj_row, adj_col in positions] | 1152a3fea3e667ecb9d7687f80ae70c506b9c1b2 | 582,668 |
def equals(v1, v2, epsilon):
"""
Returns True if difference between given values is less then tolerance.
Args:
v1: float
Value one.
v2: float
Value two
epsilon: float
Max allowed difference.
Returns:
bool
... | c44092b2e3ffb76b8cf6ffa75167228dfa04681b | 582,672 |
import pathlib
def utils_files_find(path:pathlib.Path, pattern, num=1):
"""find files in `path` by regex rules specified by `pattern`"""
files = sorted(path.rglob(pattern))
return files | e049f1899c5d7ded5640c8cd714a2bff12b5b2d7 | 582,678 |
def daily_severity_rating(fwi):
"""Daily severity rating (canadian index).
Parameters
----------
fwi : array
Fire weather index
Returns
-------
array
Daily severity rating.
"""
return 0.0272 * fwi ** 1.77 | 53aa1b8a2386f459539a10044514f778897aa316 | 582,684 |
def square(x):
"""Square function: a(x) = x*x"""
return x * x | 084c029b6122919997270ea82420f0159a772d26 | 582,685 |
def valid_replay(info, ping, replay, replay_list):
"""Make sure the replay isn't corrupt, and is worth looking at."""
if info.HasField("error"):
print((" Replay has error field ").center(107, "="))
return False
if (info.base_build != ping.base_build or # different game version
info.... | a327be698b2cede5761fbd482b676f6b5e7a31e0 | 582,687 |
def RC(a,b):
"""
Compute Carlson's integral RC(a, b).
1 /\oo dx
RC(a, b) = - | -----------------
2 | 1/2
\/0 (x + a) (x + b)
The parameters a and b may be complex numbers.
"""
A, B = a, b
for k in range(4):
g... | 3e08b68d46a60db326b74dea04c8b9577e1f986a | 582,690 |
def cli(ctx, name=""):
"""Create a new history, optionally setting the ``name``.
Output:
Dictionary containing information about newly created history
"""
return ctx.gi.histories.create_history(name=name) | 05ef3b0f344078b23cf24f6d2f56050d4345ea63 | 582,693 |
def get_private_key_user(user: str, index: int) -> str:
"""
Returns the keychain user string for a key index.
"""
return f"wallet-{user}-{index}" | 4c5b4ea6fefc4bfa25d336f8876d2a7dd754a10e | 582,696 |
def negate(functions, *args, **kwargs):
"""Returns True if all functions return False."""
for f in functions:
if f(*args, **kwargs):
return False
return True | 525a95e9fc5817c007c9044095b73610a4ecc365 | 582,698 |
def fact(x):
"""Return factorial of x."""
if x == 1:
return 1 # Base case
else:
return fact(x-1) * x | 3e11e405ad0f9960e4ecec214e7348798a67d075 | 582,701 |
import uuid
def create_unique_filename() -> str:
"""
Creates a unique filename for storing uploaded images.
"""
return str(uuid.uuid4()) | ed89bb503b03493aa1dbb7ff0c2829432ae6b599 | 582,702 |
def event_loop_policy(request) -> str:
"""Return the active event loop policy for the test.
Valid values are "default" and "uvloop".
The default implementation defers to the `event_loop_policy` marker
when it is set and otherwise selects a default policy based on the
characteristics of the test be... | f7c732b16265e14fba6cf7a06f47fd2041284e86 | 582,705 |
def _make_intro_dict(request):
"""
make poet's introduction dict
:param request: wsgi request
:return: dict
"""
param = request.args
return {
'poet': param.get('poet', '李白'),
'dynasty': param.get('dynasty', '唐')
} | 0de7636f774880517527867094095dee4b7ca1d7 | 582,706 |
def extract_primary_text(sTextualDS_node):
"""
extracts the primary text from an STextualDS node.
NOTE: In most corpora only one primary text will be linked to a document,
but this might not always be the case (e.g. in corpora of parallel texts).
"""
text_element = sTextualDS_node.find('labels[... | 64740d4d00465b94bd71d2bc6f1895831509f1bc | 582,710 |
from typing import Dict
def rock_label_map() -> Dict[int, str]:
""" Mapping from label num to label name
"""
label_map = {0: 'background', 1: 'bathtub', 2: 'bed', 3: 'bookshelf', 4: 'box', 5: 'chair', 6: 'counter', 7: 'desk',
8: 'door', 9: 'dresser', 10: 'garbage bin', 11: 'lamp', 12: 'mo... | 9a7062eaade0911fe7df125f84cf0860735a3024 | 582,711 |
def _line_is_numpy_parameter_type(line_info):
"""Returns whether the line contains a numpy style parameter type definition.
We look for a line of the form:
x : type
And we have to exclude false positives on argument descriptions containing a
colon by checking the indentation of the line above.
Args:
... | 4a8211f6d0e15e1dcdfd974fc50f1978a0ef0f9d | 582,712 |
import hashlib
def activity_hash(dataset):
"""Return the hash string that uniquely identifies an activity.
Uses the following fields, in order:
* name
* reference product
* unit
* location
* start date
* end date
An empty string is used if a field isn't pr... | cdec16ba7d018fb0b45739d394d8e44653bd359c | 582,714 |
def get_public_instance_attributes(instance):
"""
Get list of all instance public atrributes.
Parameters
----------
instance : optional
Returns
-------
list of str
"""
public_attributes = [
attribute
for attribute in instance.__dir__() if attribute[0] != '_'
... | c6cc34e599fa7fe6ed8b913aa07f7c517b97bfce | 582,715 |
def date_to_yyyydoy(date):
"""
Convert a datetime.date object to a string in the form 'yyyy.doy',
where yyyy is the 4 character year number and doy is the 3 character
day of year
:param date: datetime.date object
:type date: datetime.date
:return: string with date in the form 'yyyy.doy'
... | ef6d9ac674beaaaaf806435ad47a3b59e6196113 | 582,716 |
def assert_allclose(x, y, rtol=1.e-5, atol=1.e-5):
"""
Asserts if all numeric values from two arrays are close.
Parameters
----------
x: ndarray
Expected value.
y: ndarray
Actual value.
rtol: float (optional)
Relative tolerance on the error. Default is 1.e-5.
ato... | ebf5191d3430e515c7ad1c0c63032ae38e92a509 | 582,719 |
def cPlusPlusPrerequisites(fileDesc):
"""
Writes the prerequisites depending on the main's project language.
Parameters
-------
fileDesc : TextIOWrapper | None
Filedescriptor describing the README.md file
"""
fileDesc.write("To use this project, you'll need G++ Compiler.\n\n")
r... | 5d86f49b7a4a730aa4992147f98c0b2b2a3ceec9 | 582,728 |
def validate_predictivescalingmaxcapacitybehavior(predictivescalingmaxcapacitybehavior):
"""
Validate PredictiveScalingMaxCapacityBehavior for ScalingInstruction
Property: ScalingInstruction.PredictiveScalingMaxCapacityBehavior
"""
VALID_PREDICTIVESCALINGMAXCAPACITYBEHAVIOR = (
"SetForecast... | dfa641d5ff092f602a57903fb9667f5761a07f78 | 582,729 |
import json
def dict_to_json( dictionary: dict ) -> str:
"""Given a dictionary, turn it into a json string"""
return json.dumps( dictionary ) | b00000c138ac0490a226e8f6a97bd1b225aa734a | 582,732 |
def remove_punc(sent):
"""
Filter out punctuations
"""
punc_lst = [".", ",", "!", "?", ";"]
for punctuation in punc_lst:
sent = sent.replace(punctuation, "")
sent = sent.replace(" ", " ")
return sent | 1c73e33aae11ec329bed62c48479adb425721257 | 582,736 |
def extract_params(params):
"""Extract weights and biases."""
param_length = len(params)
if param_length == 1:
weight = params[0]
bias = None
elif param_length == 2:
weight = params[0]
bias = params[1]
else:
raise ValueError("Unexpected number of parameters: {... | 63cb6a8a21740e52442671c392afd2da470db422 | 582,737 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.