content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_dataset(opts):
""" Dataset And Augmentation
"""
if opts.dataset == 'camvids':
mean, std = camvids.get_norm()
train_transform = train_et.ExtCompose([
# et.ExtResize(size=opts.crop_size),
train_et.ExtRandomScale((0.5, 2.0)),
train_et.ExtRandomHorizo... | 046d2ebdf9a0b1be37fea052fbf07e14a623ab1e | 3,652,900 |
def gen_sankey_diagram_distribute_query(query_statement, params, final_entites_name):
"""
桑基图数据分布查询
:param query_statement:
:param params:
:param final_entites_name:
:return:
"""
query_statement = dgraph_get_project_count(query_statement)
# 第一层的节点
first_level_sql = """select a.c... | 7d87157ca289928bfe8f8bcdfb7cbc6cbee6e521 | 3,652,901 |
def declare(objective:str, displayname:str=None, criteria:str="dummy"):
"""
objective:str -> The id/name given to a scoreboard
displayname:str -> The name that will be displayed on screen
criteria:str -> The criteria of the scoreboard
"""
f = f"scoreboard objectives add {objective} {criteria}"
... | 0a574741a51afa27799b917e735657e3cb34b072 | 3,652,902 |
def complement_angle(angle):
""" 90 minus angle, in degrees"""
return 90 - angle; | bca1dfa3158df61e87cbadc47307f68298a237b7 | 3,652,903 |
def parse_custom_commands(command, separator=";"):
"""Parse run custom command string into the commands list
:param str command: run custom [config] command(s)
:param str separator: commands separator in the string
:rtype: list[str]
"""
if not command:
return []
return command.stri... | 4d55ef149aa16e224f5894fb0ef506a1bd8285f3 | 3,652,904 |
def lower_volatility_band(c, dev_target, band_target, center_target):
"""
| Calculates the lower volatility band
| Name: lower\_volatility\_band\_\ **c**\ \_times\_\ **band_target.name**\ &\ **dev_target.name**\ \_over\_\ **center_target.name**
:param c: Multiplier constant
:type c: float
:para... | d910c1f9e14fa28b171dd16e937fa65c220839d7 | 3,652,905 |
def find_by_attr(node, value, name="name", maxlevel=None):
"""Identical to :any:`search.find_by_attr` but cached."""
return search.find_by_attr(node, value, name=name, maxlevel=maxlevel) | 3d4d5084762fe25572e06eeb56fd4374d91dc4c8 | 3,652,906 |
import logging
import os
import json
import subprocess
import psutil
import signal
def training(request):
""" Function: training
* training top
"""
def _get_selected_object():
project_name = request.session.get('training_view_selected_project', None)
selected_project = Project.objects... | 0a9d0c63eba7572801e4483c8cada287a6481c36 | 3,652,907 |
import time
def remind(phenny, input):
"""Set a reminder"""
m = r_command.match(input.bytes)
if not m:
return phenny.reply("Sorry, didn't understand the input.")
length, scale, message = m.groups()
length = float(length)
factor = scaling.get(scale, 60)
duration = length * factor... | 21edf68ccb4f914325d4bb44177efb5fa44c14ac | 3,652,908 |
import glob
from pathlib import Path
def get_timestamps_from_sensor_folder(sensor_folder_wildcard: str) -> NDArrayInt:
"""Timestamp always lies at end of filename.
Args:
sensor_folder_wildcard: string to glob to find all filepaths for a particular
sensor files within a single log ... | 2e1bd2e7b568c83aac0ef1c1f81ce4bcb8f3fe1e | 3,652,909 |
import matplotlib.pyplot as plt
def plot(topography, subplot_location=111):
"""
Plot an image of the topography using matplotlib.
Parameters
----------
topography : :obj:`SurfaceTopography`
Height information
"""
# We import here because we don't want a global dependence on matplo... | fa6998cc18aa71bc9249f8ffb4254e04d4feb001 | 3,652,910 |
def vehicles_missing(request):
"""
Displays to users their theft reports
"""
reports = TheftReport.objects.all()
return render(request, "vms/theft_reports.html", {
'reports': reports,
}) | 254eb4ead3f058f10de8401263f354ef8690451c | 3,652,911 |
import os
import sys
def isfile(path):
"""
Test for existence of input file.
"""
if not os.path.isfile(path):
log("Input file not found: %s" % path)
sys.exit(1)
else:
return os.path.abspath(path) | bf6a3b5b56714ef6a75ad5a7772c99fc932e05fa | 3,652,912 |
def get_limits(data):
""" Get the x, y ranges of the ST data.
"""
y_min = 1e6
y_max = -1e6
x_min = 1e6
x_max = -1e6
for doc in data:
x = doc["x"]
y = doc["y"]
y_min = y if y < y_min else y_min
y_max = y if y > y_max else y_max
x_min = x if x < x_min e... | 9e2894626b9de59e94d65affa0a1d1c6f30e6399 | 3,652,913 |
def get_bool(prompt: str | None = None, default: bool = False) -> bool:
"""Gets a boolean response from the command line.
:param prompt: Input prompt.
:param default: Default value used if no characters are typed.
:return: Input boolean.
"""
input_str = input(_prompt_from_message(prompt, defau... | c9504afe8500a99dcf80f5f95b8a1754dc881cd2 | 3,652,914 |
def proj_helsinki(x, y):
"""Project Helsinki coordinates into ETRS-GK25 (EPSG:3879).
https://www.hel.fi/helsinki/fi/kartat-ja-liikenne/kartat-ja-paikkatieto/paikkatiedot+ja+-aineistot/koordinaatistot_ja+_korkeudet/koordinaatti_ja_korkeusjarjestelmat # pylint: disable=line-too-long
"""
# pylint: disable... | d1dc6cc314e767cc971c6b8695d2a4c4043b608a | 3,652,915 |
def _check_start_stop(raw, start, stop):
"""Aux function."""
out = list()
for st in (start, stop):
if st is None:
out.append(st)
else:
try:
out.append(_ensure_int(st))
except TypeError: # not int-like
out.append(raw.time_as... | 2d7c59fff70c7b43942060b353dcd1c7ae917443 | 3,652,916 |
import json
def main(function, js):
"""Console script for es_reindex."""
args = json.loads(js)
config = args['config']
# e.g. --json='{"config": "./es_index_tool/data/example_config.json"}'
tool = ESIndexTool(config_path=config)
if 'id' not in args:
tool.reindex()
else:
# e... | 42cf4b0c33c7a58fb521357089a29195c0f04a91 | 3,652,917 |
def read(
datapath,
qt_app=None,
dataplus_format=True,
gui=False,
start=0,
stop=None,
step=1,
convert_to_gray=True,
series_number=None,
use_economic_dtype=True,
dicom_expected=None,
orientation_axcodes="original",
**kwargs
):
"""Returns 3D data and its metadata.
... | 8ed8c33a1e7bb61aa9f06b573f2f85fc6a96481b | 3,652,918 |
def sum_squares2(n):
"""
Returns: sum of squares from 1 to n-1
Example: sum_squares(5) is 1+4+9+16 = 30
Parameter n: The number of steps
Precondition: n is an int > 0
"""
# Accumulator
total = 0
print('Before while')
x = 0
while x < n:
print('Start loo... | 1d5dfe160568f032184eea723138b8d6dd3929fc | 3,652,919 |
import os
def make_bgm(
music_path_list: list,
output_dir: str,
output_tmp_filename: str,
music_total_time: int = 0,
fade_time: list = [1000, 1000],
) -> str:
"""
调整BGM时长以适应视频
Args:
music_path_list (list): BGM文件的存放路径
output_dir (str): 转换过后BGM文件的输出路径
output_tmp_... | 89bddccd2844907ed3705f3db1e9c039a3aa3a5d | 3,652,920 |
def read_image(src):
"""Read and resize individual images"""
im = cv2.imread(src, cv2.IMREAD_COLOR)
im = cv2.resize(im, (COLS, ROWS), interpolation=cv2.INTER_CUBIC)
return im | cf3d31691ad0814c15fe635d03f2febee0150723 | 3,652,921 |
def add_db_entry():
"""
Store received data to database if validation is okay
:return: validation information and error code
"""
data = request.get_json()
app.logger.debug("Received Data (POST)")
app.logger.debug(pformat(data))
# Make sure the data is valid
validation, err_... | 639d5777285c9f5b04edbdd7e0000f941fb32c8f | 3,652,922 |
def pattern_classifier(data, pattern_threshold):
"""Return an array mask passing our selection."""
return data["key_pattern"] > pattern_threshold | 116a7f84a18b57188fb2ce24fa7ecacd1b61c3da | 3,652,923 |
def is_scalar(a) -> bool:
"""
Tests if a python object is a scalar (instead of an array)
Parameters
----------
a : object
Any object to be checked
Returns
-------
bool
Whether the input object is a scalar
"""
if isinstance(a, (list, tuple)):
return False... | 29206a7921da74257e6af66311c0bbfc4b576ac0 | 3,652,924 |
def median(ts: TimeSeries, /, window_length: int = 3) -> TimeSeries:
"""
Calculate a moving median.
On n-dimensional data, filtering occurs on the first axis (time).
Parameters
----------
ts
Input TimeSeries
window_length
Optional. Kernel size, must be odd. The default is ... | 93017c2da815687faf386beabd55a6ff4eaa674a | 3,652,925 |
import logging
def execute_read_query(connection, query):
"""Execute a read query on the postgres database.
Args:
connection (Psycopg2 Connection): The connection to the postgres database.
query (string): The SQL query to be run.
Returns:
list(tuples): The results of the SQL quer... | 8b632b7e27948f751a54b07b0fda1a6fcf683806 | 3,652,926 |
import os
def extract_strings_from_file(filename):
"""
extracts strings from a provided filename
Returns the a list of extracted strings found in a provided filename.
Entries are stripped when processing and lines leading with a comment are
ignored.
Args:
filename: the filename
... | 7288250ee6682068d7d5217ce0a3030d03f4ca30 | 3,652,927 |
import math
import copy
def convert_polynomial_coefficients(A_in, B_in, C_in, D_in, oss=False, inverse=False,
parent_aperture=None):
"""Emulate some transformation made in nircam_get_polynomial_both.
Written by Johannes Sahlmann 2018-02-18, structure largely based on nirca... | 3b1e85c0416a9a16c5c648a34704c13570ea9ee3 | 3,652,928 |
def spinner_runner_factory(spec, t_compile, extra_commands):
"""Optimized spinner runner, which receives the spec of an animation, and controls
the flow of cycles and frames already compiled to a certain screen length and with
wide chars fixed, thus avoiding any overhead in runtime within complex spinners,
... | 887af0abc7f11dcf56edb5cda7de136bb95cf6b8 | 3,652,929 |
def _project_im_rois(im_rois, im_scale_factor, im_crop):
"""Project image RoIs into the rescaled training image."""
im_rois[:, 0] = np.minimum(
np.maximum(im_rois[:, 0], im_crop[0]), im_crop[2])
im_rois[:, 1] = np.minimum(
np.maximum(im_rois[:, 1], im_crop[1]), im_crop[3])
im_rois[:, 2] ... | 596d9baa12708e1adcc9a034c34d4b751ef7e73a | 3,652,930 |
from typing import List
from typing import Tuple
def evaluate_error_absolute(poses_to_test: List[Tuple[str, kapture.PoseTransform]],
poses_ground_truth: List[Tuple[str, kapture.PoseTransform]]
) -> List[Tuple[str, float, float]]:
"""
Evaluate the absolut... | 45ef1335074514837a72be159f8e55f229676779 | 3,652,931 |
def restricted_offset(parent_dimensions, size, offset):
""" Get offset restricted by various factors
"""
limit_x = (parent_dimensions[0] - size[0]) / 2
limit_y = (parent_dimensions[1] - size[1]) / 2
x = clamp(offset[0], -limit_x, limit_x)
y = clamp(offset[1], -limit_y, limit_y)
return x, y | 8e8f16f2267c2ddefda896db9e4905836030f24e | 3,652,932 |
def wt_sgrna(target='none'):
"""
Return the wildtype sgRNA sequence.
The construct is composed of 3 domains: stem, nexus, and hairpins. The
stem domain encompasses the lower stem, the bulge, and the upper stem.
Attachments are allowed pretty much anywhere, although it would be prudent
to r... | 72d07c10defa52529818217c495d44f8fb66062e | 3,652,933 |
import csv
def export_nodes(nodes, csvfilepath):
"""
Writes the standard nodes data in `nodes` to the CSV file at `csvfilepath`.
"""
with open(csvfilepath, "w") as csv_file:
csvwriter = csv.DictWriter(csv_file, STANDARD_NODE_HEADER_V0)
csvwriter.writeheader()
for node in nodes:... | d84658904a848993237e8571412ca3a3860be999 | 3,652,934 |
def _var_network(graph,
add_noise=True,
inno_cov=None,
invert_inno=False,
T=100,
initial_values=None):
"""Returns a vector-autoregressive process with correlated innovations.
Useful for testing.
Example:
graph=num... | ca7c327f4052f44cdcfd60e628f8f53f4e411162 | 3,652,935 |
def build_features(component, borders, initial_group):
"""
Integrate peaks within similarity components and build features
:param component: a groupedROI object
:param borders: dict - key is a sample name, value is a (n_borders x 2) matrix;
predicted, corrected and transformed to normal values b... | 2070741b58c7c04b3a929747407c9dcd9caa025b | 3,652,936 |
def get_cred_fh(library: str) -> str:
"""
Determines correct SimplyE credential file
"""
if library == "BPL":
return ".simplyE/bpl_simply_e.yaml"
elif library == "NYPL":
return ".simplyE/nyp_simply_e.yaml"
else:
raise ValueError("Invalid library code passsed") | aefea283c171963778bdc34ddf2f2aeb18fd126d | 3,652,937 |
def create_app(enviornment):
"""Construct the core application."""
app = Flask(__name__, static_url_path = "")
app.config.from_object(Config)
if enviornment == 'test':
app.config['TESTING'] = True
return app
db.init_app(app)
with app.app_context():
# Imports
#... | 7b4169adfbcca18a8373ca74cc95691438318837 | 3,652,938 |
def weighted_percentiles(a, percentiles, weights=None):
"""Compute weighted percentiles by using interpolation of the weighted ECDF.
Parameters
----------
a : np.ndarray
Vector of data for computing quantiles
percentiles : np.ndarray
Vector of percentiles in [0, 100]
weights... | 1ffda97f48e4223e3c54167e99af1952b357573a | 3,652,939 |
def default_summary_collector():
"""
Get the :class:`SummaryCollector` object at the top of context stack.
Returns:
SummaryCollector: The summary collector.
"""
return _summary_collect_stack.top() | 98a547f73a6c96bc3e33331ad64430da7f19c1e2 | 3,652,940 |
def norm(*args, **kwargs):
""" See https://www.tensorflow.org/versions/master/api_docs/python/tf/norm .
"""
return tensorflow.norm(*args, **kwargs) | 95a03e8267453db6e8c2ece0a2d45131c4fcb9a9 | 3,652,941 |
import sys
def read_fasta(input_fasta):
"""Return a list of seqeunces from a given FASTA file."""
try:
seq = []
records = []
is_fasta = False
with open_fasta(input_fasta) as fasta_fh:
for line in fasta_fh:
line = line.rstrip()
if line... | 5e37feac53bf2c5e363ff241789759f5e2a2213a | 3,652,942 |
from typing import Optional
from typing import Sequence
def get_steering_policies(compartment_id: Optional[str] = None,
display_name: Optional[str] = None,
display_name_contains: Optional[str] = None,
filters: Optional[Sequence[pulumi.Input... | 6919dc3e155854db5ac0838635cb20f691a423d3 | 3,652,943 |
def res_input_matrix_random_sparse(idim = 1, odim = 1, density=0.1, dist = 'normal'):
"""reservoirs.res_input_matrix_random_sparse
Create a sparse reservoir input matrix. Wrapper for
create_matrix_sparse_random.
Arguments:
idim: input dimension
odim: hidden dimension
density: density
d... | d7d1f986228ea982d01010080dfb7749444c31c2 | 3,652,944 |
import six
def _MakeApiMap(root_package, api_config):
"""Converts a map of api_config into ApiDef.
Args:
root_package: str, root path of where generate api will reside.
api_config: {api_name->api_version->{discovery,default,version,...}},
description of each api.
Returns:
{api_name-... | 1e44188d1cced2255ca4e30efc36631bda305b57 | 3,652,945 |
def make_election_frame(votes, shares=None, party_names=None, margin_idx=None):
"""
Constructs an election frame from at most two arrays.
If provided,
"""
if votes.ndim == 1:
votes = votes.reshape(-1,1)
if votes.shape[-1] == 1 and shares is not None:
votes, shares = votes, shares... | d165e32b61c23522dfadab4ac04e438b2d7710dd | 3,652,946 |
import json
def payload_from_api_post_event(event):
"""Maps an API event to the expected payload"""
# event = {
# 'timeserie1': [(1, 100), (2, 100)],
# 'timeserie2': [(3, 100), (4, 100)],
# }
body = json.loads(event['body'])
return body | 897a3d2e846e7bbf96d0acd288924d96b07acc78 | 3,652,947 |
def format_link_header(link_header_data):
"""Return a string ready to be used in a Link: header."""
links = ['<{0}>; rel="{1}"'.format(data['link'], data['rel'])
for data in link_header_data]
return ', '.join(links) | 9a68ff381d51e6e10fe257d2d2d6766295ffc050 | 3,652,948 |
def parse_collection_members(object_: dict) -> dict:
"""Parse the members of a collection to make it easier
to insert in database.
:param object_: The body of the request having object members
:type object_: dict
:return: Object with parsed members
:rtype: dict
"""
members = list()
... | 6d5a99c9346cd2f8bf3a00c13ab291c7b972abdc | 3,652,949 |
def PoissonWasserstein_S2(tau, rho, function1, function2, numerical=False):
""" Computes the Poisson bracket of two linear functionals on the space P^{OO}(S^2), of measures with a smooth
positive density function on the 2-sphere S^2, at a measure in P^{OO}(S^2).
The Poisson bracket on P^{... | 7cb3884ecc665ced43c30dae1dca3c4f4f00af4d | 3,652,950 |
def poly_in_gdf():
""" Fixture for a bounding box polygon. """
return make_poly_in_gdf() | bf57298bc002aababa8df30b90dbbe7b91858afc | 3,652,951 |
from typing import List
def apply_inclusion_exclusion_criteria(
df: pd.DataFrame, col: str, criteria: List[List[str], List[str]]
) -> pd.Series:
"""Filter out files based on `criteria`, a nested list of row values to include or exclude, respectively
:param df: dataframe to filter
:type df: pd.DataFra... | eb8060d8d9d06a798a8617935ff8506698e63a33 | 3,652,952 |
import re
def prune_string(string):
"""Prune a string.
- Replace multiple consecutive spaces with a single space.
- Remove spaces after open brackets.
- Remove spaces before close brackets.
"""
return re.sub(
r" +(?=[\)\]\}])",
"",
re.sub(r"(?<=[\(\[\{]) +", "", re.sub... | 53a2c00f50c16b568a75e59bc32a124a5f152b4a | 3,652,953 |
def detect_face(MaybeImage):
"""
Take an image and return positional information for the largest face in it.
Args:
MaybeImage: An image grabbed from the local camera.
Returns:
Maybe tuple((bool, [int]) or (bool, str)): True and list of positional
coordinates of the largest face found. False ... | 3b530f7de671fe3d26f3f50adcead639c45be78c | 3,652,954 |
def compute_TVL1(prev, curr, bound=15):
"""Compute the TV-L1 optical flow."""
TVL1 = cv2.DualTVL1OpticalFlow_create()
flow = TVL1.calc(prev, curr, None)
assert flow.dtype == np.float32
flow = (flow + bound) * (255.0 / (2 * bound))
flow = np.round(flow).astype(int)
flow[flow >= 255] = 255
... | 9020667c141c9be8034c330c9a4943a32b3f3195 | 3,652,955 |
def _un_partial_ize(func):
"""
Alter functions working on 1st arg being a callable, to descend it if it's a partial.
"""
@wraps(func)
def wrapper(fn, *args, **kw):
if isinstance(fn, (partial, partialmethod)):
fn = fn.func
return func(fn, *args, **kw)
return wrapper | acb9409ed8fa08e8a1f915b504b073b390fa4520 | 3,652,956 |
import json
import requests
def search_full_text(text, ipstreet_api_key):
"""sends input text to /full_text semantic search endpoint. returns json results"""
endpoint = 'https://api.ipstreet.com/v2/full_text'
headers = {'x-api-key': ipstreet_api_key}
payload = json.dumps({'raw_text': str(text),
... | 7112e04698dcfaf3072b30d0085fa2dc18043f76 | 3,652,957 |
def main(filename, plotDir='Plots/'):
"""
"""
# Which pixels and sidebands?
pixelOffsets = Pointing.GetPixelOffsets('COMAP_FEEDS.dat')
# READ IN THE DATA
d = h5py.File(filename)
tod = d['spectrometer/tod']
mjd = d['spectrometer/MJD'][:]
if len(d['pointing/az'].shape) > 1:
... | 9f059f49222ed8983008f32e5e7edbc303dc1328 | 3,652,958 |
def add_rows(df, row_list=[], column_list=[], append=False):
"""
add a list of rows by index number for a wide form dataframe
"""
df = df.filter(items=row_list, axis=0)
df = pd.DataFrame(df.sum()).T
return df | 3620e625716e7570e095efd219b2505f8fb89413 | 3,652,959 |
from typing import OrderedDict
def coerce_data_type_value(context, presentation, data_type, entry_schema, constraints, value, # pylint: disable=unused-argument
aspect):
"""
Handles the ``_coerce_data()`` hook for complex data types.
There are two kinds of handling:
1. If w... | 521d022c5aead7f4066b637bbe6a84a07d4e728e | 3,652,960 |
def Inst2Vec(
bytecode: str, vocab: vocabulary.VocabularyZipFile, embedding
) -> np.ndarray:
"""Transform an LLVM bytecode to an array of embeddings.
Args:
bytecode: The input bytecode.
vocab: The vocabulary.
embedding: The embedding.
Returns:
An array of embeddings.
"""
embed = lambda x: ... | 4c56c4b35b51ce4b41f203579ca0c8d552c18b0c | 3,652,961 |
import _ast
def extract_from_code(code, gettext_functions):
"""Extract strings from Python bytecode.
>>> from genshi.template.eval import Expression
>>> expr = Expression('_("Hello")')
>>> list(extract_from_code(expr, GETTEXT_FUNCTIONS))
[('_', u'Hello')]
>>> expr = Expression('ngett... | eb766056ab08d31d20728717570ffb6deb240e03 | 3,652,962 |
import torch
def sample_raw_locations(stacking_program, address_suffix=""):
"""
Samples the (raw) horizontal location of blocks in the stacking program.
p(raw_locations | stacking_program)
Args
stacking_program [num_blocks]
Returns [num_blocks]
"""
device = stacking_program[0].de... | 8c31f916a36fadf22c86dfe671fa2f7000609f14 | 3,652,963 |
def get_raw_data(params, data_type=1):
"""Method to filter which report user wants."""
# class="table table-bordered"
data = None
raw_data = []
td_zeros = '<td>0</td>' * 12
tblanks = ['M', 'F'] * 6
blanks = ['0'] * 13
csvh = ['0 - 5 yrs', '', '6 - 10 yrs', '', '11 - 15 yrs', '',
... | 235a9cfd73e89bc93626fc3ccc49a02976038187 | 3,652,964 |
import re
def get_existing_cert(server, req_id, username, password, encoding='b64'):
"""
Gets a certificate that has already been created.
Args:
server: The FQDN to a server running the Certification Authority
Web Enrollment role (must be listening on https)
req_id: The re... | b9f4d04a0e30190870880961c100fc71964bf61d | 3,652,965 |
import subprocess
def processCall(*aPositionalArgs, **dKeywordArgs):
"""
Wrapper around subprocess.call to deal with its absense in older
python versions.
Returns process exit code (see subprocess.poll).
"""
assert dKeywordArgs.get('stdout') == None;
assert dKeywordArgs.get('stderr') == No... | 5739837cce29d27a25ad1bbcb0615769b2bc6e69 | 3,652,966 |
def as_sparse_variable(x, name=None):
"""
Wrapper around SparseVariable constructor.
@param x: A sparse matrix. as_sparse_variable reads dtype and format
properties out of this sparse matrix.
@return: SparseVariable version of sp.
@todo Verify that sp is sufficiently sparse, and raise a warning... | 994d1e112eb3080e5cfee0371e6611af9e0b2b15 | 3,652,967 |
def _get_go2parents(go2parents, goid, goterm):
"""Add the parent GO IDs for one GO term and their parents."""
if goid in go2parents:
return go2parents[goid]
parent_goids = set()
for parent_goterm in goterm.parents:
parent_goid = parent_goterm.id
parent_goids.add(parent_goid)
... | e4585bb84a4ac9532468451036a609a1d561c928 | 3,652,968 |
def compute_conditional_statistics(x_test, x, kernel, ind):
"""
This version uses cho_factor and cho_solve - much more efficient when using JAX
Predicts marginal states at new time points. (new time points should be sorted)
Calculates the conditional density:
p(xₙ|u₋, u₊) = 𝓝(Pₙ @ [u₋, u₊... | 458e1d99a739825de8b72fe125bdb00e4a1d7b9f | 3,652,969 |
def int_to_bytes(value: int) -> bytes:
"""
Encode an integer to an array of bytes.
:param value: any integer
:return: integer value representation as bytes
"""
return value.to_bytes(length=BYTES_LENGTH, byteorder=BYTES_ORDER) | 4f7fc878d8632c1ab250e8821f55e280a6be9b9b | 3,652,970 |
def generate_1d_trajectory_distribution(
n_demos, n_steps, initial_offset_range=3.0, final_offset_range=0.1,
noise_per_step_range=20.0, random_state=np.random.RandomState(0)):
"""Generates toy data for testing and demonstration.
Parameters
----------
n_demos : int
Number of demo... | cadc92671b3b89285db9427738dcf2856c97a045 | 3,652,971 |
def encrypt(binary_plaintext, binary_key):
"""Generate binary ciphertext from binary plaintext with AES."""
padded_plaintext = pad_plaintext(binary_plaintext, 128)
subkeys = key_schedule(binary_key)
final_blocks = []
for block in block_split(padded_plaintext, 128):
block_matrix = binary_to_m... | 9bce8326b7b8ba223edbbac0c7eaa79cfdfb7098 | 3,652,972 |
import json
def emit_event(project_slug, action_slug, payload, sender_name, sender_secret,
event_uuid=None):
"""Emit Event.
:param project_slug: the slug of the project
:param action_slug: the slug of the action
:param payload: the payload that emit with action
:param sender_name: ... | 53df17f6194f2e89c4cf9c4a0face05ecf49a588 | 3,652,973 |
def add_item(cart_id: str, item: CartItem):
"""
Endpoint. Add item to cart.
:param str cart_id: cart id
:param CartItem item: pair of name and price
:return: dict with cart, item and price
:rtype: dict
"""
logger.info(f'Request@/add_item/{cart_id}')
return cart.add_item(cart_id=cart... | 623be20b0bd06ff78b9d88295516b56604b276b2 | 3,652,974 |
import warnings
def _inst2earth(advo, reverse=False, rotate_vars=None, force=False):
"""
Rotate data in an ADV object to the earth from the instrument
frame (or vice-versa).
Parameters
----------
advo : The adv object containing the data.
reverse : bool (default: False)
If Tru... | 51949445daf34bb09033136e53ea705abfb8ec50 | 3,652,975 |
import os
def maja_get_subdirectories(search_directory):
"""
Search in search directory all the subdirs
TODO: use logging
:param search_directory:
:type search_directory:
"""
return [os.path.join(search_directory, name) for name in os.listdir(search_directory)
if os.path.is... | f6cae90a4b4732431ed52981a47cb88d6adca821 | 3,652,976 |
import requests
def get_artist_songs_genius(artist_id=None):
"""
Wrapper for the /artists/:id/songs Genius API endpoint
Returns songs for a given artist ID or 1 if an error occurred.
"""
if artist_id is None:
logger.debug("get_artist_song_genius was not passed correct params.")
... | aa9565f0fd29db6d4e8a54a6d4c2e951bdcbb17f | 3,652,977 |
def kepler(k, r, v, tofs, numiter=350, **kwargs):
"""Propagates Keplerian orbit.
Parameters
----------
k : ~astropy.units.Quantity
Standard gravitational parameter of the attractor.
r : ~astropy.units.Quantity
Position vector.
v : ~astropy.units.Quantity
Velocity vector.... | b8760234c1c3b530a810255fee9c816222fb8e86 | 3,652,978 |
from typing import Dict
from typing import List
def get_latency_of_one_partition(
partition: Partition, node_to_latency_mapping: Dict[Node, NodeLatency]
) -> PartitionLatency:
"""Given a partiton and its nodes' latency, return a PartitionLatency for this partition"""
def get_top_nodes(partition: Partitio... | c4d61b5bd49800f7daae54df1226d9798007c4c5 | 3,652,979 |
def nearest_dy(lon,lat,t,gs,dy,tr = [0,0],box = [0,0],time_vec = False,space_array = False):
"""
give this a dy object and a gs object,
the nearest point to the supplied lon lat will be returned
tr is a time range option [time points previous, after]
if tr > 0 time_vec=True will return a rs/H/WAVES/... | 553547a958706cc30fa35248450cf499dc875051 | 3,652,980 |
def get_return_type() -> None:
"""Prompt the user for the return datatype of the function.
:return return_type: {str}
"""
return_type = None # function or method
while return_type is None or return_type == "":
return_type = prompt(
"return type? [bool|dict|float|int|list|str|... | 2f90b037bf1344cb11d8b00e1e3ee210728bbd03 | 3,652,981 |
def solve_capcha(capcha_str):
"""Function which calculates the solution to part 1
Arguments
---------
capcha_str : str, a string of numbers
Returns
-------
total : int, the sum of adjacent matches
"""
capcha = [int(cc) for cc in list(capcha_str)]
total = 0
for ii in... | 85a74f9b708f8134500d9c7add6e2df8617ec305 | 3,652,982 |
from typing import Union
from typing import Sequence
from typing import Callable
from functools import reduce
def compose(fs: Union[ModuleList, Sequence[Callable]]) -> F:
"""
Compose functions as a pipeline function.
Args:
fs (``Sequence[Callable]`` | :class:`~torch.nn.ModuleList`): The functions... | f4d566db95107fdba89a334c2022e68ba0b42f82 | 3,652,983 |
def nanargmin(a, axis=None):
"""
Return the indices of the minimum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results
cannot be trusted if a slice contains only NaNs and Infs.
Parameters
----------
a : array_like
Input data.... | 6d2320bd38a96b364b752e2b50a204daf1f673e8 | 3,652,984 |
import re
def check_right_flank(seq_right, list_rep, verbose=False):
"""
Check if start of right flank sequence contains last repetitive sequence.
:param seq_right: str - right flank sequence
:param list_rep: list(Repetition) - list of Repetitions(seq, num)
:param verbose: bool - be verbose
:r... | c4f5675756e5acd88e71ed713bcdcb5a6c2763a2 | 3,652,985 |
import os
def is_path_creatable(pathname):
"""
if any previous level of parent folder exists, returns true
"""
if not is_path_valid(pathname):
return False
pathname = os.path.normpath(pathname)
pathname = os.path.dirname(os.path.abspath(pathname))
# recursively to find the previou... | 77a69780449534b8d46d70eb3dcf60a0fb284100 | 3,652,986 |
def readout_gg(_X, X, O):
"""
Graph Gathering implementation. (The none shown in the equation)
_X: final node embeddings.
X: initial node features.
O: desired output dimension.
"""
val1 = dense(tf.concat([_X, X], axis=2), O, use_bias=True)
val1 = tf.nn.sigmoid(val1)
val2 = dense(_X, ... | f8f8bc2ed52bf72ba14325d6d55c3bc46e100f82 | 3,652,987 |
def plot_taylor_axes(axes, cax, option):
"""
Plot axes for Taylor diagram.
Plots the x & y axes for a Taylor diagram using the information
provided in the AXES dictionary returned by the
GET_TAYLOR_DIAGRAM_AXES function.
INPUTS:
axes : data structure containing axes information for targe... | 69193482a954f1afbcac7b7934f4ce507050ce55 | 3,652,988 |
def list_timezones():
"""Return a list of all time zones known to the system."""
l=[]
for i in xrange(parentsize):
l.append(_winreg.EnumKey(tzparent, i))
return l | c9fea053f6f86043065e0e3efc04a30dc5585b5d | 3,652,989 |
import functools
def keyword_decorator(deco):
"""Wrap a decorator to optionally takes keyword arguments."""
@functools.wraps(deco)
def new_deco(fn=None, **kwargs):
if fn is None:
@functools.wraps(deco)
def newer_deco(fn):
return deco(fn, **kwargs)
... | 5ffc100c4fbbf7657c974685ab70dfc903a4abe1 | 3,652,990 |
from symgp.superexpressions import SuperMatAdd
import itertools
def get_permutations(expr, debug=False):
"""
Returns the permutations of a MatAdd expression for lengths 2 to len(expr).
For example, for A + B + C + D, we return:
[A+B, A+C, A+D, B+C, B+D, C+D, A+B+C, A+B+D, A+... | f73265bd597ab2a6a8b7401ff19a588859a867b8 | 3,652,991 |
import numpy
import math
def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True):
"""Return spherical linear interpolation between two quaternions.
>>> q0 = random_quaternion()
>>> q1 = random_quaternion()
>>> q = quaternion_slerp(q0, q1, 0.0)
>>> numpy.allclose(q, q0)
True
... | 1895bdb60e6bce11a0cd3f659ceca2a83a0c4810 | 3,652,992 |
def doctest2md(lines):
"""
Convert the given doctest to a syntax highlighted markdown segment.
"""
is_only_code = True
lines = unindent(lines)
for line in lines:
if not line.startswith('>>> ') and not line.startswith('... ') and line not in ['>>>', '...']:
is_only_code = Fals... | 33ffaa31e7d7b578e1664707476b214bdc705346 | 3,652,993 |
def get_return_value(total, cash_given):
"""show how much money you owe to customer after they give you a bill."""
return Decimal(Decimal(total) - Decimal(cash_given)).quantize(Decimal('.01')) | 3c4bc4819bc7c133b56881ea59cbd3d7a108b3dd | 3,652,994 |
import logging
def initlog(logfile=None, level=None, log_stdout=True):
"""
Initialize the log, default log level is NOTSET, it will write the log
message into logfile, and also print onto the screen.
If set log_stdout to False, will not print the log message onto the screen.
"""
log_levels = {... | c9569ce235fbb4895e918d4f96fdbd35c043546c | 3,652,995 |
def show_predictions(scores, target='y', threshold=0.5, path_out=False, verbose=True, figsize=(7, 200)):
"""This function will plot which have been correctly classified. The input is
single dict containing labels as keys and information on each model as values
in the order [auc_score, ids_test, y_true, y... | f113b485832623048c01c798c6ca059403b3fb75 | 3,652,996 |
def det(a, **kwargs):
"""
Compute the determinant of arrays, with broadcasting.
Parameters
----------
a : (NDIMS, M, M) array
Input array. Its inner dimensions must be those of a square 2-D array.
Returns
-------
det : (NDIMS) array
Determinants of `a`
See Also
... | 8d7ccb0756375db749c5a21c8f54c301b37bfc28 | 3,652,997 |
def SegStart(ea):
"""
Get start address of a segment
@param ea: any address in the segment
@return: start of segment
BADADDR - the specified address doesn't belong to any segment
"""
seg = idaapi.getseg(ea)
if not seg:
return BADADDR
else:
return seg.start... | 0ced19a5b868a605e61c28b97cf1de8b8a6c0d54 | 3,652,998 |
import json
import inspect
def update_school_term(request):
"""
修改周期的开始时间和结束时间
:param request:
:return:
"""
operation_object = None
try:
if request.method == 'POST':
object_form = SchoolTermUpdateForm(request.POST)
if object_form.is_valid():
... | 850bcaa39a1a0668f017dc90224e766b2b336a37 | 3,652,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.