content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def gene_filter(line, stop, counter, gene_counter,linesaver,cutoff,out,written):
"""
:param line:
:param stop:
:param counter:
:param gene_counter:
:param linesaver:
:param cutoff:
:param out:
:return:
"""
counter += 1
linesaver.append(line)
if line[0] == '#':
... | c9071b910a879bc32fdce14ccb1608a389dabd8f | 659,167 |
def check_all_messages(msgs):
"""
Decorator to automatically assign all messages from a class to the list of messages handled by a checker method.
Inspired by pylint.checkers.util.check_messages
"""
def store_messages(func):
func.checks_msgs = [message[1] for message in msgs]
retur... | 9b55d0b4156b092ea69289df461c4a4a8dd6c34e | 659,168 |
def construct_sentence(s, words):
"""
Given a dictionary of words an a string with no spaces,
find the original sentence in the provided string
"""
starts = {0: ''}
for idx in range(len(s) + 1):
new_starts = starts.copy()
for start_index in starts.keys():
word = s[s... | 7c581babfacc52ae887a9ed1d830bb21d6060331 | 659,169 |
import os
def find_dev(path, data_file):
"""Find usb device absolute path.
Note:
Also check if data already exists on device (with the given file name
global variable data_file_exists.
Args:
path (str): The path to the dir where the device might be.
file_name (str): csv fil... | e8c45eee8ab92ec56b0db0cd65df995a989a31b8 | 659,170 |
def get_path_from_tokens(token):
"""
Just yanks the path out of a list of template tokens. Ignores any
additional arguments.
"""
tokens = token.split_contents()
if len(tokens) > 1:
# At least one argument. Only interested in the path, though.
return tokens[1][1:-1]
else:
... | 1b760768eb4a91c1419b756af516e6f660ca1046 | 659,171 |
def remap_gender(gender: str) -> str:
"""Map gender to standard notation.
Args:
gender (str): Original gender, eg male, girl, etc
Returns:
str: m, f or other
"""
if not isinstance(gender, str):
return "other"
gender = gender.strip().lower()
if gender in ["man", "ma... | f0f0725f6379b1bdd1dfe39b98a4856400b337ed | 659,173 |
def create_ngram_index(n_grams, n_index_tokens = 1000):
"""
Args:
n_grams: a list that contains a list of n-grams for each entry.
"""
n_gram_index = {}
for i, tokens in enumerate(n_grams):
for token in tokens[:n_index_tokens]:
# Create new entry
if token not ... | dfbde2bde52098d4fae5cd52891c218f33be6389 | 659,174 |
import click
def command_group_function(**kwargs):
"""Combines decorators used for all click functions inside a ClickCommandGroup
Identical to
@click.command(**kwargs)
@click.pass_obj
Just to prevent duplicated code
"""
def decorator(func):
return click.command(**kwargs)((click.... | 1abdbc52f9a363e820f0b58d8e62e307799b6e0b | 659,175 |
def fit_unit_cube(V):
""" Fit vertices V into the unit cube (in place) """
xmin, xmax = V[:,0].min(), V[:,0].max()
ymin, ymax = V[:,1].min(), V[:,1].max()
zmin, zmax = V[:,2].min(), V[:,2].max()
scale = max([xmax-xmin, ymax-ymin, zmax-zmin])
V /= scale
V[:,0] -= (xmax+xmin)/2/scale
... | ff25a68185e20879ce5c5d2c9fc1c522026ee9c3 | 659,176 |
def add(key=None, value=None, *, myst, getpass, **kwargs):
"""
Add a new key-value pair. Accepts a optional key and an optional value for the key. If the key or value is not entered, a secure input will be prompted to enter them.
"""
if not myst.mutable:
return 'the myst is in read-only mode, us... | 31114ff2dda7edbf393f031c73bf59f6f50e9ef8 | 659,177 |
import os
def prefix(path, pre):
"""Apply prefix to last part of path
'/my/path' and 'hi_' will give '/my/hi_path'
"""
p, d = os.path.split(path)
return os.path.join(p, pre + d) | 0872574aaa38a14bd97e5ef24e54dd529a20edee | 659,178 |
def _calculate_stats(progress):
"""
Calculate the stats based on all user's games.
:param progress: user's progress model.
:return: dict which contains the stats strings.
"""
draw_result = 'Wins: {}%; Losts: {}%; Draws: {}%'
default_values = (0, 0, 0)
result = {}
for key in ('enemy'... | df370fbce9a6da9f6240b94c0b767720980bf3a3 | 659,179 |
def assert_all_passed(result):
"""Assert that all outcomes are 0 except for 'passed'.
Also returns the number of passed tests.
"""
outcomes = result.parseoutcomes()
for outcome in outcomes:
if outcome not in ("passed", "seconds", "warnings", "warning"):
assert outcomes[outcome] ... | 6e598bd7123b5b0b849b7e062d62a265cd176904 | 659,180 |
import sys
def kv_parse(string):
""" Parse a string of the form foo=bar into a dictionary """
try:
key, val = string.split('=', 1)
if key is None or key == '':
raise TypeError('Empty key')
except Exception as e:
err = "Invalid key found parsing KV string '{}': {}".format(string, str(e))
pr... | 48ba1da8a9073a7192a42a146f44505ac62f2564 | 659,181 |
import re
def split_pem(data):
"""
Split a string of several PEM payloads to a list of strings.
:param data: String
:return: List of strings
"""
return re.split("\n(?=-----BEGIN )", data) | 89e34875135406e66f7a3f536cf3909a6fc85b17 | 659,182 |
def get_variant_info(genes):
"""Get variant information"""
data = {'canonical_transcripts': []}
for gene_obj in genes:
if not gene_obj.get('canonical_transcripts'):
tx = gene_obj['transcripts'][0]
tx_id = tx['transcript_id']
exon = tx.get('exon', '-')
... | 5112793f8b603923ca652ce8d0e3219f28f4822b | 659,183 |
def is_reply(tweet):
"""
Determines if the tweet is a reply to another tweet.
:param tweet: Twint tweet object whose object will be formated
"""
# A reply's conversation_id is different than the id_str
if tweet.conversation_id != tweet.id_str:
return True
# If not a reply to anothe... | 99756f71b34213003e58b3bcfed87e00b387a049 | 659,184 |
from typing import List
from typing import Union
from typing import Dict
def act_parse_proxies(proxy_items: List[str]) -> Union[List[Dict], None]:
"""
Parse the proxy list JSON supplied by ActProxy API.
:rtype: Union[list, None]
:type proxy_items: list
:param proxy_items: List of proxy lines returned from Act... | 5020a3d26e5dd54f303343d5989c22ae787bd2b1 | 659,185 |
def check():
"""
Checks if the user is authenticated.
"""
return {'msg': 'Access'}, 200 | b8dacb70cdebc262db53b785af7b7ed376bd9b15 | 659,186 |
def get_cell(grid, y: int, x: int) -> str:
"""Returns the value of a cell"""
return grid[y - 1][x - 1] | e1912ff4cee24371de57e93b7aa55dbb287540ee | 659,188 |
def nsyll_word(word, vowels, sep=None):
"""
Count the number of syllables in a *word*, determined by the number
of characters from the *vowels* list found in that word.
If *sep* is defined, it will be used as the delimiter string (for
example, with `sep="."`, the word "a.bc.de" will be treated as t... | cc722c0cf9b7845fb95e55d6717e35b1058e473d | 659,189 |
def dumpPacket(buffer):
"""
Name: dumpPacket(buffer)
Args: byte array
Desc: Returns hex value of all bytes in the buffer
"""
return repr([ hex(x) for x in buffer ]) | 3e864d6645b4da3d76c84ef1a0819759ff29f05a | 659,190 |
def deriv(f,c,dx=0.0001):
"""
deriv(f,c,dx) --> float
Returns f'(x), computed as a symmetric difference quotient.
"""
return (f(c+dx)-f(c-dx))/(2*dx) | 8647945c4cd1b5bd37c46f1afe1dff645a5507a5 | 659,191 |
import os
def find_on_path(dir, filename):
"""Look for filename searching up through all directories on the path 'dir'.
Returns list of full paths where file exists in parent dirs starting with parent, or an empty list
"""
paths = []
for _ in range(20):
path = os.path.join(dir, filename)
if os.path.isfile... | 2fea9393eb70f2e7e3737ff3b0f62090ddfddac4 | 659,194 |
import math
def distance(origin, destination):
"""
Haversince distance from https://gist.github.com/rochacbruno/2883505
Returns distance in kilometers
"""
lat1, lon1 = origin
lat2, lon2 = destination
radius = 6371 # km radius of Earth
dlat = math.radians(lat2-lat1)
dlon = math.rad... | 5cbc59e8c0c8875fa0d03ecb2b673318b8bea01d | 659,195 |
import re
def delComment( Text ):
""" removed comment """
single_line_comment = re.compile(r"//(.*)$", re.MULTILINE)
multi_line_comment = re.compile(r"/\*(.*?)\*/",re.DOTALL)
Text = multi_line_comment.sub('\n',Text)
Text = single_line_comment.sub('\n',Text)
return Text | a8f9b5459ec35f904c2f36d6958bd3feb0864018 | 659,196 |
import subprocess
import shlex
def execute(cmd, output_file):
"""Execuit the given command and redirect STDOUT and STDERR to output_file.
Args:
cmd (string) : Command to execute
outpout_file (string) : Name of file to redirect output to
Returns:
(Popen) : Popen object representing ... | 00ad192634b976ab2688e1238bc416df0df97b7e | 659,197 |
import numpy
def psi(p):
""" Map the reference pyramid to the infinite pyramid """
zeta = p[:,2].reshape(-1,1)
pp = p / (1-zeta)
for i in numpy.flatnonzero(zeta==1):
if (numpy.abs(p[i,(0,1)]) < 1E-10).all(): pp[i] = numpy.array([0,0,numpy.inf]) # not perfect, as x,y <> 0 do not map to... | 4bc43bb79ba42cfc7dc1b69c0c22ea280a883de6 | 659,198 |
import sys
import argparse
def get_args(args=sys.argv):
"""
Extract command-line arguments.
:param list args: A list of command-line arguments
:returns: A command-line argument namespace
:rtype: Namespace
"""
p = argparse.ArgumentParser()
p.add_argument('-a', default=False, dest='all'... | 2b5f9920c4ed79b037e640c10f3bf855a8544685 | 659,199 |
import torch
def rgba_to_rgb(image):
"""
Convert an image from RGBA to RGB.
"""
if not isinstance(image, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 4:
raise ValueError(f"Input size must h... | a779503844e76fd5632385aa57519801afeb7e65 | 659,200 |
import os
import codecs
import json
def get_json(filename, work_dir=None):
"""
Reads a json file.
"""
path = filename
if work_dir is not None:
path = os.path.join(work_dir, filename)
with codecs.open(path, encoding="utf-8") as file:
result = json.load(file, encoding="utf-8")
... | fbc21f700346a29f15fa66897f7db06366203c78 | 659,201 |
def assign_label(offsets, terms):
"""
Assign BIO label to each word of the sentence.
"""
terms_sentence = []
if len(terms) == 0:
lst = [['O'] * len(offsets)]
return lst, lst, terms_sentence
max_level = max([item[-1] for item in terms])
lst = []
# nner
lst_term = []
... | 35ab9a069d0882ced2a878591c0379dec6b56796 | 659,202 |
import os
def normpath(p):
"""
Norm a path as Unix-like separator
:type p: str
:param p: The path
:rtype: str
:return: The normed path
"""
return os.path.abspath(p).replace('\\', '/') | 4a63e25070cfc0b0e409e258d5eac2f11394d613 | 659,203 |
import sys
import os
def _get_python_info():
"""Collect and return information about the Python environment"""
pyinfo = {
"Python Version" : ".".join(str(num) for num in sys.version_info),
"Python Executable": sys.executable,
}
pypath = os.environ.get("PYTHON_PATH", None)
if py... | a925396abab967fde0f4e3a1f7c95cb8f4b19763 | 659,204 |
def pass_bot(func):
"""This decorator is deprecated, and it does nothing"""
# What this decorator did is now done by default
return func | b8043b87b762db9f7b78617ad253aaca9dcd4369 | 659,205 |
import logging
def create_project_subnet(neutron_client, project_id, network, cidr, dhcp=True,
subnet_name='private_subnet', domain=None,
subnetpool=None, ip_version=4, prefix_len=24):
"""Create the project subnet.
:param neutron_client: Authenticated neutr... | 9d5deb2dfbda78800d9c6c3b35f8bf940a5909e2 | 659,206 |
from typing import Mapping
from typing import Union
from typing import Tuple
from typing import Dict
from typing import Any
def construct_url_from_shorthand(
match_dict: Mapping[str, str]
) -> Union[str, Tuple[str, Dict[str, Any]], None]:
"""Attempt to translate the given short-hand to a valid kraken API url.... | 590294b9c40c53895f827aeb1a4a908a4f68585f | 659,207 |
def internal_pressure(P_d, P_h):
"""Return total internal pressure [Pa].
:param float P_d: Design pressure [Pa]
:param float P_h: Pressure head [Pa]
"""
return P_d + P_h | d211f5cf7357cfa5281f77b33ac1c8fc1f9cac94 | 659,209 |
def get_channel(pika_connection, queue):
"""Set up a channel and a queue for a given pika connection."""
channel = pika_connection.channel()
channel.queue_declare(queue=queue, durable=True,
exclusive=False, auto_delete=False)
return channel | c3abfa38b4a6f84340f56347dd0af157a019c93b | 659,210 |
import random
def keep_fraction(l, f):
"""Return fraction `f` of list `l`. Shuffles `l`."""
random.shuffle(l)
count = int(f * len(l))
return l[:count] | b499d9c892bc17f4397b45adafaf67dfb9f6cd17 | 659,211 |
def pred(ordinal):
""" Predecessor of the ordinal.
"""
if '_pred' in dir(ordinal):
return ordinal._pred()
else:
raise TypeError("Must be given an Ordinal.") | ab6931788edbf6e211003f93e85997e8d55b9bf3 | 659,213 |
def list_to_space_string(l):
"""Return a space separated string from a list"""
s = " ".join(l)
return s | be558a1b97ee27a9e61c0efef3b50db30f9cc06a | 659,214 |
def _ComplexSentenceAsFlatList(complex_sentence, prefix=""):
"""Expand complex_sentence into a flat list of strings
e.g. ['NUMBERED'] ['IDS', 'INES'] ['SOLUTION']
to ['NUMBERED ID SOLUTION', 'NUMBERED INES SOLUTION']
"""
results = []
next_start = complex_sentence[1:].find('[')
if nex... | d3f8a7821da810feb03d5368df8c5eb06889cb1f | 659,216 |
import torch
def L1_Loss(outputs, label):
"""Computes the rrmse value"""
# error = torch.abs(outputs-label)/(label + 0.004)
# rrmse = torch.mean(error.view(-1))
print(label.size())
print(outputs.size())
Loss = torch.nn.MSELoss()
# print(Loss)
return Loss(outputs, label) | 78733b60f929da7fe01229de5a7dd8fcdff27d7f | 659,217 |
def get_employee_project_months(employee, month):
"""Calls the same method on the ``Employee`` instance."""
return employee.get_employee_project_months(month) | b0aed0d70f7344365d7e47c260bc757968ae9891 | 659,218 |
def arg_meta(*arg_flags, **arg_conf):
"""
Return a tuple `(arg_flags, arg_conf)` that contains argument flags & argument config.
`arg_flags`: A tuple contains argument flags
`arg_conf`: A dict containsf argument config
"""
return (arg_flags, arg_conf) | c626b4efe6338195253d58b759662398a1ecb9d1 | 659,220 |
def get_maintainer(file_data):
"""
Return the value of maintainer.
"""
for individual in file_data:
if 'maintainer' in individual:
maintainer = individual.split('"')
return maintainer[1] | 286dabe80cd3c61d892a241a4f2875f0ec87a8f8 | 659,221 |
def chamfer_dist(pc1, pc2):
"""Chamfer distance between two point clouds."""
N = pc1.shape[1]
M = pc2.shape[1]
pc1_expand = pc1.unsqueeze(2).repeat(1, 1, M, 1)
pc2_expand = pc2.unsqueeze(1).repeat(1, N, 1, 1)
pc_diff = pc1_expand - pc2_expand
pc_dist = (pc_diff ** 2).sum(-1)
# pc_dist =... | 6401099dcb1fc4e833683a57484d8e1cf1284fa9 | 659,223 |
def get_table_model_data_in_array(table):
"""
:param QtGui.QTableView table:
:return:
"""
model = table.model().sourceModel()
data = []
for row in range(model.rowCount()):
data.append([])
for column in range(model.columnCount()):
index = model.index(row, column)
... | 912eb12f09e3cceae0b95c912d82aee11d9f3761 | 659,224 |
import random
def generate_id():
"""Generate a random 4 digit unique number"""
val = 0
while len(set(str(val))) != 4:
val = random.randint(1000, 9999)
return val | 3bc1671c30f7c7467a9ef8d2b18ad32b85306468 | 659,225 |
import argparse
def parse_arguments():
"""Parse the command line"""
parser = argparse.ArgumentParser(description="Extract the spectrum of an outgoing particle at a given energy")
# Required command line options
parser.add_argument('ENDF', type=str, help='the ENDF file(s) whose cross section you want ... | 1628c92ae0f2efff8d37263be72f4b096a0afdaf | 659,226 |
def sec2HMS(sec):
"""Convert time in sec to H:M:S string
:param sec: time in seconds
:return: H:M:S string (to nearest 100th second)
"""
H = int(sec//3600)
M = int(sec//60-H*60)
S = sec-3600*H-60*M
return '%d:%2d:%.2f'%(H,M,S) | 216bb1ca1eb57ceea06d93ae8b83c752b9d42c8a | 659,227 |
def dot_product(a, b):
""" Return dot product between two vectors a & b. """
a1, a2, a3 = a
b1, b2, b3 = b
return a1 * b1 + a2 * b2 + a3 * b3 | 4f02efd1d0520284c547790faf3b1200812ebe67 | 659,228 |
def table_exists(cursor, table_name):
"""
Checks if the table table_name exists in the database.
returns true if the table exists in the database, false otherwise.
:param cursor: the cursor to the database's connection
:type cursor: Cursor
:param table_name: the name of the table searching for
... | 230b250203a2d5ba5153b28f10154d8f947a4264 | 659,229 |
async def async_setup(hass, config):
"""Stub to allow setting up this component.
Configuration through YAML is not supported.
"""
return True | 217771c0d766294785787851fda0d66ad6a95148 | 659,230 |
def _parse_commit_response(commit_response_pb):
"""Extract response data from a commit response.
:type commit_response_pb: :class:`.datastore_pb2.CommitResponse`
:param commit_response_pb: The protobuf response from a commit request.
:rtype: tuple
:returns: The pair of the number of index updates ... | dcb9083feb15233bf30d2b97599d08d7a7a611ee | 659,231 |
def squares(num_list):
"""assumes num_list is a list of numerics
returns a list of squares of each elem of num_list"""
square_list = []
for num in num_list:
square = num**2
square_list.append(square)
return square_list | fbbaaef36e731e8ed832401902f9ce4c626169d4 | 659,232 |
def aprioriGen(Lk, k):
"""
输入频繁项集列表 Lk 与返回的元素个数 k,然后输出候选项集 Ck。
例如: 以 {0},{1},{2} 为输入且 k = 2 则输出 {0,1}, {0,2}, {1,2}.
以 {0,1},{0,2},{1,2} 为输入且 k = 3 则输出 {0,1,2}
仅需要计算一次,不需要将所有的结果计算出来,然后进行去重操作
Args:
Lk 频繁项集列表
k 返回的项集元素个数(若元素的前 k-2 相同,就进行合并)
Returns:
retList 元素两两合并的数据集
... | 367294209948397e80ed9b45a0d8122eb3b33e2b | 659,233 |
import six
def FormatDuration(duration):
"""Formats a duration argument to be a string with units.
Args:
duration (int): The duration in seconds.
Returns:
unicode: The formatted duration.
"""
return six.text_type(duration) + 's' | 7221949968750ab543795a220ab30875840d8ec2 | 659,234 |
import torch
def vectorized_topk(scores: torch.Tensor, k: torch.Tensor, dim: int):
"""Return top k scores for every k in the given dimension.
Args:
x (torch.Tensor): Scores to be used
k (torch.Tensor): k is of size (batch_size)
dim (int): Across this dimension
"""
max_n = int(... | 8c94e90905a3ac53408a009cf17962c707b1073a | 659,235 |
def sunday(text, pattern):
"""sunday string match
Args:
text, pattern
Returns:
int: match index, -1: not match
"""
# get index from right
char_right_idx_dict = dict()
for i in range(len(pattern)):
# right pos char will replace left
char_right_idx_dict[patter... | 7fe59a98c1ce7a987b0335b8079914e35dddad23 | 659,236 |
import random
import string
def sec_token():
"""Generate a secure token that is cryptographically secure.
"""
return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(25)) | e69c3a542cd339e0f115613bd386ba04016becfe | 659,237 |
import pandas as pd
def clean_data(type, data):
"""
Prepares the data for the project.
:param type: String. The data source being to be cleaned. "pbp" for play by play, "weather" for weather.
:param data: DataFrame. The data being prepared. Should match the type.
"""
if type == "pbp":
... | 14cc48711aa629693c709c32bdec447780037290 | 659,238 |
import argparse
def list_action(list_class):
"""
Action to take a list of values and make them values in the list of type
list_class. Which will be a class descendent from AsyncContextManagerList.
"""
class ParseExpandAction(argparse.Action):
def __call__(self, parser, namespace, values, ... | 76108040db0989f232d16a6e3884c7c06967cb50 | 659,239 |
def object_is_valid_pipeline(o):
""" Determines if object behaves like a scikit-learn pipeline. """
return (
o is not None
and hasattr(o, "fit")
and hasattr(o, "predict")
and hasattr(o, "steps")
) | dac937a63fd7ad3164b851e4a6e7d02c081ace28 | 659,240 |
def expand_address_range(address_range):
"""
Expand an address if bits are marked as optional
Args:
address_range (str): The address to expand
Returns:
list(str): A list of addresses this address has been expanded to
"""
if "X" in address_range:
res = expand_address_ra... | 25fb35b28541c5260b23b5829bf2c2ed2082fc86 | 659,241 |
def get_rel_score(row):
"""
A function that is used in apply on Dataframes
Returns the predicted Survival rate at the visit time
"""
return row[row.loc["21003-4.0"]] | c498df2eec9859db9a6d953d41e12c7858a80bb4 | 659,242 |
def mandelbrotCalcRow(y, w, h, max_iteration = 1000):
""" Calculate one row of the mandelbrot set with size wxh """
y0 = y * (2/float(h)) - 1 # rescale to -1 to 1
image_rows = {}
for x in range(w):
x0 = x * (3.5/float(w)) - 2.5 # rescale to -2.5 to 1
i, z = 0, 0 + 0j
c... | 21f285b9bc9da2888e95e190c2e32014162a519f | 659,243 |
def mass_transfer_coefficient_mishra_kumar(wind_speed):
"""
Return the mass transfert coefficient [m/s] only from wind speed
source:(Berry et al., 2012)
Parameters
----------
wind_speed : Wind speed 10 meters above the surface [m/s]
"""
return 0.0025 * (wind_speed**0.78) | e65e035b0046c2e7fd351689a440e413ec8fc5c3 | 659,244 |
import os
def get_interface_names():
"""
Return the names of the network interfaces available on this system
:return: list of strings
"""
return os.listdir('/sys/class/net/') | 5e05425264621db42604e0ee3147970ee105c933 | 659,246 |
import time
def mujoco_rgb_from_states(env, sim_states, time_delay=0.008):
"""
Given the states of the simulator, we can visualize the past Mujoco timesteps.
- Simulator states are obtained via env.sim.get_state()
"""
rgb = []
for t in range(len(sim_states)):
env.sim.set_state(sim_... | 8988419cf2c4b981aa6bd611c40c06c031ddfe1d | 659,247 |
def average(values):
"""Calculates the average value from a list of numbers
Args:
values (list)
Returns:
float: The average value"""
if len(values) == 0:
return None
return sum(values)/len(values) | b5bd318e3e6dd0659aa3c62b1f28e3f6ce252015 | 659,248 |
def find_slack_handle(socials: dict):
"""Search social media values for slack
:param socials:
:return:
"""
if 'slack' in socials:
return socials['slack']
else:
return 'marty331' | 32dc2e48fbd27b39a584174bb7252747b8158764 | 659,249 |
def same_subtitle(subtitle1, subtitle2) -> bool:
"""Check if same subtitle, needed because other attributes can be differ"""
if subtitle1 == subtitle2:
return True
if subtitle1 is None or subtitle2 is None:
return False
if (subtitle1['name'] == subtitle2['name'] and
subtitle1[... | cb60a70d64e33807ab7514a9bd777728de6c17e2 | 659,250 |
import itertools
def _group_insertions(sortedlist, keys):
"""
Given a list of keys to insert into sortedlist, returns the pair:
[(index, count), ...] pairs for how many items to insert immediately before each index.
ungroup(new_keys): a function that rearranges new keys to match the original keys.
"""
... | ad51486e6e213db098c9549f6fa0817ef8a766b8 | 659,251 |
def alphastring(s):
"""
>>> alphastring('abc')
'abc'
>>> alphastring('.h')
'_h'
>>> alphastring('&/')
''
>>> alphastring('test.txt')
'test_txt'
"""
return ''.join([x for x in s if x.isalnum() or x == '.' or x == '_']).replace('.', '_') | 6eb86e9244a7e4ba0d587e80b007051706a5b9f7 | 659,252 |
def get_requirements_text(repo_dependencies):
"""
:param repo_dependencies: A list of git repositories. You can optionall add pip arguments such as '-e' (install as source).
e.g.: ['-e git+http://github.com/QUVA-Lab/artemis.git#egg=artemis', '-e git+http://github.com/petered/plato.git#egg=plato']
:... | a3fb142d7a5013d2aebfc0bdb9351a5ebb6a05d0 | 659,254 |
import re
import random
def load_chinese_dataset():
"""
加载中文数据集
:return: 中文数据
"""
tagged_sents = list()
with open('./data/000001-010000.txt') as f:
flag = True
for line in f.readlines():
if flag:
tagged_sent = line.strip().split('\t')[-1]
... | 5a3ad692e4e3ce6130b14e7017f6dd472299a9fa | 659,255 |
def ge(y):
"""ge(y)(x) = x > y
>>> list(filter(ge(3), [1,2,3,4,5]))
[3, 4, 5]
"""
return lambda x : x >= y | 0a19da5e795b9b920e116ad6e25810b2e317ce9a | 659,256 |
import struct
def _read_header(data):
"""
Returns the header portion of the given data
"""
return struct.unpack('<BBBI', data[:7]) | 61324470885f1df613845cffce6300094acdeee0 | 659,257 |
def subListInSexp(sexp, xys):
"""Given a list of tuples of the form xys = [(x1, y1), ..., (xn, yn)]
substitute (replace) `x` with `y` in `sexp`
i.e. returns `sexp[y1/x1, ..., yn/xn]`
"""
d = dict(xys)
if type(sexp) != list:
return (d[sexp] if sexp in d else sexp)
else:
retur... | cfd90c1403a47c7b0a2266d09316350e87af24ef | 659,258 |
import numpy
def nafe_drake(f):
"""
Density derived from V_p via Nafe-Drake curve, Brocher (2005) eqn 1.
"""
f *= 0.001
f = f * (
1.6612 - f * (0.4721 - f * (0.0671 - f * (0.0043 - f * 0.000106))))
f = numpy.maximum(f, 1.0) * 1000.0
return f | de44f6c89601891d5998434aa97a51e2da982b21 | 659,259 |
def _tower_job(db_row, tower_data):
"""
Utility to format DB row and Tower data into valid TowerJob as defined in
OpenAPI schema.
"""
return {
**db_row.to_dict(),
'status': tower_data['status'],
'created_at': tower_data['created'],
'started': tower_data['started'] is ... | 16f2bef87d91566b293b2dc1fc8eeb2c9b90b9cc | 659,260 |
def str2float(value: str):
""" Change a string into a floating point number, or a None """
if value == 'None':
return None
return float(value) | 00094612c7ea44bd68a7fb411fd22a7962a24874 | 659,261 |
import sys
def process_footnote(rest, pattern, lineno, encoding='ascii'):
""" handle "@footnote{ text } """
footnotebytes = bytearray('', encoding)
while ( len(rest) > 0 ):
m = pattern.match(rest)
if m:
print("%s:unexpected match: %s, line: %d" % (__name__,m.group(0),lineno))
... | 4d71202254f4f7b49a6a333f5f9e6d7c6d8b7c7f | 659,262 |
import os
import pathlib
def _sandbox_directory() -> str:
"""Return full path to Algorand's sandbox executable.
The location of sandbox directory is retrieved either from the SANDBOX_DIR
environment variable or if it's not set then the location of sandbox directory
is implied to be the sibling of thi... | b56a55dad2a401f2dba589e2d0d6554442400716 | 659,263 |
def split_at(s: str, i: int):
"""Returns a tuple containing the part of the string before the
specified index (non-inclusive) and the part after the index
"""
return (s[:i], s[i:]) | a7a064c95c0fec94af03a1fa79c8225e0d9c4cf9 | 659,264 |
def get_shades_pink():
"""
Gets the different shades of pink.
"""
pink = "#FFC0CB"
hot_pink = "#FF69B4"
deep_pink = "#FF1493"
pink_lace = "#FFDDF4"
cherry_blossom_pink = "#FFB7C5"
light_hot_pink = "#FFB3DE"
lavender_pink = "#FBAED2"
rose_pink = "#FF66CC"
light_deep_pink =... | 6b46b27668c33852091dae9830861564738a8dae | 659,265 |
def octal_to_string(octal):
"""The octal_to_string function converts a permission in octal format into a
string format."""
result = ""
value_letters = [(4,"r"),(2,"w"),(1,"x")]
for digit in [int(n) for n in str(octal)]:
for value, letter in value_letters:
if digit >= value:
... | 3ed15831d37338e1e290f2e2afbeafd0a922e6a0 | 659,266 |
def item_at_index_or_none(indexable, index):
"""
Returns the item at a certain index, or None if that index doesn't exist
Args:
indexable (list or tuple):
index (int): The index in the list or tuple
Returns:
The item at the given index, or None
"""
try:
return i... | 32ad95f8368067afe2966e04ec91d806344cc859 | 659,267 |
def dict_to_string(formula):
"""
Convert a dictionary formula to a string.
Args:
formula (dict): Dictionary formula representation
Returns:
fstr (str): String formula representation
"""
return ''.join(('{0}({1})'.format(key.title(), formula[key]) for key in sorted(formula.keys(... | 48ac8fd9cec60e14e76417a12ce9c8ae22ef4052 | 659,268 |
def parse_color(color):
"""Take any css color definition and give back a tuple containing the
r, g, b, a values along with a type which can be: #rgb, #rgba, #rrggbb,
#rrggbbaa, rgb, rgba
"""
r = g = b = a = type = None
if color.startswith('#'):
color = color[1:]
if len(color) == ... | f58331287e4ccc1f2459c1ffff4c0f3ec5f29d8b | 659,269 |
def _parse_free_spaces(string):
"""
Parses the free spaces string and returns the free spaces as integer.
Input example (without quotes): "Anzahl freie Parkplätze: 134"
"""
last_space_index = string.rindex(" ")
return int(string[last_space_index+1:]) | 21c599e7bc94d34d8dd6258d12443cc762d08cb2 | 659,270 |
from functools import reduce
def flatten_shape(input_shape, axis=1, end_axis=-1):
""" calculate the output shape of this layer using input shape
Args:
@input_shape (list of num): a list of number which represents the input shape
@axis (int): parameter from caffe's Flatten layer
@end_a... | 4961d31ce6c40f2434a50f90e530226c9148ce5d | 659,271 |
def int_def(value, default=0):
"""Parse the value into a int or return the default value.
Parameters
----------
value : `str`
the value to parse
default : `int`, optional
default value to return in case of pasring errors, by default 0
Returns
-------
`int`
the p... | b4394805007c9dcd8503d3062f76aa6840672604 | 659,272 |
def array_str(array, fmt='{:.2f}', sep=', ', with_boundary=True):
"""String of a 1-D tuple, list, or numpy array containing digits."""
ret = sep.join([fmt.format(float(x)) for x in array])
if with_boundary:
ret = '[' + ret + ']'
return ret | 20ba09133061061c414e2ba56e7635e97226ecf6 | 659,273 |
import collections
def load_lexicon(path, src_vocab, trg_vocab, encoding='utf-8', verbose=False):
"""
path: str
src_vocab: Vocab
trg_vocab: Vocab
encoding: str
verbose: bool
returns: collections.defautldict
"""
lexicon = collections.defaultdict(set)
vocab = set()
with open... | c85ff0e23591a46bd78ff43b894b378c422b453e | 659,274 |
def readline( file, skip_blank=False ):
"""Read a line from provided file, skipping any blank or comment lines"""
while 1:
line = file.readline()
if not line: return None
if line[0] != '#' and not ( skip_blank and line.isspace() ):
return line | 2350d9b5a8fbd449a1c70c8676865c15b4a56a4b | 659,275 |
def compute_sum(v, fg):
"""Compute the sum of a variable v already marked to be summed.
Sum over the given variable and update the factor connected
to it. (akin to marginalization)
Note that the variable v must have only one edge to a factor, so that the
sum is forced to be a simple linear order c... | cbe5d2f1781a7fae65151c4f4d937269eef2ef59 | 659,276 |
def scan_cluster_parsing(inp, cluster_threshold_kruskal, cluster_threshold_beta, cluster_threshold_vip, cluster_threshold_vip_relevant, cluster_orientation, cluster_vip_top_number, cluster_mean_area, cluster_labelsize_cluster, cluster_figsize_cluster):
"""
Initialize cluster analysis.
Initialization functi... | c2a9e3de143b5482c8c6ffb5274a6dd38e26fd99 | 659,277 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.