content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def calculate_delta_fields(df,fields): """Function to determine V20 - V15 for different time constant fields""" new_column_names = [] for i in fields: feature = i.split('_')[0] #cl_v15 --> cl column_name = f'{feature}_delta' new_column_names.append(column_name) v2...
011d38adffe3bc14df0da26aec15baf8002540ba
677,326
def nodes_within_bounds(indices, bounds): """ nodes_within_bounds filters a set of indices to those that are within the bounding box :param indices: a set of indices :param bounds: upper bounds for each axis, implicit minimum at 0 :return: filtered indices within bounds """ filtered = set() ...
18000d24efaade8200ca67010d1b6d52e7276f61
677,327
from typing import Tuple import torch def y0(p_1: Tuple[int, int], p_2: Tuple[int, int], xs: torch.Tensor) -> torch.Tensor: """ Returns a tensor of the y-values of line between p_1 and p_2 :param p_1: Point at which the line starts :param p_2: Point at which the line ends :param xs: Array of x...
9d3a646e6d857bfb639eccbffb16b31e0a254eb5
677,328
def secret_message(): """Shows the user a form to collect a secret message. Sends the result via the POST method to keep it a secret!""" return """ <form action="/message_results" method="POST"> Type a secret message:<br/> <input type="text" name="message"><br/> <input type="subm...
1b5a2133e26cbb4ec46937530009c2385b092864
677,329
def apk(actual, predicted, k=3): """ Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py """ if len(predicted) > k: predicted = predicted[:k] score = 0.0 num_hits = 0.0 for i, p in enumerate(predicted): if p in actual and p not in...
f0f59483f7daa20dea54f42bc01967630e443fb1
677,330
import sys import os def get_absolute_path(*part_of_the_way, dir=False): """ Enable directory check :param dir: Check if the path points to a directory :param part_of_the_way: part of the way :return: absolute path or None """ if getattr(sys, 'frozen', False): directory = os.path...
80133dcf9210704f52300330c29fe3e2e3f2f108
677,334
def _GetRegionalGetRequest(client, health_check_ref): """Returns a request for fetching the existing health check.""" return (client.apitools_client.regionHealthChecks, 'Get', client.messages.ComputeRegionHealthChecksGetRequest( healthCheck=health_check_ref.Name(), project=heal...
8abc4d639f81739fcd943658c7a6707775d5cf87
677,335
import logging def get_logger(name=None): """Return a logger to use""" return logging.getLogger("dandi" + (".%s" % name if name else ""))
ca9cf40d4edd9e5368241ff6d53e991d360601d7
677,336
import os import json def read_data_from_json(json_file): """读取JSON文件""" if not os.path.exists(json_file): raise ValueError("File not exists") with open(json_file, mode='r', encoding='utf-8') as f: return json.load(f)
c1fd48d7db8436a871cf4226cba0f90f4cd3178f
677,337
def _get_in_out_shape(x_shape, y_shape, n_classes, batch_size=None): """Returns shape for input and output of the data feeder.""" x_is_dict, y_is_dict = isinstance( x_shape, dict), y_shape is not None and isinstance(y_shape, dict) if y_is_dict and n_classes is not None: assert isinstance(n_classes, dict...
223b5a69b987282a9aa57a9627d91644b86a96a1
677,339
def _divide_if_possible(x, y): """ EXAMPLES:: sage: from sage.combinat.free_module import _divide_if_possible sage: _divide_if_possible(4, 2) 2 sage: _.parent() Integer Ring :: sage: _divide_if_possible(4, 3) Traceback (most recent call last): ...
73f88957e16c4562071152662249b1f83f1103b4
677,340
import argparse def get_options(): """ Fetches the arguments for the program """ program_desc = ("Given an input size, create a TALON job script and " "launch it.") parser = argparse.ArgumentParser(description=program_desc) parser.add_argument('--input', "-i", dest = 'input_size'...
79eda8066b7711c936cae75c7cc43cb190f5e371
677,341
def modify_carry_events_with_track_ids(df_carry_events): """ Generate a set of track IDs for each carry event. :param df_carry_events: :return: A modified df_carry_events dataframe with numeric track_ids """ df_carry_events_modified = df_carry_events.copy() df_carry_events_with_track_id = d...
80b5fc933aa846b0b05511479959991b4d3cea0c
677,343
def redistribute(M, mode): """ This function distributes the weights to a specified dimension or mode.\n Parameters ---------- M : object KRUSKAL tensor class. ktensor.K_TENSOR. mode : int Dimension number. Returns ------- M : object KRUSKAL tensor cl...
1de096a8483cac2d445a3a727784e66a9d48f9d7
677,344
def make_progress_bar_text(percentage: float, bar_length: int = 2) -> str: """ Get the progress bar used by seasonal challenges and catalysts and more Translations: "A" -> Empty Emoji "B" -> Empty Emoji with edge "C" -> 1 Quarter Full Emoji "D" -> 2 Quarter Full Emoji ...
6422dfbb7f4bb9b875491398fab57e9f8af5a380
677,345
import copy def offset_bonds(bonds, offset): """ Offset all of the numbers in the bonds array by value offset; useful for adding molecules to a system that's already established because the bond arrays start at 0. For a system with N atoms, all indices in the new molecule to be added's bonds ...
601493fb728a80a5c5ed1226fb22e41005cd9576
677,346
def get_primitive_matrix_by_centring(centring): """Return primitive matrix corresponding to centring.""" if centring == "P": return [[1, 0, 0], [0, 1, 0], [0, 0, 1]] elif centring == "F": return [[0, 1.0 / 2, 1.0 / 2], [1.0 / 2, 0, 1.0 / 2], [1.0 / 2, 1.0 / 2, 0]] elif centring == "I": ...
e24a670cf426ce8942f49631eb41c31c3b6fa468
677,347
def output_limit(): """ :return: num chars :rtype: int """ return 300
e057a83f7ab75c81fba71c45258efecf1a864ed1
677,348
def _get_children(heap, idx): """Get the children index-value of the input index.""" length = len(heap) idx_left = 2 * idx + 1 val_left = heap._idx2val(idx_left) if idx_left < length else None idx_right = idx_left + 1 val_right = heap._idx2val(idx_right) if idx_right < length else None retur...
2d073915ca595a9235caf9dab195199aba4280b5
677,349
from warnings import warn def set_style(current_style, new_style): """Utility function to take elements in new_style and write them into current_style. """ current_style['name'] = new_style.pop('name', current_style['name']) current_style['tc'] = new_style.pop('textcolor', current_style['tc']) ...
82dd6a2f7ee8538cab68ea0911aae3f8bcf6e29e
677,350
def get_userid_from_name_df(userstest, name): """ From the name we will get a User id """ return userstest[userstest.Name == name]
c9f0ce35e8b926d4aa134a188d7da25ca0f7bfb3
677,351
def numcols(m): """ Number of columns in a matrix. @type m: matrix @return: the number of columns in the matrix. return m.shape[1]; """ return m.shape[1];
249c7b1e4c6da44b4c4bd21c091e2801a4e20e0f
677,353
def getCustomStopPhrases(): """ Add any expressions that need to be ignored in addition to the nltk.corpus stoplist for english Returns ------- myStopWords : list """ myStopWords=["view entire post", "post", "twitter.com","twitter com", "share story", "intereste...
b377f7edbf93212d82a6fecb6abff99f8623035a
677,354
def load_metadata_for_docs(conn_meta, query, split_metadata=False): """ loads the metadata for documents @param conn_meta: connection to the database which includes PubMed metadata @param query: the query to contain metadata (must project pmid and metadata) @param split_metadata: if true the metadat...
5895b4a30d072ec1782c0b8713e436555e145e63
677,356
def _get_md_from_url(url): """Get markdown name and network name from url.""" values = url.split('/') return values[-1].split('.')[0] + '.md'
946bdc2e17578e041aacecb34674019a1f02c353
677,357
def triangles_cols_from_file(file_path): """Returns an array of triangles from file, which is column major. Args: file_path (str): The file name, including the path, to the data file. Returns: (list): A list of lists, which are sides to triangles. """ list_of_triangle_sides = [] ...
f29fbb56ecd5c34abcbec952b9e6f3f08f32e17b
677,358
def clean_float(v): """Remove commas from a float""" if v is None or not str(v).strip(): return None return float(str(v).replace(',', '').replace(' ',''))
fdb2b67aa974a51b2f4de167e9f63752c62680da
677,359
import copy def from_model(model): """Load |Cosmology| from `~astropy.modeling.Model` object. Parameters ---------- model : `_CosmologyModel` subclass instance See ``Cosmology.to_format.help("astropy.model") for details. Returns ------- `~astropy.cosmology.Cosmology` subclass ins...
62495e6a6fb53197668d8c5740f80ad81ae347ad
677,360
import re def find_with_line_numbers(pattern, contents): """A wrapper around 're.finditer' to find line numbers. Returns a list of line numbers where pattern was found in contents. """ matches = list(re.finditer(pattern, contents)) if not matches: return [] end = matches[-1].start() ...
322368f43a26c6b19af26a625a88d8d9b9e5d678
677,362
from typing import List def find_number_of_lis(numbers: List[int]) -> int: """https://leetcode.com/problems/number-of-longest-increasing-subsequence/""" # [length, count] of longest increasing subsequence ending at index i dp = [[1, 1] for _ in range(len(numbers))] max_length = 1 for i, value in ...
331599d3a07fd646fe8f67b0980c0d2e83460eed
677,363
import getpass def password(name, default=None): """ Grabs hidden (password) input from command line. :param name: prompt text :param default: default value if no input provided. """ prompt = name + (default and ' [%s]' % default or '') prompt += name.endswith('?') and ' ' or ': ' wh...
e1b7953e6a713e1cb31598f266e6cead09de2e45
677,364
def getPatternPercentage(df, column, pattern): """This function counts the number of df[column] which have the given pattern and returns the percentage based on the total number of rows.""" found = df.apply(lambda x: True if(isinstance(x[column], str) and x[column].startswith(pattern)) else False, axis=1).sum() r...
40ad129624e0291088af6471afcb9ea4a5648467
677,365
def invert_velocity(v, dcm_img_max=4096): """Inverts a velocity image that has been converted to uint16. Inverts the velocity direction in a phase image that has already been reference subtracted and converted to uint16. Args: v (uint16 array): Velocity image. dcm_img_max (int): Max of...
8cab7b6b4488ac4068980fb83b363905be992ace
677,366
def is_ascii(s): """ Check if a character is ascii """ return all(ord(c) < 128 for c in s)
2ca48a1337d4d49f3148583f8f86bb1f16791570
677,368
import tempfile,gzip def gunzip_string(string): """ Gunzip string contents. :param string: a gzipped string :return: a string """ with tempfile.NamedTemporaryFile() as f: f.write(string) f.flush() g = gzip.open(f.name,'rb') return g.read()
b761a2269e8b291681f6abcd7e8c132c72b224f9
677,369
def truncate_latitudes(ds, dp=10, lat_dim="lat"): """ Return provided array with latitudes truncated to specified dp. This is necessary due to precision differences from running forecasts on different systems Parameters ---------- ds : xarray Dataset A dataset with a latitude dimen...
9bdd698f598eb9de0b709d3a33cfc8668fe5baa0
677,370
def RenamePredicate(e, old_name, new_name): """Renames predicate in a syntax tree.""" renames_count = 0 if isinstance(e, dict): if 'predicate_name' in e and e['predicate_name'] == old_name: e['predicate_name'] = new_name renames_count += 1 # Field names are treated as predicate names for funct...
b01cdcb142f098faa079d2ae80952d34f8f86bcb
677,374
import pipes def get_command_quoted(command): """Return shell quoted command string.""" return ' '.join(pipes.quote(part) for part in command)
b689fb927d5c0ed253c9530edad90e860856bde4
677,375
import argparse def argparse_deprecate(replacement_message): """fail if argument is provided with deprecation warning""" def parse_type(_): """The parser type""" raise argparse.ArgumentTypeError("Deprecated." + replacement_message) return parse_type
54789797585a0eb2cb021b16bb9103857990379c
677,376
def subtracting_one(integer_one): """ It takes a integer and subtracts one Args: integer_one: the integer which needs to have one subtracted from it Returns: The integer + 1 """ return integer_one - 1
6883296d7ca2f755e3d4ba0a2dbc15a62d37d268
677,377
def check_uniq(X): """Checks whether all input data values are unique. Parameters ---------- X: array-like, shape = (n_samples, ) Vector to check whether it cointains unique values. Returns ------- boolean: Whether all input data values are unique. """ s = set() return...
fc1a98152aa63c87281c553f967e42b96a89294b
677,378
def divide_into_chunks(array, chunk_size): """Divide a given iterable into pieces of a given size Args: array (list or str or tuple): Subscriptable datatypes (containers) chunk_size (int): Size of each piece (except possibly the last one) Returns: list or str or tuple: ...
ed48ebcba3833e5d2923b6dcc6ff572c316873af
677,380
def remove_italics(to_parse: str) -> str: """ A utility function for removing the italic HTML tags. Parameters ---------- to_parse: str The string to be cleaned. Returns ------- str The cleaned string. """ return to_parse.replace("<i>", "").replace("</i>", "")
eca504b9dfa7b1dcf8892f99610c5b39ef78a1ca
677,382
def parse_iptv_login(raw_login): """ Преобразует IPTV-логин в нормальный вид :param raw_login: IP-TV Smart TUBE089004932 :return: 77089004932 """ if raw_login == '': return '' return '77'+raw_login[16:]
204640a274c16272b9b0ac8acc69720a9d0820d7
677,383
import json import hashlib def convert_inputs_md5(*args, **kwargs): """ This function is used to check if the similar call to a function has already been made :param args: The args to the given function :param kwargs: The dictionary based arguments to a given function :return: The md5 value of the...
ba52bbff8366b005ef4a17d7cf6830c68aa0e79c
677,384
from typing import Dict def settings() -> Dict[str, str]: """[summary] Returns: Dict[str, str]: [description] """ return { "config_path": "./config/experiments.yml", "job": "main" }
ce03a2816d5a85ae27140b031618caf83bcc80e8
677,385
def get_reference_layers(num_cells, pool_layers): """ By analyzing the network, get 2 lists named ref_groups and required_indices. each element of ref_groups is the number of downsampling applied to the output of the layer, for example, if ref_groups[i] = 1, at ith layer, its input...
07b732044082645d0335d5834391aabcfe574d08
677,386
import getpass def osuser(): """Return the name of the current OS user. If the name cannot be retrieved, :class:`None` will be returned. """ try: return getpass.getuser() except BaseException: return None
3f4fdc8373f70c790a4265ebb9ae95ed011fa71a
677,387
def km_to_meters(kilometers): """ >>> km_to_meters(1) 1000.0 >>> km_to_meters(0) 0.0 >>> km_to_meters(-1) Traceback (most recent call last): ValueError: Argument must be not negative >>> km_to_meters([1, 2]) Traceback (most recent call last): TypeError: Invalid argument type ...
12ac3cc3587b581f207bb3a27c7e55245d3469fc
677,388
def Factor(n): """ Provides all the factors of the number. """ try: if not isinstance(n,int): raise TypeError('Argument of Factor(n) is not integer') except: raise else: factors = {} if n<0: n = -n factors[-1]=1 if n==0 or n==1: return {n:1} mid = int(n**(1/2.0)) n_copy = n for i in rang...
e58fe0238850686f7b8899b6ff73a502e3d0dd23
677,389
def find_index(to_search, target): """Find the index of a value in a sequence""" for index, value in enumerate(to_search): if value == target: return index return -1
cdb57c9a4e1a7973b4c90e4245b939beff1d4e17
677,390
def hash_forward(a, b, c): """ 20 bits for each position, should be more than enough for any grammar """ return (a << 40) ^ (b << 20) ^ c
12258290ef8e4cee6c5b56de88f7e3e96cf61f1e
677,392
def get_available_difficulties(metadata_record): """Gets the difficulty levels that are present for a song in a metadata record.""" levels = [] for key, value in metadata_record['metadata']['difficulties'].items(): if value == True or value == 'True': levels.append(key) return levels
419203c0b04d2c1f58391ebdb757cb40f2a74f89
677,393
def is_blank(value): """ 判断各种类型的变量是否为 空变量 :param value: :return: """ if not value: return True if type(value) == bytes and (value.strip() is '' or value == "None" or value == "null"): return True if type(value) == str and (value.strip() is u'' or value == u"None" or value...
aab41d92ecdb156367e9352ac7264c835c26168a
677,394
def AsciiDataTable_to_HpFile(ascii_data_table, file_name="test.txt", schema_file_name="schema_hp"): """Converts an AsciiDataTable into an csv file by setting options and saving""" original_options = ascii_data_table.options.copy() ascii_data_table.options["column_names_begin_token"] = "!" ascii_data_tab...
18f5d521e9d28564d7e0d9ad2201ea7825e2c93a
677,395
def criteria_functions_4(): """4 functions are passed to a VMCCriteria view""" def a_to_d(args): parms = args return "ABCD".find(parms[0][0]) > -1 def e_to_m(args): parms = args return "EFGHIJKLM".find(parms[0][0]) > -1 def n_to_r(args): parms = args re...
1e15f1b51d4c48375d8cdb4545e21ab38c2cff18
677,396
import math def _map_tile_count(map_size: int, lod: int) -> int: """Return the number of map tiles for the given map. Args: map_size (int): The base map size in map units lod (int): The LOD level for which to calculate the tile count Returns: int: The number of tiles in the given...
8ced1676043098a3cfddc106b0aaab0e2745e5b2
677,397
from pathlib import Path def delta_path(input_base_path: Path, item_path: Path, output_base_path: Path) -> Path: """ Removes a base path from an item, and appends result to an output path. Parameters ---------- input_base_path : Path The sub Path to be removed from item_path. item_pat...
b4a4e2eae6ec9cfceb7412c5ab976e002eef72aa
677,398
def units_info(units): """Make the units taken from a file LaTeX math compliant. This function particularly deals with powers: e.g. 10^22 J """ components = units.split() exponent = None pieces = [] for component in components: index = component.find('^') if not ...
ce6dbca6e9544d123ee833a8a4c370eb7eb8129e
677,399
def build_tags_filter(tags): """Build tag filter based on dict of tags. Each entry in the match is either single tag or tag list. It if is a list, it is "or". """ filters = [] assert isinstance(tags, (list, dict)), 'tags must be either list or dict.' if isinstance(tags, list): tags...
a8f3acc6e2a5a920177d7965ca34efdae7415663
677,400
import json def read_json_file(file_name): """ Get the contents from the given json file. @param file_name (str): the name of the json file @return the contents of the json file """ with open(file_name) as json_data: data = json.load(json_data) return data
9e66fa028fe567795177b4a5c1013ae0ee6252ca
677,401
def mean_hr_bpm(num_beats, duration): """Average heart rate calculation This is a simple function that converts seconds to minutes and divides the total number of beats found by the total minutes in the strip. :param num_beats: a single integer of the number of total beats in a strip :param durati...
83eb5433cec77f9294e1310410e3e06ed1b1eda9
677,402
def is_pdb(datastr): """Detect if `datastr` if a PDB format v3 file.""" assert isinstance(datastr, str), \ f'`datastr` is not str: {type(datastr)} instead' return bool(datastr.count('\nATOM ') > 0)
fbcd58d55563f8fc04604fcf8f6c7c7aa000523f
677,403
import subprocess def cyg_to_win_path(cyg_path): """ Use "cygpath" on Cygwin to get windows type path which Graphviz can read. """ return subprocess.check_output(["cygpath", "-w", cyg_path]).strip(b"\n").decode()
203abe7422ca8201ce65940587e6b14f3d3323f1
677,404
def get_account_id(session): """ IAM Permission Required: - sts:GetCallerIdentity """ sts = session.client('sts') return sts.get_caller_identity()['Account']
0a991395c5e388069263e132b2807982a8e52c1c
677,405
def findall(sub, string): """ >>> text = "Allowed Hello Hollow" >>> tuple(findall('ll', text)) (1, 10, 16) """ index = 0 - len(sub) o = [] if not sub in string: return [] while True: try: index = string.index(sub, index + len(sub)) except: ...
8b13279626243b84f9df3793b1475c6e3c405fc9
677,406
import os def outcheck(path): """Decide whether to proceed or not, if output is already present.""" proceed = True if os.path.exists(path): response = input('''output path "%s" already exists. Do you want to proceed and rewrite? [y/n]\n'''%path) if response == 'n': p...
af311790cd280b3a058bbfb16da033e7daa8d54a
677,407
def similar_exact(a, b): """Exact comparison between `a` and `b` strings.""" return a == b
04a580df90bb743626859dd4f71a5c5ec3df114e
677,408
def remove_dashes(dashed_date): """ remove the dashes from a 'yyyy-mm-dd' formatted date write as a separate function because the apply(lambda x) one doesn't work as expected """ return str(dashed_date).replace('-', '')
2e9c030a9d94ddfa593a370a95a98d00ee753faf
677,409
def welcome(): """List all available api routes.""" return ( f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/<start><br/>" f"Use YYYY-MM-DD date format to choose a start date, but do not excee...
4e370fea741010e672143ef0d8196df4111d37a8
677,410
def my_function(x, y): """ A simple function to divide x by y """ print('my_function in') solution = x / y print('my_function out') return solution
303f01bc446061698fdb42cc0cb6b98ef2ff8b80
677,411
def make_wget(urls): """Download multiple URLs with `wget` Parameters ---------- urls : list A list of URLs to download from """ return 'wget -c {}'.format(' '.join(urls))
6531986f5ca3fe98406bfe0d5b8f202df96e8273
677,412
def uniform_city(): """ Uniform representation """ city = {"A":{1:1, 2:10, 3:7}, "B":{1:2, 2:20, 3:14}, "C":{1:4, 2:40, 3:28}} return city
6897ad16d38100176b70b0089c40abaa60760586
677,413
import tkinter as tk from tkinter import simpledialog def strinput(title, prompt, default='COM', nullable=False): """ Example: >>> strinput("RIG CONFIG", "Insert RE com port:", default="COM") """ root = tk.Tk() root.withdraw() ans = simpledialog.askstring(title, prompt, initialvalue=defaul...
39c55b2638b1982bb2508adb911627a606e34b90
677,414
import subprocess import os def restart(arg): """Restarts the bot in mode sent by arguments""" if not arg: return "You have to enter restart mode!" subprocess.run(["python", os.path.join( os.path.split(os.path.realpath(__file__))[0], "Restart.py"), arg, str(os.getpid())])
b9dad672b07879a79f5763f19046296eeb7a0438
677,415
def get_tf_tensor_info(tensor): """Dizionario del tensore Restituisce un dizionario del tensore serializzabile in json Args: key: Chiave del tensore rensor: tensore. Returns: Un dizionario corrispondente al sensore. """ shape = None if not tensor.tensor_shape.unkno...
b59b8fdd518782a3811c5a6f5eee122e7f076068
677,416
def text2hex(text): """ Takes in a string text, returns the encoded text in hex.""" hex_string = " ".join(format(ord(x), "x") for x in text) return hex_string
9171308f5c58ff306e1437a63027da9a197ec9de
677,417
def isascii(c): """Check if character c is a printable character, TAB, LF, or CR""" try: c = ord(c) # convert string character to decimal representation except TypeError: # it's already an int? (Py3) pass return 32 <= c <= 127 or c in [9, 10, 13]
2af9b721cab40fbcd6b65fff65b743c001ed3e5d
677,418
def f_raw(xpts, *coefficients): """ The raw function call, performs no checks on valid parameters.. :return: """ res = 0.0 for i, p in enumerate(coefficients): res += p*xpts**i return res
8479b761fb3f0e1007de2a1ad92e59316e5b8a0c
677,419
import os import errno def safely_mkdir(directory_path): """ Safely create the given directory if it doesn't already exist. Return whether or not the directory was successfully made (True if already existed). """ success = False if not os.path.exists(directory_path): try: o...
f14a05c932e486337677e84c8b0f631236634346
677,420
def _format_syslog_config(cmd_ret): """ Helper function to format the stdout from the get_syslog_config function. cmd_ret The return dictionary that comes from a cmd.run_all call. """ ret_dict = {"success": cmd_ret["retcode"] == 0} if cmd_ret["retcode"] != 0: ret_dict["message"...
815bb929cf85fae604bec5286932011b882514fe
677,421
def get_versions(cfmclient): """ Function takes input cfmclient type object to authenticate against CFM API and queries versions API to return the version number of the system represented by the CFCMclient object Current supported params are :param cfmclient: object of type CFMClient :return: l...
b38301bafe6f6f1cf1150def0dd3c504602b41d1
677,422
import re def matching_segment_range(segments, regexp, invert=False): """Returns a range object that yields the indices of those segments that match 'regexp' from all segments that are returned by function 'segment_data'. Args: segments (list): List of segments as returned by function ...
1c66a62909c998a8a7b9e2970d1ed4d1c98c0366
677,423
def _is_equal_mne_montage(montage_a, montage_b, verbose="info"): """ compare two mne montages for identity""" # fall through for msgs when verbose=True attrs_a = sorted(montage_a.__dict__.keys()) attrs_b = sorted(montage_b.__dict__.keys()) if not attrs_a == attrs_b: if verbose: ...
a21ed93aae832e7c1dcae9d1c9ab321675023cff
677,424
def find_targets(data, target): """ find all intersections in grid equal to target """ targets = list() for i, line in enumerate(data[1:-1], 1): for j, char in enumerate(line[1:-1], 1): if char == target: targets.append((i, j)) return targets
882cec64305da2a1cf79a05ba1cf56435dc49646
677,425
def get_std_color(client, color_type): """Get one of Creo's standard colors. Args: client (obj): creopyson Client. color_type (str): Color type. Valid values: letter, highlight, drawing, background, half_tone, edge_highlight, dimmed, error, warnin...
37d8aa074639bc78c87ce87af8dde861fe5e5d6b
677,426
def collectSubData(subm, created): """Returns array of time created and sub count at time """ try: subCount = subm['subreddit_subscribers'] except KeyError: subCount = 0 return [created, subCount]
060c0972ea970a3518a16fac582131526e6a0a81
677,427
import torch def bth2bht(t: torch.Tensor) -> torch.Tensor: """Transpose the 2nd and 3rd dim of a tensor""" return t.transpose(1, 2).contiguous()
5e7a448425a2d45a648eca43a260517ba78b4753
677,428
import torch def kl_regression_loss(scores, sample_density, gt_density, mc_dim=0, eps=0.0, size_average=True): """mc_dim is dimension of MC samples.""" L = torch.log(torch.mean(torch.exp(scores) / (sample_density + eps), dim=mc_dim)) - \ torch.mean(scores * (gt_density / (sample_density + eps)), dim=m...
8d774d5395770253390e6caeab9e1890ffb6997d
677,429
import io import sys def build_environ(scope, message, body): """ Builds a scope and request message into a WSGI environ object. """ environ = { "REQUEST_METHOD": scope["method"], "SCRIPT_NAME": "", "PATH_INFO": scope["path"], "QUERY_STRING": scope["query_string"].decod...
883681ae8be2f9f0c092615c18b0d4e7869592e3
677,430
def get_atom_color(): # Dictionary to store atom color """ Returns a dictionary with atom symbols as keys (strings) and color as an rgb tuple. """ a_color = {} a_color['H'] = '#ffffff' a_color['He'] = '#ff1a99' a_color['Li'] = '#999999' a_color['Be'] = '#999999' a_color['B'] = '...
590ffdaa8c8728d90ed271919362b6f1475b9d5a
677,431
import os def ping(uri): """Ping and return True if there is connection, False otherwise.""" response = False try: response = os.system("ping -c 1 -w2 " + uri + " > /dev/null 2>&1") except Exception: pass return not response
ed2ca67e0223101f6a3ab8c4bf34ff2e12f647c6
677,432
def handle_text(e, key): """ Handle a text field. """ value = "" if key in e: value = e[key] return value
81c49002d84bfae9db5b8004b53cf2f993f53c32
677,434
def basu_sig_figs(): """Returns the number of significant figures reported in Table 1 of Basu-Mandal2007. """ # q, qd, qdd sigFigTable = [[0, 14, 13], # x [0, 13, 13], # y [13, 13, 13], # z [0, 13, 13], # theta [13, 13,...
2969a6c4218b694556ac462eb3f057ac7934b555
677,435
def epoch_span_overlap(span1, span2): """Find the overlap between two epoch spans. Args: span1 (tuple of Time): Range of epochs in increasing order. span2 (tuple of Time): Range of epochs in increasing order. Returns: overlap_range (tuple of Time or None): Overlapping epoch range o...
bb1cd7edf7d58bd189c84dd7e0e1376cc3ca686b
677,437
def CAP_model(): """ CAP model hparam definition """ return { 'model': 'deep4' }
5d5c06d6bd9ac908621e0de75f696faddb6090d6
677,438
def detect_anomalies(forecast): """Detect anomalies in the forecast realized by Prophet Copied from https://towardsdatascience.com/anomaly-detection-time-series-4c661f6f165f""" forecasted = forecast[['ds', 'trend', 'yhat', 'yhat_lower', 'yhat_upper', 'fact']].copy() forecasted['anomaly'] = 0 for...
8c6946a4e531f3be006b1f1303079ca1e9349013
677,439
def _flatten(obj_to_vars): """ Object section is prefixed to variable names except the `general` section [general] warning = red >> translates to: warning = red [panel] title = white >> translates to: panel_title = white """ all_vars = dict() for obj, vars_ in obj_t...
ec5dcb1d626b545d3b1bdae13a750e0632ed3318
677,440
def is_duplicated(sentence): """Check if sentence is duplicated in the library""" f = open("OutputBrain.txt", "r") lines = f.readlines() for line in lines: if line.lower() == sentence.lower() + "\n": return True f.close() return False
79d7326c9c113975f1af062fab2b4b67e1934f01
677,441
import time def get_str_time(time_stamp, str_format='%Y%m%d%H%M'): """ 获取时间戳, Args: time_stamp 10位整型(int)时间戳,如 1375146861 str_format 指定返回格式,值类型为 字符串 str Rturn: 返回格式 默认为 年月日时分,如2013年7月9日1时3分 :201207090103 """ return time.strftime("%s" % str_format, time.localtime(time_st...
f1bb082b0edc607341ff4c3e242459751621bd0c
677,445