content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os import re import tempfile import subprocess def CleanFile(args, filename, pattern_data_list): """Replace a pattern match with new data in the passed file. Given a regular expression pattern with a single () match, it runs the regex over the passed filename and replaces the match () with the new data....
d2d08d5d751b2b984316f59ff8fc8b4cd7e61097
666,221
def string_concatenator(string1, string2): """Combines strings together by adding them and returning the combination as an output. Parameters ---------- string1 : string String that will be added to another string. string2 : string String that will be added to anot...
a721b3bcad25d4b602fbf4ec10d2bc49a07fe533
666,222
def first_choice_counts(A,P): """ Return list giving first-choice counts, in decreasing order by count """ count = { } for a in A: count[a] = 0 for ballot in P: if len(ballot)>0: a = ballot[0] count[a] += P[ballot] L = [ (count[a],a) for a in A ] L...
986c501fc9ebc57125ae355e679a0244adb4c4cf
666,223
def setInstanceState(inst, state): """Utility function to default to 'normal' state rules in unserialization. """ if hasattr(inst, "__setstate__"): inst.__setstate__(state) else: inst.__dict__ = state return inst
2082e03ef038ed15aa20c8250757f6439614d5b6
666,224
def build_group_name(stimulus): """ Grabs the parameters from the given :class:`DotsStimulus` instance and builds a string out of them :param stimulus: a :class:`DotsStimulus` object :rtype: str """ params = stimulus.export_params() abbrev = { 'interleaves': 'intlv', 'limit_...
7cf49ecbb407a9567c3955a0e5a11cd9b6dc4abc
666,225
import itertools def flatten(param_groups): """ Flattens out a pair of list of lists representing a param_group into a single list :param param_groups: The group to flatten :return: The flattened list """ return itertools.chain(*param_groups)
90c6eb3858a6de266dee80c3eea1221652e2fab5
666,226
def compare_dataIds(dataIds_1, dataIds_2): """Compare two list of dataids. Return a list of dataIds present in 'raw' or 'eimage' (1) but not in 'calexp' (2). """ print("INFO %i input dataIds found" % len(dataIds_1)) print("INFO %i calexp dataIds found" % len(dataIds_2)) dataIds_1 = [{k: v for k...
8935c3bb4c85a5d651294b52d5345656348b192c
666,227
from typing import Tuple def split_markdown_front_matter(text: str) -> Tuple[str, str]: """ Return a tuple of (front matter, markdown body) strings split from a ``text`` string. Each can be an empty string. This is used when security advisories are provided in this format. """ lines = text.spl...
9a3260368509bde504aed43d42ccd1c2fb390acf
666,228
import os def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suff...
f1d5af657c6e75053efb1ae40dfd5542b44321a6
666,229
def check_input(s): """ This function checks the input is in correct format or not :param s: The input string of each row :return: (bool) If the input format is correct """ for i in range(len(s)): if i % 2 == 1 and s[i] != ' ': return True elif len(s) != 7: return True elif i % 2 == 0 and s[i].isalpha...
d03ee2e88e2a1db0abbc3e05387f2532ab260245
666,230
import os from pathlib import Path def mkdir(properties, folder): """ This file creates a new directory for a new measurent. The name consists of the sample, the number and a time stamp. Args: properties (dictionary): dictionary with all parameters for the measurement folder (string):...
c94f92502a7c53eb414f8c66ed459383da9228a9
666,231
import argparse def CreateCliUpdateArgParser(): """Create argparser for cli update.""" parser = argparse.ArgumentParser(add_help=False) parser.add_argument( '--cli_update_url', type=str, help='Remote url to download the latest version command line.') parser.add_argument( '--no_check_update',...
4db35f7ee57d1e9a18601bb68457ef43513e7c65
666,232
import math def get_max_version_to_year(version): """ Get 3ds Max year from the release version :return: Max release version :rtype: int .. code-block:: python import MaxPlus import dccutils release_version = app.get_max_release_version(version_id) print(app.get...
e3e362145cacb0d8d46562dab3d2b05e923f78c8
666,233
def _rename_columns(df): """sets the columns names""" df = df.rename(columns={'WINTER': 'season', 'CLOSED': 'iceon_date', 'OPENED': 'iceoff_date', 'DAYS': 'duration', 'NUM_REFREEZES': 'n_freezes', ...
d5c96c7fb42561cf71731bc8d2e2b78fb700d6ba
666,234
def season(month_number): """ Возвращает название сезона по номеру месяца. :param month_number: номер месяца. :return: строка с названием сезона. """ if month_number in [1, 2, 12]: return 'Winter' elif 3 <= month_number <= 5: return 'Spring' elif 6 <= month_number <= 8: ...
e629a5c816b424a1ee0daa63102ca54089276f09
666,235
def html(): """Returns some custom HTML""" return """ <title>This is a Hello World World Page</title> <p>Hello</p> <p><b>World</b></p> """
113b0700e9a28d730a7cd52a95fd221a2b68b5cd
666,236
import numpy def translation_from_matrix(matrix): """Return translation vector from translation matrix. >>> v0 = numpy.random.random(3) - 0.5 >>> v1 = translation_from_matrix(translation_matrix(v0)) >>> numpy.allclose(v0, v1) True """ return numpy.array(matrix, copy=False)[:3, 3].copy()
90a71b2c7a98882ad1d87d5a3ea711b02ec5027e
666,237
def decimal_to_string(fnum, no_dec=0): """ Convert a decimal to a string with no_dec decimal places """ res = '' if no_dec == 0: res = str(int(fnum)) else: res = str(round(fnum, no_dec)) return res
720708e81c1893beef997db7ec6ff710fd1a4f4a
666,238
import six def str2list(s): """Returns the string `s` as a list of lines, split by \n""" return s.strip().split('\n') if isinstance(s, six.string_types) else s
8bfae807d3c220c4cf71e39340205936454fd4ed
666,240
import re def camelcase_to_underscore(string): """Convert a given string from ``CamelCase`` to ``camel_case``. :param string: The string to be converted. :type string: str :rtype: str """ # http://djangosnippets.org/snippets/585/ return re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '...
5ea3846bbaf3a4e6ee114c17ec4e5d46048a380d
666,241
def default_mutation_stength(param): """ Returns the default mutation strength for a parameter. Based on http://www.iue.tuwien.ac.at/phd/heitzinger/node27.html. """ return (param.upper_bound - param.lower_bound) / 10
d3288ae975a4803ae09ffb3f17439c56b6cf2230
666,242
def parse_bucket_blob_from_gs_link(path): """Utility to split a google storage path into bucket + blob name. Args: path (str): A string of google cloud storage path (must have gs:// prefix) Returns: (str, str): A tuple of (bucket name, blob name) """ if not path.startswith('gs://')...
72a4ab2ce199fc754fd5e485a3fe149f312d4e04
666,243
from pathlib import Path import pickle def my_piclke_dump(var, file_name): """ This function saves 'var' in a pickle file with the name 'file_name'. We use the folder 'Pickles' to save all the pickles. Example: file_name = "test" x = 4 var = x my_piclke_dump(var, file_name) :para...
26c8715dc92b963aac54f09ee15d7f77d1dc49a5
666,244
def return_xs_unique(xs, ys): """ merge sorted lists xs and ys. Return only those items that are present in the first list, but not in the second. """ result = [] xi = 0 while True: if xi >= len(xs): # If xs list is finished, return result # We're done. ...
7c9988ca0dccca001df072b68a6ba7db2cb7f478
666,245
def cumret(ts): """Calculate cumulative returns for input time series :ts: Time series :returns: Cumulative returns """ return ((ts + 1).cumprod() - 1) * 100
a7105ff05af17b101324e1dc3fd67ec63d170d9b
666,248
def get_input_nodes(node): """ Get input nodes of node. Args: node (NodeGraphQt.BaseNode). Returns: list[NodeGraphQt.BaseNode]. """ nodes = {} for p in node.input_ports(): for cp in p.connected_ports(): n = cp.node() nodes[n.id] = n retur...
42855ff941851f1b18bf025bb5b2005a0e0516f3
666,249
def cut_to_pages(h, pgsz): """Cut each data block to pages. Args: h (list): response from `asaloader.ihex.padding_space`. pgsz (int): page size, e.g. 256, 512. Returns: list: data pages """ res = [] for sect in h: sect_addr = sect['address'] sect...
73ac1000784f814f3ed70ad53f38359ffa65d150
666,250
import os def folder_exists(folderpath): """ Check whether a folder exists by given folder path. """ return os.path.isdir(folderpath)
cc053b1bbd16748512292aba9874d6d2a19c614b
666,251
def method(func): """Decorate Builder method, so that the Builder doesn't think it's an attribute factory.""" func.is_method = True return func
f6abdc5838e612c0986fd8bb6fc4960fc4aee5c1
666,252
def rankine2celcius(R): """ Convert Rankine Temperature to Celcius :param R: Temperature in Rankine :return: Temperature in Celcius """ return (R - 491.67) * 5.0 / 9
59ffd05620dd5781bb8f5d53dc67936ae7bdb37c
666,253
import re def parsev6(addr): """Takes a string with any IPv6 address and decompress it then returns a tuple with the decompressed address as a string, as well as a list with every section, a string with the full binary address and the binary values for each field. """ addr = addr.strip("[]").l...
3cde71e27aa088f78d1a1faeb9051ff881df6447
666,254
def tags_update(tags_to_add, tags_to_remove): """Serializes the given tag updates to a JSON string. :param set[str] tags_to_add: list of tags :param str[str] tags_to_remove: list of tags :return: a dictionary suitable for JSON serialization :rtype: dict """ return { 'add': sorted(...
45972efaf997039f758c03de7e8901347d3f0bb9
666,255
import random def breed_by_crossover(parent_1, parent_2): """This function will breed 1 child for the next generation using uniform crossover. The parents of the child with the best fitness value were previously selected in the tournament. The parent1 will be then set a the new child to check that the...
71c8cc46e4053200d4222f07f115cfe487717f2f
666,256
def apply_diagnostic_inflation(cov_pop_burden_df, param_df, index): """Inflates the target_pop in df Inputs: cov_pop_burden_df - a df with the column 'target_pop' param_df - a df of parameters, must contain the columns 'inflation_factor' index - a string that is one of the i...
0ae01d78b7c8d7747b80cdf9ec6fa731769e0b84
666,258
def get_argnames(func): """Get the argument names from a function.""" # Get all positional arguments in __init__, including named # and named optional arguments. `co_varnames` stores all argument # names (including local variable names) in order, starting with # function arguments, so only grab `co...
1b1e030f85d29d724c25f4770e4214f9f17cb9fc
666,259
def convert_listlike_cols_to_str(df, list_cols, convert_nan=False, nanreplacement = "[]"): """ Convert listlike values in pandas DataFrame to stringlists. Writing a DataFrame to excel and csv raises errors due to presence of listlike or arraylike data. Here, all listlike and arraylike data is converted to ...
c932ec05038d9942cefeda85de51f6359fe67e97
666,260
def calculate_percent(numerator, denominator): """Return percentage value, round to 2 digits precision. Parameters: numerator (int): parts of the whole denominator (str): the whole Returns: float: percentage value rounded (00.00) """ percent = (numerator / denominator) * 10...
d60c540369ebd733af26888497b65dce0027cdf5
666,261
def grocery_summary(grocery_purchases): """ # Takes in a list of dictionaries sorted as store as # keys and items bought as values. Congregates the # items bought between the dictionaries and returns # the combined dictionary. >>> p1 = [{'mitsuwa': ['rice'], '99ranch': ['msg']}, \ {'99ranch': [...
ddb0c941cfe755a3576199ba80cfbbb8583c116b
666,262
def ercc6_plus_clinical(): """Create test fixture for ERCC6 MANE Plus Clinical Transcript data.""" return { "#NCBI_GeneID": "GeneID:2074", "Ensembl_Gene": "ENSG00000225830.16", "HGNC_ID": "HGNC:3438", "symbol": "ERCC6", "name": "ERCC excision repair 6, chromatin remodelin...
46eb52814b5a47912c2538bbbc626f7e4c468543
666,264
def _get_statusline(params): """Generate a mock statusline like rspec would output.""" total = sum(params.values()) statusline = 'Finished in 0.001s seconds\n' passed = params.get('passed', 0) failed = params.get('failed', 0) error = params.get('error', 0) total = passed + failed + error ...
bda52894cf2495c3fe48dfe14f1127e2e6409728
666,265
from typing import OrderedDict def list_tag_attributes(attributes): """rewrite JATS list-type attribute as an HTML class attribute""" if "list-type" in attributes: list_type_class_map = OrderedDict( [ ('list-type="alpha-lower"', 'class="list list--alpha-lower"'), ...
9f7f8ee7aaba3eb6131acbebd230cbe998cf996a
666,266
import torch def l2_normalize(tensor): """Return tensor / l2_norm(tensor).""" l2_norm = torch.norm(tensor, p=2) tensor /= l2_norm return tensor
99cfe124180955480d72a041119e5a9bf94d2efd
666,267
def combo(iter_1, iter_2): """ Assume both iterables has same length combo([1, 2, 3], 'abc') Output: [(1, 'a'), (2, 'b'), (3, 'c')] """ combo_list = [] for x in range(len(iter_1)): tupl = iter_1[x], iter_2[x] combo_list.append(tupl) return combo_list
3cff4dc991efd0ee19de0ae3533cf22aaf24ba56
666,268
def predict(model, OCR_data): """ predicts augmented OCR data based on given model args: model (sklearn.svm.SVC): trained classifier from load_model OCR_data (pd.DataFrame): from OCR_and_augment returns: prediction_dict (dict): includes name, author, text, source """ ...
4e7410486d1050d85279ce2c4e5538052ba6ea7a
666,269
def offset_hex(hex_string, offset=1): """ Returns hex string offset by the given amount. Useful for generating keys for which a given node_hash is reponsible, i.e. offset the node's hash by a negative amount """ original_length = len(hex_string) offset_string = '{:x}'.format(int(hex_string, 16) ...
e206909ae5276a13fea0e960bc576789e1b692cd
666,270
def best_model(vals): """Decide on the best model according to an Information Criterion.""" if vals[0] is not None and vals[0] == min(x for x in vals if x is not None): return 1 elif vals[1] is not None and vals[1] == min(x for x in vals if x is not None): return 2 elif vals[2] is not N...
424f022dc7cc0dd4b81a867a9efcf4bc37482806
666,271
import torch def filter_pcd( pcd, tol = 0.3): """ input: pcd : Nx3 torch.float32 returns: mask : NX3 torch.bool """ m = torch.mean(pcd, dim = 0) comp = m[None,:].repeat(pcd.shape[0],1) + tol mean_free = pcd-m[None,:].repeat(comp.shape[0],1) mask = torch.norm( mean_free...
312919c130c61bc69544d9dd6c25c2fe02ca42b4
666,272
def skill(xmod, xobs, axis=-1): """ Murphy skill score """ varmod = ((xobs - xmod)**2.).sum(axis=axis) varobs = ((xobs - xobs.mean(axis=axis))**2.).sum(axis=axis) return 1 - varmod/varobs
20cdd4bebcaa22e618ef67f5975d138cdbb0d986
666,273
def _safe_indexing(X, indices): """Return items or rows from X using indices. copy of sklearn utils safe_indexing with handling of slice as well Allows simple indexing of lists or arrays. Parameters ---------- X : array-like, sparse-matrix, list, pandas.DataFrame, pandas.Series. ...
0419f9a91227d1e8c281f3e55c30a82953ca7d41
666,274
import subprocess def get_tag(): """Return the last tag for the git repository.""" # another possible option is: 'git tag | sort -V | tail -n1' return subprocess.getoutput('git tag --sort=version:refname | tail -n1')
c56bbc4e2bc3b8d996c7a31f84ed41d67914ad2c
666,275
import asyncio def _run_in_event_loop(coro, *args, **kwargs): """Run a coroutine in a runloop call. This is needed as the top level call into Resolwe Manager-using tests. An event loop is started so that it can be used within the call tree. :param coro: The coroutine to run with an underlying ev...
63c90084bca346c21ce887518b469c8b69cf31fe
666,276
import sqlite3 def execute_sql(dbfile,query,params=None): """Execute SQL against a SQLite file Args: dbfile: SQLite database file query: SQL query params: sequence of parameters Returns: list of matching rows """ conn=sqlite3.connect(dbfile) conn.row_f...
36c2c8475b7b79397891752f33310a98cb8f3819
666,278
from typing import List def add_bcc(cmd: List[int]): """Compute BCC (= Block Checking Charactor) and append to command sequence. Returns: list of binary data with BCC code. """ check: int = 0x00 for b in cmd: check = check ^ b cmd.append(check) return cmd
6fac48e348cdb2c6fd63f1545a09fa5ea6ddba61
666,279
import time def gmtime2ams(unixtime): """Converts float unix time to GMT time in format '2011-12-11 09:00:21.555'""" msec = int((unixtime%1)*1000) tm = time.gmtime(int(unixtime)) s = time.strftime("%Y-%m-%d %H:%M:%S", tm) return s + (".%03d"%msec)
d18744b30d188e2190dc817e0e0941f07a49fd23
666,280
import torch def load_background_checkpoint(netBE,netBG,optimizers,hyperparameters, background_training_mode): """ loads and returns a saved pretrained model""" print('loading background checkpoint') saved_background_checkpoint_path = hyperparameters['saved_background_check...
aa2fd6d2b1bdc733a7e6ca96d5eb56fb6b9f2a46
666,281
def BuildSt(st): """Organizes information in a single standard_timings.StandardTiming object. Args: st: A standard_timings.StandardTiming object. Returns: A dictionary of standard timings information. """ return { 'X resolution': st.x_resolution, 'Ratio': st.xy_pixel_ratio, 'Freque...
80b35d58b032721294d77711bcb9c4631d707cab
666,282
import torch def compute_dz(zs, attrs, idx): """ for a given attribute idx, compute the mean for all encoded z's corresponding to the positive and negative attribute """ z_pos = [zs[i] for i in range(len(zs)) if attrs[i][idx] == +1] z_neg = [zs[i] for i in range(len(zs)) if attrs[i][idx] == -1] # dz =...
ac26c70afb5ba00585e6865f7b5f8937ab77fdce
666,283
def concat(str1: str, str2: str) -> str: """Return a plus b Args: str1 (str): number one str2 (str): number two Returns: str: return """ return str1 + str2
3c30174bfe3f1625dfc56e248f4fac80729e1fdc
666,284
def compute_gradient(y, tx, w): """Compute the gradient. :param y: outpus/labels, numpy array (-1 = background and 1 = signal) :param tx: standardized inputs/features augmented with the first column filled with 1's :param w: weights :return: gradient """ err = y - tx.dot(w) gradient = -...
8f34fb403054d3182af7f1668efe8bd3175705f5
666,285
from numpy import ndarray,array def array_dtype(a): """Element data type of an array or array-like object""" if hasattr(a,"dtype"): return a.dtype if not hasattr(a,"__len__"): return type(a) if len(a) == 0: return float # If 'a' is a list, it may contain element of different data type. # Conve...
31cefbeb5081687fe2a08ae8ee415fbc2527a190
666,286
def file_len(fname): """Returns Number of lines of a file""" with open(fname) as f: i = -1 for i, l in enumerate(f): pass return i + 1
16d6146af3e90c24d93b224835e37604e9405dc0
666,287
def isEntity(obj): """Returns whether or not the opject passed is an Phobos entity. Args: obj(bpy.types.Object): The object for which entity status is tested. Returns: """ return obj is not None and 'entity/type' in obj and 'entity/name' in obj
d85be38a3d9c0a9c78046dc2a5c65f59ae5f8af0
666,288
import random import torch def sample_domains(train_loader, N=1, stratified=True): """ Sample N domains available in the train loader. """ Ls = [] for tl in train_loader.dataset.batches_left.values(): Ls.append(max(tl, 0)) if stratified else Ls.append(min(tl, 1)) positions = range(len...
a57d9df9a47d1e163024bec111a7de7a1452df81
666,289
def predict_times_model(times, model): """Predict times alignment from a model object. Parameters ---------- times : 1d array Timestamps to align. model : LinearRegression A model object, with a fit model predicting timestamp alignment. Returns ------- 1d array ...
e9ed5758bcb73e776be92b44cd4c2491ae30e5cf
666,290
import torch def get_recall(SR, GT, threshold=0.5): """ Args: SR: tensor Segmentation Results GT: tensor Ground Truth threshold: the threshold of segmentation Returns: RC: Recall rate """ # Sensitivity == Recall SR = SR > threshold GT = GT == torch.max(G...
54f75d00f339987c62124cd0c8d0d0e91bae23dd
666,291
import re def parse_element_string(elements_str, stoich=False): """ Parse element query string with macros. Has to parse braces too, and throw an error if brackets are unmatched. e.g. Parameters: '[VII][Fe,Ru,Os][I]' Returns: ['[VII]', '[Fe,Ru,Os]', '[I]'] e.g.2 Parameters: '...
d26950193148dd43712c5c8d0c33b4f4196e7849
666,292
from typing import Dict def extract_metadata(form_results: Dict) -> Dict: """ Function that serves as helper to save extracted results from OCR to a csv file Parameters ---------- form_results: Dict (Results from form recognizer) Returns ------- Dict Object cont...
a6a651c08e0cc025abb0c3b45f88dbe907084b39
666,293
import torch def get_flat_params_from(model): """ Get the flattened parameters of the model. Args: model: the model from which the parameters are derived Return: flat_param: the flattened parameters """ params = [] for param in model.parameters(): params.append(pa...
4acc67cadabed4863367e7c6ef59cf04fe132315
666,294
def convert_to_daily_rate(rate, unit): """From yellow brick road rate to daily rate.""" if unit == 'h': return rate * 24.0 if unit == 'd': return rate if unit == 'w': return rate / 7.0 if unit == 'm': return rate / 30.0 if unit == 'y': return rate / 365.0
2b4f0d31e92198d1ce2dec9b41d7618c2e00967c
666,295
from typing import List from typing import Tuple from typing import Optional def html_wrap_span( string: str, pairs: List[Tuple[int, int]], css_class: Optional[str] = "accentuate" ) -> str: """Wrap targeted area of Assertion with html highlighting to visualize where the error or warning is targeted ...
075e5a95b9ba6bc5fd818169824149b46796790c
666,296
def construct_info_message(module, branch, area, version, build_object): """ Gathers info to display during release Args: module(str): Module to be released branch(str): Branch to be released area(str): Area of module version(str): Release version build_object(:class...
0e3074e26414cc4da74bd6e4ccc9f5f719e69957
666,297
def rotate_points(points, R): """ Rotate points by the rotation matrix R """ rotated_points = R @ points return rotated_points
5bbae2fcacabb4f40b897c15be4c1ba7feb24746
666,298
import json def load_json(file:str) -> dict: """ """ with open(file, "r") as f: data = f.read() f.close() return json.loads(data)
dc73a4a185a0811a05c734e301e06ed1c7acc4a0
666,299
def erase_special(x): """ Removes special characters and spaces from the input string """ return ''.join([i for i in x if i.isalnum()])
839d6b2db14af782b50ee16ee24b27d6208e893d
666,300
import tempfile import zipfile def extract_files(file_path, output_dir=None): """ Extracts files from a compressed zip archive. :param str file_path: the path to the input zip archive containing the compressed files. :param str or None output_dir: the path to the directory in which to extract the file...
522bf86dc880d08349dbd9b599ba048a392d7f0e
666,301
def regex(self, compiler, connection): """regex and iregex""" lhs_sql, params = self.process_lhs(compiler, connection) rhs_sql, rhs_params = self.process_rhs(compiler, connection) params.extend(rhs_params) rhs_sql = self.get_rhs_op(connection, rhs_sql) if self.lookup_name.startswith('i'): ...
530689012485c505274bd7163c4d3a0d2cafca61
666,302
from importlib import import_module def find_builder(name): """Get builder class from name""" mod = import_module(name) return mod
0ff27ea2ff068224c5ebef911bdfd0946bdd9b9a
666,303
def linear_regression(x_list, y_list): """ Calculates slope and intercept using linear regression This implementation is not suited for large datasets Arguments: tuples_list -- An array of tuples containing x and y values Output: A tuple of slope and intercept values """ assert len(x_l...
147302deb4941303f3e34a4c9de496a21d441e0a
666,304
import json def insert_workspace_access(cursor, workspace_id, info): """ワークスペースアクセス情報登録 Args: cursor (mysql.connector.cursor): カーソル workspace_id (int): ワークスペースID info (Dict)): アクセス情報のJson形式 Returns: int: ワークスペースアクセス情報id """ # ワークスペースアクセス情報 insert実行 cu...
b55fd39908b54f428e69a0e926c7d5e6921109ce
666,305
def user_logout(change): """ When logout """ return change()
da79adb2e8bcf12054adb49db72f59149ca0fc62
666,306
def compare_list(list1: list, list2: list) -> bool: """Compare two list and ignore \n at the end of two list.""" while list1[-1] == "\n" or list1[-1] == "": list1.pop() while list2[-1] == "\n" or list2[-1] == "": list2.pop() return list1 == list2
f7e925116dd952fb64e89c4da5b2256682cfb3a3
666,307
def payoff_call_fprime(underlying, strike, gearing=1.0): """payoff_call_fprime derivative of payoff of call option with respect to underlying. :param underlying: :param strike: :param gearing: :return: value of derivative with respect to underlying. :rtype: float """ if underlying >...
6ed3846bfdf6f84e8ebcee158d6a1c80bafea57f
666,308
def datetime_format(date, caller=None): """Convert given datetime.datetime object to a string of appropriate form. Choose the format according to the "caller" arg., which is a string indicating the name of the function calling this function. """ if caller == "corona": return date.s...
daadbaa4d5146f6a86c5ce24150e0dabebc3bb09
666,309
def calc_relative_ratio(rel_pow_low_band, rel_pow_high_band): """Calculate ratio of relative power between two bands. Parameters ---------- rel_pow_low_band : float Relative power of lower band. rel_pow_high_band : float Relative power of higher band. Outputs ------- ra...
fa3762a57e6e427630621c22c9108f8ed2df46af
666,310
import importlib def get_trainer(cfg, net_G, net_D=None, opt_G=None, opt_D=None, sch_G=None, sch_D=None, train_data_loader=None, val_data_loader=None): """Return the trainer object. Args: cfg (Config): Loaded config object. net_G...
6b9856727a165fd962ad8da107bb73b769c72757
666,311
def args_assignment(cp, mp, omega_i, omega_j, i, ii): """ Assembly of the derivative parameters input: covid_parameters, model_parameters output: vector args with the variables: N, alpha, beta, gamma, los_leito, los_uti, tax_int_i, tax_int_j, tax_uti_i, tax_uti_j, taxa_mortalidade_i, taxa_m...
4b0a19670ee942730c1e5e865483f98ebf459f95
666,312
import argparse def train_parser() -> argparse.ArgumentParser: """ Returns: Argument parser for train.py script. """ parser = argparse.ArgumentParser() parser.add_argument( "-a", "--algorithm", type=str, required=True, help="Name of algorithm which s...
9e3c57d4750d099fac1ab12af2f5de69b7662b60
666,313
def removeUnderFiftyMeters(df): """ This function removes all tracer observation for which Z > 50m. Input: - df: dataframe that function should be applied at. """ # indices = df.index[df['Z'] > 50.01].tolist() return df.query('Z <= 50.01')
2a72a73258a9ca47145e3c7dc2be89e13cae8b3d
666,314
from functools import reduce def merge_identical_bases(*p_list: float) -> float: """Combind list of identical base with different quality stat into one. b1 = ('A', 0.001) b2 = ('A', 0.023) """ # base the order of identical base does not matters return reduce( lambda p1, p2: (p1 * p2 /...
c907c951e5081ec99dc95a2d0906fb4cc1a9a5af
666,315
def expectedBlockId(data): """Returns the expected flat block index""" return data[1]
88f55c2b15b0280a950b0d89ae310ad62f950548
666,316
def isOneShot(cp): """ :return bool: If the execution is configured to be oneshot backprocessing """ return cp.get("Oneshot", "enable", fallback="false").lower() == "true"
b8dacc6dcdb7bb3212d39314d41ff9ed817d1aa3
666,317
import os def blockpath_name(block_path): """extracts block name from block_path""" return block_path.split(os.sep)[-1]
655f415275f4dd489f12d593782db9e60b799d06
666,318
import os def get_file_names(prefix): """Return set of paths determined from file prefix""" image_name = os.path.basename(prefix) working_dir = os.path.dirname(prefix) return image_name, working_dir
8f4cdf30069f90eb673984e7f3ccc4090f55b5bb
666,319
def complete_out_of_view(to_check_box, im_w, im_h): """ check if the bounding box is completely out of view from the image :param to_check_box: bounding box, numpy array, [x, y, x, y] :param im_w: image width, int :param im_h:image height, int :return: out of view flag, bool """ complete...
671d9a774bcab4b45df7ac3f6f1266f95d7674c1
666,320
import re def rename_state(rename, src): """ Given a list of (old_str, new_str), replace old_strin src with new_str. :param rename: a list of (old_str, new_str) :param src: code :return: renamed src """ for (old, new) in rename: match = True index = 0 while match: ...
57a958964f6a2d70dfca32fca90e1aacc620b729
666,322
def identify_shader_stages(shader): """ Identify which shader stages to validate """ shader_stages = [] # Check which shaders exist if shader.vert_shader.find('void main') != -1: shader_stages.append((shader.vert_shader, 'tmpshader.vert')) if shader.geom_shader.find('void main') != -1: ...
3cd7c4475c01ed66a3a7077a7d4e8946e50a98b6
666,323
import re def match_node_template_node(template, node): """match node to template node""" for k,v in template.items(): if not k in node: if 0: print("k %s not in %s" % (k, node)) return False if not re.search(str(v), str(node[k])): #print("false", str(v), no...
0080c7ac34803d7c06809403598d3635df1df79e
666,324
import re import unicodedata def clean(string): """Function to clean punctuation and normalize Unicode""" if string is None or not string or string == 'None': return '' string = string.strip() string = re.sub( u'[\u0022\u055A\u05F4\u2018\u2019\u201A\u201B\u201C\u201D\u201E\u201F\u275B\...
33b2805dd11adac10254d12028b3981b8bd2b748
666,325
def check_skip_material(mat): """Simple helper to check whether we actually support exporting that material or not""" return mat.type not in {'SURFACE'} or mat.use_nodes
b578ec906c761e9458464139e00585e325ab194a
666,326
def validate_cipher_suite_id(cipher_suite_id): """Validates that a CipherSuite conforms to the proper format. Args: cipher_suite_id (int): CipherSuite id. Returns: (int): The original CipherSuite id. """ if not isinstance(cipher_suite_id, int): raise TypeError("CipherSuite...
7bf45a6270cad22481765e009a19618d6691ce8b
666,327