content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import argparse
def parse_args():
"""Uses argparse module to parse command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('--tpu_name')
parser.add_argument('--save_dir')
parser.add_argument('--restore_dir')
parser.add_argument('--use_pmap', action='store_tr... | a09c389a836dd8f06a2af08cafbe9387dd8aff68 | 669,468 |
def block_num_to_hex(block_num):
"""Converts a block number to a hex string.
This is used for proper index ordering and lookup.
Args:
block_num: uint64
Returns:
A hex-encoded str
"""
return "{0:#0{1}x}".format(block_num, 18) | 88865256e07fdcebdff440aea964f26707931735 | 669,470 |
def rebuild(expr):
""" Rebuild a SymPy tree
This function recursively calls constructors in the expression tree.
This forces canonicalization and removes ugliness introduced by the use of
Basic.__new__
"""
try:
return type(expr)(*list(map(rebuild, expr.args)))
except Exception:
... | e77b33cbcab5c47384de6fd89407c16f17e2ead8 | 669,471 |
def forward_differences(f, h, x):
"""
Forward Finite Differences.
Approximating the derivative using the Forward
Finite Method.
Parameters:
f : function to be used
h : Step size to be used
x : Given point
Returns: Approximation
"""
return (f(x + h) - f(x)) / h | 4e94c8ac1f05c86ea78e971b60ed6da0b3e845d4 | 669,472 |
from textwrap import dedent
def listify(supposed_lst:object=None):
"""
- When only providing a single element, it's easy to forget to put it inside a list!
"""
if (supposed_lst is not None):
if (not isinstance(supposed_lst, list)):
supposed_lst = [supposed_lst]
# If it was already a list, check it for empt... | feb62081617d4f14e0e9dc22aaeedac02a459cad | 669,473 |
from typing import Tuple
def bool_(buffer: bytes, offset: int = 0) -> Tuple[bool, int]:
"""
Unpack bool from Starbound save file.
:param buffer: Starbound save file
:param offset: position in Starbound save file
:return: bool, new offset
"""
return bool(buffer[offset]), offset + 1 | 25643ed6a765f562302ca35bcabd0cd23c3d72ac | 669,474 |
def get_job_main_info(job):
"""
Return a dictionary with the pieces of information that will be presented on the terminal.
:param job: A Job object provided by ScrapingHub
:return: A dictionary
"""
info = job.info
main_info = {
'id': job.id,
'spider': info.get('spider'),
... | b23679cfe8e4996d120e958929f7663d5662d1cf | 669,475 |
import json
def user_io_loop(settings: dict):
"""
This function is run on the main process as it interacts with the user.
It asks for some command and it executes the proper task if the input
was recgonized.
Parameters
----------
settings : proxy dict
shared dictionary with inform... | 6fa13628d654ad5493ad552db46323b40abac53a | 669,476 |
def pad_source(src, PAD, vocab=None):
"""
src: [n, T1]
"""
if vocab is not None:
src = [[vocab[w] for w in s] for s in src]
PAD = vocab[PAD]
max_len = max(len(s) for s in src)
for s in src:
s += [PAD] * (max_len - len(s))
return src, max_len | c855929998e26dee10c495f977f7e27ef5e56866 | 669,477 |
def remove_action(actions, name):
"""
Find all the occurrences of actions with a given name and return them and remove them from the list
:param actions: List of actions
:param name: str name to find
:returns: List of actions matching the given name
"""
matching = [action for action in ac... | 3b8bc0d0081b1bf41c58c3504f2101b42ce1d70f | 669,479 |
def version_get(v1, v2):
"""Check if version v1 is great or equal then version v2.
"""
return [int(i) for i in v1.split('.') if i.isdigit()] > [int(i) for i in v2.split('.') if i.isdigit()] | 78b7fdf4e8dcd87ff02c2fd0c4786ce55f24c3af | 669,480 |
from typing import Optional
def get_dag_id(this_dag_name: str,
parent_dag_name: Optional[str] = None) -> str:
"""Generates the name for a DAG, accounting for whether it is a SubDAG.
Args:
this_dag_name: A name for this individual DAG.
parent_dag_name: The name of the parent DAG of this DAG... | 14ffbbec93e31eed431bcbb4c94c9a82beb3491e | 669,481 |
def get_tagstring(refid, tags):
"""Creates a string from a reference ID and a sequence of tags, for use in report filenames."""
return "_".join([refid] + [t[0] + "." + (t[1] if t[1] else "None") for t in tags]) | 8ab5b461482194c2beabb861bd17c0fff91a15fa | 669,482 |
def GetLogFileDir():
"""Returns the directory set to store the environment file."""
return "/tmp" | a4bc23511e7853d01dfd5a9fec4576e229d5f24c | 669,483 |
def zahlen_rechts_oben(seitenlaenge):
"""gibt die Zahlen der Diagonalenhälfte rechts oben aus einer spiralförmigen Zahlenmatrix der Seitenlänge seitenlaenge als Liste aus (ohne 1)"""
anzahl = int((seitenlaenge-1)/2)
zahl = 1
summand = 2
zahlen = []
for i in range(anzahl):
zahl = zahl + s... | 5f627385d40d8bc9da790f15e89a6607d45aab12 | 669,484 |
def _prefixes():
"""
Defines prefixes for powers of ten. This function is not meant to be
called directly.
"""
return {
'Y': {'longform':'yotta', 'dimension':24},
'Z': {'longform': 'zetta', 'dimension':21},
'E': {'longform': 'exa', 'dimensi... | e1cd2c3cefae6c39082a56ec01ee74140607e183 | 669,485 |
def _pf1c(val1, val2):
"""
Returns
-------
Description for the return statement
"""
return int(val1 + int(val2[0])) | 361e7190936de78b144eea50ee45325a4d266382 | 669,486 |
import os
import imp
def get_module():
"""Return module."""
init_path = os.path.join(
os.path.realpath(os.path.join(os.path.dirname(__file__))),
'admin_page_lock', '__init__.py')
return imp.load_source('page_lock', init_path) | 0322c9f6da17bb9b4f93749dbde74c7803f245a3 | 669,487 |
def emptyCells(notebook):
"""
Finds the tag 'empty' in each cell and removes its content
Returns dict with empty cells
"""
clean = []
for cell in notebook['cells']:
try:
tags = cell['metadata']['tags']
if True in map(lambda x: x.lower().startswith('empty'), tags... | b8d4585d99628a680ef00a1a05623500bf395c0c | 669,488 |
import itertools
def all_liouville_subspaces(hilbert_subspace):
"""
Given a Hilbert subspace, return a comma separated list with all included
Liouville subspaces
Example
-------
>>> all_liouville_subspaces('ge')
'gg,ge,eg,ee'
"""
return ','.join(''.join(s) for s
... | c366dc36c182ea71bad527a7140eaeea54242071 | 669,489 |
def append_to(__all__):
"""
Class and function decorator to include the name in __all__.
A common use case for __all__ is to mark a group of classes or
functions that have something in common for wildcard export,
while other classes or functions defined in the same module
... | a7d029f34c4b24186e14dfeae3d2aca1f833fe1d | 669,490 |
def image_name():
"""Returns image name that is used in tests."""
return 'python:3.6.6-alpine' | e698687f65bd55652744952d0cd9c42d1223026b | 669,491 |
def normalize_btwn_0_1(list_obj):
"""
Takes a list and normalizes the values from 0 (smallest) to 1(largest)
"""
return (list_obj-min(list_obj))/(max(list_obj)-min(list_obj)) | b6b7bd4a7141c3254d46a8df1c92fe03432a63fb | 669,492 |
def get_light_positions(rays_i, img_light_pos):
"""Extracts light positions given scene IDs.
Args:
rays_i: [R, 1] float tensor. Per-ray image IDs.
img_light_pos: [N, 3] float tensor. Per-image light positions.
Returns:
rays_light_pos: [R, 3] float tensor. Per-ray light positions.
... | b96327e8104439ed466946a2e890e2e42d5337a0 | 669,493 |
import torch
from typing import OrderedDict
def load_pretrained_weights(net, path, replace_key=None, skip_key=None, required_key=None):
"""Loads pretrained weights from the path on disk to the network.
This is a utility function to handle loading pretrained weights from disk
to the network. This function... | c70288a5b21fbee9fc4c52321a23619dc58d2997 | 669,494 |
def has_sublist(superlist, sublist):
"""
Does a list contain another list within it?
Not very efficient.
If 'eq' is given, this will be used to compare items.
"""
return any(
superlist[i : i + len(sublist)] == sublist
for i in range(len(superlist) - len(sublist) + 1)
) | 5af69cdc51fe141522c963b58e2006400bcf0f19 | 669,497 |
def MSEevaluation(y, predict):
"""
Evaluate predictions the mean sqaured error
:param y: original values
:param predict: predicted values
:return: the mean squared error of the predicted values
"""
n = len(y) # number of... | d90666ef39d6b75895ee3b7757d4fd6fead3a434 | 669,499 |
import time
def CurrentTimeSec():
"""Returns a float of the current time in seconds."""
return time.time() | e629f933d6c2cb50dc614fd579fa87fd06a7aea1 | 669,500 |
import os
def ensure_directories(path):
"""Create directories for the path if they don't exist
Parameters
----------
path : The path in question. Can also contain a filename
Examples
--------
>>> path = utils.path_to('data', 'data-set', 'data.csv')
>>> utils.ensure_directories(path)
... | 6a498299b3fd3278772262cc96fdf7f412d52fb5 | 669,501 |
def find_kernel_diameter(K):
"""Find the diameter of the polytope in RKHS"""
n = K.shape[0]
best_max = 0
best_indices = [0, 0]
current_max = 0
current_indices = [0, 0]
for i in range(0, n):
for j in range(0, i+1):
current_max = K[i, i] + K[j, j] - 2*K[i, j]
cu... | 407722ab520ef4d9af7d2589b38c5ba3cdd51a39 | 669,502 |
def get_xml_node_value (root, name):
"""
return the value from an XML node, if it exists
"""
node = root.find(name)
if node:
return node.text
else:
return None | abf6de764889a3c847089372ad99803971b39e3a | 669,503 |
import argparse
def validate_ext(ext):
"""Validate extension option\n
Give an error if argument contains '/' or backslash
"""
err1 = "illegal character in extension"
if "/" in ext or "\\" in ext:
raise argparse.ArgumentTypeError(err1)
return ext | 0274e99d90b9ec2bba5525ace60c8dfcddf7a8c9 | 669,504 |
def get_first_arg(args, kwargs, name):
"""Returns named argument assuming it is in first position.
Returns None if not found.
Args:
args (tuple or list): args from function.
kwargs (dict): kwargs from function.
name (str): argument name
"""
try:
return kwargs[name]
... | accd9389853ea7bc8821e3cbee093292174ede80 | 669,505 |
def simpleVoigt(vsh,vsv):
"""
seis_model.simpleVoigt(vsh,vsv)
voigt average of horizontal and vertical shear wave velocities
v = 0.5 * (vsh + vsv)
Parameters
-----------
vsh horizontal shear wave velocity, array or scalar
vsv vertical shear wave velocity, array or scalar
... | 0e25c0fc9873e5073687df2fbb87d2a7a9572645 | 669,506 |
import random
def get_uniform_crossover_function():
"""
Returns a function that applies uniform crossover (each gene value is chosen at random from the parent genes); see :ref:`crossover-functions`
:Valid For:
any gene type
:returns: a function that accepts a list of parent genes and ap... | c913eb9ab9c8dd2a28d9ff24e8fb3643fbbe49f4 | 669,507 |
def generate_qubo_single_threaded(exact_cover, b=1):
"""Generates an upper triangular QUBO matrix for the given exact cover"""
a = len(exact_cover) * b + 1
q = dict()
for j, cur_subset in enumerate(exact_cover):
q[(j, j)] = -len(cur_subset)
for i, oth_subset in [(i, oth_subset) for i, ot... | b9549543816618cf76ab603e86d9301dbac9fee0 | 669,508 |
def add_filter(req_filter, request=''):
"""
Parameters
----------
req_filter : str
string shaped like "key":"val" or "key":{"op":"val"}
request : str (optional)
request string shaped like: {"key1":{"op1":"val1"}[,"key2":{"op2":"val2"}]*}
Returns
-------
str
... | 7d833435a2e4ead5f3d9e17571915e6768c9ebda | 669,509 |
import functools
def noop_if_no_unpatch(f):
"""
A helper for PatchTestCase test methods that will no-op the test if the
__unpatch_func__ attribute is None
"""
@functools.wraps(f)
def wrapper(self, *args, **kwargs):
if getattr(self, '__unpatch_func__') is None:
return
... | b6e8829b9a04d9acdb53bfeb9b084652942eb870 | 669,510 |
def communicator(manager):
"""Get the ``Communicator`` instance of the currently loaded profile to communicate with RabbitMQ."""
return manager.get_communicator() | 67cacd93330f6ce5f15a6f0f57aaeef10928f27f | 669,511 |
def make_repr_html(obj):
"""
Make a nice HTML table
:param obj: Python object
:return: HTML string
"""
html_text = f'<h3>{obj.__class__.__name__} {obj.name}</h3>'
html_text += '<table><tbody>'
if hasattr(obj, 'package_names'):
html_text += '<tr><td>number of packages:</td>'
... | 0ec0d807e72f3cacb5af0fd17aa17dfd99432110 | 669,512 |
from typing import List
from typing import Optional
from typing import Dict
def package_item(errorHandlerTest: bool, failureHandlerTest: bool, data: str, aggregateList: List) -> Optional[Dict]:
"""Package item task definition.
Args:
errorHandlerTest (bool): One can set this flag (i.e. throught the AP... | d011300bee3511475a9914174ff00c897394d043 | 669,513 |
import re
def get_table_dividers(table):
"""
Receives a results table
Returns a list of divider rows (------)
"""
return [len(re.findall(r"^-{3,}$", line)) for line in table.split("\n")] | da3f971fd81207ab8d1a78605c31affb105ad968 | 669,514 |
import requests
def fetch_fuel_data():
"""Get basic fuel price data."""
return requests.get('http://www.fueleconomy.gov/ws/rest/fuelprices').text | 1a5caef4036a6de278795d00cb1a4c9e31522fac | 669,515 |
def pad_sents(sents, pad_idx):
"""
@param sents (list[list[int]]):
@param pad_idx (int): Pad ID
@return sents_padded (list[list[int]]): sents with padding according to max_sent_len
"""
max_len = 0
sents_padded = []
for sent in sents: max_len = max(max_len, len(sent))
for sent in sent... | dda76936615a155d0aeb1b5dcad196f76abc9be0 | 669,516 |
from datetime import datetime
def timestamp_to_weekday(timestamp):
"""
Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
"""
return int(datetime.fromtimestamp(timestamp / 1000.0).strftime("%w")) | fad8b84ee638adc80774993888ee4152ee76fc18 | 669,517 |
def calculate_manhattan_dist(config):
"""calculate the manhattan distance from:
- a given puzzle configuration for the A* search function
"""
hn = 0 # start with the heuristics function value being 0
for tile in range(1, config.n ** 2):
# evalute the distance from each tile in the cur... | 0b2844ba31fc83ee439fa5f8d2191e1dff7079dc | 669,518 |
def get_hook_config(hook_api, module_name, key):
"""
Get user settings for hooks.
Args:
module_name:
The module/package for which the key setting belong to.
key:
A key for the config.
Returns:
The value for the config. ``None`` if not set.
The ``get_... | 45cafd4586ed33c48386fa9a6d8e48251a154cc0 | 669,519 |
def mymult(ctx, a,b):
"""
a,b are scalars
"""
return a*b | 8079d1d75f4168494ff791af2ecc954d7a8b4bd9 | 669,520 |
def get_turn_off_descriptions(get_turn_off, initial_state, current_state):
"""
Get all 'turn off' descriptions from the current state (if any).
Parameters
----------
get_turn_off: function
Function that gets the color of light which is off.
initial_state: nd.array
Initial state o... | ccf18779c38bc76da98425334db4c2b9ef159033 | 669,521 |
import re
def create_cuda_compute_type_map(cuda_compute_type_enum_class):
"""
Map the data type name to the corresponding CUDA compute type.
"""
cuda_compute_type_pattern = re.compile("COMPUTE_(?:(?P<width>\d+)(?P<type>F|I|U|BF)|(?P<tf32>TF32))")
type_code_map = { 'i' : 'int', 'u' : 'uint', 'f' :... | 1c2ced11a84abf0ebabea70ef458acd01c0de2e3 | 669,522 |
from pathlib import Path
from typing import Dict
from typing import Tuple
import json
def packages_conf(
packages_conf_path: Path, cmds: Dict[str, str], read_only: bool = False
) -> Tuple[Dict[str, str], Dict[str, str]]:
"""
Write the packages.json config file and return the list
of packages dependenc... | d2b9439d77133d4ab0b49c89ce3f8562272b5dbe | 669,523 |
def addition(a,b):
""" renvoie le rapport des deux nombres passés en paramètre"""
return a+b | 2ceeb5ded3c0badc3980f6469d8db50b5113fd1c | 669,524 |
def replace_backslashes(path:str):
"""
Replaces the backslashes of string-paths with double forward slashes
:param path: a random path that might contain backslashes
:type path: str
:return: A string-path with forward slashes
:rtype: str
|
"""
return path.replace("/", "\\") | 988489832aed706dfe9d72e09cf2b62a2cdbb105 | 669,525 |
import torch
def compute_Xty(X_t, y_t, cm_t, csd_t):
"""
cm: column means of X
csd: column SDs of X
"""
ytX_t = torch.mm(y_t.T, X_t)
# scale Xty
scaled_Xty_t = ytX_t.T / csd_t.reshape(-1,1)
# center Xty
centered_scaled_Xty_t = scaled_Xty_t - cm_t.reshape(-1,1)/csd_t.reshape(-1,1) *... | 3837a623aad24325924681c6d50984f40ae7949f | 669,526 |
import logging
def get_logger(name):
"""
Return a logger with the specified name, creating it if necessary.
:param name: module name
:return: logging.Logger
"""
logging.basicConfig(level=logging.INFO,
format="%(asctime)s:%(levelname)s:%(name)s: %(message)s",
... | 9630e884ff553fe8267c3683234de270878b5b29 | 669,527 |
def UseExistingBootDisk(disks):
"""Returns True if the user has specified an existing boot disk."""
return any(disk.get('boot') == 'yes' for disk in disks) | 2e43eab6181b4a921f516b63289bf344de076e14 | 669,528 |
import os
def pwm_dir():
"""
Returns the directory of the expression dir
"""
return os.path.dirname(__file__) | fdfc844da06dbfb21c4b10015421a0c399f8b9b4 | 669,529 |
def comma_space(s):
"""
insert a space after every comma in s unless s ends in a comma
:param s: string to be checked for spaces after commas
:return s: improved string with commas always followed by spaces
:rtype: basestring
"""
k = s.find(',')
if -1 < k < len(s) - 1 and s[k + 1] != " "... | b50c45386b03f801dc01859f8f1b171703b1df44 | 669,531 |
import configparser
import re
def _get_dict_cases(config_file, cases=('LAMMPS', 'GROMACS')):
"""
Function to return a dictionary with regex patterns for the given cases and a rating of those.
Reads in the config_file.
Parameters
----------
config_file : str or List[str]
File path to t... | b3c1afd401bd748af2afbc7b28d9bcb822e24e0b | 669,532 |
import operator
def compute_ap(lists):
"""Compute Average Precision."""
lists.sort(key=operator.itemgetter("score"), reverse=True)
rels = 0
rank = 0
score = 0.0
for one in lists:
rank += 1
if one["label"] == 1:
rels += 1
score += rels/float(rank)
if rels != 0:
score /= float(rels... | 94875378f5576a3f6b630bd373134c4498aadf37 | 669,533 |
def prepare_data(text):
"""
Prepare data
"""
labels = [t.split()[0] for t in text]
labels = [l.split(':')[0] for l in labels]
X = [t.split()[1:] for t in text]
X = [' '.join(t) for t in X]
return X, labels | c5f15a30bb397c78b7a7b32d9b10f37b1e5caab6 | 669,534 |
def smiley(message):
"""
IMPORTANT: You should NOT use loops or list comprehensions for this question.
Instead, use lambda functions, any, map, and/or filter.
Make a function that converts specific characters to smiley faces.
>>> smiley("DSC20:(")
'DSC20:)(:'
>>> smiley(":e)k3o(")
... | 0e7e197c46a507bc064c79ad438ff31ad4a77aca | 669,535 |
import os
def capitalized_fn(afile):
"""
Checks provided file with the file on disk and returns the imput with
its exact capitalization on disk. In the second value the capitalization
is preserved if it was available.
Returns tuple: (exact, capitals)
exact: what's on disk
captials: the name with capitals (pr... | b7ea9a48ee97d3af8da7021621bc6ace8ce803ab | 669,536 |
def getweapontags():
"""Return all weapon tags"""
return ('primary', 'secondary', 'melee', 'pda', 'pda2', 'building') | c49098ef7c841beb915a7248018b2eb488418611 | 669,537 |
def _tx_resource_for_name(name):
""" Return the Transifex resource name """
if name == 'core':
return "django-core.core"
else:
return "django-core.contrib-%s" % name | 834cc4502d2cb7d59acc27131f5fbc60ae6f9bd5 | 669,538 |
def count(column):
"""
Funcion encargada de contar cuantas filas tiene una columna
"""
return len(column) | eab1a21cdc025d11cdb831b9faa264a3f599e093 | 669,539 |
def remove_similar_lists(lst, lengths_lst, medium_threshold = 200):
""" removes likely assembly errors near repeats by deconvulting medium length contigs
We have already filtered out short contigs, but there are still these that cause problemswith the graph tracing.
"""
# tmp is a list of equal length w... | 60fb1dd1c039e129e64811e4910a42c78ab2968f | 669,540 |
import numpy
def median(c):
"""
计算中位数
:param c: 数组
:return:
"""
return numpy.median(c) | 4a9d0f3287f3137b7032123499182adf2a2aa07d | 669,541 |
import subprocess
def run_command(cmd, input=None):
"""
Run the given cmd and handle the status
cmd is a string showing the command to run
"""
stdout = subprocess.check_output(
cmd.split(),
universal_newlines=True,
input=input,
)
return stdout | 56e1f668bbbe5e557e696d840c5370cd3a99bf4f | 669,542 |
def get_error(confusion_map):
"""error from a confusion map"""
error = 1 - confusion_map.diagonal().sum() / confusion_map.sum()
return error | bdf74f8e153f3a3b9ff33d1fbb91c40828e3dadf | 669,544 |
def flatten_dict(d):
"""
Function to transform a nested dictionary to a flattened dot notation dictionary.
:param d: Dict
The dictionary to flatten.
:return: Dict
The flattened dictionary.
"""
def expand(key, value):
if isinstance(value, dict):
return [(key... | 66201539b86931de50ce042ab2638bc0d679848a | 669,545 |
import re
def check_promo(text):
"""Inspects text and returns an inference of the promotion
('success', 'none', 'fail').
Input:
text -- UTF-8 text string (required | type: str).
Output:
promo -- promotion: 'success', 'none', 'fail' (type: str).
"""
promo = 'none'
password_... | 787001f7635517a523e4b85e8a8cd4cf4e80ef80 | 669,546 |
import json
def _get_dmaap_creds(dmaap_file):
"""Get DMaaP credentials from DCAE for publish and subscribe"""
streams = json.load(open(dmaap_file, 'r'))
pubs = [x for x in streams
if x['dmaapStreamId'] == 'requests' and x['dmaapAction'] == 'publish']
subs = [x for x in streams
... | 94e388404ea9895dcb049917ab3a582dab7b0bca | 669,548 |
import argparse
import os
def parse_args():
"""Parse input arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--motion_pth', type=str,
help='path to motion stream results dict')
parser.add_argument('-a', '--appear_pth', type=str,
... | ab87922dcfee9dd3eeac265a1e361c4b0fbd9636 | 669,549 |
import calendar
def get_last_friday_of_month(year, month):
"""Return the date of the last Friday in the month as an int."""
# calendar_for_month is a 2D list of days of the month, grouped by week.
# For example, December 2018 looks like this:
# [[ 0, 0, 0, 0, 0, 1, 2],
# [ 3, 4, 5, 6, 7... | 55778d3dc25cd11d2414ddfda79b106d7ee5424c | 669,550 |
def _lerp(A, B, t):
"""Perform Linear interpolation in 1D"""
return A * (1.0 - t) + B * t | 6fb29bad0cec2590b4bc9ad944054a55eacb5ac4 | 669,551 |
import six
def _clean_git_uri(uri):
"""Cleans VCS uris from pip9 format"""
if isinstance(uri, six.string_types):
# Add scheme for parsing purposes, this is also what pip does
if uri.startswith("git+") and "://" not in uri:
uri = uri.replace("git+", "git+ssh://")
return uri | f1294703ff024fb8fd115c97ef9405d9c06e0498 | 669,552 |
def _interpolate(a, b, fraction):
"""Returns the point at the given fraction between a and b, where
'fraction' must be between 0 and 1.
"""
return a + (b - a) * fraction | 47ae6935841a1cd3e941cde1df39a659303fe2ad | 669,553 |
from typing import Callable
import argparse
def _deploy_parser(
name: str,
desc: str,
localfunc: Callable,
serverfunc: Callable,
contextfunc: Callable,
) -> argparse.ArgumentParser:
"""Construct a argument parser for the deploy or redeploy commands."""
deploy_parser = argparse.ArgumentPars... | 94df0f7c378ee6594d6b588fe0ecb45f3303331a | 669,555 |
def gen_archive_script(bundle_path, lib_paths):
"""Produce ar-script output in 'bundle_path' from 'lib_paths'"""
ar_input = []
ar_input.append("CREATE {bundle_path}".format(bundle_path = bundle_path))
for path in lib_paths:
ar_input.append("ADDLIB {path}".format(path = path))
ar_input.appen... | 5ac1d3cd60e8aa306d5a55cdbac7a27ee580a408 | 669,556 |
def identity(x):
"""Identity function: useful for avoiding special handling for None."""
return x | c40dbca9406d243351d7c734b935032b6eb27e67 | 669,557 |
def zenodo_get_children(data, resource_id, is_record):
"""
Get the children of the requested resource. Only going down one level.
Parameters
----------
data : dict
The project path data
resource_id : str
The resource id of the children
is_record : bool
Is this a Zen... | cca8f84539c58d9c5bf8b2cc11f82a4381cc339e | 669,558 |
def triangle_geometry(triangle):
"""
Compute the area and circumradius of a triangle.
Parameters
----------
triangle : (1x3) array-like
The indices of the points which form the triangle.
Returns
-------
area : float
The area of the triangle
circum_r : float
... | 9868cf6adeac1790034aa35b0ce7d8d7c7d38799 | 669,560 |
def find_col_index_with_name(name, trained_schema):
"""
finds the index of the column with name 'name' and returns the index
:param name: name of the column to look for
:type name: str
:param trained_schema:
:type trained_schema: List(dict)
:return: index of the element in trained_schema tha... | 66bc4c9d3f78ba6bf16a03854909787eaad21171 | 669,561 |
def anagram(word_1: str,
word_2: str) -> bool:
"""Anagram check example
:param word_1: {str}
:param word_2: {str}
:return: {bool}
"""
word_1 = word_1.lower()
word_2 = word_2.lower()
return sorted(word_1) == sorted(word_2) | 6e99ebb0659fb4f81414f2dd552f854d52d61a0d | 669,562 |
def get_month(date):
"""Extract month as form receiving string dd/mm/yyyy or mm/yyyy
Args:
date (string): Date formate dd/mm/yyyy
Returns:
mm: string with month.
"""
num_chars = len(date)
if num_chars == 10:
return date.split("/")[1]
elif num_chars == 7:
ret... | 76731d27c0183e53ee4760305529de2800237c36 | 669,563 |
def get_index(l, key, value):
"""Find the index of an element by key value, for lists of dicts
Return: index or -1
"""
return next((index for index, d in enumerate(l) if d[key] == value), -1) | 2fb4391093df6f3ec2de7247a430d40b8c58dffd | 669,564 |
def precision(tp, fp, fn):
"""
:param tp: (int) number of true positives
:param fp: (int) number of false positives
:param fn: (int) number of false negatives
:returns: precision metric for one image at one threshold
"""
return float(tp) / (tp + fp + fn + 1.0e-9) | be8822c0db010aec96ef406ffcc991d64c601c8f | 669,565 |
import os
def os_path_split(path):
"""
Split a path with os.path.split(), recursively.
:param path: The path to split
:type path: str
:rtype: List[str]
"""
rest = path
components = []
while rest != '/' and rest != '':
(rest, last) = os.path.split(rest)
components.i... | d283c1fdc6b7fb32f61f560743c778e6bfb87bd0 | 669,566 |
import sys
import termios
import tty
def read_char() -> str:
"""Read a single character from user input. Doesn't work on Windows."""
fd = sys.stdin.fileno()
oldSettings = termios.tcgetattr(fd)
try:
tty.setcbreak(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, ter... | e1316c600c300dac62f68cb59745974a341deeec | 669,567 |
def midi_to_ansi_note(midi_note):
""" returns the Ansi Note name for a midi number.
::Examples::
>>> midi_to_ansi_note(21)
'A0'
>>> midi_to_ansi_note(102)
'F#7'
>>> midi_to_ansi_note(108)
'C8'
"""
notes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']
num... | c6905c43a3aebd4d976e9fa8dbb37f2e6660cc8d | 669,568 |
def lengthOfLongestSubstring(s: str) -> int:
"""难道这是滑动窗口??"""
length = len(s)
if length <= 0: return 0
count = 1
for i in range(length):
for j in range(i+1, length):
# print(i, j)
if s[j] in s[i:j]:
# print(i, j, s[i:j], '--')
count = ... | cd39d0df2fab8fd7395bfb08471467cb6d8c21ac | 669,569 |
def UnionFindSet(m, edges):
"""
:param m:
:param edges:
:return: union number in a graph
"""
roots = [i for i in range(m)]
rank = [0 for i in range(m)]
count = m
def find(member):
tmp = []
while member != roots[member]:
tmp.append(member)
mem... | bbc1fba7b140ffc004c75258158316dac083ac36 | 669,570 |
def _traverse_reachable(paths, start):
"""Returns set of all paths reachable from point."""
s = set([start])
for target in paths[start]:
s.update(_traverse_reachable(paths, target))
return s | ee3381e3c8b51a8dc963693295e517e78f99de98 | 669,571 |
def tokenize_to_id(sentences, tokenizer):
"""Tokenize all of the sentences and map the tokens to their word IDs."""
input_ids = []
# For every sentence...
for sent in sentences:
# `encode` will:
# (1) Tokenize the sentence.
# (2) Prepend the `[CLS]` token to the start.
... | 8ef3198421246930a9f42a64557f7c584eb52239 | 669,572 |
def intersect(index, keys):
""" Utility method to compute the intersection of all the sets in index
that correspond to the given keys keys.
Args:
index, hash for format {key -> set()}
keys, list of strings
Returns:
set, the intersection of all the sets in index that correspond to... | 3a885e7f3822a5f2c9bcc3e0558d060fc61bf17b | 669,573 |
def filter_topics(topic_df, presence_thr, prevalence_thr):
"""Filter uninformative ("stop") topics
Args:
top_df (df): topics
presence_thr (int): threshold to detect topic in article
prevalence_thr (int): threshold to exclude topic from corpus
Returns:
Filtered df
"""
... | 6aa8aa5d5541c5811bd8c382bb762ac039471c73 | 669,574 |
import sympy
def diff_scalar_func(scalar_func, var):
""" Calculate partial derivative of a function with respect to a scalar or
a vector.
Args:
scalar_func: A symbolic scalar function.
var: A symbolic scalar or a symbolic vector.
Returns:
Partial der... | 1607c694210be19041a7fd6931b7824ff351ce03 | 669,575 |
import base64
def b64_encode(byte_string: bytes) -> str:
"""Base 64 encode a byte string and return a unicode string."""
b64_bytes = base64.b64encode(byte_string)
return b64_bytes.decode("utf-8") | d3c78f5914ec0feb826358bfc14b09b6efa657b5 | 669,576 |
import os
import re
def find(path = ".", recurse = True, type = None, regex = None, extensions = None,
absolute = False, case = True):
"""Get list of paths to files in a folder.
Args:
path (str): Path to a folder on a filesystem.
extensions
.. exec_code::
:caption: Ex... | 8761ab49c2f5dfc4ef4c819364afe77a1ed572b6 | 669,577 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.