content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def convert_map(old_map, convert_dict, out_loc):
"""
To convert specific populations names in a sample map to another.
Use cases: while clubbing populations, renaming them, etc...
eg: convert STU, ITU, etc... to SAS.
convert_dict for the above would be {"STU":"SAS","ITU":"SAS"}
Helpful in... | ece286a4eeb0978891ce7a94ae8b125ee8cddaf6 | 27,758 |
def decompose_name_string(name):
""" Accepts a name string and returns a list of possible versions of it. """
output = []
name_list = name.split(" ")
for i in range(len(name_list) + 1) :
output.append(" ".join(name_list[:i]))
return output | 978f332c8ac20c5363fd53572feff5b51d351a44 | 27,759 |
def inv_permutation(permutation):
"""Get the inverse of a permutation. Used to invert a transposition for example.
Args:
permutation (list or tuple): permutation to invert.
Returns:
list
"""
inverse = [0] * len(permutation)
for i, p in enumerate(permutation):
inverse[p]... | ab75f150d9df12d6bbec64fbe4744d962b9de1c6 | 27,760 |
def parent_user_password(db, parent_user):
"""Creates a parent website user with a password."""
user = parent_user
user.set_password('password')
user.save()
return user | 56718190793179034d5cce86e5bc6060c8d5d5a2 | 27,761 |
def _combine_indexers(indexers1, indexers2):
""" Conbine index data from two indexers
:param indexers1: list of indexers to combine index data
:param indexers2: second list of indexers to combine index data
:return: first list of indexers containing index data from both indexers in pair"""
if len(in... | c94d175542ff9fd3c88e592346a1f6023e27ba4a | 27,763 |
def _get_val_list(obj, path_list, reverse=False):
"""Extract values from nested objects by attribute names.
Objects contain attributes which are named references to objects. This will descend
down a tree of nested objects, starting at the given object, following the given
path.
Args:
obj: ob... | b66c7242db6c02340a2b8b2d92d842894990891b | 27,764 |
def remove_all_None(a_list):
"""Remove all None values from a list."""
# type: (list) -> list
return [item for item in a_list if item is not None] | 15eaeb7ef0208f3cd5519534bf155c62da88d3d5 | 27,765 |
def _get_ids(records, key):
"""Utility method to extract list of Ids from Bulk API insert/query result.
Args:
records (:obj:`list`): List of records from a Bulk API insert or SOQL query.
key (:obj:`str`): Key to extract - 'Id' for queries or 'id' for inserted data.
Returns:
(:obj:`... | 2fe90c06a7458af49db87d2ee01350e065920113 | 27,766 |
def diagnosis_from_description(description):
""" Return the diagnosis in each description """
diagnosis = description["meta"]["clinical"]["diagnosis"]
if diagnosis not in ["nevus", "melanoma", "seborrheic keratosis"]:
raise ValueError(diagnosis)
return diagnosis | b2a46fe653648e8a5f9b662be45a2cd1f68cc339 | 27,768 |
def filter_delivery(df, tol_imps=100, tol_ctr=100):
"""
Objective: Filter out dates where delivery unbalances greater than inputs
:param df: Dataframe
:param tol_imps: tolerance impressions in percentage * 100
:param tol_ctr: tolerance ctr in percentage * 100
:return: Dataframe with relevant dat... | 96f5df33ec07b7c500dabb5fe2333d62fe6ca6e7 | 27,772 |
def get_params_for_component(params, component):
"""
Returns a dictionary of all params for one component defined
in params in the form component__param: value
e.g.
>> params = {"vec__min_df": 1, "clf__probability": True}
>> get_params_for_component(params, "vec")
{"min_df": 1}
"""
... | aefee29c848fecab432efc74acd3d1bcaf80e539 | 27,773 |
import re
def try_include(line):
"""
Checks to see if the given line is an include. If so return the
included filename, otherwise None.
"""
match = re.match('^#include\s*[<"]?(.*)[>"]?$', line)
return match.group(1) if match else None | f30c885ffa783f78f5a71dc1906ac6e158226361 | 27,775 |
import os
def dirname(path, num=1):
"""Get absolute path of `num` directories above path"""
path = os.path.abspath(path)
for _ in range(num):
path = os.path.dirname(path)
return path | c864fc02a81ff4242c84980b6b57a0970ed82849 | 27,776 |
from typing import Dict
from pathlib import Path
import json
def get_config() -> Dict:
"""Load config file from disk as python dict and return it. File is
expected to exist on the same path as this source file.
"""
with open(
Path(Path(__file__).parent, "config.json").resolve(),
"r",
... | 68a0a11ddfea137b1ede61686df630e1d9735c21 | 27,777 |
import inspect
def _parse_cli_options(func):
"""Parse click options from a function signature"""
options = []
for param in inspect.signature(func).parameters.values():
if param.kind not in {param.POSITIONAL_OR_KEYWORD, param.KEYWORD_ONLY}:
# Only keyword arguments are currently support... | 16876af59f791a896b398f3562573ae828faee34 | 27,778 |
def get_filename_without_extension(filename):
"""
Returns the name of the 'filename', removing any extension. Here, an extension is indicated by a *dot*,
e.g. 'file.txt' where 'file' denotes the name and 'txt' is the extension.
If multiple extensions exist, only the last one is removed. In case no exte... | 7359be82706b1aa041c3559293db8e8cfe49f157 | 27,779 |
def __prepare_word(word: str) -> str:
"""
### Args
- word: `str`, word to be processed
### Returns
- `str`, word with all non-alphanumeric characters removed in lower case (spaces
are removed too)
### Errors raised
- None
"""
prepared_word = ""
for letter in word:
... | b25aab72f1640241f6a3a1e5bb7c5adc7056bc56 | 27,780 |
def make_variable_batch_size(num_inputs, onnx_model):
"""
Changes the input batch dimension to a string, which makes it variable.
Tensorflow interpretes this as the "?" shape.
`num_inputs` must be specified because `onnx_model.graph.input` is a list
of inputs of all layers and not just model inputs.... | e503ea83cac31c33fff0cee6909e7f6640acf4b5 | 27,781 |
import torch
def ratio_disc(disc, x_real, x_fake):
"""Compute the density ratio between real distribution and fake distribution for `x`
Args:
disc: The discriminator
x (ndarray): An array of shape (N,) that contains the samples to evaluate
Returns:
ndarray: The density ratios
"""
# Put sample... | c901a5a0b8c0201a00d34b8a01115240712f3b61 | 27,782 |
def decision_engine(p):
"""
Takes in the prediction object and prettifies it
to be consumed by the outbound payload
"""
return [float(p.label),
p.classProbabilities[0],
p.classProbabilities[1],
p.classProbabilities[2]] | 0c6a825f893a1436a658cdff19b1c2056a14d439 | 27,785 |
def meme(does, quality, person, be, person2):
""" Construct the stick-figure Bill meme from supplied parameters
Usage examples:
axs byname be_like , meme "finds and fixes an error in Wikipedia" smart
axs byname dont_be_like , meme 'wrote an OS that everybody hates' selfish --person2... | 456e6eb2046274cb4c539e48c0a1a53635e76e3c | 27,788 |
def power(x, n):
"""
计算幂的递归算法 x^n = x * x^(n-1)
时间复杂度 O(n)
:param x:
:param n:
:return:
"""
if n == 0:
return 1
else:
return x*power(x, n-1) | 5772fc4ccd1e392f7e8cff4a6068b4cf21989312 | 27,789 |
import re
def splitAtDelimiter(a_string, delimeters):
"""assumes a_string is a string
assumes delimeters is a string sconsisting of the desired delimiters
returns a list of strings, a_string split at the delimeters"""
pattern = "("
for item in delimeters:
pattern += (item+"|")
pattern ... | 96ffe5b6a5cad53c6ab18fa3ab23d2ff8d124391 | 27,792 |
import numpy
def _get_error_matrix(cost_matrix, confidence_level):
"""Creates error matrix (used to plot error bars).
S = number of steps in permutation test
B = number of bootstrap replicates
:param cost_matrix: S-by-B numpy array of costs.
:param confidence_level: Confidence level (in range 0.... | a7589363347884eb711dc84e110aba367493eaa5 | 27,793 |
def csv_diff():
"""The diff that should be reported for the CSV files."""
return (
r"""The files '\S*/file.csv' and '\S*/file.csv' are different:\n\n"""
r"""Column 'col_a': Series are different\n\n"""
r"""Series values are different \(33.33333 %\)\n"""
r"""\[index\]: \[0, 1, 2\]\... | 3ec0fdcadaee978cdd0f2da74acec0da371d3abc | 27,794 |
def comp_height_eq(self):
"""Computation of the Frame equivalent Height for the mechanical model
Parameters
----------
self : Frame
A Frame object
Returns
-------
Hfra: float
Equivalent Height of the Frame [m]
"""
return self.Rext - self.Rint | 25da3ee420ff1ed4dad133ac7d039ae408bb9cbe | 27,795 |
def filter_list(values, excludes):
"""
Filter a list of values excluding all elements from excludes parameters and return the new list.
Arguments:
values : list
excludes : list
Returns:
list
"""
return list(x for x in values if x not in excludes) | 68f25fe3afd4faebeefde7639a2b3d5885255e6a | 27,796 |
def _process_scopes(scopes):
"""Parse a scopes list into a set of all scopes and a set of sufficient scope sets.
scopes: A list of strings, each of which is a space-separated list of scopes.
Examples: ['scope1']
['scope1', 'scope2']
['scope1', 'scope2 scope3']
Retu... | 85fa5d8f761358225343f75e1c1dfa531e661eb3 | 27,797 |
import hashlib
def tagged_hash_init(tag: str, data: bytes = b""):
"""Prepares a tagged hash function to digest extra data"""
hashtag = hashlib.sha256(tag.encode()).digest()
h = hashlib.sha256(hashtag + hashtag + data)
return h | 955cc9fe6082d56663b9cd3531b0bb75aa2af472 | 27,798 |
def sort_decending(num):
"""Sort in descending order."""
return int("".join(sorted([n for n in str(num)], reverse=True))) | 7cd222ab31d4df559ee9554a58fcb2dd33a34eb4 | 27,802 |
def dic_longpks(pk_dic_longpk, stem_dic, INIT, PENALTY):
""" Function: dic_longpks()
Purpose: Calculate pseudoknot free energies under energy model LongPK.
Note that no shortened stems will occur here.
Input: Dictionary with pseudoknots where L2 >= 7.
... | 7030a188795003fdff892236d96b54bf1f7ba446 | 27,803 |
def generate_command_list(
tool_yml, iteration_parameters, step, local=False, file_path=None
):
"""
Generates an AWS Batch command list from a tool YML
Parameters:
-----------
tool_yml : dict
Tool YML from file
iteration_parameters: dict
Job parameters for a particular step
... | bf9f541361aaf40c24f81578b168211436e73770 | 27,805 |
def new_dict(num_dict):
""" “循环左移” 1 格,并存入新字典"""
tmp_dict = {}
n = len(num_dict)
for i in range(1, n):
tmp_dict[f'n{i}'] = num_dict[f'n{i+1}'] # format 的另一种用法
tmp_dict[f'n{n}'] = num_dict[f'n{1}']
return tmp_dict | 51614c295d4bb1763a4c8281091eb66734781583 | 27,807 |
import math
def GsoAzimuth(fss_lat, fss_lon, sat_lon):
"""Computes the azimuth angle from earth station toward GSO satellite.
Based on Appendix D of FCC 05-56.
Inputs:
fss_lat: Latitude of earth station (degrees)
fss_lon: Longitude of earth station (degrees)
sat_lon: Longitude of satellite (... | f8761e3529f75a02d90369b5f8aa353f22bbc599 | 27,808 |
from typing import Callable
from typing import Tuple
import inspect
def _make_decorator_stackable(
wrapper_func: Callable, base_func: Callable, exclude_parameters: Tuple[str],
) -> Callable:
"""
Attaches neccessary meta info directly to the decorator function's objects making multiple instance of these
... | 7648021d83ff5a44e7a86e777edba7dd8794010e | 27,809 |
def is_garbage(raw_text, precision):
""" Check if a tweet consists primarly of hashtags, mentions or urls
Args:
tweet_obj (dict): Tweet to preprocess.
"""
word_list = raw_text.split()
garbage_check = [
token for token in word_list if not token.startswith(("#", "@", "http"))]
g... | a508921e08673e686eccc43b8dab97424fff7726 | 27,810 |
def read_file(path):
"""Read file."""
with open(path) as _file:
return _file.read() | bed1e255478c6d43d84240e1c1969aa3c1bc21f3 | 27,813 |
def constrain(val, min_val, max_val):
"""
Method to constrain values to between the min_val and max_val.
Keyword arguments:
val -- The unconstrained value
min_val -- The lowest allowed value
max_val -- The highest allowed value
"""
return min(max_val, max(min_val, val)) | 655cc16ad425b6ca308d3edbd2881a3923ef195e | 27,814 |
def part2(data):
""" Check on other criteria """
return data | b13d7913ba2b30376b8a867ac8205e9b068a6d38 | 27,816 |
from typing import Counter
def small_class(raw_data, labels, threshold=20):
"""Removes samples and classes for classes that have less than
`threshold` number of samples."""
counts = Counter(labels)
data, n_labels = [], []
for i, l in enumerate(labels):
if counts[l] >= threshold:
... | cf80bd67ccc3d69baf0b71f226c8b56ef5b80e7c | 27,818 |
def rescale_size(size, scale, return_scale=False):
"""
Compute the new size to be rescaled to.
Args:
size (tuple[int]): The original size in the form of
``(width, height)``.
scale (int | tuple[int]): The scaling factor or the maximum size. If
it is a number, the imag... | 4baa26011ab191c4adca963c5ad7b6e63941b740 | 27,820 |
import subprocess
def _LoadEnvFromBat(args):
"""Given a bat command, runs it and returns env vars set by it."""
args = args[:]
args.extend(('&&', 'set'))
popen = subprocess.Popen(
args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
variables, _ = popen.communicate()
if popen.returnco... | 26971669ab52afb5e59b2128fe824dc42f69d550 | 27,821 |
def compose(f, g):
"""Function composition.
``compose(f, g) -> f . g``
>>> add_2 = lambda a: a + 2
>>> mul_5 = lambda a: a * 5
>>> mul_5_add_2 = compose(add_2, mul_5)
>>> mul_5_add_2(1)
7
>>> add_2_mul_5 = compose(mul_5, add_2)
>>> add_2_mul_5(1)
15
"""
# pylint: disabl... | 053c1c6db1517a10ef0580268abb709441a71333 | 27,822 |
from pathlib import Path
def get_rockets_frames():
"""Init rocket animation frames."""
frames_files = ['rocket_frame_1.txt', 'rocket_frame_2.txt']
frames = [(Path(__file__).resolve().parent / frame_file_name).read_text() for frame_file_name in frames_files]
return tuple(frames) | 318c514d2328ad177bf5a2ee4db46e87b9df25d0 | 27,824 |
def keynat(string):
"""
A natural sort helper function for sort() and sorted()
without using regular expressions or exceptions.
>>> items = ('Z', 'a', '10th', '1st', '9')
>>> sorted(items)
['10th', '1st', '9', 'Z', 'a']
>>> sorted(items, key=keynat)
['1st', '9', '10th', 'a', 'Z']
... | fa8a1e52ae97ff78cecab0afe1050142fd12d18a | 27,826 |
from typing import List
def intersection(lst1, lst2) -> List:
"""Calculate the intersection of two lists, with ordering based on the first list."""
lst3 = [value for value in lst1 if value in lst2]
return lst3 | 09f3447a79e995ad7dc7d34756f0cf832638228c | 27,828 |
def add_ining(new_data, data):
"""이닝 수를 최대값인 18에 맞춰서 추가해주고 키 이름도 변경해주는 함수
"""
for i in range(1, 19):
if str(i) in data:
new_data["i_"+str(i)] = data[str(i)]
else:
# 데이터 추가
new_data["i_" + str(i)] = "-"
return new_data | c6d6dcf4aab7ef5d5cad200685eaeb57689a549a | 27,829 |
def coords2polygon(coord_list):
"""Formats list of 2D coordinate points
as string defining Polygon in PostgreSQL"""
coords_ = [str(x) + " " + str(y) for x, y in coord_list]
return "POLYGON(("+",".join(t for t in coords_)+"))" | bc1d27fcdc01142497dde18da83f4584a9453971 | 27,830 |
def format_address(address):
"""Remove non alphanumeric/whitespace characers from restaurant address
but allows for commas
"""
return ''.join(chr for chr in address if chr.isalnum()
or chr.isspace() or chr == ",") | 6cb191b6672744dfedb570fa1e85f85876fa2895 | 27,832 |
import pickle
def load_pickled_data(path):
"""Load in a pickled data file
Args
----
path (str) : path to the file to read
Returns
-------
the data object
"""
with open(path, "rb") as f:
data = pickle.load(f)
return data | 18a4c352d14762c4b52dc205336a49a2c88cfbc1 | 27,833 |
def output_yolo(output):
"""Gets the output of yolo model
Args:
output (str): output of yolo model in string format
Returns:
bboxes (tuple): list of boundaries of table in the pdf page in top-left, right-bottom format
"""
output = output.split("\n")
output.remove("")
bbox... | f802d952bc2622d5dc20264b2ec858c1de9858bc | 27,834 |
def spec_is_empty(specification):
"""Check if specification value is empty
Args:
specification: List of specification values
"""
if len(specification) == 0:
return True
return False | 929bf64b50a8a74fef0efa15ec7577a1d1fd39ac | 27,835 |
import sys
def extract_house_income(loaded_df):
"""
Extracts the household income of each row. The coded values are the following:
-1 - Invalid value
1 - Less than 25k
2 - 25k to 49,999
3 - 50k to 74,999
4 - 75k to 99,999
5 - 100k and over
:param loaded_df: The dataframe loaded fro... | a6dd1a86de331433267e5d0e282be345970031cc | 27,836 |
def get_outputs(lst, uses, seen):
"""Return the list of nodes whose values are required beyond this segment.
Arguments:
lst: list of nodes (the segment)
uses: dict mapping each node to its uses (globally)
seen: set of nodes that are part of the segment
"""
outputs = []
for ... | 03d6c859bb70aa5ce868b9c71ff7ce6092d52604 | 27,837 |
import re
def regexp_quote(text):
"""\
Return a regexp matching TEXT without its surrounding space, maybe
followed by spaces. If STRING is nil, return the empty regexp.
Unless spaces, the text is nested within a regexp parenthetical group.
"""
if text is None:
return ''
if text == ' ' * len(text)... | 88da7ed8918fa8f91909eda1486b227dd7f1c41d | 27,839 |
def make_fortran_symbols(module, name):
"""
Makes a list of symbols, gcc and intel, for each variable or function
"""
gcc_symbol = "__"+module.lower() + "_MOD_" + name.lower()
intel_symbol = module.lower() + "_mp_" + name.lower() + "_"
return "(\"" + gcc_symbol + "\", \"" + intel_symbol + "\")" | 9ddac30bded9f62bf165f8f34b224f50c24849d5 | 27,843 |
def get_matches_metadata(infile):
"""
Reads match IDs and metadata from a filename.
Args:
infile: Filename where match IDs and metadata are stored (string).
Returns:
List of dicts with IDs and metadata for each match.
"""
out = []
with open(infile, "r") as file:
lines... | c9b70b40ea0c1ada0af0b6b9c6fbb7e3d95d83e5 | 27,844 |
def by_type(objects, t):
"""
Filter given list of objects by 'type' attribute.
Used for filtering ProducOption objects.
"""
return filter(lambda x: x.type == t, objects) | 8fef943468a649a199a646af2155917e787a7c52 | 27,845 |
def _get_init_or_call_arg(class_name, arg_name, init_value, call_value):
"""Returns unified value for arg that can be set at init or call time."""
if call_value is None:
if init_value is None:
raise ValueError(
f"{class_name} requires {arg_name} to be set at init or call time")
return init_v... | c955bd865da0436b6b88ccb938bda1f178b83aff | 27,846 |
def lmParamToPoint(a, c):
""" Return the coordinates of a landmark from its line parameters.
Wall landmarks are characterized by the point corresponding to the
intersection of the wall line and its perpendicular passing through the
origin (0, 0). The wall line is characterized by a vector (a, c) such a... | 6b98613216f1287ed9b25f1345ea0a18aa0fc90b | 27,847 |
from typing import Any
from typing import Callable
def pipe(in_: Any, *args: Callable[[Any], Any]) -> Any:
"""Basic pipe functionality
Example usage:
>>> pipe(
... [True, False, 1, 3],
... all,
... lambda x: "It's true" if x else "They lie"
... )
'They lie'
"""
for func... | 8eff195886ec9daf8391532cb21dc61182462c34 | 27,848 |
def remove_crs(mystring):
"""Removes new lines"""
return mystring.replace('\n', ' ').replace('\r', '') | 300d3a527912b4c60f3c5493067d1bb99756961a | 27,852 |
import textwrap
def _process_line(line, width, indent):
"""Process a line in the CLI help"""
line = textwrap.fill(
line,
width,
initial_indent=indent,
subsequent_indent=indent,
replace_whitespace=False,
)
return line.strip() | 99b5bc3c4885478a542fba24f6aee6667bdf7e3d | 27,854 |
from re import X
def label_data(frame, model):
"""Predict cluster label for each tract"""
frame["cluster"] = model.predict(X)
ix = ["geoid", "state_abbr", "logrecno", "geo_label", "cluster"]
return frame.reset_index().set_index(ix) | 7a27a0722394b90aba237a821be3d2a5730403c0 | 27,856 |
import platform
import sys
def get_platform() -> str:
"""Get FMU binary platform folder name."""
system = platform.system()
is_64bits = sys.maxsize > 2 ** 32
platforms = {"Windows": "win", "Linux": "linux", "Darwin": "darwin"}
return platforms.get(system, "unknown") + "64" if is_64bits else "32" | 06e4dd0f3296f531988d53da23cb31ee260ed4a4 | 27,857 |
def rel_2_pil(rel_coords, w, h):
"""Scales up the relative coordinates to x1, y1, x2, y2"""
x1, x2, y1, y2 = rel_coords
return [int(x) for x in [x1 * w, y1 * h, x2 * w, y2 * h]] | f619f4a0920db503401abdd0cfd86b61116c4992 | 27,858 |
import time
def datetime_format(epoch):
"""
Convert a unix epoch in a formatted date/time string
"""
datetime_fmt = '%Y-%m-%dT%H:%M:%SZ'
return time.strftime(datetime_fmt, time.gmtime(epoch)) | e45f7874bebdbe99a1e17e5eb41c5c92e15a96b3 | 27,859 |
def count_genes_in_pathway(pathways_gene_sets, genes):
"""Calculate how many of the genes are associated to each pathway gene set.
:param dict pathways_gene_sets: pathways and their gene sets
:param set genes: genes queried
:rtype: dict
"""
return {
pathway: len(gene_set.intersection(ge... | bb3859c9a6b8c17448a6cbcc3a85fc315abbab31 | 27,861 |
import numpy
def compute_mutation_frequency(x, threshold):
"""Computes mutation frequency for positions with coverage larger than
threshold.
"""
fraction_list = []
for cov, err in zip(x.coverage, x.errors):
if cov > threshold:
fraction_list.append(err / cov)
else:
... | e53c29d7547e9814c4596d358db39e332c302eca | 27,862 |
import unittest
import inspect
def AbstractTestCase(name, cls):
"""Support tests for abstract base classes.
To be used as base class when defining test cases for abstract
class implementations. cls will be bound to the attribute `name`
in the returned base class. This allows tests in the subclass to
... | 66641e3c9d805946880ac8dfc41827f51986f6aa | 27,863 |
def get_time_slices(time_range, interval):
"""
split time range based on interval
Args:
time_range (list): time range of diagnose
interval (int): diagnose time interval
Returns:
"""
time_points = [*range(time_range[0], time_range[1], interval), time_range[1]]
time_slices = ... | d22dfb72cdaa5f399171ed1380d9ad2b8bb6f8b4 | 27,864 |
import itertools
def _update_with_replacement(lhs_dict, rhs_dict):
"""Delete nodes that equate to duplicate keys
Since an astroid node doesn't 'equal' another node with the same value,
this function uses the as_string method to make sure duplicate keys
don't get through
Note that both the key an... | 6b13c197af2da654b29547bcffd5b6af8a3e6607 | 27,865 |
def _normalize(x, axis):
"""Normalize, preserving floating point precision of x."""
x_sum = x.sum(axis=axis, keepdims=True)
if x.dtype.kind == 'f':
x /= x_sum
else:
x = x / x_sum
return x | 3adc63499fab32453d53a339364c20b9f209f6eb | 27,866 |
import subprocess
def run(*args):
"""Run a command."""
return subprocess.run(args, capture_output=True, check=True, text=True) | d99d69d279424448f29eebe7cec8ee96a41b4fcd | 27,867 |
import itertools
def flat_map(visitor, collection):
"""Flat map operation where returned iterables are flatted.
Args:
visitor: Function to apply.
collection: The collection over which to apply the function.
Returns:
Flattened results of applying visitor to the collection.
"""
... | 5501e4adc18ca8b45081df4158bcd47491743f29 | 27,868 |
def hex_sans_prefix(number):
"""Generates a hexadecimal string from a base-10 number without the standard '0x' prefix."""
return hex(number)[2:] | 6faaec36b2b3d419e48b39f36c1593297710a0a4 | 27,869 |
def curly_bracket_to_img_link(cb):
"""
Takes the curly-bracket notation for some mana type
and creates the appropriate image html tag.
"""
file_safe_name = cb[1:-1].replace('/', '_').replace(' ', '_')
ext = 'png' if 'Phyrexian' in file_safe_name or file_safe_name in ('C', 'E') else 'gif'
ret... | 99a1a7ebf6318d2fbc9c2c24035e5115829b6feb | 27,872 |
import os
def is_executable(path):
"""Return True if the given path is executable"""
return os.access(path, os.X_OK) | 2fc40d31d0146a28e80911c110646a00b6f86198 | 27,873 |
import textwrap
def textjoin(text):
""" Dedent join and strip text """
text = textwrap.dedent(text)
text = text.replace('\n', ' ')
text = text.strip()
return text | bef921764388857881741f4a8c516ca723a42fd9 | 27,874 |
def name_options(options, base_name):
"""Construct a dictionary that has a name entry if options has name_postfix"""
postfix = options.get("name_postfix")
if postfix is not None:
return { "name": base_name + str(postfix) }
return {} | c5db1619fa951298743e28c78b8f62165b5d09de | 27,876 |
def is_mandatory(err: str, words: list) -> bool:
"""
This function checks whether a word containing the error string exists.
:param err: error string
:param words: list of words
:return: whether the correction can be specified as mandatory
"""
for word in words:
if err in word:
... | c44dd54733e0ede4072795e42d616533efb69de5 | 27,878 |
def first_index(keys, key_part):
"""Find first item in iterable containing part of the string
Parameters
----------
keys : Iterable[str]
Iterable with strings to search through
key_part : str
String to look for
Returns
-------
int
Returns index of first element ... | 45b41954e795ee5f110a30096aa74ea91f8e6399 | 27,879 |
def _calc_shape(original_shape, stride, kernel_size):
"""
Helper function that calculate image height and width after convolution.
"""
shape = [(original_shape[0] - kernel_size) // stride + 1,
(original_shape[1] - kernel_size) // stride + 1]
return shape | 46a40efec8c7163ead92425f9a884981e6a4a8bc | 27,880 |
def needs_column_encoding(mode):
"""
Returns True, if an encoding mode needs a column word embedding vector, otherwise False
"""
return mode in ["one-hot-column-centroid",
"unary-column-centroid",
"unary-column-partial",
"unary-random-dim"] | d5642d03628357508be87e227c5a9edf8e65da2d | 27,881 |
def intify(i):
"""If i is a long, cast to an int while preserving the bits"""
if 0x80000000 & i:
return int((0xFFFFFFFF & i))
return i | eeca1d312d7ca4b5b196a20c0d1c09beac5bc2e6 | 27,882 |
import json
def decode_frame(frame, tags=None):
""" Extract tag values from frame
:param frame: bytes or str object
:param tags: specific tags to extract from frame
:return: dictionary of values
"""
# extract string and convert to JSON dict
framebytes = frame if isinstance(frame, bytes) e... | 1e239c380c7050ff536aa7bfc1cd0b0a01959f39 | 27,884 |
import sys
def is_ammend():
"""
If the commit is an amend, it's SHA-1 is passed in sys.argv[3], hence
the length is 4.
"""
return len(sys.argv) == 4 | 614771b205ef5e6d877f3642d70e29cb8d00cf21 | 27,888 |
import textwrap
def construct_using_clause(metarels, join_hint, index_hint):
"""
Create a Cypher query clause that gives the planner hints to speed up the query
Parameters
----------
metarels : a metarels or MetaPath object
the metapath to create the clause for
join_hint : 'midpoint',... | 61c4dc58782aeb1bc31affb7ec2c74361eac8089 | 27,889 |
import sys
def mpa2seq(mpa, char_gap="-"):#{{{
"""
convert mpa record to seq
"""
try:
li = []
for item in mpa['data']:
if type(item) is tuple:
li.append(char_gap*(item[1]-item[0]))
else:
li.append(item)
return "".join(li)
... | e834f5ac77d798e5dbc3087bdfa219b99fad22d9 | 27,890 |
from typing import List
import torch
def import_smallsemi_format(lines: List[str]) -> torch.Tensor:
"""
imports lines in a format used by ``smallsemi`` `GAP package`.
Format description:
* filename is of a form ``data[n].gl``, :math:`1<=n<=7`
* lines are separated by a pair of symbols ``\\r\\n``
... | 2ca9708944379633162f6ef9b4df3357bca77e80 | 27,891 |
def assign_format_str(string, *args, **kwargs):
"""
Format string and save it to variable.
{% assign_format_str 'contacts_{lang}.html' lang=LANGUAGE_CODE as tpl_name %}
{% include tpl_name %}
"""
return string.format(*args, **kwargs) | db28016f0cf722fdf5c6f17c2a746639a1c04779 | 27,892 |
from typing import Optional
from typing import Dict
import re
def parse_git_uri(uri) -> Optional[Dict[str, str]]:
"""解释git的路径
Args:
uri str: 格式如git@github.com:group/project.git or https://github.com/group/project
Returns:
dict|None {host: "", group: "", project: ""}
"""
def _parse(... | a71a991c21d5339edfa28db41ac947b02d19d46a | 27,895 |
import os
def exists(path):
"""Determine if a file exists.
Args:
path (str): Full path to file
Returns:
bool: True if the file exists, False if not
"""
return os.path.exists(path) and os.path.isfile(path) | 816781213afd43d6dc2b13d39e03ca69ffdf6546 | 27,896 |
import re
def load_tolerances(fname):
""" Load a dictionary with custom RMS limits.
Dict keys are file (base)names, values are RMS limits to compare.
"""
regexp = r'(?P<name>\w+\.png)\s+(?P<tol>[0-9\.]+)'
dct = {}
with open(fname, 'r') as f:
for line in f:
... | 60af52ec49cadfdb5d0f23b6fa5618e7cc64b4c2 | 27,897 |
def is_list(input_check):
"""
helper function to check if the given
parameter is a list
"""
return isinstance(input_check, list) | 9ff5767c862a110d58587cccb641a04532c1a1a5 | 27,899 |
def virtual(func):
"""
This decorator is used to mark methods as "virtual" on the base
Middleware class. This flag is picked up at runtime, and these methods
are skipped during ravel requrest processing (via Actions).
"""
func.is_virtual = True
return func | 953e36a060793cfec95888ab1eb6b34722689e58 | 27,900 |
import re
def is_valid_hostname(hostname):
"""
Check if the parameter is a valid hostname.
:type hostname: str or bytearray
:param hostname: string to check
:rtype: boolean
"""
try:
if not isinstance(hostname, str):
hostname = hostname.decode('ascii', 'strict')
exc... | 31f16d1c648a230de3eb0f3158be42e0841db5a4 | 27,901 |
def _mgmtalgomac(rack, chassis, slot, idx, prefix=2):
""" Returns the string representation of an algorithmic mac address """
return "%02x:%02x:%02x:%02x:%02x:%02x" % (prefix, rack >> 8, rack & 0xFF, chassis, slot, idx << 4) | ea90898d50d5946abb6e0d6c678e876aa8b5f8cf | 27,902 |
def check_phase(w_no_board, b_no_board, w_board, b_board, player):
"""
Controllo in base allo stato in quale fase siamo e restituisce il numero della fase
:param w_no_board:
:param b_no_board:
:param w_board:
:param b_board:
:param player:
:return:
"""
if w_no_board == 0 and b_n... | 657938fdba7305f9725beec9f062adc93e133c23 | 27,904 |
def _model_insert_new_function_name(model):
"""Returns the name of the function to insert a new model object into the database"""
return '{}_insert_new'.format(model.get_table_name()) | bd3079813b266a4e792ea323ab59eb3ef377159e | 27,905 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.