content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
from sys import version def compare_dash_version(req_version="1.12"): """Compare the version of dash. Will return True if current dash version is greater than the argument "req_version". This is a private method, and should not be exposed to users. """ cur_version = version.parse(dashversion) ...
477966e35a6e030451dc6e0808596f3ff78ca4aa
61,207
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
import os def check_user_file(VPC, user_file): """Check/create USER_FILE""" if user_file: return user_file elif os.path.exists('/host/{0}/users.cfg'.format(VPC)): return '/host/{0}/users.cfg'.format(VPC) else: if not os.path.exists('/host/{0}'.format(VPC)): os.make...
c3e2ddf233580d4433ed27a36747a736a0f63230
61,218
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 get_workflow_tasks(username, m_wf_id, wf_id): """ Returns a collection of Tasks. :query int start-index: Return results starting from record <start-index> (0 indexed) :query int max-results: Return a maximum of <max-results> records :query string query: Search criteria :query string order: ...
401b51ce80a3869c6c7b0ef333a03ba20186e2ea
61,229
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 ucc_smartx_configs(request): """ Configure pytest parameters, if provided """ if not request.config.getoption("--browser"): raise ValueError( "--browser parameter was not provided while running the test cases." ) driver = request.config.getoption("--browser") LOG...
e5b29b06e29f5c21499a05b67cafcab874a56d9e
61,233
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
import os def file_save(request): """online edit file save event Arguments: request {object} -- wsgi request object Returns: str -- json object of the event description """ fid = request.POST.get('id', 0) content = request.POST.get('content', None) res = FileInfo.objects....
a28dd33342f3054b09a430fc44b5efe8ea4e9fa8
61,249
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 clear_path(graph, reg, loc1, loc2): """ Check that the path from loc1 to loc2 is clear. We have to check that there is no side effect between the two location points. We also have to check that the variable `reg` is not redefined along one of the possible pathes from loc1 to loc2. """ lo...
3557ececd4f6a02e1629a9a4c03188ab15582af9
61,265
def cv_h(P, h): """ Specific isochoric heat capacity [kJ / kg K]""" return cv(P, T_h(P, h))
2879d9df227156998b8c6e46163b3c8017a791c8
61,266
def get_annot_texts(ibs, aid_list, **kwargs): """ Add each type of text_list to the strings list Args: ibs (IBEISController): ibeis controller object aid_list (int): list of annotation ids Returns: list: annotation_text_list CommandLine: python -m ibeis.viz.viz_helpe...
0668bab02f008bbac29b6d33f9c9d05b08951e7d
61,267
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
def laps_detector(img): """determine if that shape is positive""" global NC_LAYER hashid = str(hash(img.tostring())) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.threshold(img, 0, 255, cv2.THRESH_OTSU)[1] img = cv2.Canny(img, 0, 255) img = cv2.resize(img, (21, 21), interpolation=cv2.INTER_CUBIC) i...
88ed96f1722430a50b321eac34c7961c5aa2c1ed
61,271
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
import base64 import os import tempfile def base64_key(task_id, base64_string): """ Convert a Base64 key string into a temporary key file. """ if task_id == None: common.exception("A task ID is required to convert a Base64 string " \ "into a temporary key file.") ...
6112bbd41cadf5bc2427d3ef15375ca210760c88
61,274
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
import time def sendSMS_through_SINCH(From, To, Cc, Bcc, Message, language='En', caller_area={}): """ sendSMS_through_SINCH """ _process_name = 'sendSMS_through_SINCH' _process_entity = 'sms' _process_action = 'send_sms' _process_msgID = f'process:[{_process_name}]' _process_identity_k...
51f32a2af79458ef9c1ea7b881f1882d30353642
61,279
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 linked_object(object, interface): """ Returns managed object linked to object:interface or None """ try: cn = object.get_profile().convert_interface_name(interface) except Exception as e: logger.error("Cannot convert interface name '%s': %s", interface, e) return None ...
e0c55a5d7064b6fd70789ac9fb7ec9931f67738f
61,281
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
from webtzite.models import RegisteredUser def update_collaborators(request, db_type=None, mdb=None): """Update the list of collaborators""" if not request.user.is_staff: raise PermissionDenied("collaborators update open only to staff right now.") collaborators = loads(request.POST['collaborators'...
e4bd748d3ac5158f92cb4ca29eb090a47d20949b
61,283
def changesetdisplayer(ui, repo, opts, differ=None, buffered=False): """show one changeset using template or regular display. Display format will be the first non-empty hit of: 1. option 'template' 2. option 'style' 3. [command-templates] setting 'log' 4. [ui] setting 'style' If all of thes...
25c35243a4d97b6d795b414ceb355b902153c251
61,284
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
import os def link_bam_file(orig_file, new_dir): """Provide symlinks of BAM file and existing indexes. """ new_dir = utils.safe_makedir(new_dir) update_files = [] for fname in (orig_file, "%s.bai" % orig_file, "%s.bai" % os.path.splitext(orig_file)[0]): if utils.file_exis...
1c5ee3b8ec3e8d0a99400c54fcffb175e236e770
61,289
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 _tensor_scatter_nd_update(tensor, indices, updates, name=None): # pylint: disable=unused-argument """Numpy implementation of `tf.tensor_scatter_nd_update`.""" indices = indices[..., 0] # TODO(b/140685491): This is probably wrong! if JAX_MODE: import jax.ops as jaxops # pylint: disable=g-import-not-at-t...
0ca3647d7201b02eaf8ff9a9233c48212a721de6
61,291
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
import os def multiprocess_worker(kwds): """Process chunks of input bam files.""" # source_bam can be a subset of annotate_bam start_annotate = kwds['start_annotate'] qname = kwds['qname'] source_headers = kwds['source_headers'] tempdir = kwds['tempdir'] chunk = kwds['chunk'] logger.in...
3968692e506dfbc3abdbdf69646a5857e5ec78d8
61,295
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