content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def non_return_dependencies():
"""
For dependencies only need to be executed but needn't to return any values, you could declear it in API endpoint declaration function with `dependencies=` keyword argument
For example:
You need to check API key on every API endpoint, you could write a `check_api_key` ... | 18c38267638d2a8e8441bc702b7ee716fcd034a2 | 653,254 |
def signed_int_str(input_int: int):
"""
Converts an integer into a string that includes the integer's sign, + or -
:param int input_int: the input integer to convert to a signed integer string
:return str signed_int_str: the signed integer string
"""
if input_int >= 0:
return '+' + str(... | b6ea5e9ccdb8a30273d3bb790a4c9bc663daedcc | 653,256 |
def handle_object_placement(handle_to_self_field, potential_object, objectType, list=False):
"""
Helper function to checks to see if we can safely set a given field (handle_to_self_field)
to a potential_object by checking whether or not it is an instance of objectType.
:param handle_to_self_... | a509460a770df829ef2f3b962febae4fcbd2aa25 | 653,257 |
def episode_choices():
"""Episode choices to use when testing game create form."""
return [(e, e) for e in range(0, 2)] | ef8539d296e4c2ce4fdaea82a0c510d39e929746 | 653,259 |
def kern(request):
"""Define kernel transformers for tests."""
return request.param | f6da4e16b18fb25538c8bb32d80b75891ebb031a | 653,260 |
def generate_bytes():
"""Generate bytes, randomly."""
# Not sure what do generate for bytes. This is just zero-filled
return bytes(2) | 86a671bcc9188e6f5594222604c50ac0fe084fb0 | 653,261 |
def extract_ratelimit(headers_dict):
"""Returns rate limit dict, extracted from full headers."""
return {
"used": int(headers_dict.get("X-RateLimit-Used", 0)),
"expire": float(headers_dict.get("X-RateLimit-Expire", 0)),
"limit": int(headers_dict.get("X-RateLimit-Limit", 0)),
"rem... | e299d8c56b6b83ff15af096ec8c5d467f82f5ddc | 653,262 |
import argparse
def get_args() -> argparse.Namespace:
"""Get args from command line."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--config",
type=str,
help="path to configuration file for student teacher experiment",
default="config.yaml",
)
parser.... | 1766f71df796add53a61606f73ae596b8296c733 | 653,264 |
def parse_movie_metadata(movie):
"""
Parses movies from JSON into proper format for addition to db.
Sample output: "("citizenkane", "drama mystery orsonwelles
josephcotten dorothycomingore agnesmoorehead 1941")
"""
# Massage title data
# Format is lowercase title with no spa... | 0dc414cfa4c0c2c4625e504afa9d0ff6aa5c72b1 | 653,265 |
import math
def distance(node1,node2):
"""
Calculates distance between nodes in pixels
Parameters
----------
node1 : Treelib Node
first node
node2 : Treelib Node
second node
Returns
-------
distance : float
distance between nodes in pixels
... | c0d94ba2fbc8c36e075eeb4589b1d4e6b8f17813 | 653,266 |
import json
def embed_terms(args, use_cache=True, path_to_json='ebd_cache.json'):
"""
Embeds class strings into word representations.
:param args
:param path_to_json: (str) path to json file containing word embeddings
:return: dict {newsgroup class (int id) : embedded vector (nparray of float)}
... | bbc04c796db2f4ea0061d57d0dcf9672af0e03f9 | 653,267 |
import os
def get_datasets(datasets_dir):
"""
Returns the sorted [] of (name, path) tuples of the dataset files found in
the given directory.
"""
res = []
for item in os.listdir(datasets_dir):
path = os.path.join(datasets_dir, item)
item = item.split('.')
if len(item) == 2 and os.path.isfile(path) and i... | 8c31c1d6280fd0e65ddc1cbdce0c2d06c41792e0 | 653,268 |
def _ref(ref: str):
"""
```
{'ref': ref}
```
"""
return {'ref': ref} | 14b262dfdc47902f5ad8aebb6db48462d4db3cd0 | 653,269 |
import inspect
def get_ctor_arguments(clazz):
"""
getfullargspec does not handle inheritance correctly.
Taken from https://stackoverflow.com/questions/36994217/retrieving-arguments-from-a-class-with-multiple-inheritance
"""
args = ['self']
for C in clazz.__mro__:
if '__init__' in C.__d... | b6d54c69ffffa487a6a0eb212b79386524de74ae | 653,270 |
import functools
def command(func):
"""
Decorator to declare which methods are accessible as commands, commands
always return 1 or 0, where 0 should indicate success.
:param func: function to make public
"""
func.publicly_accessible = True
@functools.wraps(func)
def wrapped(*a, **kw)... | 74244cc4270b66fb3f35a26748a26e288c5a3950 | 653,271 |
def format_weather_data(data_str):
""" Take weather data in weewx format and transform to param/value dict"""
## Data sample direct from weewx (shortened)
# "altimeter: 72.317316, ... maxSolarRad: None, ... windGustDir: 359.99994, windSpeed: 5.1645e-09"
# Replace "None" values with 0's
data_str =... | 2857bae006467dc74724397507172e951f175107 | 653,274 |
def primes(imax):
"""
Returns prime numbers up to imax.
Parameters
----------
imax: int
The number of primes to return. This should be less or equal to 10000.
Returns
-------
result: list
The list of prime numbers.
"""
p = list(range(10000))
result = []
... | 84b6d0ca986923a30e877d953e2fdec3452028ec | 653,276 |
def result_file_name(d):
""" build out the split portion of the directory structure.
:param dict d: A dictionary holding BIDS terms for path-building
"""
return "_".join([
'-'.join(['sub', d['sub'], ]),
'-'.join(['comp', d['comp'], ]),
'-'.join(['mask', d['mask'], ]),
'... | 58bd17a18a15b6ec920ce82957af11240fd77003 | 653,277 |
from typing import Union
def to_float(num:Union[float,int]) -> float:
"""to_float(float) -> float
to_float(int) -> float(int)
helper function to allow passing float or int.
"""
return float(num) if isinstance(num, int) else num | 65d94aeead387159462db661798355e86306bf19 | 653,278 |
def _pairwise(iterable):
""" Returns items from an iterable two at a time, ala
[0, 1, 2, 3, ...] -> [(0, 1), (2, 3), ...] """
iterable = iter(iterable)
return zip(iterable, iterable) | f4e27bcc1719cab16abcd048dd0ad3ee46ea2f3b | 653,279 |
import os
def get_star_index_files(path:str, with_sjdb_files:bool=False):
""" Find the file names necessary for a STAR index rooted at path.
Parameters
----------
path: string
the path to the directory containing the STAR index
with_sjdb_files: bool
whethe... | 9d1bcd6574227fb5219b9fa57e35b3a8484c826e | 653,280 |
import time
def timer(func):
"""
Created 20180719 by Magnus Wenzer
"""
def f(*args, **kwargs):
from_time = time.time()
rv = func(*args, **kwargs)
to_time = time.time()
print('Stop: "{.__name__}". Time for running method was {}'.format(func, to_time-from_... | edcff61b4dae97e50ff9b28b87461c7fa1c2c1e9 | 653,281 |
def entitydata_form_add_field(form_data_dict, field_name, dup_index, value):
"""
Add field value to form data; if duplicate then reformat appropriately.
Updates and returns supplied form data dictionary.
"""
if field_name in form_data_dict:
suffix = "__%d"%dup_index
else:
suffix... | 4fdf1f0c118f2b8d0230a7ddb73fc9a94558a4ea | 653,282 |
import numpy
def rotate(deltav,vsini,epsilon=0.6) :
""" rotation kernel from IDL Users library routine
Args :
deltav (float) : velocity spacing of pixels
vsini (float ) : v sin i for profile
epsilon (float ) : parameter for rotation kernel (default=0.6)
Returns :
norm... | 0ef936bf034016637e04db23485bfca28172b5a9 | 653,283 |
def generate_bio_entity_tags(mentions, sentence_length):
"""
Generate BIO/IOB2 tags for entity detection task.
"""
bio_tags = ['O'] * sentence_length
for mention in mentions:
start = mention['start']
end = mention['end']
bio_tags[start] = 'B-E'
for i in range(start + ... | 22c2500d8ffc9d22b751486c076508640522da64 | 653,284 |
import argparse
def init_parser():
"""Prepares the command line parser"""
parser = argparse.ArgumentParser()
parser.add_argument('from_change', help='The oldest changelist to include')
parser.add_argument('to_change', help='The newest changelist to include')
parser.add_argument('--client', help='T... | 6ac06d178dd690481fa33bf7cffc4127d7b3e382 | 653,285 |
def get_val_in_roi(roi, feature):
"""roiに対して中心の値を返す. depthとrotationを求めたい.
Parametersa
----------
roi: list
Returns
-------
-------
"""
cx = int((roi[0] + roi[2]) / 2)
cy = int((roi[1] + roi[3]) / 2)
return feature[:, cy, cx] | 890c42648acaf89c451c0e8f7b0c633d820ddcc3 | 653,286 |
import collections
import re
def rnnlm_gen_data(*files):
"""Generates data and vocab from files.
This function is used solely for testing.
"""
all_words = collections.Counter()
all_word_lists = []
for f in files:
with open(f, mode="r") as fp:
text = fp.read()
wor... | 551cae175fe0155963aca69e4d0ce3c8070e63d2 | 653,287 |
def parseTime(t):
"""
Parses a time value, recognising suffices like 'm' for minutes,
's' for seconds, 'h' for hours, 'd' for days, 'w' for weeks,
'M' for months.
>>> endings = {'s':1, 'm':60, 'h':60*60, 'd':60*60*24, 'w':60*60*24*7, 'M':60*60*24*30}
>>> not False in [endings[i]*3 == parseT... | 219511b772aebb09a0e0ef3cfc5d4fbfc5d18cb5 | 653,288 |
def type_strict_match_or_list(type_tuple_list):
""" Return a function which match strictly any of the tuple within
type_tuple_list """
def match_function(*arg_tuple, **kw):
for constraint_tuple in type_tuple_list:
if constraint_tuple == arg_tuple:
return True
... | dc36efa2dac508ed75bbb32ceeb103063bdab6fb | 653,291 |
def connected_two(position: int, mask: int) -> bool:
"""
Return True, when the player has connected 2
Arguments:
position: bit representation of the board with players pieces
mask: bit representation of board with all pieces
Return:
bool: = value is true when player has 2 connect... | 26175ea5bb77b88b67b953194fc80b9f449f7889 | 653,292 |
def LikelihoodCollector (fitted_model):
"""only return the likelihood of the fitted model"""
return fitted_model.loglikelihood | 1150d3ebb4a72c28722bb6bf61385f2e7fa69b52 | 653,293 |
def binary_search(array, target):
"""
array is assumed to be sorted in increasing values
Find the location i in the array such that array[i-1] <= target < array[i-1]
"""
lower = 0
upper = len(array)
while lower < upper: # use < instead of <=
x = lower + (upper - lower) // 2
... | 82a60dee9f4ab337860184b9409fc0ac768501d6 | 653,294 |
def get_nested_dict_value(input_dict, key):
"""Uses '.' or '->'-splittable string as key to access nested dict."""
if key in input_dict:
val = input_dict[key]
else:
key = key.replace("->", ".") # make sure no -> left
split_key = key.split('.', 1)
if len(split_key) == 2:
... | 0205c8999a488862c5825742b1d277dde98e6f73 | 653,297 |
def f(N1, N2, Vg1, Vg2, Ec1, Ec2, Cg1, Cg2, Ecm, e):
"""
Parameters
----------
N1 : Int
Number of electrons on dot 1.
N2 : Int
Number of electrons on dot 1.
Vg1 : Float
Voltage on gate 1.
Vg2 : Float
Voltage on gate 2.
Ec1 : Float
Charging energy ... | 9143a13db0beb6c258060734bb3bbefbcabc0305 | 653,298 |
def read_val_names(val_names_path):
"""
Read the filenames of validation images and labels into self.val_list
"""
val_names = []
f = open(val_names_path, 'r')
line = None
while 1:
line = f.readline().replace('\n', '')
if line is None or len(line) == 0:
break
... | 47ee20f7c947cf1f80ae7ce207c448274783fbea | 653,299 |
def unshard(x, padding=0):
"""Collect the sharded tensor to the shape before sharding."""
y = x.reshape([x.shape[0] * x.shape[1]] + list(x.shape[2:]))
if padding > 0:
y = y[:-padding]
return y | 3c348c703ca5076e86509f292351da2051fb88ee | 653,300 |
def findChIndex(c, str_in):
"""
Version 2: Using built-in methods.
Write a python function that returns the first index of a character 'c' in string
'str_in'.
If the character was not found it returns -1.
Ex:
findChIndex('a', 'dddabbb') will return 3
findChIndex('f', ... | 42d15a998721aa4b6420014088eed896ba5c971f | 653,302 |
import os
def make_folder(folder_path):
"""Description
Create a default folders
"""
return os.makedirs(folder_path, mode=0o700, exist_ok=True) | 72892f5291db50781f6abcdec12b1c185281044f | 653,303 |
import numpy
def loadImage(movie, frame, offset, gain, transform = None):
"""
Load a single frame, apply sCMOS correction and remove
values that are less than 1.0.
"""
image = movie.loadAFrame(frame)
image = (image - offset)*gain
# Apply transform if requested.
if transform is not Non... | 2889e5dcc2176d3ffc4c30c109b8ffa0d2819110 | 653,304 |
import copy
def plugin_init(config, ingest_ref, callback):
""" Initialise the plugin
Args:
config: JSON configuration document for the Filter plugin configuration category
ingest_ref: filter ingest reference
callback: filter callback
Returns:
data: JSON object t... | 9798d8e755fa57143eb87f52c04be70e6c384983 | 653,305 |
import os
def is_valid_seeds_folder(path: str):
"""
Determines if the given directory is a valid seeds folder
:param path: The path to the seeds
:return: True if valid, False if no
"""
if not os.path.exists(path) or not os.path.isdir(path):
raise NotADirectoryError("{0} must be a direc... | 62fd41f6928a33c9e6b7f8084386c14be15fe005 | 653,307 |
def is_polygon_ccw(vertices):
"""
Check if a polygon's vertices are in counter-clockwise order.
Uses the Shoelace Formula:
https://bit.ly/2t78ytv
https://en.wikipedia.org/wiki/Shoelace_formula
"""
winding_number = 0
for i in range(vertices.shape[0]):
x2_m_x1 = vertices[(i + 1) %... | 000a463ec673d02170e5a86bd35c0961025b0748 | 653,308 |
def using_apt_get_on_parrotsec(line):
"""
Checks if your image uses parrotsec and uses apt-get.
This is discouraged - you should use apt instead.
"""
return "apt-get" in line | 9cf678423f1a83673fa19ea10bb1592278297c9d | 653,309 |
import argparse
import textwrap
def parse_args():
"""
command line options
:return:
"""
parser = argparse.ArgumentParser(prog="merge_mpa_tables.py",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description=textwr... | c8787b15ae112acc8de95ee6cfc8762c24ccd693 | 653,310 |
from typing import Dict
def apply_substitutions(command: str, substitutions: Dict[str, str]) -> str:
"""
Given a command string (with templates) and a substitution mapping, produce a
concrete command string that can be run in a shell.
Parameters
----------
command
A string to be execu... | 4a803a655ae8148afbe60fbc537eab7d1ee09881 | 653,311 |
def unpack_maybe(sample):
"""
Loads the supplied sample from disk (or the network) if the audio isn't loaded in to memory already.
"""
if hasattr(sample, 'unpack'):
realized_sample = sample.unpack()
else:
realized_sample = sample
return realized_sample | 9c6590640fbb01d6c8c21d0937ee228d98b4c15c | 653,312 |
def calc_NAO_station(mslp_anomalies):
"""
DESCRIPTION
===========
Calculates the Station based NAO index, which is defined as the
normalized difference in sea level pressure between Reykjavik and
Lisbon.
Input:
mslp_anaomalies: xarray.dataset containing mean se... | 3fc4a69464fb4efa6fbec390a81f10848e029721 | 653,314 |
import sys
import base64
def compat_urlsafe_b64encode(v):
"""A urlsafe ba64encode which is compatible with Python 2 and 3.
Args:
v: A string to encode.
Returns:
The encoded string.
"""
if sys.version_info[0] >= 3: # pragma: NO COVER
return base64.urlsafe_b64encode(v.encode('U... | 95770d7d2e9255c12993dc6b6b0725032d101a17 | 653,316 |
def get_nmredata(simple_ids, shifts):
"""
combines atom ids from MOL block and chemical shifts to produce an nmredata-formatted list of chemical shifts
"""
return '\n'.join(['%s, %s, %s \\' % x for x in zip(simple_ids, shifts, simple_ids)]) | 9b1fcd88c58d6670c34e9fe240c39b59c32c4738 | 653,317 |
import math
def pi(var_lambda: float, gamma=1.4) -> float:
""""
Returns gas dynamic function pi
Parameters
----------
var_lambda: float
superficial velocity of flow
gamma: float
isentropic exponent (default 1.4)
Returns
-------
pi: float
values of GD funct... | 260a631db7e6c2cb6adef233586ac6071665b209 | 653,319 |
import torch
def iou_loss(preds, targets):
"""
Args:
preds: [n,4] ltrb
targets: [n,4]
"""
lt = torch.min(preds[:, :2], targets[:, :2])
rb = torch.min(preds[:, 2:], targets[:, 2:])
wh = (rb + lt).clamp(min=0)
overlap = wh[:, 0] * wh[:, 1] # [n]
area1 = (preds[:, 2] + preds[:, 0... | e16409a39132dad29b5013431f9040b094056cec | 653,320 |
def get_versions(existings):
"""
Given gathered path, get all existing versions.
"""
versions = set()
for k, v in existings.items():
versions = versions.union(v)
return versions | 5f8a1b58c7812a0c2db33e5663d0e82a6dc22011 | 653,321 |
import operator
def format_as_results(sim_vec, topic_uid, doc_collection,
run_name='default_run'):
"""Formats a similarity vector as the TREC output.
The format of the system results contains 5 tab-separated
columns:
1. qid
2. iter
3. docno
4. rank
5. sim
6.... | a4c6e042c183b3aaf6d95847c6f5b6747685de41 | 653,322 |
import torch
def _fixed_odeint(f, x, t_span, solver):
"""Solves IVPs with same `t_span`, using fixed-step methods"""
t, T, dt = t_span[0], t_span[-1], t_span[1] - t_span[0]
sol = [x]
steps = 1
while steps <= len(t_span) - 1:
_, x, _ = solver.step(f, x, t, dt)
sol.append(x)
t = t + dt
if steps < len(t_spa... | 5fbcd55e752e41bf0595e3027b58a38f677f0d6c | 653,323 |
def entry_boundaries(entry):
"""
Get the start/end of an entry and order (start < end)
"""
start = entry.start
end = entry.stop
return start, end | d3ce521c071c6882d336e93ae26ed2a5f901de41 | 653,325 |
def _get_type(e):
"""
Returns the type associated with handling XML objects from this etree
interface.
"""
try:
return e.__class__
except AttributeError:
return type(e) | f68619ca648306eb7588c69624d381bc637dc029 | 653,326 |
def _mixture_energy(ci, hi, Jij):
""" helper function that calculates the "energy" associated with the
mixture `ci`, given commonness vector `hi` and correlation matrix `Jij` """
energy = 0
Ns = ci.size
for i in range(Ns):
if ci[i] > 0:
energy -= hi[i] + Jij[i, i]
fo... | 9b91906fc353730496ce542d8aa0c26bda2259e5 | 653,327 |
import os
def mem(size="rss"):
"""Generalization; memory sizes: rss, rsz, vsz."""
return int(os.popen('ps -p %d -o %s | tail -1' % (os.getpid(), size)).read()) | c06bf18dab95b4b193423b3dff47355a6a5774f9 | 653,328 |
import os
def list_images(directory):
"""
Get all the images and labels in directory/label/*.jpg
"""
labels = os.listdir(directory)
# Sort the labels so that training and validation get them in the same order
labels.sort()
files_and_labels = []
for label in labels:
for f in os... | 9fd216077362b9efe6ebe5b0043d08592687ec27 | 653,329 |
def linear_annealing(current_timestep, final_timestep, start_value, final_value):
"""
Linearly anneals a value from an initial value to a final value, given the current percentage.
"""
# Pô <3
percentage = min(1.0, current_timestep / final_timestep if final_timestep != 0 else 0)
current_eps = (f... | de53d88fe0cc0fe6ef30aa986321cf9e56a9c24c | 653,330 |
def remove_subject(subject, metric, dict_exclude_subj):
"""
Check if subject should be removed
:param subject:
:param metric:
:param dict_exclude_subj: dictionary with subjects to exclude from analysis (due to bad data quality, etc.)
:return: Bool
"""
if metric in dict_exclude_subj.keys(... | 5f50d21f2c0f8fcec95c93855f99464d52a77d8c | 653,332 |
import pytz
from datetime import datetime
def unix_time(dt):
""" OS-independent method to get unix time from a datetime object (strftime('%s') does not work on solaris) """
epoch = pytz.utc.localize(datetime.utcfromtimestamp(0))
delta = dt - epoch
return delta.total_seconds() | 0d84015faa2bfab113ec08adbb8b442558a0eee2 | 653,333 |
from typing import Counter
import math
def get_entropy_from_frequencies(dict_all_environments: dict, max_env=66) -> dict:
"""
will calulate a relative Shannon entropy from the frequencies of the chemical environments
:param dict_all_environments: e.g., {'Ga': ['O:6', 'O:6', 'T:4', 'T:4']}
:param max_e... | 2a524d39a7c0132560d45465253cefafa116dd31 | 653,334 |
def flatten_binary_logits(logits, labels, ignore_index=None):
"""Flattens predictions in the batch (binary case) Remove labels equal to
'ignore_index'."""
logits = logits.view(-1)
labels = labels.view(-1)
if ignore_index is None:
return logits, labels
valid = (labels != ignore_index)
... | c09752a5d1d18689f94edd940146125a44b06172 | 653,335 |
import subprocess
import sys
def pip_install(package_name, message):
"""
Install the given package via pip.
@param package_name name of the package to be installed
@type str
@param message message to be shown to the user
@type str
@return flag indicating a successful installation
@rty... | a4f36ce3d2798c83b3d9968f5bdaeaf505d470ce | 653,336 |
def calcCSM(csm, SpecAllMics):
""" Adds a given spectrum to the Cross-Spectral-Matrix (CSM).
Here only the upper triangular matrix of the CSM is calculated. After
averaging over the various ensembles, the whole CSM is created via complex
conjugation transposing. This happens outside
(in :class:`Po... | 95bdc5bc6d0317491b7a0694ac0d1dc4fbf4ea42 | 653,337 |
def two_sum_dict(arr, target):
"""
time: O(n)
space: O(n)
"""
complement = {}
for i, num in enumerate(arr):
if num in complement:
return complement[num], i
complement[target - num] = i
return None | 90f6ed62a83590ebef3d59de9cda492f5167063b | 653,339 |
def fibo_meme(func):
"""Return memoized results from func(n).
Args:
func: A function. Can be wrapped normally or using decorator syntax.
Returns:
memoize: a wrapped function that performs lookups in a dict
"""
mem = {}
def memoize(n):
if n not in mem:
mem[n... | 02a55253dd85626d209ced9705b60753b5897840 | 653,340 |
from typing import Union
def safe_get_dict(data: Union[None, dict], key, default: dict) -> dict:
"""
This method is a safe getter function that returns a dict entry in case that the dict is provided and it contains
the key (where the value itself is a dict). Otherwise it returns the provided default value... | 08bf91ffbb4153bb29a79c1badfda13b11312e90 | 653,341 |
def get_jid(log_name):
"""Strip path and file type from the log name to return the jid as int"""
return int(log_name.split('/')[-1].split('.')[0]) | 078294e445399220e56e42e4cfdfad2fba799a1a | 653,342 |
def fexception(env, db, exception=None):
"""pass or except depending on the `exception`"""
if exception is not None:
raise exception
else:
return None | 4d827d2a30169e89d5a2c577dc22d0458e3006ca | 653,343 |
def get_bracket_depth(idx, left_bracket_indices, right_bracket_indices):
"""
Get the bracket depth of index idx.
Args:
idx (int): the index.
left_bracket_indices (list[int]): the left bracket index list.
right_bracket_indices (list[int]): the right bracket index list.
Returns:
... | 38c3a7440ebad745312e4adf8cacdf32c836bd64 | 653,344 |
def epsilon_to_kappa(r_k, epsilon, delta=0.16):
"""Convert frequency r_k and strain epsilon
to corresponding r_k and kappa as consumed by
functions in `latticegeneration`.
Returns
-------
r_k2 : float
kappa : float
See also
--------
latticegeneration.generate_ks
"""
ret... | ad8e6f65ed3352a6920f57fe0ad4cb86f886d1ee | 653,345 |
def versions_match(versions):
"""Check if the versions are the same"""
base = None
for name in versions:
if base is None:
base = versions[name]
elif base != versions[name]:
return False
return True | 6d02c9170302a18e14dfac393f1b573d491d3545 | 653,346 |
def mk_optional_string(data, jfield):
"""
Returns either the string represented in a json structure, or an empty string if it's not present
:param data: json that may contain the jfield
:param jfield: the name of the field
:return if the field exists then it's returned; otherwise an empty string i... | ecb58a820ff6a1ea1a2a82164a648b63e1f27ac7 | 653,349 |
def set_platform(job, alrb_setup):
"""
Set thePlatform variable and add it to the sub container command.
:param job: job object.
:param alrb_setup: ALRB setup (string).
:return: updated ALRB setup (string).
"""
if job.alrbuserplatform:
alrb_setup += 'export thePlatform=\"%s\";' % j... | acb4e82d880de6bac5c4016a14265f99115f4a4f | 653,351 |
def parse_object(*args):
"""
将查询到的结果转换为需要的结构
:param args:
:return:
"""
results = []
for cond in args:
result = {'OPEN_ID': cond.OPEN_ID,
'OBJECT_ID': cond.OBJECT_ID,
'SUBJECT': cond.SUBJECT,
'IMG_URL': cond.IMG_URL,
... | 2a834ccd0b6a796ac035e01a005f1e4330b46f00 | 653,352 |
import re
import inspect
def get_source(match: re.Match) -> str:
"""Extract source code lines of a matched object and prepare them
to being injected into .ipynb code cell."""
match_object = eval(match.group()[9:-1])
source_lines = inspect.getsourcelines(match_object)[0]
new_lines = [line.rstrip() ... | b6fd59308852658585c3be8783bc890a20d91830 | 653,353 |
def call_behavior_action_input_pin(self, pin_name: str):
"""Find an input pin on the action with the specified name
:param pin_name:
:return: Pin with specified name
"""
pin_set = {x for x in self.inputs if x.name == pin_name}
if len(pin_set) == 0:
raise ValueError(f'Could not find inpu... | e3031c27eef654a209e98fd6fd92cefc61c0e008 | 653,354 |
def trim_chain(chain, nwalkers, nstart, npar):
"""Trim number of usable steps in a chain"""
chain = chain.reshape(-1,nwalkers,npar)
chain = chain[nstart:,:,:]
chain = chain.reshape(-1, npar)
return chain | 7224393f690eb6be47401e7436b5a7af6bbd2247 | 653,355 |
def is_ipv4_address(addr):
"""Return True if addr is a valid IPv4 address, False otherwise."""
if (not isinstance(addr, str)) or (not addr) or addr.isspace():
return False
octets = addr.split('.')
if len(octets) != 4:
return False
for octet in octets:
if not octet.isdigit():
... | 2f7127019bcc069462ef85e5d15e5fb3a44add8b | 653,356 |
def _sorted_data(lb_node_pairs):
"""
Return HTTP request body to be sent to RCv3 load_balancer_pools/nodes API
from list of (lb_id, node_id) tuples. The returned list is sorted to allow
easier testing with predictability.
:param list lb_node_pairs: List of (lb_id, node_id) tuples
:return: List ... | 5ced0c4d7044dde6e90dd7de65926b82e8336916 | 653,357 |
def div_or_none(a,b):
"""Divide a by b. Return result or None on divide by zero."""
if b == 0:
return None
return a/b | 88bf49ac570968e0108356ecad5b6ce9d2f52f4f | 653,358 |
from typing import Optional
def validate_state_of_charge_max(state_of_charge_max: Optional[float]) -> Optional[float]:
"""
Validates the state of charge max of an object.
State of charge max is always optional.
:param state_of_charge_max: The state of charge max of the object.
:return: The valida... | b7d2e4867e18b00595c159ef26233e57482ffa5d | 653,359 |
def get_route_node(current_node, lca_id):
"""
get all node from current node to the LCA node
"""
res_list = []
while not current_node.is_virtual() and not current_node.get_id() == lca_id:
res_list.append(current_node)
current_node = current_node.parent
res_list.append(current_no... | fb004cd822b6bb7d9dbb72c0d26e65bcb0972da8 | 653,360 |
def read_file(path=None) -> str:
"""
Function for reading the single file
:param path: path to the file
:return: data: data from the file
"""
if not path:
raise NameError('Required path to the file')
with open(path, 'r') as f:
data = f.read()
return data | 097268399ed556de8c61c9cb57aae042d279faa0 | 653,361 |
def vip_discount(order):
"""淘宝88vip客户95折"""
return order.total() * .05 if order.customer.is_88vip else 0 | 62d39387e00ee7b1b2c5a2ca52207409c11c7e96 | 653,362 |
def underscore_entities(dialogue_str, global_entities_dict):
"""
Underscore the entities in dialogue.
@param dialogue_str:
@param global_entities_dict:
@return:
entities_in_this_turn: dict: the entities of this turn.
processed_dialogue_str: string with entities underscored if replace=True ... | e53d9d275bbc99ffeebd3bb82899e24e5767dee3 | 653,363 |
def timesheetentry_json(timesheetentry) -> dict:
""" Helper function to convert a TimeSheetEntry object into a json dict with nice date and time formatting """
data = {}
data['id'] = timesheetentry.id
data['project'] = timesheetentry.project.id
data['rse'] = timesheetentry.rse.id
data['date'] = ... | 67ff19f5cb1b2ab5f7e373a3f4f81d088a06b14a | 653,364 |
def get_error(At, Ft):
"""
"""
return Ft - At | d12cb377636e0a39bd481d7391ab7b29dcf27895 | 653,365 |
from typing import Mapping
from typing import Sequence
def apply_to_type(input_, input_type, func):
"""Apply a function on a object of `input_type` or mapping, or sequence of objects of `input_type`.
"""
if isinstance(input_, input_type):
return func(input_)
if isinstance(input_, (str, bytes))... | 1dda2aa64546a9a417061b76828dbc1c42deed8e | 653,367 |
import time
def get_xaxis_days(days=60):
"""
获取 X 坐标,按天。取两个月数据
"""
xaxis_days = []
for i in range(0, days):
xaxis_days.append(time.strftime("%Y%m%d", time.localtime(time.time() - i * 86400)))
xaxis_days.sort()
return xaxis_days | a8dea9e94fe0a45b4bc65133939a30df1ea26718 | 653,368 |
def range_overlap(a, b):
"""
>>> range_overlap(("1", 30, 45), ("1", 45, 55))
True
>>> range_overlap(("1", 30, 45), ("1", 57, 68))
False
>>> range_overlap(("1", 30, 45), ("2", 42, 55))
False
"""
a_chr, a_min, a_max = a
b_chr, b_min, b_max = b
# must be on the same chromosome
... | d44da19754faf683d93eea645edba03b1e1c83b9 | 653,369 |
def scale(value, input_low, input_high, output_low, output_high):
"""Scale a value from one range to another"""
scaled_input = ((float(value) - input_low) / (input_high - input_low))
return ((scaled_input) * (output_high - output_low)) + output_low | cc220e52a4060e2f80adc99fdacf6137e2b0a1ee | 653,370 |
def get_group_usage(group, date, db):
"""
Query the database for group usage on a specific date.
:param group: str
:param date: str
:param db: object
:return usage: int
"""
terms = (group, date + '%',)
db.execute('SELECT * FROM `group_stats` WHERE `group` = ? AND `datetime` LIKE ?',... | 0d1b8c8ecba39aa4e733707c74fe9deade458291 | 653,371 |
def iter_algorithm(d, n, p, corpus, pr):
"""
PR(p) = ( (1-d) / n ) + ( d * sum( PR(i) / NumLinks(i) ) )
i
d = dampening number; n = # of possible pages; p = page; i = incoming pages
"""
page_sum = 0
# This for loop will calcula... | b38cdbe6510a81791a7aa2abd0a9943c66610caf | 653,372 |
import pathlib
import re
def read_rst(filename):
"""Return the text in given filename."""
filepath = pathlib.Path(__file__).parent / filename
with filepath.open(encoding='utf-8') as f:
return re.sub(r':[a-z]+:`~?(.*?)`', r'``\1``', f.read()) | f7cfbe4f76f43b52e7acf05e46845e817a27b58f | 653,373 |
def has_attribute(ob, attribute):
"""
:func:`hasattr` swallows exceptions. :func:`has_attribute` tests a Python object for the
presence of an attribute.
:param ob:
object to inspect
:param attribute:
``str`` for the name of the attribute.
"""
return getattr(ob, attribute, No... | 5d91f5acf57842d04f2cfd57afe5f7bfe1cc08d5 | 653,374 |
def remove_stop_words(content, stopwords):
"""Removes the stopwords in an article.
:param tokens: The tokens of an article.
:type tokens: []str
:param stopwords: the list of stopwords
:type stopwords: []str
:return: The tokens of an article that are not stopwords.
:rtype: []str
"""
... | 97e7ef8e92853f629d9c6e2e211d423564d865dd | 653,375 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.