content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import torch
def make_valid_from_train(dataset, cut=0.9):
"""
Split training data to get validation set
:param dataset: Training dataset
:param cut: Percentage of dataset to be kept for training purpose
"""
tr_ds, val_ds = [], []
for task_ds in dataset:
x_t, y_t = task_ds
# shuffle before spli... | 3f6fa8fe97af132e9dd575df9416145874717f4a | 668,211 |
def find_history_active_at(obj, time):
"""Assumes obj has a corresponding history model (e.g. obj could
be Person with a corresponding PersonHistory model), then either
returns the object itself if it was active at time, or the history
object active at time, or None if time predates the object and its
... | 9fc8b43484d8de979c1e237950287a9e90439544 | 668,212 |
import collections
def fetch_for_subscriptions(weboob_proxy, method, subscriptions, backend):
"""
Fetch related items for a given list of subscriptions.
:param weboob_proxy: An instance of ``WeboobProxy`` class.
:param method: The method to call on the bakend to fetch items.
:param subscriptions:... | f32099c576f8aa2f6c40fe740edcf3b420ff19a5 | 668,214 |
def decrypt(message):
""" Takes a string and decrypt's it so that it's readable. """
decrypted = [x for x in message[::3]]
return ''.join(decrypted) | 7baa97d4cb5220ffc0d93199a83e29aca69a79ff | 668,215 |
import torch
def bins_to_depth(depth_bin):
"""
Transfer n-channel discrate depth bins to 1-channel conitnuous depth
:param depth_bin: n-channel output of the network, [b, c, h, w]
:return: 1-channel depth, [b, 1, h, w]
"""
depth = depth_bin.permute(0, 2, 3, 1) #[b, h, w, c]
# depth = depth_... | b465b0a803d9ea8fda6dc002b51f50ab150f1b00 | 668,216 |
def make_tile_type_name(cells):
"""
Generate the tile type name from cell types
"""
cell_types = sorted([c.type for c in cells])
cell_counts = {t: 0 for t in cell_types}
for cell in cells:
cell_counts[cell.type] += 1
parts = []
for t, c in cell_counts.items():
if c == 1... | a011bf07b778b24b38cc87f7e9979d150745d839 | 668,218 |
def put_number(line_number, line):
"""
Return a string. The `line_number` is formatted as 3 digits
number with a dot and a space preceding the `line`. The empty
space before line number will be replaced by '0's.
Example:
>>> put_number(1, "Hello World!")
'001. Hello World'
"""
retur... | 25f8a34aa7de91060b852ba86df44b12019802b7 | 668,219 |
def view_create_loan_application():
"""View the create loan application page."""
return {} | 7ba90a0f4ae8781de1e5093a844cf6e5773934ac | 668,221 |
def flip_bit(bit: str) -> str:
"""returns the input bit flipped"""
assert bit == "0" or bit =="1"
return "0" if bit =="1" else "1" | 52eb5f77c9787c529e185c8894259306150b38e5 | 668,222 |
def microseconds_clean(data):
"""
Second step for preprocessing the dataframe
"""
for index, elemen in data.iterrows():
if data.loc[index]['start'] == '000nan':
continue
string = data.loc[index]['start']
new_start = string[0:4] + str(int(float(string[4:6]) * 60))
... | 89696bbbd16c54599a029a00905016282436d12d | 668,223 |
def edit_features(feature_set, df):
"""Takes a set of features (obtained from LASSO) and gains user input on
how to change the set of features or to keep it as is. Inputs are the
initial featureset and the dataframe the features are being pulled from,
so that the suggested features must exist in that da... | 07076be64b791c46d72608bfbf1e6f74dc05d1e5 | 668,224 |
def add_future2connaddr(pack, future):
"""
add future into connaddr
"""
return pack | future | 0e0342a6ac46f554b5c872dda502a447ff32a68f | 668,225 |
import subprocess
def load_val_from_git_cfg(cfg_key_suffix):
"""Retrieve one option from Git config."""
cfg_key = f'cherry-picker.{cfg_key_suffix.replace("_", "-")}'
cmd = "git", "config", "--local", "--get", cfg_key
try:
return (
subprocess.check_output(cmd, stderr=subprocess.DEVN... | 7e2f682e8b9902e39c2ba332136c64797888c4c2 | 668,226 |
import os
def read_requirements(path):
"""
Read requirements
:param path: path
"""
requires = []
with open(path) as f:
install_requires = f.read().split("\n")
for ir in install_requires:
if "-r" in ir:
path = os.path.join(os.path.split(path)[0], ... | 628c9868b77530e67a3497859c7b42d147908fd7 | 668,227 |
def part1():
"""Part 1"""
return True | 555f1cb33b101abd63c5fca25e0d8753cd259f2e | 668,228 |
def home():
"""Homepage
introductionary page (renders the readme.md)
"""
return '{"version":0.1}' | cdbfeaa5ba060add85eee5250430ee7b56c1a615 | 668,230 |
def symbols(el):
"""Map words of operators to symbols of operators.
Arguments:
el {str} -- word of operator
Returns:
str -- symbol of operator
"""
el_lower = el.lower()
if el_lower == "and":
return "&"
elif el_lower == "or":
return "|"
elif el_lower == "... | 50280fafa2b59a3e1d0ad8370d1b3247c9b39b79 | 668,231 |
def clamp(number, min, max):
"""Returns number limited to range specified by min and max, inclusive"""
if number < min:
return min
elif number > max:
return max
else:
return number | 3f9b6cc60f4e5bad805c569b14adb3ef6a047943 | 668,232 |
def BuildReachableFileSet(entry_classes, reachability_tree, header_mapping):
"""Builds a set of reachable translated files from entry Java classes.
Args:
entry_classes: A comma separated list of Java entry classes.
reachability_tree: A dict mapping translated files to their direct
dependencies.
... | 792c72d4187bccd0bc097baf30d4beddbc9bcd58 | 668,234 |
def gen_bom_list(mod_list):
"""generate BOM list"""
mod_list.sort(key=lambda desig: desig[0]) # sort by desig_sign
return [bom_line[1] for bom_line in mod_list] | 89b2c21287b018f28d74f58a3dd65257a533a918 | 668,235 |
import json
def read_json(file_path: str) -> dict:
"""Reads a json file and returns the dict
"""
with open(file_path) as f:
return json.load(f) | 93df73379300052dbecc6706050b0779ac568b98 | 668,236 |
def username(user: dict):
"""
Returns the user's first and last name if they've seen set, else
returns the user's email
"""
if user["first_name"]:
return user["first_name"] + " " + user["last_name"]
return user["email"] | 19f7a4d47677fa1217c03f61f867c7704194f2bc | 668,237 |
import torch
def get_masks(slen, lengths, causal):
"""
Generate hidden states mask, and optionally an attention mask.
"""
assert lengths.max().item() <= slen
bs = lengths.size(0)
alen = torch.arange(slen, dtype=torch.long, device=lengths.device)
mask = alen < lengths[:, None]
# attent... | f71942a5d089372e8bbff6d08b8dab9df86e375a | 668,238 |
def html_color(color):
"""Interpret 'color' as an HTML color."""
if isinstance(color, str):
if color.lower() == "r":
return "#ff0000"
elif color.lower() == "g":
return "#00ff00"
elif color.lower() == "b":
return "#0000ff"
elif color.startswith(... | 0ae57dd248e67da6eef6a2796cd2b04c1a81e20e | 668,239 |
def render_badge(self, h, *args):
"""Render description component as a card badge"""
if self.text:
with h.span(class_='badge'):
h << h.span(h.i(class_='icon-pencil'), class_='label')
return h.root | 8a2bcc526bc3b77a67c97110bc4339d70cd260bf | 668,240 |
import functools
def middleware(f):
"""Function decorator for making WSGI middlewares."""
return functools.update_wrapper(
lambda app: lambda wsgi_env, start_resp: f(app, wsgi_env, start_resp),
f) | 33576f9bc905e5abc673e442198a19db4b43539f | 668,241 |
def conflateable(seg1, seg2, segment_pairs):
"""
Return True iff seg1 and seg2 are exactly one of the segment pairs
in segment_pairs (ignoring ordering of either).
seg1 and seg2 will never be identical in the input.
Parameters
----------
seg1, seg2: Segment
Two segments on which m... | 8444f5e0811bf410675e2bae300f9f58e400c31c | 668,244 |
def norm3d(x, y, z):
"""Calculate norm of vector [x, y, z]."""
return (x * x + y * y + z * z) ** 0.5 | c61e9e1fb53986b20da60899a4464e8b914f0068 | 668,246 |
def is_pangram(string: str) -> bool:
"""
Checks if the given string is a pangram or not
:param string: String to check
:return: bool
Example:
>>> is_pangram("The quick, brown fox jumps over the lazy dog!")
>>> True
"""
count = 0
for character in range(97, 123):
... | e2b836c79fec76472b21f57ec0a23d49338db8f1 | 668,247 |
import sys
import argparse
def parse_args(args=sys.argv[1:]):
"""A simple argparse to be used when pycee is executed as a script."""
parser = argparse.ArgumentParser("pycee2", description="Pycee is a tool to provide user friendly error messages.")
parser.add_argument(
"file_name",
type=st... | 789827e7d4fcc5f85e1d003adf61450e83728dd7 | 668,248 |
def rename(newname):
"""define the name of the function"""
def decorator(f):
f.__name__ = newname
return f
return decorator | 9248975ae8c1d3f73690e065ce6362e22fb4132d | 668,249 |
import argparse
def argument_parser() -> str:
"""Function to get the config id"""
parser = argparse.ArgumentParser(
description="Argument parser to obtain the name of the config file"
)
parser.add_argument(
"--config_id",
default="sample_config",
help="config id to use"... | 643e5eb7e6d1115894cc161525da70c6fc1ad189 | 668,250 |
def check_args(allowed, arg):
"""Raise name error if argument doesn't match 'allowed' list/set of values"""
assert type(allowed) in {list, set}, "First argument must be 'allowed' list/set of args values"
if arg not in allowed:
raise NameError("Unexpected arg {0}: allowed args are {1}".format(arg, al... | 8e8869d56cec0bacb9761403c5d0b35291cd8f89 | 668,251 |
def write_head(workbook, sheet, config):
"""Write header to excel."""
if 'head_style' in config:
form = workbook.add_format(config['head_style'])
else:
form = workbook.add_format()
for idx, data in enumerate(config['head']):
sheet.write(0, idx, data['cell'], form)
if 's... | 5bbc43bfc7f1e244e44295b6259cccb5352f1348 | 668,252 |
def clear_low_information_words(message):
"""
Remove links from messages
:param message:
:return: message
"""
output = []
for word in message.split():
# remove links, as they contain no real conversation info and cannot be stemmed
if not word.startswith('http'):
... | e44bf2773cd5fbee876d794307cdaa16e89ea70c | 668,253 |
import os
def _read_file_for_long_description(fname):
"""Read a file and return its content
:param fname: name of the file to extract the long description from
"""
return open(os.path.join(os.path.dirname(__file__), fname)).read() | af562f42d72bdacf3453d0f1210784ab52ca42f7 | 668,254 |
def group_chirp_bumps(stim_inten, spike_counts, n_repeat):
"""
Find the cells response to the OFF-ON-OFF initial parts of the chirps.
params:
- stim_inten: Stimulus intensity array
- spike_counts: Spike counts array of shape (t, n_cell)
- n_repeat: Number of repetitions of the chirp... | 194fcb107228a9b5355aee9abfa7c7fd21fae4fb | 668,255 |
def vel_final_dist_helper(initial_velocity, acceleration, dist):
"""
Calculates the final velocity given the initial velocity, acceleration and the distance traveled. And is a helper
function to be called by vel_final_dist()
:param initial_velocity: Integer initial velocity
:param acceleration:... | 74cc521b37a58ffc766bb3fc1a9a7ad80fcfe35e | 668,256 |
import base64
def decrypt(s: bytes):
"""加密token"""
return base64.b64decode(s)[3:-3].decode('utf-8') | 98c6898854b7850d8add1ea07259a42ce1b53883 | 668,257 |
def sol(a, b):
"""
Follows the standard DP approach of finding common subsequence.
The common length can be >=1 so if we find a common character in both
the strings, it does the job
"""
m = len(a)
n = len(b)
dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
for i in range(1, m+... | b9765ff80006c4373532ae693d24420179a373f4 | 668,258 |
import torch
def init_score_map(bboxes, ratio=0.3):
"""
初始化score_map
ratio为保留的中心区域的比率
"""
score_map = torch.zeros([1, 60, 60], dtype=torch.float32)
#初始化score_map
for bbox in bboxes:
#首先转换到60*60坐标空间
leftup_x = bbox[0] / 4.0
leftup_y = bbox[1] / 4.0
rightdown_... | a0e8ef3097701b0324de75ada0d516e960ae2408 | 668,259 |
def cust_list_y():
"""Set the "cust_y_list to test generator"""
cust_list_y = [
[
[0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1],
],
[
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, ... | f00457cbb2258c145dbc533fcbcecff9f1c99a13 | 668,260 |
def vnesi_izbiro_niz(moznosti):
"""
Uporabniku da na izbiro podane možnosti.
"""
moznosti = list(moznosti)
for i, moznost in enumerate(moznosti, 1):
print(f'{i}) {moznost}')
izbira = None
while True:
try:
izbira = int(input('> ')) - 1
return moznosti[i... | 0e6d4ee8c0d8a12112208dcdd492008766ff069f | 668,261 |
def get_valid_name(): # OK
"""Beschreibung:
Foirdert den User auf einen Namen einzutragen und
Überprüfung ob etwas vom User eingegeben wurde
Falls keine Eigabe, leerzeichen oder ein zu langer name, eigegeben wurde
ruft sicht die Funktion wieder auf(rekrusiv)
:return: name de... | e528e881d165eba8e1e1e4261462cb22da867c1f | 668,262 |
def with_metaclass(metaclass, *bases):
"""
Construct a base class with metaclass compatible with python2 and python3.
Usage:
```
class(with_metaclass(metaclass, base1, base2...)):
....
```
"""
class InterposedMetaClass(metaclass):
def __new__(mcls, name, new_bases, attr... | 731d40d481c4f9b18ba5dbfa0bf42cf5e9d019d3 | 668,264 |
def _get_dashes_key(e):
"""
Generate a key to store ongoing dashes temporarily. A <dashes ... /> tag
specifies the temporal range of some textual annotation at the start of the
dashes.
Returns
-------
('dashes', number) OR ('wedge',) : tuple of (str, number) OR (str,)
"""
if e.attri... | b3c00510b9833e3e91309054b9c065818b6a5660 | 668,265 |
import random
def generate_auth_id():
"""Generate a random integer to be used when generating API auth tokens."""
# We use MySQL's maximum value for an unsigned int:
# https://dev.mysql.com/doc/refman/5.7/en/integer-types.html
return random.SystemRandom().randint(1, 4294967295) | 6cac2a8ecc4064f073f813279d03393d63b58b26 | 668,266 |
import torch
def get_torch_device():
"""
Get a device - GPU if possible
"""
print("CUDA is available: {}".format(torch.cuda.is_available()))
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
#device = torch.device("cpu")
print("Chose device: ".format(device))
retu... | 01d4db5eda33191e95f3fa1449114339f67032d7 | 668,267 |
import subprocess
import os
def get_git_modified(project_directory):
"""Get all modified filepaths between current ref and origin/master."""
subprocess.check_call(
'git -C "{}" fetch origin'.format(project_directory),
shell=True
)
diff_cmd = 'git -C "{}" diff {{}} --name-only'.format(o... | b72fed0e02ad249b2807b5d6cd44dbede962839c | 668,268 |
def swap_optional(x, y=None):
"""Change order of arguments
Full multiline ... . .. . . .
description of the function ..
Parameters:
-----------
x : float
Positive number in cm
y : float, optional
Positive number in kg, default is None
Returns:
-------
... | 29d94207721d1c1512346ff4f03a1ffaafdd20d6 | 668,269 |
def normalize(loss):
"""
work over standard mean, to avoid unecessary chaos in policy, source from OpenAI
.. avoid using pgd_loss.mean() and use pgd_loss.sum() instead
+ may stabilize learning
- well, it normalize our advantage ( value not anymore holds advantage, +/- can be swapped )
..... | 3d5fa6d54443b9a4cb099e6a590e83a4815c8387 | 668,270 |
import pickle
def _read_results(pickle_file_name):
"""Reads results from Pickle file.
:param pickle_file_name: Path to input file.
:return: monte_carlo_dict: Dictionary in format created by
`monte_carlo.run_monte_carlo_test`.
"""
pickle_file_handle = open(pickle_file_name, 'rb')
mont... | 604a2f5eb99e00d33d9262c5680ae67f2be488b4 | 668,271 |
def _no_stop_codon(aa_seq):
""" Returns True if a sequence does not contain a stop codon,
otherwise returns False
"""
if '*' not in aa_seq:
return True
else:
return False | b48d3169d6403bc69782dede504af3962ee7d6bf | 668,272 |
def get_categories_used_ordered(ordered_categories, used_categories) -> list:
"""Returns an ordered list of categories that appear in used_categories.
* ordered_categories: manually defined ordered list
* used_categories: a list or set of categories actually used in the data frame
"""
used_set = set... | 0b436235aa2a82963bdde170d07b8a4d6a9d74cf | 668,273 |
import os
def create_dir(path='./plotting'):
"""Create new folder for pictures if it does not exist yet."""
if os.path.isdir(path):
return path
os.makedirs(path)
return path | e5405f7c067d1682441f8ea359b65e09dfcbfcaf | 668,274 |
def RK4n(diffeq, y0, t, h): # non-vectorized with lists
""" RK4 method for n ODEs:
Given y0 at t, returns y1 at t+h """
n, y1 = len(y0), [0.0]*len(y0)
k1 = diffeq(y0, t) # dy/dt at t
for i in range(n): # loop thru n ODEs
y1[i] = y0[i] + 0.... | d3f34ddf84b3326de86ee62c04793ace4a841105 | 668,275 |
import re
def get_new_version(version):
"""
Get new version by bumping only the last digit group in the string.
Args:
version (): Version: like 2.7.epic14859_9
Returns: New version: like 2.7.epic14859_10
Original credit: https://stackoverflow.com/questions/23820883/incrementing-the-last-d... | 7c3bd2fe08852b75b543fb59f33aaa1af876743c | 668,276 |
import json
import requests
import os
def mod_command(command_id=None, _op=None, system_id=None):
"""post: api v2 commands command_id associations."""
if command_id:
command_id = ''.join(command_id)
ops = ['add', 'remove']
if not _op in ops:
print("Unknown option: " + str(_op))
... | 5b13190f95d70c3cfe6fe466af35f95e1c85067f | 668,277 |
def build_ping(dest, count=None, source=None, vrf=None):
"""
Function to build the command to send to the terminal for the switch
to execute. All args come from the module's unique params.
"""
if vrf is not None:
cmd = "ping vrf {0} {1}".format(vrf, dest)
else:
cmd = "ping {0}".f... | 64541ba2f8269600042f40a204ca5c54954f49d1 | 668,278 |
def motif_factors(m, M):
"""
Generates the set of non redundant motif sizes to be checked for division
rule.
Parameters
----------
m : <int> minimum motif size
M : <int> maximum motif size
Returns
-------
factors : <list> sorted(descending) list of non-redundant motifs.
""... | f2dd9eaebc4db7d947031b49d9c494a47dd4ce9f | 668,279 |
import typing
import numbers
def get_role_arn(
account_id: typing.Union[str, int],
role_name: str,
path: str="",
partition: str="aws"):
"""Get a correctly-formatted IAM role ARN.
You can provide the path separately or as part of the role name."""
if isinstance(account_id, ... | 2d3989edb2e935383d08cd1fe3017a3e712ea462 | 668,280 |
import inspect
def singleton(cls):
""" Decorator function that turns a class into a singleton. """
# Create a structure to store instances of any singletons that get
# created.
instances = {}
# Make sure that the constructor for this class doesn't take any
# arguments. Since singletons can ... | 8118f1bb8170d59961322aa87a8c52be450b1348 | 668,282 |
def parse_id(arg):
"""
Parses an ID from a discord @
:param arg: @ or ID passed
:return: ID
"""
if "<" in arg:
for i, c in enumerate(arg):
if c.isdigit():
return int(arg[i:-1])
# Using ID
else:
return int(arg) | 3171c4a9ae0a06d674109b50d7fc806905ef03ee | 668,283 |
def dict_merge(base, override):
"""Recursively merge two dictionaries
Parameters
----------
base : dict
Base dictionary for merge
override : dict
dictionary to override values from base with
Returns
-------
dict
Merged dictionary of base and overrides
"""
... | ab35c0e4f9f72bd31855212354d6d91402dcd651 | 668,284 |
def change_pose_f1(bodys, is_gt=False):
"""
format: ---> a total list
[[jtype1, X1, Y1, Z1], [jtype2, X2, Y2, Z2], ...]
"""
include_together = []
if len(bodys) > 0:
for body in bodys:
for i in range(15):
joint = []
if not is_gt:
... | 94e65dbdd8acfdae17cbc4e81717a232c2872a4c | 668,286 |
def cria_copia_peca(peca):
"""
Devolve uma copia da peca inserida.
:param peca: peca
:return: peca
"""
return peca.upper() | 8d39f7ad40e4f215197fb2698ce25fd38e6057e6 | 668,287 |
def get_eids_from_op2_vector(vector):
"""Obtain the element ids for a given op2 vector
Parameters
----------
vector : op2 vector
An op2 vector obtained, for example, doing::
vector = op2.cquad4_force[1]
vector = op2.cquad8_stress[1]
vector = op2.ctriar_force... | 248a7b19829a59438ca74cc3fbdaf89dd8b7e240 | 668,288 |
def get_index_basename() -> str:
"""Get the basename for a streaming dataset index.
Returns:
str: Basename of file.
"""
return 'index.mds' | 7dee083f01693c3bc64260f2b67f619425661eb0 | 668,289 |
def traced_fibo_rec(num):
"""Recursive Fibo."""
return num if num <= 1 else traced_fibo_rec(num - 1) + traced_fibo_rec(num - 2) | 7e529835dd04bf2cedc17029bbd4ad72a0fe8af3 | 668,290 |
def replace(string, old, new, count=-1):
""":yaql:replace
Returns a string with first count occurrences of old replaced with new.
:signature: string.replace(old, new, count => -1)
:receiverArg string: input string
:argType string: string
:arg old: value to be replaced
:argType old: string
... | 65b871728ff1f02cd1ea2766f03ab2f73f899be0 | 668,291 |
import torch
def arange(*inputs, dtype='long', device=None):
"""Rearange from left to right."""
if dtype == 'long':
dtype = torch.long
elif dtype == 'uint8':
dtype = torch.uint8
else:
dtype = None
return torch.arange(*inputs, dtype=dtype, device=device) | b1eb180f76e060095da10c860bd31b76302a51d2 | 668,292 |
from typing import Counter
def insert(pair_counts, rules, char_counter):
"""
here we have a pair_counts where we keep track of the frequency of pairs
in the polymer. {NN: 1, NC: 4, ...}
and the global amounts of each individual character {N: 5, B: 200, ...}
"""
next_pair_counts = Counter()
... | 637df351c1f3ef50f33c8c52e291744ea785cced | 668,293 |
def convert_subscripts(old_sub, symbol_map):
"""Convert user custom subscripts list to subscript string according to `symbol_map`.
Examples
--------
>>> oe.parser.convert_subscripts(['abc', 'def'], {'abc':'a', 'def':'b'})
'ab'
>>> oe.parser.convert_subscripts([Ellipsis, object], {object:'a'})
... | 4a97647cb14726ba3b0bc109c626b8c8cc1b5815 | 668,294 |
import re
def markdown_subset_strip(md_str):
"""
Strips a subset of Markdown from a string.
"""
return re.sub(r'(`|\*|\*\*)([^`*]+)\1', r'\2', md_str) | b8a510dc0f5250054c739ee5ecbf71e2728b93b0 | 668,295 |
def map_permutations(permuts, best_permuts):
"""
Consider the fact that some nodes are heads of others.
I.e., for some nodes we know the best permutation of the corresponding subtrees.
So, we do not have to consider permuting their components.
Example:
x: [a,b,c]
If c is a head of (d,e) a... | a7798fe57a6ba7c534e064323ce25ccf11d12201 | 668,296 |
import asyncio
def run_async(func, *args, **kwargs):
"""run a function in an event loop"""
async def _fn():
return await func(*args, **kwargs)
return asyncio.run(_fn()) | b44fcd96a11204ec3822bfe5778fa1d34c7a653f | 668,297 |
def get_start_specs(start_data):
"""Get number fo searchers (m), gamma, start position of searchers (s_0), initial belief vector"""
h = int(start_data[1][0])
gamma = start_data[2][0]
n = int(start_data[3][0])
s_0 = [int(start_data[4][j]) for j in range(len(start_data[4]))]
b_0 = start_data[... | 8324f80d89a6c70e53cc20a072794d090c17233c | 668,298 |
import re
import os
def find_indices(filename, dir='', files=[]):
"""Return the list of all indices for the given filename, present
in the filename's directory."""
# get the extension-free filename, extension, and file index
# template: FILENAME.xxx.0 => FILENAME (can contain points), 0 (index)
#... | 90122e37b063cb03c9411eeab307882159834964 | 668,300 |
def contig_conversion(genome_file, element_pos):
"""
build a conversion table
returns a list of duplicate contig names
"""
conversion_table = {}
duplicate_contigs = []
with open(genome_file, "r") as fa:
for line in fa:
if line.startswith(">"):
line = line.... | 5650345384f6f806f2da319a7164bb6ac2c4fb1b | 668,301 |
from typing import Dict
from typing import Any
def _str_none(dct: Dict[str, Any]) -> Dict[str, Any]:
"""Make all the None value to string 'none'."""
return {key: "none" if value is None else value for key, value in dct.items()} | 2306e9d1e82715cddc228654aed557d8c05947d3 | 668,302 |
import xml.etree.ElementTree as etree
import six
def set_tz(ilo_client, val):
"""
Set TIMEZONE configuration item
"""
xml = ilo_client._create_dynamic_xml('MOD_NETWORK_SETTINGS',
'RIB_INFO', 'write')
if six.PY2:
child_iterator = xml.getiterator()... | 260b17452315bf1466f94b2ca56427d6fe53ef22 | 668,303 |
import subprocess
def check_output(*args, **kwargs):
"""Workaround for Python 2.6 not having subprocess.check_output"""
if "check_output" in dir(subprocess):
return subprocess.check_output(*args, **kwargs)
p = subprocess.Popen(stdout=subprocess.PIPE, *args, **kwargs)
stdout, _ = p.communicate... | e7b319e85d786fba9928597a5b61255032721cb8 | 668,304 |
def recommendation(current_price,stdev,target_price):
"""
Compares target price to current price, and
returns sell/hold/buy recommendation based on number of
standard deviations away from the mean.
"""
distance = round((target_price-current_price)/stdev,2)
if target_price <= (-2*stdev + cu... | 665e25f3e7c04175d20676bde7371f383f11f9ed | 668,305 |
import codecs
def base64_to_hex(base64_bytes: bytes) -> bytes:
""" Convert hexadecimal bytes to base64 bytes. """
return codecs.decode(base64_bytes, encoding="base64") | 111f7068b56f053efda3f41ad212e1544fac0931 | 668,306 |
import sys
def find_colids(colnames, header):
"""Get the csv column index of each field in the colnames parameter"""
colids, colmap = [-1 for _ in colnames], {}
for i, name in enumerate(colnames):
for alias in name.split('|'):
colmap[alias] = i
for i, col in enumerate(header):
... | 2e198f9afef86f701093dc9fa26e53c408edf8b0 | 668,307 |
import re
def re_filter(text, regexps):
"""Filter text using regular expressions."""
if not regexps:
return text
matched_text = []
compiled_regexps = [re.compile(x) for x in regexps]
for line in text:
if line in matched_text:
continue
for regexp in compiled_re... | fda62371c36ac43e1a6186a7f4ae4ca1a809f73a | 668,309 |
def getAllFilesInRevision(files_info):
"""Checks for existing files in the revision.
Anything that's A will require special treatment (either a merge or an
export + add)
"""
return ['%s/%s' % (f[2], f[3]) for f in files_info] | ee08019a5e6a6aa20019ff2219901b70b0d9ccf4 | 668,310 |
from typing import Union
def convert_to_n(s: str, return_str: bool = True) -> Union[str, list]:
"""
Converts a string into a sequence of digits
------
PARAMS
------
1. 's' -> input string
2. 'return_str' -> If true, returns a string of sequential digits, else returns a list of digi... | 4c1f58de93e6a701529fb7b070867fce50f82d04 | 668,311 |
def getAddressSuggestions(connection, pattern, limit):
"""Fetching address suggestions for a given search pattern
Parameters
----------
connection : psygopg2.connection
psycopg2 connection object
pattern : str
search pattern
limit : int
maximum number of suggestions to r... | a699a8368f3dbfda51fe42aaaff848938c5d8361 | 668,312 |
import sys
def query(question, default=None):
"""Query an anwer to a general question."""
sys.stdout.write(question)
answer = input()
if default is not None and answer == "":
return default
else:
return answer | 6fc981053bf429eb45d42600a7760dc9310eca1d | 668,313 |
def _cvtfield(f):
"""
If str passed in via 'f' parameter is '-' then
return empty string otherwise return value of 'f'
:param f:
:return: empty string if 'f' is '-' otherwise return 'f'
:rtype: str
"""
if f is None or f != '-':
return f
return '' | f7e953cb856824cb9f8cc720bac90a60874bb3d8 | 668,314 |
def to_power_three(number):
"""
Returns the number to the power of three.
:param number: The number
:return: The number to the power of three
"""
return number ** 3 | 7adb7ccaee8027d26f0e49b86755242b0df599e1 | 668,315 |
def VARIANCE(src_column):
"""
Builtin variance aggregator for groupby. Synonym for tc.aggregate.VAR
Example: Get the rating variance of each user.
>>> sf.groupby("user",
... {'rating_var':tc.aggregate.VARIANCE('rating')})
"""
return ("__builtin__var__", [src_column]) | 28b92e302b2c20fa5bc34e84ad2bf86721ad9724 | 668,316 |
def _trim_ds(ds, epochs):
"""Trim a Dataset to account for rejected epochs.
If no epochs were rejected, the original ds is rturned.
Parameters
----------
ds : Dataset
Dataset that was used to construct epochs.
epochs : Epochs
Epochs loaded with mne_epochs()
"""
if len(e... | 0e08273d86188b8572d0b26feea992771694feb8 | 668,317 |
def PIsA (inImage):
"""
Tells if input really a Python Obit ImageMF
return True, False
* inImage = Python Image object
"""
################################################################
try:
return inImage.ImageMFIsA()!=0
except:
return False
# end PIsA | 6b87c13bf7a6404fc8faa215c9605fb4e9f31463 | 668,318 |
def get_device_info(net_connect):
"""
GET network device info
Args:
net_connect (object): Netmiko ConnectHandler object
return: Network device show version info
rtype: dict
"""
return net_connect.send_command('show version', use_textfsm=True)[0] | e930e23bed39dfeed56cbb47a0891e5663a2b10a | 668,319 |
def calculate_dataset_size(data, user, source_ratio=(1.0, 1.0)):
"""
Gives the total number of sessions that belong to <user> and those
that do not.
"""
source_ratio_self, source_ratio_other = source_ratio
source_len = {_:0 for _ in set(map(lambda x: x[-1], data))}
for item in data: source_... | 226106091b308fd44eca39ca8a5019f664317b93 | 668,321 |
def linear_sieve(max_n):
"""Computes all primes < max_n and lits of
all smallest factors in O(max_n) time
Returns
-------
primes: list of all primes < max_n
smallest_factors: list such that if q = smallest_factors[n],
then n % q == 0 and q is minimal.
"""
smallest_factors = [0] ... | 5a368ac0bca50cbdf82f9c41db689e1536ab463a | 668,322 |
def data_is_rect(mdata):
"""return whether the number of columns is consistent across rows"""
if mdata == None: return 1
if len(mdata) == 0: return 1
rlen = len(mdata[0])
for row in mdata:
if len(row) != rlen: return 0
return 1 | 1e70c7213f4115716753511ec0ce4f0425d45fc8 | 668,324 |
import pwd
import os
def get_home():
"""Return the current user's home directory without using the HOME variable. """
return pwd.getpwuid(os.getuid()).pw_dir | 5626e1a58fbb450ae14618a1e81f9e3034496742 | 668,325 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.