content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def compute_sphercial_clustering_loss(centroids, features, batch_memberships): """Compute repulsive chain loss Args: features: [B, C] l2 normalized data, cf) B: batch size, C: feature dimension memberships (int): [B, ] current membership centroids: [K, C] cluster centers ...
23fd09308af857f463c304b62dc0bb86dd89adb2
34,500
from typing import Union import typing def av_client_start( tutk_platform_lib: CDLL, session_id: Union[int, c_int], username: bytes, password: bytes, timeout_secs: int, channel_id: int, ) -> typing.Tuple[c_int, c_uint]: """Start an AV client. Start an AV client by providing view accou...
95058f251163e987ce6eecf3646413352f6b4a8c
34,501
import logging def client_match_template(template_img_location, conf=0.8, region_=(0, 0, 1920, 1080)): """ Using pyautogui.locateCenterOnScreen() to check where are buttons to click. Parameters ---------- template_img_location : template img path conf : confidence The default is 0.8. Ret...
4e92d28c40542a571940e7916605a7ba918887f6
34,502
def balance_data(data): """ DEPRECATED """ survived, died = count_survivors(data['Survived']) remove_n = abs(survived - died) dropId = [] if survived > died: dropid = np.random.choice(data[data['Survived'] == 1].index, remove_n, replace=false) elif survived < died: dropId = np.ra...
34b502f52dfa70d2f48d0ad6735766fc969a41f9
34,503
def log_concave_rejection_sampler( mode, prob_fn, dtype, sample_shape=(), distribution_minimum=None, distribution_maximum=None, seed=None): """Utility for rejection sampling from log-concave discrete distributions. This utility constructs an easy-to-sample-from upper bound for a discret...
6c109478f39ce3ec4e5d630bb5d7b6e8a81df76c
34,504
import time def login(user_name, password): """ This function takes user name and password to login into Github account. Args: :param user_name: Github username :param password: Github password Returns: error_dict (dict): If it's logged in successfully or not wi...
fc119d4584ae721b72e916505445e1d760d04629
34,505
def make_tukey(n, a=0.5): """Make a tukey window Args: n (int): Number of points a (float, optional): Width of window. Defaults to 0.5. Returns: np.array: Weights """ x = np.arange(n) weights = np.ones_like(x, dtype=float) weights[0:int(a*n/2)] = 1/2*(1-np.cos(2*np....
cb14f4cfa9495567954b6ea83eef0f2c568190e3
34,506
def linear_gradient(start_hex: str, finish_hex: str = "#FFFFFF", n: int = 11) -> color_dict: """ returns a gradient list of (n) colors between two hex colors. start_hex and finish_hex should be the full six-digit color string, including the number sign ("#FFFFFF") """ # Starting and ending colors in...
4df9e2d3f2b921e0826ffd51dde208a30bd78e96
34,507
def bast_label_to_number(annotation, label): """Given an annotation file and a label convert it to its corresponding number for the BAST dataset.""" return bast_label_to_number_dict(annotation).get(label, None)
d62451272d84d1749d13070cda3b27825bb7c0d8
34,508
from datetime import datetime import os def most_recent_timestamp(dir): """Returns the file with the most recent timestamp in the directory.""" most_recent = datetime.datetime.min file = None for cur in os.listdir(dir): timestr = cur.split("-", maxsplit=1)[0] cur_time = datetime.dateti...
12cc4673ec5657799322adf89ce84e5ee277d787
34,509
def function_with_exception(val): """Return a `val` if it is non-negative""" if val < 0: raise ValueError("val cannot be negative.") return val
f9a4a50879477a5e45fcb9a9d54a10695fc526df
34,510
def _c(obj: model.Component): """Convert :class:`.Component`.""" # Raises AttributeError if the concept_identity is missing return str(obj.concept_identity.id)
369d1f7b797e0a7162337f36d621593c7cf1f42e
34,511
import copy def get_power_instance(wildcards): """ Returns a formatted template Arguments: rest_base - Base URL of the RESTful interface ident - Identifier of the chassis """ c = copy.deepcopy(_TEMPLATE) c['@odata.context'] = c['@odata.context'].format(**wildcards) c[...
f7fe438dcba027b68cf65919458568c742bf9735
34,512
import pyspark.sql.functions as fn from pyspark.sql import Window def get_user_history(history_type): """ :param history_type: 'click' or 'top' or 'play' :return: """ spark.sql('use {}'.format(user_pre_db)) if history_type == 'play': tmp_df = spark.sql('select user_id, movie_id, cate_i...
346c2615961db564bda0336c679e08079b8a1ec8
34,513
def display_on_frame(self, image, left_curverad, right_curverad, car_off): """ Display texts on image using passed values """ font = cv2.FONT_HERSHEY_COMPLEX curve_disp_txt = 'Curvature: Right = ' + str(np.round(right_curverad,2)) + 'm, Left = ' + str(np.round(left_curverad,2)) +...
c8e86350b7018d1b2eba94db8929a870cf6f8bc5
34,514
from pathlib import Path def path_is_relative_to(path: Path, other: PathOrStr) -> bool: """ This is copied from :meth:`pathlib.PurePath.is_relative_to` to support older Python versions (before 3.9, when this method was introduced). """ try: path.relative_to(other) return True e...
577c591d519e4b0364f202306151411694d81138
34,515
def generate_tokens( parser, lines, flags, keywords): """ This is a rewrite of pypy.module.parser.pytokenize.generate_tokens since the original function is not RPYTHON (uses yield) It was also slightly modified to generate Token instances instead of the original 5-tuples -- it's now a 4-tuple of ...
c09fea9f20879017d87e695c63d6a6cca637a0ae
34,516
def get_days_word_ending(days: int) -> str: """Определяет окончание слова "дня", "дней" и т.д. в зависимости от входящего числа""" last_numeral = days % 10 prelast_numeral = days % 100 prelast_numeral = prelast_numeral // 10 if prelast_numeral == 1: return 'дней' if last_numeral == 0 or ...
4f2887b438ab8909b29a0fa572c5735477da2262
34,517
def _init_hoomd_rb_torsions(structure, ref_energy=1.0): """RB dihedrals (implemented as OPLS dihedrals in HOOMD).""" # Identify the unique dihedral types before setting dihedral_type_params = {} for dihedral in structure.rb_torsions: t1, t2 = dihedral.atom1.type, dihedral.atom2.type t3, ...
f71d955f1f2294ed1c6a5b041ed75dea1028bc34
34,518
def moments(data): """Returns (height, x, y, width_x, width_y) the gaussian parameters of a 2D distribution by calculating its moments """ total = data.sum() X, Y = np.indices(data.shape) x = (X * data).sum() / total y = (Y * data).sum() / total col = data[:, int(y)] width_x = np.sqr...
371cb1c1b8419eb9a604300c87a7a9084a13e46f
34,519
def compute_throughputs(batch_size, gpu_times): """ Given a batch size and an array of time running on GPU, returns an array of throughputs """ return [batch_size / gpu_times[i] * 1000 for i in range(len(gpu_times))]
14b20806ad8e21126c460613a99f9b68bce31ef0
34,520
import torch def load_trained_model(args, config_class, model_class, label_count_info, n_gpu, device): """Load trained model for evaluation""" model = _build_pretrained_model(args, config_class, model_class, label_count_info) model.to(device) model_path = args.output_dir + "/epoch_%d" % args.load_n_e...
d64ff9fdd7e37dfd577983618f57f2bf7f1107cb
34,521
import re def parse_filter_field(string_filters) -> dict: """ Parses string with sets of name, value and comparison into a dict Args: string_filters: A string of the form 'name=<name1>,value=<value1>,comparison=<comparison1>;name=<name2>...' Returns: A dict of the form {<name1>:[{'Val...
adec2fa457a9f9d38770dce1ba9f50143480c884
34,522
import numpy import copy def create_empty_image_like(im: Image) -> Image: """ Create an empty image like another in shape and wcs :param im: :return: Image """ assert type(im) == Image, "Type is %s" % type(im) fim = Image() fim.polarisation_frame = im.polarisation_frame fim.data ...
544833845f6dfccb7e65dd2866542f86b3b6304a
34,523
def convert_to_one_hot(integer_vector, dtype=None, max_labels=None, mode='stack', sparse=False): """ Formats a given array of target labels into a one-hot vector. Parameters ---------- max_labels : int, optional The number of possible classes/labels. This means th...
0341090659f502f81adb368880af4659b1886236
34,524
from typing import Sequence def get_constraints( guesses: list[str], calls: list[Sequence[Call]] ) -> tuple[dict[int, str], set[str], set[str]]: """Get constraints.""" positions = {} appears = set() no_appears = set() for call, guess in zip(calls, guesses): for i, c, x in zip(itt.count...
0163f17fb93d9b2244f6762dbafdddfa7eefb0da
34,525
def apply_trained_model( trained_model_object, input_table, feature_names, replace_missing, standardize, transform_via_svd, replacement_dict_for_training_data=None, standardization_dict_for_training_data=None, svd_dict_for_training_data=None): """Uses a trained model to make predicti...
0760fe4bf49ba7f5b7b00de46a7e5dc5cb01f5d7
34,526
def extract_host(host, level='backend', default_pool_name=False): """Extract Host, Backend or Pool information from host string. :param host: String for host, which could include host@backend#pool info :param level: Indicate which level of information should be extracted from host string....
01ee481a143ab32069e91bcb082e1e1eb229da71
34,527
from medtagger.api.rest import app from typing import Any def get_api_client() -> Any: """Return API client for testing purpose.""" app.testing = True return app.test_client()
48d6897a4ed07f9fb87aee37e8e2ff69383f71f8
34,528
def verify_ospf3_metric(device, interface, metric, max_time=60, check_interval=10): """Verify the OSPF3 metric Args: device (obj): Device object interface (str): Interface name metric (str): ...
6c7f12304a4987293b9336bcbf6300951de75f09
34,529
import argparse def parse_args(): # Taken from Fast R-CNN """Parse input arguments.""" parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int) parser.ad...
405daa546ffb81a2be2f26cc2c96c64bbc75267a
34,530
from nipype.interfaces.afni import Automask from nipype.interfaces.fsl.epi import TOPUP from niworkflows.interfaces.nibabel import MergeSeries from sdcflows.interfaces.fmap import get_trt from ...interfaces.images import RescaleB0 def init_pepolar_estimate_wf(debug=False, generate_report=True, name="pepolar_estimate_...
9b7856399b0a76ca17897be470242b5a47aea969
34,531
import weakref def copy_cache( cache: t.Optional[t.MutableMapping], ) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]: """Create an empty copy of the given cache.""" if cache is None: return None if type(cache) is dict: return {} return LRUCache(cache.capac...
4c0945da8471112a28bd34ad27286df55a23e968
34,532
def get_plugins(metadata): """Return the registered plugins. Load and return all registered plugins. """ plugins = load_plugins() if not plugins: raise NoPluginsError("No plugins found") results = [] for p in sorted(plugins.get_all(), key=attrgetter("name")): if metadata: ...
b88ddbc9e85bdc04d0f2a71458ab2545f925c88b
34,533
def _ConvertUnmatchedResultsToStringDict(unmatched_results): """Converts |unmatched_results| to a dict of strings for reporting. Args: unmatched_results: A dict mapping builder names (string) to lists of data_types.Result who did not have a matching expectation. Returns: A string dictionary repr...
9c09a205bbcea48865e490f67342e0768f58555e
34,534
import os def get_resource(chmod_permission, *paths): """Take a relative filepath and return the actual path. chmod_permission is needed because our packaging might destroy the permission.""" full_path = os.path.join(os.path.dirname(__file__), *paths) os.chmod(full_path, chmod_permission) return full_path
e6d48cb4068ecfedbfa456a8f614543546eb22c5
34,535
def get_color(r, g, b, a): """ converts rgba values of 0 - 255 to the equivalent in 0 - 1 """ return (r / 255.0, g / 255.0, b / 255.0, a / 255.0)
78b4d71e04c7f3271462461641ec71e9fb849347
34,536
def atSendCmdSTTradeGetAccountList(): """ 获取策略测试的账户列表信息 :return: list of todotdict, eg: [todotdict{'Name':'', 'Handle':xxx, 'Status':'online'}] """ func_name = 'atSendCmdSTTradeGetAccountList' atserial.ATraderSTTradeGetAccountList_send() res = recv_serial(func_name) return res.result
fb9e0f0941bc251328e2b3bbc3bc6aef5a0efcaa
34,537
import os def load_data(filename): """Load a binary data.""" path = os.path.join(os.path.dirname(__file__), "data", filename) with open(path) as fptr: return fptr.read()
df1c986657210f376fb24b32cec22b47706adbbe
34,538
import re def escape_version(version): """ Escaped version in wheel filename. Doesn't exactly follow the escaping specification in :pep:`427#escaping-and-unicode` because this conflicts with :pep:`440#local-version-identifiers`. """ return re.sub(r"[^\w\d.+]+", "_", version, flags=re.UNICODE)
ad382dc611a87b66db49f0332698618bda4cf86b
34,539
def union_degree(node_df, edge_df, degree_df, OD_full_path): """ Inputs: node_df, edge_df - the node and edge specific df from get_specific_df OD_full_path - output of shortest_path degree_df - output of get degree df Outputs: edge_degree_df, node_degr...
89e5a9298fbb9214049c19c0cbc725b3ed7f66a5
34,540
def paths(resources, resource_strip_prefix): """Return a list of path tuples (target, source) where: target - is a path in the archive (with given prefix stripped off) source - is an absolute path of the resource file Tuple ordering is aligned with zipper format ie zip_path=file Args: ...
2e0ebcee01cc7b61143ba6fc63bf44820e393fcb
34,541
from typing import Optional import json import yaml from typing import cast def get_content(extra_file: ExtraFileTypeDef) -> Optional[str]: """Get serialized content based on content_type. Args: extra_file: The extra file configuration. Returns: Serialized content based on the content_ty...
0c8d9fee5c244f2e6a42f5dd53eb7c4c508b824c
34,542
def to_bs(): """Example Registry Pipeline that loads existing pipelines""" return [("pbsmrtpipe.pipelines.dev_04:pbsmrtpipe.tasks.dev_hello_world:0", "pbsmrtpipe.tasks.dev_txt_to_fasta:0")]
36c08e38ccdefda793708b88a41f61d5f05e4197
34,543
def get_total_reflectance(mco_filename): """ extract reflectance from mco file. Attention: mco_filename specifies full path. Returns: the reflectance """ return get_diffuse_reflectance(mco_filename) + \ get_specular_reflectance(mco_filename)
f3ea4830fc2c8ee45fd33c229bec3430f85c199a
34,544
import random def mutate(c, gp, pmut): """Mutation of chromosome Based on the probability to mutate, it selects a random gene to change. It selects a random other creature to take a new gene from a gene pool. Args: c: creature's chromosme to be changed. gp: gene pool to select from. ...
d65435e5ffbdcbdd44199493c2b0599fc8b96417
34,545
import numpy def _(shape: numpy.ndarray): """ If a shape is an array of points, compute the minima/maxima or let it pass through if it's 1 dimensional & length 4 """ if (shape.ndim == 1) & (len(shape) == 4): return shape return numpy.array([*shape.min(axis=0), *shape.max(axis=0)])
1ab490ece446a6afec11f90038a285adf9afa141
34,546
import subprocess import os def invoke_spec2d(path, maskname): """ Runs spec2d in the given path, assuming there's a {maskname}.plan file Note that you have to manually close the returned proc.stdout! """ planfn = os.path.abspath(os.path.join(path, maskname + '.plan')) logfn = os.path.abspat...
81314718ed5380d2b562e7060868aa01172faf82
34,547
def selectHierarchy(node): """ get the hierarchy of the current given object :param node: the object to search through :type node: string :return: list of the objects children and current object included :rtype: list """ ad = cmds.listRelatives(node, ad=1, f=1) or [] ad.append(node[0]) ...
c83c28b391e39f30dade59e73f89335a09fe807e
34,548
import logging import http def logErrorAndReturnOK(error_msg='Error found in Task'): """Logs the given error message and returns a HTTP OK response. Args: error_msg: Error message to log """ logging.error(error_msg) return http.HttpResponse()
788f2b6b30e55e8375aab5fdb364f991aed7f71f
34,549
def make_std_gaussian(var_names): """ Make a d dimensional standard Gaussian. :param var_names: The variable name of the factor. :type var_names: str list :return: The standard Gaussian :rtype: Gaussian """ assert var_names, "Error: var_names list cannot be empty." dim = len(var_nam...
3c2c9f5a35786391d6ca1131e7a54767bc18a54d
34,550
def has_prefix(sub_s): """ :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid :return: (bool) If there is any words with prefix stored in sub_s """ # In order to accelerate program for i in lis: if i.startswith(sub_s) is True: return True return False
e53f941ce35bfe1e4f9c9a20d8cf90541186397d
34,551
def sum_numbers_loop(n: int) -> int: """ BIG-O Notation = O(n) """ result = 0 for i in range(n + 1): result += i return result
d3265f5d7ceb277d105ab08f81ac4ce91fcc4153
34,552
import os def create_app(package_name, package_path, settings_override=None, register_security_blueprint=True): """Returns a :class:`Flask` application instance configured with common functionality for the RiskManager platform. :param package_name: application package name :param packa...
947562a86e97e1b6bfa209e0902933bc4e0a00bb
34,553
import itk def range(imageOrFilter) : """Return the range of values in a image of in the output image of a filter The minimum and maximum values are returned in a tuple: (min, max) range() take care of updating the pipeline """ img = image(imageOrFilter) img.UpdateOutputInformation() img.Update() c...
9bbe0fc68be26df35f062da3d4589c906050a10f
34,554
import uuid def get_unique_id(): """Generate and set unique identifier of length 10 integers""" identifier = uuid.uuid4() return str(identifier.int)[:10]
52ac119a062f454faad77df2fecb1f902bdd8530
34,555
import scipy def erb_fir_filters(signal, edges, fs): """ Generates a bank of FIR filters for a given set of erb edges following the approach of Hopkins et al. (2010), such that each filter has a response of -6 dB (relative to the peak response) at the frequencies at which its response intersects wit...
5ff1d3680e0f92e955d3a8314488b0c5900ba585
34,556
def restart(*args, **kwargs): """Return an instance of this to restart a workflow with the new input.""" return restart_type(args, kwargs)
1203873275248791046f2ef87f75276141b59a46
34,557
def FourierMaskRandom(width, height,proportion, R): """ Create a random sampling pattern where each point is sampled from : 1 if r < R 1/(1-r)**2 if r > R with 0<R<1 Args: width (int): Size of output mask in x...
d4bee00f7eb2899bceba025f90f5c5389765a30a
34,558
from typing import Any from typing import Optional from typing import Union from datetime import datetime from typing import Type from typing import Callable from re import T import functools def redis_cache( prefix: str, /, key_func: Any = None, skip_cache_func: Any = lambda *args, **kwargs: False, ...
10d40c7068a2c52b85ce3221c6f6f87421a3b40e
34,559
def get_shapes_from_group(group): """ Gets all object shapes existing inside the given group :param group: maya transform node :type group: str :return: list of shapes objects :rtype: list str .. important:: only mesh shapes are returned for now """ # checks if exists inside maya sce...
053faff6240f75ab859e1c2bbd33604bdbde0c84
34,560
def bond_quatinty(price, investment, minimum_fraction=0.1): """ Computes the quantity of bonds purchased given the investment, bond price per unit, and the minimum fraction of a bond that can be purchased :param investment: Amount of money that will be invested :param minimum_fraction:...
7b42ae44d2e2db2229251088cf3645e965887e0d
34,561
from sys import version import re def get_mysql_version(version_string): """Get MySQL version.""" return version.parse(re.sub("-.*$", "", version_string))
9c5b6f94011d6503f648aa93b84c5d57fea3fc50
34,562
def find_template(templates_list, template_name): """ Function returns copy of a template with a name template_name from templates_list. """ result_list = [template for template in templates_list if template_name == template['name']] return deepcopy(result_list[0]) if result_list else {"template":{}...
a766a5dcf6d451ff26bee94d0eb8a28ff5e98c60
34,563
def dct_compress(X, n_components, window_size=128): """ Compress using the DCT Parameters ---------- X : ndarray, shape=(n_samples,) The input signal to compress. Should be 1-dimensional n_components : int The number of DCT components to keep. Setting n_components to about ...
57cc70951c5e1e15964715383f876975d2e80844
34,564
def nan_divide(a: NDArrayOrFloat, b: NDArrayOrFloat) -> NDArrayOrFloat: """Helper function to avoid divide by zero in arrays and floats. Args: a: Numerator b: Denominator Returns: a/b replace div0 by np.nan """ bc_shp = check_broadcastable(a=a, b=b) return np.divide(a, b,...
ee3858c2ad3e2fdb87704eabb2acf523337f68d2
34,565
def get_folder_sessions(id): """ Get a list of sessions in the given folder To fetch all elements, this endpoint can be called multiple times, starting at pageNumber = 0 and incrementing the page number until no results are returned. """ url = "{}/{}/sessions".format(panopto_url("folders"),...
94dc5dd76bccc5b072aa37aa85f941cbebe7a4e9
34,566
def neighbours(image, i, j): """Define neighbours of the current pixel Arguments: image {numpy.ndarray} -- image i {int} -- row coordinate of the pixel j {int} -- column coordinate of the pixel Returns: list -- list of pixels that are neighbours of current pixel ...
eb9b7f0358fee26865ae75b544b532cb5dc5cd51
34,567
def mutation_delete_musicplaylist(identifier: str): """Returns a mutation for deleting a musicplaylist object based on the identifier. Arguments: identifier: The unique identifier of the musicplaylist object. Returns: The string for the mutation for deleting the musicplaylist object based ...
bb552783f4b9b8d232dd2fae79823eb06fcf5c00
34,568
import re def check_for_repeating_characters(tokens, character): """ References: :func:`re.findall` Args: tokens (): character (): Returns: """ replacements = [] pattern = "([" + character + "{2,}]{2,4})" for token in tokens: if len(token) > 12: ...
9a421e634ad1cd330c2933fda84eb2430e7ef2ed
34,569
import hashlib def md5sum(filename): """ Compute the MD5 hash for a given filename """ blocksize = 65536 hasher = hashlib.md5() with open(filename, "rb") as fid: buf = fid.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = fid.read(blocksize) retur...
4de15169bb672067fc4fcebeae930e56768b0881
34,570
def get_local_platform(): """Returns the name of the local platform; eg: 'linux_x86_64' or 'macosx_10_8_x86_64'. :returns: The local platform name. :rtype: str """ # TODO(John Sirois): Kill some or all usages when https://github.com/pantsbuild/pex/issues/511 # is fixed. current_platform = Platform.curren...
6e775b760a87aad924b9f62ed9c98897677f3c10
34,571
from datetime import datetime def time_stamp(): """Current time stamp""" ts = datetime.now() return ts.strftime('%d-%b-%Y %H:%M:%S')
b17e6841b4c79cc1098123e154c9dd6e59098953
34,572
def fromDict(moduleDict): """Factory function recreating any moduleItem or moduleItem subtype from a dictionary-serialized representation. If implemented correctly, this should act as the opposite to the original object's toDict method. If the requested module is builtIn, return the builtIn module object of...
f0c2fdecc8bd73a40bea92e810724e14fffad341
34,573
import argparse def setup_cli(): """ Create the cli argument interface, and parses incoming args. Returns a tuple: - the argument parser - the parsed args """ parser = argparse.ArgumentParser() parser.add_argument( "--availability", const="csm_availability_win...
822b8475010e51440560aaf2849f6022be218579
34,574
def cache_root(environ=None): """ The root directory for zipline cache files. Parameters ---------- environ : dict, optional An environment dict to forward to zipline_root. Returns ------- cache_root : str The zipline cache root. """ return zipline_path(['cache']...
b87345170f7e21a4cb02834646e552e5c3584a1a
34,575
def save_wechat_config(request): """ 保存微信配置信息 """ # 只有管理员有权限 if not request.user.is_superuser: return redirect('admin:index') conf_name = request.POST.get('conf_name') conf_value = request.POST.get('conf_value') if not conf_name or not conf_value: return render_json({'re...
551ee887aa13873265303a861c49a9f359194ff4
34,576
import logging def ParseQuickEditCommand( cnxn, cmd, issue, config, logged_in_user_id, services): """Parse a quick edit command into assignments and labels.""" parts = _BreakCommandIntoParts(cmd) parser = AssignmentParser(None, easier_kv_labels=True) for key, value in parts: if key: # A key=value as...
d009967514bd30ed493e72d3462c485424e5eb3b
34,577
def get_dict_X_dynamic(ar_iterations, forecast_cycle, input_k): """Provide information to load the dynamic data required by an AR model.""" dict_X_past = {} for i in range(ar_iterations+1): idxs = get_idx_lag(idx_start=0, ar_iteration=i, forecast_cycle=forecast_cycle, input_k=input_k) idxs_p...
a32df9643fb80533010630793c785d7a33e57062
34,578
def CMDterminate(parser, args): """Tells a bot to gracefully shut itself down as soon as it can. This is done by completing whatever current task there is then exiting the bot process. """ parser.add_option( '--wait', action='store_true', help='Wait for the bot to terminate') options, args = parser.p...
81c6f1df97c9dbf2ea955d4e5635ac2e06b007e2
34,579
def calculate_equilibrium( model, P, T, z, number_of_trial_phases=3, compare_trial_phases=False, molar_base=1.0, optimization_method=OptimizationMethod.PYGMO_DE1220, solver_args=PygmoSelfAdaptiveDESettings(50, 250) ): """ Given a mixture modeled by an EoS at a known PT-conditions, calculate the ther...
28716e9dcdb8368d4a682812d4fc094292ec6c81
34,580
import mergejsmf import os import sys def s3_include_debug_js(): """ Generates html to include the js scripts listed in /static/scripts/tools/sahana.js.cfg """ request = current.request scripts_dir = os.path.join(request.folder, "static", "scripts") sys.path.append(os.path.jo...
e2d25585d8ce27429295662a613c308105a40f34
34,581
def get_closing(image, n_erode=1, n_dilate=1, kernel=(5,5)): """ Performs the specified number of dilations, followed by the specified number of erosions to get the closing of the image. Parameters ---------- image : np.ndarray The image to perform the closing on. n_erode : int, op...
d53a8cfcf173dc72b43c707d856b29f65ddd04b4
34,582
def ZAdrift(pminitial, pmfinal, pos, smoothing = 0, deconvolve = 0, lptbool = 0): """ This function takes in initial density field, calculates ZA displacement, \ shifts the particle with that displacement and paints them. """ if not lptbool: ZAdisp = ZA(pminitial, pos) elif lptbool == ...
789bb9d20807b964a4d1f55471871e1bf10cf4e9
34,583
def create_candlestick(open, high, low, close, dates=None, direction="both", **kwargs): """ **deprecated**, use instead the new_plotly.graph_objects trace :class:`new_plotly.graph_objects.Candlestick` :param (list) open: opening values :param (list) high: high values :param (list) low: low valu...
1c0e8afba2f9f03924b84fccce470b675266d698
34,584
def sine_f0(duration: float, srate: int) -> np.ndarray: """Return the f0 contour of a sine wave of duration seconds long.""" sine_arr = np.sin(2 * np.pi * np.arange(srate * duration) * 440.0 / srate).astype( np.float64 ) f0 = pyworld.stonemask(sine_arr, *pyworld.dio(sine_arr, srate), srate) ...
aaaed0934317c884d3b7d3814fc55520f605888d
34,585
import os import torch def prepare_graph(data_folder: str, topology: str, n_nodes: int): """ Generates the graph adjacency matrix, assigns positions for plotting with Kamada-Kawai layout. All data are stored under the folder `{data_folder}/{topology}` path. :param data_folder: A string containing the ...
e29460e32407a8674110e155c747e182c4924bcd
34,586
from typing import Dict def make_opts(string: str) -> Dict[str, str]: """Parse Make opts, eg "DEBUG=1 TILES=1" => {"DEBUG": "1", "TILES": "1"}.""" if string: return {arg: val for arg, val in (opt.split("=") for opt in string.split(" "))} else: return {}
0b76c17040e69f9ba69e0b4839e36ca5d94f1ec4
34,587
import requests def generate_download_list(years, doctype='grant'): """ Given the year string from the configuration file, return a list of urls to be downloaded """ if not years: return [] urls = [] link = 'https://www.google.com/googlebooks/uspto-patents-grants-text.html' if doctype ...
94259e49a9491f2d95643c6e0dfb8507a95748be
34,588
from typing import Union import uuid import base64 def readable_uuid(source: Union[str, uuid.UUID], *, _tt=str.maketrans('+/', '-_')) -> str: """ Formats the given UUID using modified base64 without padding. Returns a string of exactly 22 characters length. """ if isinstance(source, str): ...
fd0ff92ef177f2c456686c67fcb5895e34cb2409
34,589
def auto_sigma_y(sino, weights, snr_db = 30.0, delta_pixel = 1.0, delta_channel = 1.0): """Computes the automatic value of ``sigma_y`` for use in MBIR reconstruction. Args: sino (ndarray): 3D numpy array of sinogram data with shape (num_views,num_slices,num_channels) weights (ndarra...
f76f2abfee6466d9a50d04e1eaecda485a24935c
34,590
def neighborhoods(as_geo=False): """Neighborhood names and centers (lon, lat). Note: Names take from from the Parking meter data at: http://seshat.datasd.org/parking_meters/treas_parking_meters_loc_datasd.csv Location taken from wikipedia, or manual estimates derived via Google Maps. (This should ...
202ffaad18d0158b109df0797c510ee514cb1922
34,591
from typing import Tuple from typing import Any from typing import Optional import json def list_projects(base_url: str, api_key: str) -> Tuple[Any, Optional[error.URLError]]: """GET /projects.[format]""" try: params = { "key": api_key } req = request.Request(f"{base_url}/p...
ca1ae2bae493082c1ec810d7acd3046ebd5f518d
34,592
def TMC_GetSimpleMea(WaitTime=100, mode = 1) : #TMC_GetSimpleMea - Returns angle and distance measurement - geocom manual p.95 """ [GeoCOM manual **p132**] Returns the angles and distance measurement data. This command does not issue a new distance measurement. A distance measurement has to be started ...
4c2f9018f1ffc6463f1e6dd94c42392a37945bfd
34,593
def index_at_direction(cell_index_array, direction): """ Returns the index of the neighbouring cell in the given direction""" index_array = cell_index_array.copy() if ( (index_array[1] == GRID_SIZE - 1 and RIGHT in direction) or (index_array[1] == 0 and LEFT in direction) or (index_array[0] == 0 and UP in dir...
c7127556b876133e2af1620d257832e95ac71b28
34,594
def _create_average_ops(params): """Build moving average ops.""" tf.logging.info('Creating moving average ops') with tf.variable_scope('moving_average'): moving_average_step = tf.get_variable( 'step', [], dtype=tf.float32, trainable=False) all_vars = tf.trainable_variables() average_pairs = [] ...
39e358056753f08f51b486eb20dddeac28f8375e
34,595
def reset_color_picker(modal_open, font_color): """ Reset the color-picker to white font color after closing the modal component. Parameters ---------- modal_open : bool A boolean that describes if the modal component is open or not font_color : dict of { 'hex': str, ...
03aaf2207f351eee70fbc8dda406ec0d8bc04530
34,596
import os import sys def generate_extension(ext_def): """Generate extension constructors.""" assert "name" in ext_def, "invalid extension name" ext_path = ext_def["name"].replace(".", os.path.sep) + ".pyx" ext_root = os.path.dirname(ext_path) ext_def["sources"] = [ext_path] if "extra_object...
4f63347787fd239e38c73cab876f046a631dbb2d
34,597
from typing import Any from typing import List def get_tree_effects(tree: Any) -> List[str]: """ Return all effects of a tree as action strings. I.e. traverses the tree and returns the first child of each falback node, and the postconditions of the last child of each sequence node. Args ----...
440dc454ce8e32b87a4c7711f408398d757c90ca
34,598
def obtainTagVersionList(adshList, fileLocation): """ Scans the Pre file to find the Tags and the Versions used in the filing in question so as to populate the Tags table with only that subset """ with open(fileLocation + 'pre.txt') as fileHandle: tagVersionList = list() # read schema and adv...
217aaf4a9458404cb2082ec0f8bb6bba0a5d991a
34,599