content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _translate_ip_xml_json(ip): """ Convert the address version to int. """ ip = dict(ip) version = ip.get('version') if version: ip['version'] = int(version) # NOTE(maurosr): just a fast way to avoid the xml version with the # expanded xml namespace. type_ns_prefix = ('{http...
43656a88ce2514d18c0e4fc92ab38622f2486c35
684,077
def replace_chars(string, chars=r':\/|<>?*"', replacement=''): """ Return `string` with any char in the `chars` replaced by `replacement`. Defaults to replace problematic/invalid chars for filenames/paths. """ for c in string: if c in chars: string = string.replace(c, replacemen...
4a4af79cc960e1052be13958a733eb29a075ad12
684,078
import calendar def ydhms2decyr(year,doy,hh=0,mm=0,ss=0.0): """ ydhms2decyr(year,doy,hh,mm,ss) Convert from Year, Day-of-year to decimal year """ #ms,sec = modf(float(ss)) #ms = ms * 10e5 #dto = dt.datetime(int(year),,,int(hh),int(mm),int(sec),int(ms)) #dto = dto + dt.timedelta(days...
8506afd1916aa2fe71b86312c741af9484b90893
684,079
import re def unify(x): """ Turn string or list of strings parts into string. Braces are placed around it if its not alphanumerical """ # Note that r'[\.\w]' matches anyting in 'ab_01.äé' if isinstance(x, (tuple, list)): x = ''.join(x) if x[0] in '\'"' and x[0] == x[-1] and x...
31d195beda8db853ec83ec7d6f6716da374c24dc
684,080
import string import secrets def code_verifier(length: int = 128): """ Return a cryptographically random string as specified in RFC7636 section 4.1 See https://datatracker.ietf.org/doc/html/rfc7636#section-4.1 :param length: length of the generated string, minimum 43, maximum 128. Defaults t...
9e29a98fa9bf26f19a251098b4f656022d3de8ee
684,081
def crop(image, rectangle): """ Crop out input image's fragment specified by the rectangle. :param image: input image :param rectangle: rectangle, which indicates cropped area :return: cropped original image fragment """ x, y, w, h = rectangle return image[y:y + h, x:x + w]
5e08f917878954a19141c631e79562f110a27b61
684,082
def lookup_newsletter_recipients(resource): """ Callback function to look up the recipients corresponding to a distribution list entry (in this instance: send all newsletters to orgs) Args: the (filtered) resource Returns: a list of pe_ids of the rec...
e68ddf37cb5b879fa91514fe21fa0f7e9ac153e5
684,083
def access_token(application, rhsso_service_info): """get rhsso access token""" return rhsso_service_info.access_token(application)
4135c45e5d32205586a4ed01f736092303df990d
684,084
import os def open_book_names_list(base_path, book_paths): """ Opens the file names for the books to be processed :param base_path: the path to the file directory :param book_paths: the file name containing the book file names :return: a set containing all of the file names """ with open(...
c6c8419ccd5f64a8e47df0d7a2aa8f3668b096b7
684,085
def lex_tokenize(tokenized_sentence): """Returns a list of lexes from a given tokenizer.TokenizedSentence instance. Each lex is represented as a 3-tuples of (start, end, token).""" return [(lex.begin, lex.end, lex.text) for (token, lex) in tokenized_sentence.as_pairs()]
fe47f9a327d4e8ac7ad65394426172746d72f0f6
684,086
def ensure_list(config): """ ensure_list Ensure that config is a list of one-valued dictionaries. This is called when the order of elements is important when loading the config file. (The yaml elements MUST have hyphens '-' in front of them). Returns config if no exception was raised. This...
56397e3eb6ab98d40392a668112febc77f11d9cc
684,087
import os def splitall(loc): """ Return a list of the path components in loc. (Used by relpath_). The first item in the list will be either ``os.curdir``, ``os.pardir``, empty, or the root directory of loc (for example, ``/`` or ``C:\\). The other items in the list will be strings. Adapted...
ad8b0b75ba38b967a5e231582313962b40263bff
684,088
from datetime import datetime def json_serial(obj): """JSON serializer for objects not serializable by default json code""" # yyyy-MM-dd'T'HH:mm:ss.SSS strict_date_hour_minute_second_millis if isinstance(obj, datetime): tz_string = "Z" serial = "%s.%03d" % ( obj.strftime("%Y...
3f1b6daf4309a32d18a221be14c01662358c40b0
684,089
def generate_source(email): """Generate a source code to be used in links inside an email""" return u"ev_{date}_{uuid}".format( date=email.created_at.strftime('%Y%m%d'), uuid=email.uuid)
d77a2f669b200d3ff66dc7eaff9ae7b192c37673
684,090
def get_user_age_from_userid(users, userid): """ From the user id we will get an age. I created a dictionary to find the right user records. """ byid = {} for d in users: n = d['id'] byid[n] = d user = byid[userid] return user['Age']
022daad9109bd189b4167d1457ab873313055d98
684,091
from pathlib import Path def make_save_path(save_path, net_name, net_number, epochs): """make a unique save path for model and checkpoints, using network architecture, training replicate number, and number of epochs""" save_path = Path(save_path).joinpath( f'trained_{epochs}_epochs', f'ne...
e4462c9e5d422008a79f8062cc446d069bff42e9
684,092
def plugin_type(): """ Type of plugin this is """ return ['vip']
b69309cbc6d4ed0e57c588197adf8605ca2c952b
684,093
from typing import Any from typing import Type from enum import Enum def dict_key_to_raw(key: Any, keytype: Type) -> Any: """Given a key value from the world, filter to stored key.""" if not isinstance(key, keytype): raise TypeError( f'Invalid key type; expected {keytype}, got {type(key)}....
9853507829070033b1535783da6ba0c3bfd573e2
684,094
import os def terminal_name(): """Return the name of the terminal.""" return os.environ.get('TERM_PROGRAM', '')
29ccdf354b5f67b2633828fbec63c0b930389e36
684,096
def render_path(path_to_item): """Returns a string representation of a path""" result = "" for pth in path_to_item: if isinstance(pth, int): result += "[{0}]".format(pth) else: result += "['{0}']".format(pth) return result
1deb40ad55ebd253c16e8dcc50198244b5928887
684,097
def circulation_is_item_available(item_pid): """.""" return True
639927c806be3d4b47f341e33a1bef7621dff1e6
684,098
def alter_board(board, player, cell): """Alter board string for player input""" board = list(board) # enter player letter in supplied cell board[cell - 1] = player return ''.join(board)
895b7e592f3ba530e4c8d554a5c07f5823b1b4b1
684,099
import torch def cov(m, rowvar=False): """Estimate a covariance matrix given data. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, `X = [x_1, x_2, ... x_N]^T`, then the covariance matrix element `C_{ij}` is the covariance of `x_i` and `x_j...
5b7d0c16741d94e80c4ae36c9b0c83e0c1ae5c21
684,100
import os def copy_fixtures_dir(workspace, fixtures_dir): """ Copy fixtures_dir to a temp workspace. Return path. """ workspace.run("cp -R {} fixtures/".format(fixtures_dir)) return os.path.join(workspace.workspace, "fixtures")
677114d3211acf0f056d2f9abec2a37f6a3f664e
684,101
def day(): """ Return millis for a day :return: 24 * 60 * 60 * 1000 """ return 86400000
aeff1ea1ab80c97fc0cf8c11bbda5bca24520f3c
684,102
def process_notebook_name(notebook_name: str) -> str: """Processes notebook name :param notebook_name: Notebook name by default keeps convention: [3 digit]-name-with-dashes-with-output.rst, example: 001-hello-world-with-output.rst :type notebook_name: str :returns: Processed notebook na...
0ac2d9a768a4cf6eb26844336d49b2d3e91c159d
684,103
import json import pkg_resources def get_formats(): """ returns a list dicts providing info about file formats and mime types :return: list dicts providing info about file formats and mime types :rtype: list """ return json.loads(pkg_resources.resource_string(__name__, 'formats.json'))
0d59354e98acca5be8e7af584baeda1a0d5901f9
684,104
import re def sign_transform(string): """Oracle 符号转换函数, 目的是转换日期加减格式到python格式""" pattern1 = re.compile(r'(?:to_date|date)', re.IGNORECASE) # 处理日期转换 pattern2 = re.compile(r'([-+]) *(\d*)\b,') # 处理加减日期法 pattern3 = re.compile(r'(\bdate\b\s*?)(\'.*?\')', re.IGNORECASE) pattern4 = re.compile(r'([a-zA...
93e35d6e472cfda063aa0147711fa96025a942eb
684,105
def integerize(num, count): """Calculate and return integer value if result is integer""" calc = num * count calc = int(calc) if calc.is_integer() else calc return calc
7f45ca0ee30f49ab0d12df8f7641c7e3a32855f1
684,106
import requests def get_redirected_url(url: str) -> str: """ Given a URL, return the URL it redirects to. Args: url (str) """ r = requests.get(url) return r.url
fb2b2a848ef528686e8c7e197dee2962544b3097
684,107
def data_group_details_result(): """As returned by DM `GET` """ return { '_id': 123, 'columns': [ {'type_': 'date', 'name': 'end date'}, {'type_': 'date', 'name': 'Start Date'}, {'type_': 'string', 'name': 'Ticker'}, {'type_': 'string', 'name':...
e974bcae1b3a358eecd19b9b3b27acf65ba0cfa7
684,108
def _find_var_dictionary(table, dict_name=None, dict_type=None): ############################################################################### """Find and return a var_dictionary named, <dict_name> in <table>. If not found, return None""" var_dicts = table.find("var_dictionaries") target_dict = None ...
fcd8519dd3b2b26ae6d8794e5b67a30b08b8060b
684,109
def return_top(scores, metric, x): """ :param scores: Pandas DataFrame with scores :type scores: Pandas DataFrame :param metric: String value for what score is desired ("Growth Score", "Value Score", "Momentum Score", "Score") :type metric: str :param x: Integer number of top stocks to return ...
b6dcdd3c89a21d285d35f2b15aba7c4a988c6da0
684,110
def get_qa_Z_range(): """ Returns qa Z range """ return (0.0, 130.0) # in mm
3c0a5f04407519119f7b8cd361d02a08ce879e9d
684,111
import textwrap def explain() -> str: """Explain Person Action Object""" return textwrap.dedent( """\ Person Action Object (PAO) The PAO is a system of encoding where you attribute a specific Person with an Action that includes an Object. This is a composite object which you c...
5f888831c7e1125627ac5d25e049bea6569ad8f5
684,112
def CollateDeps(deps_content): """ Take the output of deps_utils.GetDepsContent and return a hash of: { submod_name : [ [ submod_os, ... ], submod_url, submod_sha1 ], ... } """ spliturl = lambda x: list(x.partition('@')[0::2]) if x else [None, None] submods = {} # Non-OS-specific DEPS always override OS-...
a3c43e14e45b5478bf2859c2d8ea7b7bac857d99
684,113
def _encode_none(name, dummy0, dummy1, dummy2): """Encode python None.""" return b"\x0A" + name
47bb28d3ecb4e16cf2314bf51d4495589939b38f
684,114
import re def match(expr, val): """ Support method: provide matching to templates. """ return re.match(expr, val)
2e10a4d989b8de9b5845b2aa65dd15d9797ede32
684,115
def clean_names(lines, ensure_unique_names=False, strip_prefix=False, make_database_safe=False): """ Clean the names. Options to: - strip prefixes on names - enforce unique names - make database safe names by converting - to _ """ names = {} for row in lines: ...
00ade5b354cbe291ffaf26b19fbc80aac336921e
684,116
import argparse import os def _parse_args(): """Parses args, set default values if it's not passed. Returns: Object with attributes. Each attribute represents an argument. """ print('---------------------- Args ----------------------') parser = argparse.ArgumentParser() parser.add_argument( ...
cb5b352b16babb07fadf52225087eafbd2cc6ae8
684,117
def has_record(soup): """Return True if the input tree contains a mathematician record and False otherwise.""" if str(soup) == "Non-numeric id supplied. Aborting.": # This is received, for instance, by going to # http://genealogy.math.ndsu.nodak.edu/id.php?id=999999999999999999999. r...
ac02430e798b9588d9a09996d6a9b87154c447d5
684,118
def parity(x,N,sign_ptr,args): """ works for all system sizes N. """ out = 0 s = args[0] # ##### # count number of fermions, i.e. 1's in bit configuration of the state # CAUTION: 32-bit integers code only! f_count = x & ((0x7FFFFFFF) >> (31 - N)); f_count = f_count - ((f_count >> 1) & 0x55555555); f_count = (...
c6cc68eae3941c76930a8bd2df5fd67b8b491e5a
684,119
def scenegraph_to_json(sg): """ Dump an "SceneGraph" object to a dict that's used for evaluation. The output will be saved as json. Args: sg (SceneGraph): Returns: dict: contains predictions for one image. """ boxes = sg.pred_boxes.tensor.numpy().tolist() # for vg evalu...
2a39a81dfe6fcc14b8528c08bdad9521f35461db
684,120
import hashlib def get_md5(file): """Get the md5 checksum of an input file. Arguments --------- file : str Path to file for which compute the checksum. Returns ------- md5 Checksum for the given filepath. Example ------- >>> get_md5('samples/audio_samples/exa...
54386f58894bbebeaf280fa008ed7bcecc6c440e
684,121
def comp_nb_circumferential_wire(self): """Return number of adjacent wires in circumferential direction Parameters ---------- self : CondType22 A CondType22 object Returns ------- Nwppc_tan: int Number of adjacent wires in circumferential direction """ return 1
4a24f49cad93e2d8c48a8601691299cd91b67e40
684,123
def process_mmdet_results(mmdet_results, cat_id=0): """Process mmdet results, and return a list of bboxes. :param mmdet_results: :param cat_id: category id (default: 0 for human) :return: a list of detected bounding boxes """ if isinstance(mmdet_results, tuple): det_results = mmdet_resu...
d4df0645bd8fb9af2d5500e84f5ece3aec933418
684,124
def assemble_subpeak_record(subpeak, celltype_activations, sequence): """ Assemble the FASTA record of sequence and activation """ # make the header header ='\t'.join([s for s in subpeak]) header = '>' + header # make the activation string activation = ';'.join([ct+' '+str(score) for (ct,score)...
5bddb16130dba20bb9d1c4f341d842371a71838a
684,125
import argparse import sys def parse_args(): """Argument parser for this script """ parser = argparse.ArgumentParser(description='Test CIFAR-10 classification performance using XNOR-Net') parser.add_argument('--model', dest='model_file', help='XNOR-Net trained model file in .npz format') parser.ad...
013595659ddbc0b7a3e3bb521c5d9edfbec783ed
684,126
from typing import Dict def is_state_nncf(state: Dict) -> bool: """The function to check if sate is the result of NNCF-compressed model.""" return bool(state.get("meta", {}).get("nncf_enable_compression", False))
bfa60e69eb54e287b44950edc0bdfafcaa15d1b5
684,127
def read_split(split_filename): """ Return a list of pdb codes included in the split. """ print('Reading split from file', split_filename) with open(split_filename, 'r') as f: pdbcodes = [t.strip() for t in f.readlines()] return pdbcodes
651f55c40c15ded4fc103ac37db4aa96891c5201
684,129
def catch_error(something): """Try catch an exception. __Attributes__ something: Where we will search for Exception. __Returns__ something if not error or "" if error is. """ try: something except IndexError: something = "" print("An Index Error!") ...
783f6e702fdda15c21ca5ffabe66be8fc86d5cdf
684,130
def smooth(signal, owidth, edge_truncate=False): """Replicates the IDL ``SMOOTH()`` function. Parameters ---------- signal : array-like The array to be smoothed. owidth : :class:`int` or array-like Width of the smoothing window. Can be a scalar or an array with length equal...
3235de6152e9b63e074816cc3bd34152dc0ac43e
684,131
def clean_info(package_dict: dict) -> dict: """ Only keep `name` and `home-page` keys. Arguments: package_dict: Package information. Returns: Cleaned-up information. """ return {_: package_dict[_] for _ in ("name", "home-page")}
e20bb748b9322d94e70e7b53f4ab76e2ab9f61ee
684,132
def isIncreasing(l): """Testet array_like `l` auf ansteigend-geordnete Werte.""" for i, elem in enumerate(l[1:]): if elem <= l[i]: print("Kein Anstieg bei: {}->{}".format(l[i], elem)) return False return True
9bbaf68fb83ae495bb0cb408022e831189e0ff65
684,133
def make_complete_graph(num_nodes): """ Return a dictionary that represents a complete Digraph for the given number of nodes. :param num_nodes: nodes in the graph. :return: the dictionary representing a complete directed graph. """ graph_representation = {} for node in range(0, num_node...
8f67b49d197f9c70d02ad93ebe2a51c3f39f5a7c
684,134
def flipper(x: float) -> float: """Convert Tanimoto similarity into a distance Args: x (float): Tanimoto similarity Returns: float: Distance """ return x * -1 + 1
eae0462560b46dac95833a58d91f29b8a0b7e36c
684,135
def extended_euclidean_algorithm(a, b): # @param ax + by = gcd(a,b) """ Based on the fact that: b % a = b - (b // a) * a\\ gcd(a, b) = gcd(b%a, a) """ if a == 0: return b, 0, 1 gcd, x1, y1 = extended_euclidean_algorithm(b % a, a) x = y1 - (b//a)*x1 y = x1 return (gc...
002bcc088eb065ee6c8718bb0e06b57aa80020f1
684,137
def cidade_pais(cidade: str, pais: str, populacao: int = 0) -> str: """ -> Aceita o nome de uma cidade, o nome do país e a população dessa cidade, retorna essas informações formatadas. :param cidade: Nome da cidade. :param pais: Nome do país. :param populacao: Número da população da cidade....
55933630a3bdcc8b6d845b101b5c67baa95f957a
684,138
def string_to_bits(str): """ string_to_bits Function Converts a Pythonic string to the string's binary representation. Parameters ---------- str: string The string to be converted. Returns ------- data: string The binary...
2d86c9cf26b45adb81a0df37b5e0b7bcb5399f06
684,139
def alipay_ptn_check(ptn_obj): """ check alipay notify """ if ptn_obj.trade_status != "TRADE_FINISHED": return (True, 'trade status: %s' % ptn_obj.trade_status) return (False, None)
8e03b9f51e5288df3a281ebd3df635e07e1740e1
684,140
from typing import Tuple def valid(effective_kernel_size: int) -> Tuple[int, int]: """No padding.""" del effective_kernel_size return (0, 0)
0e02913f330362580da2ebf3749f17e35cd41260
684,141
import requests import json def select_equities(country=None, sector=None, industry=None): """ Description ---- Returns all equities when no input is given and has the option to give a specific set of symbols for the country, sector and/or industry provided. The data depends on the combinatio...
8aa3ef764282283c10fa9920a73456655bb9cecb
684,142
import torch import math def uniform_binning_correction(x, n_bits=8): """Replaces x^i with q^i(x) = U(x, x + 1.0 / 256.0). Args: x: 4-D Tensor of shape (NCHW) n_bits: optional. Returns: x: x ~ U(x, x + 1.0 / 256) objective: Equivalent to -q(x)*log(q(x)). """ b, c, ...
22f1cfe6b66ac11788a15edb281b6dee4e213654
684,143
def remove_underscore(text): """ Call this on variable names and api endpoints, so that BERT tokenizes names like 'find_place' as 'find place'. """ return text.replace("_", " ")
a91b33c4962881dbc68e90f7464e021dc615af32
684,144
import torch def random_mask_input_ids(input_ids, mask_token_id, exceptions, prob=0.15): """ exceptions: list, token ids that should not be masked """ probs = torch.rand(input_ids.shape) mask = probs < prob for ex_id in exceptions: mask = mask * (input_ids != ex_id) selection = [] ...
65128f55ba0d4273ef0c1c1af07f6d1acfcecb48
684,145
def filter_contacts(cmap, threshold=0.2): """Remove low score contacts from contact prediction list. :param cmap: Contact prediction map. :type cmap: :class:`~conkit.core.contactmap.ContactMap` :param threshold: Threshold, defaults to 0.2. :type threshold: float, optional """ cmap.sort('ra...
7820aed8394f1886fc0af966e31b83f2203848ca
684,146
import argparse def parse_args(*args): """ Parses command line arguments Returns a tuple of (nexus, taxon1, taxon2) """ descr = 'Calculate rates from the nexus for the two taxa' parser = argparse.ArgumentParser(description=descr) parser.add_argument("nexus", help='nexusfile') pars...
6e5843f60234a3d72580b69cb97bc83296770f67
684,147
import sys def is_merge(): """ Must check that the second parameters indicates merge, and there is no more parameters (last index is 2, hence length 3). """ try: commit_type = sys.argv[2] except IndexError: return False else: return commit_type.lower() == "merge" an...
e617fdb424f0be8982a9bd6d2daa615ad0d1ff8a
684,148
def split_seconds(seconds: int) -> dict: """This function converts seconds into a dictionary by splitting seconds without year, month, day, hour, minute and second when possible. :param seconds: seconds that will be converted Example: >>> from phanterpwa.tools import split_seconds >>> ...
babe5e8b304ad70b19fff21f4e0036d2c3f43c25
684,149
import os def getFileList(directory): """ Get list of graph files in directory""" ls = [] for (root, _, filenames) in os.walk(directory): for filename in filenames: ls.append(os.path.join(root, filename)) return ls
b86ee4d8bc0ff1715d3ca83618e0747a02c16e4e
684,150
import struct def vec_to_u64(buf): """Converts a <= 8 byte buffer to a 64-bit integer. The conversion is unique for each input size, but may collide across sizes.""" n = len(buf) assert n <= 8 if n >= 4: lo = struct.unpack("<I", buf[0:4])[0] hi = struct.unpack("<I", buf[-4:])[0] ...
b196c3efc7dbd79e3c45c60d2e4060332989326d
684,151
def _as_set(spec): """Uniform representation for args which be name or list of names.""" if spec is None: return [] if isinstance(spec, str): return [spec] try: return set(spec.values()) except AttributeError: return set(spec)
3c150b4072b169ec6cbe69ce583007e694342d78
684,152
def gps_time_2_beidou_time(gps_time_sec): """Convert time from seconds since GPS start into BeiDou time (BDT). Input: gps_time_sec - Time in seconds since GPS reference date & time [s] Output: bdt - BeiDou time [s] (time in seconds since BeiDou time reference) Author: Jonas Beuchert ...
fe6f79c81924f89f2b75788b6fc49a0dc4e82161
684,153
def mafd2(): """Create a test fixture for major affective disorder 2. Query should not include a "pediatric_disease" Extension object. """ return { "id": "normalize.disease:MAFD2", "type": "DiseaseDescriptor", "disease_id": "mondo:0010648", "label": "major affective disor...
967a2b281ca2e2d5e6e8722b16edbb3ff4fcab3d
684,154
import base64 import json def encode_data(data): """Return a base64 encoded json dump.""" encoded = base64.b64encode( json.dumps(data).encode('utf-8') ) assert len(encoded) < 250 * 1024 return encoded
ddb844d506dc9218845cfe3cefceb021401f2f73
684,155
import math def getUnitCost(demand: int) -> float: """ Implementation of decreasing unit cost: Unit cost drops as demand/production increases. """ average_fixed_cost = 2.5 weight = 0.75 average_variable_cost = weight*math.log(demand) return average_fixed_cost + average_variable_cost
7cf3fe49742cc078f5b178171753738e18ac36bb
684,156
from pathlib import Path import tempfile def tmpdir(tmpname: str = "haku") -> Path: """Geenrate a temporary directory""" tempfile.mkdtemp() return Path(tempfile.gettempdir()) / tmpname
2f6172c314403c535de6f39ed77e2c02b05b361f
684,158
from typing import Dict from typing import Union def format_sum_formula(sumform: Dict[str, Union[int, float]], break_after: int = 99) -> str: """ Makes html formated sum formula from dictionary. >>> format_sum_formula({'C': 12, 'H': 6, 'O': 3, 'Mn': 7}) '<html><body>C<sub>12 </sub>H<sub>6 </sub>O<sub>...
c38c273296884f268602a1f914dd5be52df4c904
684,159
def get_iwp_label_key( iwp_label ): """ Retrieves a key that locates the supplied IWP label within the underlying dataset. The key returned locates the label both temporarly and spatially. Takes 1 argument: iwp_label - IWP label to locate. Returns 1 value: label_key - Tuple identify...
e5814e14f3d1b4c40074e4429ae5729ea7087321
684,160
import yaml def template_params(path): """ Return parameters as dict from a YAML template file. """ with open(path, "r") as file: return yaml.safe_load(file)
5bfc8d8d107fb517fa9f76877dc45a316c0e81ef
684,161
def _mnl_transform_deriv_c(*args, **kwargs): """ Returns None. This is a place holder function since the MNL model has no shape parameters. """ # This is a place holder function since the MNL model has no shape # parameters. return None
a40b35679fbefd0c1c0e289c91ea48765784f73f
684,163
def _pad(slist, n, c=" "): """_pad(slist, n, c=' ') pads each member of string list 'slist' with fill character 'c' to a total length of 'n' characters and returns the concatenated results. strings longer than n are *truncated*. >>> >>> _pad(["this","that","the other"],9," ") 'this tha...
45e9ee4f981f59b85be07fb961ec5db751dcb3ee
684,164
def _ensure_trailing_slash(url: str) -> str: """Return url guaranteed to end in a slash""" return url if url.endswith("/") else f"{url}/"
84cce81a52b4e2c029a6dc3cb1a9bfb0b6dc25ea
684,165
def _scoped_name(name_scope, node_name): """Returns scoped name for a node as a string in the form '<scope>/<node name>'. Args: name_scope: a string representing a scope name, similar to that of tf.name_scope. node_name: a string representing the current node name. Returns A string representing a sc...
4e3ff71cb6ac74adc57637ba6ba5def59004ec6e
684,166
def process_claim(claim): """Convert a claim row into a set of points""" claim_number, details = [i.strip() for i in claim.split('@')] # strip the leading # claim_number = int(claim_number[1:]) coordinates, area = [i.strip() for i in details.split(':')] column, row = [int(i) for i in coordinates...
82b3a9d4469dc87e067de0528dfacf4ea3c1ea5b
684,167
def percentile_dataframe_by_col(raw_df, p_col, start_p=0.05, end_p=0.95, copy=True): """ :param raw_df: :param p_col: :param start_p: :param end_p: :param copy: :return: 依照指定列 p_col (比如说金额) 进行 percentile """ df = raw_df[(raw_df[p_col].quantile(start_p) < raw_df[p_col]) & (raw_d...
2f4263a79a9a391e19fbf45cbdb6b5b92f5245c0
684,168
import pickle def load_pickle(path): """ Load a dictionary containing the precision of each models """ with open(path, 'rb') as pkl: results = pickle.load(pkl) return results
54611ce5efd5adfe52e0f5db80ee088eca32d340
684,169
import math def num_digits(n): """ Return the number of digits (in base 10) for integer n > 0 """ return int(math.log10(n)) + 1
f7e8f7a6d9eb34b7f3f0926144df92881b000724
684,170
def alert_data_results(provides, all_app_runs, context): """Setup the view for alert results.""" context['results'] = results = [] for summary, action_results in all_app_runs: for result in action_results: # formatted = format_alert_result(result, True) formatted = { ...
3b5c54f7d237bdbef6a4bef11c6138b34a603673
684,171
def find_ignorespace(text, string): """Return (start, end) for string in start of text, ignoring space.""" ti, si = 0, 0 while ti < len(text) and si < len(string): if text[ti] == string[si]: ti += 1 si += 1 elif text[ti].isspace(): ti += 1 elif str...
994e4694110e314fa587fba6862f71f45e3481db
684,172
def get_best_fuzz(predicted_mem): """Retrieve the best prediction""" y_pred = predicted_mem.argmax(axis=1) return y_pred
339e6274e6326d767108146b7bf8e28f1ef43d65
684,173
def eggroll_compute_XY(X, Y): """ compute X * Y :param X: DTable, with shape (feature_dim, sample_dim) :param Y: DTable, with shape (feature_dim, sample_dim) :return: a DTable """ R = X.join(Y, lambda x, y: x * y) val = R.collect() table = dict(val) R.destroy() return table
98b0983fe77b110858efe18d9592f9f5dc73ffc2
684,174
def dict_paths2dict(adict): """ Turns a dict with '/' in keys to a nested dict. """ result = {} for k, v in adict.items(): if k.find('/') > 0: parts = k.split('/') if len(parts) > 1: k = parts[0] for part in parts[1:]: ...
df8abc9be43c6f76230463875f77d4eed18e5706
684,175
def append_heatmap(tokens, scores, latex, gamma, caption, pad_token, formatting="colorbox", truncate_pad=True): """ Produce a heatmap for LaTeX Format options: colorbox, text""" if gamma != 1: raise NotImplementedError latex += "\n\\begin{figure}[!htb]" for token, score in zip(tokens, sc...
a558988606fe7bd0514f2697fb6644fc47e6c9c4
684,176
def total_link_cost(net): """ Compute the total of link costs (volume * costfunction(volume)) over all links at current volumes on those links Parameters: net - Net object as returned by parse_net_file() Return value: total link cost """ return sum([link.volume * link.cost fo...
aeffb5c731b670d215f6055a55807b5553f5b8d6
684,177
def mysql_to_dict_id_as_key_info_as_dict(mysql_fetchall, columns): """returns a dict with the ID as the key and the info is stored in the nested dict with the column being the key""" return {info[0]: {column: info for column, info in zip(columns[1:], info[1:])} for info in mysql_fetchall}
1470c0fe8a5a072f0801a1dd48fe88f06e04d770
684,178
def sqrt(x): """Returns the square root of the AutoDiff or AutoDiffVector or AutoDiffReverse object""" return x**0.5
34cf9897595812db54e5fb8585e444beb6cfe172
684,179
def marginalize(pY_X, pX): """:return pY """ return pY_X.T @ pX
80fbb0683af455ddf0730356ad45f80e5f87ec6c
684,180
def is_integerish(var): """stackoverflow.com/questions/1265665/python-check-if-a-string-represents-an-int-without-using-try-except""" i = str(var) return i == '0' or (i if i.find('..') > -1 else i.lstrip('-+').rstrip('0').rstrip('.')).isdigit()
c43dcb5a9d35f76faf45cf103d7a282ad2df5a96
684,181
def get_position_num(region, sol_region): """地域区分、日射地域区分から地域番号 Args: region(int): 省エネルギー地域区分 sol_region(int): 年間の日射地域区分(1-5) Returns: str: 地域区分、日射地域区分から地域番号 """ nums = [ ['7', '117', '124', '-', '-'], ['49', '63', '59', '2A4', '2A5'], ['190', '230', '426'...
99c3f7303cc1f3c03e169ec5192b67f5f21cd582
684,182