content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def predecesseurs(m, s):
"""Renvoie les prédécesseurs du sommet s de la matrice d'adjacence m.
Les prédécesseurs se lisent sur la colonne s de m.
"""
pred = []
for i in range(len(m)):
if m[i][s] == 1:
pred.append(i)
return pred | b06c66c73dc8e92eb3298154a4517480fac2a97d | 663,544 |
def get_recent_signals(zakenDataset, n=100):
"""Create a list the n most recent ICTU signals from our data."""
signals = zakenDataset.data.sample(100) # INSTEAD OF PICKING THE MOST RECENT SIGNALS, WE TEMPORARILY RANDOMLY SAMPLE THEM FOR OUR MOCK UP!
signals.drop(columns=['woonfraude'], inplace=True) # For... | 354ed9578ed53e8db8a8226eaaf12d26e5c96c29 | 663,545 |
import torch
def s2s2_gram_schmidt(v1, v2):
"""Normalise 2 3-vectors. Project second to orthogonal component.
Take cross product for third. Stack to form SO matrix."""
u1 = v1
e1 = u1 / u1.norm(p=2, dim=-1, keepdim=True).clamp(min=1E-5)
u2 = v2 - (e1 * v2).sum(-1, keepdim=True) * e1
e2 = u2 / ... | 304d8e0ed133b40487020acd13631bf4cf584ee8 | 663,546 |
def operKey(obj, field):
""" generate operate Key """
return "%s:id:%s:%s" % (obj.__class__.__name__, obj.id, field) | 65045044329fc14ced8adb45eea0f8c9394b6757 | 663,548 |
def metacalibration_names(names):
"""
Generate the metacalibrated variants of the inputs names,
that is, variants with _1p, _1m, _2p, and _2m on the end
of each name.
"""
suffices = ['1p', '1m', '2p', '2m']
out = []
for name in names:
out += [name + '_' + s for s in suffices]
... | 1c1783db3dbd82239ccb2052b79280f7bde4a5b2 | 663,549 |
def loadLines(fileName, fields):
"""
:param fileName:
:param fields:
:return: lineObj = {lineID:L1045, characterID:u0, movieID:m0, character:BIANCA, text:They do not!}
lines = {lineID: lineObj
lineID: lineObj}
"""
lines = {}
with open(fileName, 'r', encodin... | cfd74cdcbe5a8744173d379f468af4a36f10ddce | 663,550 |
def session_save_path(interp, path=None):
"""Get and/or set the current session save path"""
w_act = interp.config.get_ini_w('session.save_path')
if not path:
path = ""
interp.session.save_path = path
else:
interp.config.set_ini_w('session.save_path', interp.space.wrap(path))
... | d2eed6ba461862593ad5c689b203b1137f702137 | 663,551 |
def to_decimal_place(x, decimal_place=2):
"""
Correct the number to some decimal place
:params decimal_Place: decimal place I want to pick
"""
decimal = '{0:.%sf}' % decimal_place
return float(decimal.format(x)) | 5fc342efa5c5c7f820f6ecc514b2e4537b1dd30a | 663,552 |
def convert(number):
"""
Convert a number to a string of raindrop sounds.
param: int number
return: str formatted string based on input
"""
if number % 7 == 0 and number % 5 == 0 and number % 3 == 0:
return "PlingPlangPlong"
if number % 7 == 0 and number % 5 == 0:
return "P... | 82fc137cc1c5e07f561707d719d739f8ceef4796 | 663,554 |
def generate_bq_schema(df, default_type='STRING'):
""" Given a passed df, generate the associated big query schema.
Parameters
----------
df : DataFrame
default_type : string
The default big query type in case the type of the column
does not exist in the schema.
"""
type_ma... | 1bc7ea1491fd2706bf6994bb50fefd831ba25b45 | 663,556 |
def getNamespaceUnversioned(string: str):
"""getNamespaceUnversioned
Gives namespace of a type string, version NOT included
:param string:
:type string: str
"""
if '#' in string:
string = string.rsplit('#', 1)[1]
return string.split('.', 1)[0] | 942ca50f3168124fd6935ac97a069a8519e0559a | 663,557 |
def assign_w(w_gate, w_gate_unc, w_censored, results_fut_zj, zj_idx):
"""Reduce repetetive code."""
w_gate[zj_idx, :, :, :] = results_fut_zj[4]
w_gate_unc[zj_idx, :, :, :] = results_fut_zj[5]
w_censored[zj_idx, :, :] = results_fut_zj[7]
return w_gate, w_gate_unc, w_censored | a7ca1a3c29264f3a5679b07cf6d15515c583cbd0 | 663,558 |
import six
import string
def validate_apns_token(token_str):
"""Validate an APNS token
These are 32 byte identifiers encoded as a hex string.
"""
if not isinstance(token_str, six.string_types):
return False
token_str_stripped = token_str.strip()
if len(token_str_stripped) != 64 or not ... | 4f199a26d137882d81e2e3b00746907637819a64 | 663,560 |
def MultiplyTwoNumbers(a,b):
"""
multiplying two numbers
input: a,b - two numbers
output: returns multiplication
"""
c = a*b
return c | ee083b6133de4e2c8da434b937dd801d074ae31b | 663,561 |
import string
import re
def remove_special_chars(text):
"""remove all special characters except the period (.)
comma (,) and question mark (?)
for instance, ">", "~", ", $, |, etc.
"""
schars = ''.join([a for a in string.punctuation if a not in ".,?"])
text = re.sub('[%s]' % re.escape(s... | 93b9846af47e95aaa686f22fda3efb76f543a45d | 663,562 |
def load_state_dict(network, state_dict):
"""
restore model from state_dict
"""
network["feat_model"].load_state_dict(state_dict["feat_model"])
network["classifier"].load_state_dict(state_dict["classifier"])
# for name, param in state_dict["feat_model"].items():
# print(name, "\t", ... | b9c25f45b93c379198084fbadb926543a5828298 | 663,563 |
def days_since(t1, t2):
"""
Returns the number of days between two timestamps.
:param t1: Time one.
:param t2: Time two.
"""
timedelta = t1 - t2
return timedelta.days | 9ed73a98fcb2dcde9f3317b7785bfc1bd074a23f | 663,564 |
def replicate(l):
"""
Replicates if there is only one element.
"""
if(len(l) == 1):
l.append(l[0])
return l | 4cca1426e97363b6881203b35f0556e4d061c406 | 663,565 |
import os.path
import json
def read_shm(fil):
"""Read exitsing jobstats file and return decoded json"""
jobinfo = {}
if(os.path.exists(fil)):
with open(fil) as fp:
jobinfo=json.loads(fp.read())
return jobinfo | 17bed94a4d5b4e8ead7fba4c3911ceae90542199 | 663,566 |
def percentage_to_mark(percentage):
"""Transform percentage values to mark label."""
thresholds = {
99: 'A+++',
95: 'A++',
90: 'A+',
80: 'B',
70: 'C',
60: 'D',
50: 'E',
40: 'F'
}
for threshold, mark in thresholds.items():
if percent... | a601a22dff52d84fa67eccc3b224d1c42d105f9e | 663,568 |
def minke_session_switch(context):
"""
Render the session-switch-bar.
"""
return context | 930a73655012086505c6d3c3c2a9dc7478df40e6 | 663,569 |
import re
def substitute(line, regex, class_):
"""Generate a span and put it in the line per the regex."""
result = re.search(regex, line)
if result:
for match in result.groups():
line = line.replace(
match, '<span class="{}">{}</span>'.format(class_, match), 1
... | a5c96b3550371c085cfff21c0e7bb128642793b1 | 663,570 |
def ceildiv(a, b):
"""Divides with ceil.
E.g., `5 / 2 = 2.5`, `ceildiv(5, 2) = 3`.
Args:
a (int): Dividend integer.
b (int): Divisor integer.
Returns:
int: Ceil quotient.
"""
return -(-a // b) | 2fb7849ac6ad823e4259672d29cc96b9bfef3d3f | 663,571 |
def flatten(lst):
"""Flatten a 2D array."""
return [item for sublist in lst for item in sublist] | 74dac38eff7b7eec3254dbc2fa49287f25552ad8 | 663,572 |
def proto_name(s):
"""Return the name of the proto file
>>> proto_name('foo.proto')
'foo'
:param s:
:return:
"""
return s.split('.')[0] | 5cc9c3550cbde04777abceeaf3033b2111e50741 | 663,573 |
def lcfa_pattern(tmp_path):
"""Fixture to mock pattern for LCFA files."""
return str(tmp_path / "lcfa-fake" /
"lcfa-fake-{year}{month}{day}{hour}{minute}{second}-"
"{end_hour}{end_minute}{end_second}.nc") | 6a2ca379692fc61f6a17ff3198a7cbe2a09b1181 | 663,574 |
def leverage(balance_df):
"""Checks if the leverage exposure was reduced since previous year
Explanation of Leverage: https://www.investopedia.com/terms/l/leverage.asp
balance_df = Balance Sheet of the specified company
"""
# current year
assets_curr = balance_df.iloc[balance_df.index.get_l... | 2e528e959bade3f3de875429eb1a1289c8a77d52 | 663,575 |
import json
import os
def load_regex():
"""Loads the regex strings from the file into a dict."""
return json.loads(
open(
os.path.abspath(os.path.dirname(__file__)) + "/regex.json", "r"
).read()
) | 04449f5911808edce1dfae6e379cf61d03ba0e50 | 663,576 |
from typing import OrderedDict
def makeSubstitutionInTweet(texte,rempla):
""" on traite toutes les substitutions à faire dans tweet.text avec cette
fonction, qui les prend en fonction de leur position initiale. On travaille
en partant de la fin, pour ne pas avoir à faire de décalages par rapport
aux p... | 722188c957fbb70775dfad9245e7ef0f2e2ec8f0 | 663,577 |
import os
def batchbubblekicker(data_path, channel, pipeline, *args):
"""
Given a folder with processable files and a channel to use, a sequence
of steps class as implemented in the pipelines.py file will be applied on
each of the individual images
:param data_path: folder containing images to pr... | b891d7bfad377d0bfaa6ce30641dfb84a932243f | 663,578 |
def get_progress(context, scope):
""" Returns the number of calls to callbacks registered in the specified `scope`. """
return context.get("progress", {}).get(scope) | cd0f827c3bf1f548a51dce992949b804d6b97aba | 663,579 |
def fread(path):
"""Reads a file."""
with open(path, 'r') as file:
return file.read() | 4c80975e324286e0b95298fc8c12c8670c6b60ed | 663,580 |
def get_column(a, j):
"""the column of a matrix"""
return [a_i[j] for a_i in a] | a62deec4c66f9d667dc06cb5187a9815330ac124 | 663,581 |
def Multiply_by_number(matrix_1, number): # умножение матрицы на число
"""
Функция, которая умножает матрицу на число
:params matrix_1: матрица
:params matrix_2: число, на которое необходимо умножить матрицу
:return matrix_out: матрица, как результат
"""
matrix_out = []
for... | a62c8b08be1d6947176a622d1eae059f31e29907 | 663,582 |
def apply_supported_whitelist(compiler, whitelist, target):
"""Generate a list of supported targets for a given compiler and post-binary hook
white-list."""
if compiler not in target.supported_toolchains:
return False
if not hasattr(target, "post_binary_hook"):
return True
if target.... | 24eae08e51a67ebba75ceabcac6f8f202813847c | 663,583 |
import yaml
import glob
def load_config(params):
"""
Prepare configuration dictionary.
"""
config = {}
if params.data[0].endswith('.yaml'):
with open(params.data[0]) as f:
config = yaml.load(f, Loader=yaml.FullLoader)
config['data_path'] = sorted(glob.glob(config['data_path']))
else:
con... | d8b3cee5174c32cd52f43927ae76e06597587f9f | 663,585 |
def sort_high_scores(scores, highest_possible_score):
"""Returns the high scores sorted from highest to lowest"""
if type(scores) != list:
raise TypeError(
"The first argument of sort_high_scores must be a list.")
if type(highest_possible_score) != int:
raise TypeError(
... | 3dadebc3d5c74ecd1bb5e0838b971c694a44ed12 | 663,587 |
def filter_products(queryset, user):
"""
Restrict the queryset to products the given user has access to.
A staff user is allowed to access all Products.
A non-staff user is only allowed access to a product if they are in at
least one stock record's partner user list.
"""
if user.is_staff:
... | 6189b05e41f2408d85bd22a850b3eea36d26f744 | 663,588 |
from typing import Any
def arg_dict_creator(string: Any):
"""Creates a Dict from a CSV string.
Args:
string(str): CSV string - formatted as 'field1:value1,field2:value2'.
Returns:
Dict from string representation.
"""
if not string:
return None
split_string = string.s... | 7c0d5d2b02a3a0cca7bf1f2dbf0946aabb7a5aea | 663,589 |
def create_dicts_by_chain(keys_chain: list):
"""
Create nested dicts by keys chain
>>> create_dicts_by_chain(['some', 'keys'])
{'some': {'keys': {}}}
"""
result = {}
current_dict = result
for key in keys_chain:
current_dict[key] = {}
current_dict = current_dict[key]
r... | 03ab93fbe62a59e539fd150ab1277c4377fd6739 | 663,590 |
import math
import numpy
def axis_angle_to_quaternion(n, theta):
"""OI
"""
c = math.cos(theta/2)
s = math.sin(theta/2)
quat = numpy.zeros((4,1))
quat[0] = c
quat[1:] = n*s
return quat | 45b73533e04816df8619ae7a0a806bf387103897 | 663,591 |
def extract_text_from_file_ld(filename):
"""
text extraction rule for livedoor corpus
"""
table = str.maketrans({
'\n': '',
'\t': ' ',
'\r': '',
})
with open(filename) as text_file:
# 0: URL, 1: timestamp
text = text_file.readlines()[2... | e310c368d59bb4c5ec87b7d91f199a2388e126b7 | 663,592 |
def nested_update(d, u):
""" Courtesy of:
http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
"""
for k, v in u.iteritems():
if isinstance(v, dict):
r = nested_update(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[... | 2e6bf70d9474b539c46cecfb0d4d7a013de7bc42 | 663,593 |
def load_collection(path):
"""Loads tsv collection into a dict of key: doc id, value: doc text."""
collection = {}
with open(path) as f:
for i, line in enumerate(f):
doc_id, doc_text = line.rstrip().split('\t')
collection[doc_id] = doc_text.replace('\n', ' ')
if i % 1000000 == 0:
pri... | 3813b229560e11959d135de1be62659aed8b06af | 663,594 |
def test_pos_only_call_via_unpacking(a, b, /):
"""
>>> test_pos_only_call_via_unpacking(*[1,2])
3
"""
return a + b | 835a12792583c74f3e2bc51e9adc20ce6eafe52e | 663,595 |
def sampleIdsFromNode(node, cladeTops=()):
"""Return a list of IDs of all samples found under node."""
kids = node.get('children')
if (kids):
sampleIds = []
for kid in kids:
if (kid not in cladeTops):
sampleIds += sampleIdsFromNode(kid, cladeTops)
else:
... | 7832e7916d917cb1e4fe848a6094516c2dc1c913 | 663,596 |
import re
def process_for_latex(string):
"""Returns a LaTeX-ready string, without spaces or integers."""
int_to_str = {0: "zero", 1: "one", 2: "two", 3: "three", 4: "four",
5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine"}
latex_string = string.replace(" ", "")
lst = re.findall... | 7b433538f9b7452ccea81e3a7efde43bcfd57673 | 663,597 |
import argparse
def get_parser():
"""Build argument parser for TGAN CLI utility."""
parser = argparse.ArgumentParser(description='TGAN Command Line Interface.')
parser.set_defaults(function=None)
action = parser.add_subparsers(title='action', dest='action')
action.required = True
experiments... | 84c785f8a63f8ee88996cb4177579e518cff1a68 | 663,599 |
def get_axes_bounds(fig):
"""Return the entire axes space for figure.
An axes object in mpl is specified by its relation to the figure where
(0,0) corresponds to the bottom-left part of the figure and (1,1)
corresponds to the top-right. Margins exist in matplotlib because axes
objects normally don'... | e96c81ae16c8aa9eea0173f40d9bf8b81f7a0945 | 663,600 |
def goldstein_price_function(x):
"""https://www.sfu.ca/~ssurjano/goldpr.html"""
return ((1 + (19 - 14 * x[0] + 3 * x[0]**2 - 14 * x[1] + 6 * x[0] * x[1] +
3 * x[1]**2) * (x[0] + x[1] + 1)**2) *
(30 + (18 - 32 * x[0] + 12 * x[0]**2 + 48 * x[1] -
36 * x[0] * x[1] +... | a0811ed2f45241f193f1575c6840bed9b511ae05 | 663,602 |
def filter_price_list(converted_prices, recommended_length, couples):
"""Makes sure that products with too big of a leveshtein
length won't pass further down the decisions tree"""
filtered_rice_list = []
for i in range(1, len(couples)):
if couples[i][1] == recommended_length:
filtere... | e90f1ee9f9f52a7d5c75be59a8ef8e214cf61734 | 663,603 |
def check_date_format(date):
"""check if date format fits the DD/MM/YYYY format"""
if len(date) != 10:
return False
if(date[0:1].isnumeric() is False or
date[3:4].isnumeric() is False or
date[6:9].isnumeric() is False):
return False
if date[2] and date[5] != ".":
re... | e82a32700be23234a813809ff7050c127c876fe7 | 663,604 |
def is_palindrome(x):
"""
>>> is_palindrome(121)
True
>>> is_palindrome(123)
False
"""
return str(x) == str(x)[::-1] | 6fd6000fc7af824e09c8e2034a7e0f9455cf448b | 663,605 |
def dense_flops(in_neurons, out_neurons):
"""Compute the number of multiply-adds used by a Dense (Linear) layer"""
return in_neurons * out_neurons | e9f35b2f1d7cad7c8e47f75983f806881d293ffa | 663,606 |
def areAgentsSame(agent1, agent2):
"""Check that agents' underlying structures are the same"""
agent1dict = agent1.__dict__
agent2dict = agent2.__dict__
to_find_common = {'constraint_generator', 'epsilon', 'feature_set', 'function_set', 'last_state',
'ret_train_expl', 'rhs_by_labe... | 7ad0d4e597a370f846677a9e2d6dcc59d48aea1f | 663,609 |
import requests
def getexp_fromqueue(token):
""" """
auth_token = "Token " + token
url = "http://127.0.0.1:8000/api/experiments/queue"
payload = {}
headers = {
'Authorization': auth_token,
# 'Cookie': 'csrftoken=a6IwyqS4I5vjwcNAT5Tm70PuiK7AFjcDVPHbyZy3I189V7eX5iK2m0AwJQoYyVUb; ses... | 8a37b0419a5c1f2fb10d3b9bcbbd0a9bf5dab697 | 663,610 |
import os
def check_presence_of_files(filenames):
"""check for the presence/absence of files
Parameters
----------
filenames : list
Filenames to check for presence.
Returns
-------
missing : list
List of missing filenames
"""
missing = []
for filename in file... | 31c3d135e221bcc55d8dcf848f57e124315b6e40 | 663,611 |
import torch
def replace_leaky_relu_mixed_integer_constraint(negative_slope,
x_lo,
x_up,
dtype=torch.float64):
"""
For input x ∈ [x_lo, x_up] (and x_lo < 0 < x_up), t... | 051956aaa35f192e13a58fca1e5496cebf100070 | 663,612 |
def filter_orders(pair, orders, minvolumes):
"""
fetch orders with appropriate sizes
:param pair: trading pair
:param orders: dict with orders in form {
'asks': [],
'bids': [],
... | 86243eee945633a4cfddfc89057ae73fad24a2ed | 663,613 |
def calc_beats(data, rpeak_locs, metrics):
"""Returns the times when R-peaks occur
Args:
data (2D numpy array): contains two columns with time and ECG data
rpeak_locs (1D numpy array): contains locations of R-peaks
metrics (dict): dictionary containing the metrics calculated
... | 6491e104d85bb251430f752b780e5f7a1c82bac0 | 663,614 |
def majority_vote(votes, minimum_count=3):
"""Determine the label voted for by the majority
Given a list of binary votes we compute the preferred label
based on a simple majority vote if there are atleast `minimum_count`
votes.
Returns the binary label or `None` if there are not enough votes
"... | c90e04df5b6f11272e55f9f667ccc5af9568e23d | 663,615 |
def pluralize(n, text, suffix='s'):
# type: (int, str, str) -> str
"""Pluralize term when n is greater than one."""
if n != 1:
return text + suffix
return text | 4c186689474f4b761070214a074cfa3cf91d005d | 663,616 |
def shortest_path_tree(g, s, d):
"""Reconstruct shortest-path tree rooted at vertex s, given distance map d.
Return tree as a map from each reachable vertex v (other than s) to the
edge e=(u,v) that is used to reach v from its parent u in the tree.
"""
tree = {}
for v in d:
if v is not s:
for e in... | f2bf948469b601a8074f5837f1dd52f8f926fa25 | 663,617 |
def bolt_min_dist(d_0):
"""
Minimum bolt spacing.
:param d_0:
:return:
"""
e_1 = 1.2 * d_0
e_2 = 1.2 * d_0
e_3 = 1.5 * d_0
p_1 = 2.2 * d_0
p_2 = 2.4 * d_0
return e_1, e_2, e_3, p_1, p_2 | 9903da06c7395fb1b77f3433c9c6735bbba03d39 | 663,618 |
import sys
import os
def get_user_data(error):
"""Function gets data from user
Args:
error (int): Type of data, that is incorrect or misiing (0 for amount of command args, 1 for path for file with text
Returns:
tuple: Fixed data from user
"""
if error == 0:
print(... | 67d085dfc783625eccdad56638441b2d53f51e09 | 663,619 |
import json
def load_user(DATA_FILE, user):
"""load user from user.json"""
with open(DATA_FILE, "r") as f:
data = json.load(f)
user.username = data["username"]
user.isLogin = True
user.access_token = data["access_token"]
return user | 674a9f6a0388fba9bf1d7a9f05b3fdd1f466cd11 | 663,620 |
import os
def make_maps(mappings, files):
"""
Simplifies the mappings by creating a map from each source to a destination
If there are duplicates in the list of sources, then the results are undefined.
:param mappings: dict {(file#,line#):("old_path","int_path","ext_path",...)}
:param files: dic... | 04d2f9eb5b94ba27139a2082e728b5e297d76330 | 663,621 |
def decodeImage(imageMatrix, bitPlane):
"""
Method to decode the text inside the image to a text string.
Parameters
----------
imageMatrix : list
A list of ints with the matrix of pixels of the image to be modified
bitPlane : int
The... | b98cfc69eba9b56ff6d287f423820a33edc5f875 | 663,622 |
def get_or_none(model, **kwargs):
"""
from http://stackoverflow.com/questions/1512059/
"""
try:
return model.objects.get(**kwargs)
except model.DoesNotExist:
return None | 03ad739bb220db93f2b40cf3999cc10259a82a15 | 663,623 |
def get_import_context(node):
"""
Go backs up the graph to the import that started this possible cycle,
and gets the import line number
:param node:
:return: int
"""
name = node.name
seen = set()
while node.parent and node.parent.parent:
node = node.parent
if node in ... | d6689a75e1c45ed6bd01a918a4da3042835cc82c | 663,624 |
import os
import subprocess
import sys
def runSimulation(worDir, cmd):
""" Run the simulation.
:param worDir: The working directory.
:param cmd: An array which is passed to the `args` argument of
:mod:`subprocess.Popen`
.. note:: This method is outside the class definition to
... | 211721648c5d966fa738c325021d2034d087d3a4 | 663,625 |
def set_blast_min_length(config):
"""Set minimum sequence length for running blast searches."""
return config["settings"].get("blast_min_length", 1000) | 7fe865731fb0de1dd4e45a6bdf4a4fbcdb84b7d5 | 663,626 |
def filter_out_hydrogens(mol):
"""Get indices for non-hydrogen atoms.
Parameters
----------
mol : rdkit.Chem.rdchem.Mol
RDKit molecule instance.
Returns
-------
indices_left : list of int
Indices of non-hydrogen atoms.
"""
indices_left = []
for i, atom in enumer... | e208522be13b127af7ded165b6a7b22b51bff9f2 | 663,627 |
def local_name(url):
"""Generate a local filename from a remote URL."""
# We assume that the remote url is separated by / and that the file name
# is the final part of the url
return url.split('/')[-1] | 70feaa769d6a85ac4c89ecef400d9af2dd100f6d | 663,628 |
def readlines(fil=None,raw=False):
"""
Read in all lines of a file.
Parameters
----------
file : str
The name of the file to load.
raw : bool, optional, default is false
Do not trim \n off the ends of the lines.
Returns
-------
lines : list
The list ... | 4557a9b3ada9d42932c711723eb089814f2820aa | 663,629 |
import os
def requirements():
"""Load packages in requirements.txt"""
with open(os.path.join(os.path.dirname(__file__), "requirements.txt")) as handle:
packages = handle.readlines()
packages = [package.strip() for package in packages]
return packages | 1daa29e2719b524d1e8e854b92c2fc429f92c90c | 663,630 |
def normalize_commit_message(commit_message):
"""
Return a tuple of title and body from the commit message
"""
split_commit_message = commit_message.split("\n")
title = split_commit_message[0]
body = "\n".join(split_commit_message[1:])
return title, body.lstrip("\n") | c93d05b16a8dcc02b030e6e5b2f6b05aaac5232b | 663,631 |
def matching_input_from_splitter(splitter_rpn):
"""similar to splitting_axis, but without state_input,
finding inputs that are for the same axes.
can't find the final dimensions without inputs.
"""
axes_for_inputs = {}
output_inputs = {}
stack_inp = []
for el in splitter_rpn:
... | 41ad77418451ed5350ba2c581111623a9448b459 | 663,632 |
from typing import Optional
def get_parent_job_id_from_job_tree(job_tree) -> Optional[str]:
"""job_treeから親のjob_idを取得します。
親のジョブがない場合はNoneを返します。
Args:
job_tree:
Returns:
親ジョブのjob_id。親ジョブがなければNone。
"""
tmp_list = job_tree.split("/")
if len(tmp_list) <= 2:
# "org/job_i... | 09d67f09daf6fa904594126c9a1acbe420eaeafe | 663,633 |
import re
import os
def get_newest_vcf(db_dir_content):
"""From the database fetch output, get newest VCF according to time of creation."""
db_out = []; result = []
for i in db_dir_content:
db_out.append(i[0]) ## tuple-form result
for x in db_out:
if re.search('./vcfs/.', x):
try:
result.append((os.pat... | 199a90552f1bdf05bf69bf4753fc2f169cc5895b | 663,635 |
from pathlib import Path
import os
def get_ca_bin_paths(ca_path):
"""Get paths of step binaries."""
ca_path = Path(ca_path)
step = None
step_ca = None
if (ca_path / 'step').exists():
dirs = os.listdir(ca_path / 'step')
for dir_ in dirs:
if 'step_' in dir_:
... | c77d29636a51a2c579fa468072d2d5ac8052b55a | 663,636 |
import json
def load_task(json_file):
"""Opens a task json file and returns its contents"""
try:
with open(json_file, 'r') as jinput:
raw_input = json.load(jinput)
except FileNotFoundError as e:
print(f'\n\nError, file not found: {json_file}', end='\n\n')
return
re... | 0499178a0b28caddc4e8689b5109d7a2b5af09e9 | 663,638 |
def FilterSet(df, annotSet="", annotSetArr=[], annotSetCompare="=", limit=0, negate=False):
"""Provide the ability to filter a Dataframe of AQAnnotations based on the value in the annotSet field.
Args:
df: Dataframe of AQAnnotations that will be filtered by the specified annotation set.
annotSet: String to... | e56f7fb5aba3efeba231a03f1be3817550ae7b4a | 663,639 |
import os
def _special_dbkey_maps(dbkey, ref_file):
"""Avoid duplicate VEP information for databases with chromosome differences like hg19/GRCh37.
"""
remaps = {"hg19": "GRCh37",
"hg38-noalt": "hg38"}
if dbkey in remaps:
base_dir = os.path.normpath(os.path.join(os.path.dirname(re... | 9c29b3b332759f3b08390bd9fb11937a6d1b2045 | 663,641 |
import yaml
def flatten(d):
"""Flatten nested dictionary (recursive function)"""
out = {}
for k, v in d.items():
if isinstance(v, dict):
# recursion
inner = flatten(v)
out.update({'{}.{}'.format(k, kk): vv for kk, vv in inner.items()})
else:
... | 4e5e15d5708e04da19076cb7a79c5838b5416cda | 663,643 |
import json
def load_dictionary_from_json_file(json_file_path):
"""
Loads a dictionary from file at json_file_path, returns the dictionary.
"""
with open(json_file_path, 'r') as json_file:
return json.load(json_file) | ad03c556b8cc0ddddcea88b17fe739b5ef43806e | 663,645 |
def by_author(authorname, bibs):
"""Return only bibs containing authorname."""
keepindex = []
i = 0
an = authorname.replace(" ", "")
authorname = authorname.replace(',', ', ')
authorname = authorname.replace(" ", " ")
authorshort = 'xxxxxxx'
if ',' in authorname and len(an) > (1+an.f... | 8d4ec2d56419b0b35bccfea1fa44f887f7d7a739 | 663,646 |
def getBlockZone(p, aSearch, tBlock, blockSize):
"""
Retrieves the block searched in the anchor search area to be compared with the macroblock tBlock in the current frame
:param p: x,y coordinates of macroblock center from current frame
:param aSearch: anchor search area image
:param tBlock: macrobl... | 1317c4816ca4c14de3adb34dcbddb97cea8be08a | 663,647 |
from typing import OrderedDict
def sort_and_match(ids, ref_ids):
""" sort the id list (ids) with the reference (ref_ids)
Right now it takes the intersection and then the sort & match operate
on the intersection between two lists.
Inputs:
ids (list): contains ids to be sorted
... | 4a892b9d2d1d5ae60edccebc9cf1e2d1ef48bf08 | 663,648 |
import sys
import subprocess
def ConvertToCygpath(path):
"""Convert to cygwin path if we are using cygwin."""
if sys.platform == 'cygwin':
p = subprocess.Popen(['cygpath', path], stdout=subprocess.PIPE)
path = p.communicate()[0].strip()
return path | d19eff7864f7056d935f6df2994e50017259b714 | 663,649 |
def prefix_absolute_path_references(text, base_url):
"""Adds base_url to absolute-path references.
Markdown links in descriptions may be absolute-path references.
These won’t work when the spec is not hosted at the root, such as
https://spec.matrix.org/latest/
This turns all `[foo](/bar)` found in ... | 15c5cc435f23a888a725066eba8405d1d438ce9d | 663,650 |
def find (possible):
"""Returns `(key, index)` such that `possible[key] = [ index ]`."""
for name, values in possible.items():
if len(values) == 1:
return name, values[0] | 6fb98eb6baf4756210f0e8fa38783a3498cf3093 | 663,651 |
def construct_raid_bdev(client, name, strip_size, raid_level, base_bdevs):
"""Construct pooled device
Args:
name: user defined raid bdev name
strip_size: strip size of raid bdev in KB, supported values like 8, 16, 32, 64, 128, 256, 512, 1024 etc
raid_level: raid level of raid bdev, supp... | ad9a09c100e836cf5d7f4c2593e1e838ed8bea2c | 663,653 |
def _compile_buffer_default(element, compiler, **kw):
"""Compile the element in the default case (no specific dialect).
This function should not be needed for SQLAlchemy >= 1.1.
"""
return '{}({})'.format('ST_Buffer', compiler.process(element.clauses, **kw)) | 29da46ca48565efa2b1dff6391088c991850406a | 663,654 |
def fit_pattern(pattern, word):
"""
Checks if given word fits to the pattern
"""
if len(pattern) != len(word):
return False
for i in range(len(pattern)):
if pattern[i] != '.' and pattern[i] != word[i]:
return False
return True | d6e06eb9fbf6c015fca3a691436aa973d91025b3 | 663,655 |
def test_null(x, y):
"""Test null gradient."""
return 10 + 28 / 43 | 5b91ccaa8e0afac39a92c8a620cfb83824302f78 | 663,657 |
import json
def deserialize_json_response(byte_content):
"""Deserializes byte content that is a JSON encoding.
Args:
byte_content: The byte content of a response.
Returns:
The deserialized python object decoded from JSON.
"""
return json.loads(byte_content.decode("utf-8")) | 98cf4284c0904ba31f82e1f39e848a3158a49b7c | 663,658 |
def get_ttl(seconds=None, minutes=None, hours=None, days=None, weeks=None):
"""
Get ttl in seconds calculated from the arguments.
Arguments:
seconds (int | None): Number of seconds to include in the ttl.
minutes (int | None): Number of minutes to include in the ttl.
hours (int | Non... | e1ce7725cb3253275bd3d23be39a0b8180df5e73 | 663,659 |
def potential_cloud_shadow_layer(nir, swir1, water):
"""Find low NIR/SWIR1 that is not classified as water
This differs from the Zhu Woodcock algorithm
but produces decent results without requiring a flood-fill
Parameters
----------
nir: ndarray
swir1: ndarray
water: ndarray
Outpu... | 8ef78fe9048ccac2ecc2dc1b12250eb424c083d2 | 663,660 |
import re
def countElongated(text):
""" Input: a text, Output: how many words are elongated """
regex = re.compile(r"(.)\1{2}")
return len([word for word in text.split() if regex.search(word)]) | 8aeda2940ec10d27b371bd49f1aca730cf16e2b2 | 663,661 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.