content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def measure_between(vec): """ :param vec: list of N coordinates :return: list of N-1 distances between all pairwise N coordinates """ return [abs(vec[i + 1] - vec[i]) for i in range(len(vec) - 1)]
f8f58f699aeacb036bb807435992e234a9a0ca7a
642,876
import torch def get_cm_plot(Y_cm, dim0, dim1, dim2): """ Convert the coordinate of the keypoint/center-of-mass to points in an tensor Arguments --------- Y_cm : keypoints coordinates/center-of-masses[n_bath, 3, n_reg] dim : dim of the image Return ------ out : tensor it...
9b930e47a9de8d05579e4d77c676ec45a497c8f5
642,877
def orbreap(orb): """Get the next packet from an orb""" return orb.reap()
557ad1ac2af84c0c76cf8865ad560d9728803000
642,878
def commodity_string(value): """商品名输入类型""" if len(value) > 50: raise ValueError('商品名格式不正确') return value
10acdfbfe359e502f4bf7d2033e7480de2536d86
642,879
import shutil def get_free_space(): """ Returns the amount of free space on the drive as a float rounded 1 place. """ return round(shutil.disk_usage("/")[2] / (1024.0 ** 3), 1)
cd7b2c18ce06a84a47113d419eca28ac7c885a0a
642,880
import subprocess def get_arch(): """ Returns the arch as it is determined by Linux. What is below is the rewritting of the SUBARCH variable assignment in Linux' top-level Makefile. """ return subprocess.check_output( "uname -m | sed" " -e s/i.86/x86/" " -e s/x86_64/x86/" ...
50d888ae1f4f7f7d0fcd9130b5d28fd09595da57
642,881
def check_shape(a, b): """ Checks if the shape of `a` and `b` is the same """ if not hasattr(a, "shape") or not hasattr(b, "shape"): # automatically true if one of them is a scalar return True if a.shape != () and b.shape != (): return a.shape == b.shape return True
afe0f7ba2974dbe3a0b2b54d8ac59043da3fca4e
642,882
def fetch_log_pos(server, args_array, opt_arg_list): """Method: fetch_log_pos Description: Stub holder for mysql_log_admin.fetch_log_pos function. Arguments: """ status = True if server and args_array and opt_arg_list: status = True return status
659f922d07b5bab10e47280b1980c6273a962eee
642,883
def handles_request_body(request_func): """ This function decorator may be used to mark a method as usable for intercepting request body content. handles_request_body will intercept the HTTP content in chunks as it arrives. This method, like others in the filter class may return a FilterAction....
360f1427c8b1cf2a578fd455b4117dd3fa596409
642,884
import zlib import base64 def bytes_to_compress_to_base64(bytes_text: bytes) -> str: """ Функция сжимает байтовый массив и кодирует его как base64 и возвращает как строку. """ compress_bytes_xml = zlib.compress(bytes_text) base64_compress = base64.b64encode(compress_bytes_xml) return base64...
dab975828dde765c8b1f18d76169c51cf21ac1c5
642,885
import re import getpass def userName() -> str: """ Return a database-friendly username. This will return the current user's username, removing any prefix like ``pre-``, if present. Notes ----- ARMI uses the user name in a number of places, namely in the database names, which cannot ...
dff21740fa7c28f2580dc6cf8fb8d87b54ef4443
642,886
def colval(letter: str): """ chess columns are 1-indexed, subtract one to operate on 'board' """ return { "a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5, "g": 6, "h": 7 }[letter]
9f05e98c8f76f3f9d6e56538482df8040f069701
642,887
import csv def load_tokens(dataset_path, schema): """ Returns {lang: {gloss: [tokens,]}} dict from the given dataset or raises AssertionError if there are no tokens. """ tokens = {} with open(dataset_path) as f: reader = csv.reader(f, delimiter='\t') header = next(reader) assert 'tokens' in header ...
f3b16b6ff96484048d3fdd9143c229a6dd1d3281
642,888
def _list_equal_or_subset(check_list, obj_list): """Used by output filter to check if obj_list is in check_list""" if not isinstance(check_list, list): return False return set(check_list).issubset(set(obj_list))
31c69909a1ac537fde767b64eeb369cd5eb2f016
642,890
def _sort_key(item): """ Robust sort key that sorts items with invalid keys last. This is used to make sorting behave the same across Python 2 and 3. """ key = item[0] return not isinstance(key, int), key
34f716c6e20e0646fd4aeb76650c170143cb3eca
642,891
def replace_colon(s, replacewith='__'): """replace the colon with something""" return s.replace(":", replacewith)
3ed3d11736903bf0e26f8aa22de78a247c06b5ef
642,892
def prepare_kwargs(raw, string_parameter='name'): """ Utility method to convert raw string/diction input into a dictionary to pass into a function. Always returns a dictionary. Args: raw: string or dictionary, string is assumed to be the name of the activation activation functi...
656baf750eac6c47a7ef4471c078fd67148c500b
642,893
import typing def keyword_sort_key(kw: str ) -> typing.Tuple[str, ...]: """ Return the keyword sorting key, i.e. sort by os, then arch name. """ return tuple(reversed(kw.lstrip('-~').partition('-')))
117fadd89aa88603583987ff27f35ffc33e80358
642,894
import operator def dict_proxy(attribute): """Return a decorator for a class to give it a `dict`-like API proxied from one of its attributes Parameters ---------- attribute : str The string corresponding to the attribute which will be used Returns ------- function ...
c1818a2b068879091cb150dfcc27315ece0db45b
642,895
def refine_axis(axis, shape): """refine axis""" if isinstance(axis, (tuple, list)): local_axis = axis else: local_axis = [axis] res_axis = [] shape_len = len(shape) for i in local_axis: if i < 0: laxis = shape_len + i else: laxis = i ...
6d138442e32bdb5258a4c5621becbfbd59968b81
642,896
def solution(A): """ DINAKAR keep item as key in dict, it will keep overriding repeated numbers at same key length of temp should be uniuqe element """ temp = {} for i in range(len(A)): temp[A[i]] = True print(temp) return len(temp)
4fb49df6a6ad02586d9b6b65da68a77209719a7d
642,897
import ipaddress def wrap_ipv6(ip_address): """Wrap the address in square brackets if it's an IPv6 address.""" if ipaddress.ip_address(ip_address).version == 6: return '[{}]'.format(ip_address) return ip_address
c33975f2ebf5deb482dd03d7f95692e61894e9f4
642,898
def iterate_pagerank(corpus, damping_factor): """ Return PageRank values for each page by iteratively updating PageRank values until convergence. Return a dictionary where keys are page names, and values are their estimated PageRank value (a value between 0 and 1). All PageRank values should su...
a2a9c929a4fbe70a1e4d129f68526481955e4a76
642,899
from os.path import commonpath def in_path(root, path): """Check if `path` is in the same directory hierarchy as `root`. Parameters ---------- root : :class:`str` Root directory. path : :class:`str` Filename, could be a file or a directory. Returns ------- :class:`boo...
3bdf2ca5e1ab304db2e1c1c19cdb723f2699790e
642,900
def isolate_rightmost_0_bit(n: int) -> int: """ Isolate the rightmost 0-bit. >>> bin(isolate_rightmost_0_bit(0b10000111)) '0b1000' """ return ~n & (n + 1)
1abac335b8570474121bbf307f52f7af2f0c736f
642,901
def is_palindrome(num: int) -> bool: """Checks if a number is a palindrome.""" return str(num) == str(num)[::-1]
bb6b271a1fbf77efb08091b625acd0ee932f292d
642,902
import re def wiki_escape(s): """Detect WikiSyntax (i.e. InterCaps, a.k.a. CamelCase) and escape it.""" ret = [] for word in s.split(): if re.match(r"[A-Z]+[a-z]+[A-Z]", word): word = "!%s" % word ret.append(word) return " ".join(ret)
488cf89b2bc402fdd4eb89d23bb73076cd0f2472
642,903
from typing import Optional from typing import Dict from typing import Any from typing import List def prepare_query(query: Optional[Dict[str, Any]]) -> Dict[str, List[str]]: """Convert all query values to list of strings. Query parameters may be generated in different shapes, including integers, strings, li...
402fc3df1c701b53c7425675bbe7bf25bbf20007
642,904
def init_method_normalizer(name: str): """Normalizes the name of an initialization method.""" return name.lower().replace('_', '').replace('nodeembeddinginitializer', '')
33178f4de0c01bb754516a68792aebef16fcfb6c
642,905
import os def _random_sample(n, k): """Randomly samples k values between [0, n]""" assert n>0 and k>0, "n and k must be > 0" return [int(b) % n for b in os.urandom(k)]
1abb05d877c6587437115d126923488fffa3f4c6
642,907
import operator def read_ctm(fpt, pos=(0, 1, 2, 3), has_duration=False, file_transform=None, blacklist=(), add_bool=False, offset_from_filename=None, file_segments=None): """ read a ctm file :param fpt: file pointer to read ctm file to from :param pos: 4 element tuple with posit...
31f923b01e6a998c6333966935825963d7120447
642,908
import random def mutate_value(value): """Randomly doubles or halves a value -- applied at "value" level""" if random.random() < 0.5: return value * 2 return value / 2
e054ca4c8714168667733cef32091d5b65eb6cd0
642,909
def INDICES_FILTER(arg_value): """Only keeps tensors/sequences containing ints suitable for indexing.""" return ((arg_value.is_tensor and arg_value.has_int_dtype() or arg_value.elem_type is int) and arg_value.min() >= 0)
b38ad63ee455db4c2128fdee8f27ddfc13b41ee0
642,910
def check_syllable(char): """Check whether given character is valid Hangul syllable.""" return 0xAC00 <= ord(char) <= 0xD7A3
109dfaa22b5dbff56c1f84fabaa2afa5b1b96141
642,911
import requests def httpStatusCodeCheck(url, simulate_404=False, time_out=30.000): """Checking HTTP status code, or a presumed 404 message Attributes: string url, bool simulate_404, decimal time_out """ if (simulate_404): url = '{0}/{1}'.format(url, 'sp4m-b34t2-...
f0e3519d0cef4a77f3d16f4e944ba4f4cc0919e0
642,912
def load_golden_triples(filepath): """ :param filepath: path to the test file with gold standard :return: set with test suite and a set with golden standard """ file = open(filepath, "r") test = file.readlines() test_suite = [] for sample in test: if sample == '\n': ...
1fdb0cee2d35a31cfb82ff367b8ead4cb4ace496
642,913
import re def clean_html(raw_html): """Remove HTML tags from a text""" clean_regex = re.compile('<.*?>') clean_text = re.sub(clean_regex, '', raw_html) return clean_text #def process_column(column_name, dataframe, process): """Define a method to apply the same process to every row in a ...
af05b910e5a86bcf881d0f218caf40a738bc98d7
642,914
from typing import List import os def get_dir_paths(dir_name: str) -> List[str]: """ Goes through the specified folder and retrieves all the file paths within. Args:\n dir_name: str = The path to the directory. Returns:\n file_paths: List[str] = A list of all the paths in the...
ea081a02d811a5d2bfc181137a68cdaea107bdb1
642,915
def get_idx_from_placements(placements, current_rank) -> int: """ Return the position of the current rank in the given placements. Args: placements(List[Union[_remote_device, str]]): Specifies the placement of each shard of the Tensor. The size of the list represents the num...
463686bd8da1aae4aef196a72b1d60ab334bb9da
642,916
def default_dispatchers() -> list[str]: """Получение отправителей уведомлений по умолчанию. :return: названия классов отправителей уведомлений по умолчанию """ return list(['EmailDispatch'])
efb8532d245537a1a03c598b2dc83fdc56f5fd3b
642,917
def serialize_company_address_form(cleaned_data): """ Return the shape directory-api-client expects for updating address. @param {dict} cleaned_data - All the fields in `CompanyAddressVerificationForm` @returns dict """ return { 'postal_full_name': cle...
6e08473f8fae90271ecb2290eea98928ee691aff
642,918
import argparse def _parse_args() -> argparse.Namespace: """Parses arguments.""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Crop detections from MegaDetector.') parser.add_argument( 'detections_json', help='path to...
4667ce0d97bb285b5bc57d26531210f6cd04d26c
642,919
from typing import Optional from typing import Callable import time def create_fps_timer(desired_fps: float, on_miss_callback: Optional[Callable] = None): """ Returns a timing function that sleeps to allow constant time between iterations. The precision of the time between iterations is up to the host operati...
efd3b07bb1a250b9017ef4a179af23f0da1116d5
642,920
import os def image_get_dockerfile_path(project_path, image_name): """ Get a Dockerfile image path. :param project_path: Project path (str) :param image_name: Image name (str) :rtype: Dockerfile path (str) """ return os.path.join(project_path, "images", image_name, "Dockerfile")
bc5678baecdd1b11c1a4ec6695d3300c21533528
642,921
def write_task_report(task, queue): """Generate task usage report entry. Generates a report of task computational usage, including task ID, executed command, start time, end time, exit status, CPU time, wall time, cores used, virtual memory used, swap memory used, total processes executed, max concurre...
59c56eabee0d1331276c7d48ec95296cffaa0d8d
642,922
def _get_last_nonempty_line(loglines, start_line): """Check loglines starting at index start_line and return the number of the last line that is not empty""" last_line = len(loglines) - 1 for i in range(start_line, len(loglines)): if len(loglines[i].strip()) == 0: last_line = i - 1 ...
bfdedbe0763b0a6320baee97b1b5ee8ad3c89b5f
642,923
def find_match_range(seg, genome, maxslide): """Find maximum distance over which a splice junction can be moved up- or down-stream without reducing sequencing support for that junction. In other words, find locally repeated sequences surrounding exon-intron or intron-exon boundaries that can cause ...
b60f6a03ca2757a804692f9840e7f8900164a133
642,924
def reverse(s): """ Return reverse of 's'. """ r = "".join(reversed(s)) return r
e199c0ea220378abebb90fbaf8e3a299531c6a1f
642,925
def format_range(low, high, width): """Format a range from low to high inclusively, with a certain width.""" if low == high: return "%0*d" % (width, low) else: return "%0*d-%0*d" % (width, low, width, high)
59fc9f38967541924e1d74799d655b07884d22fe
642,926
def generate_name_from_values(attributes_dict): """Generates name from AttributeValues. Attributes dict is sorted, as attributes task should be kept within each save. Args: attributes_dict: dict of attribute_pk: AttributeValue values """ return ' / '.join( str(attribute_value) ...
28a34f598c132f503e2dff0b9e8a2c502fa259da
642,927
from typing import List import os def find_txt(path: str) -> List[str]: """ List all txt files in a given directory. :param path: path to the directory :return: list of txt files """ files = os.listdir(path) files = [f for f in files if f.endswith('.txt')] return files
7a866f83e147991afa07026bd150976e310de6bb
642,928
def file_len(fname): """ Get length of file """ return sum(1 for line in open(fname))
bec5123bb225b4ee3d204fc1d9233a4bbaa16fc3
642,929
import codecs import json def load_config(config_file): """ Load configuration of the model parameters are stored in json format """ with codecs.open(config_file, encoding="utf8") as f: return json.load(f)
7c427c8f1cc804eb0f3807234f20805f9928e636
642,930
import torch def pairwise_distances(embeddings, squared=False): """ ||a-b||^2 = |a|^2 - 2*<a,b> + |b|^2 """ # get dot product (batch_size, batch_size) dot_product = embeddings.mm(embeddings.t()) # a vector square_sum = dot_product.diag() distances = square_sum.unsqueeze(1) - 2*dot_product + square_sum.unsqu...
a1f0aac31928b65a82864ef62d7bfa16f06ac602
642,931
def set_control_defaults(): """ Function to define the default values of the parameters, such that if the user does not define something the code can still be safely used. Author ---------- Jonathan Chico """ Skx_control=dict() Skx_control['Fig_control']=dict() Skx_control['Fig_contr...
a3bcaaad1bd5c932b12d06cb43adb135a3c9c03f
642,932
def concat_sequence(sequences): """Concatenate sequences of tokens into a single flattened list of tokens. Parameters ---------- sequences : list of list of object Sequences of tokens, each of which is an iterable of tokens. Returns ------- Flattened list of tokens. """ re...
0bcbdee35323b1e318c62ad55dfbe726b2b5df84
642,933
import math def estimate_risk(entry_price: float, stop_price: float) -> float: """ estimates the risk per share :param entry_price: float :param stop_price: float :return: float """ if math.isnan(entry_price) or math.isnan(stop_price): raise TypeError() return abs(entry_price...
f2ad204708b55834b70f607789c524598e1caf7e
642,934
import itertools def hex_key_xor(plaintext, key): """Encrypt a hex string with a hex key. Keyword arguments: plaintext -- the hex string to be encrypted key -- the encryption key """ HEXCHARS = '0123456789abcdef' output = '' # convert chars to binary, XOR (^), and append to ou...
cd93d9208b3cae50e5b6aa894ac896496632c650
642,935
import struct def get_terminated_strings(num, data): """Parse space- or *- separated strings of variable length Parameters ---------- num : int Number of substrings to be parsed data : str 4C binary data file Returns ------- str Truncated 4C binary file li...
c72b1fa901dcfcdd2e817a4637465437f5c6431b
642,936
import os def get_root_dir(args): """ Either the root_dir option or the current working dir """ if args.root_dir: if not os.path.isdir(os.path.realpath(args.root_dir)): raise ValueError( "Specified root dir {} does not exists".format(os.path.realpath(args.root_dir))) ...
fbe956cbdea23259d777b89dc40eb4ad6666b629
642,937
from typing import Union from pathlib import Path def convert_win_2_wsl_path(path: Union[str, Path]): """ Convert a windows path to the respective Windows Subsystem for Linux path. :param path: The Windows path. :return: The WSL path as a string. """ parts = Path(path).parts wsl_path = "/...
e2226d756c177170b65f8c487290793aba000273
642,938
import subprocess def subprocess_run_with_clean_exit(*args, check=False, **kwargs): """ As subprocess.run(*args, **kwargs), but in the event of a SystemExit, KeyboardInterrupt, or BrokenPipe exception, sends SIGTERM to the subprocess and waits for it to exit before re-raising. Typically paired with si...
cb75059549116f97ffcf1e8ef9e5281d41b5ae37
642,939
def escape_team_names(mystr): """ temporary fix for solving ? characters in bad team names encoding from LFP's ICS calendar """ mystr = mystr.replace('N?MES','NÎMES') mystr = mystr.replace('SAINT-?TIENNE','SAINT-ÉTIENNE') mystr = mystr.replace('H?RAULT', 'HÉRAULT') return mystr
ff715691ed9b2333854ab7c6717c320f45ac955a
642,940
def font_bold(mystring): """ Formats the string as bold, to be used in printouts. """ font_bold = "\033[1m" font_reset = "\033[0;0m" return font_bold + mystring + font_reset
09aa81b94a2dd9470500b93b553bc97dc0302522
642,941
def scale(val, minx, maxx, minscale, maxscale): """ Scales a value in one range to another. """ # https://stackoverflow.com/a/5295202 return (maxscale - minscale) * (val - minx) / maxx - minx + minscale
0768fa72421a185aacb2bf78c04326422fb4a470
642,942
def clean_translation(translation: str) -> str: """clean a given translation and returne a cleaned translation""" translation = translation.strip() translation = translation.lower() translation = translation.replace("¿", "") translation = translation.replace("¡", "") return translation
e8635faf49bd314b0f8c906f9c256f8a5d8a705e
642,944
import subprocess import unittest def require_ffmpeg(test_case): """ Decorator marking a test that requires FFmpeg. These tests are skipped when FFmpeg isn't installed. """ try: subprocess.check_output(["ffmpeg", "-h"], stderr=subprocess.DEVNULL) return test_case except Exce...
d21ec9e960b8ee244c7142b1a9fb5c16e2a7212f
642,945
def gsutil_rm_rf_step(url): """Returns a GCB step to recursively delete the object with given GCS url.""" step = { 'name': 'gcr.io/cloud-builders/gsutil', 'entrypoint': 'sh', 'args': [ '-c', 'gsutil -m rm -rf %s || exit 0' % url, ], } return step
b41a56d2b3e8fd2efa6c46bbb3352d64a6a009d7
642,946
from typing import Dict from typing import Any def naive_bayes_best_params_surroundings(best_params: Dict[str, Any]) -> Dict[str, Any]: """Get best parameters surroundings for random forest.""" alpha = best_params["alpha"] return { "alpha": [alpha - 0.05, alpha, min(alpha + 0.05, 1.0)] }
835eed9de898dbe44791acd5deecbae3bda74ce3
642,947
def reduceBitsToBytes(formatdescbit): """ Reduce length precicion from bits to bytes in a field-length tuple list derived from Scapy. **depreciated** since not needed without scapy :param formatdescbit: list of tuples (fieldtype, fieldlengthInBits) :return: list of tuples (fieldtype, fieldlengthIn...
7968bee79413e64f5784ae76d8f89d8fb7637be5
642,948
import os def path_to_i07_nxs_02(path_to_resources): """ Returns the path to a second i07 nexus file. If it cant be found, raises. """ return os.path.join(path_to_resources, "i07-404877.nxs")
03574a5c7647941eed9e8afb85e381f0f04b4510
642,949
def find_disjoint_subsequences(li, seq): """ Returns a list of tuples (i,j,k,...) so that seq == (li[i], li[j], li[k],...) Greedily find first tuple, then second, etc. """ subseqs = [] cur_subseq_inds = [] for (i_el, el) in enumerate(li): if el == seq[len(cur_subseq_inds)]: ...
7599f23042a5fc789e4ce26e444595134c7ad882
642,950
def average_named_tuple(named_tuple_): """Return an averaged named-tuple.""" return type(named_tuple_)(*map(lambda x: x.mean().item(), named_tuple_))
3d690814d4b5a7725b846ee29c93cdc3b4e076b4
642,951
def issue329(*args): """ Don't emit unbalanced tuple unpacking if the rhs of the assignment is a variable-length argument, because we don't know the actual length of the tuple. """ first, second, third = args return first, second, third
3a47e411e90bfd2e5257eb77abf518b0cd15dc25
642,952
import hashlib def gen_md5(str_con): """ 把输入的数据转换成MD5 :param str_con: 输入的数据 :return: """ hl = hashlib.md5() hl.update(str(str_con).encode(encoding='utf-8')) return hl.hexdigest()
1aa6e41e31eb6b180124f207f20b5c2eb33ff348
642,954
import json def format_segment(seg): """ Formats a segment assuming it's an instance of class segment with elements filename, channel, speaker, start and stop times, label, and text :param: seg: segment object :return: dict: key/val pairs contain 'segment'-level information values of output...
247ddbc76f393a94a1dee6a531039e8fbfc7359c
642,955
import functools def compose(*functions): """Simple function composition""" def compose2(f, g): return lambda *a, **k: f(g(*a, **k)) return functools.reduce(compose2, functions)
948fb6985eea3598414643a7d173d77acb8d0774
642,956
def is_counting_line_passed(point, counting_line, line_orientation): """ To check if the point passed the counting line by the x coord if it left/right or y coord if it bottom/top. :param point: the object location. :param counting_line: the coordinates list of the area. :param line_orientation: the...
2a40fd0db9e2fd3e5c6c16eeb01cd77cd4606f69
642,957
import torch def MLP(channels: list, do_bn=False): """ Multi-layer perceptron """ n = len(channels) layers = [] for i in range(1, n): layers.append( torch.nn.Conv1d(channels[i - 1], channels[i], kernel_size=1, bias=True)) if i < (n-1): if do_bn: ...
7025647a66c30172628a7fe08b6d3b2d6951555f
642,958
def amin(a, axis=None, keepdims=False, initial=None, where=True): """ Returns the minimum of an array or minimum along an axis. Note: Numpy argument `out` is not supported. On GPU, the supported dtypes are np.float16, and np.float32. Args: a (Tensor): Input data. axis (...
722eb4483b9cc55bf22db522594a740679a2ca37
642,959
import time def wait_for_udf_to_exist(connection, udf_name, sleep_time=0.25, attempts=8): """ This should be called after a udf_put to wait for the udf to be stored on the server. """ iterations = 0 exists = False # Loop while the UDF is not found on the server while not exists: ...
ef8842ad45c3f39fa5936db3ca65497d06f5f4bf
642,960
def sortTable(tSkill): """ Sort tSkill by decreasing total damage """ # Order of the skills by decreasing total damage gDmgOrder = [ i[0] for i in sorted(enumerate([ float(t) for t in tSkill[2] ]), key = lambda x: x[1], reverse = True) ] for i in range(len(tSkill)): tSkill[i] = tSkill[i][gDm...
c62d624590a4cba2af7eb080500f62bf174c81c6
642,962
def printrule(r, yf, w=None): """:returns: a string representation of a rule.""" yfstr = ','.join(''.join('%s' % b for b in a) for a in yf) result = '%s\t%s %s' % ( yfstr, r[0], ' '.join(x for x in r[1:])) if w is None: return result return '%s %s' % (w, result)
b6d2d2bd625e212d469ea1c38573e8e752bbf966
642,963
def euclidienne(num_a, num_b): """ Distance euclidienne """ return abs(num_a-num_b)
8fa446d21414470429d7979f2180fec0e9945bd1
642,964
def siqs_choose_nf_m(d): """Choose parameters nf (sieve of factor base) and m (for sieving in [-m,m]. """ # Using similar parameters as msieve-1.52 if d <= 34: return 200, 272 if d <= 36: return 300, 546 if d <= 38: return 400, 1094 if d <= 40: return 500,...
c22ae4663fd4484622e477c8010bb165dac95808
642,965
def lookup_relevant(score): """Returns the string classifcation of the score""" category = "" if score > 2.0: category = "RELEVANT" elif score > 0.0: category = "PARTIALLY RELEVANT" else: category = "NOT RELEVANT" return category
c68f45afd16dfa67afd2415044f33c6187b88c03
642,966
from datetime import datetime def oem_to_datetime(oem_time_string): """ converts oem datetime record to python datetime object Args: oem_time (string): datetime string """ date, time = oem_time_string.split('T') year, month, day = date.split('-') hour, minute, second_fraction = ...
ba8de6545d8a903a05737d4bfe816767bb6933e0
642,967
from typing import List def verify_post_order(postorder: List[int]) -> bool: """ Offer 33. 二叉搜索树的后序遍历 """ stack, root = [], float('+inf') for i in range(len(postorder) - 1, -1, -1): if postorder[i] > root: return False while stack and postorder[i] < stack[-1]: ...
56bc0e52d007689a2d329e0eac20c8a996211fb7
642,968
def factorial(n): """ factorial: calculate factorial n! :param n: input number :return: n! """ fact=1 for i in range(1,n+1): fact*=i return fact
4e99cc2924f5622f426c7f8114adf181ceb5e884
642,970
def _qrcode_to_file(qrcode, out_filepath): """ Save a `qrcode` object into `out_filepath`. Parameters ---------- qrcode: qrcode object out_filepath: str Path to the output file. """ try: qrcode.save(out_filepath) except Exception as exc: raise IOError('Error tryi...
2f7d76fc1d01bae979c4d054ff17ccde4d8a6abf
642,971
def weighted_euclidean_midpoint(x, w): """ :param x: b x seq x dim :param w: b x seq x 1 :return: b x dim """ total = w.sum(dim=1) return (x * w).sum(dim=1) / total
c005e821616da257eadd85d1c68c3437ab1f75b9
642,972
def object_id(identifier, keep_version=False) -> str: """ Returns the core object_id of a CURIE, with or without the version suffix. Note: not designed to be used with a URI (will give an invalid outcome) :param identifier: candidate CURIE identifier for processing :param keep_version: True if the ...
95583bb23147d211799ece2009ae9d0dda6de0b1
642,973
def apply_controlled_gate(gate, control, target, psi): """Apply a controlled 2-qubit gate via explicit indexing.""" # To maintain qubit ordering in this infrastructure, # index needs to be reversed. # qubit = psi.nbits - target - 1 two_q = 2**qubit control = psi.nbits - control - 1 for g in range(0, 2*...
d37fd7c80a11a43640ef664c4a82ceba7b037fb9
642,974
import re def get_text(file): """Read text from a file, normalizing whitespace and stripping HTML markup.""" _text = open(file).read() _text = re.sub(r'<.*?>', ' ', _text) _text = re.sub('\s+', ' ', _text) return _text
9cc1bb58b2e29163d99d8012dd1206b9229600fa
642,975
def test_sort(data): """self-defining sort function""" return data.sort_values(by='Data', ascending=False)
bee6859abf61cea1e7d6d5d4def435bc1062c715
642,976
def msg_defaults(): """ sets default keys on message """ _msg_data = {} _msg_data.setdefault("num_avail", 0) _msg_data.setdefault("unit_type", "unknown") _msg_data.setdefault("campsite_name", "missing campsite name") _msg_data.setdefault("date_avail", "") return _msg_data
8ce082388d41f82455af6e1eaff649d62912ddd7
642,977
def to_bool(value: str) -> bool: """ Converts string to bool """ return str(value).lower() == 'true' if value is not None else False
033204c725e5143746740c8f8489719f15d1926e
642,979
def vectorize(input: str): """The input should be 3 bumbers seperated by spaces Returns a list of floats""" array = input.split(' ') return [ eval(array[0]), eval(array[1]), eval(array[2]), ]
aab2cabf9a5eb05b84d63967f2914e7b3dc6027f
642,980
import os def save_data_to_existing_file(data, file): """Save data to existing file Positional Arguments: data (list): list of data file (str): full path to file Return: tuple (sucess): (True, complete path to file) tuple (failure): (False, empty string) """ if o...
2f18851f3d8aca8662d8623ed2d0952017e2c80d
642,981
def listi(list_, elem, default=None): """ Return the elem component in a list of lists, or list of tuples, or list of dicts. If default is non-None then if the key is missing return that. Examples: l = [("A", "B"), ("C", "D")] listi(l, 1) == ["B", "D"] l = [{"A":1, "B":2}, {"A"...
ac2866ddfd794a6bf4b02a4d1079963979d3f2d1
642,982