content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_base_out_of_iri(iri: str) -> str: """Give an iri, returns an the ontology base name Args: iri Returns: str """ if "#" in iri: index = iri.find("#") return iri[:index] else: # for example if uri looks like: # http://webprote...
dee36030c6c830afd559805f66b89021a705ed55
668,104
def get_plain_texts(input_dict): """ Widget transforms Annotated Document Corpus to string. :param adc: Annotated Document Corpus. :param feature_annotation: Select a feature annotation. :param delimiter: Delimiter for token concatenation. :param include_doc_id: Include Document Identifier. ...
16fb2269cc590f40d9b9b5ca3010080a726773fc
668,105
import string def is_starting(token, alphabet=string.ascii_lowercase): """ Determines if the token starts a new word """ return len(token) > 1 and token.startswith(' ') and token[1].lower() in alphabet
6ba4ad1a5310b6a55f9c53301b5a551c983e6ec3
668,106
def embedded_certs(certificate): """Sets ups certs from filesystem""" def _setup(tls_policy_view): tls_policy_view.add_embedded_certs(certificate) return _setup
a2efaf9cf51a2c058cb7d3c3e328a13f7ca5993f
668,107
import sys def check_virtenv(): """ Checks if current script is running in virtual env """ return True if hasattr(sys, "real_prefix") else False
14c68e06e38345935857a607dc55d0dcf98a1dfb
668,108
import random def generate_name_prefix_f(): """Randomly generate a name prefix. """ prefix = random.choice(['Miss', 'Mrs', 'Ms', ""]) return prefix
aaf614df73511e8c2f15f5a2d965d054508887de
668,109
def create_term_query(key, values, query_type): """Return an all or any term query for es""" if query_type == "or": return [{"terms": {key: values}}] else: return [{"term": {key: value}} for value in values]
c26091100a102f6d311864b53362f6917dd6803f
668,110
import re def ishex(data): """ Helper method to check if the value is hex or not """ return bool(re.fullmatch(r"^0[x|X][0-9a-fA-F]+", data)) or bool(re.fullmatch(r"^[0-9a-fA-F]+[h|H]$", data))
8062fe345bc53c1b44206dda4fb271638315e671
668,111
def get_version(nb): """Get the version of a notebook. Parameters ---------- nb : dict NotebookNode or dict containing notebook data. Returns ------- Tuple containing major (int) and minor (int) version numbers """ major = nb.get('nbformat', 1) minor = nb.get('nbformat_...
d99d4487dfff7c85fbc0d77c5a8f45a9a5838fdb
668,112
from typing import Counter def check_duplicate_fields(field_names): """ Check that there are no duplicate in the `field_names` list of field name strings, ignoring case. Return a list of unique duplicated field names. """ counted = Counter(c.lower() for c in field_names) return [field for fiel...
1eb9bf82486a1e9e717154dfca91fae0ebc3ddd1
668,113
def get_access_token(request): """ Find access token in request in next order: - acc_token query param - X-Access-Token header - access.token body value (for POST, PUT, PATCH and application/json content type) Raise ValueError if no token provided """ token = request.params.get(...
aea859a6e937b5a6c855b142f53282c28ba8eefc
668,114
def tree_to_s2t(tree_str): """ linearized the phrase tree to token sequences. Args: tree_str:(TOP (NP (NNP EDUCATION) (NNPS ADS) (: :))) Return: s2t format: words: EDUCATION ADS : tokens: NP NNP NNPS : /NP """ stack, tokens, words = [], [], [] for tok...
cadf1b09dad21b34ac23695a32fe6cada7885a25
668,115
def get_client_class_name_from_module(module): """Being a module that is an Autorest generation, get the client name.""" # Using the fact that Client is always the first element in __all__ # I externalize that code in a class in case we need to be smarter later return module.__all__[0]
a8811200027b6c2ca969c758148f49256354ad76
668,117
import os def collect_extension(dirpath, extension, skips=[ "@Recycle", "Tests" ]): """ function to collect mxf files in a given directory, recursively Parameters ---------- dirpath: string path to search extension: string filetype skips: list of ...
560cb4088ec4fe1182f7613e4baa8851fa19f48d
668,118
import re def make_operand_re(instruction_class): """Deprecated Takes the given instruction class and creates a regex that can be used to get operands. """ re_string = instruction_class.__name__ for operand in instruction_class.operand_tup._fields: re_string += '[ ]*(?P<%s>[^\s]*),' %...
b6f98096ec2403403874eda8f59c2b9dc1ee3990
668,119
def to_wrapping_list(aws_list, key, wrapper_cls): """Wrapping List To OpenStack Horizon Format""" openstack_list = [] for value in aws_list.get(key): openstack_list.append(wrapper_cls(value)) return openstack_list
87d40558a1182ef6e74141e07ab5441c686f7d7c
668,120
def split_list(n): """will return the list index""" return [(x + 1) for x, y in zip(n, n[1:]) if y - x != 1]
9535321594884b62ebc87f34cc071c761c2722db
668,121
def build_train_and_test_features( df_columns, features_to_process, predict_feature, ignore_features): """build_train_and_test_features Order matters when slicing up datasets using scalers... if not, then something that is an int/bool can get into a float column and tha...
08a9e6dc7651d71a36b9a947145618ead1fa3cee
668,122
def otherFunc(): """ @description: i do literally nothing like the rest """ return "yo"
1280307309bd881e9be5e7a6c2f44ac4542ba1bc
668,123
def rule(cond, metric="foo", increment="1"): """ A rule for the custom metric policy """ return {"metric": metric, "increment": increment, "condition": cond, "combine_op": "and" }
f61fc7d0b4c87c63db000360caa9c2a0e7741682
668,124
import time def logarithmic_progress(iterable, verbose=True): """A funny type of progress bar I use a lot. This does two things: * Return a true/false flag if the iteration is a power of two, or the last iteration. Usually I want to save results at this point, or print an update to screen. * ...
ec85fbf67c50902949b61904036a7b5da0b5e211
668,125
import warnings import logging def driver_logger(dname): """Logger to be used from a driver plugin.""" warnings.warn( DeprecationWarning( "driver_logger() deprecated, you can use standard logging module instead." ) ) return logging.getLogger("mapchete.formats.drivers." + dn...
5c670a6a887570eb5ff96a86218b6770c67198c1
668,126
def nullish_coalescing(value, default): """ nullish coalescing utility call Provides a return of the provided value unless the value is a ``None``, which instead the provided default value is returned instead. Args: value: the value default: the default value Returns: ...
7c2afd1cd2deda0bfa5aa71bb956b1997d0fac40
668,127
def checkNumOfLines(expectedLineNum, actualLineNum): """ Args: expectedLineNum: expected number of molecular lines (int) actualLineNums: actual number of identified molecular lines (int, comes back from ADMIT task) Returns" Ture if inputs are equal in value, False otherwise """ ...
d95582775d67f977ccd76e740e82360781be1f2b
668,128
def convert_ft_to_psi(fthead, sg = None, W = None): """ Conversion formula for calculating head in psi if head in ft is known, as well as either the specific gravity or Specific weight (ex. W for water = 62.32 lb/ft^3 @ 68 deg C) ex: >>> x = tdh.convert_ft_to_psi(15.0, sg = 1.0) or >>> ...
3f0e5482ba7b10a3cd5d771f920a35f13094b499
668,129
import json import logging def load_json(filename): """ Read CIB node from JSON file """ cib_file = open(filename, 'r') try: j = json.load(cib_file) except json.decoder.JSONDecodeError as e: logging.error("Could not parse CIB file " + filename) print(e) return ...
0284ff36ebbfc6fe5b17b2cebe6199479c1f7193
668,130
import argparse def argparse_now(message): """ Usage: /now [OPTION] PORTFOLIO_CODE Plot today's return rate for a portfolio (currently valid for trading days only) /now [OPTION] STOCK_KEYWORD Get real-time chart for STOCK_KEYWORD Options: -h display help message ...
35e020f17169b7bffc00d731a4f62f3d26657a79
668,131
import math def nextpow2(n): """ Return the smallest power of two greater than or equal to n. """ return int(math.ceil(math.log(n) / math.log(2)))
0048fde09533378a28c05fccf17b3b2864e8717f
668,132
def extract_http_req_body(contents): """ Splits the HTTP request by new lines and gets the last line which is the HTTP payload body """ return contents.split(b"\n")[-1]
31966a68c0bb7522a454a9cdda769785eec3bb2f
668,133
def get_fns(C,assignee=None,created=None,handled_by=None,informed=None,status=None,tag=None,recurse=True,query=None,newer_than=None,tids=None,recent=False): """return task filenames according to provided criteria""" #raise Exception(assignee,created,informed) qry = "select * from tasks t,tasks_pri_comb_lean...
6da66ab72818488c3624e702477044731c1e01b8
668,134
from typing import Optional from typing import List import os def __selected_projects(projects: Optional[str], search_dir: str = ".") -> List[str]: """Produce a set of either all projects or a validated single project.""" # Collect list of dirs that are valid projects d = search_dir all_projects = [o ...
95f48c28400fee239a299ee2ecfe7b1a282ec20c
668,135
def serialize_value(value): """ Serialize a value in an DeepImageJ XML compatible manner. :param value: :return: """ if isinstance(value, bool): return str(value).lower() else: return str(value)
dcc4ac70c778460cc6e6494e37a5035ce0d96f41
668,136
from typing import Iterable from typing import Counter def number_of_clusters(_, labels: Iterable) -> float: """Number of total clusters. Args: _: Dummy, pass anything or None labels (Iterable): Vector of sample labels. Returns (int): Number of clusters. """ ret...
3beb16b847fecb434fcdd98b86695131c38f3072
668,137
from typing import Union def device_id_from_mac_address(mac_address: Union[str, bytearray]) -> str: """ Convert device's physical address to a device ID :param mac_address: MAC-address in dash/colon/spaced/concatenated format :type mac_address: str, bytes, bytearray :return: Device ID :rtype: ...
a18012bf6e9bfd691d31136510a0c5fff66951fe
668,138
import os import pickle def load(filepath, verbose=3): """Loading pickle files for input variables. Parameters ---------- filepath : str Pathname to store pickle files. verbose : int, optional Show message. A higher number gives more informatie. The default is 3. Returns ...
0919b61a087336b895afdee7d47667a5bfabf5e3
668,139
from typing import List def assert_optional_type_hints(contents: List[str]) -> List[str]: """ Find parameters with default value None and add Optional[type] to them. :param contents: list of lines in file :return: list of lines in file """ i = 0 while i < len(contents) - 1: line ...
d95a3eec4c3e2ef0874d5ee974c614eecdddc8a7
668,142
def filter_eeg(mne_eeg, channels): """Creates a 30 Hz 4th-order FIR lowpass filter that is applied to the channels channels from the MNE_EEG data. Args: mne-eeg - mne data strucutre of n number of recordings and t seconds each Returns: filtered - mne data structure after the filter has bee...
67632f187af24cfb1e6d149d8db7f28ee7335591
668,143
import torch def hinge_loss_rec(positive: torch.Tensor, negative: torch.Tensor, margin=1) -> torch.Tensor: """Hinge loss for recommendations""" dist = positive - negative return torch.sum(torch.maximum(margin - dist, torch.Tensor([0])))
42b888c45ca521dad7737b485ff48265c905bced
668,144
import socket def is_port_open(ip,port): """ *Previously named isOpen* Args: ip (TYPE): DESCRIPTION. port (TYPE): DESCRIPTION. Returns: bool: DESCRIPTION. """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(0.3) try: s.connect((ip, ...
e71422f3c6f586194a02631d4e1c7b712f815e0e
668,145
def set_recomputation_options(opts, allow_recompute=True, allow_stateful_recompute=None): # pylint: disable=unused-argument """Set re-computation options. Args: allow_recompute: Whether or not to re-compute instructions during training. If this...
d0e4a6fbaf23401f5e5bba2ec9759627880529fc
668,146
def worst_out(E, w, basis_superset_oracle, minimize=False): """最悪棄却貪欲法 計算量は、n:=|E|とし、基拡大集合オラクルの計算量をf(n)としたとき O(nlog(n) + nf(n)) Args: M: 独立性システム w: 重み関数(コスト関数) w: E → R+ basis_superset_oracle: 基拡大集合であるかどうかを判定する関数 minimize: Trueなら最小化、Falseなら最大化 Returns: 最小基または最大基 """ Q = tuple(sorted(E, key=w, r...
55bea7488fb7de2afb8e8d1433b0feec7796c6e4
668,147
import yaml def unicode_representer(dumper, data): """ Add a custom unicode representer to use block literals for multiline strings in unicode. """ if len(data.splitlines()) > 1: return yaml.ScalarNode(tag='tag:yaml.org,2002:str', value=data, style='|') return yaml.ScalarNode(tag='tag:yaml...
8dc8d1bd8c0bb7603ab72925a7518b15c83dae8d
668,148
def passthrough_scorer(estimator, *args, **kwargs): """Function that wraps estimator.score""" return estimator.score(*args, **kwargs)
4fe20ee2f611adc523eb70d58f170775cdcabf69
668,149
def convert_to_bundleClass_format(samcc_selection): """converts samcc selection from this library to original format used by bundleClass input: samcc-ready selection, list of helices, each helix a list of format [ chain_id(string), start_residue(int), stop_residue(int) ] output: BundleClass-ready selection, list of ...
3b9c20e3d337757a1d7926302b0d2fdec80410b4
668,150
def create_ca_file(anchor_list, filename): """ Concatenate all the certificates (PEM format for the export) in 'anchor_list' and write the result to file 'filename'. On success 'filename' is returned, None otherwise. If you are used to OpenSSL tools, this function builds a CAfile that can be us...
cc9eae17844be858f54369041849acba94f70890
668,151
def cmyk(c, m, y, k): """ this was taken from https://stackoverflow.com/questions/14088375/how-can-i-convert-rgb-to-cmyk-and-vice-versa-in-python """ rgb_scale = 1.0 cmyk_scale = 1.0 r = rgb_scale * (1.0 - (c + k) / float(cmyk_scale)) g = rgb_scale * (1.0 - (m + k) / float(cmyk_scale)) b...
eb7196e6e8ff5041b137adba3a8f87d855299581
668,152
def always_weekend(day_number: int) -> bool: # type: ignore """Return if day number is weekend mock for always.""" return False
2ba5f406cce2df31020de0e45bd7ff2d6c0b546a
668,153
def sequence_region(chrom_sizes): """ This function read from a chromatin size file generated by twoBitInfo and write the information to dict return a dict """ f = open(chrom_sizes, 'r') sizes = f.readlines() sizes_dict = {} for line in sizes: chrom_info = line.rstrip().split('\t...
ddeeec9fb0f378f47f9e6db95e8badaef2c2ca40
668,154
def Bulges(blue): """ Returns all bulges in strainds """ bulge_list=[] for i,res in enumerate(blue.bp_data): if res[2]=='EA': bulge_list.append(res[0]) return bulge_list
bdc60635b2938514d533e100efefc1283386419b
668,155
def uppercase_range(code1, code2): """ If the range of characters from code1 to code2-1 includes any lower case letters, return the corresponding upper case range. """ code3 = max(code1, ord('a')) code4 = min(code2, ord('z') + 1) if code3 < code4: d = ord('A') - ord('a') retu...
bf682dc8dcc2c1bb545ae7adf4065f346e92fa71
668,156
def int_to_bin_string(x, bits_for_element): """ Convert an integer to a binary string and put initial padding to make it long bits_for_element x: integer bit_for_element: bit length of machine words Returns: string """ encoded_text = "{0:b}".format(x) len_bin = len(...
e8590223d0581985f7dcd256fa0290878ba95f68
668,157
import random def random_generator(seed: int) -> random.Random: """The random number generator used in the tests.""" return random.Random(seed)
d6996d37479310237afa5c3e1cbdd1ced10a495b
668,158
def get_record_meta(record_list): """Get meta data of FASTA record. """ acc_code = record_list[0] organism = record_list[1] EC_code = record_list[2].replace("__", " ") species = record_list[3].replace("__", " ") note = record_list[4] return acc_code, organism, EC_code, species, note
9a1382bc9473d8da19cc9de9bdffec0e273cb4b8
668,159
def gc_skew(seq): """ Calculate GC skew (g-c)/(g+c) for sequence. For homopolymer stretches with no GC, the skew will be rounded to zero. Args: seq (str): Nucleotide sequence Examples: >>> sequtils.gc_skew('AGGATAAG') 3.0 """ g = seq.count('G') c = seq.count...
0fd8223d8ce87fd4f33f344f294ad70eb29bf252
668,160
def str_to_list(string, key_name=""): """Evaluates a string as a list. Checks if border characters are '[' and ']', to avoid bad typing. key_name : string (optional) Name of the parameter. Useful for error message. """ if string[0] == '[' and string[-1] == ']': return list(eval(stri...
fdbfe4314649b4797c2620b9cdc78026c7f24717
668,161
def process_method_argument(method, available_methods=("simpson", "riemann")): """Catches unknown integration methods on a python level. Deals with upper and lower case writing. """ if not (method.lower() in available_methods): err_msg = "{} is not a valid integration method\nChoose from {}.".f...
cbd9a110774af5e4208b8d98a1061e7d6966b4d2
668,163
def missing_fields(current_json, previous_json): """ Adding fields that were in previous but are not in current stats """ missing = { } for key, val in previous_json.items(): if current_json is not None and key in current_json: continue tp = type(val) if tp == s...
fbe44e2fa7ee6a8c29a17c9c09ff423670314663
668,164
def clip_grad_by_norm_(grad, max_norm): """ in-place gradient clipping. :param grad: list of gradients :param max_norm: maximum norm allowable :return: average norm """ total_norm = 0 counter = 0 for g in grad: param_norm = g.data.norm(2) total_norm += param_norm.ite...
462ff13b7b60b09ac9025805e19fe1228e67be41
668,165
import re def idsub(tag): """In aSc, "id" fields may only contain ASCII alphanumeric characters, '-' and '_'. Substitute anything else by '_'. """ return re.sub('[^-_A-Za-z0-9]', '_', tag)
3299b7a88e512e32686780e31e52b71565cf6944
668,166
def reverse_geometric_key(gkey): """Reverse a geometric key string into xyz coordinates. Parameters ---------- gkey : str A geometric key. Returns ------- list of float A list of XYZ coordinates. Examples -------- >>> from math import pi >>> xyz = [pi, pi, ...
0619ed7ee45efe646d5836c6f767b35217ea3f6f
668,167
import string def alpha2num(alpha, maxNumberOfOptions=8): """ Funtion to turn a single letter to its numerical correspondence (e.g., "A"==1, etc.); if error, return the input :param alpha: a single letter; or can be anything :return: the numeric correspondence of the input; or the input itself ""...
d0a832ad6c25ea236b98e4b14ca27db62c61bc2c
668,168
def get_object(model, **kwargs): """ use this function for query 使用改封装函数查询数据库 """ for value in list(kwargs.values()): if not value: return None the_object = model.objects.filter(**kwargs) if len(the_object) == 1: the_object = the_object[0] else: the_o...
565e4b4f990426a92870e2fdd630983d2717cc16
668,169
import json def to_json_string(obj): """Convert object as a JSON string.""" return json.JSONEncoder(indent=2).encode(obj)
5e6377365ec5f5a2550533af733b3c5babbd81fa
668,170
def get_payload(msg): """ Get the payload from the Message. email.message.Message.get_payload will be a list of Message objects when is_multipart() is True, or a string when is_multipart() is False https://docs.python.org/3.4/library/email.message.html#email.message.Message.get_payload @param m...
b3174f85148dc33cee68b5b7543a66b9f838a4bf
668,171
import json def make_base_config(config_file, kwargs, par): """ Make a config file for `fps_single.py`. Args: config_file (str): path to general config file kwargs (dict): extra dictionary items to put in it par (bool): whether we're going to be using this to make finge...
13c88ae5976881222af04bac282378fbea1de9b2
668,172
def sim_file_to_run(file): """Extracts run number from a simulation file path Parameters ---------- file : str Simulation file path. Returns ------- run : int Run number for simulation file Examples -------- >>> file = '/data/ana/CosmicRay/IceTop_level3/sim/IC7...
cdbd04a85da96b163da95595dc3313be2c64dec8
668,173
def calculate_number_of_pay_periods(period_payment, frequency, max_tax): """ Calculate the number of pay periods that it will take to pay off a tax burden Param: period_payment: (float) How much is being taken off per pay Param: frequency: (int) How many payments per year Param: ma...
6660bb5edae99cde5d98e86e53c8f82c40ad7cb7
668,174
def age_num_to_group(age): """ A separate data file containing normative values for MMSE is ordered by age groups. This function will convert the interval value of age in the OASIS data set to age groups in order to find and convert the T-score more easily. """ if 60 <= age <= 64: return...
40f9160414e111cf930e1f985c9f664c4a9dd59d
668,175
from typing import Tuple from typing import List import re def parse_mate_info_from_id( seq_id: str ) -> Tuple[int, str]: """Extracts mate information from sequence identifier. Args: seq_id: Sequence identifier. Returns: An integer representing the mate information and the sequence ...
00f9d91b259a51bfc7d7d810089f0af0805047ef
668,176
def coord2act(board, coords): """Convert coordinate to action.""" return coords[0] * board.shape[-1] + coords[1]
1d7aafe280ae7832eb756b8945a6d56bb3929305
668,177
from typing import Callable def bin_search(func: Callable, mi: int, ma: int) -> int: """Find the value where the function returns 0. The function should return -1 if the value is too low, 1 if the value is too high, and 0 if the value is correct. Args: func (Callable): The function to test mi...
73d75e6be9b2741291fd9fe0a6d6f54e48ab8b01
668,178
def cli(ctx, deleted=False): """Get a list of local files. Output: A list of dicts with details on individual files on FTP """ return ctx.gi.ftpfiles.get_ftp_files(deleted=deleted)
723c93e2a0f8f0d50753635732f12bbcd10dfd6b
668,179
def pgsql_local(pgsql_local_create): """Configures local pgsql instance. :returns: :py:class:`ServiceLocalConfig` instance. In order to use pgsql fixture you have to override pgsql_local() in your local conftest.py file, example: .. code-block:: python @pytest.fixture(scope='session') ...
6897edecbb8b93206a18b73fa2b26983ed36525b
668,180
from functools import reduce def multiply_ints_list(tokens): """ parse action to multiply integers in a VBA expression with operator '*' """ # extract argument from the tokens: # expected to be a tuple containing a list of integers such as [a,'&',b,'&',c,...] integers = tokens[0][::2] retu...
bf6c37d12532f81bc960b7d8ecc8c14d0fc2d997
668,181
def inter_packet_time(trace): """ For a trace, returns a list of floats that represent the time difference between two adjecent packets. @param trace is a list structered as follows: `[(time, direction)]` """ times = [] # From start to -1 and from 1 to end for elem, next_elem in zip(trace[...
323afd750004aaa1f80fbaa8d982339a092eb7a4
668,182
def decode_from_bytes(value, encoding="utf-8"): """Returns a string decoded from the given bytes. Args: value (bytes): The value to be decoded. encoding (str): The encoding. Returns: str: The value decoded from bytes. """ return value.decode(encoding) if isinstance(value, b...
cf8cd010402f47fdd93bc4dd487000e74d8e9d6e
668,183
def check_primitive_type(stmt): """i_type_spec appears to indicate primitive type. """ return True if getattr(stmt, 'i_type_spec', None) else False
b6fd19bc79f19e217b6b1e9c4932cace8c342ea3
668,184
def format_timedelta_str(td, precise=True): """Convert timedelta to an easy-to-read string value.""" (milliseconds, microseconds) = divmod(td.microseconds, 1000) (minutes, seconds) = divmod(td.seconds, 60) (hours, minutes) = divmod(minutes, 60) if td.days == -1: hours += -24 return f...
4e32176cbad8fab233a0372739f02c83d7079487
668,185
def valid_category(category): """ This function checks if the given category is valid """ if not isinstance(category, str): return "Invalid format. Category must be a string" if len(category.strip()) == 0: return "Invalid category. Category can't be empty" if len(category.strip()...
811e20a32dd5cbed4ff17f84cb3ac295fb0a5049
668,186
def get_data_for_table(ModelObject, sort, page): """ Queries ndb for PER_PAGE instances of ModelObject, sorted by sort. For use with /maps and /servers, etc. Returns dictionary for appending to template_values. """ PER_PAGE = 20 # number of table entries per page i...
d5f0a21e8a8927ea3864488f1312dec08edd6884
668,187
import argparse def parse_inputs(): """ Parses the command line input arguments. If there has not been an input or output grid specified a ValueError will be raised. The only accepted arguments for `precision` is "float" or "double"; any other input (including no input at all) will raise a V...
39470dd09088ab1a047cdea59e8a3cd311ad4823
668,188
def stringify(grid: dict, n: int) -> str: """Stringify with (0, 0) in the lower-left corner.""" rows = [] for y in reversed(range(n)): row = [] for x in range(n): value = grid.get((x, y), "-") row.append(value) rows.append(row) return "\n".join("".join(r...
728d1dced3a28f9c9435707adaa8794c64ce59ce
668,189
def get_winner(game): """ Returns the winner player if any, or None otherwise. """ return game["winner"]
e21c3bc0d5965f181361bf2edea78543b448b346
668,190
import torch def _reshape_tensor_with_nans(data): """Helper function to unroll padded RNN inputs.""" data = data.reshape(-1) return data[~torch.isnan(data)]
3b076d1613b218ec088303f7b0b96d746fae6d4c
668,191
def read_txt(f): """ Return information about the time, the location (x,y), and the neuron activity of the rat from an text Note that the data should be seperated by "," Parameter f: The name of that text Precondition: NONE (name can be anything) """ lines = f.readlines() number=len(li...
8a89c2f9ea6bd64cb6192daa8fdf0dd101f056dd
668,192
def results_config(current_page): """Returns a config for each source's search results page.""" return { "coindesk": { "page_url": "https://www.coindesk.com/page/" + str(current_page) + "/?s=Bitcoin", "item_XPATH": '//div[@class="post-info"]', # XPATH for the search result item ...
83c4e5789e89bd15aed33d77aeaf7b588bfa1d38
668,193
def find_google_fileid_tree(service, fileId): """Find the folder tree of a file Arguments: service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.com/sbi-rviot/goo...
7daaf3cda1f9677de87fa7f30d693f61806c62b7
668,195
def curve(t, acc_t, fast_t, dec_t, slow_t, fast, slow): """Returns a speed value between 0 and fast for a given t t is the time (a float in seconds), from zero at which point acceleration starts typically t would be incrementing in real time as the door is opening/closing acc_t is the accelerat...
646ddccdd8d27d3fc949469868afb1c59ff9b740
668,196
def word_preprocessing(word, ignore_non_alnumspc=True, ignore_space=True, ignore_numeric=True, ignore_case=True): """ Function for word preprocessing | | Argument | | word: a string to be processed | | Parameter | | ignore_non_alnumspc: whether to remove all non alpha/numeric/space characters | | ignore_space...
b5c1737cc5b92337e05e0c1f58950146d94f95e4
668,198
def floyd_warshall(weight): """All pairs shortest paths by Floyd-Warshall :param weight: edge weight matrix :modifies: weight matrix to contain distances in graph :returns: True if there are negative cycles :complexity: :math:`O(|V|^3)` """ V = range(len(weight)) for k in V: for...
018a9908a59269532256b556619936f331261390
668,199
from datetime import datetime def m_get_date_to_now_years(seq, args=None): """ 返回传进来的时间字符串距离现在的年数 args保留小数点位数 :param seq: 日期字符串 :param args: 保留小数点位数 :return: 距离现在的年数 example: :seq '2016-01-01' :args 2 :return 0.16 "...
e0728df6b5b774b8e5b56550a78d33d521ca9f76
668,200
import traceback def capture_traceback( excinfo ): """ This should be called in an except block of a try/except, and the argument should be sys.exc_info(). It extracts and formats the traceback for the exception. Returns a pair ( the exception string, the full traceback ). """ xt,xv,xtb = ex...
b77926fbd3bb2e36a5f57b3e8f1132e20c8530b1
668,201
from datetime import datetime import calendar def get_current_month_time_ends(): """ 获取当月开始结束时刻 :return: """ today = datetime.today() _, days = calendar.monthrange(today.year, today.month) start_time = datetime(today.year, today.month, 1, 0, 0, 0) end_time = datetime(today.year, today....
4434566afc4ecebc2378080ad739a538c9d4bee2
668,203
def test_api_key(client, BinanceAPIException): """Checks to see if API keys supplied returns errors Args: client (class): binance client class BinanceAPIException (clas): binance exeptions class Returns: bool | msg: true/false depending on success, and message """ try: ...
56f189b63b6418b044c21360ae97360afa194c7b
668,204
import re def urlcheck(url): """check if url is valid for agrimet api Arguments: url {string} -- http://www.usbr.gov/pn-bin/ """ match = True pattern = r"https?:\/\/www\.usbr\.gov\/?.*?$" regex = re.compile(pattern) if regex.search(url) is None: match = False r...
963e24b542dec25e32773f8d25c21488585dd38d
668,205
def find_primary_and_secondaries(users): """Given a list of users with the same username, find the user who should be the primary user into which the other users will be merged. Return a tuple (primary_user, list_of_secondary_users) """ actives = [each for each in users if each.is_active] # If there...
6e776028ffdf60acdb07314c0aeff325c9d2fbe9
668,206
def listAddition(list, k): """do any two of the numbers from the list add up to k""" for idx in range(len(list) - 1): add1 = list[idx] for num in list[idx+1:]: if add1 + num == k: return True return False
54c0bf768b30df9e73cee5d56f0b7a9b8e2a75c6
668,207
import json def json_update(json_old, new_dic): """将字典的值更新到json串中""" if len(json_old) > 8 and isinstance(new_dic, dict): json_dic = json.loads(json_old, encoding='utf-8') json_dic.update(new_dic) json_new = json.dumps(json_dic, ensure_ascii=False) return json_new else: ...
820ae901b66935dfa24b717b93eed0a4d7a5c0a0
668,208
def _extract_open_mpi(version_buffer_str): """ Parses the typical OpenMPI library version message, eg: Open MPI v4.0.1, package: Open MPI Distribution, ident: 4.0.1, repo rev: v4.0.1, Mar 26, 2019 """ return version_buffer_str.split("v", 1)[1].split(",", 1)[0]
a20d1ed65f9b40c50ec5c28a17fd73f11a470c9e
668,209
def validator_proxy_contract(deploy_contract_on_chain, web3_home, system_address): """The plain validator proxy contract.""" contract = deploy_contract_on_chain( web3_home, "TestValidatorProxy", constructor_args=([], system_address) ) assert contract.functions.systemAddress().call() == system_a...
ae7e28975fd6b2b3dc5a6346c9dec3f5cb732791
668,210