content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def is_gzip_file(view): """ Given a view, determine if that view (probably) contains a gzipped file or not. This is currently based on a combination of the extension and the file being a binary file with the right magic bytes. """ return (view.encoding() == "Hexadecimal" and view.sub...
f457e373d59d7688a9ec3e5e64b2ab6c92115d25
61,188
from typing import Callable import functools def get_v_panel_from_i(cell_param=np.array([6.48000332e+00, 6.37762333e-10, 8.45318984e-04, 1.65194938e+03, 3.14194723e-02]), I_min: float = -4, I_max: float = 7,...
6fa736bffc1f32df41364442249195a0b066ac4a
61,190
import json def get_project(project_id: int) -> json: """ :param project_id: :return: """ query_result = db.session.query(Project).filter(Project.id == project_id).all() if len(query_result) == 1: info = { "name": query_result[0].name, "description": query_result[0].description } return j...
d25670cad7d2ce74ddc5706d333d570b090c2006
61,191
def fetchone_to_dict(sql, params=None, db='default'): """ 返回一行数据 :param sql: sql语句 :param params: sql语句参数 :param db: Django数据库名 :return: 例如:{"id": id, "username": 'username', "first_name": 'first_name'} """ cursor = connections[db].cursor() cursor.execute(sql, params) desc = curs...
79ef4f0c9e66fda994aa5d4e223a6872f92e515e
61,192
def make_zip_handler(zipfilename, max_age=None, public=None): """Factory function to construct a custom ZipHandler instance. Args: zipfilename: The filename of a zipfile. max_age: Optional expiration time; defaults to ZipHandler.MAX_AGE. public: Optional public flag; defaults to ZipHandler.PUBLIC. ...
a9833e0a07f36060efbb06099493d0a87202ce55
61,193
def rotmatrix(ang, raxis, axis=0): """Construct a 3d rotation matrix representing a rotation of ang degrees around the specified rotation axis raxis, which can be "x", "y", "z" or 0, 1, 2. If ang is a scalar, the result will be [3,3]. Otherwise, it will be ang.shape + (3,3).""" ang = np.asarray(ang) raxis = raxi...
767484648c70ff961d223e23d226ce44dabd1afe
61,194
def watershed_group_add(request): """ Controller for adding a watershed_group. """ if request.is_ajax() and request.method == 'POST': #get/check information from AJAX request post_info = request.POST watershed_group_name = post_info.get('watershed_group_name') watershed_g...
ad18b5667f0effe6fb8bd9dd787ce967d418816e
61,195
def is_trivial_pair(p): """Is the critical pair trivial?""" u, v = p; return u == v
ee4b42a9f1345c7260c3992db4c2445b32273a01
61,196
def multiplicativeAttraction(vGamble,pGamble,timePressure,neta,framing,x,need,c): """Here we assume time prssure with enhance the framing effect, and an additive risk attraction term """ expectation = pGamble * vGamble + 0 varGamble = pGamble * (vGamble - expectation) ** 2 + (1 - pGamble) * (0 - expectation...
c1c96ac867162c1c78033550641719be430e468b
61,198
def pairs_to_dict(response, decode_keys=False, decode_string_values=False): """Create a dict given a list of key/value pairs""" if response is None: return {} if decode_keys or decode_string_values: # the iter form is faster, but I don't know how to make that work # with a str_if_byt...
3303d4549e23bc2c1b360091f8f2d97cf50d0f65
61,199
def regularization_kernel(COEF_in, sigma): """ Inputs: COEF Biot-Savart Kernel sigma regularization radius Outputs: KAPPA Regularization Kernel """ COEF = COEF_in.astype(np.float32) COEF_MAG = np.abs(COEF) # Make sure the magnitude doesn't go to ...
90f5aafa1c94e75a98fd1d184d73e21040f66bd3
61,200
def load_wikitext(path, name="2", eos=None): """Loads the WikiText dataset Returns the train, validation test set, each as a list of sentences (each sentence is a list of words) Args: path (str): Path to the folder containing the ``wikitext-{2|103}-v1.zip`` file name (str):...
f4e45e3b49302f1cb88cfe64c4fa3956c6a6d55e
61,201
def response(code=200, data=None, error=None, msg=None): """ :param code: 状态码 :param data: 返回数据 :param error: 错误信息 :param msg: 提示信息 """ if code is not None and code >= 400: error = HTTP_STATUS_CODES.get(code, "unknown error") pay_load = { "code": code, "data": d...
8043dd56a0928895f9397c39782feeb38fc59028
61,202
def normalize_meaning(source_string): """Escape all HTML tags if any""" flag = 0 index = 0 # Trash is a list containing all the html tags found in the source string trash = [] for c in source_string: if c == '<': # Flag the start of the html tag flag = index ...
be22cbcbf09c4d5705f5d854e4b562d570d3f216
61,203
def verify_vxlan(device, enable_password): """ Verifies the interface vxlan 1 status is up/up. Args: device (jsonrpclib.jsonrpc.ServerProxy): Instance of the class jsonrpclib.jsonrpc.ServerProxy\ with the uri 'https://%s:%s@%s/command-api' %(username, password, ip). enable_passw...
d2f7d7455b675260448b599e21e6bcb96fe10f2a
61,204
def get_heart_rate_units_str(): """Returns the units in which heart rate is displayed.""" return "bpm"
f7a17f7d6d71124e53a72cfdc8192c78b7beba10
61,205
def cut_list(list, length): """ This function allows to cut a list into parts of a certain length. It returns a new list which takes less memory and contains for each index a part of the initial list. Args : list : list of the images path of the whole database\n length (int)...
210a1ad7db3058396ad32493a91b5c70176fb77c
61,206
import json def _convert_vars_to_json(env_dict): """Converts 'variables' in the given environment dict into string.""" if ('variables' in env_dict and isinstance(env_dict.get('variables'), dict)): env_dict['variables'] = json.dumps(env_dict['variables']) return env_dict
8dbf0456fd29833ff42570e011a45b368aa2ac0c
61,208
def signal_smooth(signal, method="convolution", kernel="boxzen", size=10, alpha=0.1): """Signal smoothing. Signal smoothing can be achieved using either the convolution of a filter kernel with the input signal to compute the smoothed signal (Smith, 1997) or a LOESS regression. Parameters ---------...
c85d8a47f971a037c748c76e3aafea425ede7fd6
61,209
def getprimarymode(image_list, bid): """Determine the primary mode of the science frame for the block """ primary_mode=None instr=[] obsmode=[] detmode=[] for img in image_list: if img[10]==bid: instr.append(img[5]) obsmode.append(img[6]) detmode.append(img[7])...
f50f585fb9e9888be0a478c230767f8ee7907fac
61,210
from typing import List def retrieve_all_source_files(source: str) -> List[str]: """Utility to aggregate all source files for future processing Args: source: The relative path to your source directory Returns: A list of existing Python files from your source directory """ all_fi...
4fd710395fe05fce3a4f8dddc29a464175a7b121
61,211
import math def day_of_the_week(year, month, day): """ given a calendar date, the routine returns a tuple with the Day Of The Week in number and in plaintext 0 for Sunday 1 for Monday and so on up to 6 Saturday """ doth = {0:'Sunday', 1:'Monday', 2:'Tuesday', 3:'Wednesday', 4:'Thursday...
7b84b17b435fe92cea17246a07b8289ac8eba97a
61,212
def convert_row(row): """ prints an array of 0's,1's,and 2's as their tictactoe characters """ row_string = '' for num in row: row_string+=(convert_num(num) + '|') return row_string
21894eb0ea59b6637a27a9d56f5070f4977708b3
61,213
from typing import Optional async def uninstall( skill: Uninstall = Body( default=None, description="Information about the skill to uninstall", example='{"skill": "https://github.com/JarbasSkills/skill-parrot.git",\ "dialog": "the skill-parrot skill has been uninstalled",...
5f9a4d702da31f14f68e5b554c0d9f591d96b893
61,214
def sgd(step_size): """Construct init and update step functions for stochastic gradient descent. Args: step_size: positive scalar, or a callable representing a step size schedule that maps the iteration index to positive scalar. Returns: An (init_fun, update_fun) pair. """ step_size = make_sch...
320f7b1042957c1ac9c87426ff49bfa0debcd12b
61,215
def match_hobbies(hobbies_flat,h1,h2,num_hobbies,num_matches): """ Match hobbies between two persons seating next to each other. Note that hobby 0 is a dummy value and should be ignored. """ return [num_matches == sum([(Element(hobbies_flat,h1*num_hobbies+i) != 0) * (Element(hob...
36e20a8487b0469487b7f7284c9e414a7ed2ddf3
61,216
def get_payload() -> bytes: """ This function returns the data to send over the socket to the server. This data should cause the server to crash and generate a core dump. Make sure to return a `bytes` object and not an `str` object. WARNINGS: 0. Don't delete this function or change it's name/p...
d40adaccaa860a734d697c426fa7bdad53e3753f
61,217
def announce_challenge(p1, p2): """Generates an announcement to be posted by the discord bot as an embed Params: p1: player1 (the challenger) as a discord.Member object. p2: player2 (the challengee) as a discord.Member object. return: Dictionary with content, title, ...
15f9510f0423ae3291e63f58de82bfbef66805af
61,219
def convert(s): """Convert hex to binary or vice versa.""" if flag_reverse: try: v = int(s, 10) except ValueError: return s return "0x" + hex(v)[2:].zfill(8) else: try: v = int(s, 16) except ValueError: return s return bin(v)[2:].zfill(8)
ec933881cb45b7950ca0f30c3bb3814677a4e995
61,220
from typing import Union from pathlib import Path from typing import Optional def first(filename: Union[str, Path], preamble_length: int = 25) -> Optional[int]: """ Return the first number that cannot be written as the sum of two numbers among the previous `preamble_length` numbers If no such set of ...
be3d8ad7efbf092d65f3fd0c4dc3d00222ac9439
61,221
from datetime import datetime def getTimestring(): """Return int only string of current datetime with milliseconds.""" (dt, micro) = datetime.utcnow().strftime('%Y%m%d%H%M%S.%f').split('.') dt = "%s%03d" % (dt, int(micro) / 1000) return dt
c94e83fd39d00c29a909626e3851e36d89baf06e
61,222
def listing(characters, outstream, *, metadata=None, partial=False, **kwargs): """ Create an html character listing Args: characters (list): Character info dicts to show outstream (stream): Output stream metadata_format (string|None): Whether to include metadata, and what ...
25e2da382a60f28d4a42a144eff400bb8595834c
61,223
from typing import Optional def format_fields_as_txt( additional_fields: Optional[FieldDocCollection] = None, field_prefix: str = '', color: bool = False) -> str: """Return a formated string containing the documentation about the audio fields. """ if additional_fields: ...
8507d550013ce501feefe4c58194433661446e03
61,224
def PPTS(y_true,y_pred,gamma): """ Compute peak percentage threshold statistic args: y_true:the observed records y_pred:the predictions gamma:lower value percentage """ # y_true r = pd.DataFrame(y_true,columns=['r']) # print('original time series:\n{}'.format(r)) ...
22775d5356f7f754dee21beb53621e18c64e26f3
61,225
def trapz(f, x): """ Numerically integrates f(x) using trapezoid method. """ return np.trapz(f, x)
e0355ddcb6b841ab5392483e325e54ba390c1cbe
61,226
def dpsi_periodic(x, t, n=1): """ derivative of Stream function for periodic boundary conditions """ return -n * 2 * pi * np.sin(n * 2 * pi * x + 0.5 * t / (n * pi))
8395eb5fce4e3a951c7d335fed0d2bef1ad0e847
61,227
def flatten_probas(preds, targets, ignore=None): """ Flattens predictions in the batch """ B, C, H, W = preds.size() preds = preds.permute(0, 2, 3, 1).contiguous().view(-1, C) # B * H * W, C = P, C targets = targets.view(-1) if ignore is None: return preds, targets valid = (targ...
4765c2b22ab526e762fa5877ca30299b4de851b7
61,228
def _convert_partials_type(type_: dtypes.dtype) -> _ir.op.MatMulPartialsType: """Convert the dtype to an _internal.ir partials type Args: type_ (dtypes.dtype): The top level dtype Raises: ValueError: If not float[16|32] Returns: _ir.op.MatMulPartialsType: The internal partials...
cd5ee5540a5666206770aa754f147badc8ced231
61,230
from typing import Union from typing import Optional from typing import Iterable def scatter_nd(indices: Union[ivy.Array, ivy.NativeArray], updates: Union[ivy.Array, ivy.NativeArray], shape: Optional[Iterable[int]] = None, tensor: Optional[Union[ivy.Array, ivy.NativeArray]] = None, reduc...
e6b13713ee3fc7d540ab872cb31792cdb4c055c3
61,231
import torch def dcca_model(stim_data, resp_data, o_dim, learning_rate=1e-3, use_all_singular_values=False, epoch_num=12, batch_size=2048, reg_par=1e-4, dropout=0.05, best_only=True, path_name="", seeds=np.ceil(np.random.rand(10)*100)): """ ARGUMENTS: stim_data : A THREE ELEMENT LIST OF STIMULI DAT...
92228ddf99177965035c625ab7fa9edec3e7ecb1
61,232
def _get_ids(tokens, tokenizer, max_seq_length): """Token ids from Tokenizer vocab""" token_ids = tokenizer.convert_tokens_to_ids(tokens) input_ids = token_ids + [0] * (max_seq_length - len(token_ids)) return input_ids
114053372ec61135c6214bc351a282d1a81432f3
61,234
def returnInstance(Type,runInfoDict, caller): """ Returns an object construction pointer from this module. @ In, Type, string, requested object @ In, caller, object, requesting object @ Out, __interFaceDict, instance, instance of the object """ if Type in knownTypes(): return __interFaceDict[T...
6c0931f5af73f1145e189a2df46ba352cff0f741
61,235
import csv def getExternalAuthors(filename): """ Returns the external authors of the network. The first column minus the ones that appear on the second column """ inside_authors = {} outside_authors = {} with open(filename, "r") as fp: reader = csv.reader(fp, delimiter=',') for...
2774c3af691ed33c3070dbd7d28f6629afa947fa
61,236
def remove_uptake_and_secretion_reactions(reactions): """ Remove all the uptake and secretion reactions added to a model, eg. when you are running multiple simulations. :param reactions: The reactions dict :type reactions: dict :return: The enzymes, compounds, and reactions data structure :rtype...
7f3e412fc98fc28b054557b2c4795c251d3facd1
61,237
def to_float(num): """ 引数をFloatに変換します。 """ return float(num) if type(num) is str else num
b2692edb3037359853bcd22fa5059efa20976a70
61,238
def get_changed_files(base_branch='develop'): """ Return a list of changed file paths against the `base_branch`. Or locally only if `base_branch` is None. Raise an exception on errors. """ # this may fail with exceptions cmd = 'git', 'diff', '--name-only', if base_branch: cmd += ...
77ca5f4d993a476c45b6a5cac2b373a8aacce9c9
61,239
def H(z): """ H(z): Function to return the Hubble parameter as measured by an observer at redshift, z. """ result = 100.0*E(z) return result
6c417ad65a3e9659c0e0c585db4a49dbad47dbbc
61,240
def get_fast_slow_calc(distance, **kwargs): """returns FastSlow instance for a given distance name""" return fast_slow_dist(distance, **kwargs)
395d7419a508d66c090b8ca5fc673287fdf8ee00
61,241
def to_collection(spocs): """ Transforms a list of spocs to a sponsored collection dictionary. AdZerk does not support fields for a collection. We set them on all creatives and get them from an arbitrary one. :param spocs: A list of spocs :return: A dictionary with collection fields (title, flight_i...
c5c01739c4790d1b5243bc4b7d7d349fd3c5c6c5
61,242
def silence(score0, score1, leader=None): """Announce nothing (see Phase 2).""" return leader, ""
6f9360400205b244667075e65f3a747b5f98ba16
61,243
def random_split(dataset_size, split_ratio=0.9, seed=0, shuffle=True): """random splitter""" np.random.seed(seed) indices = list(range(dataset_size)) np.random.shuffle(indices) split = int(split_ratio * dataset_size) train_idx, valid_idx = indices[:split], indices[split:] log.info("train_set...
50f430af94c4537b556fe48792b876d6a86e0668
61,244
import requests def wms_getcapabilities(response, hostname, params, script_root, permissions): """Return WMS GetCapabilities or GetProjectSettings filtered by permissions. :param requests.Response response: Response object :param str hostname: host name :param obj params: Request parameters :...
a8c7131d7a0fb2baf64b5f079e2c4ec5a788b43c
61,245
def get_peds_in_area(traj_data: pd.DataFrame, measurement_area: pygeos.Geometry) -> pd.DataFrame: """Filters the trajectory date to pedestrians which are inside the given area. Args: traj_data (pd.DataFrame): trajectory data to filter measurement_area (pygeos.Geometry): Returns: F...
43cae4cb164c4b075adf32fb4867f340672a3969
61,246
def volt2SPL(volt, gain, sensitivity=-35, dBref=94): """ convert volt amplitude to instantaneous sound pressure level SPL Parameters ---------- volt : 1d ndarray of integers floats Vector containing the sound waveform in volt gain : integer Total gain applied to t...
2195ffb9ec21b16bb7f15fc3888461b1226fcc9f
61,247
def estimate_AR1_halflife(df): """Estimate AR(1) half-life of columns in DataFrame""" if not isinstance(df, (pd.DataFrame, pd.Series)): raise TypeError(f"Type {type(df)} not supported (DataFrame/Series)") data = df.to_numpy() if data.squeeze().ndim == 2: return np.array([estimate_AR1_ha...
7e8c00f18d9bbca71326555879ef15b252708b23
61,248
def infer_species_from_prefix(name): """ Trying to parse prefixes of alleles such as: HLA-A but also ones with dashes in the species prefix: H-2-K and also those lacking any dashes such as: H2K ...we also need to consider that alleles, haplotypes, etc may come immediat...
f49048202c9fc065a932bce5bf1f1b9292f445e9
61,250
from functools import reduce def merge(s, p): """Merge union-find s with permutation p (as cycles).""" def find(x): while s[x] != x: x = s[x] return x def union(x, y): x = find(x) s[find(y)] = x return x for cycle in p: reduce(union, cycle) ...
b65e1151c678fc9627840799770499b5fe91f71e
61,251
from typing import Tuple def _distorted_bounding_box_crop( image_bytes: tf.Tensor, *, jpeg_shape: tf.Tensor, bbox: tf.Tensor, min_object_covered: float, aspect_ratio_range: Tuple[float, float], area_range: Tuple[float, float], max_attempts: int, ) -> tf.Tensor: """Generates cropped_i...
2dccd66df93f063f46750b8c88a1656178f7ec68
61,252
def pluralize( string ): """ Correctly convert singular noung to plural noun. """ if string.endswith('y'): plural = string[:-1] + 'ies' elif string.endswith('us'): plural = string[:-2] + 'i' else: plural = string + 's' return plural
7179c02f71f0044735c6573d64784456fcabc6cc
61,253
import csv def get_sampleID_and_sex(args): """ Retrieve sample IDs (samples with "-T*") and patient sex from title file """ sample2sex = {} with open(args.title_file_path, "rU") as titleFile: tfDict = csv.DictReader(titleFile, delimiter="\t") for row in tfDict: if row[...
a3cc0419bfcb0eb658700f4d49981887ccc7a69f
61,254
def effectiveInterval(A,B,a,bcomp): """ Determines the range along segment a that is closer to the component bcomp than to either adjacent component. Parameters ---------- A : [(x,y),(x,y)...] The main polyline. B : [(x,y),(x,y)...] The other polyline a : Integer ...
564ca7e25fc1bfee0906b1f9b2a328a652201a14
61,255
def clamp(val, min, max): """Clamp the value between min and max.""" if val <= min: return min elif val >= max: return max return val
57411c7d7fd53508889606e820c8a4158f551da1
61,256
import torch def validate_one(input, target, model): """Perform validation on the validation set""" def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1...
0e654355794c2e5d2d70c570d6959aa1cd56e19b
61,257
def getNextFirstCharColumn(row, x): """ Gets the first right pixel culumn of a char in a text row image Parameters ---------- row(numpy.ndarray) : Text row image x(int) : Starting x coord to search Returns ------- int : X coord indicating the columns starting pixel of char Use...
718500f3d5ed29b2122e0b6b8d7369a68c4dc222
61,258
def image(path, x=None, y=None, anchor='center', **kwargs): """ Function to create an image. :param path: local file path or url of image to upload :type path: str :param args: left top corner of image and width and height of image :type args: two Tuples (left, top), (width, height) or four int...
2fb8365c4e1572b4dc136a4b8fffe1c111bec773
61,259
def reverse_key_value(orig_dict): """ DESCRIPTION ----------- Reverse the key value pairs of a dictionary object. PARAMETERS ---------- orig_dict : dict A dictionary object. RETURNS ------- rev_dict : dict A dictionary with the values of the original dictionar...
92599452e511193ce34c4421b13029023fb9c762
61,260
from typing import cast def validate_integer(value: str) -> bool: """ Validates an integer value. """ return cast(bool, INTEGER_RE.match(value))
ee1f75ca864e57ec53633963958c7780e48de632
61,261
import numpy def make_labels(X): """Helper function that generates a single 1D array with labels which are good targets for stock logistic regression. Parameters ========== X : numpy.ndarray The input data matrix. This must be an array with 3 dimensions or an iterable containin...
d10ac3b9213bd6a2d43d24059295ff2779b1cd39
61,262
import urllib def location_html(location): """ Gets the html for a location object. """ if not location: return u'' html = u'' if location.name: address = location.get_display(exclude_fields=['phone']).encode('utf-8') address = urllib.quote_plus(address) url ...
535a88d8b62b0ae052b89c1878135d691bf34134
61,263
from astropy.io import fits def dendro_import_fits(filename): """Import 'filename' and construct a dendrogram from it""" with fits.open(filename) as hdus: data = hdus[1].data index_map = hdus[2].data newick = ''.join(chr(x) for x in hdus[3].data.flat) return parse_dendrogram(newi...
a191ee5d275acd81e1bf4def6501828a6e83e61f
61,264
def cv_h(P, h): """ Specific isochoric heat capacity [kJ / kg K]""" return cv(P, T_h(P, h))
2879d9df227156998b8c6e46163b3c8017a791c8
61,266
import unittest def load_tests_from_testcase(test_case_class, args): """ load tests from testcase class Args: test_case_class: TestCase class object args: parse args Returns: unittest.TestSuite() """ if 'all' in args.case_list: # Load all test cases # test_suit...
1c5384ec9d3296e1c7c18e2848a8f32089ace675
61,268
import torch def train(_model: torch.nn.Module, _criterion: torch.nn.MSELoss, dataset_train: DataLoader, dataset_test: DataLoader, _optimizer: torch.optim.Optimizer, n_epochs: int, device: torch.device, test_metrics: dict, log): """ Trains the given model according to a certain criterion and logging...
5f98faf9a0ef3594f0edf5b5af57d3a35343439b
61,269
def sweep_lin(f0, f1, duration, fs): """Generates a linear sine sweep Parameters ---------- f0: float The frequency [Hz] at which to begin the sine sweep f1: float The frequency [Hz] at which to stop the sine sweep duration: float The length of time [seconds] over which ...
1bf11d764ded84ba20015766f7799c6b53830107
61,270
import cudf._lib as libcudf from cudf.core.column import NumericalColumn from cudf.core.buffer import Buffer def prefixsum(vals): """Compute the full prefixsum. Given the input of N. The output size is N + 1. The first value is always 0. The last value is the sum of *vals*. """ # Allocate out...
7ebb33602736c84e78750c8e755aaaac8e547b2c
61,272
from typing import List from typing import Dict def BellmanFord(graph: List[Dict[str, int]], V: int, E: int, src: int) -> int: """ Returns shortest paths from a vertex src to all other vertices. """ mdist = [float("inf") for i in range(V)] mdist[src] = 0.0 for i in range(V - 1): f...
e94c56b917248dfa2babb648baac653f02ddadad
61,273
def build_factorial(factor_count, run_count): """Builds a regular two-level design based on a number of factors and runs. Full two-level factorial designs may be run for up to 9 factors. These designs permit estimation of all main effects and all interaction effects. If the number of runs requested is ...
a6e324fbeeb59733ea849e2e2b404b869ab1f729
61,275
def say_hello(name): """ Greeter Endpoint""" resp = handlers.greeter(name) return Response(resp, mimetype='plain/text')
9f83c11c37ea668aa10c97d884da4841b2a857f4
61,276
def GetAlertProperties(services, cnxn, project_id, incident_id, trooper_queue, msg): """Create a dict of issue property values for the alert to be created with. Args: cnxn: connection to SQL database. project_id: the ID of the Monorail project, in which the alert should be crea...
3af6c0c5cb615629b86726b157393823bca00afd
61,277
def PyTmHMSXtoS(h, m, s, x): """ Convert hours-minutes-seconds-milliseconds to seconds as float Parameters ---------- h: int, hours m: int, minutes s: int, seconds x: float, milliseconds Returns ------- float, seconds """ return h * 3600.0 + m * 60.0 + s + x
550362fe48d4e6c8c94b0c885611b607c8e39e63
61,278
def _update_visited(): """ Updates the visited count by one in the cache :return: The visited count in string form. """ visited = cache.get('visited') if not visited: visited = 0 else: visited = int(visited) visited += 1 cache.set('visited', str(visited)) return str(v...
b5ad3a449fcd6cd5014616823d18e74bcc9af45f
61,280
def get_model_and_assets(num_poles=1): """Returns a tuple containing the model XML string and a dict of assets.""" return _make_model(num_poles), common.ASSETS
5cf6866a78f9cda526841c49db5556e1d27e1e60
61,282
def search(index=None): """ 查询记录:如果没有索引名称的话默认就会查询全部的索引信息 :param index:查询的索引名称 :return: """ if not index: return es.search() else: return es.search(index=index)
52f8f22c98fdf79541b1bacd48bc101c73f17481
61,285
def tp_interval_has_another_wave(to_check_data:np.ndarray, threshold_val:Real, threshold_pos:Real) -> bool: """ check if there is another wave (normal, inverted, or biphasic) within tp interval """ positive_wave_pos = np.where(np.array(to_check_data)>threshold_val)[0].tolist() negative_wave_pos = n...
940c0d36ca253c33bd48178d2738b3d12467fa46
61,286
def get_square_box(box): """Get a square box out of the given box, by expanding it.""" left_x = box[0] top_y = box[1] right_x = box[2] bottom_y = box[3] box_width = right_x - left_x box_height = bottom_y - top_y # Check if box is already a square. If not, make it a square. diff = b...
6504aac3ab6447e71cd70f7ad5ea5335c1406ac7
61,287
def permute_to_N_HW_K(tensor, K): """ Transpose/reshape a tensor from (N, K, H, W) to (N, (HxW), K) """ assert tensor.dim() == 4, tensor.shape N, _, H, W = tensor.shape tensor = tensor.view(N, K, H, W) tensor = tensor.permute(0, 2, 3, 1) tensor = tensor.reshape(N, -1, K) # Size=(N,HW,K)...
e075ded87423905a64b17dbd9888308c5ba73080
61,288
def getMBAp(mol): """ ################################################################# Calculation of Moreau-Broto autocorrelation descriptors based on carbon-scaled atomic polarizability. ################################################################# """ res={} for i in range(8): ...
57109df4a681afdf336dcddc2333be2ef9a2dfb3
61,290
def selfplay_single_player(model, env, games=10): """ Since the model will is playing a single player game the self play algorithm needs to be adjusted to account for this Parameters ---------- model : muzero muzero - since we are working with only one model (since it's single player) no need for model storage...
0a98eb312c8f22e31cc209cd132ecd6e8b850a22
61,292
import base64 def get_mole_prediction(): """ predicts mole picture, wether it is bengign or malignant :return: json """ json = request.get_json() chat_id = str(json["chat_id"]) encoded_image = json["encoded_image"] img = base64.b64decode(encoded_image) img = Image.open(BytesIO(img...
a08ca0d55611f6e4b9629f10268c873af2086faa
61,293
def detect_corners(data, target_idx=9): """ data: [{'img': [np.ndarray]}] return: [{'corners', [(x,y)]}] """ aruco_dict = cv2.aruco.Dictionary_get(cv2.aruco.DICT_4X4_50) aruco_param = cv2.aruco.DetectorParameters_create() aruco_param.cornerRefinementMethod = cv2.aruco.CORNER_REFINE_S...
6cf3fd902cc4bfdf1b58119f7a943f9f7d0ba959
61,294
from functools import reduce def qsimplify(expr): """ Simplify expression by recursively evaluating the quantity arguments. If units are encountered, as it can be when using Constant, they are converted to quantity. """ def redmul(x, y): """ Function used to combine args in m...
191fdc3415d56655751ead9e317b7032c637bdc3
61,296
def get_feedback_rating(doctype, docname): """ get and return the latest feedback rating if available """ rating= frappe.get_all("Communication", filters={ "reference_doctype": doctype, "reference_name": docname, "communication_type": "Feedback" }, fields=["rating"], order_by="creation desc", as_list=True) ...
51bbfbb58dfa4d12cb38c382fa7c9905f39b3fa2
61,297
import functools def condition(model): """ La condition à remplir pour arreté la compression """ mean = functools.reduce(lambda x ,y : x+y , model)/len(model) return mean<NB_BITS_MEAN
cc7c761b02f96ed9f4002e1eb375568fcdba15ce
61,298
def main_scoped_model_class(): """ A custom Python model class defined in the ``__main__`` scope. """ return get_model_class()
39a46ad14f04d6c12976304f31ccee74c6d48b60
61,299
from pathlib import Path def directory_size_bytes(dir_path): """Return the size of the directory's contents in bytes.""" dir_path = Path(dir_path) if not dir_path.is_dir(): raise QgrRuntimeError(f'`dir_path` must be a directory. Got {dir_path}') contents = dir_path.glob('**/*') total_size...
d5ef21a98e60e03d3cc3a3635b80749a818f7ab8
61,300
def gf_factor(f, p, K, **args): """Factor (non square-free) polynomials in `GF(p)[x]`. Given a possibly non square-free polynomial `f` in `GF(p)[x]`, returns its complete factorization into irreducibles:: f_1(x)**e_1 f_2(x)**e_2 ... f_d(x)**e_d where each `f_i` is a moni...
0d411ad75fd4ec1e58b92da13881b9557e26db03
61,301
def get_first_attachment(email): """Return the file path of the first attachment from an email. Parameters ---------- email : Message An email |Message| object. Returns ------- |str| or |None| The file path to the first attachment in the email, if one exists and is ...
b066a7ebe660f7b6bd8f91a8fa9aa958dcae135b
61,302
def instance2xml_base(anno, bbox_type='xyxy'): """bbox_type: xyxy (xmin, ymin, xmax, ymax); xywh (xmin, ymin, width, height)""" assert bbox_type in ['xyxy', 'xywh'] E = objectify.ElementMaker(annotate=False) anno_tree = E.annotation( E.folder('VOC2014_instance/person'), E.filename(anno['...
a739b4a4ce61db319a625625b2a412a3f3fcbbe2
61,303
import json def _dump_user_paths(user, paths, **kwargs): """Helper function for dumping a user paths file. Returns whether or not the dump occured successfully. """ if 'raise_errors' not in kwargs: kwargs['raise_errors'] = False user_path_file = _user_path_file(user) with flock(user_pa...
fc7b17f952af6c173fcf42eef1b1855f58a22347
61,304
def get_reading_type(meter_id, quantity_id, start_date, end_date, my_cursor): """ Return the reading type for meter METER_ID with quantity id QUANTITY_ID between START_DATE and END_DATE (Totalization, Interval) or NONE if an error occurs. Uses cursor MY_CURSOR. """ monotonic_sql = """ SE...
c7be18e960cad51a759380e3084622debaa469a5
61,305