content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import json
def test_json(filename):
"""Verify that given filename is valid JSON; if not, return None."""
try:
with open(filename, 'r') as f:
data = json.load(f)
except Exception as e:
print(e)
data = None
return data | 85ba7b7366322d02e9e983f4d6ad57c6dbed8371 | 679,133 |
def get_zoom(largest, width):
"""
Determine an appropriate zoom ratio so that the given value will fit
within width.
"""
scale = 0
options = [1, 2, 3, 5]
while True:
for x in options:
zoom = x * (10**scale)
if largest // zoom <= width:
return ... | a7fa107454a70292502f7ea7486968bbca206719 | 679,134 |
def clean(bstr_in: str, command_name='()', bstr_name='') -> str:
"""clean():
- Removes '_' characters
- Raises exceptions on illegal characters
"""
bstr_out = ''
for bit in bstr_in:
if bit in '01':
bstr_out += bit
elif bit in ' _':
pass
else:
... | 4d84c3e599048258a2a1f55cedd12793a33e4462 | 679,136 |
import glob
def find_code_with_doctests():
"""Naive search for modules with any doctests strings."""
candidate = []
for file in glob.iglob("**/*.py", recursive=True):
if "main/" not in file:
continue
else:
with open(file) as handle:
if ">>>" in handl... | b563580e118ae5e16cec86ae178b7c4a9cc23f8d | 679,137 |
def regex_for_target_temperature():
""" T0:210 /210 B:0 /0 """
return '\/([0-9].*?) ' | 42aa51697029a7a9977a35b545a07213ac73e033 | 679,138 |
def contains(seq, value):
"""
Description
----------
Checks to see if a value is in the sequence or dictionary.
Parameters
----------
seq : (list or tuple or set or dict or string) - sequence/dictionary to search in\n
value : any - value to search for
Returns
----------
boo... | ca408206626d230ac5c59157f9012046071fd164 | 679,140 |
import json
def read_configuration():
"""Returns JSON object with configuration"""
with open("config.json") as f:
config = json.load(f)
return config | 4812e520a0e79b2faf6a72d81fff113e0a917de8 | 679,141 |
import os
def forks_enabled():
"""Return true if forks are enabled.
By default forks are not enabled (for the purposes of local development).
Forks can be enabled by setting the FORKS_ENABLED environment variable
to ``true`` (or, in tests, by overriding this function).
"""
return os.environ.... | 4d813304b0721f7420d99ca8f1e8e060eeb4040e | 679,142 |
def stage_title(stage):
"""Helper function for setting the title bar of a stage"""
stage_txt = ("Name", "Vocation", "Character Design and Details",
"Stats and Skills", "All Done: Thank You!")
stage_cmd = ("{w@add/name <character name>{n", "{w@add/vocation <character's vocation>{n",
... | badd7ad6a59c52a0bbc4f186aca7fd4c653a0910 | 679,143 |
import socket
def resolve_hostname(hostname):
""" This function uses system DNS to resolve a hostname.
It is capable of retrying in case the host is not immediately available
Wait time is expressed in seconds. Default is 5 attempts, 2s min, 5s max
"""
return socket.gethostbyname(hostname) | b235fe54de0ef96014619a4d41ed5179a2567935 | 679,144 |
from functools import reduce
import operator
def get_location(nested_dict=None, keys_list=None):
"""
Description
-----------
Static function to get a value of a nested key from a nested dictionary
:param nested_dict: Nested dictionary from which the nested value is to be retrieved
:param keys_... | f86dd324d1c0d05af4101c14a7c6803efd5322fb | 679,145 |
import os
def get_app_base_path():
"""Return module directory"""
return os.path.dirname(os.path.realpath(__file__)) | 0463a0f356ec5966b238bf3128564c79c55761b6 | 679,146 |
import os
import time
def catalog_creation_payload(repo_type: str,
repo_source_ip: str,
catalog_path: str,
repo_user: str = "",
repo_domain: str = "",
repo_password: str = "... | 74e3d55781970b0617479777ab1ee4ac86523ac1 | 679,148 |
def add_weight_decay(model, weight_decay=1e-5, skip_list=()):
"""Splits param group into weight_decay / non-weight decay.
Tweaked from https://bit.ly/3dzyqod
:param model: the torch.nn model
:param weight_decay: weight decay term
:param skip_list: extra modules (besides BN/bias) to skip
:ret... | 786993f755adabf09b34a36bade30cbad71d76ce | 679,149 |
from typing import List
def remove_stubs(packages: List[str]) -> List[str]:
"""Remove type stubs (:pep:`561`) from a list of packages.
>>> remove_stubs(["a", "a.b", "a-stubs", "a-stubs.b.c", "b", "c-stubs"])
['a', 'a.b', 'b']
"""
return [pkg for pkg in packages if not pkg.split(".")[0].endswith("... | 20f5c1e203db1cf10cb21932ac5c600a41a15438 | 679,151 |
from typing import Tuple
def twotuple_metric(vec1: Tuple[int, int], vec2: Tuple[int, int]) -> float:
"""Calculate two two-tuples ali-metric.
Args:
vec1: two-tuples of int
vec2: two-tuples of int
Return:
float metric: 1, 0.5 or 0
>>> twotuple_metric([0, 1], [0, 1])
1.0
... | 4b4e2f4ec2286761d27ffb17cf69387f65f68be5 | 679,152 |
def read_config(config_file, config_dict):
"""
Read config file and store parameters in dictionnary.
Input:
-config_file string
-config_dict dictionnary
"""
with open(config_file, "r") as file:
file_contents = file.readlines()
for line in file_contents:
if not... | 18252e8a801e5d56523c66abbfb6d87097284d10 | 679,153 |
def to_csv(dictionary, filename=None, headers=None, nm=False):
"""
Save spectral data as csv.
Parameters
----------
dictionary : dict
The dictrionary containing spectral data.
Get using Image.get_spectral_data()
The epected unit for wavelength is Angstrom.
filename : str... | 8ef3e3ba56b18035ae3052003e671e747a7c0077 | 679,154 |
def quantile_normalization_wiki_test_method(df):
"""
Python pandas quantile normalization to compare against spark. This
matches the wikpedia example, but it is not how it is done in RMA.
"""
df['rank'] = df.groupby('sample')["intensity_value"].rank(method="dense")
df['row_number'] = df.groupby(... | 17cabf274dcd8ccb635a55d72edcd256d71d8af5 | 679,155 |
import uuid
def generate_uuid():
"""
generate a unique id using uuid whenever a new aircraft is created
"""
return uuid.uuid4() | 2059610472fe8157a9eb09ec0801efef426dc828 | 679,156 |
from datetime import datetime
def to_graphite_time(time: datetime, default: str) -> str:
"""
Note that millissecond-level precision matters when trying to fetch events in a given time
range, hence opting for this over time.strftime("%H:%M_%Y%m%d")
"""
if time is not None:
return str(int(ti... | d714dc58b375f97f2deb040364eaea20a6b7d5a4 | 679,157 |
import re
import requests
def use_http(accession):
"""
Use urllib to get a link.
Example GCF_001548295: https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/001/548/295/
Need to extract "<a href="GCF_001548295.1_ASM154829v1/">GCF_001548295.1_ASM154829v1/</a>"
"""
accession, version = accession.split... | ae86534c3489c960999dabd450a3dc3f7d46bb83 | 679,159 |
import os
def get_os_name():
"""
:API: public
"""
return os.uname()[0].lower() | c9da8f64a79e3d5eb3281cee838208249ca870ec | 679,160 |
def get_rrmgr_cmd(src, dst, compression=None, tcp_buf_size=None,
connections=None):
"""Returns rrmgr command for source and destination."""
cmd = ['rrmgr', '-s', 'zfs']
if compression:
cmd.extend(['-c', '%s' % str(compression)])
cmd.append('-q')
cmd.append('-e')
if tcp_... | da87825ecccfb13d651a50faf0779e88d84c33f6 | 679,161 |
def standardize_lemma(lemma):
"""
Changes lemma text used to find frequency
"""
if lemma[0] in {'eg', 'vér', 'þér'}:
return ('ég', lemma[1])
else:
return (lemma[0].lower(), lemma[1]) | 8898cba207f6fdae4cfcd0b2d3b55c104ecaf3f5 | 679,162 |
def customise_csc_Validation(process):
"""Nothing for now
"""
return process | 0ee2e57d58ea9095cf2e2278c6a0299dc118fdd2 | 679,163 |
def arrow(m) -> str:
"""One directional arrow key"""
return m.arrow | 129a99c7a67f4346e2e4c19a4763f911563115df | 679,164 |
import json
def load(source_file):
"""
Converts Esri Json File to GeoJSON.
:param source_file:
Path to a file that contains the Esri JSON data.
:returns:
A GeoJSON `dict` representing the geometry read from the file.
"""
return json.load(source_file) | 1d4782a1ea8427de0695a4676ac02afcc7ee9655 | 679,165 |
import torch
def gradients(outputs, inputs):
"""
Compute t, x partial derivatives of variable u\
Input
-----
outputs: variable u
inputs: grid of t, x
Output
------
grad[:, :1]: du/dt
grad[:, 1:]: du/dx
Note: grad[:, :1] gives shape [:, 1] instead of [:]
"... | 7adda6ee84da5290208d0746470b274df70a96bb | 679,166 |
from pathlib import Path
def get_tf_version(tf_path):
"""
Traverse “up” the given directory tree looking for a
.terraform-version file and return its contents, raise an
exception if we reach root without having found anything.
"""
current_path = tf_path
while current_path != Path('/'):
... | 10db32a2701fd8577589afe5f8fb8ff64bbeda97 | 679,167 |
def combine(hi, lo):
"""Combine the hi and lo bytes into the final ip address."""
return (hi << 64) + lo | 0662305da0f258e67d5e9abf31a875dc9d605df6 | 679,168 |
import os
def get_immediate_subdirectories(a_dir):
""" Return list of subdirectories immediately under the given dir """
return [name for name in os.listdir(a_dir)
if os.path.isdir(os.path.join(a_dir, name))] | 760c9517d4d8b09848bae17bac048b88b749dfb3 | 679,169 |
def UA_a_m(UA):
"""
se ingresa el valor en unidades astronómicas y se convierte a metros
"""
m=149597870700*UA
return m | ba15a51d8f0106bad2d6cda61e4e2792c18d1d34 | 679,171 |
def assert_equal_length(psg, hyp, sample_rate):
""" Return True if the PSG and HYP have equal lengths in seconds """
return psg.shape[0] / sample_rate == hyp.total_duration | 968776dee6058b137c3c4445e0e8e87b4223e96c | 679,172 |
def calc_spread(prices, spread_coefficients):
"""Calculate the spread based on spread_coefficients.
Args:
spread_coefficients (list): A list of signed integers defining how much
of each product to buy (positive) or sell (negative) when buying or
selling the spread.
price... | 58fb5e83eaba89001d7134934d84848081190eb7 | 679,174 |
async def time_event() -> dict:
"""Create a mock time_event object."""
return {
"id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"bib": 1,
"event_id": "event_1",
"name": "Petter Propell",
"club": "Barnehagen",
"race": "race_name",
"race_id": "race_1",
... | 494c9f9ed57535b5e1b607ee5055764947d9e69a | 679,175 |
def convert_8_to_16(value):
"""Scale an 8 bit level into 16 bits."""
return (value << 8) | value | e94dc436c96a7b9aae006679f85d4872d702823d | 679,176 |
def size_of(rect):
"""Return size of list|tuple `rect` (top, left, bottom, right) as tuple (width, height)"""
return (rect[3] - rect[1], rect[2] - rect[0]) | 07f50d974e74efca3b7985822fe3b3c84cdc2538 | 679,177 |
import re
def uncolorize(s):
"""
Remove ANSI color escape codes from the string `s` and return the result.
Works with text colorized with the `colorama` module.
"""
return re.sub("\033\[([0-9]+;)*[0-9]*m", "", s, flags=re.UNICODE) | 5ea4b0c5f1b011d0947af69a5579f2804ca10a24 | 679,178 |
import numbers
def is_number(a):
"""Check that a value `a` is numeric"""
return isinstance(a, numbers.Number) | 0ae599682dad264c6705e0f37dc15969628db9ca | 679,180 |
def transform_len(val, default=None):
"""
Calculate length
<dotted>|len len(val) or raises
<dotted>|len:<default> len(val) or <default>
"""
try:
return len(val)
except TypeError:
if default is not None:
return default
raise
... | dbdd0757b387214c44a8341ac5b8b56e741a3b7c | 679,181 |
from typing import Iterable
def nested_depth(iterable:Iterable) -> int:
"""
calculate the nested depth of an iterable
Args:
iterable (Iterable): the iterable to calculate the depth of
Returns:
int: the depth
"""
depth_func = lambda L: isinstance(L, (list, tuple)) and max(map(... | 47e60775c67e55c43d55d8b34d07a7e17c101d6d | 679,182 |
def post_process_fieldsets(context, fieldset):
"""
Removes a few fields from FeinCMS admin inlines, those being
``id``, ``DELETE`` and ``ORDER`` currently.
Additionally, it ensures that dynamically added fields (i.e.
``ApplicationContent``'s ``admin_fields`` option) are shown.
"""
# abort i... | 714145bb42fc4c685a54998700445d7c8a96f5e8 | 679,183 |
def make_pull_request(fake_github):
"""
Provide a function for making a JSON pull request object.
"""
def _fn(user, repo="edx/edx-platform", **kwargs):
fake_github.make_user(user)
owner, repo = repo.split("/")
pr = fake_github.make_pull_request(user=user, owner=owner, repo=repo, ... | edad6ec5a62870f1a917bc7252c507dbb87181b6 | 679,184 |
def bmpInfo_get(byteline):
"""
Parses BMP-file to get an information about
the picture
"""
def convert(bytes_array):
return int.from_bytes(b''.join(bytes_array), 'little')
bmpInfo = {
#Bitmap file header
'bfType' : convert(byteline[0:2]),
'bfSize' : convert(byteline[2:6]),
'bfReserved1' : co... | a9504c1ea43347bcf6bcc927d3ab2f5ca39290a5 | 679,185 |
def sos_gradient(params):
"""Calculate the gradient of the sum of squares function."""
return 2 * params["value"].to_numpy() | 7a16dde8638b397c8caabd0f359bc6ca0e477216 | 679,186 |
import numbers
def commanum(v):
"""
Makes large numbers readable by adding commas
E.g. 1000000 -> 1,000,000
"""
if isinstance(v, numbers.Number):
return "{:,}".format(v)
return v | 202b3b5cabdbb347b7491583c03badddd879fc7c | 679,187 |
import glob
def createPlotString(postAnalyzerPath, description):
""" Create the plotFile readable by the PostPlot*.py program.
Args:
postAnalyzerPath: Path to the output from PostAnalyzer
description: description of the results (for instance canonical or submatrix)
... | b635d273150eb3fa3d14d53cde2ea8ac34f02f08 | 679,188 |
from typing import Any
from typing import Callable
import torch
from typing import Mapping
from typing import Iterable
def traverse_input_data(
data: Any, action_fn: Callable[..., Any], aggregate_fn: Callable[..., Any]
) -> Any:
"""
Traverses any type of nested input data. On a tensor, returns the action ... | 7cb62a6bf0968a2e9c7b6868ffd468720f7f563b | 679,189 |
def getObjectName(objects):
"""Create a string representing the objects name.
objects - list of one or more DejaVu geom. objects"""
name = ""
for object in objects:
try:
objectName = object.fullName
if objectName.split("|")[-1] != 'root':
if objectName.fin... | 356c8ea5f1982cd6f9a6002e58b2c063da3c9077 | 679,190 |
def merge_dict(dic_result, dic, path=None, update=False):
""" Method merges dic into dic_result
Args:
dic_result: the dict will be returned.
dic ('dict'): the dict used to merge with dict_result.
path (`list`): internal variable for keeping track of stack.
Examples:
>>> mer... | b0c96cf03e98a53a6dc52d1e6830a48507deb645 | 679,191 |
import os
def has_bin_in_path(bin_path):
"""Determine if the binary path is part of the system paths."""
return bin_path in os.environ['PATH'].split(':') | 26388e9d4935aa8415c1c9d3358ea8971abf0cb5 | 679,192 |
def numberOfDaysInYear(dt):
"""Calculate number of day of the year of the given datetime."""
if dt.isLeapYear():
return 366
return 365 | 7146192b1f3ac67224818ac73201eef70ba2f531 | 679,193 |
import math
def vector_normalize(vect=()):
""" Generates a unit vector from the input.
:param vect: input vector
:type vect: tuple
:return: unit vector
:rtype: list
"""
if not vect:
raise ValueError("Input argument is empty.")
sq_sum = math.pow(vect[0], 2) + math.pow(vect[1],... | 35ad0aec6bc6e5c2856ab0d93d32120435a9767f | 679,194 |
def is_integer(n):
"""Testa se uma variável é um número inteiro"""
try:
float(n)
except ValueError:
return False
else:
return float(n).is_integer() | 6f16fb4d0490a2f132b79dc874daa30e1f20ed17 | 679,195 |
import os
def split_multiext(filename, max=2):
"""Wrapper around os.path.splitext to remove potentially multiple extensions."""
all_ext = ''
n = 0
while (n < max):
n += 1
(filename,ext) = os.path.splitext(filename)
if (ext):
all_ext = ext + all_ext
else:
... | 1956552c92cd725f0e5ce2238f3ebbb07a7f9d1b | 679,196 |
from typing import List
def remove_nulls(obj):
"""Recursive function to remove nulls in a dict."""
if isinstance(obj, List):
return [remove_nulls(list_item) for list_item in obj]
if not isinstance(obj, dict):
return obj
return {k: remove_nulls(v) for k, v in obj.items() if v is not Non... | f052b45a65fc39095959d37ad17fc1180dac792d | 679,198 |
def are_disjoint(sa, sb):
"""
:param sa: set 1
:param sb: set 2
:return: True if two sets are disjoint, otherwise False
"""
return True if sa & sb == set() else False | 4a410a3246766781ead5ca007f3f31bc15d72e4b | 679,199 |
def create_coordinate_matrix(sp, xn, yn, lons, lats):
"""
Creates xn times yn matrix of GNSS points.
:param sp: Starting GNSS point.
:param xn: Number of rectangles (columns).
:param yn: Number of rectangles (rows).
:param lons: Longitude step.
:param lats: Latitude step.
:return: Matrix... | c0c8a4475c24f19db4db743be11488af7295c991 | 679,201 |
import os
import errno
def check_log_files(PSAD_LOG_DIR='/var/log/psad'):
"""Check for required logfiles in log directory
Check for
- /var/log/psad/top_attackers
- /var/log/psad/top_sigs
- /var/log/psad/top_ports
It will exist, if one of the logfiles does not exist.
Parameters:
PSAD... | ca0c199430eb8f35f6299d056eb9f012c68796e4 | 679,203 |
def containsDuplicate(nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) == 0 or len(nums) == 1:
return False
d = {}
for i in nums:
if i in d:
return True
d[i] = 0
return False | 2486865abe7888af71a09bf8605284188c5b01c0 | 679,204 |
def sanitize_identifier_for_cpp(identifier: str) -> str:
"""
Convert the provided identifier to a valid C++ identifier
:param identifier: the name which needs to to sanitized
:return: str: sanitized identifier
"""
if not identifier:
return ''
sanitized_identifier = list(identifi... | cb7bbd26efd9a20a6f230bb2979a2701b089ac79 | 679,205 |
def readfile(filename, current_dir_path):
"""Return the contents of a file as a string given a Path object to it.
Parameters
----------
filename : str
Name of the file to read.
current_dir_path : Path
pathlib.Path object for where the file is found on the system.
"""
file_pat... | 7e1709df79a0dc47830fe7a99ab0082a722ca3fb | 679,206 |
def find_best_match(path, prefixes):
"""Find the Ingredient that shares the longest prefix with path."""
path_parts = path.split('.')
for p in prefixes:
if len(p) <= len(path_parts) and p == path_parts[:len(p)]:
return '.'.join(p), '.'.join(path_parts[len(p):])
return '', path | e90c8d19eb3fcf97f88a2ed5552973e0b70b4a44 | 679,207 |
import time
def wait_for_influxdb(db_client):
"""Function to wait for the influxdb service to be available."""
try:
db_client.ping()
print("connected to db")
return None
except ConnectionError:
print("not yet")
time.sleep(1)
wait_for_influxdb(db_client) | 9c67c0421fc6542072ff561b111f053963856b84 | 679,208 |
from pathlib import Path
def base_dir():
"""Path to the test dir"""
return Path(__file__).parent.absolute() | 23ff8d338cdb331941cfb16283774cb254666035 | 679,209 |
def merge_configs(*configs):
"""Merge configuration dictionnaries following the given hierarchy
Suppose function is called as merge_configs(A, B, C). Then any pair (key, value) in C would
overwrite any previous value from A or B. Same apply for B over A.
If for some pair (key, value), the value is a d... | 7176508c24ef5e73f444fe05bee7219b522307dc | 679,210 |
def wc1(file_):
"""Takes an absolute file path/name, calculates the number of
lines/words/chars, and returns a string of these numbers + file, e.g.:
3 12 60 /tmp/somefile
(both tabs and spaces are allowed as separator)"""
with open(file_) as f:
content = f.read()
num_lines =... | c812b14d6eb786c396901740d6095c05cb478447 | 679,211 |
import torch
def compute_iou_loss(pred_reg, target_reg, cls_weights, thre, weights):
"""compute iou loss
Args:
pred_reg ([B,N,7] Tensor): normal boxes: x, y, z, w, l, h, r
target_reg ([B,N,7] Tensor): anchors
"""
cls_weights = torch.max(torch.sigmoid(cls_weights),
... | c6f03d284cd011b3d7f1a7fff15cd0f2faee8ff8 | 679,212 |
def parseOutputPattern(outpat):
"""Parses an output pattern"""
r, g, b = outpat.strip().lower().split(',')
return (r, g, b) | 95a20e3823268a0b2b021b54430fa9ce9541d358 | 679,213 |
def number_beds_avail(totalHospitalBeds, severeImpactCases):
""" calculating the number of beds available as integers and not floats"""
avail_beds = int((0.35 * totalHospitalBeds) - severeImpactCases)
return avail_beds | 64e3c29931c6e118992d4f18c2db0de6aec345db | 679,214 |
def rjust(s, width, *args):
"""rjust(s, width[, fillchar]) -> string
Return a right-justified version of s, in a field of the
specified width, padded with spaces as needed. The string is
never truncated. If specified the fillchar is used instead of spaces.
"""
return s.rjust(width, *args) | e43231268288c3488863729cf388e5573c7138d4 | 679,215 |
def process_exception_usa(country_data, feature_list):
"""Process exeptions for the usa. The category of 'Religion' only has a link to
another website. The text should not be shown.
Parameters:
country_data (pd.DataFrame): Data from the wikipedia infobox
feature_list (pd.DataFrame): Feat... | d4ac8876f49dbb70b637ed811fc7312b6aea77c8 | 679,216 |
def read_var_length(fp):
""" take a file pointer that will presumably read characters from the
pointed-to file, and return a numeric value. """
# set the variable to which we will add:
output = 0
# read the first byte
inbyte = ord(fp.read(1))
# its real value is really only the lowest 7 b... | b602e1cf8f37bf41304cd2874e11f4d04788b368 | 679,217 |
def fields(d, names, pred=lambda x: True,
key_transform=lambda x: x, value_transform=lambda x: x):
"""Returns the entries in this dictionary with keys appearing in names.
:type d: dict
:type names: [a]
:param pred: a filter that is applied to the values of the dictionary.
:type pred: (a ... | 19c39316bb39cdb72e45bb7c2e79d9cacbaffe3c | 679,218 |
def HarmonicPairConstraints(a,b,value,sd):
"""
Returns properly formated string for declaring harmonic distance constraints
between CA carbons of resiedues a and b, at distance "value", and "sd" standard deviation.
"""
st = "AtomPair CA %i CA %i HARMONIC %3.1f %3.1f\n" %(a,b,value,sd)
return st | 9cb284f171ba9f0f4b30bb02302d4b66ee4e13e2 | 679,219 |
import pickle
def saveAndLoadModel (mode, PHI=None, THETA=None, modelName='Q1/models/NBmodel.pickle'):
"""
0 for saving the model
1 for loading the model
"""
if (mode == 0):
model = (PHI, THETA)
with open(modelName, 'wb') as handle:
pickle.dump(model, handle, protocol=... | d891b7932398c483325b0974a63cec6ca6a84841 | 679,220 |
def grab_data(h5file, path, col, matching=None):
"""Grabs data in a path matching parameters
Parameters
----------
h5file : PyTables HDF5 File handle
path : str
the path to the appropriate table
col : str
the target column name
matching : tuple, optional
a tuple ... | 3600ff5d6bf9613b8ffd521723e294ab843e7cbc | 679,221 |
def out_deriv(all_deriv, dfdx, df0dx2):
""" Auxiliary function. """
aux = dfdx.shape[0]
if df0dx2 is None:
return all_deriv[:, :aux].T, all_deriv[:, aux].reshape(-1, 1), None
else:
return all_deriv[:, :aux].T, all_deriv[:, aux].reshape(-1, 1), all_deriv[:, aux+1].reshape(-1, 1) | 5fb85d7a0e4fb5338c072ec0d83955a1f6c91d66 | 679,223 |
def parse_structure(astr, level):
"""
The returned line number is from the beginning of the string, starting
at zero. Returns an empty list if no loops found.
"""
if level == 0:
loopbeg = "/**begin repeat"
loopend = "/**end repeat**/"
else:
loopbeg = "/**begin repeat%d" ... | bb030addeb659a20bf5002ecdd64fd2973278b9a | 679,224 |
def get_min(data_frame, field):
"""Calculates the minimum value of a given field in a given DataFrame.
Args:
data_frame (DataFrame): the Pandas DataFrame to analyze
field (string): the field to calculate the values of
Returns:
Series: the minimum value of the field
"""
retu... | 3f36fa254c491e8f4756b1f0c9a6bfb59bea9fbc | 679,225 |
import torch
def kinetic_energy_reg_func(x: torch.Tensor,
t: torch.Tensor,
dx: torch.Tensor,
unused_context) -> torch.Tensor:
"""
Quadratic cost / kinetic energy regularization: https://arxiv.org/pdf/2002.02798.pdf
:param... | 7c90e604e6e0a9a17f14738fe180914faf7e623f | 679,226 |
def is_Replicated(distribution):
""" Check if distribution is of type Replicated
Parameters
----------
distribution : str, list, tuple
Specified distribution of data among processes.
Default value 'b' : Block
Supported types:
'b' : Block
'r' : Replicated
... | 16ecaa2d809746867cb6fae28351ca28591857da | 679,227 |
import re
def first_clean_up(lines):
"""
A function to remove line delimiters, comments, tabs, etc. from the
.sas dictionary file.
Parameters
----------
lines : list of strings; the raw file
"""
#Remove all tabs from the string
for i in range(0, len(lines)):
lines[i]... | 5d54cb69db6164bb8eb994d473cfa623e8bf337e | 679,228 |
def verify_request_target(replay_json, request_target):
"""
Verify that the 'url' element of the first transaction contains the request target.
"""
try:
url = replay_json['sessions'][0]['transactions'][0]['client-request']['url']
except KeyError:
print("The replay file did not have a... | 5be4e46d0a0d4ef744b35a2a1f1765c6950cd50d | 679,229 |
import os
def get_class_names(base_path):
"""
Fetches class names from subdirectories in the directory given as the
base path.
Arguments:
base_path (str): path to the directory containing images or class
subdirectories.
Returns:
class_list (list): list of classes identif... | 332665bb79b6a04c5a8b63f605546d3fed233fd7 | 679,230 |
from typing import List
def gray_max(colors: List[int]) -> float:
"""
Convert to grayscale: get brightest value from channels.
:param colors: [R, G, B] values
:return: one grayscale color
"""
return max(colors) | afba2f9e40960c1e5abffba96c887f3eff9ca69e | 679,231 |
import wave
import struct
import numpy
def read_wav(input_file_name):
"""
:param input_file_name:
:return:
"""
wfh = wave.open(input_file_name, "r")
(nchannels, sampwidth, framerate, nframes, comptype, compname) = wfh.getparams()
raw = wfh.readframes(nframes * nchannels)
out = struct.u... | 00df866d6d548802de40ec9d7e4c4aa7df483785 | 679,232 |
def find_atoms(atom_neighbourhood, structure):
"""
Return list of atom occurrences in structure from an atom neighbourhood
Input:
atom_neighbourhood: GroupDefiner object
Output:
atoms: list of Atom objects
"""
locations = structure.find_substructures(atom_neighbourhood.structure)
... | 6ec40b6b16d14a11879ec4d8f62ff281cc2dc40d | 679,234 |
import argparse
def parse_arguments():
"""
Parses the command line arguments.
"""
parser = argparse.ArgumentParser(description="Compiles the ExtraCurrencies mod")
parser.add_argument("games", choices=["ets2", "ats"], nargs="+",
help="the game(s) to target")
parser.add_a... | 96da57bd099c1f4357b4d520a75eedadc78a1326 | 679,235 |
import codecs
def check_output(output_from):
"""A function which takes a string with B source, compiles and executes it
and then compares the output with an expected value."""
def _check_output(source, expected):
output = output_from(source)
assert output == codecs.encode(str(expected), 'u... | 90efcdb96093c445c1ed60430775193774906f1c | 679,236 |
import pickle
def load(ensemble):
"""
Load a previously pickled ensemble.
"""
return pickle.loads(ensemble) | 61af703ee0dc026299359bcbf67aa178109c6640 | 679,237 |
def empty_table(unique_database, request):
"""Create an empty table within the test database before executing test.
The table will have the same name as the test_function itself. Setup and teardown
of the database is handled by the unique_database fixture.
Args:
unique_database: pytest fixture defined in ... | 5bbb079be2e2c1db2e55843937ac129e7317b3e3 | 679,238 |
def append_ordinal(number):
"""Add an ordinal string to an integer.
:param number: The number to be converted to an ordinal.
:type number: int
:rtype: str
"""
suffixes = dict()
for i, v in enumerate(['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th']):
suffixes[str(i)] = ... | 0c985a3fb08a9eb7cde03aa6eb70baefe4c55483 | 679,239 |
def fix_line_breaks(text):
""" Convert Win line breaks to Unix
"""
return text.replace("\r\n", "\n") | c4c698fce80d7c3820f689a163d0df19ea682573 | 679,240 |
import configparser
def _nova_cfg():
"""
Parse nova config and return it in form of ConfigParser instance
:return: Parsed nova config
:rtype: configparser.ConfigParser
"""
nova_cfg = configparser.ConfigParser()
nova_cfg.read('/etc/nova/nova.conf')
return nova_cfg | 8b315ad893e79ecc85eb607f1bbb7e0cdb238d99 | 679,241 |
def make_jsondict(new_GCFs, old_GCFs):
"""
creates a dictionary containing the BiG-SCAPE families with the full organism names
----------
new_GCFs
dictionary, {bigscape family ID number: bigscape family ID numbers}
old_GCFs
dictionary, {full organism name: full organism names}
re... | f86ea6f1230d8d295f590111fcfb780e2aaf6e75 | 679,242 |
import sys
def get_task():
"""
Get task from user
"""
task = sys.argv[1].lower()
allowed_tasks = [
'new_config',
'validate',
'simulate',
'viewslice',
]
assert (task in allowed_tasks), \
"Error in main.get_task: input task not recognised."
retu... | 703a6bf259270ec7fe21e637ee07b9f348234eff | 679,243 |
import os
def storage_file_name(directory, resource_id):
"""Returns the path to the JSON file that contains a stored resource
structure
"""
return os.path.normpath(
os.path.join(directory, resource_id.replace("/", "_"))) | bda1b537fe2afdcb3ee398c9ce02e2f8ab8dc9c3 | 679,244 |
import json
import collections
def get_captions(json_file_path, filenames):
""" Get captions for given filenames.
Args:
json_file_path (string): Path to the json file containing annotations/captions.
filenames (list): List with all the filenames.
"""
with open(json_file_path, "r") as ... | 29ad7c3b7980f6b2206c58eb1d7f4bd6369812d1 | 679,245 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.