content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Sequence
from typing import Optional
import re
def combine_patterns(patterns: Sequence[str], groupname: Optional[str] = None) -> str:
"""Combine multiple pattern strings into a single pattern string.
Because multiple identical group names are not allowed in a pattern, the resulting object ... | 86305659bebe780517598ee84c3c91e0b4d1226d | 610,491 |
def getWordsEqualTo(wordList, targetLength):
""" return list of words of a specified length in the list """
return [word for word in wordList if len(word) == targetLength] | 4d506571207d9c4baba9ed1cbc768ff85195f367 | 610,492 |
def parse_input(puzzle_input: str) -> range:
"""Split the input of dash-separated numbers into an inclusive range"""
start, last = map(int, puzzle_input.split("-"))
return range(start, last + 1) | 101eac9b3390a7028e7db6c8a5ce717a25906499 | 610,497 |
def variable_parser(var_list, prefix):
"""return a subset of the all_variables by prefix"""
ret_list = []
for var in var_list:
varname = var.name
varprefix = varname.split('/')[0]
if varprefix == prefix:
ret_list.append(var)
return ret_list | 4a4e8c22fb07e57aa990f05651d1858d69b295e0 | 610,499 |
def find_all_indexes(text, pattern):
"""Return a list of starting indexes of all occurrences of pattern in text,
or an empty list if not found."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
# ins... | cd70275c95c6211d39d059d30ce3579151b929ef | 610,503 |
def VecAdd(a, b):
"""Return vector a-b.
Args:
a: n-tuple of floats
b: n-tuple of floats
Returns:
n-tuple of floats - pairwise addition a+b
"""
n = len(a)
assert(n == len(b))
return tuple([a[i] + b[i] for i in range(n)]) | f9ad6cdd62ed5cbe0753d4a0585f4c0070e224fc | 610,504 |
import requests
def healthcheck(url):
"""
check the health of server
Args:
url:``str``
url of healthcheck endpoint
Return:
if live True else False
"""
try:
r = requests.get('http://localhost:5000/healthcheck')
output = r.json()
... | c60f73acb071f78458d51794bb19bc5d5ebe55a9 | 610,508 |
def octets(options, cc):
"""Format each byte of the encoded character."""
utf8_bytes = cc.encode(options.encoding)
octets = []
for utf8_byte in utf8_bytes:
byte_in_hex = "0x%02X" % utf8_byte
octets.append(byte_in_hex)
return " ".join(octets) | 5ef37c3a0ca2aaf9829c7441284edb3678fd5e2f | 610,510 |
def construct_feed_dict(x, y, model):
"""
Construct feed dictionary.
Used to provide input to the tensorflow model
x - a batch of predictors
y - a batch of target
model - an instance of GraphConvLSTM
"""
feed_dict = dict()
feed_dict.update({model.inputs_placeholder: x})
... | 2cfaed76f32e4fc0592297b2ff149d7f6dbff0e4 | 610,516 |
def isDisk(result):
"""Checks if result has a disk related strings."""
disk_identifier = ["Logical Drive", "HDD", "Storage", "LogVol"]
return any(e in result for e in disk_identifier) | 8165a8fedbee6e246df4d0394ed29f9341bfd257 | 610,519 |
def get_lang_from_corpus_name(corpus_name):
"""
Determines the language of a corpus based on its name.
"""
if corpus_name.startswith("conll03_en") or corpus_name.startswith("ud_en"):
return "en"
elif corpus_name in ["conll03_de", "germeval"]:
return "de"
else:
return Non... | 76c2954fa3c474f5e788a0662fea84dede196c00 | 610,520 |
def freebsd_translator(value):
"""Translates a "freebsd" target to freebsd selections."""
return {"@com_github_renatoutsch_rules_system//system:freebsd": value} | 752f3d2b030fd01e0601bcc784dfb66900613a5a | 610,521 |
def pop_from_key_value_set(kvset, *keys):
"""
Pops the values of ``keys`` from ``kvset`` and returns them as a tuple. If a
key is not found in ``kvset``, ``None`` is used instead.
>>> kvset = [('a',0), ('b',1), ('c',2)]
>>> pop_from_key_value_set(kvset, 'a', 'foo', 'c')
(0, None, 2)
>>> kvs... | 32d0dc8cda4b32fbfe1dccc1acf2ec31f3acc717 | 610,523 |
def path_join(*args):
""" Joins given arguments into an entry route.
Slashes are stripped for each argument.
"""
reduced = [x.lstrip('/').rstrip('/') for x in args if x]
return '/'.join([x for x in reduced if x]) | 591e1dc5ff27bdded1bf03bfdc9d787eb5f36477 | 610,532 |
import six
def body_to_json(response):
"""
Returns the JSON-encoded contents of `response`, raising a detailed error on failure.
Parameters
----------
response : :class:`requests.Response`
HTTP response.
Returns
-------
contents : dict
JSON-encoded contents of `respon... | 5735e60454397fd9400cdb36760ac5cac8c2eeee | 610,535 |
def to_discord_description_safe(text: str) -> str:
"""Convert the given string to one that will be accepted by discord as a description
for a channel.
"""
return text[:1024] | 58789f4f9500d95a80a08c016a89c46d54da92c5 | 610,536 |
import torch
def transform(boxes, transform_param):
"""
transform boxes
:param boxes: (n, 4) tensor, (cx, cy, w, h) form.
:param transform_param: (n, 4) tensor.
:return: (n, 4) transformed boxes, (cx, cy, w, h) form.
"""
cx = boxes[:, 0] + transform_param[:, 0] * boxes[:, 2]
cy = boxe... | f4827c34f3a1ec4160ca283926c21e355917caa1 | 610,537 |
import math
def to_radians(degrees):
"""Convert degress to radians.
>>> to_radians(0)
0.0
>>> to_radians(360)
6.283185307179586
>>> to_radians(90)
1.5707963267948966
>>> to_radians(180)
3.141592653589793
>>> to_radians(-180)
-3.141592653589793
"""
return degrees * ... | 6fb342e5346e9f729603a21d5ad344241387eab3 | 610,538 |
def gcd(a:int,b:int)->int:
""" Euclid's algorithm for GCD of two integers
"""
if a<=0 or b<=0:
raise Exception('only positive integers as input to gcd')
while True:
if a==b:
return a
elif b==1 or a==1:
return 1
elif a>b:
b = a-... | 6d91a2faa7a593470e16a3245da6126371baafa1 | 610,540 |
def gain(xi=100.0, xf=110.0):
"""
Calculate gain from intial to final value.
"""
return (xf - xi) / xi | 41fb410c9382c5611f9a12b53148cc6c59585abd | 610,541 |
import json
def _get_ha_state_from_json(string_json):
"""
Searches through the specified JSON string looking for either the HDP 2.0 or 2.1+ HA state
enumerations.
:param string_json: the string JSON
:return: the value of the HA state (active, standby, etc)
"""
json_data = json.loads(string_json)
jmx_... | 23dd2a547982a7fcc734a90b509caeff18fa90b3 | 610,543 |
import hashlib
def sha1_hexdigest(input_string):
"""Return hex digest of the sha1sum of the input_string."""
byte_string = input_string.encode()
return hashlib.sha1(byte_string).hexdigest() | 96d7ab85d1bc3f76ae8706d7b1557c11c86a5f73 | 610,545 |
def say_hello(name):
"""Prints Hello followed by the name
Arguments:
name {String} -- name of the person
Returns:
String -- Greeting message
"""
print(f"Hello, {name}")
return f"Hello, {name}" | eaaaeafe4638c5b725f24f63f620f5ecb3748d33 | 610,547 |
def say_hello(name: str, salutation: str = "Hello") -> str:
"""Say hello to the user."""
return f"{salutation.capitalize()}, {name.capitalize()}. Welcome to the wonderful world of Python." | fbe2cb171602022c12ca9e02f02d0d61c13e85fc | 610,549 |
def parse_bpr_param_matrix(matrix_filename):
"""
Parse the BPR parameters ( alpha, beta) for each road type
(actually CAPINDEX in SQL for some reson) from the MATLAB ASCII matrix
file generated by the fitbprparams.m script from SpeedflowVoyager CSV data.
Parameters:
matrix_filename - filenam... | 4158a418a3c59a58669e063d1e2cb43ab0d67a65 | 610,553 |
def artifact_version_unsupported(artifact_version, supported_major_version):
"""artifact_version_unsupported message"""
return "The decisioning artifact version ({}) is not supported. " \
"This library is compatible with this major version: " \
"{}".format(artifact_version, supported_major... | 12228c330dbee93d8ffb1ab7e594dfce8dc0b83c | 610,556 |
def decode_data(data):
"""Decode bytes to string
"""
return data.decode(encoding='utf-8') if isinstance(data, bytes) else data | 5b7b873c27820e89151f43406051e150675cc3b2 | 610,557 |
def search_key_for_post(bookmark):
"""Generate a string search key for a bookmark"""
elements = []
elements.append(bookmark['title']) # title of bookmark
# elements.append(bookmark['link']) # bookmark tags
# elements.append(bookmark['summary']) # description
return u' '.join(elements) | 92cbc5d0666a12b390942af0e118648017cad822 | 610,560 |
from typing import Counter
import operator
def get_max_count_annotation(annotations_dic):
"""
Get the annotation with the max count from a given `annoations_dic`
annotations_dic:dict
A dictionary of the form
{pvog_id :
[annotation_1, annotation_2, ...],
... | a6bfd30faf937500f93fa13d223014ed03602321 | 610,561 |
def split_every(length, collection):
"""Splits a collection into slices of the specified length"""
return [
collection[length * i : length * (i + 1)]
for i in range(0, round(len(collection) / length + 1))
if collection[length * i : length * (i + 1)]
] | a1f44e4103057ca3c8ee6a2b6ca6423743775921 | 610,563 |
def _calc_box(ip_range, op_range):
"""Main function for calculating box regions of interest.
Called by op_box_roi and ip_box_roi.
Args:
ip_range (tuple): in-plane (min, max).
op_range (tuple): out-of-plane (min, max).
Returns:
qr, qz (tuple of ndarrays): arrays defining the re... | 6a1684da13e1e5c7c354b6e7f9c93b149dadd9b2 | 610,564 |
def minus(x, y):
"""Returns a difference of two variables"""
return x - y | 606426b03e7625541d2e5d8119dd7d734c80e94c | 610,567 |
def fetch_fields() -> dict[str, list[str]]:
"""Specify the expansions and fields for needed information."""
return {
"expansions": ["attachments.media_keys", "author_id"],
"tweet_fields": ["created_at", "entities"],
"media_fields": ["alt_text", "preview_image_url", "url"],
} | 197df16bc4b989dac6f37b03760dc1a5b36317d5 | 610,568 |
import torch
def inverse_softplus(x: torch.Tensor) -> torch.Tensor:
"""Inverse function to torch.functional.softplus.
Parameters
----------
x: torch.Tensor.
Input tensor to transform.
Returns
-------
output: torch.Tensor.
Transformed tensor.
"""
return torch.log(t... | aeb75d956e8a153a418e35b8664c1910f65a7fd7 | 610,572 |
def normalize_pipeline_name(name=''):
"""Translate unsafe characters to underscores."""
normalized_name = name
for bad in '\\/?%#':
normalized_name = normalized_name.replace(bad, '_')
return normalized_name | 750b91c1d19d9a7ce92b9c5efa453a2a13595776 | 610,574 |
def create_stairwaytotravel_url(place_id):
"""Create a url to a place page given the place id."""
return "https://stairwaytotravel.com/explore/" + str(place_id) | b658106512a3e0a26998b2462a2c83816e239439 | 610,577 |
import math
def to_deg(rad) -> float:
"""Convert radiants to angle."""
return rad / math.pi * 180.0 | 369d544ff2c7bcd3c036ca6dc47e3fa48804597f | 610,578 |
def _get_charset(headers):
"""Gets response charset.
Args:
headers: The HTTP response headers as dict.
Returns:
A response charset or None.
"""
content_type = headers.get('content-type')
charset = None
if content_type is not None:
parts = content_type.split('charse... | 83ce32a266e5235a14050382e352b3f7d45ac839 | 610,583 |
def exec_command(host, command_list):
"""
Executes shell commands on host
:param host: host object
:param command_list: list of commands to execute
:return : response from host or exception __str__
"""
if len(command_list) == 1:
try:
response = host.shell(command_list[0])... | 1b7ec4009ff98cac4d6da752238c2ab5edd474fd | 610,588 |
def ignored(part):
"""Determine if a part is ignored.
A part being ignored does not mean it will never be added, it just means
it's not _currently_ being added."""
style = part['style']
# Ignore any styles we don't support right now.
known_styles = [
# Dual-row.
'DIP',
... | 96ef22e51b7f3620fe453bd3c4792e606d925da7 | 610,592 |
def phase_folding(t, y, yerr, period):
"""
phase_folding() allows the phase folding (duh...) of a given data
accordingly to a given period
Parameters
----------
t: array
Time
y: array
Measurements
yerr: array
Measurement errors
period: float
Period to... | 5ba4206b1b146f67e608a26749d207c23830464a | 610,593 |
def read_int(b, i, size=2):
"""Read an integer from bytearray.
b -- bytearray
i -- starting index
size -- number of bytes to read
"""
return int.from_bytes(b[i:i+size], byteorder='big', signed=True) | 9971e8182db3057790bc7952856af2d88f601556 | 610,594 |
import collections
def flatten_observation_dim(observation_dim, observation_excluded=()):
"""Flattens the observation dimensions to an array.
If observation_excluded is passed in, it will still return a dictionary,
which includes all the (key, observation_dict[key]) in observation_excluded,
and ('other': the... | 08447efd546d6cb0f90d9882c0d7fa4b0ed2b082 | 610,595 |
def _media_path_url_from_info(root_desc, path_url):
"""Creates an absolute media path URL.
Constructed using the API root URI and service path from the discovery
document and the relative path for the API method.
Args:
root_desc: Dictionary; the entire original deserialized discovery document.
path_... | 88a8a23c427e3d722266ed8d37d6588f09925c41 | 610,598 |
def wpad_search_urls(subdomain_or_host, fld):
"""
Generate URLs from which to look for a PAC file, based on the subdomain and TLD parts of
a fully-qualified host name.
:param str subdomain_or_host: Subdomain portion of the fully-qualified host name.
For foo.bar.example.com, this is foo.bar.
... | 5342757fe42ddab310952420572e185037ddf18f | 610,605 |
def vminw(v, w):
"""
v - w
"""
return [v[i] - w[i] for i in range(len(v))] | 111f422052e0725f6b5fd8e0268d92da17b0fe8c | 610,608 |
def get_safe_name(name: str) -> str:
"""Returns the safe version of a username."""
# Safe name should meet few criterias.
# - Whole name should be lower letters.
# - Space must be replaced with _
return name.lower().replace(' ', '_') | 401b09a7d2f287478b3ad1f6ba285d2a7667dc79 | 610,609 |
def get_pci_list(ns, pcis, bus=0, level=0):
"""
Recursive function, returns list of PCI devices ready for TableFormatter.
:param ns: LMI Namespace.
:type ns: :py:class:`lmi.shell.LMINamespace.LMINamespace`
:param pcis: Sorted list of PCI devices and bridges.
:type pcis: List
:param bus: ID ... | 883d0b23e339b729ab59333ff11bf09dbfeb1c46 | 610,611 |
def get_input(prompt):
""" prompt user for input """
print("")
print(prompt)
result = input()
return result | 3826c39ae4f2bc184ba69b73d7e49156dee44ff0 | 610,612 |
def get_att_mats(translate_model):
"""Get's the tensors representing the attentions from a build model.
The attentions are stored in a dict on the Transformer object while building
the graph.
Args:
translate_model: Transformer object to fetch the attention weights from.
Returns:
Tuple of attention ma... | 94285f552fae658cf09549d75937fa4a55c2dfb3 | 610,618 |
def contigs_dict(contigs):
"""Creates a dictionary for contigs.
Args:
contigs: Iterable of ContigInfo protos.
Returns:
A dictionary mapping contig.name: contig for each contig in contigs.
"""
return {contig.name: contig for contig in contigs} | 476aa5df5104b30e7a987486ea767c7dfdff096c | 610,623 |
import csv
def get_source_list(filename):
"""
Read the sources and the beams they can be found in from the targets csv file.
Parameters
----------
filename: str
Name of the csv file listing all sources and the beams they can be found in.
Returns
-------
List of the source... | b81e9de5efd3688456273e0d6a42c54cb121418b | 610,625 |
def rreplace(string, old, new, occurrence=1):
"""
Replace n occurrences of old in string with new, starting from the end.
"""
parts = string.rsplit(old, occurrence)
return new.join(parts) | aae244a699fafbfbec8a4724a310f0a752335f2a | 610,627 |
def fadeout(clip, duration):
"""
Makes the clip fade to black progressively, over ``duration`` seconds.
For more advanced fading, see ``composition.crossfade``
"""
fading = lambda t: min(1.0 * (clip.duration - t) / duration, 1)
return clip.fl(lambda gf, t: fading(t) * gf(t)) | 9394f8db51a442f0692ece9de24af6af8952e15e | 610,632 |
def tableDataText(table):
"""Parses a html segment started with tag <table> followed
by multiple <tr> (table rows) and inner <td> (table data) tags.
It returns a list of rows with inner columns.
Accepts only one <th> (table header/data) in the first row.
"""
def rowgetDataText(tr, coltag='td'):... | 3a96bed29cbfb6bb44ead18cab1ecce42a13fb89 | 610,634 |
import math
def segment_length(x, y, z):
"""Return the length of the segment."""
return math.sqrt(x*x+y*y+z*z) | f1637ad185acaebeb816f531553768dfad5f91e0 | 610,635 |
import random
import string
def generate_uid(level=30):
"""
Generates a complex and safe to use unique ID. This is very useful when you need a
key for AI response endpoint.
Parameters:
level (int) (optional):
This determines how many chars will there be in the generated key. I... | a79b910880f600be4cd95cea6eeb5b876d87af0a | 610,637 |
def sh_escape(command):
"""
Escape special characters from a command so that it can be passed
as a double quoted (" ") string in a (ba)sh command.
Args:
command: the command string to escape.
Returns:
The escaped command string. The required englobing double
quo... | 9c80c687b04f19217760dc7d04d71a5742686ea1 | 610,640 |
def var_match(child_var, parent_record):
"""Given a variant from the child and a GFF record for a parent, check
if the parent contributed the variant. Return values:
-1 - No
0 - Maybe (requires parent is heterozygous)
1 - Yes (requires parent is homozygous)"""
NO, MAYBE, YES = range(-1, 2)
... | a0d953d5a4dbf51b893f477e81bde14c768ac913 | 610,646 |
def FirstRest(tokens):
"""List utility; splits a /list/ robustly into first & rest.
Args:
tokens: the list of tokens.
Returns:
Tuple of first token, and list of remaining.
"""
assert isinstance(tokens, list)
if not tokens:
first = None
rest = []
else:
first = tokens[0]
rest = ... | 413cb98ba28c5f28ced05a6694dd51ec672caf2e | 610,649 |
def is_dir(tar, key):
"""
Check whether a member in a tarball is a directory
"""
for member in tar.getmembers():
if key == "/" or member.name.startswith(key):
return True
return False | 38e7cad041fc0ec66bb71d0d2090b9e0f0a066c3 | 610,651 |
import re
def multiple_replace(text: str, chars_to_mapping: dict):
"""
This function is used to replace a dictionary of characters inside a text string
:param text:
:param chars_to_mapping:
:return:
"""
pattern = "|".join(map(re.escape, chars_to_mapping.keys()))
return re.sub(pattern,... | 977caf486cf8c89fa9aaa8b502914bf47d670ebf | 610,652 |
def median(lst, presorted=False):
"""
Returns the median of a list of float/int numbers. A lot of our median
calculations are done on presorted data so the presorted flag can be
set to skip unnecessary sorting.
:param lst: list
:param presorted: Boolean
:return: float
"""
if not pres... | 320ac6df1bf912f7ac723e7037b9fcfa9d9c8ee7 | 610,653 |
def evaluate(model, validation_dl):
"""
Evaluate model at epoch
* :param model(torch.nn.module): ResNet model
* :param validation_dl(torch.dataloader): Validation data
:return (dict): Validation results for model at current epoch
"""
model.eval()
return model.validate_epoch([mod... | e55c5ef340826071f58e093e46ad9ba2d050cecd | 610,655 |
import pwd
def to_uid(name):
"""Return an uid, given a user name.
If the name is an integer, make sure it's an existing uid.
If the user name is unknown, raises a ValueError.
"""
if isinstance(name, int):
try:
pwd.getpwuid(name)
return name
except (KeyError... | 12681eb97bbfb78ac3aa0927904ecdf023477172 | 610,660 |
def utf2latex(utf, exception=None):
"""Convert a utf character to latex"""
if utf == exception:
return(utf)
else:
latex = utf.encode('latex').decode('utf-8')
return(latex) | 4c6c587223dc21efc406cff1d9d1d398ec3f86c6 | 610,662 |
import six
def format_stat(stat):
"""Turn numbers possibly with embedded commas into integers.
Also accepts existing ints, which may be pre-converted from Excel.
:param stat: numeric value, possibly with commas
:return: int
"""
if isinstance(stat, six.integer_types):
return stat
... | 54b7e93d1666252de9209c3b6b2ed8565c80becf | 610,663 |
def check_unique(df, threshold=3):
"""
Check unique values in a dataframe.
df: dataframe
threshold: minimum about of unique values to not flag out.
"""
counts = {}
insuf_cols = []
has_empty_cols = []
cols = df.columns.values
for col in cols:
uniq_vals = df[col].unique()
... | a48ad626934aed62a318d61f605a2b0b0075cde4 | 610,669 |
def get_bbox(geo_pd):
"""Gets the bounding box of a geopandas dataframe
Args:
geo_pd (geopandas): shape from which we can get the bounding box as a basis for the extend of the meshgrid
Return:
(tuple of floats): bbox (x_min, y_min, x_max, y_max)
"""
return (geo_pd.total_bounds[0], ... | 79627a1e2e2d3557e380dd8dee01df98f695e1bd | 610,679 |
def context_before(string, index, contextnum):
"""gets the specified number of characters before the given index,
or until the beginning of the string.
"""
if contextnum < 0:
raise ValueError("Context amount cannot be negative")
bound = index - contextnum
# start at beginning of string ... | 5ca7d6d7db1d06f52a21475bc4426934ef1f2463 | 610,693 |
def fields_values(d, k):
"""
>>> data = {'name1': ['value1.1', 'value1.2'], 'name2': ['value2.1', 'value2.2'], }
>>> print(fields_values(data, 'name1'))
value1.1,value1.2
"""
values = d.get(k, [])
return ",".join(map(str, values)) | 9b693fdc1c50601efba685426a835ac11ddb0d8a | 610,695 |
def invert_dict(front_dict):
""" Take a dict of key->values and return values->[keys] """
back_dict = { value : [] for value in front_dict.values() }
for key, value in front_dict.items():
back_dict[value].append(key)
return back_dict | d936ab299f20b98272534097887070df5d08a931 | 610,697 |
def process_running(proc):
"""Checks if a process is still running. Returns Boolean."""
try:
proc.poll()
return True
except: return False | 69efb3b6295ec3e1d3e1298571d4931230fde369 | 610,698 |
def drop_origine(df):
"""
Drops rows where the Cause column has value Unspecified and Reburn, and then drops the column titled 'Origine'
"""
df=df[ (df["Cause"]!="Unspecified") & (df["Cause"]!="Reburn") ].drop("Origine",axis='columns')
return df | cfab3294c291568b8ec5cecb0fd0dda109a16db4 | 610,700 |
def omega(n,w):
"""
Calculates Omega(n,w)
Args:
n is the symplectic multiplicity (class U3State)
w is the symplectic weight (class U3State)
Returns:
Omega (float). For example:
om=U3State([4.5,.5,.5])
n=U3State([4,0,0])
omega(n,om)
returns
4.375.
"""
Omga=0
... | e095e592e7b6d30d3f435d4b58c0151d437dd7be | 610,701 |
def load_nanomax_monitor(logfile):
"""
Load the default monitor for a dataset measured at NANOMAX.
:param logfile: h5py File object of NANOMAX .h5 scan file
:return: the default monitor values
"""
group_key = list(logfile.keys())[0] # currently 'entry'
monitor = logfile["/" + group_key + "... | e39e9951331624359f303d3b8e69fb5a85086a4c | 610,708 |
def block_format(pieces, width=79):
"""Concatenate bytestrings, adding newlines.
pieces -- iterable of strings
width -- int (default 79)
Returns "".join(pieces), with added newlines between pieces as necessary to
avoid lines longer than 'width'.
Leaves newlines inside 'pieces' untouched, and... | a96785e83b0d756b3b83b61ac8cb7629084cb19e | 610,710 |
def med_caseinsensitive_equal(a, b):
"""Takes in two strings and returns True if they are case insensitive equal."""
return a.lower() == b.lower() | 0716d13646af5676db92287780fa955b5dcd28d2 | 610,711 |
def filter_terraces(terrace_df,min_size=5000, max_size=1000000):
"""
This function takes the initial terrace dataframe and sorts it to remove terraces
that are too small.
Args:
terrace_df: pandas dataframe with the terrace info
min_size (int): minimum n of pixels in each terrace
... | 532c2e3e7276a24edd0c9ffb98f0fcfe8450d003 | 610,713 |
def write_file_top_words(model, feature_names, n_top_words, fileName):
""" Writes the specified top topics and top words to the specified fileName"""
outputFile = open("raw_"+fileName, 'w')
outputFileTopics = open(fileName, 'w')
outputFile.write("File: "+"raw_"+fileName+"\n\n")
outputFileTopics.writ... | ef8b56622ede18a94edc1c9a44fa1a091e344375 | 610,714 |
def get_overlapped_chunks(ring, size):
"""
returns a list of chunks of size 'size' which overlap with one field.
If the last chunk is smaller than size, the last 'size' chunks are returned as last chunk.
"size" has to be larger than 3 to get reasonable results.
>>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0,... | dc78426f9b0d59468506faf72f09352d0d15b728 | 610,716 |
def list_to_ranges(list_of_ints, range_sep=',', slice_sep=':'):
"""
Get a ranges-str for input list
Parameters
----------
list_of_ints : list[int]
A list of integers to codify as a ranges-str
range_sep : str default ','
A range seperator string
slice_sep : str default ':'
... | 10011307067c9bf2920e66a31ddd0a0df5de73f2 | 610,717 |
import random
def __positive_pair(data_dict: dict, person: str):
"""
Function to make a positive pair for the person
given
Arguments:
data_dict {dict} -- The data dictionary of the entire dataset
person {str} -- The person to query and make a positive pair
Returns:
... | e2416b927edbaab9eb4e87f7745224899fdcf638 | 610,720 |
def PyLong_FromSize_t(space, val):
"""Return a new PyLongObject object from a C size_t, or NULL on
failure.
"""
return space.newlong_from_rarith_int(val) | 7011b8c769bb390196b6b14340b6562291251f4d | 610,723 |
def is_metric(ctx):
"""
Returns if the current context is in metric.
:arg ctx: Current Click context
:return: true if it is in metric, false otherwise
"""
return ctx.obj["unit"] == "metric" | 8fef0acfae031442239f6b3c6564d2a668302f98 | 610,727 |
def author(record):
"""
Split author field by 'and' into a list of names.
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
if "author" in record:
if record["author"]:
record["author"] = [i.strip() for i in record["author"].replace... | 3362df3d941e506ffab81a8a4e6a912fef39e5d8 | 610,728 |
import re
def hump2underline(source_str: str):
"""
驼峰形式字符串转成下划线形式
mediaType -> media_type
:param source_str: 驼峰形式字符串
:return: 字母全小写的下划线形式字符串
"""
# 匹配正则,匹配小写字母和大写字母的分界位置
p = re.compile(r'([a-z]|\d)([A-Z])')
# 这里第二个参数使用了正则分组的后向引用
sub = re.sub(p, r'\1_\2', source_str).lower()
... | ec19bce9aebbd4fd61758b41d6ae6189236b36f7 | 610,730 |
from typing import List
def tokenize_sentence(sentence: str) -> List[str]:
"""
Split sentence into tokens by spaces.
:param sentence: Sentence string.
:return: List of tokens.
"""
tokens = sentence.split()
return ["###LEFT-WALL###"] + tokens if tokens[0] != r"###LEF... | 52dbcf3fc455c25b2b6ab63e69dec350f5f84b8e | 610,731 |
from typing import List
def list_contains_round(rounds: List[int], number: int) -> bool:
"""
:param rounds: list - rounds played.
:param number: int - round number.
:return: bool - was the round played?
"""
return number in rounds | c2a4663206a3f9ac7613bad49e7576631e58d9e6 | 610,732 |
def valid_period(request):
"""
Fixture that yields valid timeout periods in seconds.
"""
return request.param | d893ebdf4ea66397ac19339ed8516bb2930265dd | 610,733 |
def _make_header(text: str, level: int) -> str:
"""Create a markdown header at a given level"""
return f"{'#' * (level + 1)} {text}" | bcb7ff6c357038a51109e9658fcb43add9dba697 | 610,735 |
def get_plugin(manager, name):
"""Find a plugin by name."""
for plugin in manager.getAllPlugins():
if plugin.name == name:
return plugin.plugin_object
return None | bcfe44ed25309adf4ddc924c485283fc8947078c | 610,737 |
def scope_vars(var_list, scope):
"""
Args:
var_list: list of `tf.Variable`s. Contains all variables that should be searched
scope: str. Scope of the variables that should be selected
"""
return [v for v in var_list if scope in v.name] | 949193b4f07f762b769404c03e46c367321b49c2 | 610,738 |
def check_bidi_comp(cond0, cond1, arg0, arg1):
"""
Check whether conditions are True for two arguments regardless of order.
Parameters
----------
cond0, cond1 : callable
Function of one variable that evaluate to a bool.
arg0, arg1 : object
Arguments to pass to `cond0` and `cond1... | 27086054fe32a14456ee0178068a6cf4919d7258 | 610,742 |
def document_sorter(document):
"""A sorting key function that sorts documents by length (descending)
and filename (ascending)
"""
return -document.size, document.filename | ae78730563415248c643f76522dba8fd814b1485 | 610,744 |
from typing import Sequence
import random
def random_english_resource_type_combo(
english_resource_type_combos: Sequence[Sequence[str]],
) -> Sequence[str]:
"""
A random choice of one set of all possible English resource type
combination sets, e.g., ulb-wa, tn-wa, tw-wa; or, ulb-wa, tn-wa,
tw-wa; ... | be91b3fdf1419d0d629f6e58bbbbf32386c14b27 | 610,746 |
def _dmp_acc(Y, V, cdd, alpha_y, beta_y, goal_y, goal_yd, goal_ydd,
execution_time, f, coupling_term, tdd):
"""DMP acceleration.
Parameters
----------
Y : array, shape (n_dims,)
Current state (position).
V : array, shape (n_dims,)
Current state derivative (velocity).
... | a7690b71ae1096479463ed2d08fc196a3c0219d5 | 610,747 |
def collate_metrics(keys):
"""Collect metrics from the first row of the table.
Args:
keys (List): Elements in the first row of the table.
Returns:
dict: A dict of metrics.
"""
used_metrics = dict()
for idx, key in enumerate(keys):
if key in ['Method', 'Download']:
... | 94366737180d8648c0bd11b06ebedaae790a2ed9 | 610,749 |
from typing import OrderedDict
def get_partial_state_dict(model_state_dict, modules,
init_from_decoder_asr=False,
init_from_decoder_mt=False):
"""Create state_dict with specified modules matching input model modules.
Note that get_partial_lm_state_dict... | 4d83f22124dca13852451e4016f5a52a727fa031 | 610,750 |
def line_points_to_grid(l_points: list) -> list:
"""
Args:
l_points: all points occupied by lines in [x1, y1] format
Returns:
grid where [x, y] value contains the number of lines that occupy that coordinate
"""
# determine size of grid
largest_x = max([i[0] for i in l_points])
... | 608897dabc05a96bed5ea0a5d070441eeb66efe9 | 610,751 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.