content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import mimetypes
def bundle_media_description(key, filename):
"""Bundle the media description necessary for uploading.
:param key: form-data key name
:param filename: Local file name or path.
:return: tuple of ('key name', ('file name', 'file object', 'MIME content-type')
:rtype: tuple
"""
... | 8c160a9c767d86a1c1867d22f018d6342239e68d | 701,537 |
from typing import List
def list_to_str(x: List[float]) -> str:
""" Produces a string of formatted floating point numbers.
Args:
x: List of floating point numbers
Returns:
s: The formatted string.
"""
strs = ''
for x_i in x:
strs += '{:.2e}, '.format(x_i)
ret... | bd578f8be50dbeae43df1be5d21d3f4b56d56f63 | 321,773 |
def _keep_only_summer(df, summer_months):
"""
Keep only the summer period.
Parameters
----------
df : DataFrame
It should have a DateTime Index.
summer_months : tuple(int, int)
Returns
-------
DataFrame
"""
return df.loc[df.index.month.isin(summer_months)].copy() | c61243fde9ed46f3c18cbea23ade8fe2da78aa25 | 186,321 |
def findBiggestRecord(vendorRDD):
""" Find and return the record with the largest number of tokens
Args:
vendorRDD (RDD of (recordId, tokens)): input Pair Tuple of record ID and tokens
Returns:
list: a list of 1 Pair Tuple of record ID and tokens
"""
return vendorRDD.takeOrdered(1, l... | 8de5ca9814924f48de1c7f5b265f74da4882eeaf | 538,823 |
import torch
def make_weights(diag_val, offdiag_val, n_units):
"""Get a connection weight matrix with "diag-offdial structure"
e.g.
| x, y, y |
| y, x, y |
| y, y, x |
where x = diag_val, and y = offdiag_val
Parameters
----------
diag_val : float
the value of... | 290627086012f025e84541befba7c2c6c49e2cc0 | 536,912 |
def fisbHexErrsToStr(hexErrs):
"""
Given an list containing error entries for each FIS-B block, return a
string representing the errors. This will appear as a comment in either
the result string, or the failed error message.
Args:
hexErrs (list): List of 6 items, one for each FIS-B block. Each entry
... | 7f81dc250b6e780f384720d98bb53574b1da86f9 | 646,553 |
def get_sheets_name(calcObject):
"""Get sheets names in a tuple."""
return calcObject.Sheets.ElementNames | 23500fbb712d7fbed78b7e4870becac7167500be | 277,937 |
def hass_to_hue_brightness(value):
"""Convert hass brightness 0..255 to hue 1..254 scale."""
return max(1, round((value / 255) * 254)) | fcadea06d13968069983091bc2660810b948e13e | 505,342 |
def splitmessage(message):
"""Returns a tuple containing the command and arguments from a message.
Returns None if there is no firstword found
"""
assert isinstance(message, str)
words = message.split()
if words:
return (words[0], words[1:]) | d8db56ef55097f9f8858de95ee3d7799c0dc127e | 700,315 |
def get_enabled_bodies(env):
"""
Returns a C{set} with the names of the bodies enabled in the given environment
@type env: orpy.Environment
@param env: The OpenRAVE environment
@rtype: set
@return: The names of the enabled bodies
"""
enabled_bodies = []
with env:
for body in env.GetBodies():
... | ea5a86538edefaacf5b47ea22b9abc3ee87bba81 | 81,774 |
def _isCharEnclosed(charIndex, string):
""" Return true if the character at charIndex is enclosed in double quotes (a string) """
numQuotes = 0 # if the number of quotes past this character is odd, than this character lies inside a string
for i in range(charIndex, len(string)):
if string[i] == '"':... | 70d70617fa869cc7b28abd3a7def28ea77b6a896 | 680,624 |
def is_upvoted(submission):
"""
If a comment is upvoted, we assume the question is welcomed, and that
there's no need for a template answer.
"""
min_score = 3
min_comment_count = 1
return (
submission.score > min_score and
len(submission.comments) > min_comment_count
) | 90fe43e6cd681a15daa97dba039e7fa94ac617ca | 24,572 |
def format_elapsed_seconds(elapsed_seconds):
"""
Helper function to convert number of seconds to a string of hours, minutes, and seconds
:param elapsed_seconds: float or int of the number of elapse seconds to format into a string
:return: formatted time string
"""
hours = int(elapsed_seconds / ... | c865645920f1c32f22022b156b9ed709ad38a717 | 531,435 |
import re
def is_project_issue(text):
"""
Issues/pull requests from Apache projects in Jira.
See: https://issues.apache.org/jira/secure/BrowseProjects.jspa#all
>>> is_project_issue('thrift-3615')
True
>>> is_project_issue('sling-5511')
True
>>> is_project_issue('sling')
False
... | f96f63488c97311cdc79f3fa2dd526023e300969 | 683,893 |
def _validate_inputs_outputs_var_format(value: str) -> str:
"""Validate inputs/outputs variables
Arguments:
value {str} -- A '.' seperated string to be checked for inputs/outputs variable
formatting
Returns:
str -- A string with validation error messages
"""
add_info = ... | e6d6cb0cf77a4b75ae5c6915f28d7f3ed16142b8 | 265,886 |
def _slice(tensor, dim, start, end):
"""Slices the tensor along given dimension."""
# Performs a slice along the dimension dim. E.g. for tensor t of rank 3,
# _slice(t, 1, 3, 5) is same as t[:, 3:5].
# For a slice unbounded to the right, set end=0: _slice(t, 1, -3, 0) is same
# as t[:, -3:].
rank = tensor.s... | c2897621afb2adefe8da78e56763cc3f0822f9bc | 399,546 |
from typing import Callable
from typing import Union
def trapezoidal_area(
fnc: Callable[[Union[int, float]], Union[int, float]],
x_start: Union[int, float],
x_end: Union[int, float],
steps: int = 100,
) -> float:
"""
Treats curve as a collection of linear lines and sums the area of the
t... | 3ac16c64b77180aff453c71f8495d9a7dc4dd599 | 270,838 |
def coco_annfile(dir, subset, year=2014):
"""Construct coco annotation file."""
annfile = '{}/annotations/instances_{}{}.json'.format(dir, subset, year)
print(annfile)
return annfile | e63bdfc40318190cc22b095455dee4a57f7f5325 | 121,099 |
def get_list_registry(from_space, capacity=None, initializer=0, flatten=True, add_batch_rank=False):
"""
Creates a list storage for a space by providing an ordered dict mapping space names
to empty lists.
Args:
from_space: Space to create registry from.
capacity (Optional[int]): Optiona... | 080277fac9493d9588d084ad0cfe25e711cfb61b | 416,476 |
import re
def clean(str, include='', alpha='a-zA-Z', numeric='0-9'):
"""Filter unwanted characters. Returns the filtered string.
Examples:
>>> clean('1.20€')
'120'
>>> clean('1.20€', '.')
'1.20'
>>> clean('1.20€', '.€')
'1.20€'
... | 31e5652d0dd863017daa4dbcb7de06efeffd9f60 | 405,758 |
def to_bool(val):
"""Convert a value to a bool."""
if isinstance(val, bool):
return val
if isinstance(val, str):
return val.lower() not in ("", "0", "false")
return bool(val) | 8050ebdc58a9774f1b023b2ee1a5f76897cb6f13 | 518,332 |
def format_seconds(s):
"""
Format a seconds value into a human-readable form
"""
years, s = divmod(s, 31556952)
min, s = divmod(s, 60)
h, min = divmod(min, 60)
d, h = divmod(h, 24)
return '%sy, %sd, %sh, %sm, %ss' % (years, d, h, min, s) | f004d9f2cef8b3b9eee967ebd9d4811cbc80ae6c | 27,113 |
import re
def parse_map_file(path):
"""
Parse libgccjit.map, returning the symbols in the API as a list of str.
"""
syms = []
with open(path) as f:
for line in f:
m = re.match('^\s+([a-z_]+);$', line)
if m:
syms.append(m.group(1))
return syms | b0f78cf1a7ebe45ae845fbacef3b7712a9d53fdc | 695,155 |
def return_tag_action(row, action_dict):
"""
Default action function for tables. This function returns the tag for the row of data. Used by the **TABLE_RETURN_TAG** action.
:param List row: the data associated with the selected row
:param Dict action_dict: the dictionary of values associated with the a... | 0dea8c52e45041f7741717453887b75009c10367 | 296,136 |
def get_charge(lines):
""" Searches through file and finds the charge of the molecule. """
for line in lines:
if 'ICHRGE' in line:
return line.split()[2]
return None | 913ec1403cdf1dba5ad4b549b61cec23d3546dc7 | 654,993 |
def make_array(dims):
""" Creates an array (dictionary with tuple coordinates as keys) of
the given dimensions (the 3 dims together indicate how many values are
to be inserted into outarr) initialized with None (value=None).
For example, if dims given = (1 2 1),
returned arr = {(0,0,0): None, (0,1,0... | aa3b0a482ad804a77a1d263b32b9f47d600f5e0f | 504,851 |
def duplicates(list, item):
"""Returns index locations of item in list"""
return [i for i, x in enumerate(list) if x == item] | b6aa59d4bc7cc869544b18a5322c05cdaa1f4d49 | 157,520 |
def populate_frames(num_frames, animation_data):
"""
Takes a dictionary of frame_id: data pairs and produces a list of length num_frames with data inserted at indices
specified by frame_id, and None everywhere else.
"""
frame_data = {}
for bone_id, keyframes in animation_data.items():
fr... | cc5e20cc04d6e5b2798497ee9d3053be62ec9d7e | 487,910 |
def IsInstalled(vm):
"""Checks whether docker is installed on the VM."""
resp, _ = vm.RemoteCommand('command -v docker',
ignore_failure=True,
suppress_warning=True)
return bool(resp.rstrip()) | 7d020d23b6e4ec242169e8ef0602f7ff601cef34 | 487,531 |
def van_der_corput(n_sample, base=2, start_index=0):
"""Van der Corput sequence.
Pseudo-random number generator based on a b-adic expansion.
Parameters
----------
n_sample : int
Number of element of the sequence.
base : int
Base of the sequence.
start_index : int
In... | fd29d56dea836df616fc42b894a25961ab42ebb1 | 230,921 |
def downright(i,j,table):
"""Return the product to down-right-diagonal"""
product = 1
for num in range(4):
if i+num>19 or j+num>9: product*=1
else: product *= int(table[i+num][j+num])
return product | efa618d32892b3fb68217fd41907f5d874172ecf | 59,833 |
import random
def create_networkcopy_with_missing_nodes(graph, list_missing_percentages):
"""
Function to generate copies of a graph with varying proportion p of missing nodes given by a list P.
The function returns a list of graphs, where each graph is a network copy with p% of the nodes missing.
... | 4830bcf73e5b8bbc6fec2b59d093435f86c3884b | 484,390 |
def cut_lines_to_n(string, n = 200):
"""
Takes a string and breaks it into lines with <= n characters per line.
Useful because psql queries have to have < 212 chars per line.
"""
out = []
lines = string.split("\n")
for line in lines:
newline = ""
words = line.split(" ")
... | 2ecad131d994838fae0cc8db5381541736e4dbd3 | 212,381 |
import re
def wktfmt(wkt: str) -> str:
"""
Round numbers in WKT str to 4 decimal places of accuracy.
"""
return re.sub(r"([+-]*\d*\.\d\d\d\d)(\d*)", r"\1", wkt) | 3e4fe65a5dd8f972fbb5bc8f13c0a0475f65fa85 | 260,282 |
def limit_results(numResults, results):
"""
Limits results to numResults
"""
if numResults < results.count():
return list(results[0:numResults])
else:
return list(results) | 11773e17aa9e4eefdf675f1b20f7310bdb09e76d | 226,363 |
def mean_pool(data):
"""Simple mean pool function for transforming 3D features of shape
[T]imesteps x [B]atch_size x [F]eature_size into 2D BxF features.
(author: @klmulligan)
Arguments:
data (tuple): Encoder result of form (data: Tensor(TxBxF), mask: Tensor(TxB))
Returns:
... | 8eb0904d549be7345fecdeace2c7c4169bcc78c2 | 178,213 |
def create_compile_command(file_name):
"""
Creates the bash command for compiling a JUnit test.
Params:
file_name (str): The file name of the test to compile.
Return:
str: The bash command for compiling.
"""
return f"javac -d classes -cp classes/:junit-jupiter-api-5.7.0.jar:apiguardian... | eda1d873d5a35e6f294070a294cc428d083ec200 | 330,212 |
import time
def thread_worker_example(item):
"""Example worker function for ThreadPoolExecutor."""
print(item)
time.sleep(1)
return item | acc23102bfe05199f3b073cc28006389b1d6343d | 284,570 |
def readSEEDTree(treeFile):
"""
Return nested dictionary where first dict is map from levels (1,2,3)
and next dict is map from role to name.
This is a simply formatted file with 4 columns:
"role\tsubsystem\tlevel 2\t level 1"
"""
seedTree = {'1': {}, '2': {}, '3': {}}
with open(treeFile... | 5ae053078d990d4b9eb92bd5a5fc35d64f771b9f | 460,468 |
import re
from typing import Tuple
async def match_splitter(match: re.Match) -> Tuple[str, str, str, str]:
"""Splits an :obj:`re.Match` to get the required attributes for substitution.
Unescapes the slashes as well because this is Python.
Args:
match (:obj:`Match<re.match>`):
Match ob... | c5e72c9b34364f8e5dbd34c8e3129b442b6e6514 | 358,227 |
from typing import Counter
def countKmers(seq):
"""Returns frequencies of kmers"""
counts = Counter(seq)
return counts | 5569c8c8a7b2104734964889a46dc4b30ba7501c | 176,495 |
import re
def WinEventSearch(regexp, event_string, remove=True):
"""Searches inside an event string for a matching regular expression.
Note: it assumes the regexp has one group search.
Args:
regexp: the regular expression string to be used.
event_string: the search target string.
... | 51a154b544be50a0f83722e7453e0e386870b9b6 | 270,586 |
def eq(max_x, x):
"""Returns equally separated decreasing float values from 1 to 0 depending on the maximu value of x
Parameters
----------
max_x : int
maximum x value (maximum number of steps)
x : int
current x value (step)
Returns
-------
float
y value
Ex... | c0076295dadf280db472f32d664eeca3a49a1780 | 99,024 |
import logging
def read_n_bytes(s, n):
"""Reads n bytes from socket s. Returns the bytearray of the data read."""
bytes_read = 0
_buffer = []
while bytes_read < n:
data = s.recv(n - bytes_read)
if data == b'':
break
bytes_read += len(data)
_buffer.append(d... | c0957afbd7595eb2e841fe0690e1f5b67d9a7945 | 395,151 |
import torch
def hot_to_indices(hot):
"""Convert an element of one-hot encoding to indices
"""
hot = torch.tensor(hot)
_,max_index=hot.max(1)
return max_index.data.cpu().numpy().tolist() | 71a911d1ecb809c439bf42e8e8503e968f3d5cf8 | 575,605 |
import base64
def base64_string_decode(data):
"""
Decodes a base64 encoded string into a string
:param data: str: string to decode
:return: str
"""
return base64.b64decode(data).decode('utf-8') | 03194e11c13e740064bc42142442df59dc1d4bc7 | 197,498 |
def pot_for_column(cls, column, summary=False):
"""Translatable texts get categorized into different POT files to help
translators prioritize. The pots are:
- flavor: Flavor texts: here, strings from multiple versions are summarized
- ripped: Strings ripped from the games; translators for "official"... | 4c6ee265b4330a1b020a3a2902d4ffa7a3932392 | 270,399 |
def make_adder(n):
"""Return a function that takes an argument K and returns N + K.
>>> add_three = make_adder(3)
>>> add_three(1) + add_three(2)
9
>>> make_adder(1)(2)
3
"""
return lambda x: x + n | e14170199d4503ebe5f91eca6c8fe3bc19637089 | 506,435 |
def auto_cmap(labels):
"""
Find an appropriate color map based on provide labels.
"""
assert len(labels) <= 20, "Too many labels to support"
cmap = "Category10_10" if len(labels) <= 10 else "Category20_20"
return cmap | 99bdf74197b17d5908237e6a45b0882330c96024 | 39,639 |
def parse_str_to_types(string):
""" Converts string to different object types they represent.
Supported formats: True,Flase,None,int,float,list,tuple"""
if string == 'True':
return True
elif string == 'False':
return False
elif string == 'None':
return None
elif string.ls... | 7b9287d6febf15d1111ddd7f2a217978c646ac3f | 261,114 |
def mk_str(mk):
"""Replace class path for backwards compatibility of matches keys."""
return str(mk).replace('indra.statements.statements', 'indra.statements') | c6bf41071e3533489c763a178331a913c115e1e8 | 426,881 |
def calc_an_sparsity(L, q, K):
"""Calculates sparsity of Adjacent Neighborhood scheme"""
return 1 + L*(q-1)*q**(K-1) | 0fc6f63a1f417c46a26721fcf82e9dc0c827cc6c | 646,391 |
def spline_grid_from_range(spline_size, spline_range, round_to=1e-6):
"""
Compute spline grid spacing from desired one-sided range
and the number of activation coefficients.
Args:
spline_size (odd int):
number of spline coefficients
spline_range (float):
one-side... | 0e5a100e644786a33ba92172d2b0ccaf6ef4971c | 592,789 |
from typing import Dict
from typing import Any
def strip_empty_params(params: Dict[str, Any]) -> Dict[str, Any]:
"""Remove any request parameters with empty or ``None`` values."""
return {k: v for k, v in params.items() if v or v is False} | aa8e320b93524ef13d25d522464ab22b48226e79 | 83,623 |
import torch
def torch_equals_ignore_index(tensor, tensor_other, ignore_index=None):
"""
Compute ``torch.equal`` with the optional mask parameter.
Args:
ignore_index (int, optional): Specifies a ``tensor`` index that is ignored.
Returns:
(bool) Returns ``True`` if target and predicti... | 1da45ac80a373c55b453fcc6327af0b5287640b2 | 127,844 |
def decode_line(s,l,func = float):
"""
split a string and convert each token with <func>
and append the result to list <l>
"""
x = s.split()
for v in x:
l.append(func(v))
return(l) | d4b602b4c44d60916c56a1ca1c04b102e4b186fb | 239,039 |
from typing import List
def simulate_day(school: List[int]) -> List[int]:
"""Simulates a school of fish for one day and returns the school."""
return [*school[1:7], school[0] + school[7], school[8], school[0]] | 126f430920474d54651bf7a19a18006f66792ff1 | 643,171 |
from typing import Callable
def finite_difference_derivative(func: Callable, x: float, h: float=1e-6) -> float:
"""Estimate the derivative of a function at a given value using the finite difference method.
Parameters
----------
func : Callable
The function for which the derivative will be est... | cf9674140be80342f63624297fcc1d3d4b9412e6 | 417,823 |
from typing import Dict
from typing import Any
from typing import Optional
def b(field: str, kwargs: Dict[str, Any],
present: Optional[Any] = None, missing: Any = '') -> str:
"""
Return `present` value (default to `field`) if `field` in `kwargs` and
Truthy, otherwise return `missing` value
"""
... | 1733631d6a8bc7790f7ec4cb63a4648ee34a4dd4 | 431,383 |
def hex2rgb(hex_: str) -> tuple:
"""
hex2rgb from
https://stackoverflow.com/a/29643643/8608146
"""
hex_ = hex_.lstrip('#')
return tuple(int(hex_[i:i + 2], 16) for i in (0, 2, 4)) | 47e7591c5ec2f21de7edfb39aa91fbc9a6b94bec | 199,159 |
def dotted_name(cls):
"""Dotted name for a class.
Example: ``my.module.MyClass``.
:param cls: the class to generate a dotted name for.
:return: a dotted name to the class.
"""
return f"{cls.__module__}.{cls.__name__}" | 2d37d2b8e3f42946923ddd1f621b2aeaa289c266 | 557,721 |
def parallel_mean(mean_a, count_a, mean_b, count_b):
"""Compute the mean based on stats from two partitions of the data.
See "Parallel Algorithm" in
https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
Args:
mean_a: the mean of partition a
count_a: the number of elements i... | 7f09e422431cb34b3cbdf72baf1ba4a69ecdd050 | 507,327 |
import pickle
def load_object(filename):
"""
Load a python object stored in a file using pickle
:param filename: File from which to load the object
:return:
"""
with open(filename, 'rb') as input_file: # Overwrites any existing file.
obj = pickle.load(input_file)
return obj | e9b8c147ede279d7aa61f0d584b5dfa82728c8de | 206,511 |
def fft_suitable(N: int) -> bool:
"""Check whether `N` has only small prime factors. Return True if
the prime factorization of `N` is suitable for efficient FFTs,
that is contains only 2, 3, 5 and 7."""
for p in [2, 3, 5, 7]:
while N % p == 0:
N //= p
# All suitable prime factors... | aa6d1fd3b51a3fafb9e05f0203d0649e4a2080e8 | 189,376 |
import random
def SplitGaps(zs):
"""Splits zs into xs and ys.
zs: sequence of gaps
Returns: tuple of sequences (xs, ys)
"""
xs = [random.uniform(0, z) for z in zs]
ys = [z-x for z, x in zip(zs, xs)]
return xs, ys | 087e95faa10c8b519aed6c018a215fa5620d8382 | 114,764 |
def millis_offset_between_epochs(reference_epoch, target_epoch):
"""
Calculates the signed milliseconds delta between the reference unix epoch and the provided target unix epoch
:param reference_epoch: the unix epoch that the millis offset has to be calculated with respect to
:type reference_epoch: int
... | 3cb20d46ccf860dc21a2327d8520711c1720ef83 | 145,496 |
import re
def count_words_in_markdown(markdown: str) -> int:
"""
Count the words in a block of Markdown text.
Strips off the markup before doing the word count.
From https://github.com/gandreadis/markdown-word-count/blob/master/mwc.py
and simplified just a bit.
"""
text = markdown
t... | f15d84c93975607b7c9ceb66946b688901ec6f6b | 297,947 |
def parse_ref(fxy) -> tuple:
"""Returns a tuple of the FXXYYYY string parsed out into integers."""
f = int(fxy[0])
x = int(fxy[1:3])
y = int(fxy[3:6])
return f, x, y | 2b191e8205cf7943dd6c962a7f172457f78208d5 | 164,195 |
def get_item_number(soup):
"""
Returns the product's unique item_number
"""
item_number = soup.find('div', attrs={'id': 'descItemNumber'})
if not item_number:
return "N/A"
item_number = item_number.get_text()
return item_number | 5460610ea099c61574ee1988695e116c5b4a3b51 | 483,489 |
def has_resource(cobj, resource_label):
"""
Check to see if a CachedImageObject has a specified resource
:param cobj: CachedImageObject object from XnatUtils
:param resource_label: label of the resource to check
:return: True if cobj has the resource and there is at least one file,
Fals... | 016a26e6660208bb92daebafb8c1e54f74dc5fc5 | 463,605 |
def check(move, occupied, width, height, n=1):
"""
_Purpose:
takes a move coord and returns a score based on how many free spaces are around the move of distance n
_Parameters:
move (tuple): xy coord of the move
occupied (list): xy coords all occupied spaces on board
width (int): width of board
height (int): ... | 1d2034e28a940fae4d67495d30f83046f363c8f5 | 579,838 |
from typing import List
from pathlib import Path
def remove_external_imports(imports: List[str], root: str) -> List[str]:
"""
removes imports from external libraries.
this is achieved by checking if the given import name contains the stem of the root directory
(main directory of repo to analyze).
... | 683ce8591966daa15bf838bc33c9b64c11c0276c | 506,843 |
def find_change(plan, category, unit):
"""
finds the change in the given category and unit in the given plan
:return: Change object
"""
for change in plan.area_changes:
if change.category == category and change.unit == unit:
return change
return None | b1adbbb34e2f1f41578d47e16eebd51c4980b14b | 577,294 |
def msvcrt_rand(s=0, size=1):
"""
Emulate interplay of srand() and rand()
:param int s: The seed.
:param int size: Desired length of returned data.
:return: A sequence of bytes computed using the supplied arguments.
:rtype: bytearray
"""
result = bytearray()
for i in range(0, size... | 0de2527a86aefd6dfb5a40e07e294844cf2d111f | 622,175 |
def CalculateRollingMax(raw_scores, total_samples, window_samples):
"""Calculates a rolling maximum across the array, in windows of the same size.
The scores returned from open-cv matchTemplate are calculated as if each
value in the array matches with the first position in the window. Here,
for each position i... | e5fc81a57d6b51c983c798a51d552af76e30a8fb | 61,613 |
from typing import List
from typing import Any
def flatten(deep_list: List[Any]) -> List[Any]:
"""
Recursively flatten the list into 1D list containing all nested elements
"""
if len(deep_list) == 0:
return deep_list
if isinstance(deep_list[0], list):
return flatten(deep_list[0]) +... | bdcfd66f360468cf9a683e7078aa28be0e5a39ca | 210,538 |
def license(_):
"""Return the contents of the LICENSE.txt file."""
with open('LICENSE.txt') as flicense:
return flicense.read() | 50e9572537dee41a36b0859cee5596f136d14fbb | 625,191 |
def _find_valid_path(options):
"""Find valid path from *options*, which is a list of 2-tuple of
(name, path). Return first pair where *path* is not None.
If no valid path is found, return ('<unknown>', None)
"""
for by, data in options:
if data is not None:
return by, data
e... | 2f156fd1d592fb3a44c5280a53180b4066fe7d18 | 68,875 |
def getRankAttribute(attribute, reverse = False):
""" Takes as input an attribute (node or edge) and returns an attribute where
each node is assigned its rank among all others according to the attribute values.
The node/edge with lowest input value is assigned 0, the one with second-lowest
value 1, and so on.
Key... | b11f79dea4cb0497a9505571f299b1e73bc47429 | 258,600 |
def obj(request):
"""Default values for the statdyn analysis command line."""
return {
"keyframe_interval": 1_000_000,
"keyframe_max": 500,
"wave_number": request.param,
} | 10c05bd99c0aa687bf6c279b2ed31c94dfc49542 | 260,015 |
from typing import Union
from typing import Tuple
from typing import List
def increase_version_number(version_buffer: Union[Tuple[int, int, int], List[int]], semantic_version: str = "patch") \
-> List[int]:
"""
Increases the number of the version based on the 'release_type' value in the release_type.y... | 98171df679ad907145b82f393f19f739cd6f0782 | 359,710 |
def stringify(item):
"""
Returns a quoted string item if passed argument
is a string, else returns a string representation
of that argument.
If passed argument is None, returns None.
Parameters
----------
item : Any type
Item to be parsed.
Returns
-------
str or No... | 6ab8bd9cca99b50c8de84b790aa0a7a3b70a9ecc | 140,466 |
def _create_weather_key(lat, lng):
"""
Creates a properly formatted key for storing in a JSON database.
Args:
lat (string or float) -- latitude component of coordinate
lng (string or float) -- longitude component of coordinate
Returns:
string -- key value
"""
tmp = "%s,%s" % (lat, ... | 0e75358d4319d3e1919bda0a46d82a84bcf6a3da | 374,996 |
from typing import Callable
def get_values_by_keys(k: list, default=None)->Callable[[dict], list]:
"""
Filter dictionary by list of keys.
Parameters
----------
k: list
default: any, optional
Set as default value for key not in dict.
Default value is None
"""
return lam... | 2306493ef30753cac90d16529a4f128c45877fba | 650,643 |
def _ensure_width(inp: str, width: int):
"""
Ensure that string `inp` is exactly `width` characters long.
"""
return inp[:width].ljust(width) | ed8ef2e184d2ea00027ed2648adc33927580e694 | 606,920 |
import re
def read_csv(filename):
"""Reads data from a space or comma delimited file.
:param filename: path of the file
:type filename: str
:return: data from file
:rtype: List[List[str]]
"""
data = []
regex = re.compile(r'(\s+|(\s*,\s*))')
with open(filename, encoding='utf-8-sig'... | 9835e3887e8e3599e94ebe5e633a329fcec03d35 | 114,986 |
import math
import torch
def cp_init(weights, factors, std=0.02):
"""Initializes directly the weights and factors of a CP decomposition so the reconstruction has the specified std and 0 mean
Parameters
----------
weights : 1D tensor
factors : list of 2D factors of size (dim_i, rank)
std : flo... | 387608d192911a8d89d95f7bf53b79cf5b2a0773 | 348,732 |
def cmmdc(x, y):
"""Computes CMMDC for two numbers."""
if y == 0:
return x
return cmmdc(y, x % y) | f1d731ca0e1942e33b4fdf2d792e16c8ccddd13c | 58,891 |
import pwd
def get_uid(name):
"""Returns an uid, given a user name."""
try:
result = pwd.getpwnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None | cdbbe8ee3cd49a1f19762aad981cafb07a088bf1 | 436,954 |
def min_delta(delta):
"""
Minimum delta criteria
Parameters
----------
delta : float
The minimum height of a leaf above its merger level
"""
def result(structure, index=None, value=None):
if value is None:
if structure.parent is not None:
return ... | 05bd53883234e1a7df5120b80c670c928697000b | 194,882 |
def _joinregexes(regexps):
"""gather multiple regular expressions into a single one"""
return b'|'.join(regexps) | de3b51de059659b6870e2fadfcdf8e4787bc2e20 | 307,460 |
from typing import List
import traceback
def catch_errors_as_message(function):
"""Catches errors as a list of messages
Parameters
----------
function : Coroutine[Any, Any, List[str]]
Function to wrap. In case of an error
the message is returned.
"""
async def wrapper(*args, ... | d187e2a060d0a62697c91149640d6480bd5a89a9 | 174,867 |
def Sub(a1, a2, ctx=None):
"""Subtract two numbers"""
return a1 - a2 | e563c81eb0f8b01f5f93b49b259954df6efd486f | 582,540 |
def _cut_if_too_long(text: str, max_length: int) -> str:
"""Cut a string down to the maximum length.
Args:
text: Text to check.
max_length: The maximum length of the resulting string.
Returns:
Cut string with ... added at the end if it was too long.
"""
if len(text) <= max_... | 72745efb8a4fd7d6b2af7356d00e1e5bc554ff62 | 679,860 |
import operator
def genderdecode(genderTag):
"""
one-hot decoding for the gender tag predicted by the classfier
Dimension = 2.
"""
index, value = max(enumerate(genderTag), key=operator.itemgetter(1))
if index == 0:
return 'm'
if index == 1:
return 'f'
if index == 2:
... | ba1ed2ea3e8504d601692ff764d871d4508b1a36 | 292,923 |
import math
def _radians_to_angle(rad):
"""
Convert radians into angle
:param rad:
:return: angle
"""
return rad * 180 / math.pi | f88aa0a2da9f0dd31a0576afcd1ffd80ba9eafc8 | 63,320 |
import gzip
def load_twitter_dict(path):
"""
Loading archived cPickled dict
Note: this function here is for the reference
Args:
path - str: path to cPickle
Returns:
tweet_list - list: list of json files
"""
with gzip.open(path, 'rb') as f:
tweet_list = f.... | 7e2ffa9de54af8aa370f2f0e8b86b66689214a1c | 561,111 |
import base64
def _b64(text):
"""Encodes text as base64 as specified in ACME RFC."""
return base64.urlsafe_b64encode(text).decode("utf8").rstrip("=") | 6385bdb0d3129157409f4e0a9717778728d7f63f | 236,086 |
from datetime import datetime
def get_datetime(date, time, *, microseconds=True):
"""
Combine date and time from dicom to isoformat.
Parameters
----------
date : str
Date in YYYYMMDD format.
time : str
Time in either HHMMSS.ffffff format or HHMMSS format.
microseconds: boo... | 641f91292da33de6d516bfa06749c98bee1dc028 | 645,437 |
import json
def load_dictionary_from_file(file_path):
"""Load a dictionary from a JSON file.
Parameters
----------
file_path : string
The JSON file path to load the dictionary from.
Returns
-------
dictionary : dict
The dictionary loaded from a JSON file.
"""
wit... | f273b13e43f0df1b3cab4c0f8097bec401b83c23 | 602,074 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.