content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import click def legends_option(**kwargs): """Get the legends option for the different systems""" def custom_legends_option(func): def callback(ctx, param, value): if value is not None: value = value.split(",") ctx.meta["legends"] = value return val...
306986591bdbe7f201c7937bc30f523672e34af6
684,410
import re def get_confirm_lines(code): """ Takes the block of code submitted to RESOLVE and returns a list of the lines that start with Confirm or ensures, keeping the semicolons attached at the end, and removing all spaces (starting, ending, or in between) @param code: All code submitted to RESOLVE v...
53a0323c8d7c8559d3fb050a31b9b715fba5211e
684,411
def category_check(valueToCheck): """ Function to check valid category input """ equals = False numbers = [] for i in range(1, 21): numbers.append(i) letters = ['A', 'B', 'C', 'D', 'E', 'F'] for element in numbers: for signum in letters: if str(element) + signum == va...
3756bbcc77f584cf69c7d8b39518b9ed94a8bc3f
684,412
import argparse def parse_arguments(): """ Parse script arguments """ parser = argparse.ArgumentParser() parser.add_argument('--input', required=True, type=str, help='NeuroCuts tree pkl file to load and analyze.') parser.add_argument('--output', required=True, type=str, help='Binary classifier filename.') parser...
6c1bc87a7912cea69f07569d08710cc65cfec4a6
684,413
def default_options(): """Default options include all required fields.""" return {'properties': {'impersonator': 'admin'}, 'user_id': '1234', 'context': {'ip': '127.0.0.1', 'user_agent': 'Chrome'}}
fcdf83f67b395b4c2898cd41dae6e9aded065a22
684,414
def variable_unit(name): """Unit symbol for a collection variable""" if name == "angle": return "deg" if name == "delay": return "s" if name == "laser_on": return "" if name == "repeat": return "" if name == "repeat2": return "" if name == "translation": return "mm" if name == "level": r...
7241babbe1d226596b782b3ec695685943313ec6
684,415
def rotate_90(grid): """ Rotate a given grid by 90 degrees. Args: grid: Grid to rotate. Returns: Grid after being rotated by 90 degrees. """ new_grid = [] for col, _ in enumerate(grid): new_row = [] # Go through the rows, # and form new rows dependin...
7d8364492aef992cea0db75c7973686973736063
684,416
def get_single_key_value_pair(d): """ Returns the key and value of a one element dictionary, checking that it actually has only one element Parameters ---------- d : dict Returns ------- tuple """ assert isinstance(d, dict), f'{d}' assert len(d) == 1, f'{d}' return lis...
7c3dcaf1198bceff01df0fcbf108520b8807bae5
684,418
def donner_carte(nombre:int, joueur:dict, paquet:list) -> bool: """Donne une carte Args: nombre (int): nombre de cartes à donner joueur (dict): profil du joueur paquet (list): paquet de jeu Returns: bool: True si pas d'erreurs """ for _ in range(nombre): ...
8e5f483a33dc7d47dc02cbb80a7cd66f8286822e
684,420
def command(cmd, *parameters): """ Helper function. Prints the gprMax #<cmd>: <parameters>. None is ignored in the output. Args: cmd (str): the gprMax cmd string to be printed *parameters: one or more strings as arguments, any None values are ignored Returns: s ...
5e0dbec3daf11708cb5235e2d08cfae88ef27abf
684,421
def hostglob_matches(glob: str, value: str) -> bool: """ Does a host glob match a given value? """ rc = False if ('*' in value) and not ('*' in glob): # Swap. tmp = value value = glob glob = tmp if glob == "*": # special wildcard rc=True elif glob.e...
39e8cf32fafc3c1612333d230c365f1c97609e0a
684,423
def forceClone(): """ forceClone() -> bool @return: True if succeeded, False otherwise. """ return bool()
e86819a01db88fe23b9567365ec432f648c3bd74
684,424
import inspect import types def find_classes_subclassing(mods, baseclass): """ Given a module or a list of modules, inspect and find all classes which are a subclass of the given baseclass, inside those modules """ # collect all modules found in given modules if not isinstance(mods, list): ...
48ca14811909c9375afd19b7d1329af85db1fd41
684,425
def bdev_get_iostat(client, name=None): """Get I/O statistics for block devices. Args: name: bdev name to query (optional; if omitted, query all bdevs) Returns: I/O statistics for the requested block devices. """ params = {} if name: params['name'] = name return cli...
a51b0bb8214e4c22bef1e54160bed4e5bfe8495f
684,426
import re def wordize(text): """ Replace characters not matching the regex "[a-z0-9_+]+" with underscores and remove any trailing and leading underscores. """ return re.sub('\\b_|_\\b', '', re.sub('[^a-z0-9_-]+', '_', text.lower()))
da347515930c65df1d6d25a2e37af840e20ae32a
684,427
import traceback def getFileData(filePath): """ Get the content of a given file :param filePath: :return fileData: """ fileData = "" try: # Read file complete with open(filePath, 'rb') as f: fileData = f.read() except Exception as e: traceback.print_...
27fcebad4927e6ade0a9da1b747a37253f442b23
684,428
def get_receptive_field(neuron_index, layer_info, pad=(0, 0)): """ neuron_index: tuple of length 2 or int represented x axis and y layer_info: tuple of length 4 has information of receptive_field """ n, j, rf, start = layer_info if isinstance(neuron_index, tuple): center_y = start + (neu...
9bb8cb612ea7b1e6e6265311c2fd6759c041ad97
684,429
def simplify_whitespace(name): """Strip spaces and remove duplicate spaces within names""" if name: return ' '.join(name.split()) return name
eafda9cc3da43f0327597e1159d13338984671e7
684,430
import toml def data_from_toml_lines(lines): """ Return a mapping of data from an iterable of TOML text ``lines``. For example:: >>> lines = ['[advisory]', 'id = "RUST1"', '', '[versions]', 'patch = [">= 1"]'] >>> data_from_toml_lines(lines) {'advisory': {'id': 'RUST1'}, 'versions': {'patch'...
a82020a5defea4356ece2f7d01ed754feafafeae
684,431
def timings(samples): """Converts samples to sample times per observation.""" groups = samples.groupby(axis=1, level=0) return groups.apply(lambda group: group.iloc[:, 1] - group.iloc[:, 0])
9626c281208acf80375b6e2e57879e97f10f4dde
684,432
import json def stdout_packet_json(packet_dict): """ stdout_packet_json() - Prints DNS packet in JSON format to stdout. Args: packet_dict (dict) - dict derived from parse_dns_packet() Returns: True """ print(json.dumps(packet_dict)) return True
d71b1872a623bc0f50df07b8ff7920e80ab69fbf
684,433
def unames_are_equivalent(uname_actual: str, uname_expected: str) -> bool: """Determine if uname values are equivalent for this tool's purposes.""" # Support `mac-arm64` through Rosetta until `mac-arm64` binaries are ready # Expected and actual unames will not literally match on M1 Macs because # they ...
7b12db4bf89b924320e4ac0e12e1b19c76c4f3d4
684,434
import numpy def read_k2sff_file(filename): """Reads K2SFF file from given name and returns time, flux numpy arrays""" time = numpy.loadtxt(filename, delimiter=',', skiprows=1, usecols=[0]) flux = numpy.loadtxt(filename, delimiter=',', skiprows=1, usecols=[1]) return time, flux
57ba42ac461df7caa8d778cbe0815160218aced1
684,435
def get_chromosome(chrom): """Get chromosome name""" if chrom == 'chrM': return 'MT' else: return chrom.lstrip('chr')
f05ed203217e6d1c3b2db247d21e36c06b927c07
684,436
def get_current_span(pin, root=False): """Helper to get the current span from the provided pins current call context""" if not pin or not pin.enabled(): return None ctx = pin.tracer.get_call_context() if not ctx: return None if root: return ctx.get_current_root_span() r...
01e1a13a1ddf515297d9a263bcae95c90799e3df
684,437
import argparse def process_arguments(): """ Process command line arguments """ parser = argparse.ArgumentParser(description="Enron Corpus Parser") parser.add_argument('-i', '--infile', type=argparse.FileType('r'), required=True, help='Path to data file to process') parser.add_ar...
0be2243ceb56ea7f7a076f71c9451a93e7fba9ab
684,438
def setSepToken(path, pair, sep_token="[SEP]"): """set SEP token for different pre-trained model""" global separate_token separate_token = sep_token for ind, p in enumerate(pair): input_sent = p[0] if isinstance(input_sent, str): pair[ind][0] = input_sent.replace("[SEP]", sep...
fbb3d2f37900f418e27338673cf407207d516b02
684,440
def part_1b_under_equilb_design_ensemble_run_limit(job): """Check that the equilbrium design ensemble run is under it's run limit.""" try: if ( job.doc.equilb_design_ensemble_number >= job.doc.equilb_design_ensemble_max_number ): job.doc.equilb_design_ensemble...
ac35846c8bc5e5cd35771bbf88c7d895802d39cc
684,441
from typing import Union from typing import List def filter_letters(letter_strings: Union[List[str], str]) -> str: """Used to take a list of letters like ["A","ABC","AB"] and filter out any duplicate letters.""" # There is probably a cute one liner, but this is easy to follow and # probably same speed ...
3533f80fe83f41736b8c44dd4eed8e8f80a77bf5
684,442
def _permutation_correctness(pathway_feature_tuples, original): """Determine whether the generated permutation is a valid permutation. Used in `permute_pathways_across_features`. (Cannot be identical to the original significant pathways list, and a feature should map to a distinct set of pathways.) ...
4e66a49aa82a53777abda73da4a15851e2527d8f
684,443
def label_to_int(label): """ Label to tensor :param label: :return: """ if label == 'female': return 0 else: return 1 # end if
3c0a4f330a7dba7444a984806872c3f6a38ce4b5
684,444
def get_column(grid, column_index): """Return the column from the grid at column_index as a list.""" return [row[column_index] for row in grid]
220cb895fa42461a521aa9f54f7bbf240d84bd43
684,445
from typing import Tuple import requests def create_sq_project(sq_server: str, auth: Tuple, proj_id: str) -> str: """Creates a SonarQube project for the current project""" url = f"{sq_server}/api/projects/create" name = f"project-{proj_id}" args = {"name": name, "project": name, "visibility": "public...
0811a097e2a9c6610da22cb4c7f1160f271142af
684,448
def fit(approach, train_dict): """ Given a train data (features and labels), fit a dummy classifier. Since we can actually not fit a model, it returns the probability of complaint. Parameters ---------- approach: dictionary Approach configuration coming from the experiment yaml trai...
25a8a48c00ba1dda838264da60f3a3475b9b5ed4
684,449
def count_words(my_string): """ This function counts words :param my_string: str - A string of words or characters :return: int - length of words """ if not isinstance(my_string, str): raise TypeError("only accepts strings") special_characters = ['-', '+', '\n'] for character i...
69860cb359c2150e52a3f6eda5b3090ab22fb07a
684,450
import re def toSentenceCase(text): """ Converts the given text to sentence case. Args: text (string): Text to convert to sentence case. Returns: (string): Sentence case version of given text. """ return re.sub(r"(?<=\w)([A-Z])", r" \1", text).title()
e1c608befc50a9896aa67dba38b8aef8924540d0
684,451
import re def readLinking(goldStdFile): """ Reads a file containing Entity Linking output according to the KBP 2013 format. Each line in the systeming output file consists of 2 or 3 fields: mention_id KB_ID (optional confidence, default is 1.0) Each line in the gold standard file may contain 2 o...
70e4a4df885de7e9426704420a10e59b1daf0e2d
684,452
def _compute_nfp_uniform(l, u, cum_counts, sizes): """Computes the expected number of false positives caused by using u to approximate set sizes in the interval [l, u], assuming uniform distribution of set sizes within the interval. Args: l: the lower bound on set sizes. u: the upper bo...
847e0141015ee3c5e07426420c14ef63f212dd8f
684,454
def class_counts(rows): """Counts the number of each type of example in a dataset.""" counts = {} # a dictionary of label -> count. for row in rows: # in our dataset format, the label is always the last column label = row[-1] if label not in counts: counts[label] = 0 ...
7ef0ca8fe014e18248edd3d0111960dc431e3cf8
684,455
def is_pandigital(n: int) -> bool: """Determine if n is pandigital.""" lst = set(sorted([int(i) for i in str(n)])) return len(lst) == 10
e324671b592c26118dc5a4308cc0501fb7511bbf
684,456
import os def file_type(file: str) -> str: """Return type of given file""" return os.path.splitext(file)[1]
97b09dc2f9ab57d52af9045fbb7a41ae20576ace
684,457
from typing import Dict from typing import Any def traverse_dict(d: Dict, key_path: str) -> Any: """ Traverse nested dictionaries to find the element pointed-to by key_path. Key path components are separated by a ':' e.g. "root:child:a" """ if type(d) is not dict: raise TypeError(f"u...
aa997f04229657996956faaec90299fe3a6c298f
684,458
def is_prime(n): """ Decide whether a number is prime or not. """ if n < 2: return False if n == 2: return True if n % 2 == 0: return False i = 3 maxi = n**0.5 + 1 while i <= maxi: if n % i == 0: return False i += 2 return Tru...
429400f6ffe153f8548cf8ccb1c16efaccb75d35
684,459
def fluid_needed(molarity : float, mw : float , mass : float) -> float: """How much liquid do you need for a solution of a specific molarity?""" return mass/mw/molarity
9f3823b0e43ac6a7455cc9ac347fb5341eccf6b1
684,460
def get_install_requires(): """ Get install requirements. Returns: list, list of dependent packages. """ with open('requirements.txt') as file: return file.read().splitlines()
193653bfe4508594c95579c2638de96d185bdff5
684,461
def all_testcases_dict(class_testsuite): """ Pytest fixture to call add_testcase function of Testsuite class and return the testcases in kernel""" class_testsuite.SAMPLE_FILENAME = 'test_sample_app.yaml' class_testsuite.TESTCASE_FILENAME = 'test_data.yaml' class_testsuite.add_testcases() return clas...
55c92bd8a2c351392502d32972e02f6fdb2e3375
684,462
from pathlib import Path def get_backups_in_path(folder, file_type): """Return a collection of all backups of a specified type in a path. Use the rglob utility function to recursively search a directory for all backup files of the type `file_type`. Pass an empty string to not spe :param fold...
cbe5569d5c520e54e55eeb99481877a73639b87e
684,463
def get_poetry_pages(): """Return an array of poetry pages to crawl""" poetry_pages = [ { "path": "/wiki/Владимир_Владимирович_Маяковский", "author_name": "Mayakovsky" }, { "path": "/wiki/Стихотворения_Блока_1897-1904", "author_name": "Blok" }, { "path": "/wi...
e849b15045857836044ae061a18075e3ffcbf990
684,464
def get_skew_diag_data(genome): """returns a skew diagram""" output = 0 result = [] # print(output, end=' ') result.append(output) for i in genome: if i == 'C': output = output-1 # print(output, end=' ') result.append(output) elif i == 'G': ...
9c48deea1447c64b7f6db8d0f0fa0b34d7c6af50
684,465
def format_xi_stats(users_as_nodes, exp, xi_mean, xi_std, tot): """Formats the curvature estimates for logging. Args: users_as_nodes: Bool indicating which interaction graph was generated. If True (False), a user-user (item-item) interaction graph was generated. exp: Boolean indicating if the interac...
77ad6c0cc534e21cf938a28a64e6bc1711caa27b
684,466
def special(): """ The jar of special chars, returns dict """ mp = {} while len(mp) < 256: mp[len(mp)] = "." mp[len(mp)] = "," mp[len(mp)] = "!" mp[len(mp)] = "*" mp[len(mp)] = "#" mp[len(mp)] = "&" mp[len(mp)] = "^" mp[len(mp)] = "~" retur...
23ff43ebd9b62b4af92b0c457aa0f42914698169
684,467
def get_all_followers(igapi, target_userid): """ Returns a list of {"username": "", "userid": 0, "is_private": false, "full_name": ""} """ follower_list = [] current_followers_list = igapi.getTotalFollowers(target_userid) for follower in current_followers_list: user = { "user...
f9e196eae08dc4da2632705580a5a2d53fe67960
684,468
def greatest_common_divisor(a: int, b: int) -> int: """ Euclid's Lemma : d divides a and b, if and only if d divides a-b and b Euclid's Algorithm >>> greatest_common_divisor(7,5) 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co...
f2e707a614e2c0b5fa73ce83fe79b1451fbdb910
684,469
def process_sync(py, nproc, sync_directory, output_directory, periods, waveform_length, sampling_rate, taper_tmin_tmaxs): """ process the sync. """ script = f"ibrun -n {nproc} {py} -m seisflow.scripts.asdf.mpi_process_sync_series --sync_directory {sync_directory} --output_directory {output_directory} --...
d1df7d2d76b68c8b8c1f1ddafcc72ea193735265
684,470
def _build_xpath_expr(attrs) -> str: """ Build an xpath expression to simulate bs4's ability to pass in kwargs to search for attributes when using the lxml parser. Parameters ---------- attrs : dict A dict of HTML attributes. These are NOT checked for validity. Returns ------- ...
b1e06e2982a4e8f745b87f25c89d50353c880e3e
684,471
def insert_symbol(symbol: str, fbid: str, dict: dict): """ Modifies the dictionary in place by inserting the symbol as the key and the fbid as the value. If the symbol is already present in the dictionary the fbid is added to the unique set of FlyBase IDs in the value :param symbol:str - A single ...
2ec8c2915b7b716ca2fe1d6519dae6cc434f9566
684,472
def buildPacket(fileData, succesfullyOpened): """Builds the packet to be returned""" statusCode = 0 #this checks if the file was succesfully opened if succesfullyOpened: statusCode = 1 #Packet Header returnArray = bytearray([ (0x497E & 0xFF00) >> 8 , (0x497E & 0xFF) >> 0...
82e5b7c118c1fc645f94dd6fdd7ac7b33986a3fd
684,473
import os import numpy def importBrukerSpectrum(path, offset, sw_p, nc_proc, sf, si, bytordp): """ Load processed 1D Bruker spectra (*1r* files) from *path*. :param str path: Path to *1r* file :param float offset: *offset* (ppm value of the first data point of the spectrum) parameter from *procs* file :param fl...
76016d93407d7495b99e4937787847524c1d061b
684,474
import collections def _infer_transform_options(transform): """ figure out what transform options should be by examining the provided regexes for keywords """ TransformOptions = collections.namedtuple("TransformOptions", ['CB', 'dual_index', 'triple_in...
b230a6785a6c1a8dd0ab4a51af653675b7963243
684,475
def next_quarter(year, quarter, num=1): """return next quarter for Gregorian calendar""" if quarter not in range(1, 5): raise ValueError("invalid quarter") quarter -= 1 # for mod, div quarter += num year += quarter / 4 quarter %= 4 quarter += 1 # back return year, quarter
3a1e6cf46d88146b38da6dfe92158c92660bb99b
684,476
import ntpath def path_leaf(path): """ guaranteed filename from path; works on Win / OSX / *nix """ head, tail = ntpath.split(path) return tail or ntpath.basename(head)
5c3bc4b4d172330da9cc553274e0eb58567dfbfe
684,477
import re def win_path_to_unix(path, root_prefix=""): """Convert a path or ;-separated string of paths into a unix representation Does not add cygdrive. If you need that, set root_prefix to "/cygdrive" """ path_re = '(?<![:/^a-zA-Z])([a-zA-Z]:[\/\\\\]+(?:[^:*?"<>|]+[\/\\\\]+)*[^:*?"<>|;\/\\\\]+?(?![...
be9255d582a6879ed0dc651e3c7c4dd2942e7197
684,479
def entry_to_bytes(arch, entry: dict) -> bytes: """ Pack a U-Boot command table *entry* (struct cmd_tbl_s), as defined by the following dictionary keys and return it's representation in bytes. +---------------+---------------+----------------------------------------------+ | Key | Value T...
5cfaeee6bdd20af86e81b6245480f419a5c9a8aa
684,480
from typing import List import os def get_tag_whitelist( github_repository: str, container_names: List[str], commits_per_branch: int ) -> List[str]: """Use git to get a list of tags we'll whitelist.""" # Initialize whitelist with anything specific whitelist = [] for container_name in container_nam...
5c184bfd673c935d2190bca4e59d38d47f757037
684,481
import requests import json def api_call(page, username, password): """ This function makes an API call to the leitos ocupaca API within DataSUS Arguments: page: a string or integer with the number of the page to request username: a string with the username login information for the API ...
0aa1f8cb6354220ad3fe7e5660dc356921810f80
684,482
import os def IsMac(): """Returns true if the platform is Mac.""" return os.name == 'posix' and os.uname()[0] == 'Darwin'
14b8515d6009a2a745e76d858778af6bf55306b2
684,483
import os import plistlib import logging def get_app_folder_and_version(app_name: str) -> tuple: """Gets the version and install path of Discord.fm with the provided .app path. :param app_name: Path to .app of Discord.fm :type app_name: str :return: Tuple with installation path and a version string r...
f30b2fdd1903544bd41949164c00a9519220b72f
684,484
def test_input_html(gen, el): """<input type="text" name="field1" value="val">""" return gen.input(type='text', bind=el)
43156da4750ec19bbc4babfee338601e859bc4e8
684,485
def ref(i): """ref returns a string with a reference to object number `i`""" return b'%d 0 R' % i
252e45a33a7ddd46186222fdd513adb1daa926d3
684,486
import re def expandMd(md): """ Turns abbreviated MD into a full array """ ret = [] for i in re.findall("\d+|\^?[ATCGN]+", md): if i.startswith('^'): ret.extend(list(i[1:])) elif i[0] in ["A","T","C","G","N"]: ret.extend(list(i)) else: re...
55a142468ac23089438aa7e1d7d773a4925fc6a8
684,488
def to_unit_memory(number, precision: int = 2): """Creates a string representation of memory size given `number`.""" kb = 1024 number /= kb if number < 100: return "{} Ki".format(round(number, precision)) number /= kb if number < 300: return "{} Mi".format(round(number, precis...
2c4c3f163c40db572656c7e4cf916de32630fb5b
684,489
def od_detection_eval(od_detection_learner): """ returns the eval results of a detection learner after one epoch of training. """ return od_detection_learner.evaluate()
d3cb6b4b46ef8de47c900ed030dee4ab88e46344
684,490
def structure_metadata(structure): """ Generates metadata based on a structure """ comp = structure.composition elsyms = sorted(set([e.symbol for e in comp.elements])) meta = { "nsites": structure.num_sites, "elements": elsyms, "nelements": len(elsyms), "compositi...
605634ee52ea917cb8074d975a118af48a4a47b4
684,491
def get_compare_state(service_bibcode, classic_bibcode, classic_score): """ compare service and classic resolved bibcodes and return descriptive state :param service_bibcode: :param classic_bibcode: :param classic_score: :return: """ not_found = '.' * 19 if classic_score == u'5': ...
a81bdd33760277cdd915d7d35a9cf572e9d6e42b
684,492
def clicked_engagement_reward(responses): """ this function will calculate the reward :param responses: :return: """ reward = 0.0 total = len(responses) for response in responses: reward = reward+((response.rating-3)/2.0) #normalize rating between -1 and 1 # reward = rew...
d4bbd1869ef5634f05f96f5a727345ec4dc69244
684,493
def swap(L, i, j): """Swaps elements i and j in list L.""" tmp = L[i] L[i] = L[j] L[j] = tmp return L
9cdc2979050e8e6049cc75656324307757a28fcd
684,495
from typing import Sequence def is_cyclic_6(num_list: Sequence[str]) -> bool: """Determines if num_list is cyclic and contains 6 values.""" return len(num_list) == 6 and num_list[-1][-2:] == num_list[0][:2]
a3274ece3534c78a8f1ffefe136def762ad132af
684,497
def parse_gav(gav, defaults=(None, None, None)): """Parses the given GAV as a tuple. gav the GAV to parse. It must be a string with two colons separating the GAV parts. defaults a triple of default coordinates to return if a part from the input is missing Returns: ...
280b8a38c4dffba7dac16f30c0418de7416727f7
684,498
def _get_indices(term, chunk): """Get indices where term appears in chunk Parameters ---------- term : str The token to look for in the `chunk` chunk : [str] A chunk of text in which to look for instances of `term` Returns ------- [int] Indices in `chunk` where ...
a9ae9f046e1266ec4fc96291d16c64ffb8a2e49a
684,499
import unicodedata def meta_tostring(metadata): """Convert the metadata dictionary to text header""" lines = [] lines.append('# {}\n'.format(metadata.get('title', ''))) for k, v in metadata.items(): if k != 'title': lines.append(f'{k}: {v}') return unicodedata.normalize('NFC'...
8863d2fa745c21e824181c113f26c22cc281a6b1
684,500
import logging def z_norm(data, params=None): """ Normalizes the data using the z-normalization Works also with multi-dimensional data :param data: 2d array of power consumption :return: the mean power consumption, the std power consumption, and the normalized power """ logging.warning(f'...
64407ca91179db3a34b7ba5011866b7865937225
684,501
from typing import Any def get_cameras_and_objects(config: dict[str, Any]) -> set[tuple[str, str]]: """Get cameras and tracking object tuples.""" camera_objects = set() for cam_name, cam_config in config["cameras"].items(): for obj in cam_config["objects"]["track"]: camera_objects.add(...
89fdb11eaacfc547cf500f94ef993efd9d339b93
684,502
def dt_to_camli_iso(dt): """ Convert a datetime to iso datetime compatible with camlistore. """ return dt.isoformat() + 'Z'
fe193c76d122f0195d511386ff3ba892b6c7b9aa
684,503
import hashlib def find_new_emails(config, emails): """Walks through e-mails, hashes them, and checks whether such a hash already exists in the config file. Only return new ones.""" #digest_message = ((hashlib.sha256(m.as_bytes()).hexdigest(), m) for m in emails) #Python 3 digest_message = ((hashlib.s...
605beb8282170259a61bceb57faf0d6f8884ed35
684,504
def floatOrNone(v, default=0.0, exctype=Exception): """Returns the float value of the given value, or default (which is normally 0.0) on error. Catches exceptions of the given exctype (Exception by default)""" try: return float(v) except exctype: return default
c0b1b0152cdc39678dc437f821054e2dd9f01a61
684,505
import torch def get_mrr(indices, targets): #Mean Receiprocal Rank --> Average of rank of next item in the session. """ Calculates the MRR score for the given predictions and targets Args: indices (Bxk): torch.LongTensor. top-k indices predicted by the model. targets (B): torch.LongTensor....
ae177696d4b7afc24ae71e67896be1c727a32efa
684,506
import os def get_dir_size(dirpath): """Modified from http://stackoverflow.com/questions/12480367/how-to-generate-directory-size-recursively-in-python-like-du-does. Does not follow symbolic links""" return ( sum( sum(os.path.getsize(os.path.join(root, name)) for name in files) ...
4d0dd19967df58a3b0ba640ac7a94283427b32c8
684,507
import os import hashlib import base64 def get_local_package_hash(module): """ Returns the base64 encoded sha256 hash value for the deployment package at local_path. :param module: :return: """ local_path = module.params['local_path'] block_size = os.statvfs(local_path).f_bsize hash...
8609ded149aa5f2ed025caf10889d4b72cf4cf8a
684,508
def get_valid_results(df_res): """Splits up results into valid and invalid results. Based on properties computed in data.py.""" # Select valid results (one pair of resized ellipses) cond_valid = df_res['inside'] & df_res['resized'] & (df_res['num_annot']==2) df_res_valid = df_res.loc[cond_valid...
e5ee85899440512d4ca451f35928405aeae1d49b
684,510
def improved_i_sqrt(n): """ taken from http://stackoverflow.com/questions/15390807/integer-square-root-in-python Thanks, mathmandan """ assert n >= 0 if n == 0: return 0 i = n.bit_length() >> 1 # i = floor( (1 + floor(log_2(n))) / 2 ) m = 1 << i # m = 2^i # # Fact: (2...
db6b6c2149e2b8a736438d0c91d0275179078b85
684,511
def calc_eps(): """ calculate machine epsilon """ eps = 1.0 while eps + 1 > 1: eps /= 2 eps *= 2 return eps
b390ded7e5b22c4705ec56f88436ec0dd7e94477
684,512
import inspect from typing import Dict from typing import Any def _build_bool_option(parameter: inspect.Parameter) -> Dict[str, Any]: """Provide the argparse options for a boolean option.""" params = {"action": "store_false" if parameter.default is True else "store_true"} return params
e97e45743c45d9e4bc240555c0ec6fe01bd6a41a
684,513
def _get_default_image_id(module): """ Return the image_id if the image_id was specified through "source_details" or None. """ if "source_details" in module.params and module.params["source_details"]: source_details = module.params["source_details"] source_type = source_details.get("sour...
b151cacf948dc9d41f8010064781d634f31984ba
684,514
from pathlib import Path def get_test_path_services(filename, data_type): """ Gets the path of the filename for a given data type Args: filename (str): Name of file, not path data_type (str): Data type, CRDS, GC, ICOS etc Returns: pathlib.Path: Absolute path to...
f9a12216a21b18403d5331db94a05f5322f53fd9
684,515
import pkg_resources def readfile(filename: str) -> str: """Read a file that is contained in the openclean_notebook package. This is a helper method to read Javascript files and HTML templates that are part of the openclean_notebook package. Returns a string containing the file contents. Paramet...
0a927ca89cc3ffb49c6f85328ff2cd830bfa8536
684,516
import string def add_numbering(ax, i=0, loc=(0.8, 0.8), label='', style='APS', numbering='abc', **kwargs): """ Add numbering (a,b,c,...) to axis. Parameters ---------- ax : matplotlib.pyplot.axis object i : int The axis index, e.g., i=1 -> (a) loc : tuple or list Position of label, relative to...
af45e454fb12eb9270b065c311d7860d9997025f
684,517
def abbr(self, abbr="", string="", **kwargs): """Defines an abbreviation. APDL Command: *ABBR Parameters ---------- abbr The abbreviation (up to 8 alphanumeric characters) used to represent the string String. If Abbr is the same as an existing ANSYS command, the abbreviati...
d149d417d49300ec3d20219d679cf2821aecc6eb
684,518
import re def normalize_tag_name(name): """ Normalize an EC2 resource tag to be compatible with shell environment variables. Basically it means the the following regex must be followed: [a-Z][a-Z0-9_]*. This function is not meant to handle all possible corner cases so try not to be stupid with tag naming....
3ae1974d144a0927561ed13ac620be5e38e02786
684,519
def number_of_frames_is_int(input): """ Validate Number of Frame input. """ try: int(input) return True except ValueError: return False
4f9ef0747e77533ca4a54a69860b2a2d4ada5cd8
684,520
def cmd_name(python_name): """Convert module name (with ``_``) to command name (with ``-``).""" return python_name.replace('_', '-')
668f55611add8463b633e55f5657002cf35b7e81
684,521