content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def all_visible_subclasses(klass): """ Returns all reachable subclasses of the supplied class, presumably a BaseModel subclass. """ def helper(klas, result): subklases = klas.__subclasses__() if len(subklases) > 0: result.update(subklases) for subklas in subklase...
a12464d35ec824ab94371020f4527b3ac912c4e9
627,963
def binomial_coeff(n, k): """Compute the binomial coefficient "n choose k". n: number of trials k: number of successes returns: int """ # Just put all three return possibilities into one statement. Could use parentheses if it # seems clearer. return 1 if k==0 else 0 if n==0 else binomi...
50f2c319a4ba316d43bb37cf8fc65df31d6dbb1b
627,964
def to_camel_case(source: str) -> str: """Converts the specified source string from snake_case to camelCase.""" parts = source.split("_") prefix = parts.pop(0) suffix = "".join([p.capitalize() for p in parts]) return f"{prefix}{suffix}"
b3a9345265bf0b9de6667edb4402b59a6a46da81
627,969
def cast(x, dtype=None): """ Casts a tensor to a new type. Parameters ---------- x : tensor A Tensor or SparseTensor or IndexedSlices of numeric type. It could be uint8, uint16, uint32, uint64, int8, int16, int32, int64, float16, float32, float64. dtype : dtpye The dest...
51808a09dea94772a367ecfb9c86f838356303df
627,970
def fullscan_policy(obs): """ A policy function that generates only fullscan data. """ valid_actions = obs['valid_actions'] ms1_action = len(valid_actions) - 1 # last index is always the action for MS1 scan return ms1_action
39172e8a421d485d790c01c14407a623026d5422
627,971
from typing import List import shlex def split_run_args(command: str) -> List[str]: """Splits a shell command string into arguments.""" return shlex.split(command)
30ba93669684e69a03a84031bb4a7ca0a5cb4963
627,974
import six def _cell(item, column, key, fmt): """Constructs a value in table cell.""" if key is None: key = column if isinstance(key, six.string_types): keys = [key] else: keys = key raw_value = None for k in keys: if k in item and item[k] is not None: ...
4b26276eeb9e5550ebaeb643b7fb5f30ca55e0e1
627,976
def file_key(entry): """ For a PlaylistEntry, return a path. """ if entry.remote: return entry.remote.path return entry.path
aafc3772a8b327f6e5d23195691ecdddd6186f86
627,981
import pathlib import yaml def read_yaml_data(data_filename: str, names=None) -> dict: """Read in a YAML data file as a dictionary""" data_path = pathlib.Path(data_filename) try: with data_path.open('r', encoding='utf-8') as fp: yaml_data = yaml.safe_load(fp) except FileNotFoundErr...
7614df406f673caee9e13517fb2eaf410750bbfd
627,982
import math def prime_check(num): """ Checks if a single number is prime. A simple function, not a speedy solution. """ if num == 1: return False upper_bound = int(math.sqrt(num) + 1) for n in range(2, upper_bound): if num % n == 0: return False return True
bad4e607392bf5030f65202ff7f252f0391123d7
627,984
import re def filter_subs(subs, pattern): """Returns a list of subtitles who's text contains the given regex pattern""" ret = [] for sub in subs: if re.search(pattern, sub.text, re.MULTILINE): ret.append(sub) return ret
aee3b85323daeffcdbe2795c35640b24be7e499f
627,985
def get_ids_from_individual(individual): """Gets the ids from a given individual Args: individual (CPPN): The individual to get the ids from. Returns: tuple: (inputs, outputs, connections) the ids of the CPPN's nodes """ inputs = [n.id for n in individual.input_nodes()] outputs...
587d3a0f031bdb113676a65892b3027b7567a436
627,986
def _get_conv_shape_1axis( image_shape, kernel_shape, border_mode, subsample, dilation=1 ): """This function compute the output shape of convolution operation. Copied and simplified from theano (2020/11/08): https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/abstract_conv.py Parameters ...
dac0c8b6fa10c85698601457dca59e858e057c61
627,987
def get_gaze_point_mm(limbus): """ Returns intersection with z-plane of optical axis vector (mm) """ # Ray-plane intersection x0, y0, z0 = limbus.center_mm dx, dy, dz = limbus.normal t = -z0 / dz x_screen_mm, y_screen_mm = x0 + dx * t, y0 + dy * t return x_screen_mm, y_screen...
adbab3ded16cbe4a9d469b7eaaf6c0c7481ed61f
627,988
def get_input_from_kvp(datainputs): """Get execute DataInputs from URL (key-value-pairs) encoding """ inputs = {} if datainputs: for inpt in datainputs.split(";"): (identifier, val) = inpt.split("=") # add input to Inputs inputs[identifier] = val retur...
d1ae77a97bd70d183f9d914d2933b2b6e38fa779
627,992
def end_of_string_doc(editor, start_line): """ Find where a docstring ends, beginning with `start_line` and working forward """ for i in range(start_line, len(editor.lines)): if editor.lines[i].endswith(('"""', "'''")): return i return None
7151f35fd7004e6233065c37a66cd699c87c7c60
627,993
def oppgaver_med_feil(data): """Sammenligner avgitt svar med riktig svar returnerer liste med indeksene til svarene som er feil. Parameters ---------- data : list En list med dictionarys Returns ------- list En list med indeksene til de spørsmålene som er besvart feil. ...
52c762cd34f4f402a2bc7e16e6daa5353ab03ce8
627,996
def dict_to_str(d, val_sep=' ', item_sep=' '): """Convert dict to string""" str_list = [f'{k}{val_sep}{v}' for k, v in d.items()] s = item_sep.join(str_list) return s
69631f17a9c07659d1cbdc70c3b397710fb0b58f
627,997
def identity(x): """Identity function: return the given argument unchanged""" return x
bfd4adbffcc67512e22396957a92fa31de727e8e
627,998
def comment_prep(content): """ Prepares the comment so we can have sme basic context. """ # same comment structure, so we'll just do it in a function text = "Imgur link: " + content text += "\n\n\n------\n" text += "This action was performed by a bot. Message +/u/arrivance for further deta...
01f606ce3a9fcf389e8c75cbdc66335dfd17a5e0
627,999
def _normalize_integer_rgb(value): """ Normalize ``value`` for use in an integer ``rgb()`` triplet, as follows: * If ``value`` is less than 0, convert to 0. * If ``value`` is greater than 255, convert to 255. Examples: >>> _normalize_integer_rgb(0) 0 >>> _normalize_integer_rg...
48204a8af4c345c5599e563a84d2a1a2d129de79
628,000
def check_enum(val, candidates, name): """ Checks the specified val is in the specified candidates. """ if val not in candidates: message = \ "{0} can not be used for {1}. " \ "Available values are {2}." \ .format(val, name, candidates) raise ValueErro...
b18c88206f2207f82bb0e1a408ff40eaa343b170
628,003
async def leave_comment(gh, issue_comment_url: str, message: str, token: str): """ Leave comment in issue or pull request :param gh: object with actions :param issue_comment_url: api string :param message: comment :param token: GitHub token :return: response """ data = {'body': messa...
cdcddeaef04cf3667cc861d44bd69180a8e49b34
628,004
def get_partial_index(df, start=None, end=None): """Get partial time index according to start and end Parameters ---------- df: pd.DatFrame or pd.Series start: str, optional, e.g., '2000-01-01' end: str, optional, e.g., '2017-08-31' Returns ------- pd.DatetimeIndex """ if s...
17b2426ae29eb5ba9a10a1d672bc9b954c69f504
628,006
import string def remove_punct(user_input): """The remove_punct function gets rid of all punctuation from the string. Parameters ---------- user_input : string Input received from user Returns ------- output_list : string User's input with removed punctuation "...
d0dd09294436e076f376f15f4030d4d49838fcdd
628,009
import math def primes_list(lower, upper): """Problem 39: A list of prime numbers Parameters ---------- lower : int The lower bound of the prime numbers to return upper : int The upper bound of the prime numbers ro return Returns ------- list of int A list of ...
2b668af4e86f6131ec93e4a694b6bdc0579a4a5d
628,015
def describe_nunique(df): """ describe method including nunique for numeric descriptions """ df_described = df.describe(include='number').T df_described['unique'] = df.select_dtypes(include='number').nunique() return df_described[['count', 'unique', 'mean', 'std', 'min', 'max', '25%', '50%', '75...
b4a8da079f8897a2eef99d80b501262ae1e62cf4
628,016
import re def clean_html(text): """ Remove html tags from text and convert a small set of html-encoded symbols :param text: string with html markup :return: text without html markup """ if text: clean_text = re.sub('<[^<]+?>', ' ', text) clean_text = clean_text.strip() ...
52db990dfe5abdb5be28aa9ede0025fd4413dd89
628,017
def get_surrounding_text(text, sub_start, sub_end=None, distance=25): """ Looks for the substrings, 'sub_start' and 'sub_end' variables in 'text' and return a new substring with a number equal to 'distance' characters in the left of 'sub_start' position and in the right of 'sub_end' position if they exi...
c5ad4a80940260ca591b7974ef9a37441140be78
628,018
def drop_systematics(blocks, systematics): """Drop a systematic from a set of blocks. Parameters ---------- blocks : list(str) All TRExFitter blocks. systematics : list(str) Name of the systematic to drop. Returns ------- list(str) Blocks without desired systema...
9dcc86d39fdc8a4a7deb583d4d4afd25cc5e620b
628,019
def pg_version(conn): """ Returns the PostgreSQL server version as numeric and full version. """ num_version = conn.get_pg_version() conn.execute("SELECT version()") full_version = list(conn.get_rows())[0]['version'] return dict(numeric=num_version, full=full_version)
18e1dd309ea1aa08cb53eef994402668cca16d04
628,020
def iseven(x): """is the number x an even number?""" return x%2 == 0
5700285b86d2a9d62cc444f752ae5d959c982aba
628,024
def getValueTryRemoveTailZero(float_num): """ try to remove .0 from an float number, 2.00 -> 2 keep other float as it was, 2.02 -> 2.02 :param float float_num :return float/int """ int_num = int(float_num) if int_num == float_num: return int_num return float_...
aef0ced52fa74236760ccc54996e59fea086f292
628,029
def merge_value_range_fields(nmdc_objs: list, tx_attributes: list, **kwargs) -> list: """ Takes each nmdc object (either a dict or class instance) and merges two attributues into a single attribute separated by a "-". Additionaly, the has_minuimum_numeric_value and has_maximum_numeric_value attrubut...
c201a79fbdf75e4dacebbe101b33f4d327f81c3b
628,030
def nan2zero(data): """ Replace NaNs and negative values by zeros """ return [val if val>0 else 0 for val in data]
066e16ebd5c4c3fa827f84d5b89901da03eea241
628,032
def to_dojo_data(items, identifier='id', num_rows=None): """Return the data as the dojo.data API defines. The dojo.data API expects the data like so: {identifier:"whatever", items: [ {name:"Lenin", id:3, ....}, ] } The identifier is optional. """ ret = {'items':items} ...
dab7fda1cf2ae577c71dba38d38f1f591ad0431b
628,037
from collections import defaultdict def convert_tab_to_dict(response): """Convert tab response to dictionary.\n Response is a string made of rows with two tab separated columns.""" if not type(response) == type("hola"): print("The argument is not a string.") return {} result = default...
b402b2104933e24aad3ec5bbda5efa608bf48c49
628,038
def _get_member_groups(get_member_group_func, identifier, security_enabled_only): """Call 'directoryObject: getMemberGroups' API with specified get_member_group_func. https://docs.microsoft.com/en-us/graph/api/directoryobject-getmembergroups """ body = { "securityEnabledOnly": security_enabled_o...
72491f91382439120079d39cab881b1b51707488
628,041
def model_to_dict(instance, fields=None, exclude=None): """ Return a dict containing the data in instance. This differs from django.forms.model_to_dict by containing non-editable fields and relation values being the related objects instead of pk of those objects. :param instance: Model instanc...
bf08b6eead47ede0923c76ac984219490f44dc91
628,042
import hashlib def key_to_md5(key): """ convert bibtex-key to shortened md5-sum to avoid special characters in the keys :param key: bibtex-key of an article :return: converted key, first six characters of the key md5-sum """ m = hashlib.md5() m.update(key.encode('utf-8')) hd = m.hexdig...
be1c3e592a5dfccd481c9223c468c0416d2fc664
628,044
import random def generate_shuffle(dic): """ Given a dictionary, shuffle the keys """ keys = list(dic.keys()) return (random.sample(keys, len(keys)))
02a621426936f8b389bf0faf4d1062d97a63d0c9
628,047
from typing import Dict from typing import Optional def local_paths_from_manifest_item( item: Dict, imgs_s3key_prefix: str, textract_s3key_prefix: Optional[str] = None, imgs_local_prefix=None, textract_local_prefix=None, ) -> Dict: """Translate Textract+image manifest S3 URIs to local paths ...
4b2cbe37f2255f371fccb9dab4fa741afa876e3f
628,048
def url(host, port): """ Return the URL where the server can be reached. """ return 'wss://{}:{}'.format(host, port)
5f6c51c218a376b3868ecea9f86256eb146b34bc
628,051
def extract_argument(arguments, prefix, remove=True): """Extract argument from arguments.""" for argument in arguments[:]: if argument.startswith(prefix): if remove: arguments.remove(argument) return argument[len(prefix):] return None
06084be10e21fce2817d0189418a2307b6ae85f7
628,052
def get_error_messages( response ): """ Builds a string based on the error messages in the payload Args: response: The response to print Returns: The string containing error messages """ # Pull out the error payload and the messages out_string = response.dict["error"]["mes...
2104ee4a243b3a778d53b5129885d74dfd8f9d01
628,058
def centerpoint(geolocations): """ :param geolocations: array of arrays in the form of [[longitude, latitude],[longitude,latitude]] :return: average latitude and longitude in the form [latitude, longitude] """ lats = [] lngs = [] for lon, lat in geolocations: lats.append(lat) ...
0e236080c31a51ba919ffb2fb25fc2c3062c6807
628,065
def _check_lesson_is_empty(parsed_lesson): """ Checking lesson for being empty Args: parsed_lesson (dict): Parsed lesson Return: bool: True if parsed_lesson['info'] have any content except whitespaces, else False """ return not parsed_lesson['info'].strip()
7976561eba0542cdd9b4a356c25c88e0e2c82472
628,066
import logging import csv def read_header(filepath): """Read header line of CSV file. INPUT: filepath: Full pathname of CSV file OUTPUT: i: First row of CSV file """ logging.info("Reading header for {0}".format(filepath)) with open(filepath, "r") as f: reader = csv.re...
0b07849a7190b307fc2d3e6f6fc4d3505320ba4d
628,067
def get_revoke_key(revoke_statement): """ Create the key from the revoke statement. The key will be used as the dictionnary key. :param revoke_statement: The revoke statement :return: The key """ splitted_statement = revoke_statement.split() revoke_privilege = splitted_statement[1] ...
0001bc2d14569bef8acbd799487450af1cf337f7
628,068
import csv def read_connections_file(infile): """ Reads a two-column CSV file of integers into a list of tuples corresponding to indices of connected concepts. :param str infile: Path to the CSV file. :returns: List of int tuples of connections. :rtype: list """ connections = [] w...
4b27bf13a5f9ec99bf2b122dfa0c732a7ade09b0
628,074
def do_enable_unwinder1(unwinders, name_re, flag): """Enable/disable unwinders whose names match given regex. Arguments: unwinders: The list of unwinders. name_re: Unwinder name filter. flag: Enable/disable. Returns: The number of unwinders affected. """ total = 0 ...
42fe9b8c5a199f9bda0cc460a043968ee62b91b6
628,075
def leapfrog(theta, r, grad, epsilon, f): """ Perfom a leapfrog jump in the Hamiltonian space INPUTS ------ theta: ndarray[float, ndim=1] initial parameter position r: ndarray[float, ndim=1] initial momentum grad: float initial gradient value epsilon: float ...
3386200209693d3cead404776499ef6c60553123
628,082
import random def _apply_func_with_prob(func, image, args, prob): """Apply `func` to image w/ `args` as input with probability `prob`.""" # Apply the function with probability `prob`. should_apply_op = random.random() + prob if should_apply_op >= 1.0: augmented_image = func(image, *args) ...
fd883ea8996e8ab1e87eb1438ef261ddd1aee597
628,084
from typing import Callable import re def get_formatter(env_var_name: str) -> Callable[[str], str]: """ Returns a formatter function for given environment variablel. :param env_var_name: name of environment variable :return: formatting function """ if env_var_name.endswith("PATH"): r...
3b1faf9748d5a752ff1c579b5458eb042f7b9865
628,086
from bs4 import BeautifulSoup def get_soup_from_static_html(html): """ Parameters ---------------- html: str/path obj the path to the html file Returns ----------------- soup: bs4 Soup obj """ with open(html, 'r') as fh: soup = BeautifulSoup(fh, 'html.parser') ...
8f77a4ed75ca64982acbb0c1cb96a2c28de239c6
628,090
def form_yes_or_no(QUESTION: str, DEFAULT_NO: bool = True) -> bool: """ Single yes or no question without recursion. Credit: Inspired from @icamys commented on 29 Nov 2020 on Github, https://gist.github.com/garrettdreyfus/8153571 """ CHOICES = " [y/N]: " if DEFAULT_NO else "...
3ed172bd61bd2e3db0484df845d0b6d9ab77f447
628,091
def valid_priority_len(priority): """Checks for values with exactly one significant digit :param float priority: :return boolean: """ result = len(str(priority).rsplit('.')[-1]) == 1 return result
ffc1048d54e5b91cc7b17408514ce4c97941ac6e
628,097
def listAxes(axd): """ make a list of the axes from the dictionary of axes Parameters ---------- axd : dict a dict of axes, whose values are returned in a list Returns ------- list : a list of the axes """ if type(axd) is not dict: if type(axd) is l...
b5e2f2f5341671d1c267d3940893b665555f1a01
628,098
def pagetitle(string, remove_first=False, divider=' > '): """Convert a string of characters to page-title format. Args: string (str): The string to conert. remove_first (bool, optional): Remove the first instance of the delimiter of the newly formed title. Returns: str:...
3814a193433d337a37ce5bec6c72cf210970f368
628,100
def create_business_hours_schedule(api, configuration, api_version, api_exception): """ Creates a schedule for an activity that occurs during normal business hours. :param api: The Deep Security API modules. :param configuration: Configuration object to pass to the api client. :param api_version: The v...
ed3ac68fcace4ac62431e5eb70a5ce23f52103db
628,102
def gen_post_id(reddit_obj_id): """ Generates the Elasticsearch document id for a post Args: reddit_obj_id (int|str): The id of a reddit object as reported by PRAW Returns: str: The Elasticsearch document id for this object """ return "p_{}".format(reddit_obj_id)
558fd8d6d70b80980ff8dc5d92b9d36ddba792d5
628,105
def collection_to_dict(collection): """Utility function to construct collection dict with names.""" return {v.name[:v.name.rfind(':')]: v for v in collection}
a2e022a26e3bf62ddd34dfcc6548b7b18e39dd52
628,108
def _ofc(id): """OFC ID converter.""" return "ofc-%s" % id
c31e2fb102c0238c943629de98cffeeac127cf29
628,111
def snake2pascal(target: str) -> str: """Convert snake case to pascal case Args: target (str) Returns: str """ return ''.join(map(lambda x: x.title(), target.split('_')))
296bf325ba758b869d8040d8a76e82d36ea05d48
628,112
import stat def calc_mode( sticky=False, isuid=True, isgid=True, type=stat.S_IFREG, owner_read=True, owner_write=True, owner_exec=True, group_read=True, group_write=True, group_exec=True, other_read=True, other_write=True, other_exec=True, ): """helper function to calculate the mode bits of a file.""" ...
b46d201deeac317bf8ff1c352784afb0e37715e0
628,116
def get_limit_spec(limit): """ Based on an input *limit* string of the form: <system>.<type>.<direction>.<qualifier> (where the "qualifier" element is optional) return the various pieces into a dictionary for convenience. Parameters ---------- limit : str The input limit s...
2d93a83014ccd28f5c93a6578ef9571ba8523c0e
628,119
def unpack_quantity(row, concept, value): """Unpack row like {"variable": [{"concept":<concept>, <value>:_i_want_this_}]} Args: row (dict): Row of Worldbank API data. concept (str): The name of the dataset containing the variable. value (str): The name of the variable to unpack. Ret...
ce51a37a99f5883ec7af7642dbed13e16f6e3d34
628,120
def serializeEdge(edge): """Return the Edge as native Python datatypes, fit for json. Edges only reference Knobs, so we have to store their Node id here to be able to correctly associate it once reconstructed. """ return { "source_nodeId": edge.source.node().uuid, "source_name": edg...
58662cdbfd1bc22e0dc4276e5240961dc0d5672a
628,121
def no_preproc(x, **kwargs): """Identity function that can be passed used as feature_preproc_fn in Dataset, since lambda is not pickleable and doesn't take an arbitrary number of params.""" return x
a897759789856c1c86cde61c4de4bedec98c29b7
628,123
import math def quaternion_from_matrix(M): """Returns the 4 quaternion coefficients from a rotation matrix. Parameters ---------- M : list[list[float]] The coefficients of the rotation matrix, row per row. Returns ------- [float, float, float, float] The quaternion coeffi...
6318208e9186ddbe26cdd1dc6175898918f39969
628,124
from unittest.mock import patch def patch_bond_device(return_value=None): """Patch Bond API device endpoint.""" return patch( "homeassistant.components.bond.Bond.device", return_value=return_value, )
c3bde7f64c663997119fecc04e126f3844066bc2
628,130
def is_local_ressource(path): """ Check if given path is a local ressource. Arguments: path (string): Ressource path. Returns: bool: True if file path, else False. """ if not path.startswith("http://") and not path.startswith("https://"): return True return False
a169ad58e0df8f5deca3ed01f1331ae0ab833b7a
628,132
def strip_signature_from_subject(content): """Assume --\n is marker for email signature and return everything before. """ return content.split('--')[0]
fe7ecd0ac59f474be0531de85b8144e1248a4e22
628,137
import itertools def compress(string: str) -> str: """Return string represented as tuples of characters and their count.""" return " ".join([ "({})".format(", ".join((str(len(list(grp))), char))) for char, grp in itertools.groupby(string, lambda c: c) ])
c47f195f2edc193bbfb28196a563a65b02f440d8
628,141
from datetime import datetime def from_datetime(value: datetime) -> str: """Convert from datetime to ISO8601-formatted string. Parameters ---------- value : datetime The datetime to be converted. Expected in UTC. Returns ------- str ISO8601-formatted string Examples ...
a6e4b0998f6adeb7edb1f9462de3aa1e18a2e8a4
628,145
def session_status(space): """Returns the current session status""" return space.wrap(space.ec.interpreter.session.status)
c7b2c03f7641622c8ee162aeafdfba07fbfd61b8
628,147
def get_attack_details(ipal_entry): """ Parse the attack-details IPAL field. The field is expected to have the format "<attack category>;<attack type>". Example: "2;12". """ split = ipal_entry["attack-details"].split(";") assert ( len(split) == 2 ), "'attack-details' field in IP...
b59b1b3f9343e917ed70f102a38d7b99597bad5c
628,148
def little_endian_data() -> bytes: """Little endian data fixture.""" return b"\x00\x00\x00\x05\x00\x00\x00\x06"
83919a672cd1a2c868c7ef61a2d20f3c993f88f4
628,149
import time def get_current_time(time_form: str="%Y%m%d%H%M%S"): """ get_current_time from time Args: time_form: str, string form of return time Returns: time_current: str """ time_now = int(time.time()) time_local = time.localtime(time_now) time_current = time.strftime...
8622ef56b9b885cd50efd83a46f2e94c24ee092f
628,151
def get_marc_as_list(raw_marc): """Method takes Solr MARC format and splits into a list of field dictionarys :param raw_marc: Raw MARC string :rtype: List of field dictionary """ output = [] marc_listing = raw_marc.split("=") for row in marc_listing: output.append({'tag':row[0:3], ...
4f86cb86f50abf4041f3cd16121df610c3671d56
628,152
import math def calculate(point1, point2): """ Calculate the distance between two points (point1 and point2) on the Earth's surface using the 'spherical law of cosines' formula. Input: point1 : two floating point numbers between -180 and 180, where positive indicates North/East ...
adf7f285d285ac575285632816a4778bbf40c9db
628,154
def request_input(message, choices): """ Request user input. Parameters ---------- message : str Message to display choices : list of str List of recognized inputs """ while True: choice = input(message).strip().lower() if choice in choices: ...
df223bc9f584c3e3df0481501473c45925d79583
628,158
def _append_norm(ktl0, norm_types): """Generate human-readable labels for multiple norms.""" ktl = {} for norm_type in norm_types: for key, val in ktl0.items(): ktl['%s/%s' % (key, norm_type)] = '%s(%s)' % (val, norm_type) return ktl
d82c927facc341c150dc63cec3b3e1df9133383f
628,159
def get_rules_with_scope(rules, scope): """ from the given collection of rules, select those with the given scope. args: rules (List[capa.rules.Rule]): scope (str): one of the capa.rules.*_SCOPE constants. returns: List[capa.rules.Rule]: """ return list(rule for rule in rules...
4922038dc098083085e16c096a40ddae1825e589
628,160
def _SharedPrefix(pattern1, pattern2): """Returns the shared prefix of two patterns. Args: pattern1: A handler's pattern string pattern2: A handler's pattern string Returns: The shared prefix of the two patterns, up to the index of the first wildcard of either pattern. For example, the shared pre...
df19be2b8a24dc5a35df9c144a114b6bd6f0fe4e
628,162
def get_enum_strings(enum_strings, enum_dict): """Get enum strings from either `enum_strings` or `enum_dict`.""" if enum_dict: max_value = max(enum_dict) return [enum_dict.get(idx, '') for idx in range(max_value + 1)] return enum_strings
f7cb8238d0cc7c3c6824ef1c160b01ec213cdd29
628,163
from typing import List def sauvegarde_fichier(nom_fichier : str, Contenu : List[str]) -> None: """Précondition : nom_fichier est un nom correct de fichier Sauvegarde le Contenu comme lignes de texte dans le fichier identifié par nom_fichier Attention : si le fichier existe déjà son contenu sera e...
17ada0ef80c506199dd93c01080fec5b017cc67f
628,165
def make_columns(repetitions, n_splits): """Provides column names for the tables of all predictions (from each split of each rep). Parameters ---------- repetitions : int Repetitions of the n-fold validation n_splits : int number of splits in KFold Returns ------- l...
83be90522ffdf0db0175c09318e12d65e585e1a4
628,166
def id_is_generic(inid, inyear): """ Test to see if an ID is one of the generic IDs :param inid: ID from marine report :param inyear: year we are checking for :type inid: string :type inyear: integer :return: True if the ID is generic and False otherwise :rtype: logical Cer...
0f458cfc339016a30a115e973d80503686b1e1bd
628,167
def reduce_broadcast(grad, var_shape): """ Sum-reduce axes of `grad` so its shape matches `var_shape. This the appropriate mechanism for backpropagating a gradient through an operation in which broadcasting occurred for the given variable. Parameters ---------- grad...
be365ab0e830b40ff17dbc5816635295a492ae80
628,169
def merge_dicts(dict1, dict2): """ Merge two dictionaries. Parameters ---------- dict1, dict2 : dict Returns ------- dict_merged : dict Merged dictionaries. """ dict_merged = dict1.copy() dict_merged.update(dict2) return dict_merged
cb792131f1793907e32090e6df5d2d2395410dfa
628,171
def select_all_columns_except_some(df, column_names): """Select all columns in the dataframe except those specified in ``column_list``. Args: df (pd.DataFrame): Dataframe. column_names (list): List of column names. Returns: pd.DataFrame: Dataframe with the columns removed. ...
ee6a345a605da46a6edd9a6808b5edbf48abd211
628,173
import json def reject(status_code, **kwargs): """ Bad request. :param int status_code: Rejection status code :param dict kwargs: Rejection body JSON :return dict: Rejection response """ body = json.dumps(kwargs) if kwargs else '' headers = { 'content-length': len(body), ...
e68113ed9c92d0c082ed4c146ca2132d3d52bc40
628,174
import torch def to_torchaudio(tensor, dim: int = -2): """Converts complex-like torch tensor to torchaudio style complex tensor. Args: tensor (torch.tensor): asteroid-style complex-like torch tensor. dim(int, optional): the frequency (or equivalent) dimension along which real and ...
a69fabe2590d73c9d7ca45d478749d722e79ecaa
628,176
def parse_stream(stream): """This function parses the contents of a stream to generate a list of lines. This function removes comments delimited by '#', ingores empty lines, and leading and trailing whitespace. Args: stream : A file that has been open()'d Returns: A list of lines. """ lines = ...
f428721e03ad6d5cde75df5fd8849e3b5461691d
628,180
def user_id(msg): """ Use the userid from the msg as the user search criteria Args: msg (errbot.backends.base.Message): The message from the bot that triggered the LDAP lookup Returns: str: The user ID that will be used to search LDAP """ if hasattr(msg.frm, "userid"): ...
43c61915eca4c13d64e9e8a081e9a67fa97437ab
628,184
def CreateEmptyHubDictionary(input_map): """hub_map_tools.CreateEmptyHubDictionary() INPUTS: - input_map -- a hub map dictionary with teacher or grade name keys, and hub IDs for values OUTPUTS: - output_map -- a new dictionary keyed by unique hub IDs, and having ...
16f5b4bd723fdb73cad2dbbc6179cea747deabbf
628,185
def getMBR(ploygon): """ get the Minimum Bounding Rectangle of the given ploygon :param ploygon: the given polygon :return: the given ploygon's MBR """ left_bottom_x = float('inf') left_bottom_y = float('inf') right_up_x = float('-inf') right_up_y = float('-inf') for plg in ployg...
167977b8f4a6edcfdb1601bedc9a06db83119f73
628,187
def convert_qa_input_dict(infer_dict): """ Input dictionaries in QA can either have ["context", "qas"] (internal format) as keys or ["text", "questions"] (api format). This function converts the latter into the former. It also converts the is_impossible field to answer_type so that NQ and SQuAD dicts have t...
f4feab9c315040094277251e0e110536c6a4a646
628,188
def max_val(t): """ t, tuple or list Each element of t is either an int, a tuple, or a list No tuple or list is empty Returns the maximum int in t or (recursively) in an element of t """ def find_all_int(data): int_list = [] for item in data: if isinstance(item, l...
97102a1024371d1e6f8f959cea53ab309dd323ea
628,190