content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def eV(E): """ Returns photon energy in eV if specified in eV or KeV. Assumes that any value that is less than 100 is in KeV. Parameters ---------- E : float The input energy to convert to eV Returns ------- E : float Energy converted to eV from KeV """ ...
bb1811163c223670822e28ac7be6f34bfcbae837
638,898
def create_vocabulary_list(data_set): """ 创建词库 @ param data_set: 数据集 @ return vocabulary_set: 词库 """ vocabulary_set = set([]) for document in data_set: # 求并集 vocabulary_set = vocabulary_set | set(document) return list(vocabulary_set)
0900428a488df95efe7a4b5bc341017056775111
638,900
from typing import List def unparse(exp): """Convert a Python object back into a lisp parsable string. This will for example convert [1,2,3] into '(1,2,3)'. """ if isinstance(exp, List): return '(' + ' '.join(map(unparse, exp)) + ')' else: return str(exp)
8a2502fb9e3f4f243ccb6f15dfb37988097c4db2
638,901
def get_page(self): """ A function which will be monkeypatched onto the request to get the current integer representing the current page. """ try: if self.POST: p = self.POST['page'] else: p = self.GET['page'] if p == 'last': return 'last' ...
dee1ebd3a08ff59a1be89ca959ef141ddb155355
638,902
def sort_paper_list(paper_list): """Sort the paper list by paper year.""" keyfunc = lambda paper: paper['year'] sorted_paper_list = sorted(paper_list, key=keyfunc) return sorted_paper_list
f8b4e15d75bffda00207fe70abd9e080cf1758c4
638,903
import os import requests import json def handle_newfile(data, context): """Background Cloud Function to be triggered by Cloud Storage. This generic function calls the Cloud Run URL endpoint. Args: data (dict): The Cloud Functions event payload. context (google.cloud.functions.Context)...
d0a36bb95ab8510440bf8d223388945369fd25af
638,905
import os def get_base_addr(pid): """ get base : usage :PID Number """ pid = int(pid) vmmap = os.popen("pmap %d | awk '{print $1}'"%(pid)).read() ba = vmmap.split("\n")[1] return int(ba,16)
e242250f3eb48403db04759f28c30d03d6a87ad1
638,906
def replaceStringBlocks(str, startId, endId, newContent): """ Replaces all string sections in blocks given by startId and endId tags by newContent. :param str str: Text content to be updated. :param str startId: Start identifier of the block to be replaced. :param str endId: End identifier of the block...
a1f7237d6eb0b135e46dd853b8371780dd33e5e4
638,907
import subprocess def get_native_windows_path(wsl_path): """Returns the native Windows path given the WSL path""" return str( subprocess.run( ["wslpath", "-a", "-w", wsl_path], stdout=subprocess.PIPE ).stdout, "utf-8", ).strip()
c282fe60a1e90ff6c1e8d3c1de3526286689deed
638,908
def sliceFromString(sliceString): """Convert a text string into a valid slice object which can be used as indices for a list or array. >>> sliceFromString("0:10") slice(0,10,None) >>> sliceFromString("0::3") slice(0,None,3) >>> sliceFromString("-8:") slice(-8,None,None) """ slic...
1b8576647e3f0c9ba9355a3b3329f7ee971f76ed
638,909
def correct_answer_for_all(context, question): """ processes the correct answer based on a given question object if the answer is incorrect, informs the user """ answers = question.get_answers() incorrect_list = context.get('incorrect_questions', []) if question.id in incorrect_list: ...
a4c60f23ec72a5f7583d8d5b27ed98f50adca6e0
638,910
import numpy def LUFactors(A): """ usage: [L,U] = LUFactors(A) Row-oriented naive LU factorization; constructs the factorization A = LU This function checks that A is square, and attempts to catch the case where A is singular. Inputs: A - square n-by-n matrix Outputs: ...
ab3c9b23adae096388ab4756057d82929164167d
638,911
def get_individual_decision_makers(decision_maker_list): """Return list of individual decision makers.""" individual_dms = [] for dm in decision_maker_list: individual_dms += dm.decision_makers return individual_dms
6b99c42955725f4292219f7f7a01e7530fece845
638,912
from sys import getsizeof def calculate_memory_for_aggregated_attractor(aggregated_attractor, aggregated_attractor_key): """ Estimate memory taken by aggregated attractor. :param aggregated_attractor: aggregated attractor :param aggregated_attractor_key: attractor key :return: memory size in byte...
2b5e819ca8b9211c3d41a3cfe7072c586aad9664
638,913
def _ByStartAndCreationTime(job): """Sort key that sorts jobs by start time, newest and unstarted first. All unstarted jobs will be first and sorted by their creation timestamp, all started jobs will be second and sorted by their start time. Args: job: googlecloudsdk.api_lib.run.job.Job Returns: Th...
f5c2d0c83e24242c75e2077d7c1179a6d329c9b9
638,914
def gen_approx_table (f, nentries, min_x, max_x): """return a list of nentries containing tuples of the form: (m, c, abs_error). min_x and max_x specify the domain of the table. """ r = [] incx = float (max_x - min_x) / nentries for i in range (nentries): a = (i * incx) + min_x ...
70830655a59a0f60c032c2fb07755b3da768930e
638,915
import argparse def argparse_xqimport(message): """ Usage: /xqimport [OPTION] XQ_PORTFOLIO_CODE QUERY_CODE Create a new portfolio according to an existing Xueqiu portfolio and set a QUERY_CODE to use other functions of this bot. Options: -n <preferred_name> set a different name from th...
2b574a921f105654b2d0a923ddbfa37470243bd9
638,916
import math def time_to_hhmmssmmm(time_value, decimal_separator="."): """ Format the given time value into a ``HH:MM:SS.mmm`` string. Examples: :: 12 => 00:00:12.000 12.345 => 00:00:12.345 12.345432 => 00:00:12.345 12.345678 => 00:00:12.346 83 => ...
844313561b6c307e24257d0e8fcc3a92945affb2
638,917
def _net_working_capital(column): """ Uses balance sheet to net working capital """ current_assets = column["Total current assets"] current_liabilities = column["Total current liabilities"] return current_assets - current_liabilities
6fe420c3c26c130775ae01c77ebc6ec69a76d182
638,918
import os def get_abs_path_to_convert_exe(): """ Get from the PATH variable the abs path of the 'convert.exe' file in the ImageMagick installation folder. Return the abs path if found, return False if not. """ listPATH = os.environ['PATH'].split(';') for path in listPATH: if 'ImageMagick'...
2b889e51d7510225c86a8e88e9be346068e9f7a8
638,919
def extend_config(args, model_data_location, stage_config): """ Extend the stage configuration with additional parameters and tags based. """ # Verify that config has parameters and tags sections if not "Parameters" in stage_config or not "StageName" in stage_config["Parameters"]: raise Exce...
95f99e1559f3ed0556900c3b4bc7d0910323a043
638,920
import time import subprocess import os def target_compr_test(command, fname_in, fname_out): """Return compression ratio and time-to-compress using a given compression algorithm Parameters ---------- command : string The command for executing the compression algorithm fname_in : strin...
484c48dcd8b244a2caf38c91bf24266bd48af8bc
638,921
def vwrite(self, par1="", par2="", par3="", par4="", par5="", par6="", par7="", par8="", par9="", par10="", par11="", par12="", par13="", par14="", par15="", par16="", par17="", par18="", par19="", **kwargs): """Writes data to a file in a formatted sequence. APDL Command: *VWRI...
1f913bc04ac764c95f76464b5a5d6fc68d7c3276
638,923
def wait_4_ticks_callback(request, tick_counter): """Parametrized fixture which returns the two possible callback methods that can be passed to ``waitUntil``: predicate and assertion. """ if request.param == 'predicate': return lambda: tick_counter.ticks >= 4 else: def check_ticks():...
47301949627e39ddb2e6fa7a05bda7ffd4178f87
638,924
import json def load_vocab(vocab_path): """ Load word -> index and index -> word mappings :param vocab_path: where the word-index map is saved :return: word2idx, idx2word """ with open(vocab_path, 'r') as f: data = json.loads(f.read()) word2idx = data idx2word = dict([(v, k) f...
b57002706bd36ad41b5085b12dbde8cf07338ffd
638,925
import os def is_file(target: str) -> bool: """Check target is file.""" if not isinstance(target, str): return False if not os.path.isfile(target): return False return True
d11cdfca2cdc62ceb78960ef47b31e615f2aa2a9
638,926
import hashlib def get_file_md5(fname): """ Calculate Md5 for downloaded file """ m = hashlib.md5() with open(fname,'rb') as fobj: while True: data = fobj.read(4096) if not data: break m.update(data) return m.hexdigest()
d6b97630ca22e97cdfc76023c4d69f93370ba30b
638,927
from itertools import islice def merge_contour_lists(*args): """Merges two or more dictionaries as given by contours_around_labels into a single dictionary.""" if len(args) == 0: return {} d = args[0].copy() for a in islice(args, 1, None): for k,v in a.iteritems(): d.setdefault(k, []).extend(v...
6692e7bcdf68b11078ff80690c313b3bbea43ccd
638,928
def get_data_metdata_from_revision_record(revision_record): """ Retrieves the data block from revision Revision Record Parameters: revision_record (string): The ion representation of Revision record from QLDB Streams """ revision_data = None revision_metadata = None if ("payload" in...
b32b69e7edcb1a18eb2cba414b1d1a39591a0eb4
638,929
def get_config(local_config): """parse paste config""" config = {} allowed_methods = local_config.get('allowed_methods', None) if allowed_methods: config['allowed_methods'] = [m.upper() for m in allowed_methods.split()] strip_script_name = local_config.get('strip_script_name', 'true') if...
be61e6fcc22ec36f4009c2583aeed6c4507b9314
638,930
def get_enzyme_reactions(eid, db): """ For a given ec number return associated reaction ids :param eid: enzyme id format "EC-x.x.x.x" :param db: database dict :return: """ erids = [] if eid[:3] != "EC-": eid = "EC-{}".format(eid) for rid, react in db['reactions'].items(): ...
cc1dd189b57ecd8ec6572c4ddeb4cf1dabd0a33f
638,931
def computeRamp(f): """ The ramp function is defined as r(x) = f if f(x)>=0 0 if f(x)<0 which is equal to max(x, 0) """ return (f+abs(f))/2
967ac9d0dc130540a82de9c97fed07114cd2aebd
638,932
def SumTotals(dictTotal): """ Summing values in a dictionary. Parameters ---------- dictTotal : TYPE DESCRIPTION. Returns ------- TYPE DESCRIPTION. """ totalVal = 0.0 for keyVal in dictTotal.keys(): for keyVal2 in dictTotal[keyVal].keys(): ...
eb80d8c24693e2a9c378389fda26a263e2d59640
638,933
def mask_spec(spec, spec_thresh=0.9, offset=1e-10): """ mask threshold a spectrogram to be above some % of the maximum power """ mask = spec >= (spec.max(axis=0, keepdims=1) * spec_thresh + offset) return spec * mask
fc2b0524df68b9e6f960ee416afdd1ac528969bc
638,934
def exception_handler(error): """Return JSON errors from Marshmallow validators""" return {"errors": error.messages}, 400
7d5f11e8ebf2fbb171134f986f5380fe3d120383
638,935
def _check_pandas_index_arguments(index, valid): """Check pandas index arguments.""" if index is None: return if isinstance(index, str): index = [index] if not isinstance(index, list): raise TypeError('index must be `None` or a string or list of strings,' ...
466e4ccd7c76cca15850850d2232769601de567c
638,936
def init(client, **kwargs): """ :param client: :param kwargs: :return: """ global g_client g_client = client return True
f6887bceabbc147363ee2e91f1c122cbaa170404
638,937
def get_mat_info(struct): """ Get some basic information of the structure, e.g. name, configuration Parameters ---------- struct: pymatgen.structure Returns ------- name: string The name of the structure configuration: list The configuration of t...
4deb66b551be31f2aaf412272f4250e330ff349b
638,938
def multiply(*args): """ :param args: This represents the group of ints that are to be multiplied :return: This returns the total product of all numbers that were multiplied """ total = 1 for arg in args: if type(arg) is int: total *= arg return total
821a12546712034f73d5a35c1b0acd98aa25f8ba
638,939
def collect(*args): """Collect arguments as a tuple :rtype: tuple :param args: tuple of arguments :return: args """ return args
394c9879f7bd7a3687131f658d2aaf842f94189c
638,940
def collect_filterstats_from_log(fp): """Collect statistics on fogpy filters from logfiles. From the content of logfiles, collect statistics on how many pixels have been removed from the various logfiles. Args: fp (file): Stream with log. NB: Will be consumed! """ D = {} while (li...
32bf0c59c52873c425dc13a6dd4ee28818508180
638,941
import os import json def parse_config_file(fname) -> dict: """ Args: fname (_type_): _description_ Returns: dict: _description_ """ with open(os.path.abspath(fname), 'r') as fp: data = json.load(fp) return data
8632ab2c4241c0750e4b1e9b29ccbd1bd7d7afb2
638,942
def _strip_extra(elements): """Remove the "extra == ..." operands from the list. This is not a comprehensive implementation, but relies on an important characteristic of metadata generation: The "extra == ..." operand is always associated with an "and" operator. This means that we can simply remove the...
cf9bf307e722aa5cb2be9f19d698828732d28cfd
638,943
def filtersubset(linking, el2kbid, gold_els): """ remove from linking and rom el2kbid all mentions that are not in gold_els """ newlinking = dict() new_el2kbid = dict() for kbid in linking.keys(): mentions = linking[kbid] for m in mentions: if m in gold_els: ...
8ccbfd4cbb775226191407a08c62915573649eb2
638,944
def remove_html_markup(inp): """ Remove html and xml tags from text. Preserves HTML entities like &amp; :param inp: (str) :return: string with HTML and XML markup removed. """ tag = False quote = False out = "" for char in inp: if char == '<' and not quote: tag ...
db5e96d014538abc5f175605f95ff31ce38825da
638,947
def _get_frequency_of_segment_in_list(seg, seg_list): """ Counts the frequency of a given segment or token in a list of segments/tokens. """ return seg_list.count(seg)
022dbe711da96a60323df0637d70b4ac34f47bc8
638,948
import re def match_device(device): """Matches device name and returns prefix, suffix""" match = re.match("(^/dev/x{0,1}[a-z]{0,1}d{0,1})([a-z]+)[0-9]*$", device) if not match: return None return match.groups()
bebde5e4a18f6112ed947e79f44da27c36c6cfab
638,949
def assure_tuple_or_list(obj): """Given an object, wrap into a tuple if not list or tuple """ if isinstance(obj, list) or isinstance(obj, tuple): return obj return (obj,)
2d5c3e5301d9e98b749faea508d8b3cc2804ca7d
638,950
def levenshteinDistance(s1, s2): """Return the edit distance between two strings""" if len(s1) > len(s2): s1, s2 = s2, s1 distances = range(len(s1) + 1) for i2, c2 in enumerate(s2): distances_ = [i2+1] for i1, c1 in enumerate(s1): if c1 == c2: distan...
d646d5db5bc57cec19052ef431263c3be3ca7347
638,951
def LoadData(data, multiline=False, source='<data>'): """Turn key=value content into a dict Note: If you're designing a new data store, please use json rather than this format. This func is designed to work with legacy/external files where json isn't an option. Only UTF-8 content is supported currently. ...
e443815f095fea639f51f5023e06a8a383324acd
638,952
import torch def collate_fn(data): """ Creates a mini-batch, overriding default_collate function in order to provide batches with input sorted by length. """ # sort such that input line lengths are in decreasing order # requirement for using torch.nn.utils.rnn.pack_packed_sequence data.sor...
7ba7ab5dd2b72ea7fd545d68ab484366ab72a046
638,953
def display_firstname(): """ 001 Ask for the user's first name and display the output message. """ firstname = input("Enter your firstname: ") return f"Hello {firstname.title()}"
528a7f5fdb589fa72d2cd06d74bffa6e2a0fabdb
638,954
def _exp_warn_msg(cls): """Generate a warning message experimental features""" pfx = cls if isinstance(cls, type): pfx = cls.__name__ msg = ('%s is experimental -- it may be removed in the future and ' 'is not guaranteed to maintain backward compatibility') % pfx return msg
e686537e12adb3de487b1ff898ec7de1342408cc
638,955
def remove_lines_from_string(s, remove_num): """ Remove lines from string and filter the output to get only the source code written :param s: :param remove_num: :return: """ str = s.splitlines() filtered_list = list(filter(lambda x: "@@" not in x, str[remove_num:])) remove_empty ...
5b3c7290909162bce670a533a8f3924a9af5f3e1
638,956
def prepare_chronotrack_result_json(text): """ :param text: string from /load-model that contains embedded json - assumed the callback function is an empty string :return: the embedded json (str) """ return text.lstrip("(").rstrip(");")
e085e87f6ccd2063012be6b571343a6a7221e120
638,957
import os import glob def find_app_yamls(app_dir): """Searches for app.yaml and module-*.yaml in app_dir or its subdirs. Recognizes Python and Go GAE apps. Returns: List of abs path to module yamls. Raises: ValueError if not a valid GAE app. """ # Look in the root first. It's how python apps an...
cd19db025800ecd19554657fdb5ebb0cb0b94468
638,958
import configparser def parse_configfile(filename: str) -> configparser.ConfigParser: """Parse the config file.""" config = configparser.ConfigParser() config.read(filename) return config
a0dd9d50e9c5778c3f4fbe3f03304eb9f2fa7da2
638,959
def convert(value, type): """Convert a value of type 'a' to the given type""" return value
7cbb3220115bbd5edebaff49504a055d207f746a
638,960
def extract_oversampled(a, xf, yf, Qpx, N): """ Extract the (xf-th,yf-th) w-kernel from the oversampled parent Offsets are suitable for correcting of fractional coordinates, e.g. an offset of (xf,yf) results in the kernel for an (-xf,-yf) sub-grid offset. We do not want to make assumptions abo...
308df4788c0f5515e06e63466915e14717e6bade
638,961
import json def load_config(): """ This Is to load the configs for the bot so people can customize it """ with open("creds.json", "r") as cf: return json.load(cf)
98f0885c360bdefd5f74c432fffb84039bb177fe
638,963
def columns_contain_correct_dtype(d_f): """This function checks if the dataframe has the correct column datatypes""" if (d_f['JURISDICTION NAME'].dtypes == 'int64' and d_f['PERCENT FEMALE'].dtypes == 'float64' and d_f['PERCENT MALE'].dtypes == 'float64'): return True return False
201231ff9960d8d5927a9b6ebc97cbe5b1f7ba8e
638,964
def make_image_carousel(columns): """ Image Carousel: reference - https://developers.worksmobile.com/jp/document/100500809?lang=en Request URL https://apis.worksmobile.com/r/{API ID}/message/v1/bot/{botNo}/message/push POST (Content-Type: application / json; charset = UTF-8) ...
037a72114e7200a522afdfd8d22326c4e0dd7e55
638,966
from typing import Iterable import functools import operator def product(iterable: Iterable): """ Multiplies all elements of iterable and returns result ATTRIBUTION: code provided by Raymond Hettinger on SO https://stackoverflow.com/questions/595374/whats-the-function-like-sum-but-for-multiplication-...
9662680401fb63c96cef271959964039d08aa20c
638,967
def date_range_str(daterange, fmt=None): """String with a single date is second is None, or range""" if fmt is None: fmt = "%m/%d/%Y" if daterange[1] is None: return daterange[0].strftime(fmt) else: return daterange[0].strftime(fmt) + " to " + daterange[1].strftime(fmt)
f3900a0845bd924456bdbcda184a7eae9c74b6a9
638,968
def cipher_ca(text, d1, d2): """Caesar or Atbash encoding/decoding. Supply both dictionaries via d1 and d2""" result = '' for c in text: if c not in d1: result += c else: result += d2[d1.index(c)] return result
f0e3c08d51d08e4299c3ee57b27d42ebb3032fa1
638,969
def parse_user_data(user): """Parse the user's information into a dictionary.""" data = { "id": user.id, "email": user.email, "username": user.username, "active": user.active, "confirmed": user.confirmed_at is not None, "preferences": dict(user.preferences or {}),...
0c2a2c97304f5db21ad313ab8d74948da380c6ce
638,970
def djoin(*tup): """ Convenience method to join strings with dots :rtype: str """ if len(tup) == 1 and isinstance(tup[0], list): return '.'.join(tup[0]) return '.'.join(tup)
0c209cd026d15b2126918b0c280e5dcdbb143d9f
638,971
def achromat(power, Va, Vb): """Compute lens powers for a thin doublet achromat, given their V-numbers.""" power_a = (Va/(Va - Vb))*power power_b = (Vb/(Vb - Va))*power return power_a, power_b
78712dfbc63f08a44866a87d432ca9b82f01f069
638,972
def _make_env(environment): """Change from Docker environment to Kubernetes env Args: environment (dict): Docker-style environment data Returns: list: Kubernetes-style env data """ env = [] for key, value in environment.items(): env.append({"name": key, "value": value})...
ba3b149dbf27ecabb6287a7d067a0f242744cb7d
638,973
import os def get_filenames_in_folder(folder_name, ext_name=True, hidden_file=False, attach_folder_name=True): """ 获取指定文件夹下的所有文件 :param folder_name: 指定文件夹 :param ext_name: 是否保留拓展文件名 :param hidden_file: 是否列出隐藏文件 :param attach_folder_name: 是否显示文件夹路径 :return: """ filenames = [] if...
b193ba342c9e33c083cda03b899cb1852f69e51b
638,974
def unchecked_return_two() -> int: """ pre: True post: __return__ > 0 post: __return__ != 3 """ return 2
8deed1bfb888a81355ed69d6db9e4aa0dcfadbb6
638,975
def find_proxy(ip,port,proxies): """ 根据ip,端口查找符合条件的代理 :param ip: 查询ip :param port: 查询端口 :param proxies: 查找的代理IP列表,类型[{'ip':<ip>,'port':<port>,...},...] :return:符合条件的代理数据 dict类型 {'ip':<ip>,'port':<port>,...} """ for i in proxies: if isinstance(i,dict): if i['ip']==ip a...
3c6ed7b19c9d9777843b5f9e892874a1701467eb
638,976
def _get_sv_callers(items): """ return a sorted list of all of the structural variant callers run """ callers = [] for data in items: for sv in data.get("sv", []): callers.append(sv["variantcaller"]) return list(set([x for x in callers if x != "sv-ensemble"])).sort()
b599880f4e1bb106dc68e7de835eedbe0995fbb6
638,977
import json def parse_acl_v2(data): """ Parses a version-2 Swift ACL string and returns a dict of ACL info. :param data: string containing the ACL data in JSON format :returns: A dict (possibly empty) containing ACL info, e.g.: {"groups": [...], "referrers": [...]} :returns: None if...
74aaf6e21c309eb52ccaba4ba0386d92f0395aa1
638,978
import numpy as np def ProcessOutput(filename): """Reads an output file, and returns a processed numpy array. Args: filename: (str) file to process. Returns: A numpy structured array. """ data = np.genfromtxt(filename, delimiter=',', skip_header=1) result = np.array(np.zeros(len(data)), ...
489e0fe1d69e10b409923bb1a7fceb10c9603980
638,979
import os def make_out_dir(dst_dirpath): """Функия берет путь и создаёт эту папку (если она не существует), возвращая этот же путь в dst_dirpath""" if not os.path.exists(dst_dirpath): os.makedirs(dst_dirpath) return dst_dirpath
5132e1b0d96035ef87dbe888f6713332f38d9f81
638,980
def check_numeric_indicator(var: str, index: str, messages: list) -> bool: """Checks that variable's numeric indicator is "0", "1" or "2". Parameters ---------- var : str Metadata variable in criteria. index : str Numeric indicator. messages : list Message to print i...
9bb5e742a9459a6ff5d93d9d21d92be2ace00cff
638,981
def defang_text(text): """ Function to normalize quoted data to be sql compliant :param text: Text to be defang'd :return: Defang'd text """ text = text.replace("'", "''") text = text.replace('"', '""') return text
36b70de8b6af691b3d9bc2c2e7be9cf3d50a6905
638,982
def get_process_metric(row, flag, ck_frame, metric, verbose=False): """ Returns the value for the given metric for a particular source :param row: the data frame row for the test :param flag: true if that's a production class; false if a test :param ck_frame: the frame with all the ck metrics :p...
1857be49afe06f5a3a06956378a7e551282c2ac7
638,983
def _IsLegacy(discovery_rest_url): """Returns whether the given discovery URL uses legacy discovery. Args: discovery_rest_url: a str containing a discovery URL for an API. Returns: True if the discovery URL is determined to be a legacy, otherwise False. """ if 'googleapis.com/$discovery' in discover...
53a8c8916a4298c2a6f73114c9f0354c1b863df4
638,984
def is_wind(text: str) -> bool: """Returns True if the text is likely a normal wind element""" # Ignore wind shear if text.startswith("WS"): return False # 09010KT, 09010G15KT if len(text) > 4: for ending in ("KT", "KTS", "MPS", "KMH"): if text.endswith(ending): ...
7a7d8b61e5598d9dd11d4fd10acfa19fdf569b03
638,985
def get_spec(field, query='', query_dsl=''): """Returns aggregation specs for a term of filtered events. The aggregation spec will summarize values of an attribute whose events fall under a filter. Args: field (str): this denotes the event attribute that is used for aggregation. ...
51baf7a7479913ea221c7d07d51744064f6417de
638,986
def to_string(s, encoding=None, errors='strict'): """Inverse of to_bytes""" if isinstance(s, bytes): return s.decode(encoding or 'utf-8', errors) elif not isinstance(s, str): return str(s) else: return s
51dcee8566bff723818a690d4774d95a57b036cc
638,987
def max_length(obj): """ Return the maximum length of obj or any of its sublists, if obj is a list. otherwise return 0. @param object|list obj: object to return length of @rtype: int >>> max_length(17) 0 >>> max_length([1, 2, 3, 17]) 4 >>> max_length([[1, 2, 3, 3], 4, [4, 5]]) ...
a7c2fcbb80ef6074879443f0883943634efa52b0
638,989
def get_pnc_bytes(file_in): """ read in the raw file """ pnc_file = open(file_in, "rb") bytes_in = pnc_file.read() # get the entire file pnc_file.close() print ("Found %d bytes in %s" % (len(bytes_in), file_in)) return bytes_in
424117b05e33fd33c5a59e59832812c74c6a6346
638,990
def _compute_olympic_average(scores, dropped_scores, max_dropped_scores): """Olympic average by dropping the top and bottom max_dropped_scores: If max_dropped_scores == 1, then we compute a normal olympic score. If max_dropped_scores > 1, then we drop more than one scores from the top and bottom and ave...
b3f8df256f94efc729bd11e47810206a9d75e497
638,991
def missing_round(rd_name): """Fills missing round for player with None entires. Args: rd_name (str) : tournament round number Returns: data (dict) : tournament round shot score data. data_pts (dict) : tournament round hole score data. """ hole_ids = [rd_name + "_...
c9e49f977dc4c3e07bd53f2473f53d808a0aed3d
638,992
def notes_view(notes, list_name): """ View for notes :param notes: :param list_name: :return: """ if notes: view = "*Your notes of {}*:\n\n{}" modified_notes = ["*{}.* {}".format(index + 1, value) for index, value in enumerate(notes)] return view.format(list_name, "\n...
e88651f43ac2809a3a1bb2c941c81977852d95e8
638,993
import os def cdpwd(f): """ a decorator to back to pwd """ def wrapper(*args, **kwargs): pwd = os.getcwd() result = f(*args, **kwargs) os.chdir(pwd) return result return wrapper
15dd2002d0f11d2ce01a9b2afc59e0545434dacb
638,994
import re def check_password(collection, id_, cont): """ Password checking """ # Invalid password cond_length = not 6 <= len(cont) <= 40 cond_symbols = re.findall(r'[^a-zA-Z0-9!@#$%&*-+=,./?|]~', cont) cond_letters = not re.findall(r'[a-zA-Z]', cont) cond_digits = not re.findall(r'[0-9]', co...
c384514bdcefd80d3c314c190b636fe8fff4eefd
638,995
def robot_paint(grid, painted_locations, current, instruction_list): """Makes robot paint given location on grid. Updates and returns grid, painted_locations. """ painted_locations.add(current) if instruction_list[0] == 0: grid[current[0]][current[1]] = '.' elif instruction_list[0] == 1: ...
abcbb7b6d77fb5839f4a4e080fc1b3b9a46da18a
638,997
def des_ccd_gain(bands=''): """ Sample from the single epoch ccd gain for DECam """ # Figure 2 in https://arxiv.org/pdf/1501.02802.pdf return [5.033 if b == 'Y' else 6.083 for b in bands.split(',')]
b9650072418e48886d3d021405cbddfe3fe0e697
638,998
def _GetFormatCharForStructUnpack(int_width): """Gets the sample's integer format char to use with struct.unpack. It is assumed that 1-byte width samples are unsigned, all other sizes are signed. Args: int_width: (int) width of the integer in bytes. Can be 1, 2, or 4. Returns: The format char corre...
841fbf1b05075f5171267a89919ce461c4fd7c19
638,999
def get_keys_of_max_n(dict_obj, n): """Returns the keys that maps to the top n max values in the given dict. Example: -------- >>> dict_obj = {'a':2, 'b':1, 'c':5} >>> get_keys_of_max_n(dict_obj, 2) ['a', 'c'] """ return sorted([ item[0] for item in sorted( d...
16b51090ac086a708deccf6876201857e06ef0fc
639,000
def accuracy_predicted_substation(**kwargs: dict) -> bool: """ Calculates whether the substation where the changes are predicted at corresponds to the substation with the label changes. Parameters ---------- **kwargs['Y_subchanged_idx'] : int The index of the substation where the 'true'...
6ba9e97e5c968b6d66cf18ab660dc3365521f077
639,001
def to_serializable(val): """Used by default.""" # print(type(val)) # in order for our dispatch (dispatching to different 'overloads' based on the first # argument type(s)) to work recursively we need to pass ourselves to json.dumps # as default again # another method would be to (ab)use str and...
2e4f9a3085bdfd926b7ebd4359dbab78cc88ba08
639,002
def isVariable(symbol, V=[]): """ >>> isVariable("Start") True >>> isVariable("A_123", ["Start"]) False >>> isVariable("A_123", ["Start", "A_123"]) True """ if V: return symbol in V return symbol[0].isupper()
5ac8f9297725b5da3f3d3254af5e91f34fb6b3dc
639,003
def text_if_str(to_type, text_or_primitive): """ Convert to a type, assuming that strings can be only unicode text (not a hexstr) @param to_type is a function that takes the arguments (primitive, hexstr=hexstr, text=text), eg~ to_bytes, to_text, to_hex, to_int, etc @param hexstr_or_primitive in...
8b2bb308c17c44f0168c47c2abfc9ab08edc4410
639,004
def check_format(number='1989592KJAB'): """ Description ----------- Function to check format compliance of US phone numbers, namely the length should be exactly 11 digits, and the first digit must be with 1 :param number: Input phone number as a string :return: True if valid format, false if...
b3740d51599de9278be34ad788633569f1e171f1
639,005
def delete_resource_file_only(resource, f): """ Delete the single resource file f from the resource without sending signals and without deleting related metadata element. This function is called by delete_resource_file() function as well as from pre-delete signal handler for specific resource types ...
ca6621b8fae398efde73c3719a709690329898dd
639,006