content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def arg_fetchlive(args):
"""Parse the fetchlive parameter from the command line."""
fetchlive = 1
if len(args) >= 1 and is_int(args[0]):
fetchlive = 0
dbg_print(1, "Fetchlive: %s" % fetchlive)
return fetchlive | b125d0703420856413a465bb1757f63c64f262cd | 3,619,200 |
import typing
def get_level_1_xml(
node: et.Element,
key: str,
search_keys: typing.List[str],
data_dict: typing.Dict[str, str]
) -> None:
"""
Return the key/value pair for the xml case
<key>
<subkey>value</subkey>
</key>
Arguments:
node - Node in the x... | d6359512a9a26ef93f78a4670b49dc4b856db52f | 3,619,201 |
def boggle(board, trie):
"""Searches for words on the assumed-nonempty board."""
height = len(board)
width = len(board[0])
matches = set()
def dfs(i, j, node):
if not (0 <= i < height and 0 <= j < width):
return
ch = board[i][j]
if ch is None:
return... | f6224aaed0912da409474934d50cf3eb5e577f07 | 3,619,202 |
def run_entrainments(model_particles, bed_particles, event_particle_ids, avail_vertices, unverified_e, h):
""" This function mimics an 'entrainment event' through
calls to the entrainment-related functions.
Uniqueness of entrainments is forced post-event. Particles
which select non-unique entrainm... | abb0b97b524dc5e29f7c27dd07bbb8914c48bb65 | 3,619,203 |
def opamp_voltage_normalizer(supply_voltage):
"""
Normalize supply voltage values.
"""
parse = split_val_condition(supply_voltage)
if parse["value"].startswith("± "):
parse["value"] = parse["value"].replace("± ", "±")
(value, unit) = [i for i in parse["value"].split(" ") if i != ""]
... | f921eccb66f3ab1d1fa21466a2e7efd1e592a4a6 | 3,619,204 |
def get_L_star_CS_d_t(L_star_CS_d_t_i):
"""(32)
Args:
get_L_star_CS_d_t_i: 日付dの時刻tにおける暖冷房区画iの1時間当たりの熱取得を含む負荷バランス時の冷房顕熱負荷(MJ/h)
L_star_CS_d_t_i: returns: 日付dの時刻tにおける1時間当たりの熱取得を含む負荷バランス時の冷房顕熱負荷(MJ/h)
Returns:
日付dの時刻tにおける1時間当たりの熱取得を含む負荷バランス時の冷房顕熱負荷(MJ/h)
"""
return np.sum(L_star_CS... | b232ebab67474ea81349ebbbc4f153b9649b2435 | 3,619,205 |
from typing import List
from typing import Type
from typing import Dict
from typing import Any
from pydantic_factories import ModelFactory
from typing import get_args
def create_function_signature_model(fn: AnyCallable, plugins: List[PluginProtocol]) -> Type[SignatureModel]:
"""
Creates a subclass of Signatur... | 113b73d02c0e5475199c46da3b64c394f487a9ef | 3,619,206 |
import math
def angacc_2_genangacc(angacc, r, dr, angvel):
"""
:param angacc: np.array
:param r: np.array
:param dr: np.array
:param angvel: np.array
:return: np.array
"""
m_rQ = r
m_rDq = dr
V = angvel
W = V
DW = angacc
t = np.linalg.norm(m_rQ)
qw = np.dot(m_r... | a4377bb861d126983f82eb4e7c1a6cd2ca261299 | 3,619,207 |
from typing import OrderedDict
import random
def random_play(data):
"""Generate a random play with plausible values for debugging purposes."""
features = data['features']
situation = OrderedDict.fromkeys(features)
situation['dwn'] = 4
situation['ytg'] = random.randint(1, 10)
situation['yfog'... | 79460497f7d407af62e5083ec3b238ed0301ab04 | 3,619,208 |
import re
def remove_proximity_around_booleans(query_str):
"""
Clients like PEP-Web (Gavant) send fulltext1 as a proximity string.
This removes the proximity if there's a boolean inside.
We could have the client "not do that", but it's actually easier to
remove than to parse and add.
>>> ... | b89ac8ab52cf00f1902603c38bc3f4fdd47cbda2 | 3,619,209 |
def extension_from_file(path):
"""Returns extension (like '.jpg') based on content of image file at path.
An empty string is returned if no match is found."""
f = file(path, 'r')
ext = extension_from_data(f.read(11))
f.close()
return ext | 8a1d4814c953a62dbf6490bdd176690698cc790f | 3,619,210 |
from scipy.interpolate import UnivariateSpline
def flux_radius(components, observation=None, frac=0.5, weight_order=0):
"""
Determine the radius R (in pixels, along semi-major axis),
the flux within R has a fraction of `frac` over the total flux.
Parameters
----------
components: a list of `... | f1325c32954547389e147392919a7a360b2cc800 | 3,619,211 |
def get_instances_for_description(x=None, labels=None, metrics=None, instance_indexes=None):
""" Returns indexes of instances for which we need descriptions
The instances are selected as follows:
- If the instance indexes are directly passed, then select those
- If instance indexes are not passed, ... | 75ce9ea8da86ff4b7987cc425ed2133a9887c6e3 | 3,619,212 |
def _hyperbolic_distance(x, y):
"""Compute hyperbolic distance between batches x and y.
Args:
x: 2D Numpy array.
y: 2D Numpy array.
Returns:
distances: 2D Numpy array such that distances[i,j] =
hyperbolic(x[i,:], y[j,:]).
"""
sq_norm_x = (x ** 2).sum(axis=1)[:,None]
sq_norm_y = (y ** 2).... | 74a711d31a40fee0f8922ffd7a025cddc33ba649 | 3,619,213 |
from typing import Union
from typing import List
from typing import Tuple
def generalized_intervals_union(
interval_list:Union[List[GeneralizedInterval],Tuple[GeneralizedInterval]],
join_book_endeds:bool=True
) -> GeneralizedInterval:
""" finished, checked,
calculate the union of a list (or tuple) of... | 660aeaaf2d0bfae65d371b12145d6dcb78ba6031 | 3,619,214 |
def _provenance_str(provenance):
"""Utility function used by compare_provenance to print diff
"""
return ["%s==%s" % (key, value) for (key, value) in provenance] | 2cbe1f177122a49bb747cce0ccca3fd715349a6a | 3,619,215 |
def _lines_as_list(path, pattern, ignore_pattern):
"""
Helper function for config. Process lines as list of strings.
"""
try:
# All lines as list of strings
if not pattern and not ignore_pattern:
with open(path, 'r') as input_file:
ret = input_file.readlines()... | 71946764f28ec70f1795dd0473c21b17a100ec5f | 3,619,216 |
def cdmi_str_to_aceflag(cdmi_str):
"""
Return the aceflag from a cdmi string
:param cdmi_str: A comma-separated list of aceflags
:type cdmi_str: str
:return: The aceflag created from the string
:rtype: int
"""
aceflag = 0
ls_flag = cdmi_str.split(",")
for flag in ls_fla... | b7eb671e7201c9913067da71d0ed1aed561723a5 | 3,619,217 |
def group_configurations_list_handler(request, course_key_string):
"""
A RESTful handler for Group Configurations
GET
html: return Group Configurations list page (Backbone application)
POST
json: create new group configuration
"""
course_key = CourseKey.from_string(course_key_st... | d24db460c6621586a945d52081a8d9a779801324 | 3,619,218 |
from typing import Union
def phik_from_binned_array(x: Union[np.ndarray, pd.Series], y: Union[np.ndarray, pd.Series], noise_correction:bool=True, dropna:bool=True, drop_underflow:bool=True, drop_overflow:bool=True) -> float:
"""
Correlation matrix of bivariate gaussian derived from chi2-value
Chi2-value ... | 874e7761a3bf6d5d9a3b7d0e0eb154c786b693d3 | 3,619,219 |
def api_client(application, request):
"""
Fixture that returns api_client
Parameters:
app (Application): Application for which create the client.
Returns:
api_client (HttpClient): Api client for application
"""
def _api_client(app=application, **kwargs):
client = app.api_... | cf2894c8f8c2adb8a8700dfa1b9f3a99e86909d8 | 3,619,220 |
def massCheck(proj, geom, label):
"""
Calculate the total liquid mass and the variation between views.
:param numpy.array(float) proj: Projection data.
:param list(dict): Geometry dict for each line of sight.
:param str label: Label defining the current projection (res/avg, Re).
:returns: Tuple... | bc6522f4e91e2927b328d46f596e5627ebb275eb | 3,619,221 |
def get_store(name=DEFAULT_STORE_NAME, factory=DEFAULT_FACTORY):
"""
Gets store provider from factory
:param factory:
:param store_name:
:return: Storage Provider
:rtype: deployer.services.storage.base.AbstractStore
"""
return factory.get(name) | 5980bb33d640b884ec295e1cbf932425fa7c8561 | 3,619,222 |
def get_domain_adapt_config(cfg):
"""Get the configure parameters for video data for action recognition domain adaptation from the cfg files"""
config_params = {
"data_params": {
"dataset_root": cfg.DATASET.ROOT,
"dataset_src_name": cfg.DATASET.SOURCE,
"dataset_src_t... | d203aa00b3349ec7c2e6043a0496fc7da82f1b08 | 3,619,223 |
def rgb2hex(r,g,b):
"""
Convert a RGB vector to hexadecimal values
"""
hexfmt = "#%02x%02x%02x"%(r,g,b)
return hexfmt | cf0452aa22d9dbdee3158a4926fa0755ca19fbd3 | 3,619,224 |
def commonInitialization(target):
"""
Routine to initialize common variables for both position forms.
"""
target.stdfont = QtGui.QFont()
target.stdfont.setFamily("Arial")
target.stdfont.setPointSize(11)
target.stdfontbold = QtGui.QFont()
target.stdfontbold.setFamily("Arial")
tar... | b7b3d9a83b06512a1fc5090d94b437bf98282aae | 3,619,225 |
def index():
"""
Renders the 'index' page
:return:
"""
return flask.render_template('index.jinja2', my_server=flask.request.url_root) | 5e2620431b0baa1b404bb574fa781d1ff18b2437 | 3,619,226 |
from typing import VT
from typing import Optional
from typing import Callable
from typing import List
from typing import Set
def match_hadamards(g: BaseGraph[VT,ET],
vertexf: Optional[Callable[[VT],bool]] = None
) -> List[VT]:
"""Matches all the H-boxes with arity 2 and phase 1, i.e. all the Hadam... | c85d32a823d69fc7079b74c682b286069ad5dcc2 | 3,619,227 |
def align_right_position(anchor, size, alignment, margin):
"""Find the position of a rectangle to the right of a given anchor.
:param anchor: A :py:class:`~skald.geometry.Rectangle` to anchor the
rectangle to.
:param size: The :py:class:`~skald.geometry.Size` of the rectangle.
:param alignment:... | a7bc5560c7b247abea71833fd8e1c3459d9dce3c | 3,619,228 |
import time
async def PUT_Attribute(request):
""" Handler for PUT /(obj)/<id>/attributes/<name>
"""
log.request(request)
app = request.app
params = request.rel_url.query
obj_id = get_obj_id(request)
attr_name = request.match_info.get('name')
log.info("PUT attribute {} in {}".format(at... | f00ca952aeb5cb80117a41f1b5c4e04d4e6f3c37 | 3,619,229 |
def _parse_docstring_field(field_lines):
"""
@param field_string:
@type field_string:
@return: return pair:
argument name, dict of updates for argument info
@rtype: C{dict}
"""
if field_lines.startswith('@type'):
field_data = field_lines.split(None, 2)
arg_name = fie... | fb10dc1db15d56fc70ee32e733113309eb9b24c3 | 3,619,230 |
def get_discount_rate(n: float, s: float, p: float) -> float:
""""
Повертає значення облікової ставки.
Parameters
----------
n : float
Термін кредиту у роках
s : float
Нарощена сума боргу
p : float
Банківський облік
Returns
-------
d : float Облікова ... | 67bb66be1b7b3e8ac34653fd47ebb960c1152dc6 | 3,619,231 |
def run_test(case_id):
"""
:param case_id: case_id is test_case_id
:return: it does the utils on test_case_id based on its test_name
"""
save_test_status(case_id, 3)
case_log = save_case_log(case_id.test_case_id, None, None, None, None)
if case_id.test_status == 3:
if case_id.test_n... | 35554578ccb572c72da7abb111063a07c0da4afd | 3,619,232 |
from functools import reduce
def _is_num_tuple(t,size):
"""Returns: True if t is a sequence of numbers; False otherwise.
If the sequence is not of the given size, it also returns False.
Parameter t: The value to test
Precondition: NONE
Parameter size: The size of the sequence
Pr... | 64b3795b8e90dc38a7c48cd177d8e2aaffc0aa3d | 3,619,233 |
def resBlock(x,kernelSize,outMaps):
"""
block of resnet units, resolution halves
"""
with tf.variable_scope(None, default_name="resBlock"):
res1 = resLayerStride(x,kernelSize,outMaps)
res2 = resLayer(res1,kernelSize,outMaps)
return res2 | 5db574f64bdfcc817e3f8e526f6ef5069eae2642 | 3,619,234 |
def load_gene_gene_dat(gene_dat_path):
"""
Load gene annotation data (transcript data).
:param gene_dat_path: str, filepath for gene_gene_dat_wsize (Part of ExcisionFinder package).
:return: Refseq gene annotations file.
"""
gene_gene_dat = pd.read_csv(
gene_dat_path,
sep="\t",
... | 78921664deb2c5381ae46a913a972361befe3b5b | 3,619,235 |
def ComputeThickness2(meshes, maximumThickness, sharpAngle, cancelToken, multiple=False):
"""
Compute thickness metrics for this mesh.
Args:
meshes (IEnumerable<Mesh>): Meshes to include in thickness analysis.
maximumThickness (double): Maximum thickness to consider. Use as small a thicknes... | c884c661934535f12e59a7252aaacf512dc80758 | 3,619,236 |
def dfs(adj_matrix, minsize):
""" depth first search
Returns subsets with at least minsize or more nodes.
"""
visited = set()
connected_sets = []
for ind, row in enumerate(adj_matrix):
if ind not in visited:
connected_sets.append(set())
stack = [ind]
... | 91cf71b55e0a6a542432bf3ac932644ad9c2b854 | 3,619,237 |
import warnings
def _fit_and_predict(estimator, X, X_for_test, y, train, test, verbose, fit_params,
method):
"""Fit estimator and predict values for a given dataset split.
Read more in the :ref:`User Guide <cross_validation>`.
Parameters
----------
estimator : estimator obje... | 37ed31d4222a8f4c1651353ce89e6ff9e098817e | 3,619,238 |
def make_surf_graph(vertices, faces, mask=None):
"""
Constructs adjacency graph from `surf`
Parameters
----------
vertices : (N, 3) array_like
Coordinates of `vertices` comprising mesh with `faces`
faces : (F, 3) array_like
Indices of `vertices` that compose triangular faces of ... | d9bc77c7849d90b5e5c103a46543a07f658fe7f7 | 3,619,239 |
import argparse
def options_parse():
"""
Command line option parser
"""
parser = argparse.ArgumentParser()
# Options for model parameters setup (only change if model training was changed)
parser.add_argument('--num_filters', type=int, default=64,
help='Filter dimension... | 60cb3e0b74bada6c720bc0038aefc809a9d825f1 | 3,619,240 |
from typing import Tuple
def clahe(
image,
clip_limit: float = 0.01,
tile_size: Tuple[int, int] = (8, 8),
use_signed_negative: bool = False,
):
"""
Applies CLAHE equalization to input image. Works on color images by
converting to Lab space, performing clahe on the L channel, and converting... | 67d28c1ec1c962225211d567707ae4a6ee98087d | 3,619,241 |
import os
import sys
def ResolvConfigDir(config_dir, sys_only=False):
"""Checks for a user config directory and if it is not
found it then resolves the absolute path of the executables
directory from the relative execution path. This is then used
to find the location of the specified directory as it r... | c1eb2e8ee4e08ce77798fcc23ce59462a5180fad | 3,619,242 |
def jsonify_dict(d):
"""Turns python booleans into strings so hps dict can be written in json.
Creates a shallow-copied dictionary first, then accomplishes string
conversion.
Args:
d: hyperparameter dictionary
Returns: hyperparameter dictionary with bool's as strings
"""
d2 = d.copy() # shallow c... | afbf5819fc4fda444076562b02deb22f8146f123 | 3,619,243 |
import json
def delete_floating_ips(request):
"""The deleting floating ips view."""
result = {}
project_id = request.POST['project_id']
user_token = request.POST['user_token']
region = request.POST['region']
floating_ips_dict = remove_project_resource(
region,
project_id,
... | d45661a0327dc832dd2671d8df83a311b5125dc1 | 3,619,244 |
def concat(funcname, args):
"""Return args spliced by sql concat operator."""
return " || ".join(args) | baf8d1a9e128d9c490744a93a90ae00b3072dc24 | 3,619,245 |
import argparse
def parse_args():
"""Parses the arguments from the command line."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--version", help="Print the version and path to this script.",
action="store_true"
)
parser.add_argument(
"--empty", help="creates a... | 7ebcfd8c09e39825e8f901615d4c64e8df27a873 | 3,619,246 |
def generate_fe_entry(entry, name):
"""add function
"""
java_output = ""
java_output += "\"" + name + "\""
java_output += ", \"" + entry["symbol"] + "\""
if entry["user_visible"]:
java_output += ", true"
else:
java_output += ", false"
if 'prepare' in entry:
java_o... | edb2ca8b4624873a57de4f2cbaf4159e2b58f19b | 3,619,247 |
def seg_file2tensor_4band(f, fir, resize):
"""
"seg_file2tensor(f)"
This function reads a jpeg image from file into a cropped and resized tensor,
for use in prediction with a trained segmentation model
INPUTS:
* f [string] file name of jpeg
OPTIONAL INPUTS: None
OUTPUTS:
* im... | 55432d85847fa8a73d01e0028a67707feaf2dddf | 3,619,248 |
def get_pyshp_field_dtypes(code):
"""Returns a numpy dtype for a pyshp field type."""
dtypes = {'N': np.int,
'F': np.float,
'L': np.bool,
'C': np.object}
return dtypes.get(code, np.object) | 7a3f54131bed276326a0dc75e2f19a1dda53d078 | 3,619,249 |
def totient(num):
"""
Counts the numbers that are relative prime to the number.
This means that if a number 'x' has common divisors with another number 'a' lower than itself,
it is, 'a' is not relative prime to 'x'.
This means that if a number is prime, its totient function is its value - 1, as
... | c944da6dc788a4bda0237c397b763d2ab304e7ad | 3,619,250 |
from pathlib import Path
def _load_requirements(requirements_file, folder="requirements"):
"""Load requirements from a file."""
requirements = []
with open(Path(folder) / Path(requirements_file), "r") as f:
for line in f:
line = line.strip()
if line and not line.startswith(... | e9d56a025986f9a2899b3d070033abcdeec21956 | 3,619,251 |
def img_preprocess(img):
"""
preprocessing on the input image
first crops the image then resizes it
"""
return resize_img(crop_img(img)) | 96798b3779100371a9a48df22913031f4ec80dc8 | 3,619,252 |
def sampled_dropout_average(mlp, inputs, num_masks,
default_input_include_prob=0.5,
input_include_probs=None,
default_input_scale=2.,
input_scales=None,
rng=(2013, 5, 17),
... | 42dff5ffdd34ac4a1723dd574b8163904ba60b7c | 3,619,253 |
def urljoin(url1: str, url2: str) -> str:
""" Custom function to join two url paths
Uses `~urllib.parse.urlparse` and `~urllib.parse.urlunparse`
to join relevant segments of two urls. Does not use `~urllib.parse.urljoin`
as that replaces existing url path with a new path.
Parameters
---------... | 8044a0abe2fc1dd51afe83a9fa2ec2d0c1303218 | 3,619,254 |
def getEvoBibAsBibtex(*keys, **kw):
"""Download bibtex format and parse it from EvoBib"""
res = []
for key in keys:
bib = get_url(
"http://bibliography.lingpy.org/raw.php?key=" + key,
log=kw.get('log')).text
try:
res.append('@' + bib.split('@')[1].split('<... | 1ffdce3077dc067122fcb3674d97a4f33560e939 | 3,619,255 |
def image_distance(x: IMAGE_HASH, y: IMAGE_HASH) -> int:
"""Calculates the distance between to image hashes
Arguments:
x {IMAGE_HASH} -- IMAGE_HASH object for image 1
y {IMAGE_HASH} -- IMAGE_HASH object for image 2
Returns:
int -- hamming distance of two image hashes
"""
r... | 5e038015883e6c52eaf66ae431f61d499a90cabe | 3,619,256 |
from datetime import datetime
import random
def random_date(start_date: str, end_date: str):
"""
This function will return a random datetime between two datetime
objects.
"""
dt_start = datetime.strptime(start_date, "%Y-%m-%d")
dt_end = datetime.strptime(end_date, "%Y-%m-%d")
delta = dt_e... | 5903b50fc79943120e418d619b5faef242609c0f | 3,619,257 |
from datetime import datetime
def oauth2_get_token():
"""Get an oauth2 auth_token for the app to work. May need app approval
"""
params = load_config_file(OAUTH_CONFIG_FILE)
oauth = OAuth2Session(params["client_id"], scope=params["scope"])
token_expires = datetime.utcfromtimestamp(params.get("expi... | 6e1ca4759d998aed02fef843fee02774d2300c8c | 3,619,258 |
def get_emails(notification_rec):
"""
Get list of emails for users listed in the specified notification
"""
# Use a set instead of list as there could be duplicates.
ret = []
for recipient in notification_rec.recipients.all():
ret.append(recipient.email)
return ret | 9c01b1e5615cf3a35fbda0c4d92a1e092cfc3d59 | 3,619,259 |
from typing import Type
import re
def generate_docstring(executable: Type[job_blocks.ExecutableSpec]) -> str:
"""Returns a docstring for a ExecutableSpec factory method."""
docstring = executable.__doc__
if _ATTRIBUTES_SECTION_HEADER not in docstring:
raise Exception(
f'Please add Attributes: sectio... | 91d58a14e9cb0ef4de73f0a1a67e8e916ea53f8f | 3,619,260 |
def _validate_min_max(wave, indep_min, indep_max):
"""Validate min and max bounds are within waveform's independent variable vector."""
imin, imax = False, False
if indep_min is None:
indep_min = wave._indep_vector[0]
imin = True
if indep_max is None:
indep_max = wave._indep_vect... | 1a17b61ad1fdd29a9cc4212f512e50a3c119aed3 | 3,619,261 |
import typing
def get_actions_with_permissions(user_id: int, permissions: Permissions, action_type_id: typing.Optional[int] = None) -> typing.List[Action]:
"""
Get all actions which a user has the given permissions for.
Return an empty list if called with Permissions.NONE.
:param user_id: the ID of ... | dc89f2dfb84c8217050b8718b08365ecbea5807f | 3,619,262 |
def format_mqc(lane, info):
"""Format the data structure as wanted by MultiQC. This will be turned
directly into the mqc.yaml to make the Yield Summary table. I'm using
summarize_lane_contents as a basis, but note that script also sucks some of
the info from here into the Overview/Lane Summary ... | 665a90ba70f7ea9d9fca3d40a4e2cd82f58525fc | 3,619,263 |
def list2xml(datalist, roottag, elementname, pretty=False):
"""Converts a list to an UTF-8 encoded XML string.
See also dict2et()
"""
root = list2et(datalist, roottag, elementname)
return to_string(root, pretty=pretty) | d3e0780ea979a1adf66d07832dcbc5c2b2df05fd | 3,619,264 |
import six
def text_type(string, encoding='utf-8'):
"""
Given text, or bytes as input, return text in both python 2/3
This is needed because the arguments to six.binary_type and six.text_type change based on
if you are passing it text or bytes, and if you simply pass bytes to
six.text_type w... | 5b962c348769ccb1029cd0d41fc23ddb6942d37d | 3,619,265 |
import hmac
import hashlib
def intercom_user_hash(data):
"""
Return a SHA-256 HMAC `user_hash` as expected by Intercom, if configured.
Return None if the `INTERCOM_HMAC_SECRET_KEY` setting is not configured.
"""
if getattr(settings, 'INTERCOM_HMAC_SECRET_KEY', None):
return hmac.new(
... | 8bdc04eef363f939248d949eccb93cdfbafd989c | 3,619,266 |
from model_utils.config import config
import multiprocessing
def create_yolox_dataset(image_dir, anno_path, batch_size, device_num, rank,
data_aug=True, is_training=True):
""" create yolox dataset """
cv2.setNumThreads(0)
if is_training:
filter_crowd = False
remove... | aa6a4c869bc4be6f80d7b680ee506353ad0be464 | 3,619,267 |
def quote_value(value: str) -> str:
"""
Ensures values with ";" are quoted.
>>> quote_value("foo")
'foo'
>>> quote_value("foo;bar")
'"foo;bar"'
"""
if value.find(";") != -1:
return f'"{value}"'
return value | e6bb23a17d554742115582feb90ba621ddd7fc66 | 3,619,268 |
import tokenize
def parse_stories(lines, only_supporting=False):
"""Parse stories provided in the bAbi tasks format. If only_supporting is
true, only the sentences that support the answer are kept.
"""
data = []
story = []
for line in lines:
line = line.decode('utf-8').strip()
... | 1684a3b33623b25169f2dbd2b31e86cc82a3ce54 | 3,619,269 |
from datetime import datetime
def check_datetime_timetz(dt: datetime) -> ResultComparison:
""" post: _ """
return compare_results(_invoker("timetz"), dt) | b44a96a27d915b2cb366715413d3501948a18854 | 3,619,270 |
def process_string(logger, content, ignore_unsuitable, old_platform,
new_platform):
"""Add a configuration for a new platform to the modulemd document string.
It returns an error code and a string.
In case of no error, code will be 0 and the string will be the processed,
output docum... | 1dc9d7f61557136a3ffe639d3588bee2dd5637cd | 3,619,271 |
def get_temporal_entropy(y: np.ndarray, fs: int, config: dict) -> float:
"""
Temporal entropy is a measure of the temporal dispersal of acoustic energy within a recording,
has been shown to reflect the number of avian calls in a recording (Sueur, Pavoine et al. 2008).
:param y: mono audio
:param fs... | 4991f6714f4a78b233d665d76c6cc444f15b6603 | 3,619,272 |
import json
import logging
def partitions_query(addr):
"""
Query the worker at the given address for its partition routing
information.
"""
stdout = external_sender_query(addr, 'partition-query')
try:
return json.loads(stdout)
except Exception as err:
e = ObservabilityRespo... | 4da58e87af7401427096f989187e2150e76ea2cd | 3,619,273 |
def metrics(output_softmax, labels, num_classes):
"""
Builds the metrics for the model, including IoU and accuracy
:param output_softmax: TF Tensor containing the sofmax operation on the last layer in the neural network
before the decoder
:param labels: TF Placeholder for th... | 97206804234d0a98d0cd9cf9569e443bc0b2210c | 3,619,274 |
def update_config(config: dict):
"""Update the passed config dictionary."""
version_classes = _get_version_classes()
if 'version' not in config:
config_version = (0, 1, 0)
else:
config_version = _version_value(config['version'])
apply_classes = [x[1] for x in version_classes if confi... | 5a3b1fe00366ed955480288c095b3d16350aa61f | 3,619,275 |
from typing import Callable
def join_docs(sep: Callable[[], Doc], docs: list[Doc]) -> list[Doc]:
"""Join a sequence of tokens with a separator"""
list_vals = []
for i, doc in enumerate(docs):
if i != 0:
list_vals.append(sep())
list_vals.append(doc)
return list_vals | 507295860e0abfeb98a527564174aa7c6c4fca85 | 3,619,276 |
def make_literal_parser(*args: t.Any) -> comb.Parser:
"""Return parser for t.Literal[args]."""
return comb.Or(*map(comb.Lit, args)) | fba98f9c650bf401a32f093afb987620ccd04021 | 3,619,277 |
import numpy
def xyz(date, velocity=False, equinox=1950.0):
"""
Calculate geocentric X,Y, and Z and velocity coordinates of the Sun.
Parameters
----------
date : float
Julian date
equinox : float
Equinox of output. If None, Equinox will be 1950.
velocity : boolean
... | bf3ec3fee8affef4a5acf7eb755edece40b32384 | 3,619,278 |
def estimation_formula_bg(growth, eps):
"""
The stock price estimation formula suggested by Benjamin Graham
According to "The Intelligent Investor"
"""
return (2*growth+8.5)*eps | b675c3ec8cd82d600473d2646cc759bc8f3279be | 3,619,279 |
import numpy
def grid3d2Order(unaries,regularizer,order='numpy',operator='adder'):
"""
returns a 2d-order model on a 3d grid (volume).
The regularizer is the same for all 2.-order functions.
Keyword arguments:
unaries -- unaries as 4d numpy array where the last dimension iterates over the labels
r... | f7dcbf83302989943823c7102598daeba6259690 | 3,619,280 |
import shutil
import subprocess
import os
def run(zmatName, cgen, opt, charge, molname, workdir, debug, checkrun = True):
"""
Run BOSS different times to generate Bonds, Angles, Dihedrals, Charges and VdW OPLSAA parameters
Parameters
----------
zmatName : str
Name of the Zmat file of the molec... | 60bf0b6648d53c829bd1ef38322226fc7dfa3872 | 3,619,281 |
import argparse
def parse_arguments(args=None) -> None:
"""Returns the parsed arguments.
Parameters
----------
args: List of strings to be parsed by argparse.
The default None results in argparse using the values passed into
sys.args.
"""
parser = argparse.ArgumentParser(
... | b5188f571b29bda0dd1ce461b325077205c162a0 | 3,619,282 |
import unittest
def makeTestSuiteV201111():
"""Set up test suite using v201111.
Returns:
TestSuite test suite using v201111.
"""
suite = unittest.TestSuite()
suite.addTests(unittest.makeSuite(DfpWebServiceTestV201111))
return suite | 8d0ca67ff0aac25a0848730bdc77b01eb791dd02 | 3,619,283 |
def refresh_handler(unused_addr, args):
"""
Refresh text
"""
logger.info("Refreshing text")
send_questions_to_line_editor()
return None | aff4e86350dc5bb2eed0e392b119e7b7637800f5 | 3,619,284 |
async def huobi_spot_tickers(api_key: str, secret_key: str, symbol: str = None):
"""
获取行情数据
:param api_key:
:param secret_key:
:param symbol:
:return:
"""
huobi = HuobiAPI(api_key, secret_key)
return await huobi.tickers(symbol=symbol) | 608415abb11a1291b322f271eb8620e63c2bd16c | 3,619,285 |
def make_quality_step(env, run_time, route_to, transit_time=1, **kwargs):
"""
"""
return {
'location': env['quality_bench'],
'worker': env['qual_inspector'],
'manned': True,
'setup_time': 0,
'run_time': run_time,
'teardown_time': 0,
'transit_time': tr... | 3f4ac237f4d0d0cd9245d6e615495563a5152a23 | 3,619,286 |
def reverse_sorting_order(str_name):
"""Return False if str_name ends with one of the err_strings suffixes. Otherwise, return True.
Negation was introduced as the function is used to determine the order of the sorting depending on scoring
function name: if scoring ends with "_error" or "_loss", it means th... | 481b78912262fd086121b6281d3f53c13f3571ff | 3,619,287 |
from typing import List
from typing import Tuple
def parse_keyval(line: str, valsplit: str = ':', csvsplit=',') -> List[Tuple[str, str]]:
"""
Parses a csv with key:value pairs such as::
John Alex:Doe,Jane Sarah:Doe
Into a list with tuple pairs (can be easily converted to a dict)::
... | f96c32234436895edeb6a0fcc42d2ec2346a258c | 3,619,288 |
def most_active():
"""Finds the most active station based on count of temp records"""
session=Session(engine)
# same as above but with station ID , aslo trying subquery method
active_station_id=session.query(\
Station.id,Station.station,\
func.count(Station.station).label('activity_c... | 29d82d9b8c26073f0b53648b1dd493920b3f8e93 | 3,619,289 |
def getUserInput():
"""
Purpose: to validate user Input
Parameters: None
Returns: x - validated user input
"""
x = input("Recursion Depth: ")
try:
x = int(x)
except ValueError:
x = getUserInput()
return x | 87a67cf12e1a45e16068bf7c64e53b33e3cdbdeb | 3,619,290 |
def attr_subresource(raml_resource, route_name):
""" Determine if :raml_resource: is an attribute subresource.
:param raml_resource: Instance of ramlfications.raml.ResourceNode.
:param route_name: Name of the :raml_resource:.
"""
static_parent = get_static_parent(raml_resource, method='POST')
i... | ef98f693ea37ac19d81fb9611eda26b3d1d30830 | 3,619,291 |
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy.signal.spectral import _spectral_helper
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
def bicoherence( da,
nperseg,
plot=False,
windowFunc='hann',
title='',
mask='A',
drawRedLi... | 59a5c265d7b27ca5f59fbec7c20896e43069d55d | 3,619,292 |
def translate_path_into_actions(rail_env, pathways, time_step):
"""Translates the solution paths of the CBS algorithm into an action for a given time step.
:param rail_env: The Flatland environment.
:param pathways: The solution paths of the CBS algorithm.
:param time_step: The time step for which an a... | e769f5a6fdc9fefa37d7ef07edc2e347225c6824 | 3,619,293 |
def test_module(client: Client) -> str:
"""
Tests API connectivity and authentication'
Returning 'ok' indicates that connection to the service is successful.
Raises exceptions if something goes wrong.
"""
try:
response = client.translate('I have the high ground!')
success = de... | 995ba791c1b7a19ed293349da91a0c0517fe2743 | 3,619,294 |
def plot_confusion_matrix(cm, label):
"""
Keyword Arguments:
correct_labels -- These are your true classification categories.
predict_labels -- These are you predicted classification categories
label -- This is a list of string labels corresponding labels
Returns: Figure
"""
fi... | 873cb3b6524c11f340e8f808580ec6b70d912427 | 3,619,295 |
def _compare_numeric(src_num, dst_num):
"""Compare numerical values. You can use '<%d','>%d'."""
dst_num = float(dst_num)
match = numeric_compare_regex.match(src_num)
if not match:
error = "Failed numeric comparison. Collected: {}. Expected: {}".format(dst_num, src_num)
raise ValueError... | 9279f671cac13d9cf29cffb9a3f85350c9e3d0da | 3,619,296 |
import subprocess
import os
def run_pd_rpc(cmd_or_code, no_print=False):
"""
This function invokes run_pd_rpc.py tool. It has a single string argument
cmd_or_code that works as follows:
If it is a string:
* if the string starts with os.sep, then it is a filename
* otherwise ... | 7dafdcfdd640595b8c4ef2815205c9fb9928ee51 | 3,619,297 |
def actionlstm_cell(x, h, a, num_units, action_dim,
initializer=tf.contrib.layers.xavier_initializer(),
bias_initializer=tf.constant_initializer(0.0),
activation=tf.tanh, scope='action_lstm'):
"""
:param x: state input
:param h: hidden state tuple... | 0d8c486e1db2ec9e356cc04bc6b72d1231e22c6b | 3,619,298 |
import sys
import getpass
def get_config():
"""Gets config from command line and console, returns config"""
# config = {
# 'overwrite': True or False
# 'server': String
# 'port': Integer
# 'user': String
# 'pass': String
# 'usessl': True or False
# 'keyfilename': Stri... | 1d649645809a30b11a904f3787ab2e560da87a42 | 3,619,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.