content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def calculations_rain_module(basin, rain_intensity, timestep):
"""
Calculates the volume of rain falling on a basin during 1 timestep.
:param basin: Basin in which the rain is falling
:param rain_intensity: amount of rain falling per hour [mm/hour]
:param timestep: amount of seconds per timestep
... | ed894972f08024bf3913ec3f933fbb07b95b4fca | 632,292 |
def linear10(value):
"""Convert dB value to linear units (power-like)."""
return 10 ** (value / 10) | fbc4c70c0dd3628ca854fa90bb2056076579d846 | 632,293 |
from pathlib import Path
def _set_dir_iol(dir_in, dir_out, dir_log=None):
""" Set directory name for input, output, and logs.
"""
dir_in = Path(dir_in)
dir_out = Path(dir_out)
if dir_log is None:
dir_log = dir_out.parent
else:
dir_log = Path(dir_log)
return dir_in, dir_out,... | 0404443da3f58342e065a169c5c8f39aeea59754 | 632,294 |
def mean_iou(pred, mask, classes = [0,1]):
"""
Computes IoU metrics for two segmentations only for given classes
(if class is not presented in mask, it is not considered in mean)
Input:
pred - predicted segmentaion - torch tensor with shape (h,w)
mask - ground tru... | 27cd87cecfe8c7200e8a7d32ae8e3e19847637cb | 632,295 |
import hashlib
def encode_password(string):
"""
Encodes a password using SHA-256 algorithm.
"""
# Converts the string into bytes
encoded_string = string.encode()
# Create the SHA-256 object
result = hashlib.sha256(encoded_string)
# Get the hexadecimal format of the encoded data
hex... | 33b982d17e59933dbc63711f213c7d72a85b22b0 | 632,296 |
def change_model_batch_shape(model, batch_shape):
"""
Change input model's batch shape.
Ref: https://discuss.tensorflow.org/t/change-batch-size-statically-for-inference-tf2/5995
"""
model_config = model.get_config()
model_config['layers'][0] = {
'name': 'new_input',
'class_name'... | 8a743168991411fdcc78fb0d0d48cb056e39c955 | 632,297 |
import os
def fullpath_names(root_dir, file_list):
"""Create a list of fullpath file-name
"""
fullpath_list = []
for i in file_list:
fullpath_list.append(os.path.join(root_dir, i))
return fullpath_list | 77432ca1400f9aad4e0929b9655ef5c472a688d4 | 632,298 |
def myfix(arg1, arg2, parg1):
"""One parameterized fixture relying on above param fixture"""
return arg1, arg2, parg1 | e0060cd8fa027fa5160de0d5e12a31bf28895579 | 632,299 |
def _get_ancestors(obj, _objects_travelled=None, max_height=None):
"""
:type _objects_travelled: list or NoneType
:rtype: list[Node]
"""
if max_height is not None:
if max_height <= 0:
return [], {}
else:
max_height -= 1
_objects_travelled = _objects_travelled or []
_objects_travelled.append(obj)
paren... | 1ca506441cb0041b637cbaa08f52b1fa7a397871 | 632,300 |
import os
def get_filenames(
loc=["/data/nordic-tweets", "/data/nordic-tweets-2"], endswith=".tsv"
):
"""
fetches all filenames from data location
"""
if isinstance(loc, list):
filenames = []
for l in loc:
filenames += get_filenames(loc=l)
return filenames
f... | 08136d7789ee4daa3553269b4b035ef9a3a71d39 | 632,301 |
def base128Size(n):
""" Return the length in bytes of a UIntBase128-encoded sequence with value n.
>>> base128Size(0)
1
>>> base128Size(24567)
3
>>> base128Size(2**32-1)
5
"""
assert n >= 0
size = 1
while n >= 128:
size += 1
n >>= 7
return size | f6288ef3da20413f9949b47d61b8cb3bcd6f045c | 632,302 |
def percent(numerator, denominator):
"""Return (numerator/denominator)*100% in string
:param numerator:
:param denominator:
:return: string
"""
# Notice the / operator is from future as real division, aka same as Py3,
return '{}%'.format(numerator * 100 / denominator) | a552e639bf4cb70fa7bddef3cc52a7295fc41da2 | 632,303 |
import torch
def combine_batches(*batches):
"""Combine two multimodal batches.
Args:
batches: list of the multimodal batch tuples to be combined.
*batches:
Returns:
a combined multimodal batch, with a `batch_size` that is equal to the sum of the batch sizes of the batches
in `ba... | cbda0315f657feba451a7bc846f3c10d08de226f | 632,304 |
def boolean_rate(iter, **kwargs):
"""
Computes the fraction of rows meeting a comparison criteria defined
by `cmp_method`. The index containing the value is passed as a kwarg
(`bool_idx`).
Useful aggregator for boolean metrics: threshold, survival,
live_accounts
... | 91fc309912b35c137ceb49563ec8ad907e1aba69 | 632,305 |
def reduced_chi_squared(yfit, y, sigma, degrees):
"""Given yfit, y, sigma, and (the number of) degrees of freedom,
return the reduced chi-squared value.
"""
error = yfit - y
return sum(error*error/sigma/sigma) / degrees | dc9f8a8cba69d7cca064c75dc2c7d88dccfe6b9c | 632,306 |
def find_no_text_pages(page_texts):
"""Find the pages in the page text list `page_texts` (created by make_page_corpus.py) that
contain no text
Returns: list of empty page numbers (page numbers start at zero)
"""
return [i for i, text in enumerate(page_texts) if not text] | 1ee3b751294d3512e0e727d723f96437b28a3b7a | 632,307 |
def remove_characters_without_dialog(screenplay):
"""
remove double 'character' instances from screenplay (happens when a character
does something, but doesn't actually speak, e.g. GEORGE: (gasps)
"""
redundant_indices_in_screenplay = []
for i in range(len(screenplay)-1):
if screenplay[i... | 831a2ee6e0d8ab1879e8b48dfe434c5d44b57649 | 632,308 |
from typing import List
import re
from textwrap import dedent
import textwrap
def wrap_paragraphs(text: str, ncols: int = 80) -> List[str]:
"""Wrap multiple paragraphs to fit a specified width.
This is equivalent to textwrap.wrap, but with support for multiple
paragraphs, as separated by empty lines.
... | 0c2953c86b0752b0e76eabfe479ad61980c76f4a | 632,310 |
from pathlib import Path
def match(path: Path) -> bool:
"""Return True if the path is a ZIP archive."""
return path.suffix.lower() == ".zip" and path.is_file() | 127c4ca25448db1cc732f22fe4e227f78b71c09e | 632,311 |
from datetime import datetime
def convert_date(date_string):
""" transforms the canonical date strings into dates """
try:
return datetime.strptime(date_string, "%Y-%m-%d")
except ValueError as e:
print("woops, the date '%s' is not in YEAR-MONTH-DAY format." % date_string)
exit(1) | 2617d666abb08b0fea31dd395f6d6fad85c2f2ab | 632,312 |
def _find_first_degree_branches(branch, branch_id):
"""Find all branches connected to a given branch.
:param pandas.DataFrame branch: branch DataFrame from Grid object.
:param int branch_id: index of branches to find neighbors of.
:return: (*set*) -- set of branch indexes (integers).
"""
from_b... | f86317bf9200ac8907661955ddfdf489457c87d8 | 632,313 |
import numpy as np
def timeseries_bootstrap(tseries, block_size):
"""
Generates a bootstrap sample derived from the input time-series. Utilizes Circular-block-bootstrap method described in [1]_.
Parameters
----------
tseries : array_like
A matrix of shapes (`M`, `N`) with `M` timepoi... | c4470ce2af695d3c58348bc27c6c56a51d425f75 | 632,315 |
from typing import Iterable
from typing import List
def buf2lines(buf: Iterable[str]) -> List[str]:
"""
Hacky functions for Ultisnips lines into normal list of str.
"""
lines = []
try:
for i, line in enumerate(buf):
lines.append(line)
except Exception:
return lines
... | 5b83721fc644a5cc63a3f82a34893f086d68205a | 632,317 |
import argparse
import os
import yaml
def get_config():
""" Parse configuration options for script.
To avoid bootstrap problems there are no defaults.
"""
parser = argparse.ArgumentParser(
description="Run Google calendar helper scripts and send "
"the output somewhere (publish fe... | ea3d3f575839a091e9c1dd79f20d19db017b1848 | 632,318 |
import inspect
def load_class(module_obj, class_name=None):
"""load the first or named class from a loaded
module, it is a helper function."""
class_members = inspect.getmembers(module_obj, inspect.isclass)
class_obj = None
for cls_obj in class_members:
if class_name is None or cls_obj[... | 2e096a7e4168fbdfff3abce5fee353e22d116229 | 632,320 |
import string
def fill_template_filename(template_string, substitution_dict):
"""
Replace variables in the template with the respective substitution dict entries.
Checks the `template_string` for variables (i.e., something like '${VAR_NAME}') that are listed as keys in `substitution_dict`. If such entrie... | 58afbd292d1de6aaa858fec1b0771dfcf8e095a7 | 632,321 |
def bulk_create_or_get(session, mapper, ids):
"""
For given model, return a list of entries with given primary keys.
Any entries that don't exist will be created.
"""
entries = list(
session.query(mapper)
.filter(mapper.id.in_(ids))
)
existing_ids = set([entry.id for entry i... | d067fcfe37305460ac0c730d17e1344fd9dddbd0 | 632,322 |
def delete_before(list, key):
"""
Return a list with the the item before the first occurrence of the
key (if any) deleted.
"""
if list == ():
return ()
else:
head1, tail1 = list
if tail1 == ():
return list
else:
head2, tail2 = tail1
... | cf3188c9955e5d8c04adc58ed65e9c5079d13d1a | 632,323 |
def get_stock_exchange(stock_code: str) -> str:
"""
Get the stock market according to the code rule.
:param stock_code: The stock code that need to check/
:return: Exchange. SSE - Shanghai, SZSE - Shenzhen. Empty string if not recognized.
"""
if len(stock_code) != 6:
return ''
if sto... | 71d0d388907e77f63f238903e98a2da0bca269cd | 632,324 |
import mimetypes
def guess_mime_type(file_):
"""Get Mime Type Of A File From Url / Path"""
s = mimetypes.guess_type(file_)
if not s[0]:
return None
else:
return s[0] | 66ff050f50f2a242f0b4298ef687dba2d08c850e | 632,325 |
def fibonacci_sum_naive(n):
"""Stupid example solution.
"""
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
sum += current
return sum % 10 | f6a1cde85c9b2f0ce80413fc687e2c3b700d1738 | 632,326 |
def cercle(x_centre, y_centre, rayon):
"""
génère un élément SVG représentant un cercle (ou un disque, cela
dépend de la couleur de remplissage du groupe où l’on se trouve)
"""
balise = "<circle cx='{x}' cy='{y}' r='{r}' />"
return balise.format(x=x_centre,
y=y_centre,
... | 34aed8c0022de78d9068db95ab8cab269f384c5f | 632,327 |
import glob
def check_for_project():
"""
Performs a check if we are operating within a project folder. When
we wish to perform a deploy action, we want to be on the same
level with the `askanna.yml` to be able to package the file.
"""
pyfiles = glob.glob("*.yml")
# look for the setup.py f... | 86fe2c3a13e9de694d8e55845bd8c16709f1dc11 | 632,328 |
def boundary_check(centralied_marks):
"""Check situation that marking point appears too near to border."""
for mark in centralied_marks:
if mark[0] < -260 or mark[0] > 260 or mark[1] < -260 or mark[1] > 260:
return False
return True | feb53f624c6980cc4101f47b6198de3ef4147cbb | 632,329 |
def convert_gold_to_str_set(test_instance):
""" Helper method to convert the gold labels into readable text strings """
return {test_instance[0][x[0]:x[1]] + '_' + x[2] for x in test_instance[1]['entities']} | bee84d584c95a05f1c6515d63d7e73799e3b320b | 632,330 |
def response_extract(selector, expr, index=0, join_str=None, strip=True, default=None, cast_as_int=False):
""" helper extract text from response selector (lib parsel)"""
r = selector.css(expr).extract()
if r is None or len(r) <= index:
return default
else:
if join_str:
r2 = j... | a31414434b3f64696ce3254ceb7bed95c4df466b | 632,333 |
def charToString(charArray):
""" Takes an array of chars and returns the corresponding string."""
result = ""
for i in charArray:
result += i.decode("UTF-8")
return result | 63ac5dbe18d6e187bb44fcdb1eee86c48c8dbefb | 632,334 |
def snap_key_to_snapnum(snap_key):
"""
Given the name of a snapshot key, finds the associated snapshot number.
This is necessary because the 0th snapshot key may not be snapshot 000 and
there could be missing snapshots. This function searches backwards for a
group of digits that identify the snapsh... | 9b30f0efc978e50beaf50427eb4aac35dcb1f964 | 632,335 |
import platform
import os
def get_host_executable_extensions():
"""Get a list of executable file extensions.
Returns:
A list of executable file extensions.
"""
# On Windows search for filenames that have executable extensions.
exe_extensions = ['']
if platform.system() == 'Windows':
extensions = ... | 9fcb1773038806d5f506ce72d39eeb469e656066 | 632,337 |
def _get_str_ip():
"""Just a user mock string."""
return "I am the stupidest living being in the entire universe, and I still somehow find a lot of folks who are just stupider." | 2e9de4743325e1fbc237a8fa00b018532765aa1c | 632,339 |
import argparse
def _parse_args():
"""Argument parser: parse the folder path.
Argument:
--inputpath
--ricepath
--homolist
--outputpath
--output_alignedpath
"""
parser = argparse.ArgumentParser(description='ArgParser for align_seedling.py')
parser.add_ar... | a5b8bd7669e2bd174bc27b669186dcccb3b20d22 | 632,340 |
def flow_perms(user, task):
"""
Assign list of permissions.
Example::
{% flow_perms request.user task as task_perms %}
"""
result = []
if hasattr(task.flow_task, 'can_execute') and task.flow_task.can_execute(user, task):
result.append('can_execute')
if hasattr(task.flow_... | 989eac73a72c868a01db9b34110c09774fa86a46 | 632,342 |
def ip_str_from4bytes(s: bytes) -> str: # b'\xc0\xa8\xfa\xe5' => 192.168.250.229
""" Convert bytestring to string representation of IPv4 address
Args:
s: source bytestring
Returns:
IPv4 address in traditional notation
"""
return str(s[0]) + "." + str(s[1]) + "." + str(s[2]) + "." ... | 0bac5deab1699eb01c2f93be9af6039eae68665f | 632,343 |
import math
def plasmaSI():
"""
This creates a dictionary of all the plasma constants used on a regular basis.
All constants are in SI units
"""
# set physical constants here in SI units
pcsi = {} #This is how he defines an empty dictionary.
pcsi['m_e'] = 9.1094e-31 # electron mass in [kg]
pcsi['m... | 76e1e21905b4a4e1573bb191e9b1fc8b9dd827e2 | 632,344 |
from yaml import dump
from typing import Dict
def yaml_samples_pep_filter(p, **kwargs) -> Dict[str, str]:
"""
YAML samples PEP filter, that returns only Sample object representations.
This filter can save the YAML to file, if kwargs include `path`.
:param peppy.Project p: a Project to run filter on
... | 3e0def23db0afd7530942c47e1a97f2088901c67 | 632,345 |
def suffix(num: int) -> str:
"""
Returns the suffix of an integer
"""
num = abs(num)
# Suffix only depends on last 2 digits
tens, units = divmod(num, 10)
tens %= 10
# suffix is always 'th' unless the tens digit
# is not 1 and the units is either 1, 2 or 3
if tens != 1:
... | f01226abef5b5e6ece3082e58d259b3f59a7ec6d | 632,346 |
def get_filenames():
"""Tile-filename dictionary."""
filenames = {0: "none.png",
1: "floor.png",
2: "wall1.png",
3: "wall2.png",
4: "wall3.png",
5: "wall4.png",
6: "wall5.png",
7: "wall6.png",
... | 8c00a46b1f714c142c54d980166265d50b83e29b | 632,347 |
def encontrarCaja(mediana,punto,inicioDimension,dimension):
"""
Funcion que encuentra un indice de caja dada una mediana, un punto y un rango de dimension (inicio y dimension). Dimension en este caso jugaria el rol de largo.
Se entiende que las operaciones se pueden calcular como un arbol binario p... | 8d6bbed37c3ba57732dd29823043067e39a6fe70 | 632,348 |
def set_significant_digits(radar) -> None:
"""
Set _Least_significant_digit netcdf attribute.
"""
fieldnames = [
("VEL", 2),
("VEL_UNFOLDED", 2),
("DBZ", 2),
("DBZ_CORR", 2),
("DBZ_CORR_ORIG", 2),
("RHOHV_CORR", 2),
("ZDR", 2),
("ZDR_CORR_A... | 746fdc88fb1d3e09a59bec2e4e05e07defb70f2c | 632,349 |
import re
def normalize(text):
"""
Removes newlines and multiple whitespace charaters
"""
text = text.strip()
text = re.sub('[\n\t]', ' ', text)
text = re.sub('\s+', ' ', text)
return text | e91c79464443e2cb6c75871cab9e4f97cf7f318f | 632,350 |
def local_shuffle(frame, num_new_parts, key_columns):
"""Regroup the frame based on the key column(s)
"""
partitions = frame.partition_by_hash(columns=key_columns, nparts=num_new_parts)
return dict(enumerate(partitions)) | 858e4a3d30fc846b6a040cbdfa7f634efaace05d | 632,351 |
def limited_join(sep, items, max_chars=30, overflow_marker="..."):
"""Join a number of strings to one, limiting the length to *max_chars*.
If the string overflows this limit, replace the last fitting item by
*overflow_marker*.
Returns: joined_string
"""
full_str = sep.join(items)
if len(fu... | 3abe07a3b24d82d391fcafbeba746470676f4312 | 632,352 |
def get_indexes_from_best_path(best_path):
"""Grab the reference and event index of the best path from the maximum_expected_accuracy_alignment function.
:param best_path: output from maximum_expected_accuracy_alignment
:return: list of events [[ref_pos, event_pos]...]
"""
path = []
while best_pa... | ffcfa377b48f02356b3ddad75b725baf22a096d8 | 632,354 |
def flagged(flag):
"""
Return special character denoting concretization happened.
"""
return '(*)' if flag else '' | 95a1a0c423bc75001c3191a260b68303b8211d57 | 632,355 |
import csv
def make_csv_reader(file_path, validate_element=None):
"""
:return array of dicts representing the .csv file
"""
ret_val = []
with open(file_path, mode='r') as csv_file:
for l in csv.DictReader(csv_file):
if validate_element:
n = l.get(validate_elemen... | 7dc0b8167419043232d3e437220875cf337e5590 | 632,356 |
def removesuffix(text, suffix):
"""Removes a suffix from a string.
If the string ends with the suffix string and the suffix is not empty,
returns string[:-len(suffix)]. Otherwise, returns the original string.
This function has been added in Python3.9 as the builtin
`str.removesuffix`, but is define... | d7c2f37b3012590c3d66911233abf6c4d7891205 | 632,357 |
def getval(constraints, key, db):
"""
Get the value of a constraint
"""
value = constraints[key]
if callable(value):
# find param
param = [e for e in db.parameters if e['Name'] == key][0]
if 'Categories' not in param:
return ''
return [e for e in param['Categor... | 2ec2e58d6c277cb62aa6cb480bdf1b617ac81c3e | 632,358 |
def generate_LSTM_samples(engine_df, nSequenceSteps):
"""
This function generates list of LSTM samples (numpy arrays of size (nSequenceSteps, 24) each) for LSTM input
and list of output labels for LSTM
"""
engine_X_train_sequence = []
engine_y_train_sequence = []
engine_data = engine... | 0620ee9ea15f9422f07e55f8db6dc74374bfec49 | 632,359 |
def get_all_morph(df):
"""
Returns all morphemes and Part-of-Speech.
- input : dataframe
- output : string
"""
ret=''
for index, row in df.iterrows():
if row['type'] == 'Inflect' or row['type'] == 'Compound':
tag=row['expression']
ret+=tag.replace('+',' ... | c96516b7e6a07b2b3f45d0597f135aa11f7d12bf | 632,360 |
from typing import List
def filter_releases_by_channel(releases: List[dict], channel: str):
"""
Filter releases by channel (stable, beta, or alpha).
:param releases: a list of releases
:param channel: a software channel (
:return: a filtered list of releases
"""
if channel not in ["stabl... | 1d72ed0088e13b3dc50a53332413877ee9c75986 | 632,362 |
def split_event(mhw_ev):
"""If event span across two years you might want to split it into two
and calculate separate stats.
"""
return mhw_ev | 2eb9e3f55fca0df98ba4b685dcbf46c7bf04277a | 632,364 |
def exec_command_msvc(self, *k, **kw):
"""
Change the command-line execution for msvc programs.
Instead of quoting all the paths and keep using the shell, we can just join the options msvc is interested in
"""
# If bullseye coverage tool is in the environment, and we are executing the CXX or C compi... | e2654092c66033ae68f63484142f0e33fa434c8c | 632,365 |
def parse_show_qos_cos_map(raw_result):
"""
Parse the show command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the 'show qos cos-map' command in a \
dictionary where each key is a code point in the cos map:
::
{
... | 3b02b3af0224aed923230680992eaabae85543cb | 632,367 |
def guess_band(filename):
""" Guess the passband using the image's filename"""
if '_B_' in filename:
passband = 'B'
elif '_V_' in filename:
passband = 'V'
elif '_R_' in filename:
passband = 'R'
elif '_I_' in filename:
passband = 'I'
else:
passband = 'clear... | 0b516d236cae8ea29d9043eaaa7a53a3d659b3a4 | 632,368 |
def indent(txt, indent_level):
"""
Indent a piece of text
>>> indent('foo', 2)
' foo'
"""
indent = " " * indent_level
return "\n".join(indent + x for x in txt.splitlines()) | b0b48e304cfafd65c8d8f7be6b056cf755951cdf | 632,369 |
def get_op_name(tensor_name):
"""
Given a tensor name, return the corresponding op name.
Args:
tensor_name: The name of a tensor.
Returns:
str: The op name
"""
return tensor_name.replace('^', '').split(':')[0] | 059f953771911370566505ff71e1a654148d2fc3 | 632,370 |
async def do_something():
"""
Do smoething
"""
return 'hello world' | cad6fb681aad4fa024d64ab774d2f1b562fd0e9a | 632,371 |
def clean_word(word):
"""
converts every special character into a separate token
"""
cleaned_words = []
temp = ""
for char in word:
if (ord(char)>=33 and ord(char)<=47) or (ord(char)>=58 and ord(char)<=64):
# if (ord(char)>=33 and ord(char)<=47 and ord(char)!=39) or (ord(char)>=5... | b1a9c0ace3799fc7dfbde505856e8485bd5c83bc | 632,372 |
def compute_security_exposure_returns(exposures, factor_returns) :
"""
Computes
"""
exposures = exposures.reset_index().sort_values('data_date').set_index('data_date')
(e1, r1) = exposures.align(factor_returns, join = 'inner')
# security factor returns
df = r1 *... | 6e5b0dfeea71414b873b8c42203b0abf21b30df3 | 632,373 |
def _make_block_map(keras_block_names):
"""Create block variables mapping."""
last_conv_number = 4
last_bn_number = 4
block_map = {}
for block_name in keras_block_names:
if "conv" in block_name:
block_map.update(
{f"{block_name}/kernel:0": f"conv2d_{last_conv_n... | 378affd41b06c409e8e207c7373dd1ddcf23f74d | 632,374 |
def mean_anomaly(dt_j2000: float) -> float:
"""eq. 16 a&m"""
return 0.3383687274133927 + 0.009145887087204227 * dt_j2000 | e22b3589ab26baddf2ee17c526f0e11948e05fbe | 632,375 |
import re
def remove_dupe_chars(text: str) -> str:
"""accept -> acept"""
text = re.sub(r"([a-zA-Z])\1+", r"\1", text)
return text | a269c01b60dbd57b4b6c0c25214f15061cb78ba6 | 632,376 |
def exclude_files():
""" Define which output files are not necessary for postprocessing """
return ['cap_press'] | 69507dfe18c5f95df659c7387963d3136837afd6 | 632,377 |
def is_even(num):
"""Проверяем, является ли число простым или нет.
Args:
num (int): Случайное число от 1 до 10
Returns:
bool: Если число простое, то возвращаем да, иначе нет.
"""
return "yes" if (num % 2) == 0 else "no" | 38828385c34ebbde3f72eaa215d55fcd990203a9 | 632,378 |
def is_number(number):
"""
Check whether this is a number (int, long, float, hex) .
Aruguments:
number: {string}, input string for number check.
"""
try:
float(number) # for int, long, float
except ValueError:
try:
int(number, 16) # for possible hex
... | 02c3d189eb1ac4f522601d55423dbd84af8ae79f | 632,379 |
from typing import Pattern
def parse_substring(full_string: str, rex: Pattern[str]) -> str | None:
"""Parse an url for substring matching the given regular expression.
Args:
url (str): String representation of the URL
rex (Pattern[str]): String represenation of a regular expression
Retur... | 9e1110badaf3d1d8d8527f4ff6db5de6be552641 | 632,384 |
def extensions(includes):
"""Formats a list of header files to include.
"""
return ["".join([i.split(".")[0], ".h"]) for i in includes if i.split(".")[0] != "types"] | 4a35a2383ca62d6f7d4cad25d2dc47e5ee179d41 | 632,385 |
import math
def tanh(x):
"""
数学形式:tanh(x)=(e ** x - e ** (-x)) / (e ** x + e ** (-x))
"""
ret = (math.e ** x - math.e ** (-x)) / (math.e ** x + math.e ** (-x))
return ret | aafab19d6a7cdfcde3dacb3f66c41fe9ff46d094 | 632,388 |
def calc_delta_theta_int_inc_heating(bpr):
"""
Model of losses in the emission and control system for space heating and cooling.
Correction factor for the heating and cooling setpoints. Extracted from EN 15316-2
(see cea\databases\CH\Systems\emission_systems.xls for valid values for the heating and co... | 8a814d90cc27d53e19437cdc394ad3a472e8d023 | 632,389 |
import subprocess
def get_HW():
"""Hardware."""
p = subprocess.Popen("cat /proc/cpuinfo | grep 'model name\|Model'", stdout=subprocess.PIPE, universal_newlines=True, shell=True)
data = p.communicate()[0].splitlines()
return (data[-1][9:] + data[0][12:]) | d3a5033aa8272055f702360c56cf683ad749489f | 632,390 |
def calc_check_digit(my_number):
"""Calculates check digits"""
my_number_sum = 0
if len(my_number) != 11:
raise TypeError("Malformed My Number Segment -- Must be 11 numbers")
# They count their digits high to low, so reorder it
my_number_list = my_number[::-1]
for n in range(1, 7):
... | 104c146fe823ad1d033a988619a25e8a0c4f46b5 | 632,391 |
import re
def matches(target, search_query):
"""
Uses a regex to match the header title with the desired title
:param target: The title to compare against
:param search_query: The field to compare with
:return: Boolean
"""
title_regex = re.compile(search_query, re.IGNORECASE)
res = tit... | 9fb66a03063c826108fd9f8c25526da63217327c | 632,392 |
import argparse
def parse_args():
"""
@brief Parse the arguments that are entered by user via command line
@return a namespace of the parsed arguments from command line
"""
parser = argparse.ArgumentParser()
# parameters accepted by the parser
parser.add_argument('-p', '--preproc... | a087504f9c45270a74394a11feeb9d85738d86b4 | 632,393 |
def sievePath(fDB, path):
"""Recursively removes all files in path that are already in the fDB.
:param fDB: the information regarding files
:type fDB: FileDB
:param path: the path
:type path: str
:rtype: int
Returns the number of deleted files.
"""
return fDB.sievePath(path) | 48287383035e78a506f3460ebfd25f520c3612c0 | 632,394 |
import time
def is_time_obj(obj):
"""Return True if obj is a time."""
return isinstance(obj, time) | 60d25cfa0983ba5b557e73d2b25b013cfb33947a | 632,395 |
def _hasAromaticAtoms(mol):
""" The BertzCT descriptor changed for molecules with aromatic rings """
return any(atom.GetIsAromatic() for atom in mol.GetAtoms()) | bb82d2eafe1358e68d152fb3969ef9dfa69259f0 | 632,396 |
def _tau_prior():
"""Default tau prior."""
return [0.0, 1e3, 'flat'] | 4022c64462ee0f4f670fd9e848bd970abcabd168 | 632,397 |
def num2columnletters(num, power=0):
"""
Takes a column number and converts it to the equivalent excel column letters
:param int num: column number
:param int power: internal power multiplier for recursion
:return str: excel column letters
"""
if num <= 26:
return chr(num % 27 + 64)... | 39096fc9df99baba6ddbc1a7a48a7eb0068ddf44 | 632,398 |
def test_faucetinfo():
"""Not implemented call yet"""
return True | 677a6fb31fa306e03b8b9897aba05d7659e10d99 | 632,399 |
def normaliseWV(wV, normFac=1.0):
"""
make char probs divisible by one
"""
f = sum(wV) / normFac
return [ i/f for i in wV ] | 11b729aad3b1f1f7a7f6cec8f3c43ec14568ddcb | 632,400 |
def _APINameFromCollection(collection):
"""Get the API name from a collection name like 'api.parents.children'.
Args:
collection: str, The collection name.
Returns:
str: The API name.
"""
return collection.split('.')[0] | 484e57081f348ba39ce65ffbfe1c23c28519fe3f | 632,401 |
import random
def pick_from_distribution(input_map):
"""
Generates an item from a distribution map
:param input_map: The dictionary of items to their probabilities
:return: An item from the dictionary
"""
rand = random.random()
total = 0.0
for item, prob in input_map.iteritems():
... | 2ba62477bdc02c6f541d5f05100dee646d9b2f76 | 632,402 |
import math
def convert_tz_hours_to_tz_offset(
tz_hours
):
"""Convert Timezone hours into Timezone offset.
Args:
tz_hours:
Returns:
"""
_tz_signed = tz_hours < 0
if _tz_signed:
tz_hours *= -1
frac, whole = math.modf(tz_hours)
int_hours = int(whole)
int_minu... | c4c6eeafbaf9f9dd5faae0679aa2fbc55ed81ca2 | 632,403 |
import torch
import numpy
def concatenate(*arrays, dimension: int = 0):
"""Concatenate multiple arrays along a specified dimension."""
if len(arrays) == 0:
raise NotImplementedError()
if all(array is None for array in arrays):
return None
elif isinstance(arrays[0], numpy.ndarray):
... | 8214ea5302635be2910e839a963c98479efccbd5 | 632,405 |
def _not_divisible(n):
"""
:param n: known number, x is the element of the sequence
:return: bool
"""
return lambda x: x % n > 0 | ea5ae585bba1ca4ca9a7791105b61df65af0e810 | 632,406 |
import socket
import sys
import traceback
def s3_test( remote_path, verbose = False ):
""" test to make sure that we can access the remote path """
try:
host, port, path = ("s3.amazonaws.com",80,"")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
... | 60df8226ee7fc2b9e19986809b04a338c5ba5155 | 632,407 |
def get_line_by_offset(file_path: str, offset: int) -> str:
"""Get line by byte offset from the given file.
:param file_path: path to the file
:param offset: byte offset
:return: read line
"""
with open(file_path, "r") as data_file:
data_file.seek(offset)
line = data_file.readli... | aa6f2e50c1d493835d0be18391a37ea43011e915 | 632,409 |
def plot_raw(fig):
"""Set up the basic plotting paramaters"""
ax = fig.add_subplot(111, projection='3d')
ax.set_autoscale_on(False)
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.set_xlim3d([0.0, 100.0])
ax.set_ylim3d([0.0, 100.0])
ax.set_zlim3d([0.0, 100.... | ed13f98ca0513b8067b6b3ebe93b988ad0b770fa | 632,410 |
import subprocess
def is_jpg_ok(fullfile):
"""Check if file is corrupted.
Args:
fullfile(str): fulle filename
Returns:
bool: False if file is corrupted.
"""
process = subprocess.Popen(['identify', '-verbose', fullfile],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
_, ... | a8b219f7bcecfc88ba20ac9f94f1cb85e6c8b089 | 632,411 |
import json
def get_end_stream_request(stream_id: str, request_id: int, api_version: str) -> str:
"""
Parameters
----------
stream_id:
ID of stream we want to stop
request_id:
ID of EndStreamRequest
Returns
-------
Serialized EndStreamRequest
"""
api_message = ... | 86265dd7cb7bef04eb9f1c5d876afa85bbac1a72 | 632,413 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.