content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_venv_name(dockenv_name):
"""
Helper function to split the user-defined virtual env name
out of the full name that includes the dockenv tag
:param dockenv_name: The full name to pull the virtual env name
out of
"""
# Format of tage name if dockenv-**NAME**:latest... | addc198d36b50b61fb2db5bad5de8af86cd54a7c | 654,962 |
import random
def get_temperature():
"""Fake room thermometer (Celsius scale)."""
t = random.uniform(20.0, 28.0)
print(f" T={t:.1f}")
return t | c0851085bdcfcbfa674f4831f78a78497841ca28 | 654,964 |
from pathlib import Path
from typing import Optional
from typing import List
import uuid
def make_metakernel(kernel_dir: Path, kernels: Optional[List[str]] = None) -> Path:
"""Create a uniquely-named SPICE metakernel in ``kernel_dir`` and return its path. If ``kernels`` is `None`, this
function searches ``ker... | b60bc7d68d5de76b720d346d5fff13990dae5828 | 654,965 |
import os
def get_subjects_and_segmentations(path):
"""
Utility method to get, filter and arrange BraTS data set in a series of lists.
:param path: The path to look for BraTS data set files.
:return: A tuple containing multimodal MRI images for each subject and their respective segmentation.
"""
... | b34a6fd52c93cf395b782f9c6a72c3d7aa59d69f | 654,966 |
def _Aij(A, i, j):
"""Sum of upper-left and lower right blocks of contingency table."""
# See `somersd` References [2] bottom of page 309
return A[:i, :j].sum() + A[i+1:, j+1:].sum() | 97f1153876d21cad8d7cba45877605d7326c96e3 | 654,967 |
from typing import Callable
from typing import Any
def get_func_name(
func: Callable[..., Any],
prepend_module: bool = False,
repr_fallback: bool = False,
) -> str:
"""Extract and return the name of **func**.
A total of three attempts are performed at retrieving the passed functions name:
1.... | b09b04796483170a84798127344d97401fdd4419 | 654,968 |
def mimic_case(old_word, new_word):
"""
>>> print(mimic_case('EtAt', 'état'))
ÉtAt
"""
if len(old_word) != len(new_word):
raise ValueError("lengths don't match")
return ''.join([
new_word[i].upper() if old_word[i].isupper() else new_word[i].lower()
for i in range(len(old_... | c4ca9536a6e2f6fb5d6c4f512ed86172810cd07e | 654,969 |
from typing import Callable
from typing import Union
def get_distance_callback(manager, distance_matrix) -> Callable:
"""Returns the distance between the two nodes."""
def distance_callback(from_index, to_index) -> Union[float, int]:
from_node = manager.IndexToNode(from_index)
to_node = manag... | 887662eff00d9b708fcb04a0b958935e940dd702 | 654,970 |
def text_to_word_sequence(text, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', lower=True, split=" ") -> list:
""" Convert text to word list
:param text: test list
:param filters: filter rules, filter all punctuation marks, tabs, newlines, etc. by default
:param lower: whether to convert text to lowerc... | 36f52f40baff004d926ae58658fe596b72b65603 | 654,971 |
def phase(x):
"""Returns 1 if the input is even and -1 if it is odd. Mathematically equivalent to (-1)^x"""
if x % 2 == 0:
return 1
else:
return -1 | a8307b21b598bec33fd9fb05719addf7127872ef | 654,972 |
def x_squared_y_integral(x,y,A):
""" Calculates the integral of x^2*y on a finite element """
term1 = .1*( (x[0]**2)*y[0] + (x[1]**2)*y[1] + (x[2]**2)*y[2] )
term2 = (1./15.)*( x[0]*x[1]*y[0] + x[0]*x[2]*y[0] + x[0]*x[1]*y[1]
+x[1]*x[2]*y[1] + x[0]*x[2]*y[2] + x[1]*x[2]*y[2])
term3... | 7876ef35482c5b25825d3f43dea49251f74205fa | 654,973 |
import os
import shutil
def create_output_dirs(path):
"""
Create directory tree for processed data.
Args:
path (str): path to folder which stores processed data.
Returns:
train_path (str), val_path (str): Path to created directories.
"""
def __create_output_dir(child_path):
... | 13b4a176aadbc51fd5e6665a08e6247d98b15d44 | 654,974 |
import tkinter
def Button(root, content, props):
"""A wrapper for tkinter.Button."""
text_var = tkinter.StringVar()
def update(**props):
"""Function used to update the label if changed."""
text_var.set(props.get('text', content))
update(**props)
if 'text' in props:
del pr... | ffdf7318b3663ffc80f0c62e874cb75ca5e1e9a5 | 654,975 |
def calculate_chunk_slices(items_per_chunk, num_items):
"""Calculate slices for indexing an adapter.
Parameters
----------
items_per_chunk: (int)
Approximate number of items per chunk.
num_items: (int)
Total number of items.
Returns
-------
list of slices
"""
a... | fd42f9be9149d7a59498e17bb76329a8e96a6ae7 | 654,976 |
import os
def read_imdb(path, seg='train'):
""" read imdb dataset """
pos_or_neg = ['pos', 'neg']
data = []
for label in pos_or_neg:
files = os.listdir(os.path.join(path, seg, label))
for file in files:
with open(os.path.join(path, seg, label, file), 'r', encoding='utf8') a... | a91dd521f4302844b800688d47e33d6a15c6494a | 654,977 |
import math
def rotate_point(x,y,theta):
"""Rotate a point around the origin by an angle theta.
Args:
x (float): x coordinate of point.
y (float): y coordinate of point.
theta (float): rotation angle (rad).
Returns:
list: [x,y] coordinates of rotated point.
"""
"... | 5b2aa1fd7240e9cb1164849c6da3c1333cba67d2 | 654,978 |
def iterable(obj):
"""Utility to check if object is iterable"""
try:
iter(obj)
except:
return False
else:
return True | e39525f0da629dea5af15c5fb85869930c9ca99b | 654,979 |
from typing import Callable
import hashlib
def get_hash(hash_type: str) -> Callable:
"""Return a hash class with an update method and a hexdigest method."""
known_hashes = {"sha1": hashlib.sha1, "sha256": hashlib.sha256}
try:
return known_hashes[hash_type]
except KeyError:
# pylint: d... | e9ac78a7710cf195f02c700cf6cd420cd09e8284 | 654,980 |
import pathlib
def zcoord(path:pathlib.Path) -> float:
"""
Return the putative Z coordinate for a image file path name
"""
return int(path.name.split(".")[0]) / 10 | fc8363fad50ca4eaecfca900198bde1e6550a505 | 654,982 |
from distutils import util
def ensure_scripts(linux_scripts):
"""
Creates the proper script names required for each platform
(taken from 4Suite)
"""
if util.get_platform()[:3] == 'win':
scripts_ = [script + '.bat' for script in linux_scripts]
else:
scripts_ = linux_scripts
... | 9de9a22dfb006a16e1430b512e642aae494ce494 | 654,983 |
import sys
import socket
def calculate_checksum(source_string):
#source_string = str(source_string)
"""
A port of the functionality of in_cksum() from ping.c
Ideally this would act on the string as a series of 16-bit ints (host
packed), but this works.
Network data is big-endian, hosts are typ... | 86075314c5aae98392e7998e45d983a57f14f2e8 | 654,984 |
from pathlib import Path
def can_override(path: Path, override: bool) -> Path:
"""Check if it's allowed to override a `path`.
Args:
path: path, where we are going to write
override: permission to override flag
Returns:
The input `path`to facilitate chaining in mapping in code.
... | c727f2fff98324564408d919c098f08d2f545bf4 | 654,985 |
import pickle
def predict(X):
"""Predict test data"""
# load the model
model = pickle.load(open('model/forest.pkl', 'rb'))
prediction_prob = model.predict_proba(X)[:, 0]
prediction = model.predict(X)
return prediction, prediction_prob | 08c86d156713698162e93db2e44dbe1ee0445feb | 654,986 |
def isLarger(ser1, ser2, fractionTrue=1.0, startIdx=0):
"""
Checks that arr1[startIdx:] > arr2[startIdx:]
Parameters
----------
ser1: pd.Series
ser2: pd.Series
fractionTrue: float in [0, 1]
startIdx: int
Returns
-------
bool
"""
numTrue = sum(ser1.loc[startIdx:] > s... | 6969938694c2a62d113cb215a0e3efb2d0262d62 | 654,987 |
import glob
from itertools import chain
from typing import Iterable
def poly_iglob(filenames_or_patterns: Iterable, *, recursive=True, ignore_case=True):
"""
Read sequence of file names with or without wildcard characters.
Any wildcards are replaced by matching file names using glob.iglob().
:param f... | ed95d6949bb8cb287a4015b157d31206eb60c94f | 654,988 |
from typing import Iterable
from typing import Sequence
def report_invalid_whitelist_values(
whitelist: Iterable[str], items: Sequence[str], item_type: str
) -> str:
"""Warns the user if there are entries in ``whitelist`` which don't
correspond to any item in ``items``. Helps highlight typos.
"""
... | a7ad1007abdaa88dea9ff2ef90194e9490998f12 | 654,991 |
def _count_of_curr_and_next(rule):
"""Count tokens to be matched and those to follow them in rule."""
return len(rule.tokens) + len(rule.next_tokens or []) + len(rule.next_classes or []) | 8005128554a40ee53156c2dcafbd7b223bbbf430 | 654,992 |
def get_charge(lines):
""" Searches through file and finds the charge of the molecule. """
for line in lines:
if 'ICHRGE' in line:
return line.split()[2]
return None | 913ec1403cdf1dba5ad4b549b61cec23d3546dc7 | 654,993 |
def tvi(b3, b4, b6):
"""
Transformed Vegetation Index (Broge and Leblanc, 2001).
.. math:: TVI = 0.5 * (120 * (b6 - b3) - 200 * (b4 - b3))
:param b3: Green.
:type b3: numpy.ndarray or float
:param b4: Red.
:type b4: numpy.ndarray or float
:param b6: Red-edge 2.
:type b6: numpy.ndar... | f7681f078e33386e5c946d33befa605a0c8e14df | 654,994 |
from typing import Callable
def _derive_template_name(view_function: Callable) -> str:
"""Derive the template name from the view function's module and name."""
# Select segments between `byceps.blueprints.` and `.views`.
module_package_name_segments = view_function.__module__.split('.')
blueprint_path... | 117ab8058eac4c199e7e688a35011cd0c650f62d | 654,995 |
def promedio_fila(matriz: list, fila: int) -> float:
""" La fila juiciosa
Parámetros:
matriz (list): Matriz que representa el salón de clases
fila (int): Fila a la cual se debe calcular el promedio
Retorno:
float: Promedio de la fila que el profesor solicitó.
"""
if fila <= 0:
... | 157530a68979c25ea842913a2907650ec6c1ea4c | 654,996 |
def count_incident_type(incidents, type):
"""
Gets total number of incidents of a certain type
:param incidents: dictionary -- set of incidents to parse
:param type: string -- key to parse within incidents
:return: int -- total incidents
"""
total = 0
for _, incident in incidents.item... | 8981fd0f3ac25f7647d3882f287d7d15cdadb70f | 654,998 |
def get_system_serial_port(system):
""" Work out the most likely serial port given the type of system. YMMV. """
if system == "Windows":
return "COM3"
elif system == "Linux":
return "/dev/ttyUSB0"
else:
raise ValueError("Invalid system - unable to determine serial_port") | 9216d540b46f4ffc756ee229e8e88cc4fadd8cdc | 654,999 |
def mac_format(mac):
"""Converts double columns to dashes of a mac address"""
return mac.replace(':', '-') | d2a9677cf283ea3cffb10e91da0ad19c08674b17 | 655,000 |
def load_data(path):
""" Load input data from a given path. Data is stored as word,label\nword,label\n ...
:param path: path to file
:return: (list of words, list of labels)
"""
words = []
labels = []
with open(path, encoding='utf-8') as f:
lines = f.read().splitlines()
for ... | 4526eea8fb0dc9782123d2b64d6c023b6e527f3d | 655,001 |
import os
def set_filename_format(now, instance, filename):
""" file format setting e.g)
{username}-{date}-{microsecond}{extension}
username-2016-07-12-158859.png """
return "{username}-{date}-{microsecond}{extension}".format(
username=instance.username,
date=str(now.date()),
... | 9ee84df47e5a9828d23db6b79af150be7f86f788 | 655,002 |
def get_flag(bits, bit):
"""
Gets the flag value.
:param bits: The bits
:type bits: int
:param bit: The bit index
:type bit: int
:returns: The flag value
:rtype: bool
"""
return bool(bits & (1 << bit)) | e3b00f75a645707c12e61add52a48f68ca4fb05c | 655,003 |
from typing import List
def get_clabe_control_digit(clabe: str) -> int:
"""Generate the checksum digit for a CLABE.
:param clabe: CLABE.
:return: The CLABE checksum digit.
"""
factors = [3, 7, 1]
products: List[int] = []
for i, digit in enumerate(clabe[:17]):
products.append((int... | 3df768c43c6643480aaec9505e8ae464d7aba66e | 655,004 |
def get_sub_neuron(G, bounding_box):
"""Returns sub-neuron with node coordinates bounded by start and end
Parameters
----------
G : :class:`networkx.classes.digraph.DiGraph`
Neuron from swc represented as directed graph. Coordinates x,y,z are
node attributes accessed by keys 'x','y','z'... | 06f498b4e02e7dc6a5a63529b0f54a1287c6045e | 655,007 |
def _getcalday(instcal, date):
"""
Get index of row for current night in instrument calendar table.
"""
for i in range(len(instcal['date'])):
if instcal['date'][i] in date:
return i
print('\n Date '+date+' not found in instrument configuration calendar.')
raise ValueError('Da... | 97dfa39d43197ec567fcea41a4f1545e7db045b6 | 655,008 |
def comp(DNA: str, pat_len: int) -> list:
"""Sort all substrings of pat_len length
:param DNA: the string to pull substrings from
:type DNA: str
:param pat_len: the length of substrings to pull
:type pat_len: int
:returns: all substrings, sorted
:rtype: list (of strs)
"""
if not DN... | 04cddfb893fe1e4b0b03d9997b53ac80b8f6e606 | 655,009 |
def get_model_config(ckpt_path):
"""Returns the model configuration to be used with each checkpoint."""
config = {
'audio_backbone': 'resnet50',
'audio_model_kwargs': {
'bn_config': {
'create_offset': True,
'create_scale': True,
'decay_rate': 0.9,
... | 2e55faea2e1c578c4c9dcc3166076dd6d0fac4e7 | 655,010 |
def get_single_value(group, name):
"""Return single value from attribute or dataset with given name in group.
If `name` is an attribute of the HDF5 group `group`, it is returned,
otherwise it is interpreted as an HDF5 dataset of `group` and the last value
of `name` is returned. This is meant to retriev... | 4bd6ff890ece8a4fc0c94fb67caa8ae111c574df | 655,011 |
def trade(first, second):
"""Exchange the smallest prefixes of first and second that have equal sum.
>>> a = [1, 1, 3, 2, 1, 1, 4]
>>> b = [4, 3, 2, 7]
>>> trade(a, b) # Trades 1+1+3+2=7 for 4+3=7
'Deal!'
>>> a
[4, 3, 1, 1, 4]
>>> b
[1, 1, 3, 2, 2, 7]
>>> c = [3, 3, 2, 4, 1]
... | 9d8ca3c2d51f95ca84e9e9d0d14694963d24b9a0 | 655,012 |
def get_activity_charts_data(activities, project=None, locale=None):
"""Get data for Translation activity and Review activity charts."""
human_translations = set()
machinery_translations = set()
new_suggestions = set()
peer_approved = set()
self_approved = set()
rejected = set()
for (lo... | 34187980539673ab2176f723cff466703b152e2a | 655,013 |
def parse_hpo_gene(hpo_line):
"""Parse hpo gene information
Args:
hpo_line(str): A iterable with hpo phenotype lines
Yields:
hpo_info(dict)
"""
if not len(hpo_line) > 3:
return {}
hpo_line = hpo_line.rstrip().split('\t')
hpo_info = {}
hpo... | 5238396661d9b77a272cfafbd0f7fec2557b17e8 | 655,014 |
def block_label_tuple_to_string(block_tuple) :
"""
Parameters
------------
block_tuple : tuple
Tuple containing the region name
(str) and (pair of ages)
Returns
--------------
block_str : str
String containing reduced info.
"""
name = block_tuple[0]
name.split... | 6d4375d927c48ecc951005a35c1e1b7596357db7 | 655,015 |
def fliplr(a):
"""Flip array in the left/right direction.
Flip the entries in each row in the left/right direction. Columns
are preserved, but appear in a different order than before.
Args:
a (~cupy.ndarray): Input array.
Returns:
~cupy.ndarray: Output array.
.. seealso:: :fu... | 3bd27276000be8939802d01d2fe71978d265cc0e | 655,016 |
import typing
def lane_offset_width_meters(shape: typing.Sequence[int],
poly_evals: typing.Tuple[typing.List[float], typing.List[float]],
xm_per_pix: float) -> typing.Tuple[float, float]:
"""Calculate center-offset of the lane, given polynomial curves for ... | b41479d72240f5f1ffc6364e9805024a0dab5d59 | 655,017 |
def z_inverse(x, mean, std):
"""The inverse of function z_score"""
return x * std + mean | fc283bb11bc1109759e34cd26eb21cd24e453c4d | 655,018 |
import os
import textwrap
import requests
import re
from datetime import datetime
import subprocess
def define_env(env):
"""
This is the hook for defining variables, macros and filters
- variables: the dictionary that contains the environment variables
- macro: a decorator function, to declare a macr... | 32fb65d2d9e47d02d13d4462375d2b2855450a08 | 655,019 |
def get_product_images(product):
"""Return list of product images that will be placed in product gallery."""
return list(product.images.all()) | 64108e6ba906f9fcafd16af172c2af9f34d2eb20 | 655,021 |
import random
def choose_between_by_p(l1, l2, p, count):
"""
Choose `count` elements from `l1` (w/ prob `p`) and `l2` (w/ prob `p`-1).
"""
assert 0 <= p
assert p <= 1
return [random.choice(l1) if random.random() <= p else random.choice(l2) for _ in range(count)] | 0a47c256db8a7d57654377ecf69cef6afcf49b5a | 655,022 |
def dataframe_selection_to_dict(df, sel_itm):
""" Return a Dict for DF Frame row defined by sel_itm index """
dd = {'Name':sel_itm}
sdf = df.loc[sel_itm]
for id in sdf.index.values:
dd[id] = sdf[id]
return dd | d9a2c50ca979c6430a67db6a2a52d6da2253d8a6 | 655,023 |
import sys
import inspect
def function_names_for_non_heating_jobs():
"""Returns the function names available for scheduling as a NonHeatingJob."""
this_module = sys.modules[__name__]
functions = inspect.getmembers(this_module, inspect.isfunction)
exclude = ['function_names_for_non_heating_jobs', 'get_... | ab1af3e20df5fbffb8e6fff487f5fbc433a9dc5f | 655,025 |
def mol_file_basename(tag):
"""Covert a tag into a molecular data file name"""
return 'c%06d.' % tag | 95ba73740de6cf283fea5a84adc79732c65bb7b8 | 655,026 |
import os
def get_user_home():
"""
Returns home path of the user.
"""
return os.getenv('HOME', os.getenv('USERPROFILE')) or '' | 4ce750b696ab5a1654f7079bf2d5b1825c051f34 | 655,029 |
import os
def expand_path(path):
""" Expand path with ~ and env """
path = os.path.expanduser(path)
path = os.path.expandvars(path)
path = os.path.abspath(path)
return path | 26f92b7e4ae81ccfa217acb49f063bec8be11a83 | 655,030 |
def u2u1(u2):
"""
inch -> mm
"""
u1 = int(round(u2 * 25.4, 0))
return u1 | 2731ec75ade33598862e50d2244a47af46c6648e | 655,031 |
def python_trailing(n):
"""Count the number of trailing zero bits in abs(n)."""
if not n:
return 0
t = 0
while not n & 1:
n >>= 1
t += 1
return t | 2b595e183d95e22eb9f801d008bca318c60958e7 | 655,032 |
import argparse
def get_timeout(value):
"""Returns the CoMetGeNe timeout (in seconds).
:param value: the value assigned to the timeout
:return: the integer value assigned to the timeout
"""
if not value.isdigit():
raise argparse.ArgumentTypeError("contains non-digit characters.")
tim... | 36eb182715495bfbce376e55f8a7f7fe2df24ea8 | 655,033 |
import torch
def flip_segment(X_spikes, segment):
"""
Flips the values of a segment in X_spikes format
:param X_spikes: spiking input data from spike generator
:param segment: segment in X_spikes to be flipped
:return: spiking data with flipped segment
"""
_, (d, t_start, t_end) = segment
... | 4c3421ce9a7c3da5b44b5af3477f872c23766122 | 655,034 |
def valueFactory(zeroValue, elemValue):
"""
Return elemValue converted to a value of the same type as zeroValue.
If zeroValue is a sequence, return a sequence of the same type and length,
with each element set to elemValue.
"""
val = zeroValue
typ = type(val)
try:
# If the type i... | 60ab7618fb7fee65a03033269499c12efc8c6091 | 655,035 |
def tts_version(version):
"""Convert a version string to something the TTS will pronounce correctly.
Args:
version (str): The version string, e.g. '1.1.2'
Returns:
str: A pronounceable version string, e.g. '1 point 1 point 2'
"""
return version.replace('.', ' point ') | 2c01d0ce7a72f162f43193bb41a4bb52f15c3fac | 655,036 |
import os
def is_word2vec_model(path):
"""
Checks to see if the path corresponds to a word2vec file.
Looks for a filename such as "vectors.enwiki.bin" or "vectors.enwiki.txt.bz2"
"""
if not os.path.isfile(path):
return False
parts = os.path.basename(path).split('.')
if len(parts) n... | 405b9216b8f018ce15d1a492e35b3b451ea2d996 | 655,037 |
def SetBaselineClamp(state):
""" This function turns on and off the baseline clamp functionality.
With this feature enabled the baseline level of each scan in a
kinetic series will be more consistent across the sequence.
state: Enables/Disables Baseline clamp functionality
1 –... | 5893f81d3aaa1692be78e427678c9ee5be633a16 | 655,038 |
import unicodedata
import re
def filename(name):
"""
return name as a valid filename on unix
change spaces to hyphens and '/' to '\'
removes trailing/leading whitespace.
"""
name = unicodedata.normalize('NFKC', name)
name = re.sub('[-\s]+', '-', name, flags=re.U).strip()
return name.re... | 173e34ed8917e854950ba741602b8abb0ab9ee51 | 655,039 |
def to_sec(d=0, h=0, m=0, s=0):
"""Convert Day, Hour, minute, seconds to number of seconds."""
secs = d*86400
secs += h*3600
secs += m*60
secs += s
return secs
################## | 423b314377b59b250309cb4957379c63f7d4173f | 655,041 |
def task_dev():
"""Run the main task for the project"""
return {
'actions': ["python3 -m hello-world-web"],
} | 3eba645636f83656753a578111c256730989765b | 655,042 |
def ETA_0(phi_0, m, om, N):
"""Isopycnal displacement amplitude. Wavenumber and frequency should be in
angular units."""
return phi_0*1j*m/(N**2 - om**2) | 10a82d706ce387519f6224e352112dc4cd935344 | 655,043 |
def alpha_for_N(comps,Influx=10,Outflux=1000):
"""calculates alpha based on required outflux for given influx"""
c=(Outflux/Influx)**(1/float(comps))
alpha_sol= (c-2)/(c-1)
return alpha_sol | 4532f6c8f32f54960562c8d6763d5051fb5b2567 | 655,044 |
import uuid
def sniffer_queue_factory(rabbit_config, rabbit_manager):
""" Return a function that creates message queues to 'sniff' messages
published to exchanges.
"""
vhost = rabbit_config['vhost']
def make(exchange, routing_key="*"):
""" Create a uniquely named queue and bind it to an e... | 2148f354c8eb3a93a9ecaa337cc49873173613da | 655,045 |
def check_point_in_box(pnt, box):
"""
判断点是否在box中
"""
p_x, p_y = pnt
x_min, y_min, x_max, y_max = box
if x_min < p_x < x_max and y_min < p_y < y_max:
return True
else:
return False | 4a0bdb4b336623c1a0e673574f75388038146d34 | 655,046 |
def _created_on_to_timestamp_ms(created_on):
"""
Converts the Message CreatedOn column to a millisecond timestamp value.
CreatedOn is number of 100 nanosecond increments since midnight 0000-01-01.
Output is number of millisecond increments since midnight 1970-01-01.
"""
return created_on / 1000... | 30ba13c0d45b2850a266a05024f37ea3aa3b6cdd | 655,047 |
from typing import List
def left(lst: List[int], idx: int) -> int:
"""Return left heap child."""
left_idx = idx * 2 + 1
if left_idx < len(lst):
return left_idx
else:
return -1 | 4a8424fd3cd40eb278bd637779cf8d7c7d8162ea | 655,048 |
import re
def import_vfunc_deprecated(infile):
"""
Imports vertex function from txt file. Values can be separated by ; or ,
and surrounded by {} or () brackets. Also first line can have the
keyword "Solution:", i.e. the PSOL format from ShapeDNA
"""
try:
f = open(infile, 'r')
excep... | def7424f7d1fb0c20557fc6f9789e13632c63f95 | 655,049 |
from datetime import datetime
def outputSPDX(doc, spdxPath):
"""
Write SPDX doc, package and files content to disk.
Arguments:
- doc: BuilderDocument
- spdxPath: path to write SPDX content
Returns: True on success, False on error.
"""
try:
with open(spdxPath, 'w') as f... | 8659c3091b41665082d0c1af7e5f54a86c7e0150 | 655,050 |
def write_nonequilibrium_trajectory(nonequilibrium_trajectory, trajectory_filename):
"""
Write the results of a nonequilibrium switching trajectory to a file. The trajectory is written to an
mdtraj hdf5 file.
Parameters
----------
nonequilibrium_trajectory : md.Trajectory
The trajectory... | 158bc16eacfd945a77ce50ac1819b852b3a3f3d4 | 655,051 |
import random
def random_IP() -> str:
"""
Get random IP
"""
ip = []
for _ in range(0, 4):
ip.append(str(random.randint(1, 255)))
return ".".join(ip) | f96527bc72bcf06658e4acc2a6298ec8d9716823 | 655,052 |
import hashlib
def compute_checksum(path, algorithm: str) -> str:
""" Generates a hex digest using specified algorithm for a file. """
buffer_size = 65536
hash_builder = hashlib.new(algorithm)
with open(path, 'rb') as f:
while True:
data = f.read(buffer_size)
if not d... | b98188f5e487884b84ec43dbd0757c3add59c432 | 655,053 |
def rev_bit_str(n: int, bitlen: int) -> int:
"""
Reverses the bitstring of length bitlen of a number n and returns the
bitreverses integer. I.e. rev_bits(3, 4) => "0011" => "1100" => 12
"""
bits = bin(n)[2:] # Truncate first 2 characters to avoid '0b'
start_pow = bitlen - len(bits)
return s... | 1899d2e20968b225ec32be58a7fb3bd9488fcd20 | 655,054 |
import logging
def set_root_logger(loglevel=logging.INFO):
""" Setup the root logger. """
rootlogger = logging.getLogger()
rootlogger.setLevel(loglevel)
return rootlogger | d7c8e7bfc1dcb9a5e2231e312dc2377634ea4b8a | 655,055 |
def _next_version(version):
"""
Given a parsed version from pkg_resources.parse_version, returns a new
version string with the next minor version.
Examples
========
>>> _next_version(pkg_resources.parse_version('1.2.3'))
'1.3.0'
"""
if hasattr(version, 'base_version'):
# Ne... | 5d94bc4e48ebf277b925e7eedf167b0760096214 | 655,056 |
def pattern_count(pattern, text):
"""
The number of times that a pattern appears as a substring of text.
Args:
pattern (str): the substring pattern to find in the given text.
text (str): the string space for looking.
Returns:
String, number of substring pattern that appears in ... | 367a82213a60585d1f22343c702de2f21aa33180 | 655,058 |
def sort_seconds(timestamps):
"""
Sorts a list of 2-tuples by their first element
"""
return sorted(timestamps, key=lambda tup: tup[0]) | 0c66b2e8d3a7360afd7d49d62bdda477820b8329 | 655,060 |
import itertools
def dfs(pos,img,list_of_all):
"""
This function performs the the deep first search of the white
neighbours of a pixel
"""
h_max,w_max,h_min,w_min = pos[0],pos[1],pos[0],pos[1]
for i,j in itertools.product([-1,0,1],[-1,0,1]):
if ((i,j) != (0,0)
and (pos... | 7ce89e45131065006a18953c675df79cd4229150 | 655,061 |
def GET_without_params(request, params):
"""
Возвращает строку GET без определенных параметров
{{ request|GET_without_params:"param1,param2" }}
"""
get_dict = request.GET.copy()
for param in params.split(','):
try:
get_dict.pop(param)
except KeyError:
pass... | 97d44866169d005da758feddb119f0dda71d5c1e | 655,062 |
def delitelji(n):
""" Vrne delitelje števila n. """
st = 0
for i in range(1, round((n+1) ** (1/2))):
if n % i == 0:
st += 1
if i != n / i:
st += 1
return st | 94e2fe26f498dd60f03de499ed8de81dc5721920 | 655,063 |
def print_beam(elements):
"""
print beam elements
"""
UFOmod = []
_iter = 0
# Beam Elements
for number, _elem in elements.items():
if _elem.type != 'riser':
continue
if _iter == 0:
UFOmod.append("'\n")
UFOmod.append("'{:} Riser element\n".f... | c1e4b6c343cf3f617f2ac527f1aaf7f576fa4345 | 655,064 |
def all_nums(table):
"""Returns True if table contains only numbers
Precondition: table is a (non-ragged) 2d List"""
cnt = 0
number_cnt = 0
for row in table:
for item in row:
cnt += 1
if type(item) in [int, float]:
number_cnt += 1
if cnt != number_... | 0721406eedda5040d39e373557540a00a14ee133 | 655,065 |
def skewed_lorentzian(x, bkg, bkg_slp, skw, mintrans, res_f, Q):
"""
Skewed Lorentzian
"""
return bkg + bkg_slp*(x-res_f)-(mintrans+skw*(x-res_f))/\
(1+4*Q**2*((x-res_f)/res_f)**2) | d9b3ff317132ffbd54824726cae4772503d65f4a | 655,066 |
import os
import logging
def get_filename(fq_filepath):
"""
This function adds a numerical increment to the filename in case the file
exists already in the disk.
:param fq_filepath: fully qualified filepath i.e.
folder/sub_folder/filename.extension
:return: fq_filepath (with incremented path i... | 27ad47e4b345f809476def71ed31645777b03bd9 | 655,067 |
import sys
import platform
def GetCurrentOSType():
"""Get a string representation for the current OS.
Returns:
'Mac', 'Win', 'Linux', or 'Linux_64'.
Raises:
RuntimeError: if OS can't be identified.
"""
if sys.platform == 'darwin':
os_type = 'Mac'
if sys.platform == 'win32':
os_type = 'Wi... | 87edfcbdb030d9ff7787cec9eb3907a56c8036a5 | 655,068 |
import time
def timeit(func):
"""
@timeit decorator that allows you to measure the execution times
of dedicated methods (module-level methods or class methods) by
just adding the @timeit decorator in front of the method call.
"""
def timed(*args, **kwargs):
ts = time.time()
res... | 79b1f125ab67477e01faab1894e115d9169362d8 | 655,069 |
def e(parameters, p, r_v):
"""
Returns an expression for the partial pressure of water vapour
from the total pressure and the water vapour mixing ratio.
:arg parameters: a CompressibleParameters object.
:arg p: the pressure in Pa.
:arg r_v: the mixing ratio of water vapour.
"""
epsilon... | 99b4ab64689547366b0a6b903408a60e237d3aba | 655,070 |
def mat_to_dudes_list(mat):
""" Extract list of vectors representing response patterns of individual participants.
"""
return [mat[:,x].reshape(64,9).argmax(axis=1) for x in range(mat.shape[1])] | d2d59d21db6fdded5502ceb01eb64943d772b07b | 655,071 |
from typing import Dict
from typing import Any
def check_is_legacy(sample: Dict[str, Any]) -> bool:
"""
Check if a sample has legacy read files.
:param sample: the sample document
:return: legacy boolean
"""
files = sample["files"]
return (
all(file.get("raw", False) is False for... | 8fab1d1e1e448d534817f0971239a72cadbd7ba4 | 655,073 |
def hits_x(s, v, min_x, max_x):
"""Calculates all possible hits = array """
# abort if we cant event reach min_x
if (v * v + v) / 2 < min_x: return []
steps = []
# if v0 gets 0, we cant move forward neither score new hits
for step in range(v):
s += v
v = max(0, v - 1)
... | 26349689158a8a353a44cf6a2f0cec9c1d4d599e | 655,074 |
import re
def url_encode_string(string):
""" "Encode" string to audio URL format of Mairo's.
Return encoded `string`.
"""
encodedString = string.replace(" ", "-")
encodedString = "".join(
list(filter(lambda c: c not in "?.,!/;:’'\"", encodedString))
)
return re.sub("[^A-Za-z0... | ddcd5442e987f68ec71fc7c8aa1966bbc43a4967 | 655,075 |
import platform
import os
def __get_clear_command():
"""Get the command line call for the current operating system to clear the terminal window. If
the operating system is not detected or if it is determined that the script is not running in
the terminal window, return None."""
os_clear_command = Non... | 5173e86cb8966c23fab56f22ca10a8b4055b4866 | 655,076 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.