content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_position_by_substring(tofind, list):
"""
Get index where `tofind` is a substring of the entry of `list`
:param tofind: string to find in each element of `list`
:param list: list to search through
:return: index in `list` where `tofind` is found as a substring
"""
for i, e in enumera... | 8836fe6cbb1279d21320c6048c45d36746aafc8a | 666,778 |
def add_sections(base_dict, new_tools):
"""
Take a base_dict (reference) containing a (reference) set of tools,
and a set of new_tools. Add the missing section labels in the tools from the new_tools
that are already in the base(reference)
Also change the section_labels when the one in new_tools is n... | 2097be143ffe5964bf65262f115e99756bafa266 | 666,779 |
def _get_creator(hardict):
"""
Get creator of HAR file.
"""
creator = hardict["log"]["creator"]
return "%s %s%s" % (creator["name"], creator["version"],
" (Comment: %s)" % creator["comment"] if creator.get("comment") else "") | 59cc6f8fbb754ee61aaa532640882107670f812e | 666,780 |
def classesMatch(annotation1, annotation2, equivalentClasses):
"""Checks if the classes match, considering 'equivalentClasses' and returns a boolean."""
if equivalentClasses == False:
return True
if equivalentClasses == None:
if annotation1.annotationClass == annotation2.annotationClass:
... | 61bf9fad3fb737e6bd5a0e99431ad77dbf039943 | 666,782 |
from datetime import datetime
def to_iso(time_millis):
"""Converts the given time since epoch in millis to an ISO 8601 string"""
return datetime.utcfromtimestamp(time_millis / 1000).isoformat() | 4ec3d3d3fcbd3d714d627509ddddd8ad1fc1e596 | 666,783 |
def Find_the_bbox(annotations):
"""
input: annotations -> the coco format annotations
output: bbox -> a list of bbox cordinates , i.e:[0,155,23,56]
"""
bbox_0 = 1000
bbox_1 = 1000
bbox_2 = 0
bbox_3 = 0
for annotation in annotations:
bbox_0 = int( min(... | 27d5bef25079d81b51efef153a052ffa87735726 | 666,784 |
def _format_range(start, end):
"""
Build string for format specification.
used by many commands, like delete, load, etc...
:param start:
:param end:
:return: the string to be used for range in the command
"""
if start is None:
return ''
if end is None:
return str(star... | bcca178e1d064ef0a0744906c511fc4b2e289ec8 | 666,785 |
def prefix_to_items(items, prefix):
"""Add a prefix to the elements of a listing. For example, add "Base" to
each item in the list.
"""
return ['{}{}'.format(prefix, x) for x in items] | 41c3abc10bfe8b2163ab9d8e5c3394a66f49247c | 666,786 |
def employeeStatistic(employees, dayNum):
"""暴力破解"""
if len(employees) == 1:
return [0]
ret = []
for i, n in enumerate(employees):
tmpRes = 0
for j in range(i + 1, len(employees)):
if employees[j] > n:
tmpRes = j - i
break
ret... | 2cd2c054d24c2f6cf4d531817228af48dd2db934 | 666,787 |
def mismatch_training(names, train_df):
"""Check if file name is different than the target label"""
count = 0
candidate_name = train_df.label
for i in range(len(names)):
c = candidate_name[i].lower().strip()
#print(names[i], c)
if(names[i][0] == 'O'):
names[i][0] = names[i][0... | 12c404780a43f6853f30457b999cde11eedb85aa | 666,788 |
import numpy
def frametoimage(imgframe,imgmeta):
"""
To convert stuctured image frame to nd image array.
Parameters
----------
imgframe : Stuctured image data.
imgmeta : Metadata of the image.
Needed for get image width, height and band information.
Returns
-------
rs... | d65c8fea2f2b399e5438b3bab0cbaa7a7c2b5068 | 666,790 |
def dedupe_in_order(in_list, dont_add=set()):
"""
Deduplicate the in_list, maintaining order
:param dont_add: an additional stoplist
"""
dedupe = set() | dont_add
ordered_deduped = []
for l in in_list:
if l not in dedupe:
ordered_deduped.append(l)
dedupe.add(l)
return ordered_deduped | 0df861711b28f58410d0234c6b01c4ed8c2b5d0a | 666,791 |
def is_page_editor(user, page):
"""
This predicate checks whether the given user is one of the editors of the given page.
:param user: The user who's permission should be checked
:type user: ~django.contrib.auth.models.User
:param page: The requested page
:type page: ~integreat_cms.cms.models.... | 51ff98bce8361f6e51654eed6f9021fc5365ae79 | 666,792 |
def optimize_model(m):
"""
Optimization routine we use to optimize a (Bayesian-)GPLVM.
We first fix the variances to low values to force
the latent mapping function `f` (`Y = f(X)`) learn
the structure in the beginning and not allow the
model to explain the data by pure noise.
Usage exampl... | 7782aeca6bde254f43b0118068329c4a1a15d5d2 | 666,793 |
def line_number_match(array1, array2):
"""
Function that compares two lists of line numbers and determines which line numbers are missing from either array.
:param array1: A list to be compared
:param array2: A list to be compared
:return: Where in the program there is a parenthesis missing as an in... | e6d18247f2b71751820fe673c619e01764031000 | 666,794 |
def _is_supported(arg, supported: set):
""" Check that aggregations in `arg` are a subset of `supported`
"""
if isinstance(arg, (list, dict)):
if isinstance(arg, dict):
_global_set = set()
for col in arg:
if isinstance(arg[col], list):
_glo... | f9e134a5b599226a9c396cc73d9cb8fc8a1fc4fc | 666,795 |
def parse_row(row):
"""
Take in a tr tag and get the data out of it in the form of a list of
strings.
"""
return [str(x.string) for x in row.find_all('td')] | 44b8eadcd11d79ede2ae3d0a0866bfa80ff5e36d | 666,796 |
def eco_fen(board):
"""
Takes a board position and returns a FEN string formatted for matching with
eco.json
"""
board_fen = board.board_fen()
castling_fen = board.castling_xfen()
to_move = 'w' if board.turn else 'b'
return "{} {} {}".format(board_fen, to_move, castling_fen) | bb8afe9f8cc02ea48e55f9197eed760fe5e25a1f | 666,797 |
def _arbitrary_ds_da_func(ds_da, *args, **kwargs):
"""Function for testing if checking the first item in arg list is ds/da."""
return ds_da, args, kwargs | 618750d736dbb6dd42a90eea889f052e9e3f20e3 | 666,799 |
def minus(a:int,b:int)->int:
"""
minus operation
:param a: first number
:param b: second number
:return: a-b
"""
return a-b | 9a20af293d84884fc8d0762c177b301ca197871c | 666,800 |
def bit_set(data, bit):
""" Note: This is NOT in place. """
mask = (data << (bit - 1))
return mask | data | 061b0f189b930c7a7d7956cf3fdd8a3aba3a71ae | 666,801 |
import requests
import json
def get(api_path):
"""Request the api path and return the response."""
response = requests.get(api_path)
if response.ok:
try:
# return the json from the API endpoint
return json.loads(response.text)
except ValueError:
# handl... | afb8e7ebfd1175919e9afaa739bd3505472dd3b9 | 666,802 |
def create_wiki_url(page: str) -> str:
"""Creates canonical URL to `page` on wiki
Args:
page (str): subject page
Returns:
str: canonical URL
"""
return f"https://genshin-impact.fandom.com{page}" | 4dc7e9eeb77e0345ec4f066627f7c6664143d65e | 666,803 |
import itertools
def get_flattened_subclasses(cls):
"""
Returns all the given subclasses and their subclasses recursively for the given class
:param cls: Class to check
:type cls: Type
:return: Flattened list of subclasses and their subclasses
"""
classes = cls.__subclasses__()
return ... | c9b0eef89f499f34c7e6ffa02ee3267657d1fff7 | 666,804 |
def accuracy(labels, scores, threshold=0.5):
"""
Computes accuracy from scores and labels. Assumes binary classification.
"""
return ((scores >= threshold) == labels).mean() | e0603cfea4ce69a57e116ac62e46efb1aed133a9 | 666,805 |
def deal_hands(deck, start):
"""
Deal hands from the deck starting at index i
"""
return (
[deck[start], deck[start + 2]],
[deck[start + 1], deck[start + 3]],
) | 53c3c32eb8188d012cea2d9046c64f68a5cd28a8 | 666,806 |
import sys
def get_from_sys_modules(cls_name):
"""Gets the class from a dot notation name
Args:
cls_name: dot notation enum name
Returns:
module: enum class
"""
# Split on dot notation
split_string = cls_name.split(".")
module = None
for idx, val in enumerate(split_s... | b6b861495916f0d65fd80efbfcd2d62cc3af6555 | 666,807 |
def in_sh(argv, allstderr=True):
"""
Provides better error messages in case of file not found or permission
denied. Note that this has nothing at all to do with shell=True, since
quoting prevents the shell from interpreting any arguments -- they are
passed straight on to shell exec.
"""
# NB... | 7236d3d403c80122e57cc1c3238006c2e4a38067 | 666,808 |
def banner(text: str) -> str:
"""Generate a banner of 3 lines"""
FILLER = "#"
text = text.strip()
middle_line = FILLER + text.center(int(len(text) / 0.618)) + FILLER
top_line = bottom_line = FILLER * len(middle_line)
return "\n".join([top_line, middle_line, bottom_line]) | 775c0cbb6f7650e87df3f56b2dc1c84b083d656b | 666,809 |
def feature_basic_statistics(df, feature, artist_filter=None):
"""returns min, max & avg of given feature for specified artist"""
if artist_filter:
mask = df["name_artist"] == artist_filter
else:
mask = [True] * df.shape[0]
min = df.loc[mask, feature].min()
max = df.loc[mask, featur... | 45187cb20610a0af5180fb6b6e3abb8f82af6b98 | 666,810 |
def set_training_mode_for_dropout(net, training=True):
"""Set Dropout mode to train or eval."""
for m in net.modules():
# print(m.__class__.__name__)
if m.__class__.__name__.startswith('Dropout'):
if training==True:
m.train()
else:
m.eval()... | 4a0f7b9a2442032fafd9d597efe0e1463344c3ff | 666,811 |
from typing import Union
from typing import Set
def split_once(text: str, separates: Union[str, Set[str]]): # 相当于另类的pop, 不会改变本来的字符串
"""单次分隔字符串"""
out_text = ""
quotation = ""
is_split = True
separates = separates if isinstance(separates, set) else {separates}
for char in text:
if char... | 2228cc54736ae03d09d55d70ccbf6fe90bd327d5 | 666,812 |
def elbow_point(points):
"""Return the index in ``points`` for maximal curvature.
Parameters
----------
points : list of int
Returns
-------
int
"""
second_derivative_list = [points[x+1] + points[x-1] - 2 * points[x]
for x in range(1, len(points) - 1)]... | 2459209da76976fb53838d4c2de0c4e4101e9d4d | 666,813 |
import os
import csv
def validate_types_and_id(meta_dictionary, logger, filename):
"""Validate a genetic_alteration_type, datatype (and stable_id in some cases) against the predefined
allowed combinations found in ./allowed_data_types.txt
"""
result = True
# this validation only applies to items t... | b505db5be0df8b061e9889493418d87387b3f331 | 666,815 |
import torch
def mean_frobenious_distance(generated_cbt, test_data):
"""
Calculate the mean Frobenious distance between the CBT and test subjects (all views)
Args:
generated_cbt: trained DGN model
test_data: list of data objects
"""
frobenius_all = []
for data i... | cc9e8c5e9fa4c7a5071b0e4c221dd301d832c55e | 666,816 |
def manipulate(root, strblock):
"""
Maliciously manipulates the structure to create a crafted FIT file
"""
# locate /images/kernel-1 (frankly, it just expects it to be the first one)
kernel_node = root[0][0]
# clone it to save time filling all the properties
fake_kernel = kernel_node.clone()... | 8f2b092a38f807b30421e1a48ebaf9a89da751d7 | 666,817 |
import pickle
def load_object(filename):
"""
Load python object
-------------------------------------------
Inputs:
filename: name of pickle file I want to load. Example: 'dump_file.pkl'
-------------------------------------------
Output:
loaded object
"""
with open(filename, "... | 700012eca7175992eeac07d93d1ebfd307f5f4ae | 666,818 |
import numpy
def B_Mat(uv0, uv1, p00, p10, p01, p11, nPixels):
""" Create a cooefficent B matrix. """
c1 = (uv1.u - uv0.u) * uv0.v + uv0.u * (uv1.v - uv0.v)
c2 = uv1.u - uv0.u
c3 = uv1.v - uv0.v
coeffs = numpy.zeros((1, nPixels))
coeffs[0, p00] = c1 - c2 - c3
coeffs[0, p10] = -c1 + c2
... | 02aea226e7bfe084aeaecc38283bcab6ee8b475c | 666,819 |
def mean_dim(tensor, dim=None, keepdims=False):
"""Take the mean along multiple dimensions.
Args:
tensor (torch.Tensor): Tensor of values to average.
dim (list): List of dimensions along which to take the mean.
keepdims (bool): Keep dimensions rather than squeezing.
Returns:
... | d47a131ecff97ff597ea19f310c1330a6e426122 | 666,820 |
import os
def createDaemon(UMASK=0, MAXFD=1024):
"""
this function is based on this receipe:
http://code.activestate.com/recipes/278731-creating-a-daemon-the-python-way/
"""
# first fork
pid = os.fork()
if (pid == 0): # first child.
os.setsid()
pid = os.fork() # second chil... | f44e71a1286bef0131dda1fea0b341f7cd9e3b2e | 666,821 |
def levenshtein(s1, s2, weights=(1, 1, 1)):
"""
python implementation of a generic Levenshtein distance
this is much less error prone, than the bitparallel C implementations
and is therefor used to test the C implementation
However this makes this very slow even for testing purposes
"""
row... | 1221b55bc5e92d52c371b3e4f876ea365de0ea8b | 666,822 |
def humanize_time(secs):
"""
Takes *secs* and returns a nicely formatted string
"""
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins, 60)
return "%02d:%02d:%02d" % (hours, mins, secs) | 8b450b2add2ce4da5432e52fee8ac9ff98e2b0e5 | 666,823 |
def drop_unlinked_cfs(data):
"""Drop CFs which don't have ``input`` attribute"""
for method in data:
method[u'exchanges'] = [cf for cf in method['exchanges']
if cf.get('input') is not None]
return data | 99757464b03598abfe50574b61d5cee833617200 | 666,824 |
def get_first_and_last_names(user):
"""
Returns a the most reliable values we have for a user's first and last name based on
what they have entered for their legal address and profile.
Args:
user (django.contrib.auth.models.User):
Returns:
(str or None, str or None): A tuple contai... | 6968b7b9f472a85930f661d6472d503c7045c969 | 666,825 |
import os
def ExeName(env, exePath):
"""Figure out the real name of an executable.
Given the Linux-style path, this works out what an executable is actually
called, so that we can run on cygwin.
"""
pre = env.subst('$PROGPREFIX')
suf = env.subst('$PROGSUFFIX')
dirpath = os.path.dirname(ex... | 7717faaf298f7dadfdfaa3ea7190b1ba41f83f30 | 666,826 |
def _reorder(xs, indexes):
"""Reorder list xs by indexes"""
if not len(indexes) == len(xs):
raise ValueError("xs and indexes must be the same size")
ys = [None] * len(xs)
for i, j in enumerate(indexes):
ys[j] = xs[i]
return ys | 1106354917f3358971fe532f8b1fc5163a10b0cd | 666,827 |
def error_applookuprecord_unknown(value:str) -> str:
"""
Return an error message for a unknown record identifier.
Used when setting the field of an applookup control to a record identifier
that can't be found in the target app.
"""
return f"Record with id {value!r} unknown." | 47872e250a7d03c97cad47c00d6d46e3fdabc8c1 | 666,829 |
def digest_repr(obj):
""" Return a short digest of a possibly deeply nested (JSON) object.
"""
if isinstance(obj, (tuple, list, set, dict)):
def nesting(collection):
"Helper"
if isinstance(collection, dict):
collection = collection.values()
if isin... | 5d08c6a1683e659e44297783de1c59e8e291e2f9 | 666,830 |
def group(iterable, n):
"""Splits an iterable set into groups of size n and a group
of the remaining elements if needed.
Args:
iterable (list): The list whose elements are to be split into
groups of size n.
n (int): The number of elements per group.
... | d451ce6b89e4a2984905c598ee413ad2811a1f6c | 666,831 |
def question_1():
"""Return the correct answer for the following question.
What's the correct data type of the following values: True, False
a) Integer
b) Boolean
c) String
d) Collection
"""
return 'Boolean' | fdcc57e44dd7cd300eb953dd4b1613a86b8e0325 | 666,832 |
def read(strg):
"""Read string generated by the generate() function, or any other number in 10-digit string format."""
l = int(strg[:2])
h = int(strg[2:4])
c = int(strg[4])
unique_identifier = int(strg[5:])
return (l,h,c, unique_identifier) | a1e07810896de7c35cf4bb193173a7dbc14fabe7 | 666,833 |
import sys
def mayaStartupHasRun():
"""
Returns True if maya.app.startup has already finished, False otherwise.
"""
return 'maya.app.startup.gui' in sys.modules or 'maya.app.startup.batch' in sys.modules | 2ba5222524befd181de94a7957821a3cc2f7d905 | 666,834 |
def collection_attribs(col):
"""Returns a list of the unique non-subscripted attributes of items in `col`."""
attribs = (attrib for item in col for attrib in item.__dict__ if attrib[0] != '_')
return list(set(attribs)) | dbbd1c09e8dba064efa0ac6534cfd4348875bf6c | 666,835 |
def f_to_c(f):
"""
Convert fahrenheit to celcius
"""
return (f - 32.0) / 1.8 | 12df6accdfd901e35c3ddd4086b98f6d0cce79ef | 666,836 |
import os
import glob
def def_file_names(mode, ref_dir, test_dir, img_name, olist, verbose=True):
"""Generate image file names."""
test_fname = os.path.realpath(os.path.join(test_dir, img_name))
if mode == "ref":
ref_fname = os.path.realpath(os.path.join(ref_dir, img_name))
else:
# Sup... | cfcaf3e354bc4e1b373611819ebcd42506e491d7 | 666,837 |
import math
def e_dist(p1,p2):
"""
Takes two points and returns
the euclidian distance
"""
x1,y1=p1
x2,y2=p2
distance = math.sqrt((x1-x2)**2+(y1-y2)**2)
return int(distance) | 6d98e613d5d367d47dfbd123cc424331e768b921 | 666,838 |
import json
def serialize(d):
"""
Serialize a dict as a json string. To be used in client requests
"""
return json.dumps(d) | 63be596eb576ba6f844e8a82baa3cac6863e0738 | 666,839 |
def power(n):
"""Return 2 to the n'th power"""
return 2 ** n | 94c50cc9694c5b66fc8dc16fc7e1057d78121ba3 | 666,840 |
def check_winner(board):
"""
Returns player that wins
-1 if draws
0 if game has not ended
"""
# Check rows for winner
for row in range(6):
for col in range(4):
if (board[row][col] == board[row][col + 1] == board[row][col + 2] ==\
board[row][col + 3]) and (... | e3894cefc692d0551b083bac0ca842e690d8ebd6 | 666,841 |
def flipBit(int_type, offset):
"""Flips the bit at position offset in the integer int_type."""
mask = 1 << offset
return(int_type ^ mask) | f94d8b6eb6d9053a224b9cfc054b3a590af097d3 | 666,842 |
def flattenSpiderConfig(run_spider_config) :
"""creates a flat dict from nested spider_config dict"""
spider_config_flat = {}
for conf_class, conf_set in run_spider_config.iteritems() :
if conf_class != "_id" :
for conf_field, conf_data in conf_set.iteritems() :
spider_config_flat[conf_field] = conf_da... | cf5cd4f74f7765b3c487a4c35b8f1442affa5a0e | 666,843 |
def readLocationChange(sheet, row=19, colStart=1, nphases=10):
""" Read locations of peak angle and obtain change in location
"""
distances = sheet.rows[row-1][colStart:colStart+nphases]
distances = [obj.value for obj in distances]
locationchange = max(distances) - min(distances)
return loc... | 005ab971e24377af8d2e0c0a10555deefd6d870a | 666,844 |
def expand_pv(pv):
""" Returns the LCS Process Variable in full syntax AADDDNNNCMM as a string
where AA is two character area,
DD is device type,
NNN is device number,
C is channel type,
MM is channel number
Returns partial PVs when input string is incomplete.
... | f41dc8cf20dd55ed1cb0103c42ce67301ec93372 | 666,846 |
import random
def generate_equations(allowed_operators, dataset_size, min_value, max_value):
"""Generates pairs of equations and solutions to them.
Each equation has a form of two integers with an operator in between.
Each solution is an integer with the result of the operaion.
allowed_ope... | 7a098aaf4fbfc55840ff21d946d474db54c07c1c | 666,847 |
import torch
def grid_8_neighbor_graph(N):
"""
Build discrete grid graph, each node has 8 neighbors
:param n: sqrt of the number of nodes
:return: A, the adjacency matrix
"""
N = int(N)
n = int(N ** 2)
dx = [-1, 0, 1, -1, 1, -1, 0, 1]
dy = [-1, -1, -1, 0, 0, 1, 1, 1]
A = torc... | 44d680be6168df4a5b55de58f756f043ab35f256 | 666,848 |
def parsedFile(file):
"""Take a parsed file and return the list Of Chords and Interval Vectors.
The file was already parsed possibly from corpus. Then with chordify and
PC-Set we compute a list of PC-chords and Interval Vectors.
"""
mChords = file.chordify()
chordList = []
chordVectors = []... | 0f4b6424429c52aa53f1271f478693f5607b0218 | 666,849 |
def grab_job_links(soup):
"""
Grab all non-sponsored job posting links from a Indeed search result page using the given soup object
Parameters:
soup: the soup object corresponding to a search result page
e.g. https://ca.indeed.com/jobs?q=data+scientist&l=Toronto&start=20
... | 159b3d768266900446bc17326aeb41bfd048b267 | 666,852 |
def gene2bin(parameters, gene, geneType):
"""
geneBin = gene2bin(parameters, gene, geneType)
Turns genes into the binary-string form
gene:
integer
geneType:
string
geneBin:
string, of all ones and zeros
>>> geneType = 'repn'
>>> parameters = {'genetics': {geneT... | bf919c9da48d162621e73e593308d3e31bc19368 | 666,853 |
def unique_items(seq):
"""A function that returns all unique items of a list in an order-preserving way"""
id_fn = lambda x: x
seen_items = {}
result = []
for item in seq:
marker = id_fn(item)
if marker in seen_items: continue
seen_items[marker] = 1
result.append(item... | b0e04c1f46e9758b2f1582c7fa47dfc72d26293c | 666,854 |
def checkComp(parts, ind, wmap):
"""
Finds longest compound terms from list of tokens starting at an index.
:param parts: List of tokens
:param ind: Index of the current token
:param wmap: Dictionary mapping token to lemma
:returns: Longest compound term, index after the longest compound ter... | 07507c4b8b3f0869047920d2b2d74b4b12dca7fa | 666,855 |
def rgb_to_hex(rgb):
"""Returns the hex color code for the rgb tuple."""
hexcodes = ("%02x" % int(v * 255) for v in rgb)
return "#%s" % "".join(hexcodes) | b4f1b0e5491546732fe29e020320c7acddca2619 | 666,856 |
import numpy
def fit(model, packed, *args, **kwargs):
"""Fit model to packed data.
packed[0] is x, packed[1:] is sx.
args and kwargs are forwarded to the model.fit(...).
"""
data = packed.reshape(-1, packed.shape[-1])
labels = numpy.zeros(data.shape[0], bool)
return model.fit(data, label... | d03fa59a9fbb222c06697fc89fc4bdb9284bebe1 | 666,857 |
def ner(nlp_obj, corpus):
"""NER for a single sentence."""
doc = nlp_obj(corpus)
return [(ent.text, ent.label_, ent.start_char, ent.end_char) for ent in doc.ents] | 81b160a7a59383c39325f88c3c3613c7f1783dd4 | 666,858 |
def _num_frame_valid(nsp_src, nsp_win, len_hop):
"""Computes the number of frames with 'valid' setting"""
return (nsp_src - (nsp_win - len_hop)) // len_hop | eeaa97c550018125d0e07c0a4d3c103f83f427b7 | 666,859 |
import os
def extract_name(path_file):
""" Extract graph name from path """
path_splitted = os.path.split(path_file)
filename_splitted = path_splitted[1].split('.')
return filename_splitted[0] | 9459f20ecd45278d0decc646f953d0fa6f4d6b97 | 666,860 |
import os
import yaml
def check_file_existence(output_file: str) -> bool:
"""This functions checks if the file already exists on filesystem
Args:
output_file (str): File location
Returns:
bool. The return code::
False -- If the file not exists or is blank
True -- I... | dcb3e3ac464098b32dd36a4bcdbf86c43e57db8d | 666,861 |
def maeConfig(argument_parser):
"""
Set CLI arguments
:param argument_parser: argument parser
:type argument_parser: ```ArgumentParser```
:returns: argument_parser
:rtype: ```ArgumentParser```
"""
argument_parser.description = """Computes the mean absolute error between labels and pred... | ac73f73a403964a0b73705ce4b274858204b4574 | 666,862 |
import os
def get_latest_mod(src_file):
"""
Gets the last modification date of
the specified file.
"""
# Get date of latest modification
stats = os.stat(src_file)
latest_mod = stats[8]
return latest_mod | f3e83cbde7bccf1225fbca5e82dda9df53abdbd0 | 666,863 |
def valid_symbol(symbol):
"""Returns whether the given symbol is valid according to our rules."""
if not symbol:
return 0
for s in symbol:
if not s.isalnum() and s != '_':
return 0
return 1 | 00f9ea9c722a855845b68a09572475a264dd4afd | 666,864 |
def slice(ds, idx_start, idx_stop):
"""Retrieve a slice of the dataset."""
if type(ds) != tuple: raise TypeError("'ds' isn't a tuple")
if len(ds) != 2: raise ValueError("'ds' isn't a 2-element tuple")
if idx_stop < idx_start: raise RuntimeError("'idx_start' value of the range has a greater value then 'i... | b90ac1eb5ffcd380fedbd6aa813614a2034efa9f | 666,865 |
import re
def format_float(value):
"""Modified form of the 'g' format specifier."""
string = "{:g}".format(value).replace("e+", "e")
string = re.sub("e(-?)0*(\\d+)", r"e\1\2", string)
return string | bc8b6ecd9a28f449494ce790659123c60531480e | 666,866 |
def wc_diff(row):
"""字符串长度差"""
return abs(len(row["s1"]) - len(row["s2"])) | 6188814f1878efa39e0bf840a3b94c67e0376b8d | 666,867 |
def unlisted(fun):
"""decorator for methods that shouldn't be listed with list"""
fun.unlisted = True
return fun | 1b2e5625056b5a4b3ec089753503bcdc49a03d0e | 666,868 |
import hashlib
def keyhash(string):
"""Hash the string using sha-1 and output a hex digest. Helpful for anonymizing known_mods."""
return hashlib.sha1(string.encode('utf-8')).hexdigest() | 0e32320597d273f509cc3ab69980196129651586 | 666,869 |
def remove_query_string(url):
"""
Removes query string from a url
:param url: string with a url
:return: clean base url
"""
if not isinstance(url, str):
raise TypeError('Argument must be a string')
return url.split('?')[0] | 3aca0acfb898b5bd23535e128c0a487aca1220df | 666,870 |
def file_mode_converter(num: int):
"""
十进制mode 转 user:group:other mode
0444 <--> 292
444 --> 100 100 100(2) --> 292(10)
:param num: 十进制数字
:return: ser:group:other mode
格式:0ugo
"""
# 数字转二进制字符串
user = (num & 0b111000000) >> 6
group = (num & 0b111000) >> 3
other = n... | 266971fbef2655428cba13fa8f32f92903b5f899 | 666,871 |
def listify(i):
"""
Iterable to list.
"""
return list(i) | 4500b0488d99bfc37a376edbbd29a57e7b312c8b | 666,872 |
def get_sound_effect_for_answer(answer_was_right):
"""get the appropriate sound effect"""
print("=====get_sound_effect_for_answer fired...")
print("=====answer_was_right: " + str(answer_was_right))
if answer_was_right is None:
return ""
if answer_was_right:
return "<audio src=\"http... | 30966f2dc34848898b18a1cc6e33209095b6f2dd | 666,873 |
def aztec_xihuitl_date(month, day):
"""Return an Aztec xihuitl date data structure."""
return [month, day] | ad12ae0222aaef89accf1dc3c3af55bff0cf6c93 | 666,874 |
def intersect_bounds(
bbox0: tuple[float, float, float, float],
bbox1: tuple[float, float, float, float]
) -> tuple[float, float, float, float]:
"""Get the intersection in w s e n
Parameters:
bbox0: bounding coordinates
bbox1: bounding coordinates
Returns:
intersection coor... | a0318f72edca084c800999c9393203364de5d791 | 666,875 |
def bar(self, *args, **kwargs):
""" Make a bar plot
Wraps matplotlib bar()
See plot documentation in matplotlib for accepted keyword arguments.
"""
if len(self.dims) > 1:
raise NotImplementedError("plot can only be called up to one-dimensional array.")
return self._plot1D('bar',*args, *... | 2cb12d50e5c48e6d2b06c4947a1bea5e645f0e99 | 666,876 |
def auth_path(index, height):
"""Return the authentication path for a leaf at the given index.
Keyword arguments:
index -- the leaf's index, in range [0, 2^height - 1]
height -- the height of the binary hash tree
Returns:
The authentication path of the leaf at the given index as a list of nod... | ee17ebcae1bca3f89d72c545989c77c3e41d1c3f | 666,877 |
def scene_to_dict(scene, use_base64=False):
"""
Export a Scene object as a dict.
Parameters
-------------
scene : trimesh.Scene
Scene object to be exported
Returns
-------------
as_dict : dict
Scene as a dict
"""
# save some basic data about the scene
export = ... | b0bdda831ad0be259268c0c17eef83ee0eb6a0cc | 666,878 |
def get_environment(hostname):
"""Get whether dev or qa environment from Keeper server hostname
hostname(str): The hostname component of the Keeper server URL
Returns one of 'DEV', 'QA', or None
"""
environment = None
if hostname:
if hostname.startswith('dev.'):
environment ... | b5965347cd60f8a49b038ba6558cd1d2e3a24446 | 666,879 |
def _import_string(names):
"""return a list of (name, asname) formatted as a string"""
_names = []
for name, asname in names:
if asname is not None:
_names.append(f"{name} as {asname}")
else:
_names.append(name)
return ", ".join(_names) | f2081ba174e7383dbf2c88e66e7905e3f6e42a50 | 666,880 |
def _is_leap(year):
"""year -> 1 if leap year, else 0."""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) | af47e173570aefcad109216281f55f53c2be1e13 | 666,881 |
def clean_place_string(place_string):
""" takes e.g. 'St. Lorenzen (St. Michaelsburg)' and
returns the tuple ('St. Lorenzen', 'St Michaelsburg') """
first_place = place_string.split("(")[0]
lg = " ".join(place_string.split("(")[1:])
lg = lg.replace(')', '')
return(first_place, lg) | b397b34ee6e3c2a8e6aa655f3d66a8fd68bd4315 | 666,882 |
def IsDict(inst):
"""Returns whether or not the specified instance is a dict."""
return hasattr(inst, 'iteritems') | 280262355d162f6178971389ab8f18d489b86ec3 | 666,883 |
from typing import List
def get_migration_table_name(allowed_packages: List, current_package_name) -> str:
"""Convert Python package name to migration table name."""
package_name = allowed_packages[0]
if package_name == "all":
package_name = current_package_name
table = package_name.replace(... | 882b72742c6bf6904e11245c79a30ee8d0bbb653 | 666,884 |
import os
def config_from_env(prefix):
"""
Configure from the environment based on expected prefix of environment
variables. Returned dictionary has the prefix + '_' stripped off and the
second part of variable name turned to lower case (for consistency with INI
parsing). E.g. LDAP_SEARCH_BASE is ... | 7551d36afd5fa85c56b23b5d7a03b4f5247942ef | 666,885 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.