content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def preço_final(preço, **kwargs):
"""
Preço final
-----------
Calcula o valor final de um produto.
args
----
preço : float
Preço inicial do produto
**kwargs
--------
imposto : float
Imposto sobre o preço (%)
desconto : float
Desconto... | 0efe232ca55e803b162bf460be83f00547571c81 | 685,316 |
def add_doubles_emd(x=float, y=float):
"""
return x+y;
"""
return float | 48f511998d91f46dfb0fa1b3289a6f3c51d2fa52 | 685,317 |
def convert_coordinates(value: str) -> float:
"""Convert coordinates to lat/long."""
if len(value) < 8:
return float(value[0] + "." + value[1:])
return float(value[0:2] + "." + value[2:]) | 3923c3aa85c0944e0d49b029122a3b6ba30492f6 | 685,318 |
def magnitude(vector):
""" get magnitude (length) of vector """
return (vector[0]**2 + vector[1]**2 + vector[2]**2) ** .5 | 6341599fa5c996cd6918e035a4133ef0562f26ea | 685,319 |
import os
def get_files_size(files):
"""!
@brief Return the sum of the size of all provided files.
"""
return sum(os.path.getsize(f) for f in files) | 45a1ee108d93878238b664f343847288e12cb9d8 | 685,320 |
def add_user(db, meeting_id, user_email, responded=False,busy_times=[]):
"""
@brief addds a user to a specific collection in our mongo database
@param mongo the "meetme" database
@param meeting_id a unique meeting_id, randomly generated and shared across multiple users
attending the ... | f75d2d99386e0e291b44d8952eddf1ae88b3fc74 | 685,321 |
def expandUrlData(data):
"""
dict -> a param string to add to a url
"""
string = "?" # the base for any url
dataStrings = []
for i in data:
dataStrings.append(i+"="+data[i])
string += "&".join(dataStrings)
return string | ed6cdd5748463fa8a6a3d7acefe608d5e74305aa | 685,322 |
def is_complete(board: list[list[int]]) -> bool:
"""
Periksa apakah papan (matriks) telah terisi penuh dengan nilai bukan nol.
>>> is_complete([[1]])
True
>>> is_complete([[1, 2], [3, 0]])
False
"""
return not any(elem == 0 for row in board for elem in row) | 6290771a2cc1c3d24ca603514d07cc93a9ce4406 | 685,323 |
import sympy
def airystressint(XA, XB, YA, YB, P, a, b, E, nu):
"""
Calculate integrals of strain energy values based on an Airy stress function
"""
x1, x2, xa, xb, ya, yb = sympy.symbols("x_1, x_2 x_a x_b y_a y_b")
sigma = sympy.Matrix([
[3 * P / (2 * a**3 * b) * x1 * x2],
[0],
... | 5cbce39d65b53e62c3728400e1ad8daf98cb7b61 | 685,324 |
def reverseVowels(s):
"""
:type s: str
:rtype: str
"""
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
L = list(s)
i = 0
j = len(L) - 1
while i < j:
while i < j and L[i] not in vowels:
i += 1
while j > i and L[j] not in vowels:
j -= 1
L[i], L[j] = L[j], L[i]
i += 1
j -= 1
return '... | e1f1c6dd9cc080fd81fc7e83e28f9fa51be34dfd | 685,325 |
import hashlib
import time
def generate_hash():
"""
Utility function generate will generate a hash on a timestamp.
"""
hash = hashlib.sha1()
time_str = str(time.time())
utf8_time_str = time_str.encode('utf-8')
hash.update(utf8_time_str)
return hash.hexdigest() | 0746aef9621a3c0cd326c7ea203beff0f6da30e3 | 685,326 |
def calc_route(centrex=400, centrey=300, halfwidth=200, radius=100):
"""This just calculates the 6 points in our basic figure of eight
should be easy enough and we then draw lines between each point and
get the last point
>>> calc_route(400, 300, 200, 100)
[(200, 400), (100, 300), (200, 200), (600,... | 769adee8e7454fee7afeda38e4df05f258e5e6ac | 685,327 |
def dggs_cell_overlap(cell_one: str, cell_two: str):
"""
Determines whether two DGGS cells overlap.
Where cells are of different resolution, they will have different suid lengths. The zip function truncates the longer
to be the same length as the shorter, producing two lists for comparison. If these lis... | 7a666846f37917b07ee74c8780868f540f280d21 | 685,328 |
import binascii
def decode_block_header(proto_block_header):
"""
Decodes the header of Block
Args:
proto_block_header (str): Block Header proto
Returns: Decoded BlockHeader inside Block instance.
"""
block_header = {}
block_header['number'] = proto_block_header.number
block_h... | 362c0ed474b13790a52d18df284cfa3d250e371b | 685,329 |
import subprocess
def cmd(command):
"""
쉘 명령 수행 후 Standard Output과 Standard Error를 리턴
:return: (bytes, bytes)
"""
popen = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
(stdoutdata, stderrdata) = popen.communicate()
return stdoutdata, stderrdata | eaf3cb54ec9b72c66be042d3358c5427cd46acd0 | 685,330 |
import torch
def BOnormalized(W, alpha = torch.tensor(1)):
"""
Adds `alpha` to the diagonal of `W`
Parameters
----------
W : (N, N) array_like
Similarity array from SNF
alpha : (0, 1) torch.tensor, optional
Factor to add to diagonal of `W` to increase subject self-affinity.
... | 2cba63c0dcff4ce6e25f2277e59e2a38c1a4ed55 | 685,331 |
def topological_sort(adjacency_list, visited_list):
"""
Topological sorting for Acyclic Directed Graph
"""
output_stack = []
def _topology_sort_util(vertex):
if not visited_list[vertex]:
visited_list[vertex] = True
for neighbor in adjacency_list[vertex]:
... | 32f2776c24abe4ebec1a15c7f04cc7ea949c66fe | 685,332 |
def hash_helper(df, i):
"""
tools for multy thread hash generator
"""
df['hash_' + i] = df[i].apply(hash)
return df[['hash_' + i]] | 063eb49001527807c1523befea0d5be1f14da724 | 685,333 |
def get_padding(kernel_size, dilation=1):
"""get padding size"""
return int((kernel_size * dilation - dilation) / 2) | 283915e15fd5d5b75156d6a0299579720ff281dc | 685,335 |
def groupms_byiconf(microstates, iconfs):
"""
This function takes in a list of microstates and a list of conformer indicies, divide microstates into two groups:
the first one is those contain one of the given conformers, the second one is those contain none of the listed conformers.
"""
ingroup = []... | c9c50f2dd8d0228b788f680aefe785a29b9a132c | 685,336 |
def normalize_json(item_y):
"""Converts a nested json string into a flat dict
"""
out = {}
def flatten(item_x, name=''):
"""Flatten nested string"""
if type(item_x) is dict:
for item_a in item_x:
flatten(item_x[item_a], name + item_a + '_')
elif type... | 634cbbc229640fee858528bd87f67b3fa063e636 | 685,337 |
import torch
def ones_like(input_, dtype=None):
"""Wrapper of `torch.ones_like`.
Parameters
----------
input_ : DTensor
Input tensor.
dtype : data-type, optional
Data type of output tensor, by default None
"""
return torch.ones_like(input_._data, dtype=dtype) | 61aeab959f113bb14393931fede11246dc687059 | 685,338 |
def pick_rand_param_perm_from_dict(param_pool, random_state):
"""
pick a parameter permutation given a list of dictionaries contain
potential values OR a list of values OR a
distribution of values (a distribution must have the .rvs() function to
sample values)
----------
param_pool : list of... | bbb566b0e0c22b05ed05ecc16ab1ef6fb2ef2e92 | 685,339 |
def get_bucket_and_key(s3_path):
"""Get the bucket name and key from the given path.
Args:
s3_path(str): Input S3 path
"""
s3_path = s3_path.replace('s3://', '')
s3_path = s3_path.replace('S3://', '') #Both cases
bucket, key = s3_path.split('/', 1)
return bucket, key | 4dc081f959a89c24653868b0ae9f297ed81d2589 | 685,340 |
def boiler_mode(raw_table, base_index):
""" Convert boiler mode to english """
value = raw_table[base_index]
if value == 4:
return "Summer"
if value == 5:
return "Winder"
return "Unknown" | 4f171ace2286f9e77aebd45027efaaf35c2741e1 | 685,341 |
def get_longitude_ref_multiplier(imgMetadata):
"""
Returns the longitude multiplier according to the
Exif.GPSInfo.GPSLongitudeRef EXIF tag contained in the imgMetadata dict.
"""
if imgMetadata['Exif.GPSInfo.GPSLongitudeRef'].value.lower() == 'w':
return -1
return 1 | 46fb8631b0b8f1f6d9d067761f2de4a14273710e | 685,342 |
import random
def calc_number(oef):
""" blah """
naam, low, high = oef
aantal = random.randint(low, high)
return (naam, aantal) | 9b788caf42df27f0378a2b933ad9cebc2e980d74 | 685,343 |
def args_to_string(args):
"""
Transform experiment's arguments into a string
:param args:
:return: string
"""
args_string = ""
args_to_show = ["experiment", "network_name", "fit_by_epoch", "bz_train",
"lr", "decay", "local_steps"]
for arg in args_to_show:
arg... | d2b1da8143af92d50cdbf07c1f61f0915f1980c7 | 685,344 |
def esc_format(text):
"""Return text with formatting escaped
Markdown requires a backslash before literal underscores or asterisk, to
avoid formatting to bold or italics.
"""
for symbol in ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']:
text = str... | 12770a69da56cd6e9de92a6a301857d42ee1381b | 685,345 |
import inspect
import sys
def hook_classes():
"""Return a list of all hook classes in the `ext` module."""
return [cls for name, cls in inspect.getmembers(sys.modules[__name__])
if inspect.isclass(cls) and hasattr(cls, 'hook_method')] | 993afbe5c91ed421edfc35e73484d36f8fe2eb17 | 685,346 |
def _count_lines(file_path):
"""Most simple line count you can imagine.
Returns:
A `int` for the line_count.
"""
count = 0
with open(file_path, "r") as fobj:
for line in fobj:
count += 1
return count | 78b748d0dc74d0fa91aeba5cbc4ca76f1cffa111 | 685,347 |
import json
def load_json(filename):
"""Loads a JSON file and returns a dict of its documents."""
docs = {}
with open(filename, encoding="utf-8") as fh:
lines = fh.readlines()
for line in lines:
doc = json.loads(line)
docs[doc["_id"]] = doc
return docs | 76565128ad98f3f125b0b1a3b13aaabbe5338e3b | 685,348 |
import requests
def get_advice():
"""
Calls the adviceslip API, and gets a piece of advice
:return: Advice in string
"""
response = requests.get(url='http://api.adviceslip.com/advice')
advice = response.json()['slip']['advice']
return advice | 2623c0e838e2cc3a3d832f16aae20bf1fc32494b | 685,349 |
def parse_index_file(filename):
"""Parse index file."""
index = []
for line in open(filename):
index.append(int(line.strip()))
return index | 461af60da32b21b2e98826c9a728f5bf09d9d516 | 685,350 |
def text_tostring(t, default=None, emphasis='emphasis', strong='strong', sup='sup',
fn_anc='fn_anc', fn_sym='fn_sym'):
"""Convert Text object to str.
Mark all styled text with special characters and return str
Example:
>>> t = [('Unmarked text. ', None), ('Text marked "emphasis".', ... | 85def71094b60d5ec0676b6551aa8449e043021e | 685,351 |
import dill
def block_worker(payload):
"""
Worker function used compute pairwise distance/similarity over a whole
block.
"""
similarity, block, serialized, graph = payload
if serialized:
similarity = dill.loads(similarity)
pairs = []
n = len(block)
for i in range(n):
... | 49209ca96aabf483c9485a639c7156f30b888d1b | 685,352 |
def calculate_diff_null(null_dist, reps): # pragma: no cover
"""
Helper function to calculate the distribution of thedifference under
null.
"""
diff_null = []
for i in range(0, reps - 1):
for j in range(i + 1, reps):
diff_null.append(null_dist[i][0] - null_dist[j][1])
... | 691662ba6ec380098cda2366a75010559dd755b2 | 685,353 |
def cli(ctx, metadata_id):
"""Returns a dictionary that includes information about a specified repository revision.
Output:
Returns a dictionary that includes information about a
specified repository revision.
For example::
{u'changeset_revision': u'7602de1e7f32',
... | de63ed30ced4ed860d91e732f58e26c0488f8e25 | 685,354 |
import click
def tar_add_filter(tarinfo):
"""Outputs a file progress counter while compressing file backups."""
msg = '\r{}/{} files packed.'.format(globals()['current_file_number'],
globals()['total_num_files'])
click.echo(click.style(msg, fg='yellow'), nl=False)
... | a064e3a87fcc54cf5560cd2dd9f49bdd45fb6766 | 685,355 |
def pretty_frame_name(frame_name):
"""omit some stdc++ stacks"""
pretty_names = (
('std::__invoke_impl', ''),
('std::__invoke', ''),
('std::_Bind', ''),
('Runnable::operator()', ''),
('std::thread::_Invoker', ''),
('std::thread::_State_impl', 'std::thread'),
... | f9f4ec24b81f6d3e5a86d8d6f98e00513a6c8c81 | 685,356 |
def repeat(f, x, n):
""" Repeat Function
>>> list(repeat(flatten, [1, 2, [3, [4]], 5], 2))
[1, 2, 3, 4, 5]
"""
if n == 0: return x
return repeat(f, f(x), n - 1) | 275289dbd4f827fedde6023ef461d20b1cbd50ca | 685,357 |
import glob
def setup_filepaths(data_path, participant_numbers):
"""Set up filepaths for reading in participant .h5 files.
Args:
data_path (str): path to directory containing .h5 files
participant_numbers (list): participant numbers for filepaths
Returns:
list: filepaths to all o... | b845ae2677e185936427fe8ba301cd5ee14f5855 | 685,358 |
def get_dividing_point(y: list):
"""
找出不同样例的分界点
Args:
y (list): 数据标签
Returns:
int: -1表示全部相同,否则表示分界点
"""
last = y[0]
for i, yi in enumerate(y):
if yi != last:
return i
else:
last = yi
return -1 | 9ec03107d1a340bb5464aae92db62b3e136abc04 | 685,359 |
def parse_imr_line(line):
"""
Parses a line of the IMR csv dataset to tupples
:param line:
:return: ( (label1 (int), label2 (int)), features(list of float) )
"""
sl = line.split(";")
if not sl[1].isdigit():
return
label1 = int(sl[1])
label2 = int(sl[2])
features = map(fl... | d9075a74f94a126489fcff75884456dfad4960b8 | 685,360 |
def remove_shallow_clusters(clusters, ncont_min):
"""From a list of contour clusters, remove those which are too shallow."""
if ncont_min == 0:
return clusters
deep_clusters = []
for clust in clusters:
# Retain if not outermost contour
if clust.parent is not None:
... | 748f7d904852f7f4050f135a0c0a717af0e45983 | 685,361 |
def storage_account_name_validate(name):
""" Check for valid storage account name """
if "." in name:
print("Storage account names cannot contain '.'")
return False
return True | 9801588c0437f10ebdbd69d1bb171b391f00f5fd | 685,362 |
def getDjangoURLPatterns():
"""Returns the URL patterns for the tasks in this module.
"""
patterns = [(r'tasks/surveys/projects/send_reminder/spawn$',
'soc.tasks.surveys.spawnRemindersForProjectSurvey'),
(r'tasks/surveys/projects/send_reminder/send$',
'soc.tasks.survey... | 79069dc43cc62536bed8e043fd3aedf7a9f4ad30 | 685,363 |
def _log_level_from_verbosity(verbosity):
"""Get log level from verbosity count."""
if verbosity == 0:
return 40
elif verbosity == 1:
return 20
elif verbosity >= 2:
return 10 | 6b60fde72e6c819827f137e5fa659fdfdcbfbed7 | 685,364 |
def completed_value():
"""Completed value test setup."""
return {
'deviceArn': 'arndevice',
'deviceParameters': 'parameters',
'outputS3Bucket': 'amazon-braket-bucket',
'outputS3Directory': 'complete/directory',
'quantumTaskArn': 'arntask',
'shots': 123,
's... | d39a7f12a374974f86de13f03c48a69c1882869a | 685,365 |
def show_fact_sheet_f(responses, derived):
"""
If one of the claimants earns over $150,000, Fact Sheet F is indicated.
"""
return derived['show_fact_sheet_f_you'] or derived['show_fact_sheet_f_spouse'] | d1ab65201afd733ebe3ea5728ad94a1dbcc820c5 | 685,366 |
def _fixops(x):
"""Rewrite raw parsed tree to resolve ambiguous syntax which cannot be
handled well by our simple top-down parser"""
if not isinstance(x, tuple):
return x
op = x[0]
if op == 'parent':
# x^:y means (x^) : y, not x ^ (:y)
# x^: means (x^) :, not x ^ (:)
... | 8b68af09c7072bc265c88d5658ce0b52feefb37b | 685,367 |
def intersects(region1, region2):
"""
Check if two regions intersect.
If regions share an end, they don't intersect unless one of the regions has zero length in which case they do
intersect.
Arguments:
region1 -- a first region.
region2 -- a second region.
Returns True if regions inter... | c0b0f2d376e89ed2c65de8dedc9ff62f6392032b | 685,368 |
def escape_text(s):
"""Convert a string to a raw Text property value that represents it.
s -- 8-bit string, in the desired output encoding.
Returns an 8-bit string which passes is_valid_property_value().
Normally text_value(escape_text(s)) == s, but there are the following
exceptions:
- all ... | 5b930b3150181466f5ebe6c38407f64db9e2d499 | 685,369 |
def group_numbers_in_radius(numbers, radius):
"""Group numbers into sublists with a given radius.
This is used for deduping - we want to make sure that
"""
results, before, after = [], [], []
print('group_numbers_in_radius', numbers, radius)
def emit():
result = before + after
if ... | 9fb832818470e30f7b3f9a2a0849bdb9c32e6265 | 685,370 |
import functools
import operator
def get_confidence(model, tag_per_token, class_probs):
"""
Get the confidence of a given model in a token list, using the class probabilities
associated with this prediction.
"""
token_indexes = [model._model.vocab.get_token_index(tag, namespace = "labels") for tag... | 7089dc157c2e9a7c637e4a27e9ddd26ee2505871 | 685,371 |
def _OP_regexp_total(context="bare"):
"""a function to store and explain the regexp used to scan formatch OPs"""
total="(?:" + "[^-+<>\[\],()*]*" + "(?:^+)?" + ")"
total=".*"
#An OP (without numerical prefix) is any number of signs that do not include -+<>[],()*
# followed by one or zero "^+" and t... | df36d611549978c10cbf997b9976ea2c02a8e68e | 685,372 |
def authn_args_gather(request, authn_class_ref, cinfo, **kwargs):
"""
Gather information to be used by the authentication method
"""
authn_args = {
"authn_class_ref": authn_class_ref,
"query": request.to_urlencoded(),
"return_uri": request["redirect_uri"],
}
if "req_user... | 727489be16515610418ed1f014c96994c59555f5 | 685,373 |
import re
import os
def filter_files(files_list, prefix, filter_patterns=('(.*[\\\\/])?\.git[\\\\/].*',
'(.*[\\\\/])?\.git$',
'(.*)?\.DS_Store.*',
'(.*)?\.g... | d803435a0a28c7a9f80355976ff6f159f37f5264 | 685,374 |
def gap_line(x, x0, y0, m):
"""
Return the y-value of the gap at the provided x values given.
Simply computes the function for a line
y = (x - x0) * m + y0
"""
return (x - x0) * m + y0 | 9df6f36e804d7629ad7f6e72ade981a5731ec9ba | 685,375 |
def normalise_sequence(input_sequence):
"""
Normalise a list or tuple to produce a tuple with values representing the proportion of each to the total of the
input sequence.
"""
return (i_value / sum(input_sequence) for i_value in input_sequence) | cbbe1948152834d9282a146d24a1584943fd7166 | 685,376 |
import os
def File_Exists(path):
"""
Returns true if file exist
:param path:Directory
:return:
"""
return os.path.isfile(path) | 65a9370c57390aecbb713897e5d64ff52b97fb0c | 685,377 |
def replace_all(text, dic):
"""
Replaces all occurrences in text by provided dictionary of replacements.
"""
for i, j in list(dic.items()):
text = text.replace(i, j)
return text | e838486cbc7f013e96c592ba9d761e7c23a6f448 | 685,378 |
def fermeture_image():
"""
génère la balise svg fermante. Doit être placée après tous les
éléments de description de l’image, juste avant la fin du fichier.
"""
return "</svg>" | 38270671ba763e3df47f00d79fc0876a3647ea25 | 685,379 |
def plantloopfieldlists(data):
"""return the plantloopfield list"""
objkey = "plantloop".upper()
numobjects = len(data.dt[objkey])
return [
[
"Name",
"Plant Side Inlet Node Name",
"Plant Side Outlet Node Name",
"Plant Side Branch List Name",
... | a722969820690690b5d70a1d9b0c3b28f4909994 | 685,380 |
import ast
def get_cast(dataframe):
"""
This function is to get information about actors
Input: dataframe
Output: list
"""
casts = []
for row_number in range(len(dataframe)):
cast = []
for cast_info in ast.literal_eval(dataframe.cast.to_list()[row_number]):
cast... | 76bb96744f04e6018652451beb19dce6cdb9eb4e | 685,382 |
def create_document1(args):
""" Creates document 1 -- an html document"""
return f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="font-family:sans-serif;margin-left:2em;">
<table>
<tbody style="border-collapse: collapse;border: 10px solid #d9d7ce; display: inl... | eff68b4b59cd1c1b5f60b2a0d3edf7e9b25130d8 | 685,383 |
def source_to_locale_path(path):
"""
Return locale resource path for the given source resource path.
Locale files for .pot files are actually .po.
"""
if path.endswith("pot"):
path = path[:-1]
return path | 6a2ca315e7bb2dfe03dede7c2be06602ff47cb40 | 685,385 |
def contentcmd(*args, **kwargs):
"""Decorator for bot commentary"""
def decorate(func, name=None):
setattr(func, '_jabberbot_content_command', True)
setattr(func, '_jabberbot_command_name', name or func.__name__)
return func
if len(args):
return decorate(args[0], **kwargs)
... | bf3db7412220f60ce63b4d8a4d5530c571f691cd | 685,386 |
import argparse
def parse_args():
""" Parse input arguments """
parser = argparse.ArgumentParser(description='SoundNet')
parser.add_argument('-o', '--outpath', dest='outpath', help='output feature path. e.g., [output]', default='PretrainedModel/')
parser.add_argument('-p', '--phase', dest='phase', h... | a80b94b83b68c50b135cb9aa70c5baaec65b9abb | 685,387 |
def is_arraylike(x):
"""
Determine if `x` is array-like. `x` is index-able if it provides the
`__len__` and `__getitem__` methods. Note that `__getitem__` should
accept 1D NumPy integer arrays as an index
Parameters
----------
x: any
The value to test for being array-like
Retur... | 516d37891dc73d134f7b88a13530aca35011b2d5 | 685,388 |
import random
import math
def roulette_index(n, random=random):
"""Randomly choose an index from 0...n-1. Choice has a weight of (index+1)."""
rouletteValue = random.randint(0, n * (n-1) // 2)
return math.ceil(-0.5 + math.sqrt(0.25 + 2 * rouletteValue)) | 410db3423f592b956af1e49a47fa8d59ff52b630 | 685,389 |
def calculate_interval(start_time, end_time, deltas=None):
"""Calculates wanted data series interval according to start and end times
Returns interval in seconds
:param start_time: Start time in seconds from epoch
:param end_time: End time in seconds from epoch
:type start_time: int
:type end_t... | fa681e9a8a0bf8b8a82d955e6ffb565264b145e5 | 685,390 |
def do_something5(a, b, c=None):
"""Do something.
"""
return a + b if c else 0 | e14022e55675accd7026d8a21bdec486a283fce8 | 685,391 |
def fpOutlierCleaner(pred, x, y):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the form (x, y, error).
"""
... | 837e4f8b88f33d2a2e0a62d3a7225b925b5a4e88 | 685,392 |
def getContainers(name):
"""
getting the id of the container
:param name:
:return:
"""
return "docker ps -aqf name={}".format(name) | 646b31e72c2813ec6cec4b9cfbd70dab3dcebd8c | 685,393 |
def flatten(x: dict, prefix="", grouped=True) -> dict:
"""Flattens dictionary by a group (one level only).
Arguments:
x {dict} -- Dictionary to be flattened.
Keyword Arguments:
prefix {str} -- Group prefix to flatten by. (default: {''})
grouped (bool) -- True if parameters are inte... | fa1e402bed2027d478ca1b29d9274c43a26fa980 | 685,394 |
def get_repo(name, data, type_):
"""
@param name: resource name
@param data: rosdoc manifest data
@param type_: resource type ('stack' or 'package')
"""
return data.get('repo_name', '') | eb0f3f67c95782827dc3546b4381d04409c676d0 | 685,395 |
def intron_finder(read, read_start, read_end, args):
"""
Finds introns based on the cigar code. Also filters introns based on the
first_exon argument and removes introns which contain a long insertion
preceding the intron (likely triple-chimeric reads).
"""
introns = ()
counter = 0
prev... | 8c49e48f4e720c25921c5176a7d1eb3e04888bbd | 685,396 |
from pathlib import Path
import tempfile
import os
def create_tempdir(base_dirname: str) -> Path:
"""
Creates a new tempdir in the default temp location.
Remark: the temp dir won't be cleaned up automatically!
Args:
base_dirname (str): The name the tempdir will start with. A number will
... | ce3138caedec6a91d48f2d2d10cea365c5213db1 | 685,397 |
import os
def find_python_module_path(module):
"""Find the location of a given python package
Args:
module: given Python module
Returns:
The path of the Python module
"""
proc = os.popen("python -c import %s;print(%s.__path__[0])" %
(module, module))
outpu... | ec7a849fb008ad604b1fef39c1c15846b06a397e | 685,398 |
from typing import Mapping
def _parse_columns(columns):
"""Expects a normalized *columns* selection and returns its
*key* and *value* components as a tuple.
"""
if isinstance(columns, Mapping):
key, value = tuple(columns.items())[0]
else:
key, value = tuple(), columns
return ke... | 9b6f368fa6af69fdbf149799f040eaa3df6a811b | 685,400 |
import os
def findFileWithExtension(filePath, extensions):
"""Find a file name in the given path with the given extension"""
try:
fileNames = os.listdir(filePath)
except:
print("Folder", filePath, " not found")
return
for fileName in fileNames:
ext = os.path.splitext(fileName)
if ext[1] ... | 5038c2ce4d7ef59f758f023d6156873b4ced5120 | 685,402 |
from bs4 import BeautifulSoup
import re
def review_to_wordlist(review):
"""
Function to convert a document to a sequence of words.
Returns a list of words.
"""
# Remove HTML
review_text = BeautifulSoup(review).get_text()
#
# Remove non-letters
review_text = re.sub("[^a-zA-Z]"," ", ... | 837cd5cf942130906fbeae90945b008f82ea195e | 685,403 |
def _IsNamedTuple(x):
"""Returns whether an object is an instance of a collections.namedtuple.
Examples::
_IsNamedTuple((42, 'hi')) ==> False
Foo = collections.namedtuple('Foo', ['a', 'b'])
_IsNamedTuple(Foo(a=42, b='hi')) ==> True
Args:
x: The object to check.
"""
return isinstance(x, tupl... | 93c7438f5472c8d8b95b48aaced4833e0632c3c7 | 685,404 |
import traceback
import sys
def format_exception(msg, *args, **kwargs):
"""
Given an exception message string, uses new-style formatting arguments
``{filename}``, ``{lineno}``, ``{func}`` and/or ``{text}`` to fill in
information about the exception that occurred. For example:
try:
... | f4f3bd08d58d6477deca902554b9f62cef9dae15 | 685,405 |
import yaml
import re
import os
def write_dflt_file(tmpl_file, parameters_file, run_duration=1.0):
"""Create a model input file populated with default values.
Parameters
----------
tmpl_file : str
The path to the template file defined for the model.
parameters_file : str
The path to t... | 86ff6aae10ddd2b9a3e3ea2cf50c5026196f45b9 | 685,406 |
def MaybeAddColor(s, color):
"""Wrap the input string to the xterm green color, if color is set.
"""
if color:
return '\033[92m{0}\033[0m'.format(s)
else:
return s | ca082aecae9bf62d8569c030b4bdf7ed6f7cad3d | 685,407 |
def _memory_usage(df):
"""Return the total memory usage of a DataFrame"""
return df.memory_usage(deep=True).sum() | 595b947d75df08b34bcaaf72b3023a5e86268d45 | 685,408 |
import argparse
def _parser() -> object:
"""Take care of all the argparse stuff.
:returns: the args
"""
parser = argparse.ArgumentParser(description='Baraffe table Query.')
parser.add_argument('column', help='Input fits file to calibrate',
choices=["M/Ms", "Teff", "L/Ls", ... | c3181247a558d39b0535ec35ed8b3874b58f1d4f | 685,409 |
import math
def sinc(x):
"""Supporting sinc function
"""
if (abs(x) < 1.0e-4):
return 1.0
else:
return(math.sin(x)/x) | 92af9d777a9ad6e4840cc359b97ba8bce858fd0f | 685,410 |
import os
def user_directory_path(instance, imagename):
""" Should upload to MEDIA/uploads/username/imagename """
return os.path.join("uploads", instance.patient.user.username, imagename) | 59cb54bc4e8a3b8d1781b85e2936f78057a48f45 | 685,411 |
from typing import List
def assert_empty_line_between_description_and_param_list(
docstring: List[str]
) -> List[str]:
"""
make sure empty line between description and list of params
find first param in docstring and check if there is description above it
if so, make sure that there is empty line ... | d03eb05064609928020c84785b561cd6b7bfa1f6 | 685,412 |
import subprocess
def call_external_program(*args):
"""
Provides uniform interface to subprocess.check_output.
Regardless of the external program's exit code, this always returns a tuple
of the return code and the output string (including stderr).
"""
try:
output = subprocess.check_ou... | f18bc90ca13fb9946d367af3d185a569a9eefd03 | 685,413 |
def token_sub(request):
"""Returns the sub to include on the user token."""
return request.param if hasattr(request, 'param') else None | 8cb5b0783e7333aa83c65ae8f57414e6f588550e | 685,414 |
def int2color(x):
"""
converts lattice integer to RGB tuple
:param x: int
:return: RGB
"""
# r = int(1000 * x % 255)
# g = int(10000 * x % 255)
# b = int(100000 * x % 255)
x = 0 if x == 0 else int(1/x)
b = x & 0xff
g = (x >> 8) & 0xff
r = (x >> 16) & 0xff
return [r, g... | f0faaf6cbb7656928f474d06b61f74bf96653a8e | 685,415 |
import re
def clean_text(training_corpus):
""" Function used for cleaning text from data that follows the format of the Brown corpus. Closed
category words and punctuation are not removed to be able to ensure that training sentences are
syntactically sound. The first return value is a list that co... | 5f55c7698e86ca66e54a0a552ecd5476ff10c475 | 685,417 |
def isAcronym(word):
"""
Is the given word an acronym (separated by periods, so it doesn't end a
sentence)? cf. lots of interesting acronyms, e.g. this is one. solve for
x. a.b.c. is also one. You might also want to give an example
parenthetically (e.g. this one).
"""
word = word.strip("... | dbdb869d850d776433d644037d063faec512e086 | 685,418 |
def _get_single_wdr_with_qw_sel(asm_str):
"""returns a single register from string with quad word select and check proper formatting (e.g "w5.2")"""
if len(asm_str.split()) > 1:
raise SyntaxError('Unexpected separator in reg reference')
if not asm_str.lower().startswith('w'):
raise SyntaxErr... | 436caef3f2b32231d1d13d6d7eb84cb0f769cacb | 685,419 |
def check_has_join(subject, object):
"""CHECK_HAS_JOIN
DESCRIPTION: Determine whether SQL query has join in WHERE conditions. Used as a
flag for separate query result processing.
INPUT:
- subject of WHERE clause of SQL query
- object of WHERE clause of SQL query
OUTPUT: result: ... | 340c757689c8d04a7ed8251d179b4c9a85851385 | 685,420 |
async def index():
"""
Home Path for API
"""
return {
"Welcome to": "Unofficial Fiverr API",
"For docs": "Visit /docs",
"For redocs": "Visit /redoc",
} | e28e2f19d072276818b837a7dd8eeecc1504ebec | 685,421 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.