content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def system(cmd): """Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- None : we explicitly do NOT ret...
591c03e6555a271ae3152890888963928bb66d2e
3,619,800
def make_dataset(name, args): """ Creates the dataset with the given name. Parameters ---------- name: the name of the dataset to create. args: hyper-paremeters for the dataset. Returns ------- dataset_fn: a function which creates the specified dataset. """ if name not in _data...
13a06cba585f673a83fcfdbdf1ab32874ac51d65
3,619,801
def create_df(client, candles): """ Создаеv датафрейм для списка свечей :param dict candles: List of candles from API :return: DataFrame with candles """ df = DataFrame([{ 'time': c.time, 'volume': c.volume, 'open': cast_money(client, c.open), 'cl...
4d84cd1c5368586926fcbfd4104aac74c6f807ef
3,619,802
import select def current_user(request, user_id=None): """Return the list of all the users with their ids. """ print("TODO Take time and refact this s...") session = request.dbsession if user_id is not None: userid = user_id else: userid = int(request.authenticated_userid...
8cea15008da2aaa8897a6f88582d4b4154e600f7
3,619,803
def istext(obj): """ Deprecated. Use:: >>> isinstance(obj, str) after this import: >>> from future.builtins import str """ return isinstance(obj, type(u''))
60f3d751f22ad4d120ce7624dd9a07d2c841e206
3,619,804
def track_to_p_matrix(track, char_map=CHAR_MAP, x_vel_limits=None, y_vel_limits=None, x_accel_limits=None, y_accel_limits=None, max_total_accel=np.inf): """ Converts a map described by a list of strings to P-matrix format for an OpenAI Gym Discrete environment. Maps are specified usin...
68cddbbd0b8bd9bd1b0a0cf33c0d5eb4b9a22a31
3,619,805
def crc16(string, value=0): """CRC-16 poly: p(x) = x**16 + x**15 + x**2 + 1 @param string: Data over which to calculate crc. @param value: Initial CRC value. """ crc16_table = [] for byte in range(256): crc = 0 for _ in range(8): if (byte ^ crc) & 1: ...
e31ddafc6216b682d9cd0ac24a9fb634f1be1fb8
3,619,806
def get_fpn_featureMaps(features,num_filt=256): """ features: list of different maps produced by a backbone **Resnet50** : for resnet50 it contains all the 5 feature maps from each block Return: list of pyramid features """ C1,C2,C3,C4,C5 = features C5d1 = keras.layers.Conv2D(num_filt,(...
3b265bb62163cc075e8aa608bbbf21b654df4b98
3,619,807
import time def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). S...
bd225cd4ecd5af4a9ee9f29137e46807bf534ee9
3,619,808
def Interface_Static_Standards(*args): """ * Initializes all standard static parameters, which can be used by every function. statics specific of a norm or a function must be defined around it :rtype: void """ return _Interface.Interface_Static_Standards(*args)
85dfea02a10d62203eaf7afe814b7ee25b925cfe
3,619,809
from typing import Sequence from typing import Dict from typing import List def batch_inputs(input_records: Sequence[Dict[K, V]]) -> Dict[K, List[V]]: """Batch inputs from list-of-dicts to dict-of-lists.""" assert input_records, 'Must have non-empty batch!' ret = {} for k in input_records[0]: ret[k] = [r[...
c7e5a13258b131f93d11886f114d49b8804c3bd1
3,619,810
def chunks(seq, size): """Breaks a sequence of bytes into chunks of provided size :param seq: sequence of bytes :param size: chunk size :return: generator that yields tuples of sequence chunk and boolean that indicates if chunk is the last one """ length = len(seq) return ((seq...
25abe8afdb032af0e2b10dbd3c03b369d862813f
3,619,811
def compare( left, right, left_label="left", right_label="right", drop_close=True, **kwargs ): """Compare the data in two IamDataFrames and return a pandas.DataFrame Parameters ---------- left, right : IamDataFrames two :class:`IamDataFrame` instances to be compared left_label, right_la...
0820c606a93d3e12c333d43018f55f53407ff530
3,619,812
from sys import path def locate_package_directory(): """Identify a directory of the package and its associated files.""" try: return path.abspath(path.dirname(__file__)) except Exception as path_error: message = ('The directory in which the package and its ' 'associated ...
690b309e3348d9c606a9fc8a023fd240c5855b77
3,619,813
def combine_shuffle(parcellation, scale, spatnull, alpha): """ Combines outputs of all simulations into single files for provided inputs Parameters ---------- parcellation : str Name of parcellation to be used scale : str Scale of `parcellation` to be used spatnull : str ...
6e56b3d57e0c14b7a624f406e66c3a902590a2db
3,619,814
def tcycle(iterable, n): """ >>> tcycle([1, 2, 3], 2) (1, 2) >>> tcycle([1, 2, 3], 4) (1, 2, 3, 1) """ return tuple(islice(cycle(iterable), n))
d836316de1dd91770d662aca9fb024c702499317
3,619,815
from typing import List from typing import Callable from typing import Any from typing import Union from typing import Tuple def compute_best_permutation(x: List, y: List, sim: Callable[[Any, Any], Union[bool, int, float]], agg: Ca...
4d0c9a4d1a719c6b67f585e13fb803f8ff81bb6e
3,619,816
import torch def change_box_order(boxes, order): """Change box order between (xmin,ymin,xmax,ymax) and (xcenter,ycenter,width,height). Args: boxes: (tensor) bounding boxes, sized [N,4]. order: (str) either 'xyxy2xywh' or 'xywh2xyxy'. Returns: (tensor) converted bounding boxes, sized [N...
6dd1ef6d2370c79de7ec321ab16592316b7b75da
3,619,817
def GetLidarSimulation(environment,position,orientation): """ This function simulates the operation of the LIDAR by returning a list with the polar coordinates of the location of the obstacles environment -> List with all objects that are in the circuit as well as the edges of the circuit posi...
18b82528945a541411f21f36015c6518cd0e81fd
3,619,818
import ast def For_range(t, x): """Special conversion for ``for name in range(n)``, which detects ``range()`` calls and converts the statement to: .. code:: javascript for (var name = 0, bound = bound; name < bound; name++) { // ... } """ if (isinstance(x.target, ast.Name)...
e1d71e1c76798e7282c67de01dd7ff281ef28f9e
3,619,819
def calculate_G3( n_numbers, neighborsymbols, neighborpositions, G_elements, gamma, zeta, eta, cutoff, cutofffxn, Ri, normalized=True, image_molecule=None, n_indices=None, weighted=False, ): """Calculate G3 symmetry function. These are 3 body or angular i...
41b8e163da879ca9e0339f8ac79f3f3d1abfb6fe
3,619,820
import fractions def decimals(): """Generates instances of decimals.Decimal.""" return ( floats().map(float_to_decimal) | fractions().map( lambda f: Decimal(f.numerator) / f.denominator ) )
b8e376543fc6182e5a9b6434865410f0950d622b
3,619,821
def is_index(obj): """Verifies whether an object is a table index.""" return isinstance(obj, _supported_types().index_types)
e658951433b63e67ddbc4a98439569b1fb5b98fc
3,619,822
def stack_controls(controls: list[dict], key: str = "tau"): """ Stack the controls in one vector Parameters ---------- controls : list[dict] List of dictionaries containing the controls key : str Key of the controls to stack such as "tau" or "qddot" """ the_tuple = (c[ke...
8936bfbb1e4074cc79157fbdffaeb9e75de93f3a
3,619,823
def secondYAxis(requestContext, seriesList): """ Graph the series on the secondary Y axis. """ for series in seriesList: series.options['secondYAxis'] = True series.name= 'secondYAxis(%s)' % series.name return seriesList
d1c34f16da1f2142021c845afffb63b595e2ce69
3,619,824
def _next_incompatible_version(version): """ Find the next non-compatible version. This is for use with the ~= compatible syntax. It will provide the first version that this version must be less than in order to be compatible. :param str version: PEP 440 compliant version number :return: T...
7a9bdddf27cdd06e975236b0e7a64ae38d08bc98
3,619,825
def SNR_tot(G, BP, RP, J, H, K, lum, mass, teff, rad, numax, s=1., deltaT=1550, Amax_sun=2.5, obs='kepler-sc', D=1): """ predicted S/N for a given set of parameters INPUT: mag - relevant magnitude e.g. V or Kp for kepler... lum - luminosity in Lsun mass - stellar mass in Msun ...
14c1f2d1b612fa5a4c1a3b820b14d7d49cab563e
3,619,826
def checkFormat(DATAFIL): """ check the file format """ # Open file, read first 4 bytes as string f = open(DATAFIL, 'rb') dataBytes = np.fromfile(f, dtype=np.uint8, count=4) data = "".join(map(chr, dataBytes)) f.close() # If string matches a particular format, return format if d...
8e82a9f3a62092dbe75d7d948756eecc026b4b45
3,619,827
from datetime import datetime import csv def parse_csv(csv_path, ftype='csv', dt_col="date_time", dt_format="%Y%m%d %H:%M:%S", dni_col='DNI', dhi_col='DHI', stime=None, etime=None): """Parse a csv file containing direct normal and diffuse horizontal data, ignoring NULL and zero...
e29c7dbbb71b0353ceec0522ecab382f429d3c6a
3,619,828
import re def has_surr_char(string): """ Returns True if the given string contains any 'surround' characters, False otherwise. These characters many cause bugs in programs if used. """ re1 = re.compile(INVALID_CHARACTERS) if re1.search(string): return True else: ret...
4da7ee3c2041e2dc113b65e55233d6aad9e978ad
3,619,829
import logging def CreateChrootSnapshot(snapshot_name, chroot_vg, chroot_lv): """Create a snapshot for the specified chroot VG/LV. Args: snapshot_name: The name of the new snapshot. chroot_vg: The name of the VG containing the origin LV. chroot_lv: The name of the origin LV. Returns: True if t...
ef804e01da6143b2ff4393a27a6db16c66fc5ff4
3,619,830
import typing def decode_u256(as_bytes: typing.List[int]) -> int: """Decodes an unsigned 256 bit integer. """ size = as_bytes[0] if size <= NUMERIC_CONSTRAINTS[CLTypeKey.U8].LENGTH: return decode_u8(as_bytes[1:]) elif size <= NUMERIC_CONSTRAINTS[CLTypeKey.U32].LENGTH: return d...
0fd8e9a47a805d9d56c6d019c470e22a06e0c606
3,619,831
def import_image( dbsession, account: str, operation_id: str, import_manifest: ImportManifest, force: bool = False, annotations: dict = None, ) -> dict: """ Process the image import finalization, creating the new 'image' record and setting the proper state for queueing :param dbsess...
e385bfd6032cd7919dae325d2021f4cf15ea27a5
3,619,832
def image_code(): """ 图片验证码的实现逻辑 1. 获取参数 图片验证码的随机值 ! 切记! 一定要判断 2. 生成图片验证码 3. 将图片文字和随机值保存到redis中 4. 将图片验证码 返回 :return: """ image_code_id = request.args.get("imageCodeId", None) # 判断参数是否有值 if not image_code_id: abort(403) # 生成图片验证码 name, text, image = capt...
cb154182071efd367d1229e058cf90166b7bea44
3,619,833
from typing import Union from pathlib import Path from typing import Optional def clone_renku_repository( url: str, path: Union[Path, str], gitlab_token=None, deployment_hostname=None, depth: Optional[int] = None, install_githooks=False, install_lfs=True, skip_smudge=True, recursiv...
1fbc1941b670caab64619705c666d636f0f6bcf1
3,619,834
import os def traintest_split(data_dir='.', in_extension='.obfs', save_dir=None, save=True, trainfile='train', testfile='target', recurse=0, testsize=0.1): """ Implements the sklearn train_test_split function in a recursive fashion """ w...
e0c987c80d0d04dcd7012fa109623c360809af83
3,619,835
def display_content(value): """This callback is used on the User Guide page and returns the selected User Guide when a user selects a certain tab. User Guides can be added to HIVE in the userguide.py page. """ return userguide.user_guide(value)
f47dd22f395b8b249d2d2bfc1d14a09f6004325b
3,619,836
def adjust_anomaly_scores(scores, dataset, is_train, lookback): """ Method for MSL and SMAP where channels have been concatenated as part of the preprocessing :param scores: anomaly_scores :param dataset: name of dataset :param is_train: if scores is from train set :param lookback: lookback (win...
2f6adcdcae841573b362f1629138fdc70a568a24
3,619,837
import mpmath def sf(k, nc, ntotal, ngood, nsample): """ Survival function of Fisher's noncentral hypergeometric distribution. """ _hg._validate(ntotal, ngood, nsample) sup, p = support(nc, ntotal, ngood, nsample) if k < sup[0]: return mpmath.mp.one elif k >= sup[-1]: retur...
4b4915b3bc2a9201bb66fca3e630cf59cd9afc8e
3,619,838
def part_2_solution(graph, search_key): """ keeps a persistant counter that is recursively passed into a helper function for ever depth of the helper function, the branch product gets updated, when a recursive function exits it updates the counter with the product of counts for each sub-bag the co...
16ac48370de6d94397747b6b16791e0615f390aa
3,619,839
def example3(): """Demonstrates exception handling, peek, reduce. """ def square_and_raise_on_3(x): if x == 3: raise ValueError('unaccepted value') return x ** 2 result = (Pipes(_EXAMPLE_COLLECTION) .lz_map(lambda x: x['size']) .lz_peek(lambda x:...
962ebdbabe1fd0e2fe0c9cf09964b996b0385a02
3,619,840
def get_func_qty(*args): """get_func_qty() -> size_t""" return _idaapi.get_func_qty(*args)
affa7952d604fd20674cadbe76cd9f55db669c14
3,619,841
def is_model_quantized(sym_model): """Checks whether the model is quantized. Args: sym_model (tuple): symbol model (symnet, args, auxs). Returns: boolean: True if model is quantized, else False. """ assert isinstance(sym_model, tuple) and isinstance(sym_model[0], mx....
32e8fd62bbc3280c0edd158194e8e7b2ffee53bf
3,619,842
def evaluate(bounds, func): """ Evaluates simpsons rules on an array of values and a function pointer. .. math:: \int_{a}^{b} = \sum_i ... Parameters ---------- bounds: array_like An array with a dimension of two that contains the starting and ending points for the int...
af5102d37c1943420a0ff3fff980342ee8c9dad9
3,619,843
def process_image(image, target_shape): # downsampling to desired shape """Given an image, process it (downsample if needed) and return a numpy array.""" h, w, c = target_shape image = load_img(image, target_size=(h, w)) # Load the image. Downsampling included! e.g. to (32,32,3) img_arr = img_to_array(...
968daaf8da198fc4ce129ea07c57c84942dc86ab
3,619,844
import hashlib def get_dataset_id(settings): """ Creates and returns an unique ID (for practical purposes), given the data parameters. The main use of this ID is to make sure we are using the correct data source, and that the data parameters weren't changed halfway through the simulation sequence. """...
a696f0f85c8ee9c3cab975838db520cc061dfaf4
3,619,845
def get_sampler_diags(fit): """Returns useful sampler diagnostics for a particular MCMC fit with pystan""" rhat=fit.summary()['summary'][:,-1] rhat_worst=rhat[np.abs(1-rhat)==max(np.abs(1-rhat))][0] n_eff_int_site=int(fit.summary()['summary'][0,-2]) return rhat_worst,n_eff_int_site
acee6147024ae32116e8b905eae18d8e47125148
3,619,846
def get_category(url=None, category='nieruchomosci', transaction_type='wszystkie', voivodeship=None, city=None, street=None, filters=None): """ Parses available offer urls from given category search page :param url: Url to search web page :param category: Type of property of interest (Mies...
60aa51056bb209de8b777a7977504ab04847b6a2
3,619,847
def wmt_preprocess(dataset, training, max_length=-1, max_eval_length=-1): """Preprocessing for LM1B: filter out targets exceeding maximum length.""" def train_right_length(example, target): l = tf.maximum(tf.shape(example["inputs"])[0], tf.shape(target)[0]) return tf.less(l, max_length + 1) def eval_rig...
870d1c1a7b6ee8e2a9c424884558355d4164a6d6
3,619,848
import torch def instance_masks_to_semseg_mask(instance_masks, category_labels): """ Converts a tensor containing instance masks to a semantic segmentation mask. :param instance_masks: tensor(N, T, H, W) (N = number of instances) :param category_labels: tensor(N) containing semantic category label fo...
127c9b9ff3d1044b1c5e1e8650ed493f8a4bc6de
3,619,849
def URem(a, b): """Create the SMT expression (unsigned) remainder `self % other`. Use the operator % for signed modulus, and SRem() for signed remainder. >>> x = BitVec('x', 32) >>> y = BitVec('y', 32) >>> URem(x, y) URem(x, y) >>> URem(x, y).sort() BitVec(32) >>> (x % y).sexpr() ...
e37ed84f308e0936880f134344c9563428110059
3,619,850
import requests def _make_request(endpoint: str) -> dict: """Helper method handles terra fcd api requests. [Source: https://fcd.terra.dev/v1] Parameters ---------- endpoint: str endpoint url Returns ------- dict: dictionary with response data """ url = f"https://f...
85617c3fbba2b8bd3624e50837f3f9fecd97555d
3,619,851
import time def fix_end_now(json): """Set end time to the time now if no end time is give""" if 'end' not in json or json['end'] is None: json['end'] = int(time.time()) return json
2c126e00ac293c6a511cb86457d60536f1d690ef
3,619,852
import os def load_and_concate(rfiles): """ Loads and concatenates radiomic features from different MR contrasts Args: rfiles (list): list of radiomic files (one for each scan) Returns: pandas dataframe: radiomic features """ animal_id = [] for i, file in enumerate(rfiles...
bc6813097f00d0c7f23b4c362cdaca1a2323659c
3,619,853
def file_to_bounding_boxes(file_path, output_folder=None, save_images=False, **kwargs): """ file_path: path to image file. """ # read image using PIL: image = Image.open(file_path) # convert to numpy array: image_numpy = np.asarray(image) # Predict bounding boxes and store to dictionar...
60efc4bfb7c5fbe6d97658f4b54888bcb8415091
3,619,854
def count_parameters(net, trainable=False): """Counts the parameters of a given PyTorch model.""" params = trainable_parameters(net) if trainable else net.parameters() return sum(p.numel() for p in params)
4fc2b7fe1c40bb60db48270da4b03dcdd8499728
3,619,855
def prepare_computational_basis(nqubits, number): """Encode number as binary and create the circuit""" # Create empty circuit of requested size qc = QuantumCircuit(nqubits) # encode number into a byte array ba = int2ba(number, nqubits); # Populate the circuit for q in range(nqubi...
ca2d1d3ca6b153aa02cedf45a7f80647ef7dbbc0
3,619,856
def dropout(x, rate, is_training): """drop out layer""" return tf.layers.dropout(x, rate, name='dropout', training = is_training)
1965781d9b16708e5c0dc8c8b153bd2d24c13395
3,619,857
def get_cell_inj_span(test_line): """ Return the location of %cell in the given line as (start_index, end_index), or None if %cell does not occur. """ if not test_line.strip().startswith(CELL_INJ_TOKEN): return None else: cell_start = test_line.index(CELL_INJ_TOKEN) cell_...
bd844a139cbd28b697b877c07f094d56094f7460
3,619,858
def in1u_w(name, shape, seed=None, regu=None): """ Convolutional Architecture for Fast Feature Embedding. FAN_IN, factor=1.0, uniform=True. """ init = tf.contrib.layers.variance_scaling_initializer( factor=1.0, mode="FAN_IN", uniform=True, seed=seed) return w(name, shape, tf.float32,...
992d3e19eaa869d3da67d480382f73728918e773
3,619,859
def topics_to_calldata(topics, bytes_per_topic=3): """Converts a list of topics to calldata. Args: topics (bytes[]): List of topics. bytes_per_topic (int): Byte length of each topic. Returns: bytes: Topics combined into a single string. """ return b''.join(topic.to_bytes(b...
2d500016963934fdbc60b388632b817624d5ad8d
3,619,860
def read_size(calibxml): """ This function extracts the size of an image from the xml file. .. note:: Usually, it is similar to "AutoCal_[Focal]_[CameraName].xml" Parameters ---------- calibxml : str Name of the camera calibration file Returns ------- np.ndarra...
5fb106c54ed63a13c6f8ae312fb2e5b6055a0a20
3,619,861
import re def get_packages_names(latex_file): """Find all the package name in a file Args: latex_file: A pathlib file Returns: A list of all the package name found in the latex_file """ with latex_file.open('r', encoding='utf-8') as f: data = f.read() packages_info ...
6eb1b1c02ef254fa6e112ecbae960060af3b7405
3,619,862
def remove_basic_block_assembly(pydot_cfg): """ Remove assembly text from the CFG's basic blocks """ # Avoid graph and edge nodes, which are the 1st and 2nd nodes nodes = pydot_cfg.get_nodes()[2:] for n in nodes: n.set_label("") return pydot_cfg
3ca5d7fcd46dc96bff92aea67b47afbe53accc40
3,619,863
import sys def python(*args, **kwargs): """Run a python script with the current interpreter.""" return exec_getout(sys.executable, *args, **kwargs)
4f7622f5d5cf2427ffb79661bc70258ee7caa03d
3,619,864
def CheckNaN(data): """ Raise exception if data contains NaN. Useful to stop training if network doesn't converge and loss function returns NaN. Example: samples >> network.train() >> CheckNan() >> log >> Consume() >>> from nutsflow import Collect >>> [1, 2, 3] >> CheckNaN() >> Collect() ...
c6d10a034a787e53ef493c755e326bd374131427
3,619,865
from typing import Any def build_patch302_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest: """Patch true Boolean value in request returns 302. This request should not be automatically redirected, but should return the received 302 to the caller for evaluation. See https:/...
300330aea3a177307e52d77f55df9844f367e39b
3,619,866
def construct_array(nums): """ :param nums: array :return: mul array """ l = len(nums) ans = [1 for _ in range(l)] p = q = 1 for i in range(l): ans[i] *= q ans[-i - 1] *= p q *= nums[i] p *= nums[-i - 1] return ans
5327945cbb83290af94efcce07e4ae391fb3da45
3,619,867
def create_col(card: dbc.Card) -> dbc.Col: """Pass each card to create a Col element""" return dbc.Col( className="mb-2", children=[card], width=12, sm=12, lg=6, xl=4 )
8624d68e7a80cefe6587a614150aed0023412428
3,619,868
import argparse import os import json import shutil def main(): """ Use pw_module_tests.testinfo.json files to find and copy fuzzers. """ parser = argparse.ArgumentParser() parser.add_argument('--buildroot') parser.add_argument('--out') args = parser.parse_args() print(' buildroot: ' + args.buildroot) ...
bcbbda75629e9186d37387ccad02b5560ad4342c
3,619,869
def make_report(subreads, output_dir, dpi=DEFAULT_DPI): """ Create a basic subread metrics report. Since this may be run either as an independent tool or as part of the barcoding report, it handles the .pbi file reading flexibly. """ pbi_stream = get_pb_index_streamed(subreads) dists, uniqu...
469f22291ff591aeaf6219a97eb09aa4d4ad966c
3,619,870
def return_point(m, n, p): """ m is the index number of the Hammersley point to calculate n is the maximun number of points p is the order of the Hammersley point, 1,2,3,4,... etc l is the power of x to go out to and is hard coded to 10 in this example :return type double """ if p == 1:...
73b1c75d6b4ebdc6a0616d9a7b2d6207a4728316
3,619,871
def select2_css_url(): """ Return the full url to the Select2 CSS file. """ return get_select2_setting('css_url') or \ select2_url('css/select2.min.css')
ea9cac6f9e687620ed3cc8d4c45d33e551df3dbe
3,619,872
def GetQuasiSequenceOrder(ProteinSequence, maxlag=30, weight=0.1): """ ############################################################################### Computing quasi-sequence-order descriptors for a given protein. [1]:Kuo-Chen Chou. Prediction of Protein Subcellar Locations by Incorporating Quasi...
99b0d6129f2693893382493a3de241cd00f75b68
3,619,873
def OverscanTrim(d,ds): """ Overscan correct and Trim a refurbished HIRES image """ ds = ds.split(',') dsy = ds[0][1:] dsx = ds[1][:-1] dsy = dsy.split(':') dsx = dsx.split(':') x0 = int(dsx[0])-1 x1 = int(dsx[1]) y0 = int(dsy[0])-1 y1 = int(dsy[1]) newdata = d[x0:x1]...
ceb434ca75f458c43137b73b89c0f0242bfe7e93
3,619,874
import requests def requests_put(url, expected_sc=200, **kwargs): """ Calls our above requests wrapper for a PUT request, and sets the default expected status code to 200. """ return do_request_with_auth_retry(url=url, method=requests.put, expected_sc=expected_sc, **kwargs)
3c5aa69d8b21e67960cfff76820ccf2b64a6f879
3,619,875
def calculate_decomposition(data, model=MODEL_ADDITIVE, frequency=2): """ Calculate time series decomposition Args: data (list[float]): Input time series values model (str): Seasonal component type frequency (int): Seasonal component frequency Returns: dict: Calculation...
444e05c5f36479f7c1ddbd8c7fbb3d6785d6bf2f
3,619,876
from typing import List from typing import Dict def add_funders_relationships(funders: List, funders_by_key: Dict) -> List: """ Adds any children/parent relationships to funder instances in the funders list. :param funders: List of funders :param funders_by_key: Dictionary of funders with their id as key...
4411094812ae3932453f4cbb33f8c845fca6f800
3,619,877
import re def __tokenize(syntax) -> list: """ Validate and tokenize the syntax. Valid syntax: snake_case_words, integers, plus, minus. """ if not re.match(r"^[\w\d\s\+-]+$", syntax): raise SyntaxError("Invalid syntax.") syntax = re.sub(r"\s*([+-])\s*", r" \g<1> ", syntax) return ...
68e79222987771d964ac0d39e38c425d710d3765
3,619,878
import copy def reducer(state, action): """Screen specific reducer Given :func:`screen.set_position` action adds "position" data to state :param state: data structure representing current state :type state: dict :param action: data structure representing action :type action: dict """...
2c918ee2b9ae40689f1df4de6b48a1da951716de
3,619,879
def see_model_list(): """ Get's the data about all models in the DB to put on a table: - name - organism - strain Returns: render_template to see_data with tab_status set to models. """ tab_status = {"enzymes": "#", "metabolites": "#", "models": "active", "organisms": "#", "...
1edcdc1382d3a6d26f22e8e5ffcb9a5f1c294742
3,619,880
def localsys_get_login(): """Retrieves the login credentials from the computer you are on. Good for command line tools""" try: sid = local_credentials.get_password('minervaclient_sid','minerva') pin = local_credentials.get_password('minervalcient_pin','minerva') if sid is None or pin...
d3c6a5870680f8688816e158015260d598c001fe
3,619,881
def GetOrigFn( module, fnName ): """Return the original function.""" return DictGet( orig_fns, ( module, fnName ), getattr( module, fnName ) )
cb36ff0baa63abd08ac9651a251cd6feb2e7913b
3,619,882
import platform def host_toolchain(xcrun_toolchain='default', tools=None, suffixes=None): """ Return a Toolchain with the first available versions of all specified tools, plus clang and clang++, searching in the order of the given suffixes. If no matching executables are found, return None. "...
d385dc97ea2051282b5d096fb1243783d067c46a
3,619,883
def transcribe_audio(audio_stream, model: str, language_code: str): """ Transcribe the given audio chunks """ global client encoding = RecognitionConfig.AudioEncoding.LINEAR16 try: audio = RecognitionAudio(content=audio_stream) config = RecognitionConfig( s...
0c2c0c7c5455cdb79965bd38108a6e71ddde41a9
3,619,884
def indent(yaml: str): """Add indents to yaml""" lines = yaml.split("\n") def prefix(line): return " " if line.strip() else "" lines = [prefix(line) + line for line in lines] return "\n".join(lines)
815babb29378f1cfac6ada8258322df92235fc9e
3,619,885
def smooth_pr(prec, rec): """ Smooths precision recall curve according to TREC standards. Evaluates max precision at each 0.1 recall. Makes the curves look nice and not noisy """ n = len(prec) m = 11 p_smooth = np.zeros((m), dtype=np.float) r_smooth = np.linspace(0.0, 1.0, m) for i in range(m): j = np.argmi...
6129cb1348446df2f56eb5601cac585c498d5311
3,619,886
def get_rbac_role_assigned(self) -> dict: """Get list of accessible menus based on the current session permissions .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - rbacRole - GET - /rbac/role/menuAssigned .. no...
91d0dcbded36b857a0dc0ddfeaa2815516d162f6
3,619,887
def close_session(module_session): """Closes the Shell Interactive Session Args: module_session (object): The module session object that should be closed Returns: A dict holding the result message """ module_session.close() return Response.ok("The Shell Interactive session has be...
45bc4a094e8d33320efb1b5738ee59fddc344f46
3,619,888
def Xfact(m): """Xfact(m) Computes (2m-1)!!/sqrt((2m)!) """ res = 1. for i in xrange(1,2*m+1): if i % 2: res *= i # (2m-1)!! res /= np.sqrt(i) # sqrt((2m)!) return res
23653360ef3f8f5d4e5b9cdb16e8ab58835960cf
3,619,889
import os def process_csv(csv_file=None): """ Function to read the content(s) of CSV file(s). The function reads the contents of CSV file(s) available in a certain directory and populate a dictionary with e-mail id as key in order to have unique e-mails. :param csv_file: Name of the csv_file...
00368fff96e0c254b57f395e1b4ba769a01f995d
3,619,890
import requests def stacks_list(credentials): """ List the stacks accessible to the currently logged in user. """ url = _urljoin(credentials["host"], "api/a0.1/stacks/") headers = {"Authorization": "Token {}".format(credentials["token"])} resp = requests.get(_ensure_protocol(url), headers=head...
9a63b7a402104f41f6a7c1f9c023b979428b088f
3,619,891
def remove_0x_head(s): """ Better use from django_eth_events.utils import remove_0x_head, because in pyEthereum version <= 1.6.1 is bugged for Python3 """ return s[2:] if s[:2] in (b'0x', '0x') else s
b903e6eb97e8cb5fc2d7b216cdabcdc2f3b157a0
3,619,892
def build_doc(cls, **kwargs): """Decorator to build docstrings for datalad commands It's intended to decorate the class, the __call__-method of which is the actual command. It expects that __call__-method to be decorated by eval_results. Note that values for any `eval_params` keys in `cls._params_...
570d149ca0c56c5d85ed3eaff366d4843fa3fa2d
3,619,893
from typing import List def get_dev_requirements() -> List[str]: """Fetch requirements for library development.""" with open(_DEV_REQUIREMENTS, mode="r") as f: return f.readlines()
b0f9a4a958d64ff3da0c7622fb6dcea69dd95de5
3,619,894
def wait_result(ref): """ Waits for the referenced agent to finish, whereupon its latest result will be returned. Args: ref (uuid.UUID): The UUID of the agent. Usually received when a window is created. Raises: KeyError: When an agent with the given UUID could not be fo...
afa95f1378813da5bedeea3d2e9aa2c3a5b7108b
3,619,895
import torch from typing import Tuple def mask_tokens(inputs: torch.Tensor, tokenizer: PreTrainedTokenizer, args) -> Tuple[torch.Tensor, torch.Tensor]: """ Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. """ if tokenizer.mask_token is None: raise ...
7f633b0c08de12655b406c852dd038aca3dd64d4
3,619,896
def _has_sectors(tax_name: str, ignore_sectors: bool) -> bool: """Determine whether we are doing a sector-based forecast.""" return tax_name in ["birt", "sales", "wage", "rtt"] and not ignore_sectors
5725693c514937988b4e668c699606cb3ab46d10
3,619,897
import tqdm def merge_modules(pose_graph, module_corners, observations, image_width, image_height, merge_threshold, max_module_depth, max_num_modules, max_combinations, reproj_thres, min_ray_angle_degrees): """Merge duplicate modules by projecting each module into each keyframe and finding overlapp...
d228530251074b39abf5234be0418818f224c867
3,619,898
def KK_RC23_fit(params, w, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ Rs = params["Rs"] R1 = params["R1"] R2 = params["R2"] R3 = params["R3"] R4 = params["R4"] R5 = params["R5"] R6 = params["R6"] ...
fab416c023a215c62e51c6cc2e5857be8e85a063
3,619,899