content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def build_dataset(cfg, args=None):
"""
Build the module with cfg.
Args:
cfg (dict): the config of the modules
registry(Registry): A registry the module belongs to.
Returns:
The built module.
"""
args = cfg
name = args.pop("name")
dataset = DATASET_REGISTRY.ge... | c5657ca553ae268a17f5e3ac084b72cf0e0c1535 | 55,600 |
def plot_damped_oscillator(m=1.0, k=1.0, b=1.0):
"""
m = 1.0 # mass [kg]
k = 1.0 # spring constant [N/m]
b = 1.0 # friction constant [Ns/m = kgm/s^2*s/m = kg/s]
"""
two_gamma = b/m
omega_squared = k/m
gamma = two_gamma/2
omega = np.sqrt(omega_squared)
if gamma == 0.0:
... | f226a3d227383b0c59af5355d4a70ed719ac8bc2 | 55,601 |
def combine_dictionaries(dict1,dict2):
"""append lists that share the same key, and add new keys
WARNING: this only works if the dictionaries have values that are lists"""
outdict = dict1
for key in dict2:
if key in outdict:
assert(isinstance(dict2[key],list))... | bc291bd8b31870ee8d04f4cb13c94c88bb97fea9 | 55,602 |
def greatest_common_divisor(larger_num, smaller_num):
"""This function uses Euclid's algorithm to calculate the Greatest Common Divisor
of two non-negative integers
pre: larger_num & smaller_num are both non-negative integers, and larger_num > smaller_num
post: returns the greatest common d... | 70db69b222f1a4a0d395e9bb1ff87ef031dbbbd6 | 55,603 |
import json
from datetime import datetime
import os
def create_raid_handler(event, context):
"""
Create and new RAiD by; generating a handle, registering with ANDS and putting to the RAiD DB and Provider Index.
:param event:
:param context:
:return: RAiD object
"""
if 'requestContext' not ... | db49d6d4f04e2a84118446b2004bd8c1656c2b80 | 55,604 |
import os
import yaml
def workbook_contains_workflow(config, clients, deployment, workbook,
workflow_name):
"""Validate that workflow exist in workbook when workflow is passed
:param workbook: parameter containing the workbook definition
:param workflow_name: parameter cont... | c52a2f5fda2ef387debd1360f918b3801578ea3a | 55,605 |
import argparse
def get_args():
"""
Get arguments from command line
"""
parser = argparse.ArgumentParser()
parser.add_argument("image_path", type=str, help="path to image in which to predict class label")
parser.add_argument("checkpoint", type=str, help="checkpoint in which trained mo... | ec468187194d8c2af0182c5464452c614842091a | 55,606 |
import sys
def reset(verbose: int = 0, **kwargs) -> logger: # noqa
"""
重置 logger 等级函数
:param verbose: 等级级别 0 - 3
:param kwargs:
:return:
"""
levels = ['WARNING', 'INFO', 'DEBUG', 'TRACE']
level0 = levels[-1] if verbose > len(levels) else levels[verbose]
logger.remove()
logg... | badd705e2320a5a9725ef2e0349040dbec3ffe00 | 55,607 |
def randomColor(image):
"""
对图像进行颜色抖动
:param image: PIL的图像image
:return: 有颜色色差的图像image
"""
random_factor = np.random.randint(0, 31) / 10. # 随机因子
color_image = ImageEnhance.Color(image).enhance(random_factor) # 调整图像的饱和度
random_factor = np.random.randint(1... | 71825e6d4c6e0feac26f5b292210f54db79447d4 | 55,608 |
import os
import json
def get_user_set_parameters(remove: bool = False) -> dict:
"""
Scans the environment variables for any user returned parameters that have a prefix MAGNUS_PRM_
Args:
remove (bool, optional): Flag to remove the parameter if needed. Defaults to False.
Returns:
dict... | 0f9ccfda02041d7ef398e9943a85b0ea16db3d9f | 55,609 |
def tj_max_volume():
"""
Real Name: b'Tj max Volume'
Original Eqn: b'162.4'
Units: b'MCM'
Limits: (None, None)
Type: constant
b''
"""
return 162.4 | c921033f825ed719d41f7663fd7c83cc46227f57 | 55,610 |
def cca(features_x, features_y):
"""Compute the mean squared CCA correlation (R^2_{CCA}).
Args:
features_x: A num_examples x num_features matrix of features.
features_y: A num_examples x num_features matrix of features.
Returns:
The mean squared CCA correlations between X and Y.
"""
qx, _ = np.l... | ff7d0fa7c8e0fe71ef72d0716af2a2f331ed1db8 | 55,611 |
def get_stats_value(value_considered,ad_or_ped,ind_clusters,demographics_coll,logger):
"""get the Kruskal Wallis U index and p-value for a type of demographics
Parameters: value_considered (str): type of demographics we want the KW U index and p-value
ad_or_ped (str): "adult" or "pediatric", to ... | fc2f3bcdbc98bb55ceaf1db63acab176bb3919b1 | 55,612 |
def overlap_ellipse_polygon(ellipse, polygon):
"""Get ratio of how much of ``ellipse`` that is contained in ``polygon``.
Current implementation:
Convert ellipse to polygon and use :py:meth:`overlap_polygon_polygon`
:param ellipse: The ellipse.
:type ellipse: :py:class:`b2ac.geometry.ellipse.B2ACEl... | 21c5619bbc6e9316b7f7478f31ccc234f931293c | 55,613 |
from re import DEBUG
import sqlite3
import syslog
import traceback
def create_db_connection(database_file):
"""
Create a database connection to the SQLite3 database specified
by database_file.
"""
consql = None
mf.syslog_trace(f"Connecting to: {database_file}", False, DEBUG)
try:
c... | 0ee0bc7e1763b51b731c10652ee4c2fdc9deb32d | 55,614 |
def percent_median(data: pd.DataFrame) -> pd.DataFrame:
"""
Calculate the points expected as a percentage of the median player in the position
Args:
data (pd.DataFrame): the dataframe that has the players and a single scoring scheme
Returns:
pd.DataFrame: updated dataframe with a colum... | 6e9e19ddd3936a770516e3693e15cbbbe24d47e3 | 55,615 |
def _build_g_gradient(x, classifier, pred_class, target_class):
"""
Build tensors of gradient `g`.
:param x: One input sample
:type x: `np.ndarray`
:param classifier: A trained model
:type classifier: :class:`Classifier`
:param pred_class: Predicted class
:type pred_class: `int`
:pa... | 780da740cbf0d29a3d3fb7f8205855c4b156178f | 55,616 |
import time
import requests
def reboot_and_wait(username, password, check_func=None, timeout=100):
"""
重启光猫并等待光猫重启完成,这需要一个检查函数来确定光猫是否重启完成,如果检查光猫重启状态时间超时,则将抛出TimeoutError异常
:param username: 终端配置账户用户名
:param password: 终端配置账户密码
:param check_func: 光猫重启完成检查函数,它不接受任何参数,由返回值来决定光猫是否重启成功 (默认值是 None,即使用内置的检... | 72ff57c61c3e6a1585a897050ee5ca9f41cf0d39 | 55,617 |
def _percent_match(date_classes, tokens):
"""
For each date class, return the percentage of tokens that the class matched (floating point [0.0 - 1.0]). The
returned value is a tuple of length patterns. Tokens should be a list.
"""
match_count = [0] * len(date_classes)
for i, date_class in enume... | fb90ab7d1d6cf0b0d5024d2834175a0d068ac8e0 | 55,618 |
def convert_ATvalue(byte_string, is_little_endian, struct_format=None):
"""Read and return AT (tag) data_element value(s)"""
length = len(byte_string)
if length == 4:
return convert_tag(byte_string, is_little_endian)
# length > 4
if length % 4 != 0:
logger.warn("Expected length to be... | c1ff908a413d27d29e4fc378259027eb12075c1f | 55,619 |
def build_asn1(context, recipe, bindata=None, ofs=0, outer_class=None):
"""Construct an ASN.1 structural element from a recipe and bindata.
with ofset. The result can either be an ASN1Object subclass
instance or an offset into bindata. The context is used to lookup
identifiers during lazy bin... | 5cbf80dd5f98020b22639658c4a648ba68afb9ca | 55,620 |
def find_idx_in_list(lst, target_value, start=0):
"""Find the max idx in the list such that lst[idx] < target_value.
If list is empty or the first value is larger than the target value, return -1
"""
if len(lst) == 0 or lst[0] > target_value:
return -1
for idx in range(start, len(lst)):
... | e87258a00c98a02ca4fe94e7cab67dbc1b07a34f | 55,621 |
from typing import Iterable
from typing import List
def tishka_flatten(data: Iterable) -> List:
"""
Non recursive algorithm
Based on append/extend elements to new list
"""
nested = True
while nested:
new = []
nested = False
for i in data:
if isinstance(i, l... | ca9d6eb4507e95ba94b6c1859aa30b81dd6f7a32 | 55,622 |
def server_create_snapshot_respect_max(request, server_id):
"""
View for creating a new snapshot on a server
Dialog asks for confirmation then runs synchronous creation of new
snapshot, then potentially starts a job to delete old ones asynchronously
if there is a maximum set and it has been exceede... | 5d1c67476812d63267942024a72519577379b386 | 55,623 |
import collections
def api_calls(function: Function) -> collections.Counter:
"""
Returns counter containing API calls and the number of times they were called.
e.g.
with dragodis.open_program("input.exe") as dis:
func = dis.get_function(0x40000)
api_calls = functions.api_c... | 907e72ecd3a3d152443a7ad6e926c49d8051f074 | 55,624 |
def _preprocess(features, wires, weights):
"""Validate and pre-process inputs as follows:
* Check that the features tensor is one-dimensional.
* Check that the first dimension of the features tensor
has length :math:`n` or less, where :math:`n` is the number of qubits.
* Check that the shape of t... | 716de91ef381f1cd9f1c1e255094e0821be98c2f | 55,625 |
def apply_xtalk(vis, xtalk):
"""
Apply to a (NTIMES,NFREQS) visibility waterfall a crosstalk signal
Args:
vis (array-like): shape=(NTIMES,NFREQS)
the visibility waterfall to which gains will be applied
xtalk (array-like): shape=(NTIMES,NFREQS) or (NFREQS,)
the crosst... | 01712c18166889011a03627e07c79c71404cc2cd | 55,626 |
import requests
def get_vcdr_sddc_details_json(strVCDRProdURL, sddc_id, session_token):
"""Get Recovery SDDC Details - Get details of a specific Recovery SDDC. """
myHeader = {'x-da-access-token': session_token}
myURL = f'{strVCDRProdURL}/api/vcdr/v1alpha/recovery-sddcs/{sddc_id}'
response = requests.... | 8852683fe2d62f152559070643a4b9e13cfece4a | 55,627 |
from re import T
import torch
def estimate(
signal: T.Union[T.List, np.ndarray, torch.Tensor],
sample_rate: float,
pitch_min: float = 20,
pitch_max: float = 20000,
frame_stride: float = 0.01,
threshold: float = 0.1,
) -> torch.Tensor:
"""estimate the pitch (fundamental frequency) of a sign... | 81d94cfcdceba4518b56d64e9002b61a60608a4e | 55,628 |
def _residual_maker(A, b):
"""
Returns a matrix which can be used to make residuals from b
"""
n = A.shape[0]
I = eye(n)
return I - _hat(A) | 7d649d295faa8553a82d65c4ea2708d0a64b26ed | 55,629 |
def highway_ramps_example(render=None):
"""
Perform a simulation of vehicles on a highway section with ramps.
Parameters
----------
render: bool, optional
Specifies whether or not to use the GUI during the simulation.
Returns
-------
exp: flow.core.experiment.Experiment
... | 66c4fa17af6a09b0ba52245638fb054fdfeca0e6 | 55,630 |
import typing
def count(*items: typing.Any) -> int:
"""Count the number of items that are provided that are `UNDEFINED`."""
return sum(1 for item in items if item is UNDEFINED) | bc8f3465d685401ed108bcdcec69e4c27867ffff | 55,631 |
def _urlescape(name):
"""Escape the given name for inclusion in a URL.
Escaping is done in the manner in which AutoDuck(?) seems to be doing
it.
"""
name = name.replace(' ', '_')\
.replace('(', '.28')\
.replace(')', '.29')
return name | ec94492778ccdefdde7d657f8fffd953915949ae | 55,632 |
def threshold_voltage(logId, print_error = True):
"""
기울기가 커야 전압을 조금만 조절해도 전류 변화가 크고,
누설 전류가 작음.
"""
sample = np.array(logId)
sample = sample.astype(np.float)
rowsize = sample.shape[0]
columsize = sample.shape[1]
for i in range(0, rowsize) :
for j in range(0,columsize) :
... | 8df1ebeeac7a278278cff567c06b099edceef6d8 | 55,633 |
def not_started_timeout():
"""
Fixture that yields a :class:`~adbtp.timeouts.Timeout` that has not been started.
"""
return timeouts.Timeout(1) | 4336427e0c47c63d8d2f2e9b247e7a274e1815b9 | 55,634 |
import operator
def 数组_是否全部相同(iterable, eq=operator.eq):
"""
#allsame([1, 1, 1, 1])
# True
#allsame([])
# True
#allsame([0, 1])
# False
#iterable = iter([0, 1, 1, 1])
#next(iterable)
#allsame(iterable)
# True
#allsame(range(10))
# False
#allsame(range(10), lambd... | 36250c46043888e8df27315ae45f151a1e4494e9 | 55,635 |
def normalize(data):
"""
Normalize data set to have zero mean and unit variance.
Args
data: A numpy array of arrays containing input or target data.
Returns
A normalized numpy array of arrays.
"""
return (data - data.mean(axis=0)) / data.var(axis=0) | d09f7bc81c5f6c5e1c593836bd758a3553f243ca | 55,636 |
from typing import TextIO
import csv
def load_chords(fhandle: TextIO) -> annotations.ChordData:
"""Load Queen format chord data from a file
Args:
fhandle (str or file-like): path or file-like object pointing to a chord file
Returns:
(ChordData): loaded chord data
"""
start_times... | 80be5d91989b89d6ecf6f164d3cebe8573b564c3 | 55,637 |
import re
def try_repat(s, default=None):
""" Try compiling a regex pattern.
If `s` is Falsey, `default` is returned.
On errors, InvalidArg is raised.
On success, a compiled regex pattern is returned.
"""
if not s:
return default
try:
p = re.compile(s, flags=re.... | 871549a3fb43418053bd2b1a2bab68d96ab49da6 | 55,638 |
import statistics
def mean_median_diff(district_plan, party_to_analyze, competing_party):
"""
:param district_plan: an iterable of Districts
:param party_to_analyze: the key specifying which party to analyze
:param competing_party: the competing party
:return: median - mean party share across all ... | 82bbf5fa9b5af2ec8f572d743dc7f2f92b6970da | 55,639 |
def get_airfares():
"""Requests user's input information at the root --> /, and gets the cheapest airfares based on users input.
"""
departure = (request.form.get("departure")).upper()
arrival = (request.form.get("arrival")).upper()
departure_date = request.form.get("departure_date")
return_dat... | 3aadec31895b78e05653a419731e67e38e871e69 | 55,640 |
from typing import List
def our_istft(z: nparr) -> List[nparr]:
"""
:param z: matrix of size [stft_freq,stft_time,len(signals)] of transformed spectrograms
:return: signals: list of numpy arrays
"""
stft_n = 512
return [ss.istft(cur_z, nperseg=stft_n)[1] for cur_z in np.transpose(z, (2, 0, 1))... | 9583d252e8400b0fa57f6a69679d5479ebe4c85c | 55,641 |
def run_to_ball_bottom_left(obs, player_x, player_y):
""" run to the ball if it is to the bottom left from player's position """
def environment_fits(obs, player_x, player_y):
""" environment fits constraints """
# ball is to the bottom left from player's position
if (obs["memory_pattern... | 482d4ae53c105efd087e2c6325e2427507500cb2 | 55,642 |
def other(
player_id # type: int
):
# type: () -> int
"""
Returns the index of the opposite player to the one given: ie. 1 if the argument is 2 and 2 if the argument is 1.
:param player:
:return:
"""
return 1 if player_id == 2 else 2 | 0216b42f821a3dfb8ece1702ca28cf56070eaa7a | 55,643 |
def is_chi(item):
"""
:param item: array of tile 34 indices
:return: boolean
"""
if len(item) != 3:
return False
return item[0] == item[1] - 1 == item[2] - 2 | e2c1b915ed7a8c841a436e3dfe88d7bae1a38e5a | 55,644 |
from typing import Dict
def make_dict_for_graph_data(db: Session, user_id: int) -> Dict[str, int]:
"""create a dict with number of events per day for current week"""
events_this_week, events_for_graph = get_events_for_the_week(db, user_id)
for event_obj in events_this_week:
event_date = event_obj... | e417d129f5262c42747ce0b4f7bf81e598f1e683 | 55,645 |
def coord(x_coordinate = 0, y_coordinate = 0):
"""function to form a coordinate string from x and y integers"""
return '(' + str(x_coordinate) + ',' + str(y_coordinate) + ')' | 65bb18ffefdaaa13b30d5237b9061b053a9e8a9d | 55,646 |
def to_camera_coordinate(joints, T, R):
"""
Args:
joints: 3x24xT
T: 3x1
R: 3x3
Returns:
"""
new_joints = np.zeros_like(joints)
for t in range(joints.shape[2]):
new_joints[:, :, t] = (R @ joints[:, :, t]) + T
return new_joints | 6ce9b73ecbbe9617c8fd0938a021094caec97273 | 55,647 |
def XML_file_to_parameter(file_name):
"""
Convert a xml file into pyqtgraph parameter object.
=============== =========== ================================================
**Parameters** **Type** **Description**
*file_name* string the file name of the XML file to be co... | 194a9b715fc331b9106a14f5db351985dc5d3e5d | 55,648 |
def CopyTraceDataFromHTMLFilePath(html_path, trace_path, gzipped_output=False):
"""Copies trace data from an existing HTML file into new trace file(s).
If |html_path| doesn't contain any trace data blocks, this function throws an
exception. If |html_path| contains more than one trace data block, the first
bloc... | 5fdab909aec29104aed3e5ed41df96dc6a7c3fb1 | 55,649 |
def public(*objects):
"""add objects to `__all__`. deprecated"""
return _add(_caller_modules()[1], objects) | 7c397333883ffb447f970b92fa1baa6b69527456 | 55,650 |
from typing import Dict
from typing import Any
def format_results(json_results: Dict[str, Any]) -> str:
"""
Purpose:
Format the json to a text response
Args:
json_results: crash data
Returns:
text_string: formatted text
"""
early_morning_crashes = len(json_results["ear... | 95bfbb9365bdb7fcfd1bdb79d005cde6f3b0aa8c | 55,651 |
from typing import List
def equal_camera_params(camera_params_a: List[float], camera_params_b: List[float]) -> bool:
"""
Checks if the camera parameters are equals.
:param camera_params_a: first camera parameters
:param camera_params_b: second camera parameters
:return: True if they are equal, Fa... | 1b97163baca39d332536a1c3a77cbafd28021008 | 55,652 |
from datetime import datetime
def series():
"""Make mocked series as fixture."""
arr = np.random.randn(100)
locs = np.arange(20, 40)
arr[locs] = np.NaN
series = Series(arr, index=bdate_range(datetime(2009, 1, 1), periods=100))
return series | e743055a74b9aebfd24b28f09cc6249f2f17ae97 | 55,653 |
from typing import Tuple
from typing import Any
from typing import Callable
from typing import Optional
def get_arg_by_name(name: str, args: Tuple[Any], func: Callable) -> Optional[Any]:
"""Get the index of the argument in the function signature that matches the name provided"""
sig = signature(func)
for ... | 1b8e8e72e0d4db249c32669c656591d940ac1fa3 | 55,654 |
from typing import List
def create_fyle_projects_payload(projects: List[DestinationAttribute], existing_project_names: list):
"""
Create Fyle Projects Payload from Xero Projects and Customers
:param projects: Xero Projects
:return: Fyle Projects Payload
"""
payload = []
for project in pro... | b35fe6a9a02c591a544609a448e59ea0c5a0cf03 | 55,655 |
import re
def get_s3_key_as_string(s3_url):
""" Returns a file from S3 as string. Machine should have access to S3
Args:
s3_url (str): in form of 'https://s3-eu-west-1.amazonaws.com/x/y/file.yaml'
or 'https://s3.eu-central-1.amazonaws.com/x/y/file.yaml'
Returns:
str: content of gi... | 77a7ec756ed534c05ea7d7630f0f948f1ec5062a | 55,656 |
from typing import Optional
from typing import Generator
def set_virtual_time_policy(
policy: VirtualTimePolicy,
budget: Optional[float] = None,
maxVirtualTimeTaskStarvationCount: Optional[int] = None,
waitForNavigation: Optional[bool] = None,
initialVirtualTime: Optional[network.TimeSinceEpoch] =... | 36b67a3d51a0186d127ace9c0357d812edf594b6 | 55,657 |
def write_txt(w_path, val):
"""Write a text file from the string input.
"""
with open(w_path, "w") as output:
output.write(val + '\n')
return None | 964f92cd63c0c448ef96577fa506051a3a89c08b | 55,658 |
def sendEmail():
"""
"""
if request.method == 'POST':
user_email = request.form.get('user_email')
firstName = request.form.get('firstName')
lastName = request.form.get('lastName')
subject = request.form.get('subject')
user_massage = request.form.get('userMessage')
... | c18610f08b123c2e6308ebd9ac99c2eb2c827682 | 55,659 |
def add_node(store, node_list, lb_id, current_timestamp):
"""
Returns the canned response for add nodes
"""
if lb_id in store.lbs:
_verify_and_update_lb_state(store, lb_id, False, current_timestamp)
if store.lbs[lb_id]["status"] != "ACTIVE":
resource = invalid_resource(
... | 170e8fddf65f3968705baa706c2dccc56129cf1d | 55,660 |
from typing import List
def create_vulnerability(
name: str,
author: Identity,
external_references: List[ExternalReference],
object_marking_refs: List[MarkingDefinition],
) -> Vulnerability:
"""Create a vulnerability."""
return Vulnerability(
created_by_ref=author,
name=name,
... | 7fbbadb0488fd06ba75b487347667cfa0058a598 | 55,661 |
def histtrends2():
"""
Reads in future LENS 1970-2005 SI-x data
Returns
----------
lstfrz_trendh2 : array of last freeze trends
leaf_trendh2 : array of leaf trends
"""
directory = '/volumes/eas-shared/ault/ecrl/spring-indices/LENS_springonset/data/cesmclimo/'
name2 = 'Leaftren... | ca92bedf3459089eb7cda0698899638d6c6c5c8b | 55,662 |
def load_manifest(path: Pathlike) -> Manifest:
"""Generic utility for reading an arbitrary manifest."""
raw_data = load_yaml(path)
data_set = None
for manifest_type in [RecordingSet, SupervisionSet, FeatureSet, CutSet]:
try:
data_set = manifest_type.from_dicts(raw_data)
excep... | bcbf4848768b6c66ec5a5f6fac929cd818a1a7aa | 55,663 |
def ListToDict(args):
"""
change a list to dict
:param args: a list
:type args: list
:return: dict
.. code-block:: python
>>> a = [1,2,3,4]
>>> print(ListToDict(a))
{1: {2: {3: 4}}}
"""
if not isinstance(args, list):
return None
if len(... | 23f3ed1f47adbc842906a06d704150962b3f5a76 | 55,664 |
def compare_maps(map1: Nifti1Image, map2: Nifti1Image):
"""
Compare two maps, given as Nifti1Image objects.
This function exploits that nibabel's get_fdata() caches the numerical arrays,
so we can use the object id to cache extraction of the nonzero coordinates.
Repeated calls involving the same map... | 333b8676408d42c2aa25311997e8002ed04f5a66 | 55,665 |
def blockingCallOnMainThread(func, *args, **kwargs):
"""
Modified version of twisted.internet.threads.blockingCallFromThread
which waits 30s for results and otherwise assumes the system to be shut down.
This is an ugly workaround for a twisted-internal deadlock.
Please keep the look intact in case someone ... | 80549226fc26d69c4740110817f37435e33ba956 | 55,666 |
from typing import Optional
def get_region_commitment(commitment: Optional[str] = None,
project: Optional[str] = None,
region: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRegionCommitmentResult:
"""... | 31fbf797b0e4bc637027784bb99887f8b18c67a1 | 55,667 |
import torch
def create_mock_target(number_of_nodes, number_of_classes):
"""
Creating a mock target vector.
"""
return torch.LongTensor(
[np.random.randint(0, number_of_classes - 1) for node in range(number_of_nodes)]
) | 0892fcea085dab7df3633720c69466ac958f3e3d | 55,668 |
def string_of_error(return_code: int) -> str:
"""Decode the TREXIO exit code.
Argument is an integer return code that correspond to one of the TREXIO errors.
Returns string that contains description of TREXIO ~return_code~.
"""
try:
error_str = pytr.trexio_string_of_error(return_code)
... | ec6a391cdb1051080ebe93dfb07e5d59f5a9f996 | 55,669 |
from typing import Optional
def get_float(message: str = "Choose a number", title: str = "Title", default_value: float = 0.0,
min_: float = -10000, max_: float = 10000, decimals: int = 3) -> Optional[float]:
"""
Simple dialog to ask a user to select a floating point number
within a certain r... | 809fb85f96eed285c4a301a9a263866aa3fed697 | 55,670 |
import os
def add_extension_if_needed(filepath, ext, check_if_exists=False):
"""Add the extension ext to fpath if it doesn't have it.
Parameters
----------
filepath: str
File name or path
ext: str
File extension
check_if_exists: bool
Returns
-------
File name or path wi... | b95f644c347323b168076ead95ffdcbc0748f82e | 55,671 |
def score_filter(predictions, min_score):
"""Remove prediction bounding boxes with probability under a threshold
Parameters
----------
predictions : dict
all predictions
min_score : int
threshold score
Returns
-------
dict
filtered predictions
"""
new_p... | 28f8c0604f3dabc76ffbda911357d0bdd5bd5331 | 55,672 |
import math
def plot_connectivity(
epoch,
fig=None,
locations=None,
calc_type="correlation",
pair_list=[],
threshold=0,
show_sphere=True,
readjust_sphere="auto",
colormap="RdBu_r",
vmin=None,
vmax=None,
line_width=None,
title=None,
colorbar=True,
caption=Non... | 450362f28beb17dd36b066f786a8023abb8e939e | 55,673 |
def consolidate(*levels):
"""
Arranges list of object dictionaries levels into a
hierarchical data structure, based upon the attribute
"parent"
Must pass arguments in ascending order (e.g. children,
parents, grandparents)
"""
# consolidated = list(levels) # modify copy
consolidate... | 7cb064d3651767732c979ba34952a0a8c8962eb0 | 55,674 |
def verbose_name_plural(obj):
"""Return model verbose name in plural mode."""
if isinstance(obj, models.Model):
type(obj)._meta.verbose_name_plural
return obj._meta.verbose_name_plural | df05ace5cd8927ba5549cf601148554bc69f34b0 | 55,675 |
import struct
def decode_option(packet, offset):
"""Decode a navdata option."""
id_nr, size = struct.unpack_from("HH", packet, offset)
end_offset = offset + size
data = packet[offset + struct.calcsize("HH"):end_offset]
return id_nr, data, end_offset | c0ada56ba1f227a9db74b6d090496b3cfdbb1041 | 55,676 |
def split_range_into_groups(
n,
group_size,
which_group_complete="last"):
"""Partitions `n` elements into adjacent groups,
each with `group_size` elements
Group number starts from 0 and increments upward
Can be used to generate groups for sliding window aggregation.
... | aba2d19fa52f44dc0817290efb9fcea9a9209845 | 55,677 |
import math
def getsteps(tspan, h):
"""
Given a timespan and a timestep h, return the number of steps.
"""
t1, t2 = tspan
return int(math.floor((t2-t1)/h)) | a10e0a4302352be6eafb9fad8e00005b9c79dd27 | 55,678 |
def mds(data, variables=None):
"""
Python implementation of the MDS coordinates calculated by the CCG program corrmat when set to
'ordination' mode.
MDS coordinates are calculate from the correlation matrix
.. seealso::
1. Deutsch, M. V, & Deutsch, C. V. (2013). A Program to Calculate and... | 5cbe72605825bc49fd41addf3c13cdb143279808 | 55,679 |
from typing import Union
def boolean(value: Union[bool, str, float] = False) -> bool:
"""
Return boolean from string.
"""
if isinstance(value, bool):
return value
elif isinstance(value, str):
value = value.lower().strip()[0]
if value in ["y", "t"]:
return True
... | 4f1db3e1224e0633c5d663e6ae85a8ae19c51624 | 55,680 |
from typing import List
def solve(
context: mgp.ProcCtx, points: List[mgp.Vertex], method: str = DEFAULT_SOLVING_METHOD
) -> mgp.Record(sources=List[mgp.Vertex], destinations=List[mgp.Vertex]):
"""
The tsp_module solver returns 2 fields whose elements at indexes are correlated
* `sources` - element... | 6662f6e353441dbfb360684829a30fd4c542f616 | 55,681 |
import sys
import os
def get_ancestor_paths(path):
"""Returns a list of ancestors for a given path
"""
ancestors = []
stop_val = "/"
if "darwin" in sys.platform:
stop_val = "/"
elif "win" in sys.platform:
stop_val = ":\\"
stop_len = len(stop_val) * -1
if os.path.exists(... | b125fcc0b776ea2a272666f7a272f19ec116f394 | 55,682 |
def convert_dataset_to_samples(dataset, max_span_length, ner_label2id=None, context_window=0, split=0):
"""
Extract sentences and gold entities from a dataset
"""
# split: split the data into train and dev (for ACE04)
# split == 0: don't split
# split == 1: return first 90% (train)
# split =... | c060cccfbf6892999cf9ccd0ee2f72f0e2e9a6f8 | 55,683 |
import scipy
def calculate_viewport_info(coordinates):
"""takes a coordinate array and returns a list of the edges of all viewports"""
# the coordinates array contains four channels: u, v, x, y
u = coordinates[:,:,0]
labeled_array, num_labels = scipy.ndimage.measurements.label(u >= 0.0)
# shapes
... | 97278dadc8d02dd63f19cfb1774500e3f57fb9eb | 55,684 |
def build_bin_mask(n,chrs,zoom_dict,chr_dict,chr_bin_range,bin_positions,axis=None):
"""build a 1D mask (x or y axis) based upon user chr/coor selection
"""
bin_mask=np.zeros(n,dtype=bool)
# build bin mask based on user chr/zoom selection
for c in chrs:
c_ind=chr_dict[c]
r=c... | bd651489e524c89826f8d59b4acab0dad66b3da0 | 55,685 |
def fill_nnz(
mat: "sp.csr_matrix", all_nnz: "np.ndarray[int]", fill_value: float = 1e-9
) -> sp.csr_matrix:
"""
Given an input sparse matrix and a superset of nonzero coordinates, fill the
matrix to ensure all values in the set are stored explicitely with the
value of fill_value.
Parameters
... | 08fa0f5de958adf0608a69937839e131ceaaba85 | 55,686 |
def maxima(array):
""" get the index of the maximum value in a 2D array"""
return np.unravel_index(array.argmax(), array.shape) | a64de68bbdda70a9dd789769f6c7334d23f9eb6a | 55,687 |
def strip_noise_from_key_signature(key):
"""Removes any unneccessary characters (7,9,11,m,M etc...)"""
#Change this to a map or something
key = key.replace('9', '')
key = key.replace('7', '')
key = key.replace('5', '')
key = key.replace('m', '')
key = key.replace('M', '')
return key | 5aa910f96dce275f9e4b6af7926179e73a2c313d | 55,688 |
def validate_digits(digits):
"""Validate digits parameter."""
if digits is None:
return None
try:
digits = int(digits)
except ValueError as e:
raise ValidationError("Digits must be a valid integer value") from e
if digits < 6 or digits > 8:
raise ValidationError("Digi... | 0b1ef0f6b71efeb7b08379ff3d899f5aaa6c7a46 | 55,689 |
def inet_aton(ipaddress):
"""
Convert an IP address in presentation format to its integer octet format
"""
return struct_unpack("<I", struct_pack("<B<B<B<B", \
*map(int, ipaddress.split("."))))[0] | 12d97f46bc57d353c23124d2936d951475a6981a | 55,690 |
def relative_standard_error(series: list, sequence_length: int) -> float:
"""
Calculate the relative standard error
Source:
Hou, T, et. al.
Quasi-Monte Carlo based uncertainty analysis: sampling effciency and error estimation
Reliability Engineering & System Safety
2018
"""
series ... | 9e767aa5f9546bf81c05da5c493f2d06d98d6a08 | 55,691 |
def create_cdr(src_cdr, dst_visit):
""" Create cdr """
dst_cdr, _ = dst.Cdr.get_or_create(
cdr_id=src_cdr.cdr_id,
subject_visit_id=dst_visit.subject_visit_id,
memory=src_cdr.memory,
orientation=src_cdr.orientation,
judge_prob_solving=src_cdr.judge_prob_solving,
c... | 1f8d5431c6010a207efe5e305e60a3e0089a941a | 55,692 |
def derived_something():
"""
A docstring template to describe the function.
This function is part of the unit test template
Returns
-------
An string with the word output
"""
print("This message shows that you have successfully imported \
the derived_something() function from the ... | 97586600645d87c557a1ebeb83e0f9e3a5c1381f | 55,693 |
def calculate_percent(x, y):
"""
计算百分比
:param x: 分子
:param y: 分母
:return: 百分比
"""
x = float(x)
y = float(y)
return safe_div(x, y) * 100 | d63e33462995573f4bab1e8bdc35c6d3eea98f9d | 55,694 |
def plot_histogram(filename, mydata, bins = 10, title = None, xlabel = None, ylabel = None, dpi = 150, figsize = (10,10), tfont = 17, lfont = 14):
"""
Plots a histogram for scalar timeseries.
"""
fig = plt.figure(figsize = figsize)
plt.hist(mydata, bins = bins)
if title:
plt.title(title,... | 06cd0b9a88fb4dbab67061a6cc188ba8bde50c3a | 55,695 |
def _darknet_body(x, for_small=False):
"""Darknent body having 52 Convolution2D layers"""
x = _darknet_conv_bn_act(32, (3, 3), "block1_conv1")(x)
x = _darknet_resblocks(x, 64, 1, block_index=2, downsampling=not for_small)
x = _darknet_resblocks(x, 128, 2, block_index=3)
x = _darknet_resblocks(x, 256... | 8fbfc4475c05c57c5c5119e601e3cdcf082b1280 | 55,696 |
from typing import List
import random
import string
def get_addresses(n=50) -> List[dict]:
"""
Generate random addresses
"""
def _get_address() -> dict:
return {
"name": "John Doe",
"companyName": "Test Co",
"streetAddress": "{} Test St".format(random.randi... | e125abb419cfeb9e06c2c0930f5e3082baa01b72 | 55,697 |
def share_post_friends(request, author_id, post_id):
"""
**[Internal]** <br>
## Description
POST to the endpoint to reshare a post. the server will create a new, reshared post,
and forward it to the corresponding followers' inboxes.
## Request
nothing, but requires to be authenticated as t... | 54964d3179c25b3f8e2c4d317f69ad81996bf0b2 | 55,698 |
def equal_weighting(X, types):
"""
Calculate criteria weights using objective Equal weighting method
Parameters
----------
X : ndarray
Decision matrix with performance values of m alternatives and n criteria
types : ndarray
Returns
-------
ndarray
... | a769da203c9c10a488d650c11272bb544b523133 | 55,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.