content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _is_messy_encoding(normalized_encoding: str) -> bool: """判断经常导致乱码的 iso8859-* 和 windows-125* 编码""" return normalized_encoding.startswith('iso8859') or normalized_encoding.startswith('cp125')
739dff1e818503704590668cb02f1e5ff642f902
675,554
def MaximumLikelihood(pmf): """Returns the hypothesis with the highest probability.""" prob, val = max((prob, val) for val, prob in pmf.Items()) return val
272c6072bc3efc182806a883d0af9c18b04742f5
675,555
import re def fuzzy_annotation_search(search_name, search_list): """Returns all files containing both name and an annotation extension""" hits = [] for ext in ["gtf", "gff"]: # .*? = non greedy filler. 3? = optional 3 (for gff3). (\.gz)? = optional .gz expr = fr"{search_name}.*?\.{ext}3?(\...
cd622bd242f57459827dd4ff00e2dd7f1b358ae1
675,556
from datetime import datetime import pytz def read_gpvtg(sentence, timestamp, do_print=False): """ Read and parse GPVTG message""" values = sentence.split('*')[0].split(',') result = {} # Linux timestamp try: result['linux_stamp'] = int(timestamp) except: result['linux_stamp']...
7029eda2f45f7d87d0fafe673fa2244135dbdcae
675,557
def increment_by_42(f): """A function meant to be a decorator. @param f The function we are going to wrap. This function is passed to us by the intepreter. @return A wrapped function. """ def incrementor(*args): incremented = map(lambda n: n+42, args) return f(*incremen...
f4df1d4c95ccb642ef0e761ea48b9ec3f2b1b74d
675,558
def create_delegator_for(method): """ Creates a method that forwards calls to `self._main_win` (an instance of :class:`TreeListMainWindow`). :param `method`: one method inside the :class:`TreeListMainWindow` local scope. """ def delegate(self, *args, **kwargs): return getattr(self._main_wi...
3f163673fb7b50d7f036202e06f115d3e79fc73c
675,559
def COUNT_DISTINCT(src_column): """ Builtin unique counter for groupby. Counts the number of unique values Example: Get the number of unique ratings produced by each user. >>> sf.groupby("user", ... {'rating_distinct_count':tc.aggregate.COUNT_DISTINCT('rating')}) """ return ("__builtin__count__disti...
d488eda52080b6554256dfd08f29f174b7fbe1ea
675,560
import string def plural(text): """ >>> plural('activity') 'activities' """ aberrant = { 'knife': 'knives', 'self': 'selves', 'elf': 'elves', 'life': 'lives', 'hoof': 'hooves', 'leaf': 'leaves', 'echo': 'echoes', 'embargo': 'e...
95da4a879336783fc7b9de6a0068b55abedfc2b7
675,561
import torch def normal_sample_deterministic(mu, logvar, eps, use_cuda=False): """ Reparmaterization trick for normal distribution """ if use_cuda: eps = eps.cuda() std = torch.exp(logvar / 2.0) return mu + eps * std
135d5ebb89799eb2c2b95aaada07bf02e4e8b782
675,562
def clamp(value, minimumValue, maximumValue): """clamp the value between the minimum and the maximum value :param value: value to clamp :type value: int or float :param minimumValue: minimum value of the clamp :type minimumValue: int or float :param maximumValue: maximum value of the clamp ...
a9fa67fe2beb876d3c6455fbbaf5c918772480d7
675,563
def nominal_nuisance_parameters(): """ Utility function to be used as input to various SampleAugmenter functions, specifying that nuisance parameters are fixed at their nominal valuees. Returns ------- output : tuple Input to various SampleAugmenter functions """ return "nomina...
0df2d5d30e69b95a49837d960540907a4bdf989c
675,564
def check_for_url_proof_id(id, existing_ids = None, min_id_length = 1, max_id_length = 21): """Returns (True, id) if id is permissible, and (False, error message) otherwise. Since we strip the id, you should use the returned one, not the original one""" id = id.strip() # maybe this is too restrictive,...
9603c8fa24a445d8eec32a73c5bddb5db066d29c
675,565
def is_equal_1d(ndarray1, ndarray2, showdiff=False, tolerance=0.000001): """ Whether supplied 1d numpy arrays are similar within the tolerance limit? Parameters ---------- ndarray1 : numpy.ndarray[float64, ndim=1] First array supplied for equality with `ndarray2`. ndarray2 : numpy...
7d7db89b379b6ab626ad18d2e1de19312166c90e
675,567
import numpy as np def score(cats, hweight=1.0, dweight=1.0, display=50): """ Computes scores for CATS vehicles and displays them CATS field layout: body, weapons, wheels, gadgets, health, damage, energy """ # calculate the score for each CATS vehicle and sort scores = np.heaviside(cats[...
8429c194f37d7809db89f41a05ab68a399845411
675,568
def sort_and_uniq(linput): # @ReservedAssignment """ Función que elimina datos repetidos. :param linput: Lista :type linput: list :return: Lista modificada :rtype: list """ output = [] for x in linput: if x not in output: output.append(x) output.sort() ...
009bb3ddb963789de8129979ebf5f2c784c2a6ba
675,572
def is_audio_format(fmt): """ To know whether the file needs conversion. """ return fmt in ['aac', 'mp3', 'm4a', 'wav']
4d8f59b91601423508669094389e5b1f0e84495a
675,573
import asyncio def swait(co): """Sync-wait for the given coroutine, and return the result.""" return asyncio.get_event_loop().run_until_complete(co)
3fca650eadce043602a07c909a0988846e6405e0
675,574
def get_indexes(table, col, v): """ Returns indexes of values _v_ in column _col_ of _table_. """ li = [] start = 0 for row in table[col]: if row == v: index = table[col].index(row, start) li.append(index) start = index + 1 return li
fd585a908477dd3632f2dbc3f450c1601157e928
675,575
def calculate_original_position_pytorch(preds, crop_center, crop_size, hand_side, resized_size): """ checked """ new_preds = preds.clone() bs = preds.shape[0] hand_side = hand_side.view(bs,-1) for i in range(bs): if hand_side[i]: new_preds[i, :, 0] = resized_size - new_...
80d900000cb63598484d0433918ca04e120a75ea
675,576
def in_direction_of_goal(board): """ Values if any of the placed blocks are in the direction of the goal :param board: current Board State """ value = 0 for block in board.move.placed_blocks: x = block[1] y = block[0] for i in board.numbered: if i[0] ...
060e93fe7118051f0d04cc1a31fd859187140bc3
675,577
def newickContainsReservedWord(nt, options): """ newickContainsReservedWord() checks the newick to make sure that there are no reserved names used as IDs. At present the only reserved name is 'parameters'. """ reservedWords = set(['parameters', 'burnin', options.rootName]) if nt is None: ...
9f76f765dcc22a946510f1b53e24e601fe6f9d9a
675,579
def get_move(board): """ Given a Board object, this method prompts the user for a move and then gets it and returns it in the form of a three-element tuple. First element of tuple: row ID Second element of tuple: column ID Third element of tuple: Boolean indicating if the move is to flag or not ...
40df6a7a4d046dc666f8292cf647489a10d338fc
675,580
import json def load_json(filename): """Load a json file as a dictionary""" try: with open(filename, 'rb') as fid: data = json.load(fid) return data, None except Exception as err: return None, str(err)
ce780775aa54913c63e2b9a4525c0da6f053e3fb
675,583
def determine_Cd(w_10): """ Determining the wind speed drag coefficient Following Large & Pond (1981) https://doi.org/10.1175/1520-0485(1981)011%3C0324:OOMFMI%3E2.0.CO;2 """ return min(max(1.2E-3, 1.0E-3 * (0.49 + 0.065 * w_10)), 2.12E-3)
8afdb7c802e0d97276b172372079f29d8f9416fa
675,584
import argparse def parse_args(): """Parses command line arguments.""" description = "runs a BOHB search for hyperparameters" parser = argparse.ArgumentParser(description=description) parser.add_argument('data_path', metavar='D', type=str, help='path to the data folder') pa...
3fe642b7184bd920cbd9cdd1d17d60f1397d4c43
675,585
def combinations(variables, field_items, current=None): """Return all combinations of variables in the stencil with fields in the dataset. """ result = [] if current is None: current = [] pos = len(current) for name, field in field_items: if not field.get("vega_lite_types"): ...
437205fa32354b49febdec26bb350d75a34ca65b
675,587
def pack(timestamp, temp, accel_data, gyro_data, magnet_data=None): """ 最新位置情報データを辞書化する。 引数: timestamp 時刻 temp 気温(float) accel_data 加速度データ(辞書) gyro_data 角速度データ(辞書) magnet_data 磁束密度データ(辞書):オプション 戻り値: 最新位置情報データ群(辞書) """ return_dict = {'a...
ae0a9ebddc4e942658cfd6e61ede6b6b8058fe16
675,588
def to_dms(value): """ Convert a number to sexagesimal format (DD:MM:SS.ss). "dms" is a mnemonic for "degrees minutes seconds", but it will maintain whatever units happen to be passed in (e.g. hours) """ sign = '' if value < 0: sign = '-' value = -value degrees...
2e8d6bddff845180efcb1a74711b3bd7249ba5cc
675,589
def doppler_resolution(band_width, start_freq_const=77, ramp_end_time=62, idle_time_const=100, num_loops_per_frame=128, num_tx_antennas=3): """Calculate the doppler resolution for the given radar configuration. Args: start_freq_const (float): Frequency chirp starting point. ...
f9c10b6341a9e479537ae8adfbbd3f72321c0f1a
675,590
def compare_ints(item_co_int, rel_int, other_co_int, coord_int): """ Returns the int of the item_coordinates, if the number of the relation is > 0 and the item_int is > other_co_int aswell or the relation is < 0 and the item_co_int < other_co_int respectively. If the relation is positive and the ite...
6986589460ff3715796a5ae66f3bbdb4259fbdb2
675,591
import argparse def parse_arguments() -> argparse.Namespace: """ Parses command-line arguments and returns a Namespace of input values. Returns ------- An argparse Namespace object """ infile_help = "name/path of input file of tabular data to read" column_help = "label of column to u...
5c54bd462a3ed16810d3f0bb3249e4f2ee98ff8f
675,592
import torch def lengths_to_mask(lengths, max_len): """ This mask has a 1 for every location where we should calculate a loss lengths include the null terminator. for example the following is length 1: 0 0 0 0 0 0 The following are each length 2: 1 0 0 0 0 3 0 0 0 0 if max_len is ...
d487f46c129014092f520f7361926389c6a5ee1a
675,594
def check_line(line): """Check that: * a line has nine values * each val has length 1 * each val is either digital or "-" * digital values are between 1 and 9 """ vals = line.split() if not len(vals) == 9: return False for val in vals: if not len(val) == 1: ...
8d1a8d49e30c7fac395cba351010c77461bf0540
675,595
import six def collect_ancestor_classes(cls, terminal_cls=None, module=None): """ Collects all the classes in the inheritance hierarchy of the given class, including the class itself. If module is an object or list, we only return classes that are in one of the given module/modules.This wi...
8ad9eddf72ea9f7104a28b21797237f42f57b341
675,596
def k_to_q(k: float, d: float) -> float: """ Parameters ---------- k : float [description] d : float [description] Returns ------- float [description] """ k_div_d = k / d if k_div_d >= 0.5: base = 1 - k_div_d return 1 - 2 * base * base...
5242dc943cc7bbb3b2982d3a0711ba1b55f64dfb
675,597
import os def is_linux(): """ Parses unix name output to check if running on GNU/Linux. Returns True if running on Linux, returns False otherwise. """ if os.uname()[0] == "Linux": return True return False
b0acc5820d5d7b86dd59b41c8b8114a8b3f74be0
675,598
def bin2hex(binbytes): """ Converts a binary string to a string of space-separated hexadecimal bytes. """ return ' '.join('%02x' % ord(c) for c in binbytes)
35bc13518b946db00192026dba2705626d4f06f1
675,599
import numpy def trouver_zero_fonction_croissante(valeur_1, valeur_2, fonction_a_annuler, precision=1e-6): """recherche le zero de la fonction dans l'intervalle [valeur_1, valeur_2] fonction est supposee etre CROISSANTE dans l'intervalle [valeur_1, valeur_2] """ milieu = (valeur_1 + valeur_2) / 2...
f721c3aa87006baf49bddd48d7a308cde653508d
675,600
import os def matches_extension(path, extension): """ Returns True if path has the given extension, or if the last path component matches the extension. >>> matches_extension("./www/profile.php", "php") True >>> matches_extension("./scripts/menu.js", "html") False >>> matches_extension("./LICENSE", "...
9ff3e5d3ed4ad18354b3798f4104b7fa8c722e22
675,601
def palabra_es_valida(palabra, lista): """Devuelve True si la palabra se encuentra dentro de la lista recibida""" # ... COMPLETAR! return True
f444c44bfda23823f62fde946f76a3260f0946d5
675,602
import torch def calc_f1_micro(predictions, labels): """ Calculate f1 micro. Args: predictions: tensor with predictions labels: tensor with original labels Returns: f1 score """ preds = predictions.max(1)[1].type_as(labels) true_positive = torch.eq(labels, preds)....
d99778a3b3ee96ad3605e9a3aa947d9ca8af6b37
675,603
def fileParse_Bin(filePath): """ fileParse_Bin Input(s): filepath: A string containing the path to a text-formatted LUT Returns: rgbValues: A 2D list of 8-bits RGB values """ # Open the file in read only & binary mode, then read 8 KiB with open(filePath, 'rb') as fid: binData = fid.read(8192) # Init t...
3c1bae9c581341246d5aad682eee079092363fed
675,604
def flatten(t): """ Helper function to make a list from a list of lists """ return [item for sublist in t for item in sublist]
3181a5f9404f8803741276648f77e50203cb581d
675,605
def get_html_header() -> str: """Helper to get a HTML header with some CSS styles for tables."" Returns: A HTML header as string. """ return """<head> <style> table { font-family: arial, sans-serif; border-collapse: colla...
fc2302ff199ef944169a4096a53f6bd48fdb06fd
675,606
import subprocess def GetCommandOutput(command): """Runs the command list, returning its output. Prints the given command (which should be a list of one or more strings), then runs it and returns its output (stdout and stderr) as a string. If the command exits with an error, raises OSError. From chromium...
7b050e8d752ec3c508b4b8fc56a72a5c433530a7
675,607
import secrets def new_pwd(char_list): """Choose length of password and return password as string.""" while True: try: length = int(input("Length of password (5-40): ")) if length < 5: print("Password too short! Please try again.") elif length > 40: ...
9b7cdf3e39f6246ffbea5942438da52908d12d59
675,608
def project_to_stack(translation, resolution, coords_p): """Convert a dictionary of project coordinates into a dictionary of stack coordinates""" return {dim: int(val - translation[dim] / resolution[dim]) for dim, val in coords_p.items()}
5d2159b1655f1d773a5a9839686f14cc6d511012
675,609
import glob def found_with_glob(value): """ Check if at least one file match the given glob expression. :param value: glob expression """ for _ in glob.glob(value): return True return False
38677a00e2c80981baa8d1d27ad0bec2b8df009f
675,610
def message_prettify(champion): """ Beautiful formatting text. """ message = ( f'-----------------------------------\n' f"Name: {champion.name}\n" f'-----------------------------------\n' f'Role: {champion.roles}\n' f'-----------------------------------\n' f'Core weapons:\n\n' ...
c695e77ff70f4f4070305ce6fea2ec0eee821ac0
675,611
def extract_label(element): """Extracts and appends label from filename. Assumes there's only one label per video. """ element["label"] = element["filename"].split("/")[-3] return element
afe3805198f0825b3eec5adc547b62f5e85e4a27
675,615
from pathlib import Path def response4(): """Read html sample from resp.html file. (for CasimLoggedin)""" path = Path("tests/test_tools/resp_folders.html") content = path.read_text() return content
b15603768c2cdc9f4275369b9425066e02b38ffd
675,616
import shutil def get_path_to_executable(executable): """ Get path to local executable. :param executable: Name of executable in the $PATH variable :type executable: str :return: path to executable :rtype: str """ path = shutil.which(executable) if path is None: raise ValueErro...
5a840d2dd6ade2fe3f4f26861efac0b69e3a33b9
675,619
def transactions_report(df, frequency='M'): """Create an transactions report based on a specified reporting frequency. Args: df (dataframe): Pandas dataframe of transaction items. frequency (optional, string, default 'M'): Optional frequency indicator (Y, Q, M, W, D) Returns: df (d...
fccb11b5a83612e3c69c8cb136ffeefb0c994ef7
675,620
def _direction_to_index(direction): """Map direction identifier to index. """ directions = {-1: 0, 0: slice(None), 1: 1, '<=': 0, '<=>': slice(None), '>=': 1} if direction not in directions: raise RuntimeError('Unknown direction "{:d}".'.format(direction)) return directions[direction]
1612c7107601a6166e478815b89725701f8dc3ff
675,621
import os import random def create_tsv_for_multiple_choice(input_dir, output_file, num_of_choices=5): """ Function to create a tsv file with random negative samples from corpus. For all component including unconnected ones. Last option is always the no link option. :param input_dir: directory with .tx...
54283b1b5e691070206de47e3d5518a0aeaa2e91
675,622
import re def hasNonInitialPeriod (tok): """Examples: St., I.B.M. """ # Clojure original: # #(some? (re-matches #"(\p{L}+\.)+(\p{L}+)?" %) if (re.search('^([A-Za-z]+\.)+([A-Za-z]+)?$',tok)): return True else: return False
e5218b2ad2d403eeecd3e273337553590f93b220
675,623
import requests import warnings def check_pypi_module(module_name, module_version=None, raise_on_error=False, warn_on_error=True): """ Checks that module with given name and (optionally) version exists in PyPi repository. :param module_name: name of module to look for in PyPi :param module_version: (...
f491303844d8ec138e75872be8a16cb0e399e9fc
675,624
import numpy def crop(z, x,y, xmin, xmax, ymin, ymax, all=False): """ Crops the image or 2D array, leaving only pixels inside the region you define. >>> Znew,Xnew,Ynew = crop(Z, X, Y, 0,10,-20,20) where X,Y are 1D or 2D arrays, and Z is a 2D array. :param z: 2d array :param x,y: 1d or 2d arrays. In the latter ca...
2f1437fd51398e95b41b70e70647c754b6e358c1
675,625
def to_representation(date_object, date_format): """Method for represents ISO format.""" format = None if format == "ISO": format = "%Y-%m-%dT%H:%M:%SZ" elif format == "DMY": format = "%d-%m-%Y" else: format = "%Y-%m-%d %H:%M:%S" return date_object.strftime(object)
544ec2eb0015219e532a92163c6b4d40fb2efa0d
675,626
def postprocess_chain(chain, guard_solutions): """ This function post-processes the chains generated by angrop to insert input to pass the conditions on each gadget. It takes two arguments: chain - the ropchain returned by angrop guard_solutions - the required inputs to satisfy the gadget c...
a7977ce25ba61e977718f3b9d88328aaa70e2827
675,627
def get_json_key_value(json_object, keys_list): """ Get the value from json pointing to string of keys input: [k1,k2] """ # This will be the key key = keys_list[0] # We check for types, if its a dict or list if isinstance(json_object, list): key = int(key) # Check for index out of r...
562b1a0b07e19589960b4838ba68b57211f512cf
675,628
def _parse_top_section(line): """ Returns a top-level section name ("PATH", "GEM", "PLATFORMS", "DEPENDENCIES", etc.), or `None` if the line is empty or contains leading space. """ if line == "" or line[0].isspace(): return None return line
ac202bc8ccbcdf3dd392b442b11ed3601cca9149
675,629
def _rolling_stack_operation(stack, function, keep_first=False, *args, **kwargs): """ Perform an rolling operation for all images of an image stack. :math:`I_{new} = func(I_{n-1}, I_n)` This is just a wrapper for a function which can perform a procedure for two subsequent images for a whole stack....
c99f9186263699866dde961652e02a2357af90b5
675,630
def remove_line_break_escapes(value): """ removes line break escapes from given value. it replaces `\\n` with `\n` to enable line breaks. :param str value: value to remove line break escapes from it. :rtype: str """ return value.replace('\\n', '\n')
f9423411a771a7e7561e165e8a13f125e3aee918
675,631
def mirror_layer(layer: tuple, direction: str) -> tuple: """Change rotation property of given layer if necessary""" _, _, rotation, distribution = layer # mirrored layer of normal distribution identical with original layer if distribution == "Normal": return layer if direction == "horizon...
2c7c54a6ec49bdaac0540faf1a00dbd63281a4ed
675,632
def get_validation_digit(number): """ Calculates the validation digit for the given number. """ sum = 0 dvs = [4, 3, 6, 7, 8, 9, 2] number = str(number) for i in range(0, len(number)): sum = (int(number[-1 - i]) * dvs[i] + sum) % 10 return (10 - sum) % 10
4c664267319e739ddb1dd7ba10d409462e8e3ed7
675,633
def _get_id(name): """Gets id from a condensed name which is formatted like: name/id.""" return name.split("/")[-1]
6489f23b5a5a25ee73ed14af2f18ae141fd748f8
675,634
def each_cons(array, limit): """Given array, returns it all sets of each cons elements""" return [array[i:i+limit] for i in range(len(array)-limit+1)]
9d7777b4d1ad2584fa7ad07df20496170908f4be
675,635
def init_tokens( tokenlist ): """ Returns elments of the list that are initializers """ def cond( elem ): return elem[1].type == 'EQUAL' return filter( cond, tokenlist)
4b54701c2aa6fea3d4ffb8c76bafa473affd071e
675,636
def extract_endpoints(data): """ Turn the dictionary of endpoints from the config file into a list of all endpoints. """ endpoints = [] for nodetype in data: for interval in data[nodetype]: for api in data[nodetype][interval]: endpoints += ( da...
350d93864de0a1ca26732b605874cdd9a3af3a48
675,637
def jk(klajsf): """ """ return None
533c20696b38afdb388e28bdce4b69b2db63499d
675,639
import argparse def parse_command_line_arguments(): """ Defines and parses command-line arguments (both positional and optional) :return: parsed object to be used to extract arguments values """ parser = argparse.ArgumentParser() # Positional args parser.add_argument('data_directory', ac...
914d44a58bdfda601be9f4cb2a519b6098981ae2
675,640
import json import requests def getListOfPositions(position_name : str): """ Retrives all Microsoft publicily listed positions with name `position_name` by sending POST to Microsoft career endpoint. Args: position_name (str): Name of the position Returns: ...
66b753167e6bcd252a77df3e25743d0eae6e2796
675,641
import math def str_to_float(sval): """ str_to_float() - convert string to floating point handling NA Parameters: sval - string to convert Return value: floating point value or "NA" """ val = sval if val != "NA": if val == '': val = "NA" else: ...
ffd1cc8468c068c710d37f4d9caa379c5e65753e
675,642
import io import zipfile def strings_to_zipped_file(strings_dict: dict) -> io.BytesIO: """name: content""" zipped_file = io.BytesIO() with zipfile.ZipFile(zipped_file, 'w') as f: for name, content in strings_dict.items(): f.writestr(name, content) zipped_file.seek(0) return zipped_file
d474dd706eb69a9645d9f784ea7c6eacb8b37370
675,643
import mimetypes import os def IsTextfile(filename): """Check if a file is a text file.""" if os.path.isfile(filename): mtype = mimetypes.guess_type(filename) if mtype != None and "text" in str(mtype[0]): return True return False
7c8047b4c4b72f5d7f2383aa841e3319da923934
675,644
def test_savestate(neuron_instance): """Test rxd SaveState Ensures restoring to the right point and getting the right result later. Note: getting the right result later was a problem in a prior version of NEURON, so the continuation test is important. The issue was that somehow restoring from a Sa...
9ed97f29c8d6c97bcb813803b3022bc0783884c2
675,645
def ask(message, options, allow_empty=False, help=None) -> str: """Ask user for input Parameters ---------- message : str Message. options : dict ``{command: description}`` mapping. allow_empty : bool Allow empty string as command. help : str If provided, add...
20c592b5b46dc1ee082053d5d898e1543fb9bb5e
675,646
import random def random_payload_shuffled_bytes(random_payload_bytes): """ Fixture that yields the randomly generated payload bytes but shuffled in a random order. """ return random.sample(random_payload_bytes, len(random_payload_bytes))
9cf54600d4e6c6dd6dd888daad63de36b6b5b23d
675,647
import argparse from pathlib import Path def io_parser(): """Parser shared by all commands to get input/output files.""" parser = argparse.ArgumentParser(add_help=False) file_help = """File to read from. Can be specified several times for several files. Be careful that bash will expand glob patterns *...
03d7e7ef7135a30bbde59149b219335dfa2ec835
675,648
def load_data(localFileName): """ expects: HEADER section before DATA section, all lines start in column 0 DATA section element all have space in column 0 <space>1 23.45 67.89 last line of file is: " EOF" """ with open(localFileName, mode='r') as infile: content ...
4baeaddc6c70c148d16f8d7f4711a96bc9e5ec81
675,649
from typing import Optional def greeting(name: Optional[str] = None) -> str: """Says hello given an optional name. NOTE: `Optional` is just a convenience. It's equivalent to `Union[str, None]`. """ if name: return f"Hello {name}!" else: return "Hello you!"
c325659aedaf7b9254dca97ddb51ee96bdaa19ac
675,650
def ip_get_dn(d): """ return the dictionary with items ``((v1,v2), i)``, where ``(v1, v2)`` is an edge, and ``i`` the index given to the vertex """ c = 0 dn = {} for k, v in d.items(): for k2 in v: a = [k, k2] a.sort() t = tuple(a) if t...
9931b4c1f8db645ec791207d3d574b783c9d443e
675,651
def unicommon_completer(unicommon, stoichiometry_input, diff_chains): """ Small function that 'completes' the eunicommons dictionary with the stoichiometry provided """ unicommon_keys = set([ch.id for ch in unicommon.keys()]) for stoich_input_key in list(stoichiometry_input.keys()): if stoich_inp...
e1de8e94875927eb3b75a93d1325b41b2433393b
675,652
import math def ecliptic_longitude_radians(mnlong, mnanomaly): """Returns ecliptic longitude radians from mean longitude and anomaly correction.""" return math.radians((mnlong + 1.915 * math.sin(mnanomaly) + 0.020 * math.sin(2 * mnanomaly)) % 360)
8c2075fb071676a00fa0eeec871d2eddc805b02c
675,653
def buff_internal_eval(params): """Builds and evaluates BUFF internal energy of a model in parallelization Parameters ---------- params: list Tuple containing the specification to be built, the sequence and the parameters for model building. Returns ------- model.bude_score...
0a61d7175812862392964f1ae338e75b0b3f3cc9
675,654
from typing import Dict from typing import Any def countdown( element: Dict[str, Any], all_data: Dict[str, Dict[int, Dict[str, Any]]] ) -> Dict[str, Any]: """ Countdown slide. Returns the full_data of the countdown element. element = { name: 'core/countdown', id: 5, # Countdown ...
e43869e55bd68273a3324c036deef4f352275589
675,655
import torch def complex_matrix_inverse(mat_r, mat_i, reg=1e-3): """ M = A + iB Re{M^-1} = (A + B(A^-1)B)^-1 Im{M^-1} = -Re{M^-1} * B(A^-1) """ try: dtype = mat_r.dtype ## --------------------------------------- ## mat_r, mat_i = mat_r.double(), mat_i.double() ## ------------------------...
dc7da15e3a76128682d415d0e7c41d0aa80115dc
675,656
import numpy def _check_range_params_densfunc(params,type): """Check that the current parameters are in a reasonable range (prior)""" # Second parameter is always a scale height, which we don't allow neg. if params[1] < 0.: return False if type.lower() == 'exp': if numpy.fabs(params[0]) > 2.: ...
83821aaedf07fb436a99d445bfbc39189301d6fe
675,657
def is_csv_accepted(request): """ Returns if csv is accepted or not :return: True if csv is accepted, False otherwise """ return request.args.get('format') == "csv"
e02e9f0de5e84f6e163d5d6d161352740e418daa
675,658
def vap_from_sh(sh, p, roundit=True): """ This function calculates a vapour pressure scalar or array from a scalar or array of specific humidity and pressure and returns it. It requires a sea (station actually but sea level ok for marine data) level pressure value. This can be a scalar or an array, ...
8f5e7fca48e5180d0dd42f2ae35318b86a61163a
675,659
def hello(): """Just a test endpoint to make sure server is running""" return "Hey there!\n"
c1141449ecb2a87209604705b350c45daeefe626
675,660
def can_copy(user, plan): """ Can a user copy a plan? In order to copy a plan, the user must be the owner, or a staff member to copy a plan they own. Any registered user can copy a template. Parameters: user -- A User plan -- A Plan Returns: True if the User has p...
25c6d5589c09b74257905ab8494c728c3ffabdd3
675,662
def sample_to_name(sample_id, eliminate_parens = True, eliminate_hcl = False): """ Returns processed version of sample id. Note:The best way to match is to try to match annotations in lowercase. """ if 'ethylisothiourea sulfate' in sample_id: return 'Methylisothiourea sulfate' # Elimi...
055f04581a26db79acbfaf61e81498004588ed22
675,663
def countsToIlluminance(signal_counts, total_throughput, camera_background_counts=385, camera_quantum_efficency=0.6, numerical_aperture=0.25, magnification=10, pixel_size=6.5e-6): """Converts pixel counts to illuminance.""" # Number of photons collected photon...
06a51d47f97117e7d570d35a7dd8cdb324d4110c
675,664
def PM_da_control_3d(PM_ds_control_3d): """To MPI Perfect-model-framework corresponding control maps xr.DataArray of subselected North Atlantic.""" return PM_ds_control_3d["tos"]
77afe1982d0e68faf3cce68136fe4c772d04321d
675,666
def getParentLayer(layer): """ Get the parent layer \nin: MixinInterface.LayerProperties \nout: MixinInterface.LayerProperties """ return layer.getParent()
973c4d62a3c9899e8de435328c80a8422d35c2d1
675,667
def fib(cv=1, lv=0): """The fibonacci sequence, this incrementer uses the last value""" if cv == None: cv = 1 if lv == None: lv = 0 return cv + lv
379e18d2cc58a77d6d406af3280681c00c4a1b52
675,668
import pickle def load_classifcation_metrics_pkl(classification_pkl): """Load a classificationMetrics pickle file""" with open(classification_pkl, 'rb') as fh: cm_h = pickle.load(fh) return cm_h
29bf0616608daf0f9cdd5800e94f91018664b585
675,669
def read_file(): """Opens Project Euer Name file. Reads names, sorts and converts str into a list object""" a = open('names.txt', 'r') data = a.read() names = data.split(",") a.close() names.sort() return names
5d206295651d0a631a14aa2eac3191d5589781d0
675,670