content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def requires_package(pkg, msg, error_type=ImportError): """Decorator when a function requires an optional dependency Parameters ---------- pkg : imported package object msg : string Message to show to user with error_type error_type : python error class """ def _requires_package...
64dc9a174adcea1202d24fb339edde8776bdd7b8
668,437
def get_engine_turbo(t): """ Function to get turbo or regular for engine type """ tt = t.split(" ")[-1] if "turbo" in tt: return "turbo" return "regular"
faae5a1e3005c54591366306869e9d22bd5f500c
668,438
def code_add_space(code, space_count=1, space_str=" "): # 逐行加空格 """传入字符串,逐行加入空格,符合python规范""" ls = code.split('\n') ret_code = space_line = "" for i in range(space_count): space_line += space_str for s in ls: if len(s) > 0: ret_code += (space_line + s + "\n") el...
3288e882d88083e74e2359078bea7b22acc0fb0a
668,440
import re def assert_package_is_source(package_definition): """Check if a defined package refers to a source repo.""" # basically identical to assert_valid_package_def but this regex will # also match <username>/<repository>:<branchname>[extras] charset = r"A-Za-z0-9_\.\\\-~" regex = (r"^[{}]+\/[{...
18a324dd80fb0fa3acd71d760d006edc2ba6abee
668,441
import glob import os def get_full_filepath(folder: str, base_name: str) -> str: """ This gets an absolute path to a file of an unknown extension Thank you Blender https://stackoverflow.com/questions/19824598/open-existing-file-of-unknown-extension?rq=1 :param folder: Absolute path of file :...
17f51539f93b50e3765696a4b4c1fbf5ab48d496
668,443
import time def fmtdate(timestamp): """ return the date to human readable format """ return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(timestamp)))
58284b5a3d2a29d0042f239335cc6caf72813cd8
668,444
def _getMultiElemText(parentElem, elemName, topKey, bottomKey): """ XML parsing helper function to return a 2-level :py:class:`dict` of multiple elements by a specified name, using ``topKey`` as the first key, and ``bottomKey`` as the second key. :param SubElement parentElem: the :py:class:`XML SubElem...
59b886995189e3b1a8fbf0d50e3dbb4fe6af3474
668,446
def toa_rad(swdn_toa, swup_toa, olr): """All-sky TOA downward radiative flux.""" return swdn_toa - swup_toa - olr
5ff43ca4495142340b6936a0beed60b350404edb
668,448
def is_point_in_range(p, p_min=None, p_max=None) -> bool: """Check if point lays between two other points. Args: p: tuple (x, y) p_min (optional): min border point p_max (optional): max border point Returns: True if p_max >= p >= p_min """ if p_min is None and p_max...
5c86a40a936bb5e979edc63add5cc0415ff5d444
668,449
def even(x): """ even :: Integral a => a -> Bool Returns True if the integral value is even, and False otherwise. """ return x % 2 == 0
b298173d03658bbc5be7df5b343e363dcdd93647
668,450
def split_estimates(df, org): """Split the passed dataframe into either Sakai or DH10B subsets""" if org == 'dh10b': subset = df.loc[df['locus_tag'].str.startswith('ECDH10B')] else: subset = df.loc[~df['locus_tag'].str.startswith('ECDH10B')] return subset
a4a13c29f6f5729d57003a5b45af99c57f34949c
668,451
def test_1_data(): """Normal signal, with noise""" metrics = {"num_beats": 35, "duration": 27.775, "voltage_extremes": [-0.68, 1.05], "beats": [0.217, 1.031, 1.844, 2.633, 3.422, 4.211, 5.028, 5.681, 6.678, 7.517, 8.328, 9.122, 9.889, 10.733, 11.586, 12.406, 13.239, 14.05...
ac1321b2c7101216beed9f04e649806cb0322eca
668,452
def _is_madx_string_col_identifier(type_str: str) -> bool: """ ``MAD-X`` likes to return the string columns by also indicating their width, so trying to parse `%s` identifiers only we might miss those looking like `%20s` specifying (here) a 20-character wide column for strings. Args: type_...
0dd7f7f5e60d138b6b3285756fbaec2c8e6e3f07
668,453
import json def load_credentials(): """loads the credentials file with important stuff in it""" with open('credentials.json') as f: return json.load(f)
73da5a55388b4116caf31c5662a45edfc73905ab
668,454
def only_true(*elts): """Returns the sublist of elements that evaluate to True.""" return [elt for elt in elts if elt]
48e84744946dad669fae2312682fe938dd118d9f
668,455
def check_for_duplicate(posts, post_id): """ fix duplicate posts in a list of posts returns true if post_id is in posts """ for post in posts: if post_id == post.post_id: return True return False
032cfec93278dc6fffce47b746a110ad0d80e89d
668,456
def get_or_create_instance(model_class, **kwargs): """Identical to get_or_create, expect instead of saving the new object in the database, this just creates an instance. """ try: return model_class.objects.get(**kwargs), False except model_class.DoesNotExist: return model_class(**kw...
883123bbb1f1996915918be3eef84447de43ffa7
668,457
from typing import List import copy from datetime import datetime def generate_message(source: str, status_list: List[dict]) -> dict: """Generate status message""" return { 'source': source, 'status_list': copy.deepcopy(status_list), 'message_timestamp': datetime.utcnow().timestamp() ...
d1d54b4f9277e26ba497e4c9b4b4d958687eee8f
668,458
import re def template_tags(template_fn): """return list of tags from a template file""" with open(template_fn) as template: tags = re.findall(r'{.*?}', template.read()) return set(tags)
e8b89f15526ef26ad47626ba3bcbe16fd8ddc75c
668,459
def role_for_new_user(is_first_user: bool = False, email: str = 'foo@bar.com') -> str: """The role for automatically created users""" if is_first_user: return 'Admin' else: return 'Guest'
501588e5d209b2161c148de4c72ac8162b351bca
668,460
import torch def masking_fn(X, t_sparsity): """Default masking function used by the PruningAgent.""" threshold = torch.sort(torch.abs(X).flatten())[0][int(len(X.flatten()) * t_sparsity.get_epoch_sparsity())] return (torch.abs(X) > threshold).float()
7f2a8abe7f13ce83f534ecef85a87d5afbd2490c
668,461
import argparse def parse_arguments(): """ Parse file arguments """ parser = argparse.ArgumentParser(description="Predict sentiment from a given text") parser.add_argument('question', help="text or list of texts to perform inference on", nargs='+') return parser.parse_args()
3a66d7db16e8c9c87b1b24bf25693be0425eda74
668,462
import os def get_mac(ip): """Gets the mac + name from the ARP cache""" p = os.popen('arp -e ' + str(ip)) try: li = [x for x in p.readlines()[1].split(' ') if x] except IndexError: return None return li[2], ('Unknown' if li[0] == str(ip) else li[0])
579f9a6b43e86d3a9885cb8d26316015a7253547
668,463
import subprocess def GetSystemInformation(): """Gets the system's hardware information. Returns: str: the information, outputs of dmidecode, or None. """ dmi_info = None try: dmi_info = subprocess.check_output(['dmidecode', '--type=system']) except subprocess.CalledProcessError: pass retur...
6bf5fb4c317605cc9b900d398941d2217799083c
668,464
def is_prime(n: int) -> bool: """ Checks if n is a prime number """ if n < 1: return False for i in range(2, n // 2): if n % i == 0: return False return True
ba2f14cdf1d18d34a1e19060b8e0cfa5c121dde4
668,465
def smooth(scalars, weight) : # Weight between 0 and 1 """taken from open stacks weight average operation to remove flutations Args: scalars (_type_): input data weight (_type_): weigth factor Returns: _type_: smoothed data """ last = scalars[0] # First value in the...
ab0eece54a0d2268b5cb1fe33c793a91c40b80dd
668,466
import torch import math def angle_loss(orient, gt_orient): """Only for evaluation""" angle = torch.atan2(orient[:, 0], orient[:, 1]) * 180 / math.pi gt_angle = torch.atan2(gt_orient[:, 0], gt_orient[:, 1]) * 180 / math.pi angle_loss = torch.mean(torch.abs(angle - gt_angle)) return angle_loss
e26f493ffbd5dc8e0b9130d9fd963e7bb77bb346
668,467
def valid_ipv4_host_address(host): """Determine if the given host is a valid IPv4 address.""" # If the host exists, and it might be IPv4, check each byte in the # address. return all([0 <= int(byte, base=10) <= 255 for byte in host.split('.')])
e0796d4334ee1985391f21ea421a34faf0d3bfc7
668,469
def format_sex_string(sex_str): """ Converts 'M', 'F', or else to 'male', 'female', or empty string (e.g. ''). Args: sex_str (str): String consisting of 'M', 'F', '', or None. Returns: str: 'M', 'F', or '' """ if sex_str == "M": sex = "male" elif sex_str == "F": ...
415aab0d3fd38e6bfb18e658564faeb51f852a4a
668,470
import os import sys def sequence_list(input_file): """ Creates a list with all the sequences available in the digest (without duplicates) """ # Check if the input file output.3.MS2 is present in the directory if not os.path.isfile("./" + input_file): print("ERROR! Input file output.3.MS2 ...
ff1f2534cc3c858f2c7d305271e4068d80665fbc
668,471
def mandel(x, y, max_iters): """ Given the real and imaginary parts of a complex number, determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iterations. """ c = complex(x, y) z = 0.0j for i in range(max_iters): z = z*z + c if (z.r...
988f34156365551631eb926da2e1d5e08faff4f0
668,473
def subject(source: str, terms: list, vocabulary_uri: str = '/vocabularies/1', **kwargs) -> dict: """ { 'source': source, 'terms': terms, 'vocabulary': vocabulary_uri, # ... } """ _subject = { 'source': source, 'terms': terms, 'voca...
fcfbf47949b9fbf5b13360d35832180581265226
668,474
import numpy import ctypes def ctypes2numpyT(cptr, shape, dtype=numpy.float32, stride = None): """convert a ctypes pointer array to numpy array """ size = 1 for x in shape: size *= x if stride is None: res = numpy.zeros(size, dtype=dtype) if not ctypes.memmove(res.ctypes.data, ...
bb2447b1512d8e1b002b5e3dbfbd7efbe724d033
668,475
import requests import sys import time def wait_for_result(resturl, taskid, user_agent, polling_interval=1, timeout=30, retrycount=180): """ Polls **resturl** with **taskid** :param resturl: :param taskid: :param user_agent: :param polling_interval: ...
61952c0699ac4b9586eff2f79eddbdba96d779b3
668,476
def make_car(marka, model, **car_info): """Tworzy słownik zawierający informacje o samochodzie""" car_info["marka"] = marka car_info["model"] = model return(car_info)
d80bb90cbd2ced1d2cd4f1116cf2a26858d58991
668,477
def one_or_more(string): """ A regex wrapper for an arbitrary string. Allows an arbitrary number of successive valid matches (at least one) to be matched. """ return r'(?:{:s}){{1,}}'.format(string)
45397b292b1f472138c9b757458d7743a13b3d93
668,478
def cooper_jacob_correction(observation, sat_thickness): """correction method for observed drawdown for unconfined aquifers. Parameters ---------- observation : :class:`welltestpy.data.Observation` The observation to be corrected. sat_thickness : :class:`float` Vertical length of th...
863e88e37101c7e7b609708b01a844d7d4953334
668,479
def _compile(compile_func, source): """Compile some source with a compile func.""" result = compile_func(source) assert result.errors == (), result.errors assert result.code is not None return result.code
9e910ca052117b0de768b590675d389ff25f9c72
668,480
import torch def second_box_encode(boxes, anchors, encode_angle_to_vector=False, smooth_dim=False): """box encode for VoxelNet Args: boxes ([N, 7] Tensor): normal boxes: x, y, z, l, w, h, r anchors ([N, 7] Tensor): anchors """ xa, ya, za, wa, la, ha, ra = torch.split(anchors, 1, dim=-1...
f6c6229f0f9da5c2e0e350187fb5436c387e21c1
668,481
def get_explict_dest(pdf, dest_list): """ Find explict destination page number and rectangle. :param pdf: pdfplumber.pdf.PDF object :param dest_list: A explict destination list, e.g. [page, /XYZ, left, top, zoom] :return: A list of destination contains page number and rectangle coordinates """ ...
e6f2abebc2c036ad3f1b3f8a42259b3805b64f02
668,482
import argparse import os def parse_args(): """ Setup and parse CLI arguments. """ parser = argparse.ArgumentParser( description="Copy/inspect registry images", ) parser.add_argument("src", help="Source registry image") parser.add_argument("dst", nargs="?", help="Dest registry imag...
58e84e060c9862ce572464f7b5e4bb7286020a54
668,483
def get_elev_abbrev(cell): """ Parse elevation and station abbreviation. """ tc = cell.text_content().strip() return int(tc[:-6]), tc[-4:-1]
01c32c5e57a4f8a55fe0eae8b1525f0eb2941d9d
668,484
import os def directorySubtypeGenerator(folder, flareType, subtype): """ Generates Directories based in the subtype and type of flares """ if os.path.isdir('./{}/{}/{}'.format(folder, flareType, subtype)) == False: os.makedirs('./{}/{}/{}'.format(folder, flareType, subtype)) return os...
45a5280864f2c2fbde17d23800d2ef94adfddee3
668,485
def write_vcf(dframe): """Variant Call Format (VCF) for SV loci.""" return NotImplemented # See export.export_vcf()
39e69960c79fc96b4a130d84faa864b3e2454b98
668,486
import json import re def _ignore_kfp_version_helper(file): """Ignores kfp sdk versioning in command. Takes in a JSON input and ignores the kfp sdk versioning in command for comparison between compiled file and goldens. """ if 'executors' in file['pipelineSpec']['deploymentSpec']: for exe...
ca6958207605d76a246810f94a617f9682286404
668,487
import os import subprocess def call_eventalign_script(fast5_dir, reference, output_dir, threads=1, overwrite=False): """Call eventalign script from scripts folder""" # call_eventalign.sh -f ../test_files/minion-reads/canonical/ -t 1 -r ~/data/example_references/ecoli_k12_mg1655.fa -o ~/CLionProjects/nanopoli...
2ba6fe58b02195838cfe90c11152e862e983ed4f
668,488
import json def str_format_dict(jdict, **kwargs): """Pretty-format a dictionary into a nice looking string using the `json` package. Arguments --------- jdict : dict, Input dictionary to be formatted. Returns ------- jstr : str, Nicely formatted string. """ kwarg...
15c24c57c9d59bfa01a914755165a00c9922bbff
668,489
def get_stats(data: list, index: int = 0) -> dict: """ Generate list of users """ result = {} for row in data: # If we already found user previously, aggregate new values if row[index] in result: result[row[index]]["products_bought"] += row[2] result[row[index]]["tota...
1f613f72b25e58e18731750588f37cba6890b080
668,490
from typing import Optional import re def _normalize(x: Optional[str]) -> Optional[str]: """ Normalize string to lowercase, no whitespace, and no underscores. Examples -------- >>> _normalize('Offshore Wind') 'offshorewind' >>> _normalize('OffshoreWind') 'offshorewind' >>> _normal...
3b5daf8bda7708e9fa2b5124c4738a4d469e8ddc
668,491
import pandas def get_CSV(FILENAME): """ Retrieves CSV file containing workout log information. """ LOGFILE = pandas.read_csv(FILENAME, header=0, index_col=0) return LOGFILE
c7a7270b19a151c88ffacbc82dab9ef49c1bdd8d
668,493
def get_genres(): """Restituisce la lista dei generi esistenti""" genres = [ {'name': 'Comedy'}, {'name': 'Documentary'}, {'name': 'Drama'}, {'name': 'Action'}, {'name': 'Adventure'}, {'name': 'Horror'}, {'name': 'Mystery'}, {'name': 'Crime'}, ...
92b4fd6475536bd1cfc0ab4ebdc073a732e7d4b6
668,494
def AddAssay(adata, data, key, slot="obsm"): """Add a new data as a key to the specified slot Parameters ---------- adata: :AnnData AnnData object data: `pd.DataFrame` The data (in pandas DataFrame format) that will be added to adata. key: `str` T...
1f34fc40b338e755983bbc551a565b4af23dfb9b
668,495
def create_mosaic_pars(mosaic_wcs): """Return dict of values to use with AstroDrizzle to specify output mosaic Parameters ----------- mosaic_wcs : object WCS as generated by make_mosaic_wcs Returns -------- mosaic_pars : dict This dictionary can be used as input to astrodri...
e9a8a499ce3a9196fcaf4f57c4bda4aa25905655
668,496
import math def cent_diff(freq1, freq2): """Returns the difference between 2 frequencies in cents Parameters ---------- freq1 : float The first frequency freq2 : float The second frequency Returns ------- float The difference between the 2 frequencies """...
e08a8579afaf534c99d772e8e098f13d4b8ed371
668,497
import numpy def neff_fwhm(stamp): """FWHM-like quantity derived from N_eff = numpy.sum(PSF**2.)**-1""" norm = numpy.sum(stamp, axis=(-1, -2), keepdims=True) return 1.18 * (numpy.pi*numpy.sum((stamp/norm)**2., axis=(-1, -2)))**(-0.5)
cf56eba05ad009661329204fc08324cb61aca8b1
668,499
def class_in_closure(x): """ >>> C1, c0 = class_in_closure(5) >>> C1().smeth1() (5, ()) >>> C1.smeth1(1,2) (5, (1, 2)) >>> C1.smeth1() (5, ()) >>> c0.smeth0() 1 >>> c0.__class__.smeth0() 1 """ class ClosureClass1(object): @staticmethod def smeth1(*...
94c203f2d6b8cfcccc6ac5b1234000dd6fca65d0
668,500
def detailedview(av_data: dict, filehash: str) -> str: """Builds and returns a string containing detailed information regarding the analysis for each antivirus engine""" vt_url = f'https://www.virustotal.com/gui/file/{filehash}' response = f"__VirusTotal Analysis Summary__:\n\nHash: `{filehash}`\n\nLink: [C...
08caa2ce53626ea0031772063ced58a2669399ad
668,502
def read_file(file_path): """Read initial program""" with open(file_path, 'r') as program: program = open(file_path, "r") program = str(program.read()) return program.split('\n')
2df37a477b43b62fff0d57970c53213532335185
668,503
def _get_obj_file(ctx, src): """Returns the obj file for the given src.""" extension_index = src.short_path.rindex(".c") obj_file = src.short_path[0:extension_index] + ".o" return ctx.new_file(obj_file)
3b36875c0d87be630077017163ffd3900c7d87b3
668,505
import re def sort_key_natural(s, _nsre=re.compile('([0-9]+)')): """Adapted from http://blog.codinghorror.com/sorting-for-humans-natural-sort-order.""" return [int(text) if text.isdigit() else text.lower() for text in re.split(_nsre, str(s))]
303757c9c0464b4e91d21599e8a9fd3050cbfc87
668,506
def build_credentials_dict() -> dict: """Build a credentials dict, used for testing.""" return {"allow": [], "deny": []}
ca7b169f923907cbc5083be15617d46a9c63df8c
668,507
from pathlib import Path def get_ss_dir(): """Checks whether the db directory exist, and gets its path. Returns: Path: the directory itself Raises: FileNotFoundError: if directory was not found """ for path in ['server_settings', '../server_settings']: ss_dir = Path(path...
ab4586fce673d018aa8956860e34490536601b48
668,508
def findSurefireCommand(output): """ Find where the maven surefire plugin (which is the test plugin) begins its command Parameters ---------- output : list of str The lines of the build output Returns ------- str The line that contains the java command to run the ma...
4756a7ab2db56157bc2ef828feffc17a3f4f2212
668,509
def find_nested_parentheses(string): """ An equation that could contain nested parentheses :param str string: An equation to parse :return: A dict with the indexes of opening/closing parentheses per nest level :rtype: dict """ indexes = {} nested_level = 0 for i, char in enumerate(st...
cdf8bf428e396c087a7d0e0caa33651653007373
668,510
def log_likelihood(reference, test): """ Given a list of reference values and a corresponding list of test probability distributions, return the average log likelihood of the reference values, given the probability distributions. @param reference: A list of reference values @type reference: C{l...
9d2f7c414339970e0e213c7ec1983c265687a6dc
668,511
def _append_ns(in_ns, suffix): """ Append a sub-namespace (suffix) to the input namespace :param in_ns Input namespace :type in_ns str :return: Suffix namespace :rtype: str """ ns = in_ns if ns[-1] != '/': ns += '/' ns += suffix return ns
fdd6378538cc3045463fbe981acaa3d03a7f7adc
668,512
import os def get_size_for_benchmark(): """ Returns the size for the seed for each benchmark. """ size = 256 if 're2-2014-12-09' in os.environ['BENCHMARK']: size = 64 if 'libpng' in os.environ['BENCHMARK']: size = 128 return size
a250ce37ff10bfc0151793e7e7baa23caaa3488a
668,513
import codecs def parse(*args, **kwargs): """Parse documentation files into internal variable for rendering with setup """ # noinspection PyPep8Naming SEPARATOR = kwargs.get('separator', '\n') coding = kwargs.get('coding', 'UTF-8') stream = [] for arg in args: with codecs.open(arg...
e6eb0308b49bf9dd2764725be25c845460fedd2b
668,514
def der_value_offset_length(der): """Returns the offset and length of the value part of the DER tag-length-value object.""" tag_len = 1 # Assume 1 byte tag if der[tag_len] < 0x80: # Length is short-form, only 1 byte len_len = 1 len = int(der[tag_len]) else: # Length is ...
ed989e1188c0d443ee2b6334b185110524a1fddb
668,515
def radtodeg(rad): """ Function that converts radians to degrees """ return rad * (180/3.14159)
a9838043fee2e1cdd06d20974be461fd1053208b
668,516
def render(line, prefix_arg=None, color=-1): """ Turn a line of text into a ready-to-display string. If prefix_arg is set, prepend it to the line. If color is set, change to that color at the beginning of the rendered line and change out before the newline (if there is a newline). :param str lin...
c2526f48def3fb528d87b47dd38aa88b8e08b2ba
668,517
def onek_unk_encoding(x, set): """Returns a one-hot encoding of the given feature.""" if x not in set: x = 'UNK' return [int(x == s) for s in set]
c788794770757e31f749e42cc61b15f86c632b96
668,518
def hamming_distance(str1, str2): """Computes the hamming distance (i.e. the number of differing bits) between two byte strings. Keyword arguments: str1 -- the first byte string str2 -- the second byte string """ distance = 0 for b1, b2 in zip(str1, str2): # xor in each place is...
5bc24c6ebf7b0d0f589e91b9f50617bb037c83a8
668,520
import fnmatch def is_copy_only_path(path, context): """Check whether the given `path` should only be copied and not rendered. Returns True if `path` matches a pattern in the given `context` dict, otherwise False. :param path: A file-system path referring to a file or dir that should be rend...
9dd45350a0a4df42923e50c06aca110fbcf40f38
668,521
import subprocess def has_alamo(): """ Checks for ALAMO """ try: s = subprocess.check_output(["alamo"]) if b"Licensing error" in s: _alamo_ok = False else: _alamo_ok = True except (subprocess.CalledProcessError, FileNotFoundError): _alamo_ok ...
abb3bef5c1c24888ebf287eabd439612b6d43313
668,522
def jaccard_coefficient(x,y): """ Jaccard index used to display the similarity between sample sets. :param A: set x :param y: set y :return: similarity of A and B or A intersect B """ return len(set(x) & set(y)) / len(set(x) | set(y))
d806a6e2a9e86d840eeba2709acd373e32c4801f
668,523
def prioritized_model_fields(): """return prioritized model fields""" return (("priority",), )
744bca25de7da228eeec2d1a076c8e9c1139a9ed
668,524
import ssl def get_ssl_context(account): """Returns None if the account doesn't need to skip ssl verification. Otherwise returns ssl context with disabled certificate/hostname verification.""" if account["skip_ssl_verification"]: ssl_context = ssl.create_default_context() ssl_context.c...
a4c095b3b843849d287eaf257e4b775f3391ac9c
668,525
def removeBelowValue(requestContext, seriesList, n): """ Removes data below the given threshold from the series or list of series provided. Values below this threshold are assigned a value of None. """ for s in seriesList: s.name = 'removeBelowValue(%s, %d)' % (s.name, n) s.pathExpression = s.name ...
52afb595f42de0c4a18fff60458bbdc012a57dcc
668,526
import requests def request_issues(url): """Request issues from the given GitHub project URL. Parameters ---------- url : str URL of GitHub project. Returns ------- response : Response Response data. """ response = requests.get(url) return response
9f33675d687941873d9b401ddd381894b8cdb3e2
668,527
def create_snapshot_dict(pair, revision_id, user_id, context_id): """Create dictionary representation of snapshot""" parent, child = pair.to_2tuple() return { "parent_type": parent.type, "parent_id": parent.id, "child_type": child.type, "child_id": child.id, "revision_id": revision_i...
2b773edd8ae64d1fd7fcf74b4fbb31b8902234c8
668,528
def new_evidence_file(network_filename, variable, value): """Creates a new evidence file for a given goal variable-value pair (and returns its filename).""" new_filename = network_filename + '.inst' with open(new_filename, 'w') as evidence_file: evidence_file.write( '<?xml version="1...
0faa00acc621da427540e41d215307bc369be253
668,529
import codecs def token_process(vocab_path): """ 数据处理 :return: """ # 将词表中的词转换为字典 token_dict = {} with codecs.open(vocab_path, 'r', 'utf8') as reader: for line in reader: token = line.strip() token_dict[token] = len(token_dict) return token_dict
bf46deedb4f3c3b1d61ecda2e590826e251c4cc7
668,530
def erd_encode_bytes(value: bytes) -> str: """Encode a raw bytes ERD value.""" return value.hex('big')
35c6f185f4626e3fa29a5476f44d600414bb73cd
668,531
def get_source_date(source): """ Return date for a source in the "Old Russian" subcorpus. If the given date for a source is a range, e.g., 1100-1150 date_begin = 1100 date_end = 1150 date_middle = 1125 """ date_rough = source.split("(") date_long = date_rough[1][:-1] if len(date...
a392280f26c57f25c5defadc3e2d1b5c22b32c4c
668,532
def quaternion_is_valid(quat, tol=10e-3): """Tests if a quaternion is valid :param quat: Quaternion to check validity of :type quat: geometry_msgs.msg.Quaternion :param tol: tolerance with which to check validity :return: `True` if quaternion is valid, `False` otherwise :rtype: bool """...
486396802e1bb8386d8c0a722145d1feca3c14fa
668,533
def normalize_program_type(program_type): """ Function that normalizes a program type string for use in a cache key. """ return str(program_type).lower()
a22858f13708964f159b9b930aa289c9184661e1
668,534
def Inf(): """ Return floating point inf """ return float("inf")
0c05b3714b68306f6497fa879111ef5ee2932467
668,535
def _strip_path_prefix(path, prefix): """Strip a prefix from a path if it exists and any remaining prefix slashes Args: path: <string> prefix: <string> Returns: <string> """ if path.startswith(prefix): path = path[len(prefix):] if path.startswith("/"): pa...
9cd4460ffd318600287300686de748141442e0d1
668,536
from typing import Optional def is_eof(char: Optional[str]) -> bool: """Check if a character is EOF.""" return char is None
089c2d04b2bf3be34707e1b4206b0537baadd9c8
668,537
def classification_labels(row): """Function for mapping labels""" if row["label"] == 1: return "Negative" return "Positive"
0a23b71c42663c5211b24e2deaa03cab5eef6d3b
668,538
def clean_backticks(msg): """Prevents backticks from breaking code block formatting""" return msg.replace("`", "\U0000ff40")
5ec8b60fc50b9f1eb5dd51cc1ce2b699be151413
668,539
def pythonify_metrics_json(metrics): """Converts JSON-style metrics information to native Python objects""" metrics = metrics.copy() for key in metrics.keys(): if key.endswith("_histogram") or key.endswith("_series"): branch = metrics[key] for sub_key in branch.keys(): ...
0c0339c83146aab6581061be1a07ba4c683eb2aa
668,540
def newline_to_br(base): """Replace newline with `<br />`""" return base.replace('\n', '<br />')
fe807e08a875358f8f8da0c422f1b43cd19f7e03
668,541
def exchangeRate(dollar): """美元 -> 人民币 汇率为6.5 """ return dollar * 6.5
cc62b838108134f1e4e029eef6a4479c9ddbf022
668,543
import threading def _thread_not_active(): """ Return true if a terraform apply is not already running """ return "TerraformThread" not in [x.name for x in threading.enumerate()]
4603b3cb4f382925dbe784fb7ff67ee101855c58
668,545
def _check_udp_checksum(pkt): """Check udp checksum in ip packet. Return true if checksum is correct.""" new = pkt.__class__(str(pkt)) del new['UDP'].chksum new = new.__class__(str(new)) return new['UDP'].chksum == pkt['UDP'].chksum
038593005f8b173ec9ad4176836ef68d802bb0e7
668,546
def is_key(sarg): """Check if `sarg` is a key (eg. -foo, --foo) or a negative number (eg. -33).""" if not sarg.startswith("-"): return False if sarg.startswith("--"): return True return not sarg.lstrip("-").isnumeric()
f61ef81e2f8bcbbb9e7b51f695f6a8c789abbd0a
668,547
import argparse def get_parser(): """Return argument parser.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "-v", "--verbose", action="store_true", dest="verbose", default=False, help="Verbose output", ) # add arguments...
9ab14237762a848eb2a993a0272f9af433cde989
668,548
import base64 import struct import hmac import hashlib import time def GoogleAuth(key): """ 谷歌验证码 # RFC 协议下有HOTP和TOTP 前者是计数 后者是计时 生成验证码 # hopt 由 RFC 协议 RFC4266 # google auth 用的是TOTP 而TOTP是在HOTP的基础上计时 :return: """ def get_hotp_token(secret, intervals_no): """This is where the...
96175b53eb96ba246160ab75465c00f051cae75e
668,549