content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_H(m, n):
"""Calculate the distance of each point of the m, n matrix from the center"""
u = np.array([i if i <= m / 2 else m - i for i in range(m)],
dtype=np.float32)
v = np.array([i if i <= m / 2 else m - i for i in range(m)],
dtype=np.float32)
v.shape = n, 1
... | 23ea3f28816283c42f4722a6a5044772f2c0d2c3 | 3,653,600 |
def create_users(xml_filename, test_mode=False, verbose=False):
"""
Import OET cruise record XML file and create django auth users from the list of participants
:param filename: the name of the XML file
:return: the number of users created
"""
num_created = 0
cruise_record = xml2struct(xml_... | c15bf515f482b7b82bfa94e96708ec4d4caf96be | 3,653,601 |
import json
def writeJSONFile(filename,JSONDocument):
""" Writes a JSON document to a named file
Parameters
----------
filename : str
name of the file
JSONDocument : str
JSON document to write to the file
Returns
-------
True
"""
filename='data/'+filename
... | 4f20b42a5f38554589a7bb03039ba348e3b0bb15 | 3,653,602 |
def read_readme():
"""Read README content.
If the README.rst file does not exist yet
(this is the case when not releasing)
only the short description is returned.
"""
try:
return local_file('README.rst')
except IOError:
return __doc__ | ed3c00a1f6e05072b59895efc93dd2380d590553 | 3,653,603 |
def get_data_loader(dataset, dataset_dir, batch_size, workers=8, is_training=False):
""" Create data loader. """
return data.DataLoader(
get_dataset(dataset, is_training=is_training, dataset_dir=dataset_dir),
batch_size=batch_size,
shuffle=is_training,
num_workers=workers,
... | c7a126f37a78ef527a3e51136ffd9fbacbb5ddec | 3,653,604 |
def listwhom(detailed=False):
"""Return the list of currently avalailable databases for covid19
data in PyCoA.
The first one is the default one.
If detailed=True, gives information location of each given database.
"""
try:
if int(detailed):
df = pd.DataFrame(get_db_list_d... | a912113ee5f713522b5abfbdd8bc77cea54a5b10 | 3,653,605 |
def project(s):
"""Maps (x,y,z) coordinates to planar-simplex."""
# Is s an appropriate sequence or just a single point?
try:
return unzip(map(project_point, s))
except TypeError:
return project_point(s)
except IndexError: # for numpy arrays
return project_point(s) | 1039e29da4b1a7c733449354d507525d746fc389 | 3,653,606 |
def point_at_angle_on_ellipse(
phi: ArrayLike, coefficients: ArrayLike
) -> NDArray:
"""
Return the coordinates of the point at angle :math:`\\phi` in degrees on
the ellipse with given canonical form coefficients.
Parameters
----------
phi
Point at angle :math:`\\phi` in degrees to ... | 223e38a209280754538c5e1141317463ae4f4b98 | 3,653,607 |
def bmm(tensor1, tensor2):
"""
Performs a batch matrix-matrix product of this tensor
and tensor2. Both tensors must be 3D containing equal number
of matrices.
If this is a (b x n x m) Tensor, batch2 is a (b x m x p) Tensor,
Result will be a (b x n x p) Tensor.
Parameters
----------
... | f3663c612024195cda85b11019423cdb71d75da4 | 3,653,608 |
def get_monotask_from_macrotask(monotask_type, macrotask):
""" Returns a Monotask of the specified type from the provided Macrotask. """
return next((monotask for monotask in macrotask.monotasks if isinstance(monotask, monotask_type))) | 46d4516327c89755eaa3ba6f6fa3503aae0c5bd9 | 3,653,609 |
from SPARQLWrapper import SPARQLWrapper, JSON
def vivo_query(query, parms):
"""
A new VIVO query function using SPARQLWrapper. Tested with Stardog, UF VIVO and Dbpedia
:param query: SPARQL query. VIVO PREFIX will be added
:param parms: dictionary with query parms: queryuri, username and password
... | 396d2f8cfdd930f85d37a9b90be0cdb49bb47a4e | 3,653,610 |
def get_services_by_type(service_type, db_session):
# type: (Str, Session) -> Iterable[models.Service]
"""
Obtains all services that correspond to requested service-type.
"""
ax.verify_param(service_type, not_none=True, not_empty=True, http_error=HTTPBadRequest,
msg_on_fail="Inva... | 7352eb1e126af170f0c460edd9b69c77e07e3e0a | 3,653,611 |
import os
from shutil import copyfile
import subprocess
def copy_arch(arch, library_dir, libgfortran, libquadmath):
"""Copy libraries specific to a given architecture.
Args:
arch (str): The architecture being copied.
library_dir (str): The directory containing the dynamic libraries.
l... | 9c297b892dd1b1108a634c4abd97384275dbb05a | 3,653,612 |
import os
def getREADMEforDescription(readmePath=os.path.join(os.path.abspath(os.path.dirname(__file__)), 'README.md')):
"""Use the Markdown from the file for the package's long_description.
long_description_content_type should be 'text/markdown' in this case.
This is why we need the README to be in the MANIFES... | 2b0eff2cb2a7fe5d94a512c6f62b4ad8bf48b290 | 3,653,613 |
def abstractable(cls):
"""
A class decorator that scoops up AbstractValueRange class properties in order
to create .validate and .abstract methods for the class. Note that properties
added after the class is defined aren't counted. Each AbstractValueRange
found is is also replaced with a class instance constr... | ac14a1148d74a38618a8adc58df5a251296e72ee | 3,653,614 |
def summary1c(sequence):
"""
What comes in: A sequence of integers, all >= 2.
What goes out:
-- Returns the sum of INDICES of the items in the sequence
that are prime.
Side effects: None.
Examples:
-- If the given sequence is [20, 23, 29, 30, 33, 29, 100, 2, 4],
th... | c2c2f60fecafc883899942b389ce1780638342da | 3,653,615 |
from typing import List
from typing import Tuple
def choose_page(btn_click_list: List[Tuple[int, str]]) -> str:
"""
Given a list of tuples of (num_clicks, next_page) choose the next_page that
corresponds to exactly 1 num_clicks.
This is to help with deciding which page to go to next when clicking on ... | e61bc1e52c6531cf71bc54faea0d03976eb137ad | 3,653,616 |
from datetime import datetime
def get_content(request, path=''):
"""Get content from datastore as requested on the url path
Args:
path - comes without leading slash. / added in code
"""
content = StaticContent.get_by_key_name("/%s" % path)
if not content:
if path == '':
... | b7bb9550b78cb723ef669ad1c0df597f02d9d673 | 3,653,617 |
def reconstruct_entity(input_examples, entitys_iter):
""" the entitys_iter contains the prediction entity of the splited examples.
We need to reconstruct the complete entitys for each example in input_examples.
and return the results as dictionary.
input_examples: each should contains (start, end) indic... | 520acff8bfd0616a045ca1286c51d75ea9465f0e | 3,653,618 |
from typing import Dict
from typing import List
import yaml
def ensure_valid_schema(spec: Dict) -> List[str]:
"""
Ensure that the provided spec has no schema errors.
Returns a list with all the errors found.
"""
error_messages = []
validator = cerberus.Validator(yaml.safe_load(SNOWFLAKE_SPEC... | 216ce1189a66e83cf1b73cf5e2834434dcd73c9b | 3,653,619 |
def realord(s, pos=0):
"""
Returns the unicode of a character in a unicode string, taking surrogate pairs into account
"""
if s is None:
return None
code = ord(s[pos])
if code >= 0xD800 and code < 0xDC00:
if len(s) <= pos + 1:
print("realord warning: missing surro... | 6683725d24a984ecf4feb2198e29a3b68c7f1d5b | 3,653,620 |
import numpy
def evaluateSpectral(left_state,right_state,xy):
"""Use this method to compute the Roe Average.
q(state)
q[0] = rho
q[1] = rho*u
q[2] = rho*v
q[3] = rho*e
"""
spec_state = numpy.zeros(left_state.shape)
rootrhoL = numpy.sqrt(left_state[0])
rootrhoR = numpy.sqrt(righ... | f0c5d23396f486250de0e92f1abde4d03545f4f7 | 3,653,621 |
def get_multidata_bbg(requests):
"""function for multiple asynchronous refdata requests, returns a
dictionary of the form correlationID:result.
Function Parameters
----------
requests : dictionary of correlationID:request pairs. CorrelationIDs
are unique integers (cannot reuse until previou... | d0580910ac74fe7ac85795caa6b5321122626986 | 3,653,622 |
def specific_kinetic_energy(particles):
"""
Returns the specific kinetic energy of each particle in the set.
>>> from amuse.datamodel import Particles
>>> particles = Particles(2)
>>> particles.vx = [1.0, 1.0] | units.ms
>>> particles.vy = [0.0, 0.0] | units.ms
>>> particles.vz = [0.0, 0.0]... | 89a126c23b291a526401a00f812b40a5283319f4 | 3,653,623 |
def parse_loot_percentage(text):
"""Use to parse loot percentage string, ie: Roubo: 50% becomes 0.5"""
percentage = float(text.split(':')[1].strip("%")) / 100
return percentage | 97dc4f20f02ef0e5d3e592d3084dce80549777ce | 3,653,624 |
def major_minor_change(old_version, new_version):
"""Check if a major or minor change occurred."""
major_mismatch = old_version.major != new_version.major
minor_mismatch = old_version.minor != new_version.minor
if major_mismatch or minor_mismatch:
return True
return False | effa9f55c82a9edcacd79e07716527f314e41f39 | 3,653,625 |
from typing import Optional
from typing import List
from typing import Dict
def list_all_queues(path: str, vhost: Optional[str] = '/') -> List[Dict]:
"""Send a request to RabbitMQ api to list all the data queues.
Args:
path: Path to the RabbitMQ management api to send the request to.
vhost: Vi... | 9b57721509fdc6ec31eebb0ca8a0f28797419d95 | 3,653,626 |
def get_tf_model_variables(config_path, init_checkpoint):
"""Return tf model parameters in a dictionary format.
Args:
config_path: path to TF model configuration file
init_checkpoint: path to saved TF model checkpoint
Returns:
tf_config: dictionary tf model configurations
tf_variables: dictionar... | 5c9a1c138f3c12460668464d2c865787d7720e95 | 3,653,627 |
def org_unit_type_filter(queryset, passed_in_org_types):
"""Get specific Organisational units based on a filter."""
for passed_in_org_type in passed_in_org_types:
queryset = queryset.filter(org_unit_type_id=passed_in_org_type)
return queryset | 0495cabe121f8d6fdb584538f13764bd81d978c5 | 3,653,628 |
def is_str_digit(n: str) -> bool:
"""Check whether the given string is a digit or not. """
try:
float(n)
return True
except ValueError:
return False | 0e3b4c38cfd9fe2024bde2b63502c74dce307533 | 3,653,629 |
import cv2
import random
from re import DEBUG
def draw_all_poly_detection(im_array, detections, class_names, scale, cfg, threshold=0.2):
"""
visualize all detections in one image
:param im_array: [b=1 c h w] in rgb
:param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]
:param... | 4c9e3fc04b9743a687791341f70a51b8f66c7447 | 3,653,630 |
import os
import tempfile
def generate_dswx_layers(input_list, output_file,
hls_thresholds = None,
dem_file=None,
output_interpreted_band=None,
output_rgb_file=None,
output_infrared_rgb_file=No... | eb783b48276e6b62b63665fe84bfa5b5bf2a04cb | 3,653,631 |
import operator
def range_check_function(bottom, top):
"""Returns a function that checks if bottom <= arg < top, allowing bottom and/or top to be None"""
if top is None:
if bottom is None:
# Can't currently happen (checked before calling this), but let's do something reasonable
return lambda _: True
else:... | 95e22a544633f166b275d548fd4a07383e3ea098 | 3,653,632 |
def filter_employee():
""" When the client requests a specific employee.
Valid queries:
?employeeid=<employeeid>
Returns: json representation of product.
"""
query_parameters = request.args
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
cursor = conn.cursor()
lookup_... | 2238b10ad528a1ce523ff206d9f41f04e369adb4 | 3,653,633 |
import chunk
def ParallelLSTDQ(D,env,w,damping=0.001,ncpus=None):
"""
D : source of samples (s,a,r,s',a')
env: environment contianing k,phi,gamma
w : weights for the linear policy evaluation
damping : keeps the result relatively stable
ncpus : the number of cpus to use
"""
if ncpus:
... | 9a9ca1247fccf45c523d64e9dbff2313c6c9572b | 3,653,634 |
def get_value_from_settings_with_default_string(wf, value, default_value):
"""Returns either a value as set in the settings file or a default as specified by caller"""
try:
ret = wf.settings[value]['value']
return str(ret)
except KeyError:
return default_value | 7a08ac33073b451a6000931c6bd5b41f33b0c486 | 3,653,635 |
def jsonify(records):
"""
Parse asyncpg record response into JSON format
"""
return [dict(r.items()) for r in records] | 618cb538331c4eb637aa03f0ba857da3f2fa4c1c | 3,653,636 |
def smoothing_cross_entropy(logits,
labels,
vocab_size,
confidence,
gaussian=False,
zero_pad=True):
"""Cross entropy with label smoothing to limit over-confidence.
Args:
... | d0374cb850d25975c5e882335933c18da9647382 | 3,653,637 |
from anyway.app_and_db import db
def get_db_matching_location_interurban(latitude, longitude) -> dict:
"""
extracts location from db by closest geo point to location found, using road number if provided and limits to
requested resolution
:param latitude: location latitude
:param longitude: locatio... | 6e3bd7153cc555954768dd34a5a1b0090510a834 | 3,653,638 |
import re
def get(settings_obj, key, default=None, callback=None):
"""
Return a Sublime Text plugin setting value.
Parameters:
settings_obj - a sublime.Settings object or a dictionary containing
settings
key - the name of the setting
default - the defa... | b1bab5380cb94fb6493431b8732d9c963e9f1f14 | 3,653,639 |
import json
def parse_json_confing(config_file):
"""Parse JSON for config
JSON will can look like this:
{
"request_type": "server",
"comboBase": "www.cdn.com"
"base": "/base/path", //build directory
"js_path": "js", //path relative to base
"css_path": "pa... | 28f7f0cd41f31524450b03e0af806d79c857666e | 3,653,640 |
def site():
"""Main front-end web application"""
html = render.html("index")
return html | 0b8e144a6c366692c51a3fb5431d73fb9ed0e8c1 | 3,653,641 |
def parse_vad_label(line, frame_size: float = 0.032, frame_shift: float = 0.008):
"""Parse VAD information in each line, and convert it to frame-wise VAD label.
Args:
line (str): e.g. "0.2,3.11 3.48,10.51 10.52,11.02"
frame_size (float): frame size (in seconds) that is used when
... | 658a2a00b8b0b2cfdb83b649d2f87fcf23cbb6b4 | 3,653,642 |
def preprocess_image(img, img_width, img_height):
"""Preprocesses the image before feeding it into the ML model"""
x = get_square_image(img)
x = np.asarray(img.resize((img_width, img_height))).astype(np.float32)
x_transposed = x.transpose((2,0,1))
x_batchified = np.expand_dims(x_transposed, axis=0)
... | 50540e81da95651d22dec83271257657d7978f79 | 3,653,643 |
def Pose_2_KUKA(H):
"""Converts a pose (4x4 matrix) to an XYZABC KUKA target (Euler angles), required by KUKA KRC controllers.
:param H: pose
:type H: :class:`.Mat`
.. seealso:: :class:`.Mat`, :func:`~robodk.TxyzRxyz_2_Pose`, :func:`~robodk.Pose_2_TxyzRxyz`, :func:`~robodk.Pose_2_ABB`, :func:`~robodk.... | 5c15c450b9be728e1c0c8727066485ec0176711c | 3,653,644 |
from typing import Optional
def skip_regenerate_image(request: FixtureRequest) -> Optional[str]:
"""Enable parametrization for the same cli option"""
return _request_param_or_config_option_or_default(request, 'skip_regenerate_image', None) | 5d621202d0b72da53994b217f570bd86ccd5ada2 | 3,653,645 |
def parse_config(tool_name, key_col_name, value_col_name):
"""Parses the "execute" field for the given tool from installation config
file.
Parameters:
tool_name: Tool name to search from file.
Raises:
STAPLERerror if config file does not exists.
STAPLERerror if tool value can not be read ... | bd80078cbd488bafb8ba9ba46464460a12761b2f | 3,653,646 |
import ntpath
def path_leaf(path):
"""
Extracts file name from given path
:param str path: Path be extracted the file name from
:return str: File name
"""
head, tail = ntpath.split(path)
return tail or ntpath.basename(head) | 98ef27b218fdb5003ac988c42aff163d1067021f | 3,653,647 |
from typing import List
def delete_cache_clusters(
cluster_ids: List[str],
final_snapshot_id: str = None,
configuration: Configuration = None,
secrets: Secrets = None,
) -> List[AWSResponse]:
"""
Deletes one or more cache clusters and creates a final snapshot
Parameters:
cluster_... | 6c3e013eaedc0590b6eee7f50a9ce47f92ed57fc | 3,653,648 |
import torch
def define_styleGenerator(content_nc: int, style_nc: int, n_c: int, n_blocks=4, norm='instance', use_dropout=False, padding_type='zero', cbam=False, gpu_ids=[]):
"""
This ResNet applies the encoded style from the style tensor onto the given content tensor.
Parameters:
----------
... | ed996a2dbd1d2375a248582db21397ee051b5f25 | 3,653,649 |
def answer():
"""
answer
"""
# logger
M_LOG.info("answer")
if "answer" == flask.request.form["type"]:
# save answer
gdct_data["answer"] = {"id": flask.request.form["id"],
"type": flask.request.form["type"],
"sdp": fla... | 055a590107e30e4cd582e658e2f62fcba975f3dc | 3,653,650 |
def load_requirements():
""" Helps to avoid storing requirements in more than one file"""
reqs = parse_requirements('requirements-to-freeze.txt', session=False)
reqs_list = [str(ir.req) for ir in reqs]
return reqs_list | 4dcde55604cc8fc08a4b57ad1e776612eed18808 | 3,653,651 |
import warnings
import os
import types
import six
import sys
def discover(type=None, regex=None, paths=None):
"""Find and return available plug-ins
This function looks for files within paths registered via
:func:`register_plugin_path` and those added to `PYBLISHPLUGINPATH`.
It determines *type* - :c... | 9e680498a1ed6e05c84fe77858431400be889191 | 3,653,652 |
def next_permutation(a):
"""Generate the lexicographically next permutation inplace.
https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
Return false if there is no next permutation.
"""
# Find the largest index i such that a[i] < a[i + 1]. If no such
# index exists, the... | b6246d53b5e0ac0e28aa5afda03d7756657a40bf | 3,653,653 |
from numpy.linalg import norm
def normalize(v):
"""
Calculate normalized vector
:param v: input vector
:return: normalized vector
"""
return v/norm(v) | 0ade14b6136e5f55410f6d4cc3fb5b466fa60566 | 3,653,654 |
import re
def replace_hyphen_by_romaji(text):
"""
長音「ー」などを仮名に置換する。
"""
# error check
if len(text) < 2:
return ""
while "-" in list(text) or "~" in list(text):
text_ = text
if (text[0] == "-" or text[0] == "~") and len(text) >= 2:
text = text[2:]
... | 9e2d7216bbd751f49ed54519f5eaf8d516ae8025 | 3,653,655 |
def aucroc_ic50(df,threshold=500):
"""
Compute AUC ROC for predictions and targets in DataFrame, based on a given threshold
Parameters
----------
df : pandas.DataFrame with predictons in column "preds" and targets in column "targs" in nM
threshold: float, binding affinty threshold for binders in... | d4535bc493bcaca45fa9ba739135261b9d514aa2 | 3,653,656 |
def infer_getattr(node, context=None):
"""Understand getattr calls
If one of the arguments is an Uninferable object, then the
result will be an Uninferable object. Otherwise, the normal attribute
lookup will be done.
"""
obj, attr = _infer_getattr_args(node, context)
if (
obj is uti... | 593435273bf57430ab96034772ef38694a491813 | 3,653,657 |
def get_plugin(molcapsule: 'PyObject *', plug_no: 'int') -> "PyObject *":
"""get_plugin(molcapsule, plug_no) -> PyObject *"""
return _libpymolfile.get_plugin(molcapsule, plug_no) | b66687947619808a410d603df70895845afb4d16 | 3,653,658 |
def fake_redis_con():
"""
Purpose:
Create Fake Redis Connection To Test With
Args:
N/A
Return:
fake_redis_con (Pytest Fixture (FakeRedis Connection Obj)): Fake redis connection
that simulates redis functionality for testing
"""
return fakeredis.FakeStrictRedi... | 10d8e340e60e3d591473e942b2273871e6dcaebe | 3,653,659 |
import inspect
def verbose(function, *args, **kwargs):
"""Improved verbose decorator to allow functions to override log-level
Do not call this directly to set global verbosrity level, instead use
set_log_level().
Parameters
----------
function - function
Function to be decorated to a... | 7c2b2d8e827b6d60120b764fe964aa7e9c7b3f41 | 3,653,660 |
import torch
def bittensor_dtype_to_torch_dtype(bdtype):
""" Translates between bittensor.dtype and torch.dtypes.
Args:
bdtype (bittensor.dtype): bittensor.dtype to translate.
Returns:
dtype: (torch.dtype): translated torch.dtype.
"""
if bdtype == bittensor.proto.... | b0d6ccae56ed871224c8c45bd8aaff61846c99fa | 3,653,661 |
def read_all(dataset, table):
"""Read all data from the API, convert to pandas dataframe"""
return _read_from_json(
CFG.path.replace("data", dataset=dataset, table=table, converter="path")
) | d40016f8d8356795b9f6451b165410c25a79627c | 3,653,662 |
def compute_spectrum_welch(sig, fs, avg_type='mean', window='hann',
nperseg=None, noverlap=None,
f_range=None, outlier_percent=None):
"""Compute the power spectral density using Welch's method.
Parameters
-----------
sig : 1d or 2d array
Tim... | e7856e370d7783628afdea9777a693c4c72e2dfd | 3,653,663 |
def _function_set_name(f):
"""
return the name of a function (not the module)
@param f function
@return name
.. versionadded:: 1.1
"""
name = f.__name__
return name.split(".")[-1] | e1b73fbc520c7d9745872b0cd19766d42c027d15 | 3,653,664 |
from typing import Sequence
from pathlib import Path
from typing import Optional
from typing import Callable
from typing import Set
def _notes_from_paths(
paths: Sequence[Path],
wiki_name: str,
callback: Optional[Callable[[int, int], None]]) -> Set[TwNote]:
"""
Given an iterable of paths, compile ... | d522aaf2db500864eba78a4f2bd0fdfbf83051f0 | 3,653,665 |
def load_matrix(file_matrix, V):
"""load matrix
:param file_matrix: path of pre-trained matrix (output file)
:param V: vocab size
:return: matrix(list)
"""
matrix = [[0 for _ in range(V)] for _ in range(V)]
with open(file_matrix) as fp:
for line in fp:
target_id, context... | 0a7aa27638bdc223d9860b9e39aa9b6089e59a0f | 3,653,666 |
def add(*args):
"""Adding list of values"""
return sum(args) | 9bc68771c10b537f0727e76cc07297e7d0311a5d | 3,653,667 |
import pytz
from datetime import datetime
def get_chart_dates(df, start_date=None, end_date=None, utc=True, auto_start=None, auto_end=None):
"""
Get dates for chart functions.
More info on date string formats at: https://strftime.org/
Parameters:
df : The dataframe for the chart, ne... | 603b8e2cea59a52104941da7f3526e4c38b94c16 | 3,653,668 |
import time
import sys
from pathlib import Path
import os
import yaml
def run_benchmark_suite(analyser, suite, verbose, debug, timeout, files, bench):
""" Run an analyzer (like Mythril) on a benchmark suite.
:param analyser: BaseAnalyser child instance
:param suite: Name of test suite
:param verbose: ... | a6e2833805b8b4034215709851ce3a16cfd1f13d | 3,653,669 |
def Eip1(name, ospaces, index_key=None):
"""
Return the tensor representation of a Fermion ionization
name (string): name of the tensor
ospaces (list): list of occupied spaces
"""
terms = []
for os in ospaces:
i = Idx(0, os)
sums = [Sigma(i)]
tensors = [Tensor([i], n... | 3b118106e0c0839549edb5556215241bd3b5f8d4 | 3,653,670 |
import logging
def load_rtma_data(rtma_data, bbox):
"""
Load relevant RTMA fields and return them
:param rtma_data: a dictionary mapping variable names to local paths
:param bbox: the bounding box of the data
:return: a tuple containing t2, rh, lats, lons
"""
gf = GribFile(rtma_data['... | 1e97228b613dc42fb51c29ace44c306ea81052cb | 3,653,671 |
import traceback
import six
def serialize_remote_exception(failure_info, log_failure=True):
"""Prepares exception data to be sent over rpc.
Failure_info should be a sys.exc_info() tuple.
"""
tb = traceback.format_exception(*failure_info)
failure = failure_info[1]
if log_failure:
LOG.... | 2ba794797362b7761a0dc6cbf58851a60a50cc0c | 3,653,672 |
import itertools
import shlex
def combine_arg_list_opts(opt_args):
"""Helper for processing arguments like impalad_args. The input is a list of strings,
each of which is the string passed into one instance of the argument, e.g. for
--impalad_args="-foo -bar" --impalad_args="-baz", the input to this function is
... | 77cfc6fa54201083c2cb058b8a9493b7d020273e | 3,653,673 |
def in_data():
"""Na funçao `in_data` é tratado os dados da matriz lida do arquivo txt."""
points = {}
i, j = map(int, file.readline().split(' '))
for l in range(i):
line = file.readline().split(' ')
if len(line)==j:
for colun in range(len(line)):
if line[col... | 423b96cda6802fdfb23a36aa486b7e067999a60d | 3,653,674 |
def doom_action_space_extended():
"""
This function assumes the following list of available buttons:
TURN_LEFT
TURN_RIGHT
MOVE_FORWARD
MOVE_BACKWARD
MOVE_LEFT
MOVE_RIGHT
ATTACK
"""
space = gym.spaces.Tuple((
Discrete(3), # noop, turn left, turn right
Discrete... | 27ceab538f9a7102724a81ae1f692340c3b5e2e6 | 3,653,675 |
def svn_auth_provider_invoke_first_credentials(*args):
"""
svn_auth_provider_invoke_first_credentials(svn_auth_provider_t _obj, void provider_baton, apr_hash_t parameters,
char realmstring, apr_pool_t pool) -> svn_error_t
"""
return _core.svn_auth_provider_invoke_first_credentials(*args) | 951d2554df8efa4e392668c743f2b3f51cab2f48 | 3,653,676 |
def kill_process(device, process="tcpdump", pid=None, sync=True, port=None):
"""Kill any active process
:param device: lan or wan
:type device: Object
:param process: process to kill, defaults to tcpdump
:type process: String, Optional
:param pid: process id to kill, defaults to None
:type ... | be3947e624d1d2e8ca4015480a07bde67475c721 | 3,653,677 |
def get_sentence(soup, ets_series, cache, get_verb=False):
"""
Given an ETS example `ets_series`, find the corresponding fragment, and
retrieve the sentence corresponding to the ETS example.
"""
frg = load_fragment(soup, ets_series.text_segment_id, cache)
sentence = frg.find('s', {'n': ets_serie... | 1a39307d973a5fb93fea7b100f03d0797af1f1ef | 3,653,678 |
def PreAuiNotebook(*args, **kwargs):
"""PreAuiNotebook() -> AuiNotebook"""
val = _aui.new_PreAuiNotebook(*args, **kwargs)
val._setOORInfo(val)
return val | 29400857cdca1fa42058d4200111bd7eeae8410b | 3,653,679 |
def get_nsx_security_group_id(session, cluster, neutron_id):
"""Return the NSX sec profile uuid for a given neutron sec group.
First, look up the Neutron database. If not found, execute
a query on NSX platform as the mapping might be missing.
NOTE: Security groups are called 'security profiles' on the ... | 0b02a7f90d2e9e9d5917612280ed00ebfcab7f93 | 3,653,680 |
def customiseGlobalTagForOnlineBeamSpot(process):
"""Customisation of GlobalTag for Online BeamSpot
- edits the GlobalTag ESSource to load the tags used to produce the HLT beamspot
- these tags are not available in the Offline GT, which is the GT presently used in HLT+RECO tests
- not loading t... | 8d0a8a0fa8e48e597dc4be910c6d9281e5ab4ae2 | 3,653,681 |
def path_to_filename(username, path_to_file):
""" Converts a path formated as path/to/file.txt to a filename, ie. path_to_file.txt """
filename = '{}_{}'.format(username, path_to_file)
filename = filename.replace('/','_')
print(filename)
return filename | a29e98db8ac4cd7f39e0f0e7fc1f76e72f5fa398 | 3,653,682 |
from typing import List
def _convert_artist_format(artists: List[str]) -> str:
"""Returns converted artist format"""
formatted = ""
for x in artists:
formatted += x + ", "
return formatted[:-2] | 66f8afb0eb09e9a66eaa728c28576bb0e5a496d3 | 3,653,683 |
def slerp(val, low, high):
"""
Spherical interpolation. val has a range of 0 to 1.
From Tom White 2016
:param val: interpolation mixture value
:param low: first latent vector
:param high: second latent vector
:return:
"""
if val <= 0:
return low
elif val >= 1:
... | 499b192a90475fc3b4a888270159e98cbfa449fd | 3,653,684 |
import json
async def verify_input_body_is_json(
request: web.Request, handler: Handler
) -> web.StreamResponse:
"""
Middleware to verify that input body is of json format
"""
if request.can_read_body:
try:
await request.json()
except json.decoder.JSONDecodeError:
... | 7c424b941d3a86e95029f60759b0f47c3d1c44d3 | 3,653,685 |
def svn_repos_get_logs4(*args):
"""
svn_repos_get_logs4(svn_repos_t repos, apr_array_header_t paths, svn_revnum_t start,
svn_revnum_t end, int limit, svn_boolean_t discover_changed_paths,
svn_boolean_t strict_node_history,
svn_boolean_t include_merged_revisions,
apr_array_heade... | 6363e6846e7a1788eef769b529e641c14b4f0525 | 3,653,686 |
def linreg_predict(model, X, v=False):
"""
Prediction with linear regression
yhat[i] = E[y|X[i, :]], model]
v[i] = Var[y|X[i, :], model]
"""
if 'preproc' in model:
X = preprocessor_apply_to_test(model['preproc'], X)
yhat = X.dot(model['w'])
return yhat | 5b326bf06b8061e86c5b4ebc5cf2d5e43cadcd1c | 3,653,687 |
def parse_hostportstr(hostportstr):
""" Parse hostportstr like 'xxx.xxx.xxx.xxx:xxx'
"""
host = hostportstr.split(':')[0]
port = int(hostportstr.split(':')[1])
return host, port | 7d67b548728d8cc159a7baa3e5f419bf7cbbc4d3 | 3,653,688 |
def sigmoid_grad_input(x_input, grad_output):
"""sigmoid nonlinearity gradient.
Calculate the partial derivative of the loss
with respect to the input of the layer
# Arguments
x_input: np.array of size `(n_objects, n_in)`
grad_output: np.array of size `(n_objects, n_in)`
... | f397cdb3c9608fa09c5053e27e57525e2a8e3ba5 | 3,653,689 |
def f_is3byte(*args):
"""f_is3byte(flags_t F, void ?) -> bool"""
return _idaapi.f_is3byte(*args) | 9fb9f351a4d595c7ecde83492d92911cd646bc0a | 3,653,690 |
def make_desired_disp(vertices, DeformType = DispType.random, num_of_vertices = -1):
"""
DispType.random: Makes a random displacement field. The first 3 degrees of freedom are assumed to
be zero in order to fix rotation and translation of the lattice.
DispType.isotropic: Every point moves towards the ... | 90697baa3879f22cb400c1da0923fc611d43a72c | 3,653,691 |
import os
import subprocess
def unix_sort_ranks(corpus: set,
tmp_folder_path: str):
"""
Function that takes a corpus sorts it with the unix sort -n command and generates the global ranks
for each value in the corpus.
Parameters
----------
corpus: set
The corpus (al... | 03602684aca066fae93caa95b368641561e16c2e | 3,653,692 |
def do_filter():
"""Vapoursynth filtering"""
opstart_ep10 = 768
ncop = JPBD_NCOP.src_cut
ep10 = JPBD_10.src_cut
ncop = lvf.rfs(ncop, ep10[opstart_ep10:], [(0, 79), (1035, 1037)])
return ncop | 30d605e2267875eaaa4506bc27b0df380a0e48d1 | 3,653,693 |
def test_returns_less_than_expected_errors(configured_test_manager):
"""A function that doesn't return the same number of objects as specified in the stage outputs should throw an OutputSignatureError."""
@stage([], ["test1", "test2"])
def output_stage(record):
return "hello world"
record = Re... | 6f88de961911f6bc862619e67f2d72a520f2ca90 | 3,653,694 |
import pickle
def xgb(validate = True):
"""
Load XGB language detection model.
Parameters
----------
validate: bool, optional (default=True)
if True, malaya will check model availability and download if not available.
Returns
-------
LANGUAGE_DETECTION : malaya._models._sklear... | 87de42a5957facbc057ecf024334b307df09b19f | 3,653,695 |
import csv
import math
def get_current_data(csv_file):
"""
Gathers and returns list of lists of current information based in hourly data from NOAA's National Data Buoy Center
archived data. Returned list format is [current depths, current speeds, current directions].
Input parameter is any CSV or text... | f217d66a40466f8bcc590f0cc61fc8c3687b63da | 3,653,696 |
from typing import Optional
from typing import Union
from typing import Sequence
from typing import List
def _get_batched_jittered_initial_points(
model: Model,
chains: int,
initvals: Optional[Union[StartDict, Sequence[Optional[StartDict]]]],
random_seed: int,
jitter: bool = True,
jitter_max_r... | 2ba3573f26922cec0cd4a76646bc1d5ad96051b4 | 3,653,697 |
import warnings
import copy
def load_schema(url, resolver=None, resolve_references=False,
resolve_local_refs=False):
"""
Load a schema from the given URL.
Parameters
----------
url : str
The path to the schema
resolver : callable, optional
A callback function ... | b937d56eb7b23a530758327fbf463adb63be4cf4 | 3,653,698 |
def fastaDecodeHeader(fastaHeader):
"""Decodes the fasta header
"""
return fastaHeader.split("|") | 06f0af70765670dafa0b558867e2d9094c3d928b | 3,653,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.